Debian Codegraph @

Source/Core/Common/Crypto/SHA1.cpp

raw symbols SCIP
1 // Copyright 2017 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "SHA1.h"
5
6 #include <algorithm>
7 #include <array>
8 #include <memory>
9
10 #include <fmt/ranges.h>
11 #include <mbedtls/sha1.h>
12
13 #include "Common/Assert.h"
14 #include "Common/CPUDetect.h"
15 #include "Common/CommonTypes.h"
16 #include "Common/Swap.h"
17
18 #ifdef _MSC_VER
19 #include <intrin.h>
20 #else
21 #ifdef _M_X86_64
22 #include <immintrin.h>
23 #elif defined(_M_ARM_64)
24 #include <arm_acle.h>
25 #include <arm_neon.h>
26 #endif
27 #endif
28
29 #ifdef _MSC_VER
30 #define ATTRIBUTE_TARGET(x)
31 #else
32 #define ATTRIBUTE_TARGET(x) [[gnu::target(x)]]
33 #endif
34
35 namespace Common::SHA1
36 {
37 class ContextMbed final : public Context
38 {
39 public:
40 ContextMbed()
41 {
42 mbedtls_sha1_init(&ctx);
43 ASSERT(!mbedtls_sha1_starts_ret(&ctx));
44 }
45 ~ContextMbed() override { mbedtls_sha1_free(&ctx); }
46 void Update(const u8* msg, size_t len) override
47 {
48 ASSERT(!mbedtls_sha1_update_ret(&ctx, msg, len));
49 }
50 Digest Finish() override
51 {
52 Digest digest;
53 ASSERT(!mbedtls_sha1_finish_ret(&ctx, digest.data()));
54 return digest;
55 }
56 bool HwAccelerated() const override { return false; }
57
58 private:
59 mbedtls_sha1_context ctx{};
60 };
61
62 class BlockContext : public Context
63 {
64 protected:
65 static constexpr size_t BLOCK_LEN = 64;
66 static constexpr u32 K[4]{0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6};
67 static constexpr u32 H[5]{0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0};
68
69 virtual void ProcessBlock(const u8* msg) = 0;
70 virtual Digest GetDigest() = 0;
71
72 void Update(const u8* msg, size_t len) override
73 {
74 m_msg_length += len;
75
76 // Block has some partial data. Copy msg into it.
77 if (m_block_position != 0)
78 {
79 const size_t count_to_fill_block = m_block.size() - m_block_position;
80
81 // Not enough to fill block.
82 if (len < count_to_fill_block)
83 {
84 std::copy_n(msg, len, m_block.data() + m_block_position);
85
86 m_block_position += len;
87 return;
88 }
89
90 std::copy_n(msg, count_to_fill_block, m_block.data() + m_block_position);
91 ProcessBlock(m_block.data());
92
93 msg += count_to_fill_block;
94 len -= count_to_fill_block;
95 m_block_position = 0;
96 }
97
98 // Our block is empty. We can process msg blocks directly, avoiding unnecessary copies.
99 while (len >= m_block.size())
100 {
101 ProcessBlock(msg);
102
103 msg += m_block.size();
104 len -= m_block.size();
105 }
106
107 // Copy any remaining partial data into block.
108 std::copy_n(msg, len, m_block.data() + m_block_position);
109 m_block_position += len;
110 }
111
112 Digest Finish() override
113 {
114 // m_block_position is guaranteed < BLOCK_LEN
115 m_block[m_block_position++] = 0x80;
116
117 constexpr size_t MSG_LEN_POS = BLOCK_LEN - sizeof(u64);
118
119 if (m_block_position > MSG_LEN_POS)
120 {
121 // Pad current block and process it
122 std::fill(m_block.begin() + m_block_position, m_block.end(), 0x00);
123 ProcessBlock(m_block.data());
124 m_block_position = 0;
125 }
126
127 // Pad block.
128 std::fill(m_block.data() + m_block_position, m_block.data() + MSG_LEN_POS, 0x00);
129 m_block_position = MSG_LEN_POS;
130
131 // Write the message length.
132 const Common::BigEndianValue<u64> msg_bit_length{m_msg_length * CHAR_BIT};
133 Update(reinterpret_cast<const u8*>(&msg_bit_length), sizeof(msg_bit_length));
134
135 return GetDigest();
136 }
137
138 private:
139 alignas(64) std::array<u8, BLOCK_LEN> m_block{};
140 size_t m_block_position{};
141 size_t m_msg_length{};
142 };
143
144 template <typename ValueType, size_t Size>
145 class CyclicArray
146 {
147 public:
148 inline ValueType operator[](size_t i) const { return data[i % Size]; }
149 inline ValueType& operator[](size_t i) { return data[i % Size]; }
150 constexpr size_t size() { return Size; }
151
152 private:
153 std::array<ValueType, Size> data;
154 };
155
156 #ifdef _M_X86_64
157
158 // Uses the dedicated SHA1 instructions. Normal SSE(AVX*) would be needed for parallel
159 // multi-message processing. While Dolphin could gain from such implementation, it requires the
160 // calling code to be modified and/or making the SHA1 implementation asynchronous so it can
161 // optimistically batch.
162 class ContextX64SHA1 final : public BlockContext
163 {
164 public:
165 ContextX64SHA1()
166 {
167 state[0] = _mm_set_epi32(H[0], H[1], H[2], H[3]);
168 state[1] = _mm_set_epi32(H[4], 0, 0, 0);
169 }
170
171 private:
172 struct XmmReg
173 {
174 // Allows aliasing attributes to be respected in the
175 // face of templates.
176 __m128i data;
177
178 XmmReg& operator=(const __m128i& d)
179 {
180 data = d;
181 return *this;
182 }
183 operator __m128i() const { return data; }
184 };
185 using WorkBlock = CyclicArray<XmmReg, 4>;
186
187 ATTRIBUTE_TARGET("ssse3")
188 static inline __m128i byterev_16B(__m128i x)
189 {
190 return _mm_shuffle_epi8(x, _mm_set_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
191 }
192
193 template <size_t I>
194 ATTRIBUTE_TARGET("sha")
195 static inline __m128i MsgSchedule(WorkBlock* wblock)
196 {
197 auto& w = *wblock;
198 // Update and return this location
199 auto& wx = w[I];
200 // Do all the xors and rol(x,1) required for 4 rounds of msg schedule
201 wx = _mm_sha1msg1_epu32(wx, w[I + 1]);
202 wx = _mm_xor_si128(wx, w[I + 2]);
203 wx = _mm_sha1msg2_epu32(wx, w[I + 3]);
204 return wx;
205 }
206
207 ATTRIBUTE_TARGET("sha")
208 void ProcessBlock(const u8* msg) override
209 {
210 // There are 80 rounds with 4 bytes per round, giving 0x140 byte work space, but we can keep
211 // active state in just 0x40 bytes.
212 // see FIPS 180-4 6.1.3 Alternate Method for Computing a SHA-1 Message Digest
213 WorkBlock w;
214 auto msg_block = (const __m128i*)msg;
215 for (size_t i = 0; i < w.size(); i++)
216 w[i] = byterev_16B(_mm_loadu_si128(&msg_block[i]));
217
218 // 0: abcd, 1: e
219 auto abcde = state;
220
221 // Not sure of a (non-ugly) way to have constant-evaluated for-loop, so just rely on inlining.
222 // Problem is that sha1rnds4 requires imm8 arg, and first/last rounds have different behavior.
223
224 // clang-format off
225 // E0 += MSG0, special case of "nexte", can do normal add
226 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_add_epi32(abcde[1], w[0]), 0);
227 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], w[1]), 0);
228 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], w[2]), 0);
229 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], w[3]), 0);
230 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<4>(&w)), 0);
231 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<5>(&w)), 1);
232 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<6>(&w)), 1);
233 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<7>(&w)), 1);
234 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<8>(&w)), 1);
235 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<9>(&w)), 1);
236 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<10>(&w)), 2);
237 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<11>(&w)), 2);
238 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<12>(&w)), 2);
239 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<13>(&w)), 2);
240 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<14>(&w)), 2);
241 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<15>(&w)), 3);
242 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<16>(&w)), 3);
243 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<17>(&w)), 3);
244 abcde[1] = _mm_sha1rnds4_epu32(abcde[0], _mm_sha1nexte_epu32(abcde[1], MsgSchedule<18>(&w)), 3);
245 abcde[0] = _mm_sha1rnds4_epu32(abcde[1], _mm_sha1nexte_epu32(abcde[0], MsgSchedule<19>(&w)), 3);
246 // state += abcde
247 state[1] = _mm_sha1nexte_epu32(abcde[1], state[1]);
248 state[0] = _mm_add_epi32(abcde[0], state[0]);
249 // clang-format on
250 }
251
252 Digest GetDigest() override
253 {
254 Digest digest;
255 _mm_storeu_si128((__m128i*)&digest[0], byterev_16B(state[0]));
256 u32 hi = _mm_cvtsi128_si32(byterev_16B(state[1]));
257 std::memcpy(&digest[sizeof(__m128i)], &hi, sizeof(hi));
258 return digest;
259 }
260
261 bool HwAccelerated() const override { return true; }
262
263 std::array<XmmReg, 2> state{};
264 };
265
266 #endif
267
268 #ifdef _M_ARM_64
269
270 class ContextNeon final : public BlockContext
271 {
272 public:
273 ContextNeon()
274 {
275 state.abcd = vld1q_u32(&H[0]);
276 state.e = H[4];
277 }
278
279 private:
280 using WorkBlock = CyclicArray<uint32x4_t, 4>;
281
282 struct State
283 {
284 // ARM thought they were being clever by exposing e as u32, but it actually makes non-asm
285 // implementations pretty annoying/makes compiler's life needlessly difficult.
286 uint32x4_t abcd{};
287 u32 e{};
288 };
289
290 static inline uint32x4_t MsgSchedule(WorkBlock* wblock, size_t i)
291 {
292 auto& w = *wblock;
293 // Update and return this location
294 auto& wx = w[0 + i];
295 wx = vsha1su0q_u32(wx, w[1 + i], w[2 + i]);
296 wx = vsha1su1q_u32(wx, w[3 + i]);
297 return wx;
298 }
299
300 template <size_t Func>
301 static inline constexpr uint32x4_t f(State state, uint32x4_t w)
302 {
303 const auto wk = vaddq_u32(w, vdupq_n_u32(K[Func]));
304 if constexpr (Func == 0)
305 return vsha1cq_u32(state.abcd, state.e, wk);
306 if constexpr (Func == 1 || Func == 3)
307 return vsha1pq_u32(state.abcd, state.e, wk);
308 if constexpr (Func == 2)
309 return vsha1mq_u32(state.abcd, state.e, wk);
310 }
311
312 template <size_t Func>
313 static inline constexpr State FourRounds(State state, uint32x4_t w)
314 {
315 return {f<Func>(state, w), vsha1h_u32(vgetq_lane_u32(state.abcd, 0))};
316 }
317
318 virtual void ProcessBlock(const u8* msg) override
319 {
320 WorkBlock w;
321 for (size_t i = 0; i < w.size(); i++)
322 w[i] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(&msg[sizeof(uint32x4_t) * i])));
323
324 std::array<State, 2> states{state};
325
326 // Fashioned to look like x64 impl.
327 // In each case the goal is to have compiler inline + unroll everything.
328 states[1] = FourRounds<0>(states[0], w[0]);
329 states[0] = FourRounds<0>(states[1], w[1]);
330 states[1] = FourRounds<0>(states[0], w[2]);
331 states[0] = FourRounds<0>(states[1], w[3]);
332 states[1] = FourRounds<0>(states[0], MsgSchedule(&w, 4));
333 states[0] = FourRounds<1>(states[1], MsgSchedule(&w, 5));
334 states[1] = FourRounds<1>(states[0], MsgSchedule(&w, 6));
335 states[0] = FourRounds<1>(states[1], MsgSchedule(&w, 7));
336 states[1] = FourRounds<1>(states[0], MsgSchedule(&w, 8));
337 states[0] = FourRounds<1>(states[1], MsgSchedule(&w, 9));
338 states[1] = FourRounds<2>(states[0], MsgSchedule(&w, 10));
339 states[0] = FourRounds<2>(states[1], MsgSchedule(&w, 11));
340 states[1] = FourRounds<2>(states[0], MsgSchedule(&w, 12));
341 states[0] = FourRounds<2>(states[1], MsgSchedule(&w, 13));
342 states[1] = FourRounds<2>(states[0], MsgSchedule(&w, 14));
343 states[0] = FourRounds<3>(states[1], MsgSchedule(&w, 15));
344 states[1] = FourRounds<3>(states[0], MsgSchedule(&w, 16));
345 states[0] = FourRounds<3>(states[1], MsgSchedule(&w, 17));
346 states[1] = FourRounds<3>(states[0], MsgSchedule(&w, 18));
347 states[0] = FourRounds<3>(states[1], MsgSchedule(&w, 19));
348
349 state = {vaddq_u32(state.abcd, states[0].abcd), state.e + states[0].e};
350 }
351
352 virtual Digest GetDigest() override
353 {
354 Digest digest;
355 vst1q_u8(&digest[0], vrev32q_u8(vreinterpretq_u8_u32(state.abcd)));
356 u32 e = Common::FromBigEndian(state.e);
357 std::memcpy(&digest[sizeof(state.abcd)], &e, sizeof(e));
358 return digest;
359 }
360
361 virtual bool HwAccelerated() const override { return true; }
362
363 State state;
364 };
365
366 #endif
367
368 std::unique_ptr<Context> CreateContext()
369 {
370 if (cpu_info.bSHA1)
371 {
372 #ifdef _M_X86_64
373 // Note: As of mid 2022, > 99% of CPUs reporting to Steam survey have SSSE3, ~40% have SHA.
374 // Seems unlikely we'll see any cpus supporting SHA but not SSSE3 (in the foreseeable future at
375 // least).
376 if (cpu_info.bSSSE3)
377 return std::make_unique<ContextX64SHA1>();
378 #elif defined(_M_ARM_64)
379 return std::make_unique<ContextNeon>();
380 #endif
381 }
382 return std::make_unique<ContextMbed>();
383 }
384
385 Digest CalculateDigest(const u8* msg, size_t len)
386 {
387 auto ctx = CreateContext();
388 ctx->Update(msg, len);
389 return ctx->Finish();
390 }
391
392 std::string DigestToString(const Digest& digest)
393 {
394 return fmt::format("{:02X}", fmt::join(digest, ""));
395 }
396
397 std::string DigestToSource(const Digest& digest)
398 {
399 return fmt::format("{{0x{:02X}}}", fmt::join(digest, ", 0x"));
400 }
401 } // namespace Common::SHA1