Path: blob/main/contrib/llvm-project/llvm/lib/Support/BLAKE3/blake3.c
35294 views
/*===-- blake3.c - BLAKE3 C Implementation ------------------------*- C -*-===*\1|* *|2|* Released into the public domain with CC0 1.0 *|3|* See 'llvm/lib/Support/BLAKE3/LICENSE' for info. *|4|* SPDX-License-Identifier: CC0-1.0 *|5|* *|6\*===----------------------------------------------------------------------===*/78#include <assert.h>9#include <stdbool.h>10#include <string.h>1112#include "blake3_impl.h"1314const char *llvm_blake3_version(void) { return BLAKE3_VERSION_STRING; }1516INLINE void chunk_state_init(blake3_chunk_state *self, const uint32_t key[8],17uint8_t flags) {18memcpy(self->cv, key, BLAKE3_KEY_LEN);19self->chunk_counter = 0;20memset(self->buf, 0, BLAKE3_BLOCK_LEN);21self->buf_len = 0;22self->blocks_compressed = 0;23self->flags = flags;24}2526INLINE void chunk_state_reset(blake3_chunk_state *self, const uint32_t key[8],27uint64_t chunk_counter) {28memcpy(self->cv, key, BLAKE3_KEY_LEN);29self->chunk_counter = chunk_counter;30self->blocks_compressed = 0;31memset(self->buf, 0, BLAKE3_BLOCK_LEN);32self->buf_len = 0;33}3435INLINE size_t chunk_state_len(const blake3_chunk_state *self) {36return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) +37((size_t)self->buf_len);38}3940INLINE size_t chunk_state_fill_buf(blake3_chunk_state *self,41const uint8_t *input, size_t input_len) {42size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len);43if (take > input_len) {44take = input_len;45}46uint8_t *dest = self->buf + ((size_t)self->buf_len);47memcpy(dest, input, take);48self->buf_len += (uint8_t)take;49return take;50}5152INLINE uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state *self) {53if (self->blocks_compressed == 0) {54return CHUNK_START;55} else {56return 0;57}58}5960typedef struct {61uint32_t input_cv[8];62uint64_t counter;63uint8_t block[BLAKE3_BLOCK_LEN];64uint8_t block_len;65uint8_t flags;66} output_t;6768INLINE output_t make_output(const uint32_t input_cv[8],69const uint8_t block[BLAKE3_BLOCK_LEN],70uint8_t block_len, uint64_t counter,71uint8_t flags) {72output_t ret;73memcpy(ret.input_cv, input_cv, 32);74memcpy(ret.block, block, BLAKE3_BLOCK_LEN);75ret.block_len = block_len;76ret.counter = counter;77ret.flags = flags;78return ret;79}8081// Chaining values within a given chunk (specifically the compress_in_place82// interface) are represented as words. This avoids unnecessary bytes<->words83// conversion overhead in the portable implementation. However, the hash_many84// interface handles both user input and parent node blocks, so it accepts85// bytes. For that reason, chaining values in the CV stack are represented as86// bytes.87INLINE void output_chaining_value(const output_t *self, uint8_t cv[32]) {88uint32_t cv_words[8];89memcpy(cv_words, self->input_cv, 32);90blake3_compress_in_place(cv_words, self->block, self->block_len,91self->counter, self->flags);92store_cv_words(cv, cv_words);93}9495INLINE void output_root_bytes(const output_t *self, uint64_t seek, uint8_t *out,96size_t out_len) {97uint64_t output_block_counter = seek / 64;98size_t offset_within_block = seek % 64;99uint8_t wide_buf[64];100while (out_len > 0) {101blake3_compress_xof(self->input_cv, self->block, self->block_len,102output_block_counter, self->flags | ROOT, wide_buf);103size_t available_bytes = 64 - offset_within_block;104size_t memcpy_len;105if (out_len > available_bytes) {106memcpy_len = available_bytes;107} else {108memcpy_len = out_len;109}110memcpy(out, wide_buf + offset_within_block, memcpy_len);111out += memcpy_len;112out_len -= memcpy_len;113output_block_counter += 1;114offset_within_block = 0;115}116}117118INLINE void chunk_state_update(blake3_chunk_state *self, const uint8_t *input,119size_t input_len) {120if (self->buf_len > 0) {121size_t take = chunk_state_fill_buf(self, input, input_len);122input += take;123input_len -= take;124if (input_len > 0) {125blake3_compress_in_place(126self->cv, self->buf, BLAKE3_BLOCK_LEN, self->chunk_counter,127self->flags | chunk_state_maybe_start_flag(self));128self->blocks_compressed += 1;129self->buf_len = 0;130memset(self->buf, 0, BLAKE3_BLOCK_LEN);131}132}133134while (input_len > BLAKE3_BLOCK_LEN) {135blake3_compress_in_place(self->cv, input, BLAKE3_BLOCK_LEN,136self->chunk_counter,137self->flags | chunk_state_maybe_start_flag(self));138self->blocks_compressed += 1;139input += BLAKE3_BLOCK_LEN;140input_len -= BLAKE3_BLOCK_LEN;141}142143chunk_state_fill_buf(self, input, input_len);144}145146INLINE output_t chunk_state_output(const blake3_chunk_state *self) {147uint8_t block_flags =148self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END;149return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter,150block_flags);151}152153INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],154const uint32_t key[8], uint8_t flags) {155return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT);156}157158// Given some input larger than one chunk, return the number of bytes that159// should go in the left subtree. This is the largest power-of-2 number of160// chunks that leaves at least 1 byte for the right subtree.161INLINE size_t left_len(size_t content_len) {162// Subtract 1 to reserve at least one byte for the right side. content_len163// should always be greater than BLAKE3_CHUNK_LEN.164size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN;165return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN;166}167168// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time169// on a single thread. Write out the chunk chaining values and return the170// number of chunks hashed. These chunks are never the root and never empty;171// those cases use a different codepath.172INLINE size_t compress_chunks_parallel(const uint8_t *input, size_t input_len,173const uint32_t key[8],174uint64_t chunk_counter, uint8_t flags,175uint8_t *out) {176#if defined(BLAKE3_TESTING)177assert(0 < input_len);178assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN);179#endif180181const uint8_t *chunks_array[MAX_SIMD_DEGREE];182size_t input_position = 0;183size_t chunks_array_len = 0;184while (input_len - input_position >= BLAKE3_CHUNK_LEN) {185chunks_array[chunks_array_len] = &input[input_position];186input_position += BLAKE3_CHUNK_LEN;187chunks_array_len += 1;188}189190blake3_hash_many(chunks_array, chunks_array_len,191BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, key, chunk_counter,192true, flags, CHUNK_START, CHUNK_END, out);193194// Hash the remaining partial chunk, if there is one. Note that the empty195// chunk (meaning the empty message) is a different codepath.196if (input_len > input_position) {197uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;198blake3_chunk_state chunk_state;199chunk_state_init(&chunk_state, key, flags);200chunk_state.chunk_counter = counter;201chunk_state_update(&chunk_state, &input[input_position],202input_len - input_position);203output_t output = chunk_state_output(&chunk_state);204output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]);205return chunks_array_len + 1;206} else {207return chunks_array_len;208}209}210211// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time212// on a single thread. Write out the parent chaining values and return the213// number of parents hashed. (If there's an odd input chaining value left over,214// return it as an additional output.) These parents are never the root and215// never empty; those cases use a different codepath.216INLINE size_t compress_parents_parallel(const uint8_t *child_chaining_values,217size_t num_chaining_values,218const uint32_t key[8], uint8_t flags,219uint8_t *out) {220#if defined(BLAKE3_TESTING)221assert(2 <= num_chaining_values);222assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2);223#endif224225const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2];226size_t parents_array_len = 0;227while (num_chaining_values - (2 * parents_array_len) >= 2) {228parents_array[parents_array_len] =229&child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN];230parents_array_len += 1;231}232233blake3_hash_many(parents_array, parents_array_len, 1, key,2340, // Parents always use counter 0.235false, flags | PARENT,2360, // Parents have no start flags.2370, // Parents have no end flags.238out);239240// If there's an odd child left over, it becomes an output.241if (num_chaining_values > 2 * parents_array_len) {242memcpy(&out[parents_array_len * BLAKE3_OUT_LEN],243&child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN],244BLAKE3_OUT_LEN);245return parents_array_len + 1;246} else {247return parents_array_len;248}249}250251// The wide helper function returns (writes out) an array of chaining values252// and returns the length of that array. The number of chaining values returned253// is the dyanmically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,254// if the input is shorter than that many chunks. The reason for maintaining a255// wide array of chaining values going back up the tree, is to allow the256// implementation to hash as many parents in parallel as possible.257//258// As a special case when the SIMD degree is 1, this function will still return259// at least 2 outputs. This guarantees that this function doesn't perform the260// root compression. (If it did, it would use the wrong flags, and also we261// wouldn't be able to implement exendable ouput.) Note that this function is262// not used when the whole input is only 1 chunk long; that's a different263// codepath.264//265// Why not just have the caller split the input on the first update(), instead266// of implementing this special rule? Because we don't want to limit SIMD or267// multi-threading parallelism for that update().268static size_t blake3_compress_subtree_wide(const uint8_t *input,269size_t input_len,270const uint32_t key[8],271uint64_t chunk_counter,272uint8_t flags, uint8_t *out) {273// Note that the single chunk case does *not* bump the SIMD degree up to 2274// when it is 1. If this implementation adds multi-threading in the future,275// this gives us the option of multi-threading even the 2-chunk case, which276// can help performance on smaller platforms.277if (input_len <= blake3_simd_degree() * BLAKE3_CHUNK_LEN) {278return compress_chunks_parallel(input, input_len, key, chunk_counter, flags,279out);280}281282// With more than simd_degree chunks, we need to recurse. Start by dividing283// the input into left and right subtrees. (Note that this is only optimal284// as long as the SIMD degree is a power of 2. If we ever get a SIMD degree285// of 3 or something, we'll need a more complicated strategy.)286size_t left_input_len = left_len(input_len);287size_t right_input_len = input_len - left_input_len;288const uint8_t *right_input = &input[left_input_len];289uint64_t right_chunk_counter =290chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);291292// Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to293// account for the special case of returning 2 outputs when the SIMD degree294// is 1.295uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];296size_t degree = blake3_simd_degree();297if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {298// The special case: We always use a degree of at least two, to make299// sure there are two outputs. Except, as noted above, at the chunk300// level, where we allow degree=1. (Note that the 1-chunk-input case is301// a different codepath.)302degree = 2;303}304uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];305306// Recurse! If this implementation adds multi-threading support in the307// future, this is where it will go.308size_t left_n = blake3_compress_subtree_wide(input, left_input_len, key,309chunk_counter, flags, cv_array);310size_t right_n = blake3_compress_subtree_wide(311right_input, right_input_len, key, right_chunk_counter, flags, right_cvs);312313// The special case again. If simd_degree=1, then we'll have left_n=1 and314// right_n=1. Rather than compressing them into a single output, return315// them directly, to make sure we always have at least two outputs.316if (left_n == 1) {317memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);318return 2;319}320321// Otherwise, do one layer of parent node compression.322size_t num_chaining_values = left_n + right_n;323return compress_parents_parallel(cv_array, num_chaining_values, key, flags,324out);325}326327// Hash a subtree with compress_subtree_wide(), and then condense the resulting328// list of chaining values down to a single parent node. Don't compress that329// last parent node, however. Instead, return its message bytes (the330// concatenated chaining values of its children). This is necessary when the331// first call to update() supplies a complete subtree, because the topmost332// parent node of that subtree could end up being the root. It's also necessary333// for extended output in the general case.334//335// As with compress_subtree_wide(), this function is not used on inputs of 1336// chunk or less. That's a different codepath.337INLINE void compress_subtree_to_parent_node(338const uint8_t *input, size_t input_len, const uint32_t key[8],339uint64_t chunk_counter, uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN]) {340#if defined(BLAKE3_TESTING)341assert(input_len > BLAKE3_CHUNK_LEN);342#endif343344uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];345size_t num_cvs = blake3_compress_subtree_wide(input, input_len, key,346chunk_counter, flags, cv_array);347assert(num_cvs <= MAX_SIMD_DEGREE_OR_2);348349// If MAX_SIMD_DEGREE is greater than 2 and there's enough input,350// compress_subtree_wide() returns more than 2 chaining values. Condense351// them into 2 by forming parent nodes repeatedly.352uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2];353// The second half of this loop condition is always true, and we just354// asserted it above. But GCC can't tell that it's always true, and if NDEBUG355// is set on platforms where MAX_SIMD_DEGREE_OR_2 == 2, GCC emits spurious356// warnings here. GCC 8.5 is particularly sensitive, so if you're changing357// this code, test it against that version.358while (num_cvs > 2 && num_cvs <= MAX_SIMD_DEGREE_OR_2) {359num_cvs =360compress_parents_parallel(cv_array, num_cvs, key, flags, out_array);361memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN);362}363memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);364}365366INLINE void hasher_init_base(blake3_hasher *self, const uint32_t key[8],367uint8_t flags) {368memcpy(self->key, key, BLAKE3_KEY_LEN);369chunk_state_init(&self->chunk, key, flags);370self->cv_stack_len = 0;371}372373void llvm_blake3_hasher_init(blake3_hasher *self) { hasher_init_base(self, IV, 0); }374375void llvm_blake3_hasher_init_keyed(blake3_hasher *self,376const uint8_t key[BLAKE3_KEY_LEN]) {377uint32_t key_words[8];378load_key_words(key, key_words);379hasher_init_base(self, key_words, KEYED_HASH);380}381382void llvm_blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context,383size_t context_len) {384blake3_hasher context_hasher;385hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT);386llvm_blake3_hasher_update(&context_hasher, context, context_len);387uint8_t context_key[BLAKE3_KEY_LEN];388llvm_blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN);389uint32_t context_key_words[8];390load_key_words(context_key, context_key_words);391hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL);392}393394void llvm_blake3_hasher_init_derive_key(blake3_hasher *self, const char *context) {395llvm_blake3_hasher_init_derive_key_raw(self, context, strlen(context));396}397398// As described in hasher_push_cv() below, we do "lazy merging", delaying399// merges until right before the next CV is about to be added. This is400// different from the reference implementation. Another difference is that we401// aren't always merging 1 chunk at a time. Instead, each CV might represent402// any power-of-two number of chunks, as long as the smaller-above-larger stack403// order is maintained. Instead of the "count the trailing 0-bits" algorithm404// described in the spec, we use a "count the total number of 1-bits" variant405// that doesn't require us to retain the subtree size of the CV on top of the406// stack. The principle is the same: each CV that should remain in the stack is407// represented by a 1-bit in the total number of chunks (or bytes) so far.408INLINE void hasher_merge_cv_stack(blake3_hasher *self, uint64_t total_len) {409size_t post_merge_stack_len = (size_t)popcnt(total_len);410while (self->cv_stack_len > post_merge_stack_len) {411uint8_t *parent_node =412&self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN];413output_t output = parent_output(parent_node, self->key, self->chunk.flags);414output_chaining_value(&output, parent_node);415self->cv_stack_len -= 1;416}417}418419// In reference_impl.rs, we merge the new CV with existing CVs from the stack420// before pushing it. We can do that because we know more input is coming, so421// we know none of the merges are root.422//423// This setting is different. We want to feed as much input as possible to424// compress_subtree_wide(), without setting aside anything for the chunk_state.425// If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once426// as a single subtree, if at all possible.427//428// This leads to two problems:429// 1) This 64 KiB input might be the only call that ever gets made to update.430// In this case, the root node of the 64 KiB subtree would be the root node431// of the whole tree, and it would need to be ROOT finalized. We can't432// compress it until we know.433// 2) This 64 KiB input might complete a larger tree, whose root node is434// similarly going to be the the root of the whole tree. For example, maybe435// we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the436// node at the root of the 256 KiB subtree until we know how to finalize it.437//438// The second problem is solved with "lazy merging". That is, when we're about439// to add a CV to the stack, we don't merge it with anything first, as the440// reference impl does. Instead we do merges using the *previous* CV that was441// added, which is sitting on top of the stack, and we put the new CV442// (unmerged) on top of the stack afterwards. This guarantees that we never443// merge the root node until finalize().444//445// Solving the first problem requires an additional tool,446// compress_subtree_to_parent_node(). That function always returns the top447// *two* chaining values of the subtree it's compressing. We then do lazy448// merging with each of them separately, so that the second CV will always449// remain unmerged. (That also helps us support extendable output when we're450// hashing an input all-at-once.)451INLINE void hasher_push_cv(blake3_hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN],452uint64_t chunk_counter) {453hasher_merge_cv_stack(self, chunk_counter);454memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv,455BLAKE3_OUT_LEN);456self->cv_stack_len += 1;457}458459void llvm_blake3_hasher_update(blake3_hasher *self, const void *input,460size_t input_len) {461// Explicitly checking for zero avoids causing UB by passing a null pointer462// to memcpy. This comes up in practice with things like:463// std::vector<uint8_t> v;464// blake3_hasher_update(&hasher, v.data(), v.size());465if (input_len == 0) {466return;467}468469const uint8_t *input_bytes = (const uint8_t *)input;470471// If we have some partial chunk bytes in the internal chunk_state, we need472// to finish that chunk first.473if (chunk_state_len(&self->chunk) > 0) {474size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk);475if (take > input_len) {476take = input_len;477}478chunk_state_update(&self->chunk, input_bytes, take);479input_bytes += take;480input_len -= take;481// If we've filled the current chunk and there's more coming, finalize this482// chunk and proceed. In this case we know it's not the root.483if (input_len > 0) {484output_t output = chunk_state_output(&self->chunk);485uint8_t chunk_cv[32];486output_chaining_value(&output, chunk_cv);487hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter);488chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1);489} else {490return;491}492}493494// Now the chunk_state is clear, and we have more input. If there's more than495// a single chunk (so, definitely not the root chunk), hash the largest whole496// subtree we can, with the full benefits of SIMD (and maybe in the future,497// multi-threading) parallelism. Two restrictions:498// - The subtree has to be a power-of-2 number of chunks. Only subtrees along499// the right edge can be incomplete, and we don't know where the right edge500// is going to be until we get to finalize().501// - The subtree must evenly divide the total number of chunks up until this502// point (if total is not 0). If the current incomplete subtree is only503// waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have504// to complete the current subtree first.505// Because we might need to break up the input to form powers of 2, or to506// evenly divide what we already have, this part runs in a loop.507while (input_len > BLAKE3_CHUNK_LEN) {508size_t subtree_len = round_down_to_power_of_2(input_len);509uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN;510// Shrink the subtree_len until it evenly divides the count so far. We know511// that subtree_len itself is a power of 2, so we can use a bitmasking512// trick instead of an actual remainder operation. (Note that if the caller513// consistently passes power-of-2 inputs of the same size, as is hopefully514// typical, this loop condition will always fail, and subtree_len will515// always be the full length of the input.)516//517// An aside: We don't have to shrink subtree_len quite this much. For518// example, if count_so_far is 1, we could pass 2 chunks to519// compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still520// get the right answer in the end, and we might get to use 2-way SIMD521// parallelism. The problem with this optimization, is that it gets us522// stuck always hashing 2 chunks. The total number of chunks will remain523// odd, and we'll never graduate to higher degrees of parallelism. See524// https://github.com/BLAKE3-team/BLAKE3/issues/69.525while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {526subtree_len /= 2;527}528// The shrunken subtree_len might now be 1 chunk long. If so, hash that one529// chunk by itself. Otherwise, compress the subtree into a pair of CVs.530uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;531if (subtree_len <= BLAKE3_CHUNK_LEN) {532blake3_chunk_state chunk_state;533chunk_state_init(&chunk_state, self->key, self->chunk.flags);534chunk_state.chunk_counter = self->chunk.chunk_counter;535chunk_state_update(&chunk_state, input_bytes, subtree_len);536output_t output = chunk_state_output(&chunk_state);537uint8_t cv[BLAKE3_OUT_LEN];538output_chaining_value(&output, cv);539hasher_push_cv(self, cv, chunk_state.chunk_counter);540} else {541// This is the high-performance happy path, though getting here depends542// on the caller giving us a long enough input.543uint8_t cv_pair[2 * BLAKE3_OUT_LEN];544compress_subtree_to_parent_node(input_bytes, subtree_len, self->key,545self->chunk.chunk_counter,546self->chunk.flags, cv_pair);547hasher_push_cv(self, cv_pair, self->chunk.chunk_counter);548hasher_push_cv(self, &cv_pair[BLAKE3_OUT_LEN],549self->chunk.chunk_counter + (subtree_chunks / 2));550}551self->chunk.chunk_counter += subtree_chunks;552input_bytes += subtree_len;553input_len -= subtree_len;554}555556// If there's any remaining input less than a full chunk, add it to the chunk557// state. In that case, also do a final merge loop to make sure the subtree558// stack doesn't contain any unmerged pairs. The remaining input means we559// know these merges are non-root. This merge loop isn't strictly necessary560// here, because hasher_push_chunk_cv already does its own merge loop, but it561// simplifies blake3_hasher_finalize below.562if (input_len > 0) {563chunk_state_update(&self->chunk, input_bytes, input_len);564hasher_merge_cv_stack(self, self->chunk.chunk_counter);565}566}567568void llvm_blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out,569size_t out_len) {570llvm_blake3_hasher_finalize_seek(self, 0, out, out_len);571#if LLVM_MEMORY_SANITIZER_BUILD572// Avoid false positives due to uninstrumented assembly code.573__msan_unpoison(out, out_len);574#endif575}576577void llvm_blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek,578uint8_t *out, size_t out_len) {579// Explicitly checking for zero avoids causing UB by passing a null pointer580// to memcpy. This comes up in practice with things like:581// std::vector<uint8_t> v;582// blake3_hasher_finalize(&hasher, v.data(), v.size());583if (out_len == 0) {584return;585}586587// If the subtree stack is empty, then the current chunk is the root.588if (self->cv_stack_len == 0) {589output_t output = chunk_state_output(&self->chunk);590output_root_bytes(&output, seek, out, out_len);591return;592}593// If there are any bytes in the chunk state, finalize that chunk and do a594// roll-up merge between that chunk hash and every subtree in the stack. In595// this case, the extra merge loop at the end of blake3_hasher_update596// guarantees that none of the subtrees in the stack need to be merged with597// each other first. Otherwise, if there are no bytes in the chunk state,598// then the top of the stack is a chunk hash, and we start the merge from599// that.600output_t output;601size_t cvs_remaining;602if (chunk_state_len(&self->chunk) > 0) {603cvs_remaining = self->cv_stack_len;604output = chunk_state_output(&self->chunk);605} else {606// There are always at least 2 CVs in the stack in this case.607cvs_remaining = self->cv_stack_len - 2;608output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key,609self->chunk.flags);610}611while (cvs_remaining > 0) {612cvs_remaining -= 1;613uint8_t parent_block[BLAKE3_BLOCK_LEN];614memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32);615output_chaining_value(&output, &parent_block[32]);616output = parent_output(parent_block, self->key, self->chunk.flags);617}618output_root_bytes(&output, seek, out, out_len);619}620621void llvm_blake3_hasher_reset(blake3_hasher *self) {622chunk_state_reset(&self->chunk, self->key, 0);623self->cv_stack_len = 0;624}625626627