Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
ff5b365
hash: detail::timing_guard sets arm64's DIT for its scope and restore…
Nov 22, 2026
1ff528f
hash: a disengaged detail::timing_guard fires no seam, and the seam s…
Nov 22, 2026
be454f1
hash: mac and the keyed modes of BLAKE2b and BLAKE3 set DIT around ea…
Nov 22, 2026
5cd3d25
hash: the labels of timing_keyed's BLAKE3 checks spell the overload t…
Nov 22, 2026
08245b0
hash: the key derivations and the password hashes set DIT around each…
Nov 22, 2026
37640c6
hash: the timing_keyed tests pass clang-tidy: constant keys, HKDF apa…
Nov 22, 2026
ebe18fa
hash: timing_keyed holds its destroyed keyed hasher in a unique_ptr, …
Nov 22, 2026
5e2e5d5
hash: a coverage test per backend, driven by the capability table, pr…
Nov 22, 2026
bc78c98
hash: the coverage tests state how a new cell gets its call, and each…
Nov 22, 2026
e9bab02
hash: a test proves the asynchronous forms set DIT on the thread that…
Nov 22, 2026
f6c3071
hash: the timing_async cancellation case waits on a promise for the h…
Nov 22, 2026
8b0f6d9
hash: the guard's cost measured in release and the pages say which fu…
Nov 22, 2026
0b0bfeb
hash: the DIT pages name the built platforms and synchronous backends…
Nov 22, 2026
2b66149
hash: timing_during observes DIT set while hkdf_extract, hkdf_expand,…
Nov 22, 2026
1323a0f
hash: the seam support's example names hash::hkdf_extract, the scope …
Nov 22, 2026
74d3fea
hash: blake3_test pins the documented sizes, 1,912 bytes of BLAKE3's …
Nov 22, 2026
b2d423c
hash: the coverage tests run every keyed cell again from a thread tha…
Nov 22, 2026
09015e0
hash: timing_async asserts async_bcrypt_verify's answer and checks he…
Nov 22, 2026
481b75b
hash: timing_botan_failure shows Botan throwing inside a guard answer…
Nov 22, 2026
5cbd7a9
hash: the MACs chapter and the DIT section name mac<macs::siphash_2_4…
Nov 22, 2026
e519946
hash: force_dit is defined once, in support/timing_dit.hpp, which car…
Nov 22, 2026
af15c40
hash: timing_async declares cheap only where it is called, outside th…
Nov 22, 2026
051336d
hash: the timing tests name their file-scope data test_key, test_salt…
Nov 22, 2026
8c10341
hash: async_heavy_test's cancellation race holds the pool's thread in…
Nov 22, 2026
8f6b7cc
hash: the timing tests' wrapped byte arrays end with a trailing comma…
Nov 22, 2026
b386ca7
hash: timing_async and timing_during build their byte arrays in a con…
Nov 22, 2026
58b4512
hash: a reference that includes hash reads only the backends its buil…
Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,13 @@ specific to hash.
decoding); a moved pin carries that commit. A moved pin is a change of its own (rule 12).
- A test is declared through `hash-run` in `test/Jamfile`, which runs it with exceptions and
without.
- Every function that computes on a key, a password or a key derivation's secret input holds
`detail::timing_guard` as its first statement (`timing{engaged}` where the arguments decide
whether the call is keyed); unkeyed digests and Boost.Hash2's types by alias hold none. A new
keyed function, or a keyed cell that `doc/capabilities.json` gains (a MAC, a key derivation, a
password hash, on any backend), holds the guard and gets its call in that backend's
`test/timing_coverage_<backend>_test.cpp`, which fails until it does. `detail/timing.hpp` is a
copy of webcpp::crypto's `detail/timing.hpp` (hash cannot depend on crypto): a change to one is
made to both, and crypto's `test/timing_hash_interop_test.cpp` runs the two together.
- `include/webcpp/hash/detail/canary.h` is a C header: it is in neither the headers-alone list nor
`meta/include-boundaries.json`.
15 changes: 14 additions & 1 deletion bench/Jamfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
# accompanying file LICENSE_1_0.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)

