1*81ad6265SDimitry Andric /*===-- blake3.c - BLAKE3 C Implementation ------------------------*- C -*-===*\
2*81ad6265SDimitry Andric |*                                                                            *|
3*81ad6265SDimitry Andric |* Released into the public domain with CC0 1.0                               *|
4*81ad6265SDimitry Andric |* See 'llvm/lib/Support/BLAKE3/LICENSE' for info.                            *|
5*81ad6265SDimitry Andric |* SPDX-License-Identifier: CC0-1.0                                           *|
6*81ad6265SDimitry Andric |*                                                                            *|
7*81ad6265SDimitry Andric \*===----------------------------------------------------------------------===*/
8*81ad6265SDimitry Andric 
9*81ad6265SDimitry Andric #include <assert.h>
10*81ad6265SDimitry Andric #include <stdbool.h>
11*81ad6265SDimitry Andric #include <string.h>
12*81ad6265SDimitry Andric 
13*81ad6265SDimitry Andric #include "blake3_impl.h"
14*81ad6265SDimitry Andric 
llvm_blake3_version(void)15*81ad6265SDimitry Andric const char *llvm_blake3_version(void) { return BLAKE3_VERSION_STRING; }
16*81ad6265SDimitry Andric 
chunk_state_init(blake3_chunk_state * self,const uint32_t key[8],uint8_t flags)17*81ad6265SDimitry Andric INLINE void chunk_state_init(blake3_chunk_state *self, const uint32_t key[8],
18*81ad6265SDimitry Andric                              uint8_t flags) {
19*81ad6265SDimitry Andric   memcpy(self->cv, key, BLAKE3_KEY_LEN);
20*81ad6265SDimitry Andric   self->chunk_counter = 0;
21*81ad6265SDimitry Andric   memset(self->buf, 0, BLAKE3_BLOCK_LEN);
22*81ad6265SDimitry Andric   self->buf_len = 0;
23*81ad6265SDimitry Andric   self->blocks_compressed = 0;
24*81ad6265SDimitry Andric   self->flags = flags;
25*81ad6265SDimitry Andric }
26*81ad6265SDimitry Andric 
chunk_state_reset(blake3_chunk_state * self,const uint32_t key[8],uint64_t chunk_counter)27*81ad6265SDimitry Andric INLINE void chunk_state_reset(blake3_chunk_state *self, const uint32_t key[8],
28*81ad6265SDimitry Andric                               uint64_t chunk_counter) {
29*81ad6265SDimitry Andric   memcpy(self->cv, key, BLAKE3_KEY_LEN);
30*81ad6265SDimitry Andric   self->chunk_counter = chunk_counter;
31*81ad6265SDimitry Andric   self->blocks_compressed = 0;
32*81ad6265SDimitry Andric   memset(self->buf, 0, BLAKE3_BLOCK_LEN);
33*81ad6265SDimitry Andric   self->buf_len = 0;
34*81ad6265SDimitry Andric }
35*81ad6265SDimitry Andric 
chunk_state_len(const blake3_chunk_state * self)36*81ad6265SDimitry Andric INLINE size_t chunk_state_len(const blake3_chunk_state *self) {
37*81ad6265SDimitry Andric   return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) +
38*81ad6265SDimitry Andric          ((size_t)self->buf_len);
39*81ad6265SDimitry Andric }
40*81ad6265SDimitry Andric 
chunk_state_fill_buf(blake3_chunk_state * self,const uint8_t * input,size_t input_len)41*81ad6265SDimitry Andric INLINE size_t chunk_state_fill_buf(blake3_chunk_state *self,
42*81ad6265SDimitry Andric                                    const uint8_t *input, size_t input_len) {
43*81ad6265SDimitry Andric   size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len);
44*81ad6265SDimitry Andric   if (take > input_len) {
45*81ad6265SDimitry Andric     take = input_len;
46*81ad6265SDimitry Andric   }
47*81ad6265SDimitry Andric   uint8_t *dest = self->buf + ((size_t)self->buf_len);
48*81ad6265SDimitry Andric   memcpy(dest, input, take);
49*81ad6265SDimitry Andric   self->buf_len += (uint8_t)take;
50*81ad6265SDimitry Andric   return take;
51*81ad6265SDimitry Andric }
52*81ad6265SDimitry Andric 
chunk_state_maybe_start_flag(const blake3_chunk_state * self)53*81ad6265SDimitry Andric INLINE uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state *self) {
54*81ad6265SDimitry Andric   if (self->blocks_compressed == 0) {
55*81ad6265SDimitry Andric     return CHUNK_START;
56*81ad6265SDimitry Andric   } else {
57*81ad6265SDimitry Andric     return 0;
58*81ad6265SDimitry Andric   }
59*81ad6265SDimitry Andric }
60*81ad6265SDimitry Andric 
61*81ad6265SDimitry Andric typedef struct {
62*81ad6265SDimitry Andric   uint32_t input_cv[8];
63*81ad6265SDimitry Andric   uint64_t counter;
64*81ad6265SDimitry Andric   uint8_t block[BLAKE3_BLOCK_LEN];
65*81ad6265SDimitry Andric   uint8_t block_len;
66*81ad6265SDimitry Andric   uint8_t flags;
67*81ad6265SDimitry Andric } output_t;
68*81ad6265SDimitry Andric 
make_output(const uint32_t input_cv[8],const uint8_t block[BLAKE3_BLOCK_LEN],uint8_t block_len,uint64_t counter,uint8_t flags)69*81ad6265SDimitry Andric INLINE output_t make_output(const uint32_t input_cv[8],
70*81ad6265SDimitry Andric                             const uint8_t block[BLAKE3_BLOCK_LEN],
71*81ad6265SDimitry Andric                             uint8_t block_len, uint64_t counter,
72*81ad6265SDimitry Andric                             uint8_t flags) {
73*81ad6265SDimitry Andric   output_t ret;
74*81ad6265SDimitry Andric   memcpy(ret.input_cv, input_cv, 32);
75*81ad6265SDimitry Andric   memcpy(ret.block, block, BLAKE3_BLOCK_LEN);
76*81ad6265SDimitry Andric   ret.block_len = block_len;
77*81ad6265SDimitry Andric   ret.counter = counter;
78*81ad6265SDimitry Andric   ret.flags = flags;
79*81ad6265SDimitry Andric   return ret;
80*81ad6265SDimitry Andric }
81*81ad6265SDimitry Andric 
82*81ad6265SDimitry Andric // Chaining values within a given chunk (specifically the compress_in_place
83*81ad6265SDimitry Andric // interface) are represented as words. This avoids unnecessary bytes<->words
84*81ad6265SDimitry Andric // conversion overhead in the portable implementation. However, the hash_many
85*81ad6265SDimitry Andric // interface handles both user input and parent node blocks, so it accepts
86*81ad6265SDimitry Andric // bytes. For that reason, chaining values in the CV stack are represented as
87*81ad6265SDimitry Andric // bytes.
output_chaining_value(const output_t * self,uint8_t cv[32])88*81ad6265SDimitry Andric INLINE void output_chaining_value(const output_t *self, uint8_t cv[32]) {
89*81ad6265SDimitry Andric   uint32_t cv_words[8];
90*81ad6265SDimitry Andric   memcpy(cv_words, self->input_cv, 32);
91*81ad6265SDimitry Andric   blake3_compress_in_place(cv_words, self->block, self->block_len,
92*81ad6265SDimitry Andric                            self->counter, self->flags);
93*81ad6265SDimitry Andric   store_cv_words(cv, cv_words);
94*81ad6265SDimitry Andric }
95*81ad6265SDimitry Andric 
output_root_bytes(const output_t * self,uint64_t seek,uint8_t * out,size_t out_len)96*81ad6265SDimitry Andric INLINE void output_root_bytes(const output_t *self, uint64_t seek, uint8_t *out,
97*81ad6265SDimitry Andric                               size_t out_len) {
98*81ad6265SDimitry Andric   uint64_t output_block_counter = seek / 64;
99*81ad6265SDimitry Andric   size_t offset_within_block = seek % 64;
100*81ad6265SDimitry Andric   uint8_t wide_buf[64];
101*81ad6265SDimitry Andric   while (out_len > 0) {
102*81ad6265SDimitry Andric     blake3_compress_xof(self->input_cv, self->block, self->block_len,
103*81ad6265SDimitry Andric                         output_block_counter, self->flags | ROOT, wide_buf);
104*81ad6265SDimitry Andric     size_t available_bytes = 64 - offset_within_block;
105*81ad6265SDimitry Andric     size_t memcpy_len;
106*81ad6265SDimitry Andric     if (out_len > available_bytes) {
107*81ad6265SDimitry Andric       memcpy_len = available_bytes;
108*81ad6265SDimitry Andric     } else {
109*81ad6265SDimitry Andric       memcpy_len = out_len;
110*81ad6265SDimitry Andric     }
111*81ad6265SDimitry Andric     memcpy(out, wide_buf + offset_within_block, memcpy_len);
112*81ad6265SDimitry Andric     out += memcpy_len;
113*81ad6265SDimitry Andric     out_len -= memcpy_len;
114*81ad6265SDimitry Andric     output_block_counter += 1;
115*81ad6265SDimitry Andric     offset_within_block = 0;
116*81ad6265SDimitry Andric   }
117*81ad6265SDimitry Andric }
118*81ad6265SDimitry Andric 
chunk_state_update(blake3_chunk_state * self,const uint8_t * input,size_t input_len)119*81ad6265SDimitry Andric INLINE void chunk_state_update(blake3_chunk_state *self, const uint8_t *input,
120*81ad6265SDimitry Andric                                size_t input_len) {
121*81ad6265SDimitry Andric   if (self->buf_len > 0) {
122*81ad6265SDimitry Andric     size_t take = chunk_state_fill_buf(self, input, input_len);
123*81ad6265SDimitry Andric     input += take;
124*81ad6265SDimitry Andric     input_len -= take;
125*81ad6265SDimitry Andric     if (input_len > 0) {
126*81ad6265SDimitry Andric       blake3_compress_in_place(
127*81ad6265SDimitry Andric           self->cv, self->buf, BLAKE3_BLOCK_LEN, self->chunk_counter,
128*81ad6265SDimitry Andric           self->flags | chunk_state_maybe_start_flag(self));
129*81ad6265SDimitry Andric       self->blocks_compressed += 1;
130*81ad6265SDimitry Andric       self->buf_len = 0;
131*81ad6265SDimitry Andric       memset(self->buf, 0, BLAKE3_BLOCK_LEN);
132*81ad6265SDimitry Andric     }
133*81ad6265SDimitry Andric   }
134*81ad6265SDimitry Andric 
135*81ad6265SDimitry Andric   while (input_len > BLAKE3_BLOCK_LEN) {
136*81ad6265SDimitry Andric     blake3_compress_in_place(self->cv, input, BLAKE3_BLOCK_LEN,
137*81ad6265SDimitry Andric                              self->chunk_counter,
138*81ad6265SDimitry Andric                              self->flags | chunk_state_maybe_start_flag(self));
139*81ad6265SDimitry Andric     self->blocks_compressed += 1;
140*81ad6265SDimitry Andric     input += BLAKE3_BLOCK_LEN;
141*81ad6265SDimitry Andric     input_len -= BLAKE3_BLOCK_LEN;
142*81ad6265SDimitry Andric   }
143*81ad6265SDimitry Andric 
144*81ad6265SDimitry Andric   size_t take = chunk_state_fill_buf(self, input, input_len);
145*81ad6265SDimitry Andric   input += take;
146*81ad6265SDimitry Andric   input_len -= take;
147*81ad6265SDimitry Andric }
148*81ad6265SDimitry Andric 
chunk_state_output(const blake3_chunk_state * self)149*81ad6265SDimitry Andric INLINE output_t chunk_state_output(const blake3_chunk_state *self) {
150*81ad6265SDimitry Andric   uint8_t block_flags =
151*81ad6265SDimitry Andric       self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END;
152*81ad6265SDimitry Andric   return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter,
153*81ad6265SDimitry Andric                      block_flags);
154*81ad6265SDimitry Andric }
155*81ad6265SDimitry Andric 
parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],const uint32_t key[8],uint8_t flags)156*81ad6265SDimitry Andric INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],
157*81ad6265SDimitry Andric                               const uint32_t key[8], uint8_t flags) {
158*81ad6265SDimitry Andric   return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT);
159*81ad6265SDimitry Andric }
160*81ad6265SDimitry Andric 
161*81ad6265SDimitry Andric // Given some input larger than one chunk, return the number of bytes that
162*81ad6265SDimitry Andric // should go in the left subtree. This is the largest power-of-2 number of
163*81ad6265SDimitry Andric // chunks that leaves at least 1 byte for the right subtree.
left_len(size_t content_len)164*81ad6265SDimitry Andric INLINE size_t left_len(size_t content_len) {
165*81ad6265SDimitry Andric   // Subtract 1 to reserve at least one byte for the right side. content_len
166*81ad6265SDimitry Andric   // should always be greater than BLAKE3_CHUNK_LEN.
167*81ad6265SDimitry Andric   size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN;
168*81ad6265SDimitry Andric   return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN;
169*81ad6265SDimitry Andric }
170*81ad6265SDimitry Andric 
171*81ad6265SDimitry Andric // Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time
172*81ad6265SDimitry Andric // on a single thread. Write out the chunk chaining values and return the
173*81ad6265SDimitry Andric // number of chunks hashed. These chunks are never the root and never empty;
174*81ad6265SDimitry Andric // those cases use a different codepath.
compress_chunks_parallel(const uint8_t * input,size_t input_len,const uint32_t key[8],uint64_t chunk_counter,uint8_t flags,uint8_t * out)175*81ad6265SDimitry Andric INLINE size_t compress_chunks_parallel(const uint8_t *input, size_t input_len,
176*81ad6265SDimitry Andric                                        const uint32_t key[8],
177*81ad6265SDimitry Andric                                        uint64_t chunk_counter, uint8_t flags,
178*81ad6265SDimitry Andric                                        uint8_t *out) {
179*81ad6265SDimitry Andric #if defined(BLAKE3_TESTING)
180*81ad6265SDimitry Andric   assert(0 < input_len);
181*81ad6265SDimitry Andric   assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN);
182*81ad6265SDimitry Andric #endif
183*81ad6265SDimitry Andric 
184*81ad6265SDimitry Andric   const uint8_t *chunks_array[MAX_SIMD_DEGREE];
185*81ad6265SDimitry Andric   size_t input_position = 0;
186*81ad6265SDimitry Andric   size_t chunks_array_len = 0;
187*81ad6265SDimitry Andric   while (input_len - input_position >= BLAKE3_CHUNK_LEN) {
188*81ad6265SDimitry Andric     chunks_array[chunks_array_len] = &input[input_position];
189*81ad6265SDimitry Andric     input_position += BLAKE3_CHUNK_LEN;
190*81ad6265SDimitry Andric     chunks_array_len += 1;
191*81ad6265SDimitry Andric   }
192*81ad6265SDimitry Andric 
193*81ad6265SDimitry Andric   blake3_hash_many(chunks_array, chunks_array_len,
194*81ad6265SDimitry Andric                    BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, key, chunk_counter,
195*81ad6265SDimitry Andric                    true, flags, CHUNK_START, CHUNK_END, out);
196*81ad6265SDimitry Andric 
197*81ad6265SDimitry Andric   // Hash the remaining partial chunk, if there is one. Note that the empty
198*81ad6265SDimitry Andric   // chunk (meaning the empty message) is a different codepath.
199*81ad6265SDimitry Andric   if (input_len > input_position) {
200*81ad6265SDimitry Andric     uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;
201*81ad6265SDimitry Andric     blake3_chunk_state chunk_state;
202*81ad6265SDimitry Andric     chunk_state_init(&chunk_state, key, flags);
203*81ad6265SDimitry Andric     chunk_state.chunk_counter = counter;
204*81ad6265SDimitry Andric     chunk_state_update(&chunk_state, &input[input_position],
205*81ad6265SDimitry Andric                        input_len - input_position);
206*81ad6265SDimitry Andric     output_t output = chunk_state_output(&chunk_state);
207*81ad6265SDimitry Andric     output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]);
208*81ad6265SDimitry Andric     return chunks_array_len + 1;
209*81ad6265SDimitry Andric   } else {
210*81ad6265SDimitry Andric     return chunks_array_len;
211*81ad6265SDimitry Andric   }
212*81ad6265SDimitry Andric }
213*81ad6265SDimitry Andric 
214*81ad6265SDimitry Andric // Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time
215*81ad6265SDimitry Andric // on a single thread. Write out the parent chaining values and return the
216*81ad6265SDimitry Andric // number of parents hashed. (If there's an odd input chaining value left over,
217*81ad6265SDimitry Andric // return it as an additional output.) These parents are never the root and
218*81ad6265SDimitry Andric // never empty; those cases use a different codepath.
compress_parents_parallel(const uint8_t * child_chaining_values,size_t num_chaining_values,const uint32_t key[8],uint8_t flags,uint8_t * out)219*81ad6265SDimitry Andric INLINE size_t compress_parents_parallel(const uint8_t *child_chaining_values,
220*81ad6265SDimitry Andric                                         size_t num_chaining_values,
221*81ad6265SDimitry Andric                                         const uint32_t key[8], uint8_t flags,
222*81ad6265SDimitry Andric                                         uint8_t *out) {
223*81ad6265SDimitry Andric #if defined(BLAKE3_TESTING)
224*81ad6265SDimitry Andric   assert(2 <= num_chaining_values);
225*81ad6265SDimitry Andric   assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2);
226*81ad6265SDimitry Andric #endif
227*81ad6265SDimitry Andric 
228*81ad6265SDimitry Andric   const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2];
229*81ad6265SDimitry Andric   size_t parents_array_len = 0;
230*81ad6265SDimitry Andric   while (num_chaining_values - (2 * parents_array_len) >= 2) {
231*81ad6265SDimitry Andric     parents_array[parents_array_len] =
232*81ad6265SDimitry Andric         &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN];
233*81ad6265SDimitry Andric     parents_array_len += 1;
234*81ad6265SDimitry Andric   }
235*81ad6265SDimitry Andric 
236*81ad6265SDimitry Andric   blake3_hash_many(parents_array, parents_array_len, 1, key,
237*81ad6265SDimitry Andric                    0, // Parents always use counter 0.
238*81ad6265SDimitry Andric                    false, flags | PARENT,
239*81ad6265SDimitry Andric                    0, // Parents have no start flags.
240*81ad6265SDimitry Andric                    0, // Parents have no end flags.
241*81ad6265SDimitry Andric                    out);
242*81ad6265SDimitry Andric 
243*81ad6265SDimitry Andric   // If there's an odd child left over, it becomes an output.
244*81ad6265SDimitry Andric   if (num_chaining_values > 2 * parents_array_len) {
245*81ad6265SDimitry Andric     memcpy(&out[parents_array_len * BLAKE3_OUT_LEN],
246*81ad6265SDimitry Andric            &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN],
247*81ad6265SDimitry Andric            BLAKE3_OUT_LEN);
248*81ad6265SDimitry Andric     return parents_array_len + 1;
249*81ad6265SDimitry Andric   } else {
250*81ad6265SDimitry Andric     return parents_array_len;
251*81ad6265SDimitry Andric   }
252*81ad6265SDimitry Andric }
253*81ad6265SDimitry Andric 
254*81ad6265SDimitry Andric // The wide helper function returns (writes out) an array of chaining values
255*81ad6265SDimitry Andric // and returns the length of that array. The number of chaining values returned
256*81ad6265SDimitry Andric // is the dyanmically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,
257*81ad6265SDimitry Andric // if the input is shorter than that many chunks. The reason for maintaining a
258*81ad6265SDimitry Andric // wide array of chaining values going back up the tree, is to allow the
259*81ad6265SDimitry Andric // implementation to hash as many parents in parallel as possible.
260*81ad6265SDimitry Andric //
261*81ad6265SDimitry Andric // As a special case when the SIMD degree is 1, this function will still return
262*81ad6265SDimitry Andric // at least 2 outputs. This guarantees that this function doesn't perform the
263*81ad6265SDimitry Andric // root compression. (If it did, it would use the wrong flags, and also we
264*81ad6265SDimitry Andric // wouldn't be able to implement exendable ouput.) Note that this function is
265*81ad6265SDimitry Andric // not used when the whole input is only 1 chunk long; that's a different
266*81ad6265SDimitry Andric // codepath.
267*81ad6265SDimitry Andric //
268*81ad6265SDimitry Andric // Why not just have the caller split the input on the first update(), instead
269*81ad6265SDimitry Andric // of implementing this special rule? Because we don't want to limit SIMD or
270*81ad6265SDimitry Andric // multi-threading parallelism for that update().
blake3_compress_subtree_wide(const uint8_t * input,size_t input_len,const uint32_t key[8],uint64_t chunk_counter,uint8_t flags,uint8_t * out)271*81ad6265SDimitry Andric static size_t blake3_compress_subtree_wide(const uint8_t *input,
272*81ad6265SDimitry Andric                                            size_t input_len,
273*81ad6265SDimitry Andric                                            const uint32_t key[8],
274*81ad6265SDimitry Andric                                            uint64_t chunk_counter,
275*81ad6265SDimitry Andric                                            uint8_t flags, uint8_t *out) {
276*81ad6265SDimitry Andric   // Note that the single chunk case does *not* bump the SIMD degree up to 2
277*81ad6265SDimitry Andric   // when it is 1. If this implementation adds multi-threading in the future,
278*81ad6265SDimitry Andric   // this gives us the option of multi-threading even the 2-chunk case, which
279*81ad6265SDimitry Andric   // can help performance on smaller platforms.
280*81ad6265SDimitry Andric   if (input_len <= blake3_simd_degree() * BLAKE3_CHUNK_LEN) {
281*81ad6265SDimitry Andric     return compress_chunks_parallel(input, input_len, key, chunk_counter, flags,
282*81ad6265SDimitry Andric                                     out);
283*81ad6265SDimitry Andric   }
284*81ad6265SDimitry Andric 
285*81ad6265SDimitry Andric   // With more than simd_degree chunks, we need to recurse. Start by dividing
286*81ad6265SDimitry Andric   // the input into left and right subtrees. (Note that this is only optimal
287*81ad6265SDimitry Andric   // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree
288*81ad6265SDimitry Andric   // of 3 or something, we'll need a more complicated strategy.)
289*81ad6265SDimitry Andric   size_t left_input_len = left_len(input_len);
290*81ad6265SDimitry Andric   size_t right_input_len = input_len - left_input_len;
291*81ad6265SDimitry Andric   const uint8_t *right_input = &input[left_input_len];
292*81ad6265SDimitry Andric   uint64_t right_chunk_counter =
293*81ad6265SDimitry Andric       chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);
294*81ad6265SDimitry Andric 
295*81ad6265SDimitry Andric   // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to
296*81ad6265SDimitry Andric   // account for the special case of returning 2 outputs when the SIMD degree
297*81ad6265SDimitry Andric   // is 1.
298*81ad6265SDimitry Andric   uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];
299*81ad6265SDimitry Andric   size_t degree = blake3_simd_degree();
300*81ad6265SDimitry Andric   if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {
301*81ad6265SDimitry Andric     // The special case: We always use a degree of at least two, to make
302*81ad6265SDimitry Andric     // sure there are two outputs. Except, as noted above, at the chunk
303*81ad6265SDimitry Andric     // level, where we allow degree=1. (Note that the 1-chunk-input case is
304*81ad6265SDimitry Andric     // a different codepath.)
305*81ad6265SDimitry Andric     degree = 2;
306*81ad6265SDimitry Andric   }
307*81ad6265SDimitry Andric   uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];
308*81ad6265SDimitry Andric 
309*81ad6265SDimitry Andric   // Recurse! If this implementation adds multi-threading support in the
310*81ad6265SDimitry Andric   // future, this is where it will go.
311*81ad6265SDimitry Andric   size_t left_n = blake3_compress_subtree_wide(input, left_input_len, key,
312*81ad6265SDimitry Andric                                                chunk_counter, flags, cv_array);
313*81ad6265SDimitry Andric   size_t right_n = blake3_compress_subtree_wide(
314*81ad6265SDimitry Andric       right_input, right_input_len, key, right_chunk_counter, flags, right_cvs);
315*81ad6265SDimitry Andric 
316*81ad6265SDimitry Andric   // The special case again. If simd_degree=1, then we'll have left_n=1 and
317*81ad6265SDimitry Andric   // right_n=1. Rather than compressing them into a single output, return
318*81ad6265SDimitry Andric   // them directly, to make sure we always have at least two outputs.
319*81ad6265SDimitry Andric   if (left_n == 1) {
320*81ad6265SDimitry Andric     memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);
321*81ad6265SDimitry Andric     return 2;
322*81ad6265SDimitry Andric   }
323*81ad6265SDimitry Andric 
324*81ad6265SDimitry Andric   // Otherwise, do one layer of parent node compression.
325*81ad6265SDimitry Andric   size_t num_chaining_values = left_n + right_n;
326*81ad6265SDimitry Andric   return compress_parents_parallel(cv_array, num_chaining_values, key, flags,
327*81ad6265SDimitry Andric                                    out);
328*81ad6265SDimitry Andric }
329*81ad6265SDimitry Andric 
330*81ad6265SDimitry Andric // Hash a subtree with compress_subtree_wide(), and then condense the resulting
331*81ad6265SDimitry Andric // list of chaining values down to a single parent node. Don't compress that
332*81ad6265SDimitry Andric // last parent node, however. Instead, return its message bytes (the
333*81ad6265SDimitry Andric // concatenated chaining values of its children). This is necessary when the
334*81ad6265SDimitry Andric // first call to update() supplies a complete subtree, because the topmost
335*81ad6265SDimitry Andric // parent node of that subtree could end up being the root. It's also necessary
336*81ad6265SDimitry Andric // for extended output in the general case.
337*81ad6265SDimitry Andric //
338*81ad6265SDimitry Andric // As with compress_subtree_wide(), this function is not used on inputs of 1
339*81ad6265SDimitry Andric // chunk or less. That's a different codepath.
compress_subtree_to_parent_node(const uint8_t * input,size_t input_len,const uint32_t key[8],uint64_t chunk_counter,uint8_t flags,uint8_t out[2* BLAKE3_OUT_LEN])340*81ad6265SDimitry Andric INLINE void compress_subtree_to_parent_node(
341*81ad6265SDimitry Andric     const uint8_t *input, size_t input_len, const uint32_t key[8],
342*81ad6265SDimitry Andric     uint64_t chunk_counter, uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN]) {
343*81ad6265SDimitry Andric #if defined(BLAKE3_TESTING)
344*81ad6265SDimitry Andric   assert(input_len > BLAKE3_CHUNK_LEN);
345*81ad6265SDimitry Andric #endif
346*81ad6265SDimitry Andric 
347*81ad6265SDimitry Andric   uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];
348*81ad6265SDimitry Andric   size_t num_cvs = blake3_compress_subtree_wide(input, input_len, key,
349*81ad6265SDimitry Andric                                                 chunk_counter, flags, cv_array);
350*81ad6265SDimitry Andric   assert(num_cvs <= MAX_SIMD_DEGREE_OR_2);
351*81ad6265SDimitry Andric 
352*81ad6265SDimitry Andric   // If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
353*81ad6265SDimitry Andric   // compress_subtree_wide() returns more than 2 chaining values. Condense
354*81ad6265SDimitry Andric   // them into 2 by forming parent nodes repeatedly.
355*81ad6265SDimitry Andric   uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2];
356*81ad6265SDimitry Andric   // The second half of this loop condition is always true, and we just
357*81ad6265SDimitry Andric   // asserted it above. But GCC can't tell that it's always true, and if NDEBUG
358*81ad6265SDimitry Andric   // is set on platforms where MAX_SIMD_DEGREE_OR_2 == 2, GCC emits spurious
359*81ad6265SDimitry Andric   // warnings here. GCC 8.5 is particularly sensitive, so if you're changing
360*81ad6265SDimitry Andric   // this code, test it against that version.
361*81ad6265SDimitry Andric   while (num_cvs > 2 && num_cvs <= MAX_SIMD_DEGREE_OR_2) {
362*81ad6265SDimitry Andric     num_cvs =
363*81ad6265SDimitry Andric         compress_parents_parallel(cv_array, num_cvs, key, flags, out_array);
364*81ad6265SDimitry Andric     memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN);
365*81ad6265SDimitry Andric   }
366*81ad6265SDimitry Andric   memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);
367*81ad6265SDimitry Andric }
368*81ad6265SDimitry Andric 
hasher_init_base(blake3_hasher * self,const uint32_t key[8],uint8_t flags)369*81ad6265SDimitry Andric INLINE void hasher_init_base(blake3_hasher *self, const uint32_t key[8],
370*81ad6265SDimitry Andric                              uint8_t flags) {
371*81ad6265SDimitry Andric   memcpy(self->key, key, BLAKE3_KEY_LEN);
372*81ad6265SDimitry Andric   chunk_state_init(&self->chunk, key, flags);
373*81ad6265SDimitry Andric   self->cv_stack_len = 0;
374*81ad6265SDimitry Andric }
375*81ad6265SDimitry Andric 
llvm_blake3_hasher_init(blake3_hasher * self)376*81ad6265SDimitry Andric void llvm_blake3_hasher_init(blake3_hasher *self) { hasher_init_base(self, IV, 0); }
377*81ad6265SDimitry Andric 
llvm_blake3_hasher_init_keyed(blake3_hasher * self,const uint8_t key[BLAKE3_KEY_LEN])378*81ad6265SDimitry Andric void llvm_blake3_hasher_init_keyed(blake3_hasher *self,
379*81ad6265SDimitry Andric                               const uint8_t key[BLAKE3_KEY_LEN]) {
380*81ad6265SDimitry Andric   uint32_t key_words[8];
381*81ad6265SDimitry Andric   load_key_words(key, key_words);
382*81ad6265SDimitry Andric   hasher_init_base(self, key_words, KEYED_HASH);
383*81ad6265SDimitry Andric }
384*81ad6265SDimitry Andric 
llvm_blake3_hasher_init_derive_key_raw(blake3_hasher * self,const void * context,size_t context_len)385*81ad6265SDimitry Andric void llvm_blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context,
386*81ad6265SDimitry Andric                                        size_t context_len) {
387*81ad6265SDimitry Andric   blake3_hasher context_hasher;
388*81ad6265SDimitry Andric   hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT);
389*81ad6265SDimitry Andric   llvm_blake3_hasher_update(&context_hasher, context, context_len);
390*81ad6265SDimitry Andric   uint8_t context_key[BLAKE3_KEY_LEN];
391*81ad6265SDimitry Andric   llvm_blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN);
392*81ad6265SDimitry Andric   uint32_t context_key_words[8];
393*81ad6265SDimitry Andric   load_key_words(context_key, context_key_words);
394*81ad6265SDimitry Andric   hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL);
395*81ad6265SDimitry Andric }
396*81ad6265SDimitry Andric 
llvm_blake3_hasher_init_derive_key(blake3_hasher * self,const char * context)397*81ad6265SDimitry Andric void llvm_blake3_hasher_init_derive_key(blake3_hasher *self, const char *context) {
398*81ad6265SDimitry Andric   llvm_blake3_hasher_init_derive_key_raw(self, context, strlen(context));
399*81ad6265SDimitry Andric }
400*81ad6265SDimitry Andric 
401*81ad6265SDimitry Andric // As described in hasher_push_cv() below, we do "lazy merging", delaying
402*81ad6265SDimitry Andric // merges until right before the next CV is about to be added. This is
403*81ad6265SDimitry Andric // different from the reference implementation. Another difference is that we
404*81ad6265SDimitry Andric // aren't always merging 1 chunk at a time. Instead, each CV might represent
405*81ad6265SDimitry Andric // any power-of-two number of chunks, as long as the smaller-above-larger stack
406*81ad6265SDimitry Andric // order is maintained. Instead of the "count the trailing 0-bits" algorithm
407*81ad6265SDimitry Andric // described in the spec, we use a "count the total number of 1-bits" variant
408*81ad6265SDimitry Andric // that doesn't require us to retain the subtree size of the CV on top of the
409*81ad6265SDimitry Andric // stack. The principle is the same: each CV that should remain in the stack is
410*81ad6265SDimitry Andric // represented by a 1-bit in the total number of chunks (or bytes) so far.
hasher_merge_cv_stack(blake3_hasher * self,uint64_t total_len)411*81ad6265SDimitry Andric INLINE void hasher_merge_cv_stack(blake3_hasher *self, uint64_t total_len) {
412*81ad6265SDimitry Andric   size_t post_merge_stack_len = (size_t)popcnt(total_len);
413*81ad6265SDimitry Andric   while (self->cv_stack_len > post_merge_stack_len) {
414*81ad6265SDimitry Andric     uint8_t *parent_node =
415*81ad6265SDimitry Andric         &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN];
416*81ad6265SDimitry Andric     output_t output = parent_output(parent_node, self->key, self->chunk.flags);
417*81ad6265SDimitry Andric     output_chaining_value(&output, parent_node);
418*81ad6265SDimitry Andric     self->cv_stack_len -= 1;
419*81ad6265SDimitry Andric   }
420*81ad6265SDimitry Andric }
421*81ad6265SDimitry Andric 
422*81ad6265SDimitry Andric // In reference_impl.rs, we merge the new CV with existing CVs from the stack
423*81ad6265SDimitry Andric // before pushing it. We can do that because we know more input is coming, so
424*81ad6265SDimitry Andric // we know none of the merges are root.
425*81ad6265SDimitry Andric //
426*81ad6265SDimitry Andric // This setting is different. We want to feed as much input as possible to
427*81ad6265SDimitry Andric // compress_subtree_wide(), without setting aside anything for the chunk_state.
428*81ad6265SDimitry Andric // If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once
429*81ad6265SDimitry Andric // as a single subtree, if at all possible.
430*81ad6265SDimitry Andric //
431*81ad6265SDimitry Andric // This leads to two problems:
432*81ad6265SDimitry Andric // 1) This 64 KiB input might be the only call that ever gets made to update.
433*81ad6265SDimitry Andric //    In this case, the root node of the 64 KiB subtree would be the root node
434*81ad6265SDimitry Andric //    of the whole tree, and it would need to be ROOT finalized. We can't
435*81ad6265SDimitry Andric //    compress it until we know.
436*81ad6265SDimitry Andric // 2) This 64 KiB input might complete a larger tree, whose root node is
437*81ad6265SDimitry Andric //    similarly going to be the the root of the whole tree. For example, maybe
438*81ad6265SDimitry Andric //    we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the
439*81ad6265SDimitry Andric //    node at the root of the 256 KiB subtree until we know how to finalize it.
440*81ad6265SDimitry Andric //
441*81ad6265SDimitry Andric // The second problem is solved with "lazy merging". That is, when we're about
442*81ad6265SDimitry Andric // to add a CV to the stack, we don't merge it with anything first, as the
443*81ad6265SDimitry Andric // reference impl does. Instead we do merges using the *previous* CV that was
444*81ad6265SDimitry Andric // added, which is sitting on top of the stack, and we put the new CV
445*81ad6265SDimitry Andric // (unmerged) on top of the stack afterwards. This guarantees that we never
446*81ad6265SDimitry Andric // merge the root node until finalize().
447*81ad6265SDimitry Andric //
448*81ad6265SDimitry Andric // Solving the first problem requires an additional tool,
449*81ad6265SDimitry Andric // compress_subtree_to_parent_node(). That function always returns the top
450*81ad6265SDimitry Andric // *two* chaining values of the subtree it's compressing. We then do lazy
451*81ad6265SDimitry Andric // merging with each of them separately, so that the second CV will always
452*81ad6265SDimitry Andric // remain unmerged. (That also helps us support extendable output when we're
453*81ad6265SDimitry Andric // hashing an input all-at-once.)
hasher_push_cv(blake3_hasher * self,uint8_t new_cv[BLAKE3_OUT_LEN],uint64_t chunk_counter)454*81ad6265SDimitry Andric INLINE void hasher_push_cv(blake3_hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN],
455*81ad6265SDimitry Andric                            uint64_t chunk_counter) {
456*81ad6265SDimitry Andric   hasher_merge_cv_stack(self, chunk_counter);
457*81ad6265SDimitry Andric   memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv,
458*81ad6265SDimitry Andric          BLAKE3_OUT_LEN);
459*81ad6265SDimitry Andric   self->cv_stack_len += 1;
460*81ad6265SDimitry Andric }
461*81ad6265SDimitry Andric 
llvm_blake3_hasher_update(blake3_hasher * self,const void * input,size_t input_len)462*81ad6265SDimitry Andric void llvm_blake3_hasher_update(blake3_hasher *self, const void *input,
463*81ad6265SDimitry Andric                           size_t input_len) {
464*81ad6265SDimitry Andric   // Explicitly checking for zero avoids causing UB by passing a null pointer
465*81ad6265SDimitry Andric   // to memcpy. This comes up in practice with things like:
466*81ad6265SDimitry Andric   //   std::vector<uint8_t> v;
467*81ad6265SDimitry Andric   //   blake3_hasher_update(&hasher, v.data(), v.size());
468*81ad6265SDimitry Andric   if (input_len == 0) {
469*81ad6265SDimitry Andric     return;
470*81ad6265SDimitry Andric   }
471*81ad6265SDimitry Andric 
472*81ad6265SDimitry Andric   const uint8_t *input_bytes = (const uint8_t *)input;
473*81ad6265SDimitry Andric 
474*81ad6265SDimitry Andric   // If we have some partial chunk bytes in the internal chunk_state, we need
475*81ad6265SDimitry Andric   // to finish that chunk first.
476*81ad6265SDimitry Andric   if (chunk_state_len(&self->chunk) > 0) {
477*81ad6265SDimitry Andric     size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk);
478*81ad6265SDimitry Andric     if (take > input_len) {
479*81ad6265SDimitry Andric       take = input_len;
480*81ad6265SDimitry Andric     }
481*81ad6265SDimitry Andric     chunk_state_update(&self->chunk, input_bytes, take);
482*81ad6265SDimitry Andric     input_bytes += take;
483*81ad6265SDimitry Andric     input_len -= take;
484*81ad6265SDimitry Andric     // If we've filled the current chunk and there's more coming, finalize this
485*81ad6265SDimitry Andric     // chunk and proceed. In this case we know it's not the root.
486*81ad6265SDimitry Andric     if (input_len > 0) {
487*81ad6265SDimitry Andric       output_t output = chunk_state_output(&self->chunk);
488*81ad6265SDimitry Andric       uint8_t chunk_cv[32];
489*81ad6265SDimitry Andric       output_chaining_value(&output, chunk_cv);
490*81ad6265SDimitry Andric       hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter);
491*81ad6265SDimitry Andric       chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1);
492*81ad6265SDimitry Andric     } else {
493*81ad6265SDimitry Andric       return;
494*81ad6265SDimitry Andric     }
495*81ad6265SDimitry Andric   }
496*81ad6265SDimitry Andric 
497*81ad6265SDimitry Andric   // Now the chunk_state is clear, and we have more input. If there's more than
498*81ad6265SDimitry Andric   // a single chunk (so, definitely not the root chunk), hash the largest whole
499*81ad6265SDimitry Andric   // subtree we can, with the full benefits of SIMD (and maybe in the future,
500*81ad6265SDimitry Andric   // multi-threading) parallelism. Two restrictions:
501*81ad6265SDimitry Andric   // - The subtree has to be a power-of-2 number of chunks. Only subtrees along
502*81ad6265SDimitry Andric   //   the right edge can be incomplete, and we don't know where the right edge
503*81ad6265SDimitry Andric   //   is going to be until we get to finalize().
504*81ad6265SDimitry Andric   // - The subtree must evenly divide the total number of chunks up until this
505*81ad6265SDimitry Andric   //   point (if total is not 0). If the current incomplete subtree is only
506*81ad6265SDimitry Andric   //   waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have
507*81ad6265SDimitry Andric   //   to complete the current subtree first.
508*81ad6265SDimitry Andric   // Because we might need to break up the input to form powers of 2, or to
509*81ad6265SDimitry Andric   // evenly divide what we already have, this part runs in a loop.
510*81ad6265SDimitry Andric   while (input_len > BLAKE3_CHUNK_LEN) {
511*81ad6265SDimitry Andric     size_t subtree_len = round_down_to_power_of_2(input_len);
512*81ad6265SDimitry Andric     uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN;
513*81ad6265SDimitry Andric     // Shrink the subtree_len until it evenly divides the count so far. We know
514*81ad6265SDimitry Andric     // that subtree_len itself is a power of 2, so we can use a bitmasking
515*81ad6265SDimitry Andric     // trick instead of an actual remainder operation. (Note that if the caller
516*81ad6265SDimitry Andric     // consistently passes power-of-2 inputs of the same size, as is hopefully
517*81ad6265SDimitry Andric     // typical, this loop condition will always fail, and subtree_len will
518*81ad6265SDimitry Andric     // always be the full length of the input.)
519*81ad6265SDimitry Andric     //
520*81ad6265SDimitry Andric     // An aside: We don't have to shrink subtree_len quite this much. For
521*81ad6265SDimitry Andric     // example, if count_so_far is 1, we could pass 2 chunks to
522*81ad6265SDimitry Andric     // compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still
523*81ad6265SDimitry Andric     // get the right answer in the end, and we might get to use 2-way SIMD
524*81ad6265SDimitry Andric     // parallelism. The problem with this optimization, is that it gets us
525*81ad6265SDimitry Andric     // stuck always hashing 2 chunks. The total number of chunks will remain
526*81ad6265SDimitry Andric     // odd, and we'll never graduate to higher degrees of parallelism. See
527*81ad6265SDimitry Andric     // https://github.com/BLAKE3-team/BLAKE3/issues/69.
528*81ad6265SDimitry Andric     while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {
529*81ad6265SDimitry Andric       subtree_len /= 2;
530*81ad6265SDimitry Andric     }
531*81ad6265SDimitry Andric     // The shrunken subtree_len might now be 1 chunk long. If so, hash that one
532*81ad6265SDimitry Andric     // chunk by itself. Otherwise, compress the subtree into a pair of CVs.
533*81ad6265SDimitry Andric     uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;
534*81ad6265SDimitry Andric     if (subtree_len <= BLAKE3_CHUNK_LEN) {
535*81ad6265SDimitry Andric       blake3_chunk_state chunk_state;
536*81ad6265SDimitry Andric       chunk_state_init(&chunk_state, self->key, self->chunk.flags);
537*81ad6265SDimitry Andric       chunk_state.chunk_counter = self->chunk.chunk_counter;
538*81ad6265SDimitry Andric       chunk_state_update(&chunk_state, input_bytes, subtree_len);
539*81ad6265SDimitry Andric       output_t output = chunk_state_output(&chunk_state);
540*81ad6265SDimitry Andric       uint8_t cv[BLAKE3_OUT_LEN];
541*81ad6265SDimitry Andric       output_chaining_value(&output, cv);
542*81ad6265SDimitry Andric       hasher_push_cv(self, cv, chunk_state.chunk_counter);
543*81ad6265SDimitry Andric     } else {
544*81ad6265SDimitry Andric       // This is the high-performance happy path, though getting here depends
545*81ad6265SDimitry Andric       // on the caller giving us a long enough input.
546*81ad6265SDimitry Andric       uint8_t cv_pair[2 * BLAKE3_OUT_LEN];
547*81ad6265SDimitry Andric       compress_subtree_to_parent_node(input_bytes, subtree_len, self->key,
548*81ad6265SDimitry Andric                                       self->chunk.chunk_counter,
549*81ad6265SDimitry Andric                                       self->chunk.flags, cv_pair);
550*81ad6265SDimitry Andric       hasher_push_cv(self, cv_pair, self->chunk.chunk_counter);
551*81ad6265SDimitry Andric       hasher_push_cv(self, &cv_pair[BLAKE3_OUT_LEN],
552*81ad6265SDimitry Andric                      self->chunk.chunk_counter + (subtree_chunks / 2));
553*81ad6265SDimitry Andric     }
554*81ad6265SDimitry Andric     self->chunk.chunk_counter += subtree_chunks;
555*81ad6265SDimitry Andric     input_bytes += subtree_len;
556*81ad6265SDimitry Andric     input_len -= subtree_len;
557*81ad6265SDimitry Andric   }
558*81ad6265SDimitry Andric 
559*81ad6265SDimitry Andric   // If there's any remaining input less than a full chunk, add it to the chunk
560*81ad6265SDimitry Andric   // state. In that case, also do a final merge loop to make sure the subtree
561*81ad6265SDimitry Andric   // stack doesn't contain any unmerged pairs. The remaining input means we
562*81ad6265SDimitry Andric   // know these merges are non-root. This merge loop isn't strictly necessary
563*81ad6265SDimitry Andric   // here, because hasher_push_chunk_cv already does its own merge loop, but it
564*81ad6265SDimitry Andric   // simplifies blake3_hasher_finalize below.
565*81ad6265SDimitry Andric   if (input_len > 0) {
566*81ad6265SDimitry Andric     chunk_state_update(&self->chunk, input_bytes, input_len);
567*81ad6265SDimitry Andric     hasher_merge_cv_stack(self, self->chunk.chunk_counter);
568*81ad6265SDimitry Andric   }
569*81ad6265SDimitry Andric }
570*81ad6265SDimitry Andric 
llvm_blake3_hasher_finalize(const blake3_hasher * self,uint8_t * out,size_t out_len)571*81ad6265SDimitry Andric void llvm_blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out,
572*81ad6265SDimitry Andric                             size_t out_len) {
573*81ad6265SDimitry Andric   llvm_blake3_hasher_finalize_seek(self, 0, out, out_len);
574*81ad6265SDimitry Andric #if LLVM_MEMORY_SANITIZER_BUILD
575*81ad6265SDimitry Andric   // Avoid false positives due to uninstrumented assembly code.
576*81ad6265SDimitry Andric   __msan_unpoison(out, out_len);
577*81ad6265SDimitry Andric #endif
578*81ad6265SDimitry Andric }
579*81ad6265SDimitry Andric 
llvm_blake3_hasher_finalize_seek(const blake3_hasher * self,uint64_t seek,uint8_t * out,size_t out_len)580*81ad6265SDimitry Andric void llvm_blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek,
581*81ad6265SDimitry Andric                                  uint8_t *out, size_t out_len) {
582*81ad6265SDimitry Andric   // Explicitly checking for zero avoids causing UB by passing a null pointer
583*81ad6265SDimitry Andric   // to memcpy. This comes up in practice with things like:
584*81ad6265SDimitry Andric   //   std::vector<uint8_t> v;
585*81ad6265SDimitry Andric   //   blake3_hasher_finalize(&hasher, v.data(), v.size());
586*81ad6265SDimitry Andric   if (out_len == 0) {
587*81ad6265SDimitry Andric     return;
588*81ad6265SDimitry Andric   }
589*81ad6265SDimitry Andric 
590*81ad6265SDimitry Andric   // If the subtree stack is empty, then the current chunk is the root.
591*81ad6265SDimitry Andric   if (self->cv_stack_len == 0) {
592*81ad6265SDimitry Andric     output_t output = chunk_state_output(&self->chunk);
593*81ad6265SDimitry Andric     output_root_bytes(&output, seek, out, out_len);
594*81ad6265SDimitry Andric     return;
595*81ad6265SDimitry Andric   }
596*81ad6265SDimitry Andric   // If there are any bytes in the chunk state, finalize that chunk and do a
597*81ad6265SDimitry Andric   // roll-up merge between that chunk hash and every subtree in the stack. In
598*81ad6265SDimitry Andric   // this case, the extra merge loop at the end of blake3_hasher_update
599*81ad6265SDimitry Andric   // guarantees that none of the subtrees in the stack need to be merged with
600*81ad6265SDimitry Andric   // each other first. Otherwise, if there are no bytes in the chunk state,
601*81ad6265SDimitry Andric   // then the top of the stack is a chunk hash, and we start the merge from
602*81ad6265SDimitry Andric   // that.
603*81ad6265SDimitry Andric   output_t output;
604*81ad6265SDimitry Andric   size_t cvs_remaining;
605*81ad6265SDimitry Andric   if (chunk_state_len(&self->chunk) > 0) {
606*81ad6265SDimitry Andric     cvs_remaining = self->cv_stack_len;
607*81ad6265SDimitry Andric     output = chunk_state_output(&self->chunk);
608*81ad6265SDimitry Andric   } else {
609*81ad6265SDimitry Andric     // There are always at least 2 CVs in the stack in this case.
610*81ad6265SDimitry Andric     cvs_remaining = self->cv_stack_len - 2;
611*81ad6265SDimitry Andric     output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key,
612*81ad6265SDimitry Andric                            self->chunk.flags);
613*81ad6265SDimitry Andric   }
614*81ad6265SDimitry Andric   while (cvs_remaining > 0) {
615*81ad6265SDimitry Andric     cvs_remaining -= 1;
616*81ad6265SDimitry Andric     uint8_t parent_block[BLAKE3_BLOCK_LEN];
617*81ad6265SDimitry Andric     memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32);
618*81ad6265SDimitry Andric     output_chaining_value(&output, &parent_block[32]);
619*81ad6265SDimitry Andric     output = parent_output(parent_block, self->key, self->chunk.flags);
620*81ad6265SDimitry Andric   }
621*81ad6265SDimitry Andric   output_root_bytes(&output, seek, out, out_len);
622*81ad6265SDimitry Andric }
623*81ad6265SDimitry Andric 
llvm_blake3_hasher_reset(blake3_hasher * self)624*81ad6265SDimitry Andric void llvm_blake3_hasher_reset(blake3_hasher *self) {
625*81ad6265SDimitry Andric   chunk_state_reset(&self->chunk, self->key, 0);
626*81ad6265SDimitry Andric   self->cv_stack_len = 0;
627*81ad6265SDimitry Andric }
628