Path: blob/main/sys/contrib/openzfs/module/icp/algs/blake3/blake3.c
48674 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/2122/*23* Based on BLAKE3 v1.3.1, https://github.com/BLAKE3-team/BLAKE324* Copyright (c) 2019-2020 Samuel Neves and Jack O'Connor25* Copyright (c) 2021-2022 Tino Reichardt <[email protected]>26*/2728#include <sys/simd.h>29#include <sys/zfs_context.h>30#include <sys/blake3.h>3132#include "blake3_impl.h"3334/*35* We need 1056 byte stack for blake3_compress_subtree_wide()36* - we define this pragma to make gcc happy37*/38#if defined(__GNUC__)39#pragma GCC diagnostic ignored "-Wframe-larger-than="40#endif4142/* internal used */43typedef struct {44uint32_t input_cv[8];45uint64_t counter;46uint8_t block[BLAKE3_BLOCK_LEN];47uint8_t block_len;48uint8_t flags;49} output_t;5051/* internal flags */52enum blake3_flags {53CHUNK_START = 1 << 0,54CHUNK_END = 1 << 1,55PARENT = 1 << 2,56ROOT = 1 << 3,57KEYED_HASH = 1 << 4,58DERIVE_KEY_CONTEXT = 1 << 5,59DERIVE_KEY_MATERIAL = 1 << 6,60};6162/* internal start */63static void chunk_state_init(blake3_chunk_state_t *ctx,64const uint32_t key[8], uint8_t flags)65{66memcpy(ctx->cv, key, BLAKE3_KEY_LEN);67ctx->chunk_counter = 0;68memset(ctx->buf, 0, BLAKE3_BLOCK_LEN);69ctx->buf_len = 0;70ctx->blocks_compressed = 0;71ctx->flags = flags;72}7374static void chunk_state_reset(blake3_chunk_state_t *ctx,75const uint32_t key[8], uint64_t chunk_counter)76{77memcpy(ctx->cv, key, BLAKE3_KEY_LEN);78ctx->chunk_counter = chunk_counter;79ctx->blocks_compressed = 0;80memset(ctx->buf, 0, BLAKE3_BLOCK_LEN);81ctx->buf_len = 0;82}8384static size_t chunk_state_len(const blake3_chunk_state_t *ctx)85{86return (BLAKE3_BLOCK_LEN * (size_t)ctx->blocks_compressed) +87((size_t)ctx->buf_len);88}8990static size_t chunk_state_fill_buf(blake3_chunk_state_t *ctx,91const uint8_t *input, size_t input_len)92{93size_t take = BLAKE3_BLOCK_LEN - ((size_t)ctx->buf_len);94if (take > input_len) {95take = input_len;96}97uint8_t *dest = ctx->buf + ((size_t)ctx->buf_len);98memcpy(dest, input, take);99ctx->buf_len += (uint8_t)take;100return (take);101}102103static uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state_t *ctx)104{105if (ctx->blocks_compressed == 0) {106return (CHUNK_START);107} else {108return (0);109}110}111112static output_t make_output(const uint32_t input_cv[8],113const uint8_t *block, uint8_t block_len,114uint64_t counter, uint8_t flags)115{116output_t ret;117memcpy(ret.input_cv, input_cv, 32);118memcpy(ret.block, block, BLAKE3_BLOCK_LEN);119ret.block_len = block_len;120ret.counter = counter;121ret.flags = flags;122return (ret);123}124125/*126* Chaining values within a given chunk (specifically the compress_in_place127* interface) are represented as words. This avoids unnecessary bytes<->words128* conversion overhead in the portable implementation. However, the hash_many129* interface handles both user input and parent node blocks, so it accepts130* bytes. For that reason, chaining values in the CV stack are represented as131* bytes.132*/133static void output_chaining_value(const blake3_ops_t *ops,134const output_t *ctx, uint8_t cv[32])135{136uint32_t cv_words[8];137memcpy(cv_words, ctx->input_cv, 32);138ops->compress_in_place(cv_words, ctx->block, ctx->block_len,139ctx->counter, ctx->flags);140store_cv_words(cv, cv_words);141}142143static void output_root_bytes(const blake3_ops_t *ops, const output_t *ctx,144uint64_t seek, uint8_t *out, size_t out_len)145{146uint64_t output_block_counter = seek / 64;147size_t offset_within_block = seek % 64;148uint8_t wide_buf[64];149while (out_len > 0) {150ops->compress_xof(ctx->input_cv, ctx->block, ctx->block_len,151output_block_counter, ctx->flags | ROOT, wide_buf);152size_t available_bytes = 64 - offset_within_block;153size_t memcpy_len;154if (out_len > available_bytes) {155memcpy_len = available_bytes;156} else {157memcpy_len = out_len;158}159memcpy(out, wide_buf + offset_within_block, memcpy_len);160out += memcpy_len;161out_len -= memcpy_len;162output_block_counter += 1;163offset_within_block = 0;164}165}166167static void chunk_state_update(const blake3_ops_t *ops,168blake3_chunk_state_t *ctx, const uint8_t *input, size_t input_len)169{170if (ctx->buf_len > 0) {171size_t take = chunk_state_fill_buf(ctx, input, input_len);172input += take;173input_len -= take;174if (input_len > 0) {175ops->compress_in_place(ctx->cv, ctx->buf,176BLAKE3_BLOCK_LEN, ctx->chunk_counter,177ctx->flags|chunk_state_maybe_start_flag(ctx));178ctx->blocks_compressed += 1;179ctx->buf_len = 0;180memset(ctx->buf, 0, BLAKE3_BLOCK_LEN);181}182}183184while (input_len > BLAKE3_BLOCK_LEN) {185ops->compress_in_place(ctx->cv, input, BLAKE3_BLOCK_LEN,186ctx->chunk_counter,187ctx->flags|chunk_state_maybe_start_flag(ctx));188ctx->blocks_compressed += 1;189input += BLAKE3_BLOCK_LEN;190input_len -= BLAKE3_BLOCK_LEN;191}192193chunk_state_fill_buf(ctx, input, input_len);194}195196static output_t chunk_state_output(const blake3_chunk_state_t *ctx)197{198uint8_t block_flags =199ctx->flags | chunk_state_maybe_start_flag(ctx) | CHUNK_END;200return (make_output(ctx->cv, ctx->buf, ctx->buf_len, ctx->chunk_counter,201block_flags));202}203204static output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],205const uint32_t key[8], uint8_t flags)206{207return (make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT));208}209210/*211* Given some input larger than one chunk, return the number of bytes that212* should go in the left subtree. This is the largest power-of-2 number of213* chunks that leaves at least 1 byte for the right subtree.214*/215static size_t left_len(size_t content_len)216{217/*218* Subtract 1 to reserve at least one byte for the right side.219* content_len220* should always be greater than BLAKE3_CHUNK_LEN.221*/222size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN;223return (round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN);224}225226/*227* Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time228* on a single thread. Write out the chunk chaining values and return the229* number of chunks hashed. These chunks are never the root and never empty;230* those cases use a different codepath.231*/232static size_t compress_chunks_parallel(const blake3_ops_t *ops,233const uint8_t *input, size_t input_len, const uint32_t key[8],234uint64_t chunk_counter, uint8_t flags, uint8_t *out)235{236const uint8_t *chunks_array[MAX_SIMD_DEGREE];237size_t input_position = 0;238size_t chunks_array_len = 0;239while (input_len - input_position >= BLAKE3_CHUNK_LEN) {240chunks_array[chunks_array_len] = &input[input_position];241input_position += BLAKE3_CHUNK_LEN;242chunks_array_len += 1;243}244245ops->hash_many(chunks_array, chunks_array_len, BLAKE3_CHUNK_LEN /246BLAKE3_BLOCK_LEN, key, chunk_counter, B_TRUE, flags, CHUNK_START,247CHUNK_END, out);248249/*250* Hash the remaining partial chunk, if there is one. Note that the251* empty chunk (meaning the empty message) is a different codepath.252*/253if (input_len > input_position) {254uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;255blake3_chunk_state_t chunk_state;256chunk_state_init(&chunk_state, key, flags);257chunk_state.chunk_counter = counter;258chunk_state_update(ops, &chunk_state, &input[input_position],259input_len - input_position);260output_t output = chunk_state_output(&chunk_state);261output_chaining_value(ops, &output, &out[chunks_array_len *262BLAKE3_OUT_LEN]);263return (chunks_array_len + 1);264} else {265return (chunks_array_len);266}267}268269/*270* Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time271* on a single thread. Write out the parent chaining values and return the272* number of parents hashed. (If there's an odd input chaining value left over,273* return it as an additional output.) These parents are never the root and274* never empty; those cases use a different codepath.275*/276static size_t compress_parents_parallel(const blake3_ops_t *ops,277const uint8_t *child_chaining_values, size_t num_chaining_values,278const uint32_t key[8], uint8_t flags, uint8_t *out)279{280const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2] = {0};281size_t parents_array_len = 0;282283while (num_chaining_values - (2 * parents_array_len) >= 2) {284parents_array[parents_array_len] = &child_chaining_values[2 *285parents_array_len * BLAKE3_OUT_LEN];286parents_array_len += 1;287}288289ops->hash_many(parents_array, parents_array_len, 1, key, 0, B_FALSE,290flags | PARENT, 0, 0, out);291292/* If there's an odd child left over, it becomes an output. */293if (num_chaining_values > 2 * parents_array_len) {294memcpy(&out[parents_array_len * BLAKE3_OUT_LEN],295&child_chaining_values[2 * parents_array_len *296BLAKE3_OUT_LEN], BLAKE3_OUT_LEN);297return (parents_array_len + 1);298} else {299return (parents_array_len);300}301}302303/*304* The wide helper function returns (writes out) an array of chaining values305* and returns the length of that array. The number of chaining values returned306* is the dyanmically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,307* if the input is shorter than that many chunks. The reason for maintaining a308* wide array of chaining values going back up the tree, is to allow the309* implementation to hash as many parents in parallel as possible.310*311* As a special case when the SIMD degree is 1, this function will still return312* at least 2 outputs. This guarantees that this function doesn't perform the313* root compression. (If it did, it would use the wrong flags, and also we314* wouldn't be able to implement exendable ouput.) Note that this function is315* not used when the whole input is only 1 chunk long; that's a different316* codepath.317*318* Why not just have the caller split the input on the first update(), instead319* of implementing this special rule? Because we don't want to limit SIMD or320* multi-threading parallelism for that update().321*/322static size_t blake3_compress_subtree_wide(const blake3_ops_t *ops,323const uint8_t *input, size_t input_len, const uint32_t key[8],324uint64_t chunk_counter, uint8_t flags, uint8_t *out)325{326/*327* Note that the single chunk case does *not* bump the SIMD degree up328* to 2 when it is 1. If this implementation adds multi-threading in329* the future, this gives us the option of multi-threading even the330* 2-chunk case, which can help performance on smaller platforms.331*/332if (input_len <= (size_t)(ops->degree * BLAKE3_CHUNK_LEN)) {333return (compress_chunks_parallel(ops, input, input_len, key,334chunk_counter, flags, out));335}336337338/*339* With more than simd_degree chunks, we need to recurse. Start by340* dividing the input into left and right subtrees. (Note that this is341* only optimal as long as the SIMD degree is a power of 2. If we ever342* get a SIMD degree of 3 or something, we'll need a more complicated343* strategy.)344*/345size_t left_input_len = left_len(input_len);346size_t right_input_len = input_len - left_input_len;347const uint8_t *right_input = &input[left_input_len];348uint64_t right_chunk_counter = chunk_counter +349(uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);350351/*352* Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2353* to account for the special case of returning 2 outputs when the354* SIMD degree is 1.355*/356uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];357size_t degree = ops->degree;358if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {359360/*361* The special case: We always use a degree of at least two,362* to make sure there are two outputs. Except, as noted above,363* at the chunk level, where we allow degree=1. (Note that the364* 1-chunk-input case is a different codepath.)365*/366degree = 2;367}368uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];369370/*371* Recurse! If this implementation adds multi-threading support in the372* future, this is where it will go.373*/374size_t left_n = blake3_compress_subtree_wide(ops, input, left_input_len,375key, chunk_counter, flags, cv_array);376size_t right_n = blake3_compress_subtree_wide(ops, right_input,377right_input_len, key, right_chunk_counter, flags, right_cvs);378379/*380* The special case again. If simd_degree=1, then we'll have left_n=1381* and right_n=1. Rather than compressing them into a single output,382* return them directly, to make sure we always have at least two383* outputs.384*/385if (left_n == 1) {386memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);387return (2);388}389390/* Otherwise, do one layer of parent node compression. */391size_t num_chaining_values = left_n + right_n;392return compress_parents_parallel(ops, cv_array,393num_chaining_values, key, flags, out);394}395396/*397* Hash a subtree with compress_subtree_wide(), and then condense the resulting398* list of chaining values down to a single parent node. Don't compress that399* last parent node, however. Instead, return its message bytes (the400* concatenated chaining values of its children). This is necessary when the401* first call to update() supplies a complete subtree, because the topmost402* parent node of that subtree could end up being the root. It's also necessary403* for extended output in the general case.404*405* As with compress_subtree_wide(), this function is not used on inputs of 1406* chunk or less. That's a different codepath.407*/408static void compress_subtree_to_parent_node(const blake3_ops_t *ops,409const uint8_t *input, size_t input_len, const uint32_t key[8],410uint64_t chunk_counter, uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN])411{412uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];413size_t num_cvs = blake3_compress_subtree_wide(ops, input, input_len,414key, chunk_counter, flags, cv_array);415416/*417* If MAX_SIMD_DEGREE is greater than 2 and there's enough input,418* compress_subtree_wide() returns more than 2 chaining values. Condense419* them into 2 by forming parent nodes repeatedly.420*/421uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2];422while (num_cvs > 2) {423num_cvs = compress_parents_parallel(ops, cv_array, num_cvs, key,424flags, out_array);425memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN);426}427memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);428}429430static void hasher_init_base(BLAKE3_CTX *ctx, const uint32_t key[8],431uint8_t flags)432{433memcpy(ctx->key, key, BLAKE3_KEY_LEN);434chunk_state_init(&ctx->chunk, key, flags);435ctx->cv_stack_len = 0;436ctx->ops = blake3_get_ops();437}438439/*440* As described in hasher_push_cv() below, we do "lazy merging", delaying441* merges until right before the next CV is about to be added. This is442* different from the reference implementation. Another difference is that we443* aren't always merging 1 chunk at a time. Instead, each CV might represent444* any power-of-two number of chunks, as long as the smaller-above-larger445* stack order is maintained. Instead of the "count the trailing 0-bits"446* algorithm described in the spec, we use a "count the total number of447* 1-bits" variant that doesn't require us to retain the subtree size of the448* CV on top of the stack. The principle is the same: each CV that should449* remain in the stack is represented by a 1-bit in the total number of chunks450* (or bytes) so far.451*/452static void hasher_merge_cv_stack(BLAKE3_CTX *ctx, uint64_t total_len)453{454size_t post_merge_stack_len = (size_t)popcnt(total_len);455while (ctx->cv_stack_len > post_merge_stack_len) {456uint8_t *parent_node =457&ctx->cv_stack[(ctx->cv_stack_len - 2) * BLAKE3_OUT_LEN];458output_t output =459parent_output(parent_node, ctx->key, ctx->chunk.flags);460output_chaining_value(ctx->ops, &output, parent_node);461ctx->cv_stack_len -= 1;462}463}464465/*466* In reference_impl.rs, we merge the new CV with existing CVs from the stack467* before pushing it. We can do that because we know more input is coming, so468* we know none of the merges are root.469*470* This setting is different. We want to feed as much input as possible to471* compress_subtree_wide(), without setting aside anything for the chunk_state.472* If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once473* as a single subtree, if at all possible.474*475* This leads to two problems:476* 1) This 64 KiB input might be the only call that ever gets made to update.477* In this case, the root node of the 64 KiB subtree would be the root node478* of the whole tree, and it would need to be ROOT finalized. We can't479* compress it until we know.480* 2) This 64 KiB input might complete a larger tree, whose root node is481* similarly going to be the the root of the whole tree. For example, maybe482* we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the483* node at the root of the 256 KiB subtree until we know how to finalize it.484*485* The second problem is solved with "lazy merging". That is, when we're about486* to add a CV to the stack, we don't merge it with anything first, as the487* reference impl does. Instead we do merges using the *previous* CV that was488* added, which is sitting on top of the stack, and we put the new CV489* (unmerged) on top of the stack afterwards. This guarantees that we never490* merge the root node until finalize().491*492* Solving the first problem requires an additional tool,493* compress_subtree_to_parent_node(). That function always returns the top494* *two* chaining values of the subtree it's compressing. We then do lazy495* merging with each of them separately, so that the second CV will always496* remain unmerged. (That also helps us support extendable output when we're497* hashing an input all-at-once.)498*/499static void hasher_push_cv(BLAKE3_CTX *ctx, uint8_t new_cv[BLAKE3_OUT_LEN],500uint64_t chunk_counter)501{502hasher_merge_cv_stack(ctx, chunk_counter);503memcpy(&ctx->cv_stack[ctx->cv_stack_len * BLAKE3_OUT_LEN], new_cv,504BLAKE3_OUT_LEN);505ctx->cv_stack_len += 1;506}507508void509Blake3_Init(BLAKE3_CTX *ctx)510{511hasher_init_base(ctx, BLAKE3_IV, 0);512}513514void515Blake3_InitKeyed(BLAKE3_CTX *ctx, const uint8_t key[BLAKE3_KEY_LEN])516{517uint32_t key_words[8];518load_key_words(key, key_words);519hasher_init_base(ctx, key_words, KEYED_HASH);520}521522static void523Blake3_Update2(BLAKE3_CTX *ctx, const void *input, size_t input_len)524{525/*526* Explicitly checking for zero avoids causing UB by passing a null527* pointer to memcpy. This comes up in practice with things like:528* std::vector<uint8_t> v;529* blake3_hasher_update(&hasher, v.data(), v.size());530*/531if (input_len == 0) {532return;533}534535const uint8_t *input_bytes = (const uint8_t *)input;536537/*538* If we have some partial chunk bytes in the internal chunk_state, we539* need to finish that chunk first.540*/541if (chunk_state_len(&ctx->chunk) > 0) {542size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&ctx->chunk);543if (take > input_len) {544take = input_len;545}546chunk_state_update(ctx->ops, &ctx->chunk, input_bytes, take);547input_bytes += take;548input_len -= take;549/*550* If we've filled the current chunk and there's more coming,551* finalize this chunk and proceed. In this case we know it's552* not the root.553*/554if (input_len > 0) {555output_t output = chunk_state_output(&ctx->chunk);556uint8_t chunk_cv[32];557output_chaining_value(ctx->ops, &output, chunk_cv);558hasher_push_cv(ctx, chunk_cv, ctx->chunk.chunk_counter);559chunk_state_reset(&ctx->chunk, ctx->key,560ctx->chunk.chunk_counter + 1);561} else {562return;563}564}565566/*567* Now the chunk_state is clear, and we have more input. If there's568* more than a single chunk (so, definitely not the root chunk), hash569* the largest whole subtree we can, with the full benefits of SIMD570* (and maybe in the future, multi-threading) parallelism. Two571* restrictions:572* - The subtree has to be a power-of-2 number of chunks. Only573* subtrees along the right edge can be incomplete, and we don't know574* where the right edge is going to be until we get to finalize().575* - The subtree must evenly divide the total number of chunks up576* until this point (if total is not 0). If the current incomplete577* subtree is only waiting for 1 more chunk, we can't hash a subtree578* of 4 chunks. We have to complete the current subtree first.579* Because we might need to break up the input to form powers of 2, or580* to evenly divide what we already have, this part runs in a loop.581*/582while (input_len > BLAKE3_CHUNK_LEN) {583size_t subtree_len = round_down_to_power_of_2(input_len);584uint64_t count_so_far =585ctx->chunk.chunk_counter * BLAKE3_CHUNK_LEN;586/*587* Shrink the subtree_len until it evenly divides the count so588* far. We know that subtree_len itself is a power of 2, so we589* can use a bitmasking trick instead of an actual remainder590* operation. (Note that if the caller consistently passes591* power-of-2 inputs of the same size, as is hopefully592* typical, this loop condition will always fail, and593* subtree_len will always be the full length of the input.)594*595* An aside: We don't have to shrink subtree_len quite this596* much. For example, if count_so_far is 1, we could pass 2597* chunks to compress_subtree_to_parent_node. Since we'll get598* 2 CVs back, we'll still get the right answer in the end,599* and we might get to use 2-way SIMD parallelism. The problem600* with this optimization, is that it gets us stuck always601* hashing 2 chunks. The total number of chunks will remain602* odd, and we'll never graduate to higher degrees of603* parallelism. See604* https://github.com/BLAKE3-team/BLAKE3/issues/69.605*/606while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {607subtree_len /= 2;608}609/*610* The shrunken subtree_len might now be 1 chunk long. If so,611* hash that one chunk by itself. Otherwise, compress the612* subtree into a pair of CVs.613*/614uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;615if (subtree_len <= BLAKE3_CHUNK_LEN) {616blake3_chunk_state_t chunk_state;617chunk_state_init(&chunk_state, ctx->key,618ctx->chunk.flags);619chunk_state.chunk_counter = ctx->chunk.chunk_counter;620chunk_state_update(ctx->ops, &chunk_state, input_bytes,621subtree_len);622output_t output = chunk_state_output(&chunk_state);623uint8_t cv[BLAKE3_OUT_LEN];624output_chaining_value(ctx->ops, &output, cv);625hasher_push_cv(ctx, cv, chunk_state.chunk_counter);626} else {627/*628* This is the high-performance happy path, though629* getting here depends on the caller giving us a long630* enough input.631*/632uint8_t cv_pair[2 * BLAKE3_OUT_LEN];633compress_subtree_to_parent_node(ctx->ops, input_bytes,634subtree_len, ctx->key, ctx-> chunk.chunk_counter,635ctx->chunk.flags, cv_pair);636hasher_push_cv(ctx, cv_pair, ctx->chunk.chunk_counter);637hasher_push_cv(ctx, &cv_pair[BLAKE3_OUT_LEN],638ctx->chunk.chunk_counter + (subtree_chunks / 2));639}640ctx->chunk.chunk_counter += subtree_chunks;641input_bytes += subtree_len;642input_len -= subtree_len;643}644645/*646* If there's any remaining input less than a full chunk, add it to647* the chunk state. In that case, also do a final merge loop to make648* sure the subtree stack doesn't contain any unmerged pairs. The649* remaining input means we know these merges are non-root. This merge650* loop isn't strictly necessary here, because hasher_push_chunk_cv651* already does its own merge loop, but it simplifies652* blake3_hasher_finalize below.653*/654if (input_len > 0) {655chunk_state_update(ctx->ops, &ctx->chunk, input_bytes,656input_len);657hasher_merge_cv_stack(ctx, ctx->chunk.chunk_counter);658}659}660661void662Blake3_Update(BLAKE3_CTX *ctx, const void *input, size_t todo)663{664size_t done = 0;665const uint8_t *data = input;666const size_t block_max = 1024 * 64;667668/* max feed buffer to leave the stack size small */669while (todo != 0) {670size_t block = (todo >= block_max) ? block_max : todo;671Blake3_Update2(ctx, data + done, block);672done += block;673todo -= block;674}675}676677void678Blake3_Final(const BLAKE3_CTX *ctx, uint8_t *out)679{680Blake3_FinalSeek(ctx, 0, out, BLAKE3_OUT_LEN);681}682683void684Blake3_FinalSeek(const BLAKE3_CTX *ctx, uint64_t seek, uint8_t *out,685size_t out_len)686{687/*688* Explicitly checking for zero avoids causing UB by passing a null689* pointer to memcpy. This comes up in practice with things like:690* std::vector<uint8_t> v;691* blake3_hasher_finalize(&hasher, v.data(), v.size());692*/693if (out_len == 0) {694return;695}696/* If the subtree stack is empty, then the current chunk is the root. */697if (ctx->cv_stack_len == 0) {698output_t output = chunk_state_output(&ctx->chunk);699output_root_bytes(ctx->ops, &output, seek, out, out_len);700return;701}702/*703* If there are any bytes in the chunk state, finalize that chunk and704* do a roll-up merge between that chunk hash and every subtree in the705* stack. In this case, the extra merge loop at the end of706* blake3_hasher_update guarantees that none of the subtrees in the707* stack need to be merged with each other first. Otherwise, if there708* are no bytes in the chunk state, then the top of the stack is a709* chunk hash, and we start the merge from that.710*/711output_t output;712size_t cvs_remaining;713if (chunk_state_len(&ctx->chunk) > 0) {714cvs_remaining = ctx->cv_stack_len;715output = chunk_state_output(&ctx->chunk);716} else {717/* There are always at least 2 CVs in the stack in this case. */718cvs_remaining = ctx->cv_stack_len - 2;719output = parent_output(&ctx->cv_stack[cvs_remaining * 32],720ctx->key, ctx->chunk.flags);721}722while (cvs_remaining > 0) {723cvs_remaining -= 1;724uint8_t parent_block[BLAKE3_BLOCK_LEN];725memcpy(parent_block, &ctx->cv_stack[cvs_remaining * 32], 32);726output_chaining_value(ctx->ops, &output, &parent_block[32]);727output = parent_output(parent_block, ctx->key,728ctx->chunk.flags);729}730output_root_bytes(ctx->ops, &output, seek, out, out_len);731}732733734