# The throughput of PBKDF2-HMAC-SHA-512 at 1,000,000 iterations (spec 4.3).
# The throughput of PBKDF2-HMAC-SHA-512 at 1,000,000 iterations (spec 4.3),
# and the cost of the timing guard (timing.cpp).
# pbkdf2_sha512_key is the correctness test of the measured program: each
# variant's derived key against an independent value, on every target, never
# failing on a time. The measurements themselves are made by collect.py, which
Expand Down Expand Up @@ -38,6 +39,18 @@ webcpp.run pbkdf2_sha512_key : pbkdf2_sha512.cpp : $(.requirements) ;
exe pbkdf2_sha512 : pbkdf2_sha512.cpp : $(.requirements) <variant>release ;
explicit pbkdf2_sha512 ;

# The cost of detail::timing_guard, the scope every keyed function runs in
# (doc/performance.adoc). timing_check is the correctness test of the measured
# program, run in every lane of test/: the measurement at 10^3 iterations, its
# line's form and the thread's DIT checked. It needs no backend:
# detail/timing.hpp alone.
webcpp.run timing_check : timing.cpp : <optimization>speed ;

# The same program at variant=release, the one collect.py --timing measures,
# natively and by hand (doc/performance.adoc); no lane measures it.
exe timing : timing.cpp : <variant>release <optimization>speed ;
explicit timing ;

# The allocation counts of doc/allocation.adoc (spec section 7.7), from release
# builds only: the programs of test/allocation_test.cpp,
# test/allocation_openssl_test.cpp and test/allocation_botan_test.cpp built at
Expand Down
291 changes: 273 additions & 18 deletions bench/collect.py

Large diffs are not rendered by default.

248 changes: 248 additions & 0 deletions bench/timing.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// Copyright (c) 2026 WebCpp.org
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)

// The cost of detail::timing_guard, the scope every keyed public function of hash runs in (a MAC,
// a key derivation, a password hash, a keyed mode of BLAKE2b or BLAKE3), which sets 64-bit ARM's
// DIT (data-independent timing) bit where the CPU has it and restores the thread's state after
// it. bench/timing.cpp of webcpp::crypto measures crypto's copy of the guard the same way.
//
// Run as `timing --measure`, it times, in one process, 10^7 iterations each of an empty loop body,
// of a guard entered from a thread whose DIT is clear (it sets DIT and clears it again), of a
// guard entered with DIT already set (it reads DIT and leaves it; the program sets DIT for that
// part with the same `msr` as the guard, and clears it after), and of a disengaged guard (what an
// unkeyed call of a function that is keyed by its arguments pays: the flag, read from memory as a
// member is, and a branch), five runs of each, interleaved, and prints one JSON line:
// `{"dit": true|false, "clear": <ns>, "set": <ns>, "disengaged": <ns>, ...}`, each cost the
// median of its runs minus the empty loop's median, in nanoseconds per guard, then each part's
// fastest and slowest run (minus the same median), the iterations, the runs, the target and the
// compiler. "dit" says whether the guard sets DIT here (a target it covers, on a CPU that has it);
// where it does not, the guard executes no instruction and the costs are the loop's noise. Both
// modes fail when the process starts with DIT set, or when the thread's DIT is not as the guard
// must leave it after a part. Run with no argument, it is the correctness test: the same
// measurement at 10^3 iterations, whose line must also have that form, and whose "dit" must be
// what the library reads. A measurement never fails on its time; bench/collect.py --timing runs
// it and writes doc/performance.adoc.

#include <webcpp/hash/detail/timing.hpp>

#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <span>
#include <string_view>

namespace detail = webcpp::hash::detail;

namespace {

#ifdef WEBCPP_TARGET_WASIP2
constexpr std::string_view target = "wasip2";
#elif defined(WEBCPP_TARGET_WASIP3)
constexpr std::string_view target = "wasip3";
#elif defined(WEBCPP_TARGET_EMSCRIPTEN)
constexpr std::string_view target = "emscripten";
#else
constexpr std::string_view target = "native";
#endif

// The compiler, as it names itself: MSVC defines no __VERSION__.
#ifdef __VERSION__
constexpr std::string_view compiler = __VERSION__;
#elif defined(_MSC_FULL_VER)
#define WEBCPP_HASH_BENCH_STRING(x) #x
#define WEBCPP_HASH_BENCH_VERSION(x) WEBCPP_HASH_BENCH_STRING(x)
constexpr std::string_view compiler = "MSVC " WEBCPP_HASH_BENCH_VERSION(_MSC_FULL_VER);
#else
constexpr std::string_view compiler = "unknown";
#endif

// The iterations of a measured run, and of the correctness test's.
constexpr std::uint64_t measured_iterations = 10'000'000;
constexpr std::uint64_t checked_iterations = 1'000;

// The runs of each part; their median is the part's time.
constexpr std::size_t runs = 5;

// Whether the guard sets DIT on this target and CPU.
bool guard_sets_dit() noexcept {
#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED
return detail::cpu_has_dit();
#else
return false;
#endif
}

// Sets or clears this thread's DIT where the guard would, as a program that asks for it does.
void force_dit([[maybe_unused]] bool set) noexcept {
#ifdef WEBCPP_HASH_DETAIL_TIMING_COVERED
if (detail::cpu_has_dit()) {
detail::write_dit(set ? detail::dit_bit : 0);
}
#endif
}

// The nanoseconds of one iteration of body, over iterations of it.
template <class Body>
double nanoseconds_per_iteration(std::uint64_t iterations, Body body) {
auto const start = std::chrono::steady_clock::now();
for (std::uint64_t i = 0; i < iterations; ++i) {
body(i);
}
std::chrono::duration<double, std::nano> const elapsed =
std::chrono::steady_clock::now() - start;
return elapsed.count() / static_cast<double>(iterations);
}

// A part's runs, each less the empty loop's median: their median, fastest and slowest.
struct summary {
double median = 0;
double fastest = 0;
double slowest = 0;
};

summary summarise(std::array<double, runs> values, double loop) {
std::ranges::sort(values);
return {
.median = values[runs / 2] - loop,
.fastest = values.front() - loop,
.slowest = values.back() - loop,
};
}

// What one measurement gives: the guard's three costs, and whether DIT was as the guard must leave
// it before and after each part.
struct result {
summary clear;
summary set;
summary disengaged;
bool restored = true;
};

result measure(std::uint64_t iterations) {
std::array<double, runs> empty{};
std::array<double, runs> clear{};
std::array<double, runs> set{};
std::array<double, runs> disengaged{};
// A process that starts with DIT set would measure the set part twice.
bool restored = !detail::dit_is_set();
// Written by every iteration of every part, so that no loop is removed or merged.
std::uint64_t volatile sink = 0;
// The disengaged guard's flag, read at each iteration as a keyed function reads its member.
bool volatile keyed = false;
for (std::size_t run = 0; run < runs; ++run) {
empty[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { sink = i; });
clear[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) {
detail::timing_guard const guard;
sink = i;
});
restored = restored && !detail::dit_is_set();
force_dit(true);
set[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) {
detail::timing_guard const guard;
sink = i;
});
restored = restored && detail::dit_is_set() == guard_sets_dit();
force_dit(false);
restored = restored && !detail::dit_is_set();
disengaged[run] = nanoseconds_per_iteration(iterations, [&sink, &keyed](std::uint64_t i) {
detail::timing_guard const guard{keyed};
sink = i;
});
restored = restored && !detail::dit_is_set();
}
double const loop = summarise(empty, 0).median;
return {
.clear = summarise(clear, loop),
.set = summarise(set, loop),
.disengaged = summarise(disengaged, loop),
.restored = restored,
};
}

// Writes the JSON line of a measurement into line; the number of characters, or -1.
int format(std::span<char> line, result const& measured, std::uint64_t iterations) {
return std::snprintf(
line.data(), line.size(),
R"({"dit": %s, "clear": %.3f, "set": %.3f, "disengaged": %.3f, "clear_fastest": %.3f, )"
R"("clear_slowest": %.3f, "set_fastest": %.3f, "set_slowest": %.3f, )"
R"("disengaged_fastest": %.3f, "disengaged_slowest": %.3f, )"
R"("iterations": %llu, "runs": %zu, "target": "%.*s", "compiler": "%.*s"})",
guard_sets_dit() ? "true" : "false", measured.clear.median, measured.set.median,
measured.disengaged.median, measured.clear.fastest, measured.clear.slowest,
measured.set.fastest, measured.set.slowest, measured.disengaged.fastest,
measured.disengaged.slowest, static_cast<unsigned long long>(iterations), runs,
static_cast<int>(target.size()), target.data(), static_cast<int>(compiler.size()),
compiler.data());
}

// Skips prefix at the start of text, or returns null when text does not start with it.
char const* skip(char const* text, std::string_view prefix) {
return text != nullptr && std::string_view(text).starts_with(prefix) ? text + prefix.size()
: nullptr;
}

// Reads a finite number at the start of text into value; what follows it, or null.
char const* number(char const* text, double& value) {
if (text == nullptr) {
return nullptr;
}
char* end = nullptr;
value = std::strtod(text, &end);
return end != text && std::isfinite(value) ? end : nullptr;
}

// Whether line opens with the form collect.py reads: "dit" as the library reads it, then the three
// costs as finite numbers.
bool well_formed(char const* line) {
double clear = 0;
double set = 0;
double disengaged = 0;
char const* rest =
skip(line, guard_sets_dit() ? R"({"dit": true, "clear": )" : R"({"dit": false, "clear": )");
rest = number(skip(number(rest, clear), R"(, "set": )"), set);
rest = number(skip(rest, R"(, "disengaged": )"), disengaged);
return skip(rest, R"(, "clear_fastest": )") != nullptr;
}

int usage() {
static_cast<void>(std::fprintf(stderr, "usage: timing [--measure]\n"));
return 2;
}

} // namespace

int main(int argument_count, char** arguments) {
std::span<char*> const given(arguments, static_cast<std::size_t>(argument_count));
bool const measuring = given.size() == 2 && std::string_view(given[1]) == "--measure";
if (given.size() != 1 && !measuring) {
return usage();
}
std::uint64_t const iterations = measuring ? measured_iterations : checked_iterations;
result const measured = measure(iterations);
std::array<char, 1024> line{};
int const written = format(line, measured, iterations);
if (written < 0 || static_cast<std::size_t>(written) >= line.size()) {
static_cast<void>(std::fprintf(stderr, "timing: the line does not fit\n"));
return 1;
}
std::printf("%s\n", line.data());
if (!measured.restored) {
static_cast<void>(std::fprintf(
stderr, "timing: the thread's DIT was set at the start or not restored by a guard\n"));
}
if (measuring) {
return measured.restored ? 0 : 1;
}
bool const formed = well_formed(line.data());
std::printf("form %s\nstate restored %s\n", formed ? "ok" : "FAILED",
measured.restored ? "ok" : "FAILED");
return formed && measured.restored ? 0 : 1;
}
10 changes: 10 additions & 0 deletions doc/async.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ Each runs, by default, on the synchronous function's backend
(<<hash-default-backend>>): `backends::webcrypto`, the browser's WebCrypto, is
used only when the type names it, on Emscripten (<<hash-async-webcrypto>>).

An asynchronous function sets DIT (data-independent timing) where its
synchronous function does (<<hash-backends-dit>>), on the thread that
computes: a heavy function's synchronous function runs on a thread of the
executor's pool, inside its own guard, and gives that thread its DIT back
when it returns; a cheap one's runs at once on the calling thread, inside its
guard. The initiating function holds no guard of its own, and
`async_digest` computes an unkeyed digest, which sets none. On
`backends::webcrypto` the browser's JavaScript engine computes, on a target
where the guard does nothing, and nothing is added.

[#hash-async-heavy]
=== The heavy functions on another thread

Expand Down
Loading
Loading