diff --git a/.gitmodules b/.gitmodules index 20c0dc58..96aa8b76 100644 --- a/.gitmodules +++ b/.gitmodules @@ -70,3 +70,15 @@ [submodule "libs/crypto"] path = libs/crypto url = ../crypto.git +[submodule "third_party/libs/xkcp"] + path = third_party/libs/xkcp + url = https://github.com/XKCP/XKCP.git +[submodule "third_party/libs/libsodium"] + path = third_party/libs/libsodium + url = https://github.com/jedisct1/libsodium.git +[submodule "third_party/libs/blake3"] + path = third_party/libs/blake3 + url = https://github.com/BLAKE3-team/BLAKE3.git +[submodule "libs/hash"] + path = libs/hash + url = ../hash.git diff --git a/AGENTS.md b/AGENTS.md index 2a14e444..a9ec98f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,10 +109,10 @@ webcpp/ third_party/ third-party code the libraries and their tests use, not webcpp's: each a submodule under third_party/libs/, pinned at a commit and keeping its own licence (openssl, libdatachannel, bearssl, secp256k1, bitcoin for - ctaes, and the test data wycheproof, bips, JSON-Schema-Test-Suite and - nativejson-benchmark), and the Jamfile that declares it as - /webcpp/third_party// and /third_party// (guidelines - chapter 10) + ctaes, xkcp, libsodium, blake3, and the test data wycheproof, bips, + JSON-Schema-Test-Suite and nativejson-benchmark), and the Jamfile that + declares it as /webcpp/third_party// and + /third_party// (guidelines chapter 10) doc/ the index page (index.adoc, Jamfile) releases/ each version's release notes, which the index page shows site/ the site, a repository of its own, webcpporg/webcpporg.github.io, a @@ -910,7 +910,14 @@ testing.launcher on emscripten", chapter 6). Every program that node runs (`webcpp.run`, `webcpp.run-fail`, `webcpp.example`) links `-sNODERAWFS=1`, so that it reads the host's files and its standard input: without it, node gives it an empty file system of Emscripten's own, and a -test reads its input file as empty. No other program gets it. +test reads its input file as empty. No other program gets it. A program of +`webcpp.run`, `webcpp.run-fail` or `webcpp.example` that reads a fixed path, +as a C library's own tests read theirs (libsodium's `/test-data`), asks for +`off`: it links Emscripten's NODEFS (`-lnodefs.js`) in +place of `-sNODERAWFS=1`, under which nothing can be mounted, and mounts the +host's directories itself where it reads them (`FS.mount`); it then reads no +standard input of the host's, so an example with a `.input` does not +ask for it. **A program on emscripten links at its compile's level of optimization** (the Jamroot's region `emscripten-link-optimization`): `-O0` for @@ -1057,7 +1064,7 @@ webcpp.source-only + ; (reference source trees) | Rule | Passes when | Notes | | --- | --- | --- | | `webcpp.targets t ...` | | the Jamfile's default targets; before its first program, once; each is `native`, `emscripten`, `wasip2` or `wasip3`, or the build stops naming it | -| `webcpp.run` | the program exits with 0 | built once per target it declares; a user's `exception-handling=off` links `tools/throw_exception.cpp`; on emscripten, run by node, linked with `-sNODERAWFS=1`; links `/webcpp//node-test` on every target (Targets, above) | +| `webcpp.run` | the program exits with 0 | built once per target it declares; a user's `exception-handling=off` links `tools/throw_exception.cpp`; on emscripten, run by node, linked with `-sNODERAWFS=1`, or with NODEFS, which the program mounts itself, under `off`; links `/webcpp//node-test` on every target (Targets, above) | | `webcpp.run-fail` | the program exits with another status | built and run as `webcpp.run`'s, and links `/webcpp//node-test` likewise | | `webcpp.compile` | the sources compile | no program is linked; takes `/webcpp//node-test` for its header | | `webcpp.compile-fail` | the sources do not compile | left out of clang-tidy; any error passes it, the wrong one included; takes `/webcpp//node-test` for its header | @@ -1065,7 +1072,7 @@ webcpp.source-only + ; (reference source trees) | `webcpp.compile-diagnostic` | the sources stop with every error they state in clang's `-verify` comments, `// expected-error@:* {{}}` for a header they include or `// expected-error@+1 {{}}` for the next line | compiled with `-Xclang -verify -Xclang -verify-ignore-unexpected=error,note`, so an error not stated and a note are ignored, the cascade that follows a header's `#error` among them; then `tools/compile_diagnostic/check.py` runs the compile again with clang's diagnostic log and fails on any error located in a comment (a `//` one or a `/* */` one over several lines) after an `expected-` of that comment, which is `-verify`'s own report on a directive it could not read and so dropped (a header it names that cannot be located, a `{{...}}` whose `}}` is not on its line), and on a compile that reports no error at all: each directive clang reads, every one outside a branch the preprocessor skips, must be read whole, the header it names found and included, and its error raised in that header; built on b2's `clang` toolset only (native clang, `clang-wasip2`, `clang-wasip3`) and skipped elsewhere, since `-verify` is clang's: a refusal would turn every gcc and msvc lane red for a declaration that holds; left out of clang-tidy; takes `/webcpp//node-test` for its header | | `webcpp.boost-test` | every case of the Boost.Test suite passes | native only, whatever the Jamfile declares; the header-only framework, `tools/boost_test_runner.cpp`, is one object of the suite's, always compiled with exceptions | | `webcpp.source-only` | | declares child source directories whose original Jamfiles are not WebCPP projects; use in `build.jam` before discovery; it changes neither explicit compilation nor lint | -| `webcpp.example` | the program exits with 0, and its standard output, carriage returns removed, equals `.expected` beside it | its standard input is `.input` beside it, else empty, never the terminal, on every target (wasmtime passes it through, and node under `-sNODERAWFS=1`); run through `testing.launcher` for WASI, and on emscripten with the node on `PATH`, not the one b2's toolset registered, which b2 gives only to its own testing rules, by `tools/example/run_example.py`, which names a failing exit status (or the signal) before the diff; always run again, and `.input` is a source of the run; links `/webcpp//node-test` on every target (Targets, above) | +| `webcpp.example` | the program exits with 0, and its standard output, carriage returns removed, equals `.expected` beside it | its standard input is `.input` beside it, else empty, never the terminal, on every target (wasmtime passes it through, and node under `-sNODERAWFS=1`, which `off` replaces with NODEFS); run through `testing.launcher` for WASI, and on emscripten with the node on `PATH`, not the one b2's toolset registered, which b2 gives only to its own testing rules, by `tools/example/run_example.py`, which names a failing exit status (or the signal) before the diff; always run again, and `.input` is a source of the run; links `/webcpp//node-test` on every target (Targets, above) | | `webcpp.link` | the program links | never run: a program for a browser, which node refuses to run (`-sENVIRONMENT=web`), or one that needs the network; b2's `link` test, which `--dump-tests` lists and the report shows as a link test; never linked with `-sNODERAWFS=1`. The explicit target `-program` is the same program, an `exe` of the same sources and requirements, `-program.js` on emscripten, for a target that needs its files, such as a page that loads it. An example Jamfile's is shown on the page by its code, and has no `.expected` (chapter 3) | | `webcpp.headers-alone` | each public header compiles alone | one test per header, `alone-` with `/` as `-` (`alone-xactor-scheduler`), against `/webcpp///` and the requirements given, for the targets given or the Jamfile's; `only` restricts a call to the public headers its globs match, relative to `/webcpp/` (`wasi/http/response.hpp`), a glob that matches none stopping the build; a library may call it several times, and a header two calls take stops the build, naming it | | `webcpp.data` | | requirements, or usage requirements, that give a program of `webcpp.run` or `webcpp.run-fail` the absolute directories, each read at the same path on every target: on wasip2 and wasip3 wasmtime preopens it (`wasmtime --dir="" `); natively and on emscripten (`-sNODERAWFS=1`) the program reads the host's files already. A relative directory stops the build, as does one whose path holds `"`, `$` or a backquote, which the shell would read inside `--dir="..."`, naming the character | diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index f28833f3..64fc8dde 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -102,6 +102,7 @@ Not built yet: `tools/test/component_jam_test.py`, `tools/generated/generated_test.py`, `tools/test/emscripten_test.py`, `tools/test/crypto_jamfiles_test.py`, `tools/test/crypto_jamfiles_format_test.py`, + `tools/test/hash_jamfiles_test.py`, `tools/test/hash_jamfiles_format_test.py`, `tools/test/external_test.py`, `tools/test/doc_test.py`, `tools/test/harness_test.py`, `tools/test/third_party_test.py`, @@ -343,7 +344,12 @@ exactly its authors' and the program carries only what it calls. 2. `third_party/Jamfile` builds it from its own sources, file by file, as a static library, in the library's own C dialect, on every target and with every file: a file that does not apply to a target still compiles, to the - stubs other files call. A single unity source is not used. + stubs other files call. A single unity source is not used. Three exceptions, + each recorded in its row of chapter 10: BLAKE3's intrinsics files compile on + their instruction sets alone, each flagged for its own set; XKCP is built + from the one file of Keccak-p[1600] the library calls (and the high-level + files increment 3 of webcpp::hash lists), not from every file of its + package; libsodium is built without its `.S` files. 3. Every file is compiled with `-ffunction-sections -fdata-sections` (`/Gy /Gw` on MSVC); upstream's warnings are not webcpp's (`off`); each define the library cannot work out for itself on a target sits beside the @@ -581,17 +587,19 @@ aliases, concepts, variables, data members and macros. silently. - A user's Jamfile of a library whose own tests cannot express it (b2's raw `exe`, a refusal on one target) is a fixture of the tools' test, not a - library's test: `tools/test/fixtures/crypto_jamfiles//` holds the + library's test: `tools/test/fixtures/_jamfiles//` holds the case's `Jamfile`, its sources and `.outcome`, and - `tools/test/crypto_jamfiles_test.py` builds each case on a scratch + `tools/test/_jamfiles_test.py` builds each case on a scratch superproject, with b2 as a user runs it, once per target, in a build - directory the cases of a target share. The outcome file's lines starting + directory the cases of a target share, through `tools/test/user_jamfiles.py`, + which every such test shares. The outcome file's lines starting with `#` are comments; a block `[all]`, `[native]`, `[native-linux]`, - `[native-darwin]`, `[native-windows]`, `[wasip2]`, `[wasip3]` or - `[emscripten]` applies by the target and the system (`[all]` and each block - that matches apply). `targets: ...` (native only without it) names - the targets the case is built for; `build: succeeds` or `build: fails` is - b2's exit status; after `build: fails` every other line must be a whole line + `[native-darwin]`, `[native-windows]`, `[native-arm64]`, `[native-x86_64]`, + `[wasip2]`, `[wasip3]` or `[emscripten]` applies by the target, the system + and the machine's architecture (`[all]` and each block that matches apply). + `targets: ...` (native only without it) names the targets the case + is built for; `build: succeeds` or `build: fails` is b2's exit status; after + `build: fails` every other line must be a whole line of b2's output (trailing spaces aside), in any order; a line of one lowercase word and a colon is reserved for these directives, and `line: ` states a literal output line, empty for a blank one, also for @@ -650,7 +658,7 @@ with `lint: failed: ` for each rule that failed. | bare throw | a `throw` expression in a library's public header (`libs/*/include/**`), outside comments and literals, at its line: inside `#ifndef WEBCPP__NO_EXCEPTIONS` too, in a template that nothing instantiates, which clang-tidy's analysis without exceptions does not see, and as a rethrow, `throw;`; `boost::throw_exception` is the one way to raise, `std::rethrow_exception` the one way to rethrow (above) | | changelog form | a library's changelog or a version's release notes out of `AGENTS.md` chapter 5's form: a section or a region missing or out of order, a line that starts with no verb of the list, a cross-reference, an inline anchor such as `[[nodiscard]]` outside a passthrough, more than ten lines for a library and a version, text outside a bullet | | canary pins | a `WEBCPP_CRYPTO__COMMIT` of crypto's `detail/canary.h` that is not the first seven digits of the commit the superproject records for its submodule (`ctaes`: `bitcoin`) | -| nodiscard results | a function of a library's `include/` that returns `boost::system::result` without `[[nodiscard]]`, at its line, when the library asks for the rule in its `meta/lint.json` (`"nodiscard-results"` and its reason; crypto does): `boost::system::result` carries no `[[nodiscard]]` of its own; and a malformed file or an unknown key | +| nodiscard results | a function of a library's `include/` that returns `boost::system::result` without `[[nodiscard]]`, at its line, when the library asks for the rule in its `meta/lint.json` (`"nodiscard-results"` and its reason; crypto and hash do): `boost::system::result` carries no `[[nodiscard]]` of its own; and a malformed file or an unknown key | A source b2 expects not to compile (`webcpp.compile-fail`), and one that must stop with the error it states (`webcpp.compile-diagnostic`), are left @@ -947,8 +955,10 @@ update --init third_party/libs/`; a build that needs none never looks. | Target | What it is | Licence | | --- | --- | --- | -| `bearssl` | BearSSL from webcpp's unmodified mirror `webcpporg/bearssl` at `7bea48e`; a static library built file by file by `third_party/Jamfile` with webcpp::crypto's canary, on every target; `WEBCPP_CRYPTO_HAS_BEARSSL=1` | MIT | +| `bearssl` | BearSSL from webcpp's unmodified mirror `webcpporg/bearssl` at `7bea48e`; a static library built file by file by `third_party/Jamfile` with webcpp::crypto's and webcpp::hash's canaries (hash's when `libs/hash` is checked out), on every target; `WEBCPP_CRYPTO_HAS_BEARSSL=1`, and `WEBCPP_HASH_HAS_BEARSSL=1` with hash's canary | MIT | | `bips` | `bitcoin/bips` at `927b6de9`, shallow, test data: crypto's tests read BIP340's `bip-0340/test-vectors.csv` and BIP341's `bip-0341/wallet-test-vectors.json` at run time under the directory its define `WEBCPP_TEST_BIPS` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when it changes | BSD-2-Clause, as BIP340's header states | +| `blake3` | BLAKE3 1.8.7 at `f3149ec`; `third_party/Jamfile` compiles `c/blake3.c`, `blake3_dispatch.c` and `blake3_portable.c` on every target, the intrinsics files on their instruction sets alone (an exception to chapter 5 rule 2), with webcpp::hash's canary; `WEBCPP_HASH_HAS_BLAKE3=1` | CC0-1.0, Apache-2.0, or Apache-2.0 with LLVM exception | +| `blake3_vectors` | BLAKE3's official vectors, `test_vectors/test_vectors.json` of the submodule `third_party/libs/blake3` at `f3149ec`, test data: hash's tests read it at run time under the directory its define `WEBCPP_TEST_BLAKE3_VECTORS` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when it changes | CC0-1.0, Apache-2.0, or Apache-2.0 with LLVM exception | | `ca_certificates` | Dated Mozilla/curl CA data snapshot under `third_party/ca_certificates`, verified against its manifest and embedded by a build-generated header; updated explicitly by `tools/ca_certificates/update.py` | MPL-2.0 | | `ctaes` | `src/crypto/ctaes` of `bitcoin/bitcoin` v31.1 at `9be056a` (commit `9be056a8a72b624dae9623b2f7bded92c2a21c91`), the submodule `third_party/libs/bitcoin`, shallow; `third_party/Jamfile` compiles its `ctaes.c` alone, with webcpp::crypto's canary, on every target (`WEBCPP_CRYPTO_HAS_CTAES=1`); the tree's `src/secp256k1/` subtree is never on an include path and no glob over `third_party/libs` reaches it | MIT | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | @@ -956,7 +966,9 @@ update --init third_party/libs/`; a build that needs none never looks. | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | | `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC, WASIp2 single and WASIp3 single/cooperative | Apache-2.0 | | `secp256k1` | libsecp256k1 v0.8.0 at `6e2c8bc`; a static library built file by file by `third_party/Jamfile` (`src/secp256k1.c` and its two precomputed tables, every module on) with webcpp::crypto's canary, on every target; its tables by `webcpp-secp256k1-tables` (`auto`: small on Emscripten, large elsewhere); `WEBCPP_CRYPTO_HAS_SECP256K1=1` | MIT | +| `sodium` | libsodium 1.0.22 at `77e1ce5`, the submodule `third_party/libs/libsodium`; a static library built file by file by `third_party/Jamfile` (every `.c` of `src/libsodium/`, no assembly, the defines libsodium's configure finds on each target, upstream's `builds/msvc/version.h` copied into the build directory) with webcpp::hash's canary, on every target; `WEBCPP_HASH_HAS_SODIUM=1`; `sodium-test-config` gives a program its private headers and test defines; shared with webcpp::crypto | ISC | | `wycheproof` | C2SP's Wycheproof at `12fd3aaf` (2026-10-06), shallow, test data: crypto's tests read its `testvectors_v1/` at run time under the directory its define `WEBCPP_TEST_WYCHEPROOF` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of its files changes | Apache-2.0 | +| `xkcp` | XKCP (the Keccak team's code package) at `d20c8fc` (2026-11-10, no release tags); `third_party/Jamfile` compiles its `KeccakP-1600-opt64.c` alone (Keccak-p[1600], the generic64 profile) with webcpp::hash's adapter, `config.h` and canary, on every target; `WEBCPP_HASH_HAS_XKCP=1` | CC0; `brg_endian.h` under Brian Gladman's terms | OpenSSL builds from a checkout or a source distribution. Before Configure, its builder stages the distributable tree and checks a digest of paths, Git file @@ -8385,6 +8397,65 @@ created from one import commit of `reference/source/`. Source: `libraries/webrtc/openspec/changes/genesis/design.md` Open Questions (proposals). +### hash (hashing and key derivation over Boost.Hash2 and C backends; wrapper; accepted 2026-11-14, increment 1 built, not merged) + +webcpp::hash is one entry point for hashing and key derivation in a C++20 +program on every target webcpp has, a wrapper (`"port-of": null`). Increment 1 +is built on the library's branch (`libs/hash`, to become `webcpporg/hash`): +Boost.Hash2's algorithms and `hmac` re-exported by alias (`algorithms.hpp`, +`hmac.hpp`); Keccak-256 with the original padding over XKCP's permutation +(`keccak.hpp`) and BLAKE3 over its official C implementation (`blake3.hpp`), +both in Hash2's HashAlgorithm form; HKDF (RFC 5869, `hkdf.hpp`) and PBKDF2 +(RFC 8018, `pbkdf2.hpp`) on the backends `hash2`, `sodium`, `bearssl` and +`openssl` (`backends/`); Argon2id (RFC 9106, parallelism 1, `argon2.hpp`) and +scrypt (RFC 7914, `scrypt.hpp`) from libsodium; the profile and the default +backend (`config.hpp`), the capability table (`doc/capabilities.json`), and +the measured table (`doc/measurements*.json`, regenerated by the `measure` +lane). The C libraries are built by `third_party/Jamfile` (`xkcp`, `blake3`, +`sodium`, `bearssl`, each with a canary), their own suites by the `c-suites` +lane (`test/c_suites`), the examples are in `example/` and the documentation +in `doc/`. Every function is synchronous, reports failure as a +`boost::system::result`, takes its data as `std::span` and allocates nothing in +webcpp's own code. Its repository, `webcpporg/hash`, is still to be created by +the owner (gates G1, G2 and G4); the proposal, with the specification, the +design and the plan, is in `libraries/hash/openspec/changes/genesis/` +(proposals). + +- **Two constructions of webcpp's own, over an audited primitive each, and no + primitive.** HKDF and PBKDF2 over Boost.Hash2's `hmac` on every target, + the RFC's text step by step in under 150 lines with every intermediate value + wiped; and Keccak-256's sponge (absorbing, the `0x01 ... 0x80` padding and + squeezing) over XKCP's Keccak-p[1600], line for line as Boost.Hash2's + `detail::keccak_base<0x01, 512, 256>`, which is its oracle, until Boost + publishes a `keccak_256`. This departs from chapter 4's rule that webcpp + writes no cryptography of its own, as the owner recorded on 2026-11-14. + Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section + 1.3 (proposals). +- **The key derivation functions have backends, as webcpp::crypto's + algorithms do, and a backend that lacks a function refuses at compile + time.** `backends::hash2`, `sodium`, `bearssl` and `openssl` (native, + wasip2 and wasip3); natively the fastest linked backend is the default, on + WebAssembly the one that gives the smallest binary, decided by a measured + table that every pin move regenerates; one setting in `config.hpp` (a + profile) changes every default at once. + Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section + 1.4 (proposals). +- **The C libraries of hash (`xkcp`, `blake3`, `sodium`) are built file by + file by `third_party/Jamfile`, with a link-time canary each.** The shared + block of that Jamfile (`HASH`, `.hash-c-library`, `hash-checked-out`) is + the one every C library of hash uses; `.hash-c-library` and crypto's + `.c-library` share the C libraries' properties (`.c-sections`) and the + link's (`.gc`), each defined once. + Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section + 5 (proposals). +- **Seven increments, each usable alone.** The first, built, is Hash2 by alias, + `keccak_256`, `blake3`, HKDF, PBKDF2, Argon2id, scrypt, the profile and the + measured table; the next ones widen the backends' surface (libsodium's, + XKCP's, OpenSSL's, BearSSL's, Botan's) and add the browser backend over + WebCrypto through a parallel asynchronous family. + Source: `libraries/hash/openspec/changes/genesis/reference/spec.md` section + 1.5 (proposals). + ## 18. Proposed, not decided The proposals not yet decided, each briefly, with the questions they leave diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 240668dc..0a0a9c06 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -27,6 +27,9 @@ secp256k1 over C libraries built from source, from R. * link:{library-pages}document/{library-page}[document]: a header-only JSON document for {cpp}20 that behaves as JavaScript does, exact in decimal, in one relocatable binary image, with a JavaScript module, from R. +* link:{library-pages}hash/{library-page}[hash]: hashing and key derivation for +{cpp}20 over Boost.Hash2 and C backends: Keccak-256, BLAKE3, HKDF, PBKDF2, +Argon2id and scrypt, from R. * link:{library-pages}idna/{library-page}[idna]: a header-only library of internationalized domain names for {cpp}20: Punycode, UTS 46 and IDNA2008 validity over Unicode 17.0.0 tables, from R. @@ -84,6 +87,10 @@ None. * Fixed links over code hiding the underscores of names under their underline. * Fixed the header cells of a table with a header column lacking their scope, which the site's HTML check refuses. * Changed the references to leave out detail macros, WEBCPP_*_DETAIL_*. +* Fixed a stacked table's cell letting a word wider than its line, such as a commit, run past its frame. +* Fixed a stacked table's caption shrinking to its longest word. +* Added the user's Jamfiles of webcpp::hash, tested as fixtures of a test of the tools. +* Changed the lint's canary-pins rule to read webcpp::hash's detail/canary.h beside webcpp::crypto's. * Fixed the WASIp2 test launcher interrupting large finite workloads after 60 seconds. * Fixed Chrome provisioning and browser/TLS profile coverage in Asio CI lanes. * Added source-built OpenSSL and Cobalt SSL targets for WASIp2. @@ -266,6 +273,39 @@ could not read and dropped, such as one naming a header that does not exist. * Added ctaes, Bitcoin Core's constant-time AES at v31.1, built from source as /third_party//ctaes, and the fixtures of the user's Jamfiles of webcpp::crypto's block cipher and signing programs. +* Added XKCP's Keccak-p[1600], built from source with webcpp::hash's adapter as +`/third_party//xkcp`. +* Added libsodium 1.0.22, built from source as /third_party//sodium with the defines +its own configure finds on each target, and /third_party//sodium-test-config for a +program that compiles against its private headers. +* Added `off`, for a program of webcpp.run, webcpp.run-fail or webcpp.example +that mounts on emscripten the host's directories it reads, where it reads them, as libsodium's own +tests read `/test-data`. +* Added BLAKE3's C implementation 1.8.7, built from source as /third_party//blake3, +portable on WebAssembly and dispatched to its intrinsics files natively, its vectors as +/third_party//blake3_vectors. +* Added the feature webcpp-blake3-testing, which builds /third_party//blake3 with +BLAKE3_TESTING for BLAKE3's own test program. +* Added a probe of the configured compiler for x86-64 or arm64, on a native toolset whose +build request names no architecture, which picks BLAKE3's intrinsics files. +* Changed /third_party//bearssl to carry webcpp::hash's canary beside webcpp::crypto's, +and WEBCPP_HASH_HAS_BEARSSL, when libs/hash is checked out. +* Changed the check that a program links OpenSSL's archives once to cover a program naming +webcpp::hash's and webcpp::crypto's OpenSSL, when libs/hash is checked out. +* Fixed the check that a program links OpenSSL's archives once finding no link line on WASI. +* Changed /third_party//sodium to link its programs on Emscripten with +-sALLOW_MEMORY_GROWTH=1, for the memory Argon2id and scrypt allocate. +* Added tools/hash/measure.py and webcpp::hash's own lane measure, which builds and measures +its capability table's programs on the four targets in one command. +* Added own lanes that build for every target in one command, whose CI job installs and +registers the WebAssembly toolsets beside Clang 18: webcpp::hash's measure. +* Fixed the lint's clang-tidy refusing such a lane, whose sources it now analyses +natively. +* Added tools/hash/doc_tables.py, which generates webcpp::hash's comparison tables, +backend lists and llms.txt from its capability table and its measurements, and checks them +when its page is built. +* Changed tools/hash/doc_tables.py to give each chapter two comparison tables, each under the +eight columns from which a table scrolls. [#webcpp-0-1-0-compilers-tested] == Compilers tested diff --git a/libs/hash b/libs/hash new file mode 160000 index 00000000..36df8a14 --- /dev/null +++ b/libs/hash @@ -0,0 +1 @@ +Subproject commit 36df8a1445da78ce207626cf4958e64e60f3b2b1 diff --git a/third_party/Jamfile b/third_party/Jamfile index 2bd8fbb9..142522c9 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -10,12 +10,16 @@ # requirements give a program what it needs. A target whose submodule is not # checked out stops the build that needs it, naming the command that checks # it out; a build that needs none never looks. The C libraries of -# webcpp::crypto's backends are built here from their own sources, file by file. +# webcpp::crypto's and webcpp::hash's backends are built here from their own +# sources, file by file. +import configure ; import errors ; import feature ; import path ; +import project ; import regex ; import webcpp ; +import webcpp-target ; project /webcpp/third_party ; @@ -162,13 +166,29 @@ webcpp-ca-certificates.declare ca_certificates/cacert.pem ca_certificates/manife ../tools/ca_certificates/generate.py ../tools/ca_certificates/bundle.py ; explicit ca_certificates ca_certificates-header ; -# The C libraries of webcpp::crypto's backends: each a static library compiled -# file by file in the library's own C dialect (no -std), every function and -# datum in a section of its own, so that a program keeps only what it calls -# (CODING-GUIDELINES.md chapter 5, "Bringing a C library into webcpp"). -# Upstream's warnings are not ours. webcpp's libs/crypto/src/canary_.c -# joins each: it defines the symbol the backend's header reads, which names the -# commit and the configuration. +# The C libraries of webcpp::crypto and webcpp::hash: each a static library +# compiled file by file in the library's own C dialect (no -std), every +# function and datum in a section of its own, so that a program keeps only what +# it calls (CODING-GUIDELINES.md chapter 5, "Bringing a C library into +# webcpp"). Upstream's warnings are not ours. Each library's block below adds +# the check that the library is checked out and the include directory of its +# canaries' header. +.c-sections = static off off + clang:"-ffunction-sections -fdata-sections" + gcc:"-ffunction-sections -fdata-sections" + emscripten:"-ffunction-sections -fdata-sections" + msvc:"/Gy /Gw" ; + +# What a program that links one of them needs: the linker's removal of unused +# sections, which wasm-ld, Emscripten and MSVC's release link do by default +# (link.exe leaves /OPT:REF off under /DEBUG, so it is asked for). +.gc = darwin:-Wl,-dead_strip + linux:-Wl,--gc-sections + windows:"/OPT:REF" ; + +# The C libraries of webcpp::crypto's backends. webcpp's +# libs/crypto/src/canary_.c joins each: it defines the symbol the +# backend's header reads, which names the commit and the configuration. path-constant CRYPTO : ../libs/crypto ; # The canaries and their header are webcpp::crypto's: a checkout without @@ -184,21 +204,9 @@ rule crypto-checked-out ( properties * ) } } -.c-library = static off off - @crypto-checked-out - clang:"-ffunction-sections -fdata-sections" - gcc:"-ffunction-sections -fdata-sections" - emscripten:"-ffunction-sections -fdata-sections" - msvc:"/Gy /Gw" +.c-library = $(.c-sections) @crypto-checked-out $(CRYPTO)/include ; -# What a program that links one of them needs: the linker's removal of unused -# sections, which wasm-ld, Emscripten and MSVC's release link do by default -# (link.exe leaves /OPT:REF off under /DEBUG, so it is asked for). -.gc = darwin:-Wl,-dead_strip - linux:-Wl,--gc-sections - windows:"/OPT:REF" ; - # BearSSL (MIT), from webcpp's unmodified mirror webcpporg/bearssl. Every .c # of src/, the POWER8 ones too, which off POWER compile to the stubs other # files call. One source of entropy, getentropy, with RDRAND and /dev/urandom @@ -245,11 +253,15 @@ rule bearssl-seeder ( properties * ) alias bearssl-test-config : : : : $(.bearssl-config) libs/bearssl/src ; explicit bearssl-test-config ; +# webcpp::hash's canary joins crypto's when libs/hash is checked out +# (bearssl-hash-canary, after the C libraries of webcpp::hash below). lib bearssl : [ glob libs/bearssl/src/*.c libs/bearssl/src/*/*.c ] $(CRYPTO)/src/canary_bearssl.c : $(.c-library) @bearssl-checked-out libs/bearssl/inc libs/bearssl/src $(.bearssl-config) - : : libs/bearssl/inc WEBCPP_CRYPTO_HAS_BEARSSL=1 $(.gc) ; + @bearssl-hash-canary + : : libs/bearssl/inc WEBCPP_CRYPTO_HAS_BEARSSL=1 $(.gc) + @bearssl-hash-usage ; explicit bearssl ; # ctaes (MIT), Pieter Wuille's constant-time AES as Bitcoin Core v31.1 ships it @@ -330,3 +342,461 @@ lib secp256k1 emscripten,auto:WEBCPP_CRYPTO_SECP256K1_SMALL_TABLES=1 $(.gc) ; explicit secp256k1 ; + +# The C libraries of webcpp::hash. webcpp's libs/hash/include/webcpp/hash/ +# detail/canary.h is the header of the canaries each of them defines. +path-constant HASH : ../libs/hash ; + +# The canaries' header is webcpp::hash's: a checkout without libs/hash stops +# the build of a C library of hash's, naming the command, and leaves the other +# targets of this Jamfile as they are. +rule hash-checked-out ( properties * ) +{ + if ! [ path.exists [ path.native $(HASH)/build.jam ] ] + { + errors.user-error "libs/hash is not checked out: it holds no build.jam," + "which the C libraries of webcpp::hash are built with. Check it out" + "with `git submodule update --init libs/hash`." ; + } +} + +.hash-c-library = $(.c-sections) @hash-checked-out + $(HASH)/include ; + +# BearSSL, /third_party//bearssl above, is webcpp::crypto's target and carries +# webcpp::hash's canary too: an object of its own, compiled with BearSSL's +# defines, which the library's sources gain only when libs/hash holds it, so +# that a checkout without libs/hash builds crypto's BearSSL as before. The +# check runs at build time; WEBCPP_HASH_HAS_BEARSSL then joins the usage +# requirements. +obj bearssl_hash_canary : $(HASH)/src/canary_bearssl.c + : $(.hash-c-library) $(.bearssl-config) ; +explicit bearssl_hash_canary ; + +rule bearssl-hash-canary ( properties * ) +{ + if [ path.exists [ path.native $(HASH)/src/canary_bearssl.c ] ] + { + return bearssl_hash_canary ; + } +} + +rule bearssl-hash-usage ( properties * ) +{ + if [ path.exists [ path.native $(HASH)/src/canary_bearssl.c ] ] + { + return WEBCPP_HASH_HAS_BEARSSL=1 ; + } +} + +# XKCP (CC0; brg_endian.h under Brian Gladman's terms), the Keccak team's code +# package at d20c8fc (2026-11-10; XKCP has no release tags): its Keccak-p[1600] +# alone, in the plain-64bits implementation with all rounds unrolled +# ("generic64"), on every target: wasm32 has 64-bit integers, MSVC compiles it +# with _rotl64, and XKCP's faster profiles are GNU assembly. Its config.h, which +# XKCP's build generates, is webcpp's libs/hash/src/xkcp/config.h. A program +# reaches it through webcpp::hash's adapter (libs/hash/src/xkcp_adapter.c), so +# no include directory of XKCP's is a usage requirement. +path-constant XKCP : libs/xkcp ; + +rule xkcp-checked-out ( properties * ) +{ + if ! [ path.exists [ path.native + $(XKCP)/lib/low/KeccakP-1600/plain-64bits/KeccakP-1600-opt64.c ] ] + { + errors.user-error "third_party/libs/xkcp is not checked out: it holds no" + "lib/low/KeccakP-1600/plain-64bits/KeccakP-1600-opt64.c. Check it out" + "with `git submodule update --init third_party/libs/xkcp`." ; + } +} + +lib xkcp + : libs/xkcp/lib/low/KeccakP-1600/plain-64bits/KeccakP-1600-opt64.c + $(HASH)/src/xkcp_adapter.c $(HASH)/src/canary_xkcp.c + : $(.hash-c-library) @xkcp-checked-out $(HASH)/src/xkcp + libs/xkcp/lib/common libs/xkcp/lib/low/common + libs/xkcp/lib/low/KeccakP-1600/common + libs/xkcp/lib/low/KeccakP-1600/plain-64bits + libs/xkcp/lib/low/KeccakP-1600/plain-64bits/SnP + : : WEBCPP_HASH_HAS_XKCP=1 $(.gc) ; +explicit xkcp ; + +# libsodium 1.0.22 (ISC), jedisct1/libsodium at 77e1ce5: every .c of +# src/libsodium/, one object per file, with the defines libsodium's own +# configure finds on each target (sodium-target-defines), without its +# assembly: HAVE_AMD64_ASM and HAVE_AVX_ASM stay off, as configure's +# --disable-asm leaves them, so that the seven .S files are not needed and +# the C code is used (design D11); the C files of the assembly's paths +# compile to nothing. Shared by webcpp::hash and, later, webcpp::crypto: one +# copy per program. On Emscripten a program that links it links with +# -sALLOW_MEMORY_GROWTH=1: Argon2id and scrypt allocate the memory their costs +# name (64 MiB for crypto_pwhash's interactive costs), past Emscripten's +# fixed 16 MiB, as libsodium's own tests link. +path-constant SODIUM : libs/libsodium ; + +rule sodium-checked-out ( properties * ) +{ + local core = $(SODIUM)/src/libsodium/include/sodium/core.h ; + if ! [ path.exists [ path.native $(core) ] ] + { + errors.user-error "third_party/libs/libsodium is not checked out. Check it" + "out with `git submodule update --init third_party/libs/libsodium`." ; + } +} + +# version.h is written by libsodium's configure, from version.h.in; upstream +# ships it generated, as builds/msvc/version.h. b2 copies that file, unchanged, +# into the build directory, as sodium-version/sodium/version.h: its directory +# sodium-version gives sodium.h its "sodium/version.h", and sodium-version/ +# sodium gives sodium/version.c its "version.h". The submodule is never +# written. The copy's place is fixed (), so that both directories +# are known here; it is the same file for every build. +.sodium-version = [ project.current ] ; +.sodium-version = [ path.root [ $(.sodium-version).build-dir ] [ path.pwd ] ] ; +.sodium-version = $(.sodium-version)/sodium-version ; +make sodium/version.h : libs/libsodium/builds/msvc/version.h : common.copy + : @sodium-checked-out $(.sodium-version) ; +explicit sodium/version.h ; + +# libsodium's configuration on each target, as libsodium's own configure finds +# it at the pin, run once per target in a scratch copy (never the submodule): +# +# ./configure --disable-shared --enable-static --disable-asm +# +# natively, and, as dist-build/wasm32-wasi.sh and dist-build/emscripten.sh run +# it at the pin, with --without-pthreads --disable-ssp and, on WASI, +# CC=/bin/clang CFLAGS=--target=wasm32-wasip2 (or wasip3) +# --host=wasm32-wasi, on Emscripten under emconfigure. Each group below is the +# DEFS of `./config.status --config` and the generated Makefile that libsodium's +# C files read, on the targets whose configure found it. A define that no C +# file of src/libsodium/ reads is recorded here and left out: the package's +# strings (PACKAGE*, VERSION, LT_OBJDIR), the headers' (HAVE_STDIO_H, +# HAVE_STDLIB_H, HAVE_STRING_H, HAVE_STRINGS_H, HAVE_INTTYPES_H, HAVE_STDINT_H, +# HAVE_SYS_STAT_H, HAVE_SYS_TYPES_H, HAVE_UNISTD_H, HAVE_WCHAR_H, HAVE_DLFCN_H, +# STDC_HEADERS, HAVE_COMMONCRYPTO_COMMONRANDOM_H), HAVE_ARC4RANDOM_BUF, +# HAVE_PTHREAD_PRIO_INHERIT, the system's extension macros (_GNU_SOURCE, +# _DARWIN_C_SOURCE, _ALL_SOURCE, __EXTENSIONS__ and the rest of +# AC_USE_SYSTEM_EXTENSIONS, which these toolchains' defaults already give), +# and HAVE_CET_H, which only the .S files read. DEV_MODE is off everywhere. +# Four that only libsodium's tests read (HAVE_ARC4RANDOM, HAVE_CATCHABLE_ABRT, +# HAVE_CATCHABLE_SEGV, HAVE_CLOCK_GETTIME) are sodium-test-config's. + +# Every target's: webcpp's three, which the canary reads (CONFIGURED, +# SODIUM_STATIC, NATIVE_LITTLE_ENDIAN), and those configure finds on every +# run. +.sodium-common = CONFIGURED=1 SODIUM_STATIC=1 + NATIVE_LITTLE_ENDIAN=1 HAVE_ALLOCA=1 HAVE_ALLOCA_H=1 + HAVE_ATOMIC_OPS=1 HAVE_C11_MEMORY_FENCES=1 + HAVE_C_VARARRAYS=1 HAVE_GCC_MEMORY_FENCES=1 + HAVE_INLINE_ASM=1 HAVE_NANOSLEEP=1 + HAVE_POSIX_MEMALIGN=1 HAVE_SYS_PARAM_H=1 + HAVE_SYS_RANDOM_H=1 ; + +# wasip2 and wasip3 (wasi-sdk 34, wasm32-wasi; the two runs agree): no mmap, +# no threads, getentropy. +.sodium-wasi = HAVE_GETENTROPY=1 HAVE_THREADS_H=1 ; + +# Emscripten 6.0.11: no getentropy (randombytes calls JavaScript's), no TI +# mode. +.sodium-emscripten = HAVE_EXPLICIT_BZERO=1 HAVE_GETPID=1 + HAVE_SYS_MMAN_H=1 HAVE_THREADS_H=1 ; + +# Native, on macOS and Linux alike (macOS 27 arm64 with Apple Clang 21, and +# x86-64 by a run with CC="cc -arch x86_64" --host=x86_64-apple-darwin; +# Ubuntu 24.04 x86-64 with GCC 14 and Clang 18; Ubuntu 24.04 arm64 with GCC +# 14 and Clang 18). TLS, the thread-local storage class, is _Thread_local: +# autoconf 2.72 runs configure's checks under -std=gnu23 wherever the +# compiler has it, where its check takes thread_local, a keyword only from +# C23; Clang 18, which has no gnu23, gives _Thread_local, the keyword of +# every dialect from C11, which webcpp's build (no -std) compiles in. +.sodium-posix = HAVE_GETENTROPY=1 HAVE_GETPID=1 + HAVE_MADVISE=1 HAVE_MLOCK=1 HAVE_MMAP=1 + HAVE_MPROTECT=1 HAVE_PTHREAD=1 HAVE_RAISE=1 + HAVE_SYSCONF=1 HAVE_SYS_MMAN_H=1 HAVE_TI_MODE=1 + HAVE_WEAK_SYMBOLS=1 TLS=_Thread_local ; + +# macOS: memset_s. +.sodium-darwin = HAVE_MEMSET_S=1 ; + +# Linux: glibc's getrandom, getauxval and explicit_bzero, on x86-64 and arm64 +# alike. +.sodium-linux = HAVE_EXPLICIT_BZERO=1 HAVE_GETAUXVAL=1 + HAVE_GETRANDOM=1 HAVE_SYS_AUXV_H=1 + HAVE_THREADS_H=1 ; + +# The architecture's, natively: x86-64's intrinsics' headers and RDRAND, +# whose C files enable each instruction set by a target attribute of their +# own, so that no file needs a flag (configure's CFLAGS_SSE2 and the rest are +# empty on every run); arm64's crypto extensions, the same. +.sodium-x86_64 = HAVE_MMINTRIN_H=1 HAVE_EMMINTRIN_H=1 + HAVE_PMMINTRIN_H=1 HAVE_TMMINTRIN_H=1 + HAVE_SMMINTRIN_H=1 HAVE_AVXINTRIN_H=1 + HAVE_AVX2INTRIN_H=1 HAVE_AVX512FINTRIN_H=1 + HAVE_WMMINTRIN_H=1 HAVE_RDRAND=1 ; +.sodium-arm64 = HAVE_ARMCRYPTO=1 ; + +# MSVC has no configure: builds/msvc/vs2022/libsodium/libsodium.props at the +# pin defines inline=__inline, NATIVE_LITTLE_ENDIAN, SODIUM_STATIC (a static +# library) and _CRT_SECURE_NO_WARNINGS (left out: the CRT's headers read it, +# no C file of libsodium's), and libsodium's private/common.h defines the +# intrinsics' HAVE_* itself under _MSC_VER. CONFIGURED is webcpp's, as on +# every target; common.h does not require it under MSVC. inline=__inline is +# for C alone, a (MSVC's C++ compile never reads ): the C++ +# translation units of a program that uses sodium-test-config, among them, +# include the standard library's headers, which refuse a macro named after a +# keyword. +.sodium-msvc = CONFIGURED=1 SODIUM_STATIC=1 + NATIVE_LITTLE_ENDIAN=1 /Dinline=__inline ; + +# The defines only libsodium's tests read, by the same configure runs. The +# x86-64 macOS run, cross-compiled, could not run the checks of the catchable +# signals, which every native run that could finds. +.sodium-test-common = HAVE_CLOCK_GETTIME=1 ; +.sodium-test-arc4random = HAVE_ARC4RANDOM=1 ; +.sodium-test-catchable = HAVE_CATCHABLE_ABRT=1 + HAVE_CATCHABLE_SEGV=1 ; + +# The architecture a native build is for, x86_64 or arm64, as configure's +# runs name them: with , else the machine b2 +# runs on (b2's OSPLAT, X86_64 or ARM64, which names its model). A build that +# gives one of and without the other, or any +# other pair, is returned as -, which +# sodium-target-defines refuses: no model is guessed. +local rule sodium-architecture ( properties * ) +{ + local architecture = [ feature.get-values : $(properties) ] ; + local model = [ feature.get-values : $(properties) ] ; + if ! $(architecture) && ! $(model) + { + switch [ modules.peek : OSPLAT ] + { + case X86_64 : return x86_64 ; + case ARM64 : return arm64 ; + } + return [ modules.peek : OSPLAT ] ; + } + switch $(architecture:E=unknown)-$(model:E=unknown) + { + case x86-64 : return x86_64 ; + case arm-64 : return arm64 ; + } + return $(architecture:E=unknown)-$(model:E=unknown) ; +} + +# The defines of a build: the groups above by its target, its system, its +# toolset and its architecture. A native build none of the configure runs +# covers (another system, or another architecture) stops, naming it, rather +# than build libsodium with a guessed configuration. +rule sodium-target-defines ( properties * ) +{ + local target = [ webcpp-target.target-of $(properties) ] ; + local toolset = [ feature.get-values : $(properties) ] ; + local system = [ feature.get-values : $(properties) ] ; + switch $(target) + { + case wasip2 : return $(.sodium-common) $(.sodium-wasi) ; + case wasip3 : return $(.sodium-common) $(.sodium-wasi) ; + case emscripten : return $(.sodium-common) $(.sodium-emscripten) ; + } + if $(toolset) = msvc + { + return $(.sodium-msvc) ; + } + local architecture = [ sodium-architecture $(properties) ] ; + local defines = $(.sodium-common) $(.sodium-posix) + $(.sodium-$(architecture)) ; + switch $(system)-$(architecture) + { + case darwin-x86_64 : return $(defines) $(.sodium-darwin) ; + case darwin-arm64 : return $(defines) $(.sodium-darwin) ; + case linux-x86_64 : return $(defines) $(.sodium-linux) ; + case linux-arm64 : return $(defines) $(.sodium-linux) ; + } + errors.user-error "/third_party//sodium: libsodium's configuration is" + "derived for macOS and Linux on x86-64 and arm64, WASI, Emscripten and" + "MSVC; this build is for $(system:E=no system) on $(architecture)" ; +} + +# What libsodium's own tests add on each target: the four defines only they +# read, as configure found them (HAVE_ARC4RANDOM natively and on WASI, the +# catchable signals natively, not on MSVC, whose build defines none of them). +rule sodium-test-defines ( properties * ) +{ + local target = [ webcpp-target.target-of $(properties) ] ; + if [ feature.get-values : $(properties) ] = msvc + { + return ; + } + switch $(target) + { + case native : return $(.sodium-test-common) $(.sodium-test-arc4random) + $(.sodium-test-catchable) ; + case emscripten : return $(.sodium-test-common) ; + } + return $(.sodium-test-common) $(.sodium-test-arc4random) ; +} + +lib sodium + : [ glob-tree-ex libs/libsodium/src/libsodium : *.c ] + $(HASH)/src/canary_sodium.c + : $(.hash-c-library) @sodium-checked-out + @sodium-target-defines + sodium/version.h sodium/version.h + libs/libsodium/src/libsodium/include + libs/libsodium/src/libsodium/include/sodium + $(.sodium-version) $(.sodium-version)/sodium + : : libs/libsodium/src/libsodium/include $(.sodium-version) + sodium/version.h SODIUM_STATIC=1 + WEBCPP_HASH_HAS_SODIUM=1 $(.gc) + emscripten:-sALLOW_MEMORY_GROWTH=1 ; +explicit sodium ; + +# What a program that compiles against libsodium's private headers adds, as +# libsodium's own tests and webcpp::hash's RFC 9106 test do: the library's +# include directories, the directory of include/sodium/private, argon2's, the +# copied version.h's, and the library's defines, with those only the tests +# read. +alias sodium-test-config : : @sodium-checked-out : : + libs/libsodium/src/libsodium/include + libs/libsodium/src/libsodium/include/sodium + libs/libsodium/src/libsodium/crypto_pwhash/argon2 + $(.sodium-version) $(.sodium-version)/sodium + sodium/version.h @sodium-target-defines @sodium-test-defines ; +explicit sodium-test-config ; + +# BLAKE3's C implementation (CC0-1.0, or Apache-2.0, or Apache-2.0 with LLVM +# exception), c/ of BLAKE3-team/BLAKE3. blake3.c, blake3_dispatch.c and +# blake3_portable.c on every target; the intrinsics files only on the targets +# of their instruction sets, each with its flag, as BLAKE3's own CMake builds +# them where it has no assembler: they include x86 or Arm headers that no +# WebAssembly sysroot has (a recorded exception to CODING-GUIDELINES.md +# chapter 5 rule 2). BLAKE3's dispatcher chooses at run time. On WebAssembly +# the four BLAKE3_NO_* leave the portable code alone. Never BLAKE3_USE_TBB. +path-constant BLAKE3 : libs/blake3 ; + +rule blake3-checked-out ( properties * ) +{ + if ! [ path.exists [ path.native $(BLAKE3)/c/blake3.h ] ] + { + errors.user-error "third_party/libs/blake3 is not checked out. Check it out with" + "`git submodule update --init third_party/libs/blake3`." ; + } +} + +# The instruction set a build of BLAKE3 is for: wasm on WebAssembly; natively +# x86-64, arm64 or other. A request that names both and +# is taken as it names them. Else the configured compiler is +# asked, as tools/openssl/build.py asks it for OpenSSL's target: b2 sets +# neither feature on a native toolset unless the request does, and the +# compiler then builds for whatever it defaults to (MSVC for the host's +# PROCESSOR_ARCHITECTURE, whatever b2 itself was built for). Each probe, +# probes/blake3_.c, compiles only when the macros that blake3.hpp and +# src/canary_blake3.c read say x86-64 (__x86_64__, _M_X64) or arm64 +# (__aarch64__, _M_ARM64), so that the build, the canary and the header +# cannot disagree. +obj blake3_probe_x86_64 : probes/blake3_x86_64.c : off ; +obj blake3_probe_arm64 : probes/blake3_arm64.c : off ; +explicit blake3_probe_x86_64 blake3_probe_arm64 ; + +rule blake3-architecture ( properties * ) +{ + if [ webcpp-target.target-of $(properties) ] != native + { + return wasm ; + } + local architecture = [ feature.get-values : $(properties) ] ; + local address-model = [ feature.get-values : $(properties) ] ; + if $(architecture) && $(address-model) + { + switch $(architecture)-$(address-model) + { + case x86-64 : return x86-64 ; + case arm-64 : return arm64 ; + case * : return other ; + } + } + if [ configure.builds /webcpp/third_party//blake3_probe_x86_64 : $(properties) + : "BLAKE3's compiler targets x86-64" ] + { + return x86-64 ; + } + if [ configure.builds /webcpp/third_party//blake3_probe_arm64 : $(properties) + : "BLAKE3's compiler targets arm64" ] + { + return arm64 ; + } + return other ; +} + +# Each intrinsics file is an object of its own, so that its flag reaches it +# alone; on a target without its instruction set the object is empty of +# sources (b2's no), which the third_party test checks. +rule blake3-x86 ( properties * ) +{ + if [ blake3-architecture $(properties) ] = x86-64 + { + return ; + } + return no ; +} + +obj blake3_sse2 : libs/blake3/c/blake3_sse2.c + : $(.hash-c-library) @blake3-x86 clang:-msse2 + gcc:-msse2 ; +obj blake3_sse41 : libs/blake3/c/blake3_sse41.c + : $(.hash-c-library) @blake3-x86 clang:-msse4.1 + gcc:-msse4.1 ; +obj blake3_avx2 : libs/blake3/c/blake3_avx2.c + : $(.hash-c-library) @blake3-x86 clang:-mavx2 + gcc:-mavx2 msvc:"/arch:AVX2" ; +obj blake3_avx512 : libs/blake3/c/blake3_avx512.c + : $(.hash-c-library) @blake3-x86 + clang:"-mavx512f -mavx512vl" + gcc:"-mavx512f -mavx512vl" + msvc:"/arch:AVX512" ; +explicit blake3_sse2 blake3_sse41 blake3_avx2 blake3_avx512 ; + +# What each instruction set adds: on WebAssembly, and on a native target that +# is neither x86-64 nor arm64, the four BLAKE3_NO_*, the portable code alone; +# on x86-64 the four intrinsics objects; on arm64 the NEON file, which +# BLAKE3_USE_NEON=1 makes blake3_dispatch.c call. +rule blake3-profile ( properties * ) +{ + switch [ blake3-architecture $(properties) ] + { + case x86-64 : + return blake3_sse2 blake3_sse41 blake3_avx2 + blake3_avx512 ; + case arm64 : + return libs/blake3/c/blake3_neon.c BLAKE3_USE_NEON=1 ; + case * : + return BLAKE3_NO_SSE2 BLAKE3_NO_SSE41 + BLAKE3_NO_AVX2 BLAKE3_NO_AVX512 ; + } +} + +# BLAKE3's own test program (libs/hash/test/c_suites, the lane c-suites) needs +# blake3_dispatch.c compiled with BLAKE3_TESTING, which makes the dispatcher's +# choice of instruction sets a global it sets, so that one run checks each. +# Propagated, so that the program's request reaches the library; off, the +# default, everywhere else. +feature.feature webcpp-blake3-testing : off on : propagated ; + +lib blake3 + : libs/blake3/c/blake3.c libs/blake3/c/blake3_dispatch.c + libs/blake3/c/blake3_portable.c $(HASH)/src/canary_blake3.c + : $(.hash-c-library) @blake3-checked-out libs/blake3/c + @blake3-profile on:BLAKE3_TESTING + : : libs/blake3/c WEBCPP_HASH_HAS_BLAKE3=1 $(.gc) ; +explicit blake3 ; + +# BLAKE3's official vectors, test_vectors/test_vectors.json at the pin, read at +# run time from the directory WEBCPP_TEST_BLAKE3_VECTORS gives, on every target. +# Quoted as wycheproof's define is, with forward slashes, so that a path with a +# space or a backslash survives. +.blake3-vectors = [ regex.replace $(BLAKE3)/test_vectors "\\\\" "/" ] ; +alias blake3_vectors : : @blake3-checked-out : : + "\"WEBCPP_TEST_BLAKE3_VECTORS=\\\"$(.blake3-vectors)\\\"\"" + [ webcpp.data $(BLAKE3)/test_vectors ] + libs/blake3/test_vectors/test_vectors.json ; +explicit blake3_vectors ; diff --git a/third_party/libs/blake3 b/third_party/libs/blake3 new file mode 160000 index 00000000..f3149ec5 --- /dev/null +++ b/third_party/libs/blake3 @@ -0,0 +1 @@ +Subproject commit f3149ec5bb5449af877ba20377a11008ff499fa2 diff --git a/third_party/libs/libsodium b/third_party/libs/libsodium new file mode 160000 index 00000000..77e1ce5d --- /dev/null +++ b/third_party/libs/libsodium @@ -0,0 +1 @@ +Subproject commit 77e1ce5d6dee871c49ef211222ba18ef0c486bda diff --git a/third_party/libs/xkcp b/third_party/libs/xkcp new file mode 160000 index 00000000..d20c8fca --- /dev/null +++ b/third_party/libs/xkcp @@ -0,0 +1 @@ +Subproject commit d20c8fcaecc543f816a0721d0dfc13b4cf27c14d diff --git a/third_party/probes/blake3_arm64.c b/third_party/probes/blake3_arm64.c new file mode 100644 index 00000000..8cf38c36 --- /dev/null +++ b/third_party/probes/blake3_arm64.c @@ -0,0 +1,19 @@ +/* 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) + * + * third_party/Jamfile's probe of the configured compiler: it compiles only for + * arm64, read from the macros that webcpp::hash's blake3.hpp and + * src/canary_blake3.c read, so that the build of /third_party//blake3, its + * canary and the header agree on the instruction set. */ +#if !(defined(__aarch64__) || defined(_M_ARM64)) +#error "not arm64" +#endif + +int webcpp_blake3_probe_arm64(void); + +int webcpp_blake3_probe_arm64(void) { + return 0; +} diff --git a/third_party/probes/blake3_x86_64.c b/third_party/probes/blake3_x86_64.c new file mode 100644 index 00000000..83226b35 --- /dev/null +++ b/third_party/probes/blake3_x86_64.c @@ -0,0 +1,19 @@ +/* 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) + * + * third_party/Jamfile's probe of the configured compiler: it compiles only for + * x86-64, read from the macros that webcpp::hash's blake3.hpp and + * src/canary_blake3.c read, so that the build of /third_party//blake3, its + * canary and the header agree on the instruction set. */ +#if !(defined(__x86_64__) || defined(_M_X64)) +#error "not x86-64" +#endif + +int webcpp_blake3_probe_x86_64(void); + +int webcpp_blake3_probe_x86_64(void) { + return 0; +} diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index b29bb7d6..c041e529 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -83,9 +83,12 @@ from b2's command line alone; an own lane of such a library likewise. own-lane runs one own lane, OWN-LANE being one entry of the own-lanes matrix as JSON: it registers -the toolset of the lane it shares (Clang 18 when it names no target), prints its b2 command and runs -it. Without a target, b2's exit status is its verdict; with one, it writes DIR/.xml, which the -job uploads, and fails only when b2 cannot build at all, as a lane does. +the toolset of the lane it shares (Clang 18 when it names no target), and for an own lane of +EVERY_TARGET_LANES, which names no target yet builds for every target in one command, the toolsets +of wasip2, wasip3 and emscripten after it (its entry says wasm, emsdk and node, which its job +installs), prints its b2 command and runs it. Without a target, b2's exit status is its verdict; +with one, it writes DIR/.xml, which the job uploads, and fails only when b2 cannot build at +all, as a lane does. register adds the toolsets of the lanes named by id to the user-config.jam, in their order, the first being b2's default toolset: what the CI's tools job builds the tests of the tools with. A WASI @@ -185,6 +188,16 @@ ('cobalt', 'browser-network-counterparts'), ('document', 'js'), ('trystero', 'interop')} +# The own lanes that name no target yet build for every target in one command, (library, lane): +# hash's measure, whose Jamfile names wasip2's, wasip3's and emscripten's toolsets in its +# programs' references. Their job installs wasi-sdk, wasmtime, emsdk and the CI's node, and +# registers those three toolsets after Clang 18's, b2's default, the native target's +# (own_lane_toolsets). +EVERY_TARGET_LANES = {('hash', 'measure')} + +# The lanes whose toolsets an own lane of EVERY_TARGET_LANES registers after its own. +EVERY_TARGET_TOOLSETS = ('wasip2', 'wasip3', 'emscripten') + # MSVC's lanes build 64-bit programs, embed their manifest with the linker and abbreviate b2's # paths against Windows's MAX_PATH, as xstate-cpp's green Windows jobs did. b2 abbreviates each # word of the toolset directory too, and msvc-14.3 and msvc-14.5 are their own abbreviations, @@ -614,6 +627,16 @@ def own_lane_profile(own: OwnLane) -> Lane: return own_lane_base(own.target) +def own_lane_toolsets(own: OwnLane) -> list[Lane]: + """The lanes whose toolsets the own lane's job registers, in order, the first b2's default: + the lane it shares, then, for one of EVERY_TARGET_LANES, the lanes of EVERY_TARGET_TOOLSETS.""" + lanes = [own_lane_profile(own)] + if (own.library, own.lane) in EVERY_TARGET_LANES: + known = {lane.id: lane for lane in LANES} + lanes += [known[lane_id] for lane_id in EVERY_TARGET_TOOLSETS] + return lanes + + def own_lane_entry(own: OwnLane) -> dict[str, object]: """The own lane as an entry of the own-lanes matrix: its library, its lane and its directories; its target and its id when it names one; and, for every entry, its kind, the name @@ -629,7 +652,10 @@ def own_lane_entry(own: OwnLane) -> dict[str, object]: # with it, and a driven test its driver. Without the CI's Node, one would run with the # image's own, another version. A lane of programs alone, a served one, needs none. node = base.node or own.kind == 'original' - entry.update(kind=own.kind, name=own.name, os=base.os, wasm=base.wasm, emsdk=base.emsdk, + wasm, emsdk = base.wasm, base.emsdk + if (own.library, own.lane) in EVERY_TARGET_LANES: + wasm = emsdk = node = True + entry.update(kind=own.kind, name=own.name, os=base.os, wasm=wasm, emsdk=emsdk, node=node, cc=base.cc, cxx=base.cxx, external=needs_external(own.library), chrome=(own.library, own.lane) in CHROME_LANES) return entry @@ -879,7 +905,9 @@ def run_lane(lane: Lane, user_config: Path, out_dir: Path, extra: list[str]) -> def run_own_lane(own: OwnLane, user_config: Path, out_dir: Path, extra: list[str]) -> int: """Runs the own lane, and returns its exit status.""" - register(resolved(own_lane_profile(own)), user_config) + # Each read first, so that one that cannot be read leaves user_config as it was. + for lane in [resolved(lane) for lane in own_lane_toolsets(own)]: + register(lane, user_config) if own.target is None: label = f'own lane {" ".join(own.requests)}' status = run_b2(label, own_lane_command(own, user_config, None, extra)) diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 81c22430..8439f3a7 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -523,6 +523,37 @@ def test_an_own_lanes_command(root): assert (lane.id, lane.os) == (lane_id, 'ubuntu-24.04'), lane +def test_an_every_target_lane_sets_up_and_registers_every_toolset(root): + # hash's own lane measure names no target and builds for the four targets in one command: + # its job installs wasi-sdk, wasmtime, emsdk and the CI's node, and registers Clang 18 + # first (b2's default toolset, the native target), then wasip2's, wasip3's and emscripten's + # toolsets, which its Jamfile names in the programs' references. No other own lane without a + # target gets them. + assert matrix.EVERY_TARGET_LANES == {('hash', 'measure')}, matrix.EVERY_TARGET_LANES + measure = matrix.parsed_own_lanes('hash measure libs/hash/test/measure programs')[0] + entry = own_lane_entry_of(measure) + assert (entry['wasm'], entry['emsdk'], entry['node']) == (True, True, True), entry + assert 'platform' not in entry and entry['name'] == 'Own lane (hash, measure)', entry + assert [lane.id for lane in matrix.own_lane_toolsets(measure)] == [ + 'clang-18', 'wasip2', 'wasip3', 'emscripten'] + config = root / 'config.jam' + assert matrix.own_lane_command(measure, config, None, []) == [ + 'b2', f'--user-config={config}', '-a', 'toolset=clang-18', + 'libs/hash/test/measure//measure'] + oracle = matrix.parsed_own_lanes('beta oracle libs/beta/test/oracle original')[0] + entry = own_lane_entry_of(oracle) + assert (entry['wasm'], entry['emsdk']) == (False, False), entry + assert [lane.id for lane in matrix.own_lane_toolsets(oracle)] == ['clang-18'] + config = boost_only(root) + for lane in matrix.own_lane_toolsets(measure): + matrix.register(matrix.resolved(lane), config) + text = config.read_text() + for line in ('using clang : 18 : clang++-18 ;', 'using clang : wasip2 :', + 'using clang : wasip3 :', 'using emscripten :'): + assert line in text, (line, text) + assert text.index('using clang : 18') < text.index('using clang : wasip2'), text + + def test_beast_browser_lanes_cover_policies_and_exception_modes(root): config = root / 'config.jam' options = ['exception-handling=on,off', 'webcpp-beast-unsupported=error,ignore'] @@ -1540,6 +1571,7 @@ def test_an_unavailable_container_image_fails_without_a_build(root): test_own_lanes_of_every_library_and_of_one, test_own_lanes_on_targets, test_an_own_lanes_command, + test_an_every_target_lane_sets_up_and_registers_every_toolset, test_beast_browser_lanes_cover_policies_and_exception_modes, test_asio_capability_lanes_cover_suspension_and_exception_modes, test_openssl_upstream_lanes_use_the_windows_builds, diff --git a/tools/doc/docinfo.html b/tools/doc/docinfo.html index 29d5eaa9..ff6fba18 100644 --- a/tools/doc/docinfo.html +++ b/tools/doc/docinfo.html @@ -174,11 +174,18 @@ column's header above its cell, from the data-label postprocess.mjs gives the cell; a table of two columns, a name and what it is, reads stacked without them. */ @media screen and (max-width: 56.1875em) { - table.tableblock, table.tableblock > tbody, table.tableblock > tbody > tr, - table.tableblock > tbody > tr > td, table.tableblock > tbody > tr > th { + table.tableblock, table.tableblock > tbody, table.tableblock > tbody > tr { display: block; width: auto; } + /* A cell, a block as wide as the row, breaks a word wider than its line, which Asciidoctor's + style for a table (word-wrap: normal) keeps whole past the row's frame. */ + table.tableblock > tbody > tr > td, table.tableblock > tbody > tr > th { + display: block; width: auto; overflow-wrap: break-word; + } table.tableblock > thead, table.tableblock > colgroup { display: none; } + /* The caption of a table laid out as a block is a block as wide as it: a table caption, an + anonymous table of its own, would be as narrow as its longest word. */ + table.tableblock > caption { display: block; } table.tableblock { border-width: 0; } table.tableblock > tbody > tr { border: 1px solid #dedede; margin-bottom: .75em; } table.tableblock > tbody > tr:last-child { margin-bottom: 0; } @@ -203,11 +210,14 @@ and its columns could no longer be compared, so wider than a phone it stays a table and scrolls in its box. */ .table-scroll.stacked > table.tableblock, .table-scroll.stacked > table.tableblock > tbody, -.table-scroll.stacked > table.tableblock > tbody > tr, +.table-scroll.stacked > table.tableblock > tbody > tr { display: block; width: auto; } .table-scroll.stacked > table.tableblock > tbody > tr > td, -.table-scroll.stacked > table.tableblock > tbody > tr > th { display: block; width: auto; } +.table-scroll.stacked > table.tableblock > tbody > tr > th { + display: block; width: auto; overflow-wrap: break-word; +} .table-scroll.stacked > table.tableblock > thead, .table-scroll.stacked > table.tableblock > colgroup { display: none; } +.table-scroll.stacked > table.tableblock > caption { display: block; } .table-scroll.stacked > table.tableblock { border-width: 0; } .table-scroll.stacked > table.tableblock > tbody > tr { border: 1px solid #dedede; margin-bottom: .75em; diff --git a/tools/doc/extensions_test.py b/tools/doc/extensions_test.py index fb22b588..5f7672cb 100755 --- a/tools/doc/extensions_test.py +++ b/tools/doc/extensions_test.py @@ -899,6 +899,33 @@ def test_the_table_of_contents_breaks_a_name_after_its_scopes(_: None) -> None: assert '>Boost.Hash2 and a_b' in toc, toc +def test_a_stacked_cell_breaks_a_word_wider_than_its_line(_: None) -> None: + # Asciidoctor's style gives a table no break inside a word (word-wrap: normal), which a cell + # inherits, and the page gives one back only to an AsciiDoc cell's content: a plain cell of a + # stacked row, a block as wide as the page, then holds a word wider than its line, such as a + # compiler's commit in a measured table, past the row's frame. On a phone, and in a box the + # script stacks, a cell breaks such a word, and only such a word. + for wanted in ('screen and (max-width: 56.1875em)', None): + cells = {selector: declarations for media, selectors, declarations in page_style() + if media == wanted for selector in selectors + if selector.endswith('table.tableblock>tbody>tr>td') + or selector.endswith('table.tableblock>tbody>tr>th')} + assert len(cells) == 2 and all( + declarations.get('overflow-wrap') == 'break-word' + for declarations in cells.values()), (wanted, cells) + + +def test_a_stacked_table_s_caption_is_as_wide_as_the_table(_: None) -> None: + # A table laid out as a block keeps its caption a table caption, an anonymous table of its + # own as narrow as its longest word ("Table 1." over four lines at 390px): on a phone, and in + # a box the script stacks, the caption is a block as wide as the table. + for wanted in ('screen and (max-width: 56.1875em)', None): + captions = [declarations for media, selectors, declarations in page_style() + if media == wanted for selector in selectors + if selector.endswith('table.tableblock>caption')] + assert captions and all(d.get('display') == 'block' for d in captions), (wanted, captions) + + def test_detail_macros_stay_out_of_the_reference(_: None) -> None: # A detail macro, WEBCPP__DETAIL_*, is the library's own business, as a detail # namespace is: the shared settings exclude it, and reference.py fails a reference that @@ -951,6 +978,8 @@ def test_detail_macros_stay_out_of_the_reference(_: None) -> None: test_a_table_too_wide_stacks_as_on_a_phone, test_a_key_column_keeps_room_for_its_words, test_the_table_of_contents_breaks_a_name_after_its_scopes, + test_a_stacked_cell_breaks_a_word_wider_than_its_line, + test_a_stacked_table_s_caption_is_as_wide_as_the_table, test_detail_macros_stay_out_of_the_reference, ] diff --git a/tools/hash/doc_tables.py b/tools/hash/doc_tables.py new file mode 100644 index 00000000..a99f19ab --- /dev/null +++ b/tools/hash/doc_tables.py @@ -0,0 +1,504 @@ +#!/usr/bin/env python3 +# 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 tables of webcpp::hash's guide, generated from its data (owner's documentation +requirements). + + python3 tools/hash/doc_tables.py --write [--library libs/hash] + python3 tools/hash/doc_tables.py --check [--library libs/hash] + +Reads, in the library's doc/: capabilities.json (which backend implements each public name, on +which targets, over which hmacs, with its constant time: Task 14), guide.json (what the guide +says of each name that no test produces: its use, its security and where the world uses it, each +with a source, and the rows of "Choose by use case"), and, when they are there, +measurements.json (each program's size per target and its throughput, and the orders that +detail/ranking.hpp is generated from: tools/hash/measure.py, Task 21). It writes, in doc/: + +- generated/compare-.adoc: the comparison that opens each chapter, two tables with a + row per public name: what it is (output, security, standard, status, the browser's + WebCrypto), and how to choose it (from measurements.json, its throughput natively and its + smallest program on Emscripten, then where it is used, each with its source, and when to + choose it); +- generated/backends-.adoc: the backends of each algorithm, from the capability + table (backend, the Jamfile line, targets, hmacs, constant time), and, for an algorithm whose + backend the profile chooses, the order of each profile on each target from measurements.json; +- generated/choose.adoc: the decision table "Choose by use case", whose backend column is the + capability table's; +- generated/measured.adoc: the includes of the data chapters other tools generate, + backends.adoc and measurements.adoc (tools/hash/measure.py), performance.adoc + (bench/collect.py) and allocation.adoc (bench/allocation_collect.py), each one that is there; +- llms.txt: the guide's index for language models, installed beside the page. + +--check renders the same files from the same data and fails, naming +`python3 tools/hash/doc_tables.py --write`, when one differs from what is committed, is +missing, or is left over; the doc build runs it (doc/Jamfile). It also fails when guide.json +lacks a public name of the capability table, names one it does not have, or a use case names +an example that example/ does not hold. Nothing in the output depends on the time or the +machine, so the files change only with their data. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +WRITE = 'python3 tools/hash/doc_tables.py --write' +LICENCE = ('// Copyright (c) 2026 WebCpp.org\n' + '//\n' + '// Distributed under the Boost Software License, Version 1.0. (See\n' + '// accompanying file LICENSE_1_0.txt or copy at\n' + '// https://www.boost.org/LICENSE_1_0.txt)\n') +# The chapters of the measured data, in the order the guide shows them, and the tool that +# writes each. +MEASURED_CHAPTERS = ( + ('backends.adoc', 'tools/hash/measure.py --capabilities'), + ('measurements.adoc', 'tools/hash/measure.py --write'), + ('performance.adoc', 'bench/collect.py'), + ('allocation.adoc', 'bench/allocation_collect.py'), +) +WASM = ('wasip2', 'wasip3', 'emscripten') +# Spec 4.1's profiles, in the order the tables list them. +PROFILES = ('auto', 'fastest', 'smallest', 'portable') +# The chapters whose throughput is a rate over 1 MiB (tools/hash/measure.py's workloads). +RATE_CHAPTERS = ('digests', 'macs', 'non-cryptographic') + + +class Failure(Exception): + """A fault of the data, which --write and --check both report.""" + + +def load(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding='utf-8')) + except (OSError, ValueError) as error: + raise Failure(f'{path}: {error}') from error + + +def generated_header(sources: str) -> str: + return f'{LICENCE}\n// Generated by tools/hash/doc_tables.py from {sources}: do not edit.\n' + + +def cell(text: str) -> str: + """A table cell's text: a | would end the cell.""" + return text.replace('|', '{vbar}') + + +def link(text: str, url: str) -> str: + return f'link:{url}[{text.replace("]", "]")}]' + + +class Data: + """The capability table, the guide's facts and the measurements, joined.""" + + def __init__(self, library: Path) -> None: + self.library = library + doc = library / 'doc' + self.capabilities = load(doc / 'capabilities.json') + self.guide = load(doc / 'guide.json') + measured = doc / 'measurements.json' + self.measurements = load(measured) if measured.is_file() else None + self.backends = {b['name']: b for b in self.capabilities['backends']} + self.functions: dict[str, tuple[dict, dict]] = {} + for algorithm in self.capabilities['algorithms']: + for function in algorithm['functions']: + self.functions[function['name']] = (algorithm, function) + self.check_guide() + + def check_guide(self) -> None: + facts = self.guide['functions'] + missing = [name for name in self.functions if name not in facts] + extra = [name for name in facts if name not in self.functions] + faults = [f'doc/guide.json has no entry for {name}, a function of ' + f'doc/capabilities.json' for name in missing] + faults += [f'doc/guide.json describes {name}, which doc/capabilities.json does not ' + f'have' for name in extra] + chapters = {a['chapter'] for a in self.capabilities['algorithms']} + listed = [c['chapter'] for c in self.guide['chapters']] + faults += [f'doc/guide.json has no chapter {c} of doc/capabilities.json' + for c in sorted(chapters - set(listed))] + for case in self.guide['use_cases']: + if case['function'] not in self.functions: + faults.append(f'doc/guide.json: the use case "{case["need"]}" names ' + f'{case["function"]}, which doc/capabilities.json does not have') + if not (self.library / 'example' / case['example']).is_file(): + faults.append(f'doc/guide.json: the use case "{case["need"]}" names ' + f'example/{case["example"]}, which is not there') + if faults: + raise Failure('\n'.join(faults)) + + def records(self, operation: str) -> list[dict]: + if self.measurements is None: + return [] + return [r for r in self.measurements['records'] if r['operation'] == operation] + + def order(self, operation: str, hmac: str | None, target: str, by: str) -> list[str] | None: + if self.measurements is None: + return None + for row in self.measurements['orders']: + if (row['operation'], row['hmac'], row['target']) == (operation, hmac, target): + return list(row[by]) + return None + + +def rate(ns: float) -> str: + return f'{1e9 / ns:,.0f} MiB/s' + + +def duration(ns: float) -> str: + if ns >= 1e6: + return f'{ns / 1e6:.1f} ms' + if ns >= 1e3: + return f'{ns / 1e3:.2f} µs' + return f'{ns:.0f} ns' + + +def fastest_native(data: Data, name: str, chapter: str) -> str: + """The best native median of the function's records, over hmac_sha2_256 for a KDF, with + its backend.""" + found = [r for r in data.records(name) + if r['target'] == 'native' and r['throughput'] + and r['hmac'] in (None, 'hmac_sha2_256')] + if not found: + return '-' + best = min(found, key=lambda r: r['throughput']['median_ns']) + ns = best['throughput']['median_ns'] + value = rate(ns) if chapter in RATE_CHAPTERS else duration(ns) + return f'{value} ({best["backend"]})' + + +def smallest_emscripten(data: Data, name: str) -> str: + found = [r for r in data.records(name) + if r['target'] == 'emscripten' and r['size_bytes'] + and r['hmac'] in (None, 'hmac_sha2_256')] + if not found: + return '-' + best = min(found, key=lambda r: r['size_bytes']) + return f'{best["size_bytes"]:,} bytes ({best["backend"]})' + + +def compare_table(data: Data, chapter: dict) -> str: + key = chapter['chapter'] + m = data.measurements + measured = m is not None + out = [generated_header('doc/capabilities.json, doc/guide.json and doc/measurements.json'), + ''] + # Two tables, what each function is and how to choose it, each led by the name: one of all + # their columns would be a matrix (tools/doc/postprocess.mjs), which scrolls in its box. + facts_columns = ['Name', 'Output', 'Security', 'Standard', 'Status', + 'In the browser (WebCrypto)'] + choice_columns = ['Name'] + (['Fastest natively', 'Smallest on Emscripten'] if measured + else []) + ['Where it is used', 'Choose it when'] + facts_rows: list[list[str]] = [] + choice_rows: list[list[str]] = [] + for algorithm in data.capabilities['algorithms']: + if algorithm['chapter'] != key: + continue + for function in algorithm['functions']: + name = function['name'] + facts = data.guide['functions'][name] + uses = '; '.join(link(cell(u['text']), u['source']) for u in facts['uses']) + named = f'<<{facts["anchor"]},`{name}`>>' + facts_rows.append([named, facts['output'], facts['security'], + facts.get('standard', algorithm['standard']), facts['status'], + facts['webcrypto'] or 'no']) + choice_rows.append([named] + ([fastest_native(data, name, key), + smallest_emscripten(data, name)] if measured + else []) + [uses, facts['choose']]) + tables = ((f'[#{chapter["anchor"]}-compare]', f'What each of "{chapter["title"]}" is', + ['2', '1', '3', '2', '1', '2'], facts_columns, facts_rows), + (f'[#{chapter["anchor"]}-choose]', f'How to choose among "{chapter["title"]}"', + ['2'] + (['2', '2'] if measured else []) + ['4', '4'], choice_columns, + choice_rows)) + for anchor, title, widths, columns, rows in tables: + out.append(anchor) + out.append(f'.{title}') + out.append(f'[cols="{",".join(widths)}",options="header"]') + out.append('|===') + out.append(' '.join(f'| {c}' for c in columns)) + for row in rows: + out.append('') + out.extend(f'| {cell(value)}' if not value.startswith('link:') and '<<' not in value + else f'| {value}' for value in row) + out.append('|===') + out.append('') + if m is not None: + out.append(f'The measured columns are doc/measurements.json\'s ({m["date"]}, ' + f'{m["machine"]["cpu"]}): the native throughput over 1 MiB, or the time of ' + 'one derivation over `hmac_sha2_256`, of the fastest backend, and the ' + 'smallest Emscripten program that calls the function; <> ' + 'has every backend on every target.' + + (' The data was measured on a loaded, shared machine, so close figures may ' + 'swap at the next measurement.' if m.get('loaded') else '')) + else: + out.append('The measured columns, throughput natively and the size of a program on ' + 'Emscripten, come from doc/measurements.json, which this build of the guide ' + 'does not have yet.') + out.append('') + return '\n'.join(out) + + +def backend_targets(data: Data, backend: str) -> str: + return ', '.join(data.backends[backend]['targets']) + + +def hmacs_text(hmacs: list[str] | None) -> str: + if hmacs is None: + return '-' + return ', '.join('any other Hash2 hash (`hmac`)' if h == 'other' else f'`{h}`' + for h in hmacs) + + +def first_with(order: list[str], having: set[str]) -> str: + return next((b for b in order if b in having), '-') + + +def defaults_rows(data: Data, function: dict) -> list[str]: + """Per target, the order of each profile, every backend linked: the function's own rows + of measurements.json (each HKDF step is measured and ordered alone, as detail/ranking.hpp + orders it), kept to the backends that have this function.""" + having = set(function['backends']) + operation = function['name'] + portable = [b['name'] for b in data.capabilities['backends'] if b['portable']] + rows = [] + for target in data.capabilities['targets']: + present = {b for b in having if target in data.backends[b]['targets']} + if not present: + continue + hmac = 'hmac_sha2_256' if function['kind'] == 'function' and \ + next(iter(function['backends'].values()))['hmacs'] is not None else None + by_size = data.order(operation, hmac, target, 'by_size') + by_speed = data.order(operation, hmac, target, 'by_throughput') + if by_size is None or by_speed is None: + continue + size = [b for b in by_size if b in present] + speed = [b for b in by_speed if b in present] + auto = size if target in WASM else speed + rows.append('') + rows.append(f'| {target}') + rows.append(f'| {", ".join(auto)}') + rows.append(f'| {", ".join(speed)}') + rows.append(f'| {", ".join(size)}') + rows.append(f'| {first_with(portable, present)}') + return rows + + +def backends_table(data: Data, algorithm: dict) -> str: + out = [generated_header('doc/capabilities.json and doc/measurements.json'), ''] + out.append(f'[#hash-backends-of-{algorithm["name"].replace("_", "-")}]') + names = [f['name'] for f in algorithm['functions']] + shown = ', '.join(f'`{n}`' for n in names) if len(names) <= 3 else \ + f'`{names[0]}` to `{names[-1]}`, {len(names)} names' + out.append(f'.Who implements {shown} ({algorithm["standard"]})') + out.append('[cols="2,1,2,2,3,1",options="header"]') + out.append('|===') + out.append('| Function | Backend | The program\'s Jamfile names | Targets | Hmacs ' + '| Constant time') + for function in algorithm['functions']: + for backend, held in function['backends'].items(): + out.append('') + out.append(f'| `{function["name"]}`') + out.append(f'| `{backend}`') + out.append(f'| `{data.backends[backend]["jamfile"]}`') + out.append(f'| {backend_targets(data, backend)}') + out.append(f'| {hmacs_text(held["hmacs"])}') + out.append(f'| {held["constant_time"]["value"]}') + out.append('|===') + out.append('') + sources = sorted({(backend, held['constant_time']['source']) + for function in algorithm['functions'] + for backend, held in function['backends'].items()}) + out.append('What each backend states on constant time, as the capability table read it:') + out.append('') + out.extend(f'* `{backend}`: {cell(source)}' for backend, source in sources) + out.append('') + if not algorithm['overridable']: + names = sorted({b for f in algorithm['functions'] for b in f['backends']}) + out.append(f'One backend, {", ".join(f"`{n}`" for n in names)}: no profile or ' + 'override changes it.') + out.append('') + return '\n'.join(out) + for function in algorithm['functions']: + rows = defaults_rows(data, function) + if not rows: + out.append(f'The default backend of `{function["name"]}` on each target follows ' + 'the measured orders of doc/measurements.json, which this build of the ' + 'guide does not have yet; until then, the order of ' + '`detail/ranking.hpp` applies.') + out.append('') + continue + out.append(f'.The default backend of `{function["name"]}`: the first linked backend ' + 'of each order') + out.append('[cols="1,2,2,2,1",options="header"]') + out.append('|===') + out.append('| Target | auto (no profile) | fastest | smallest | portable') + out.extend(rows) + out.append('|===') + out.append('') + has_hmac = any(held['hmacs'] is not None for function in algorithm['functions'] + for held in function['backends'].values()) + over = ('The orders shown are those over `hmac_sha2_256`, and over every hmac the table ' + 'does not measure; `hmac_sha2_512` has its own orders, which can differ ' + '(<>). ') if has_hmac else '' + out.append(f'{over}Each order is measured with every backend linked; a backend ' + 'the program does not link is skipped. A named profile, ' + '`WEBCPP_HASH_PROFILE_BACKEND_`, or an override, ' + f'`WEBCPP_HASH_DEFAULT_BACKEND_{algorithm["macro"]}_`, takes its backend ' + 'where it has the function (<>).') + out.append('') + return '\n'.join(out) + + +def choose_table(data: Data) -> str: + out = [generated_header('doc/guide.json and doc/capabilities.json'), ''] + out.append('[#hash-choose-table]') + out.append('[cols="3,3,2,2,2",options="header"]') + out.append('|===') + out.append('| I need to ... | Use | Its backends: the Jamfile names | Profile ' + '| Example') + for case in data.guide['use_cases']: + _, function = data.functions[case['function']] + jamfiles = ', '.join(f'`{b}`: `{data.backends[b]["jamfile"]}`' + for b in function['backends']) + out.append('') + out.append(f'| {cell(case["need"])}') + out.append(f'| <<{case["anchor"]},{cell(case["use"])}>>') + out.append(f'| {jamfiles}') + out.append(f'| {cell(case["profile"])}') + out.append(f'| `example/{case["example"]}`') + out.append('|===') + out.append('') + return '\n'.join(out) + + +def measured_includes(data: Data) -> str: + out = [generated_header('the data chapters present in doc/'), ''] + missing = [] + for name, tool in MEASURED_CHAPTERS: + if (data.library / 'doc' / name).is_file(): + out.append(f'include::../{name}[]') + out.append('') + else: + missing.append(f'`doc/{name}` ({tool})') + if missing: + out.append('[NOTE]') + out.append('====') + out.append('This build of the guide does not have ' + ', '.join(missing) + + ' yet: the matrices they hold join the guide here once their data is ' + 'committed.') + out.append('====') + out.append('') + return '\n'.join(out) + + +def llms_txt(data: Data) -> str: + page = data.guide['page'] + lines = ['# webcpp::hash', '', + '> Hashing and key derivation for C++20 on every target webcpp has (native, ' + 'wasip2, wasip3, Emscripten): Boost.Hash2\'s digests and HMAC, Keccak-256, BLAKE3, ' + 'HKDF, PBKDF2, Argon2id and scrypt over C backends. Every function is synchronous, ' + 'returns boost::system::result and allocates nothing in webcpp\'s own code. A ' + 'program links /webcpp/hash//hash and the library of each backend it uses.', '', + 'Primitives only: protocol steps (BIP39, hash160, EIP-55, Nostr ids, NIP-44) ' + 'are what a domain library builds from these functions; the guide shows them as ' + 'examples, never as this library\'s API.', '', + f'- [The guide]({page}): every chapter, example and table', + f'- [Choose by use case]({page}#hash-choose): a decision table, need to ' + 'function, backend and example', ''] + for chapter in data.guide['chapters']: + lines.append(f'## {chapter["title"]}') + lines.append('') + lines.append(f'{chapter["summary"]} [{chapter["title"]}]({page}#{chapter["anchor"]})') + lines.append('') + for algorithm in data.capabilities['algorithms']: + if algorithm['chapter'] != chapter['chapter']: + continue + for function in algorithm['functions']: + facts = data.guide['functions'][function['name']] + backends = ', '.join(f'{b} ({data.backends[b]["jamfile"]}; ' + f'{backend_targets(data, b)})' + for b in function['backends']) + standard = facts.get('standard', algorithm['standard']) + lines.append(f'- webcpp::hash::{function["name"]} ' + f'(<{function["header"]}>, {standard}): ' + f'{facts["summary"]} Status: {facts["status"]}. ' + f'Choose it: {facts["choose"]} Backends: {backends}. ' + f'[Section]({page}#{facts["anchor"]})') + lines.append('') + lines.append('## Choose by use case') + lines.append('') + for case in data.guide['use_cases']: + lines.append(f'- I need to {case["need"]}: {case["use"]}; backend: {case["profile"]}; ' + f'example libs/hash/example/{case["example"]}. ' + f'[Section]({page}#{case["anchor"]})') + lines.append('') + lines.append('## Data') + lines.append('') + lines.append('- doc/capabilities.json: which backend implements each function, on which ' + 'targets, over which hmacs, and its constant time') + lines.append('- doc/measurements.json: each backend\'s program size per target and its ' + 'throughput') + lines.append('') + return '\n'.join(lines) + + +def render(data: Data) -> dict[str, str]: + """Every generated file, by its path relative to the library's doc/.""" + files: dict[str, str] = {} + for chapter in data.guide['chapters']: + files[f'generated/compare-{chapter["chapter"].replace("_", "-")}.adoc'] = \ + compare_table(data, chapter) + for algorithm in data.capabilities['algorithms']: + files[f'generated/backends-{algorithm["name"].replace("_", "-")}.adoc'] = \ + backends_table(data, algorithm) + files['generated/choose.adoc'] = choose_table(data) + files['generated/measured.adoc'] = measured_includes(data) + files['llms.txt'] = llms_txt(data) + return files + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=(__doc__ or '').split('\n')[0]) + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument('--write', action='store_true') + mode.add_argument('--check', action='store_true') + parser.add_argument('--library', default=str(ROOT / 'libs' / 'hash')) + arguments = parser.parse_args(argv) + library = Path(arguments.library) + doc = library / 'doc' + try: + files = render(Data(library)) + except Failure as failure: + print(f'doc_tables.py: {failure}', file=sys.stderr) + return 1 + present = {str(p.relative_to(doc)) for p in (doc / 'generated').glob('*.adoc')} + if arguments.write: + (doc / 'generated').mkdir(exist_ok=True) + for name in present - set(files): + (doc / name).unlink() + for name, text in files.items(): + (doc / name).write_text(text, encoding='utf-8') + return 0 + faults = [] + for name, text in files.items(): + path = doc / name + if not path.is_file(): + faults.append(f'doc/{name} is missing') + elif path.read_text(encoding='utf-8') != text: + faults.append(f'doc/{name} differs from what its data renders') + faults += [f'doc/{name} is left over: no data renders it' + for name in sorted(present - set(files))] + for fault in faults: + print(f'doc_tables.py: {fault}; run `{WRITE}`', file=sys.stderr) + return 1 if faults else 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/hash/measure.py b/tools/hash/measure.py new file mode 100644 index 00000000..6987a43c --- /dev/null +++ b/tools/hash/measure.py @@ -0,0 +1,1357 @@ +#!/usr/bin/env python3 +# 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) + +"""webcpp::hash's measured table (spec section 4.2), and the files generated from it. + + python3 tools/hash/measure.py --write [--invocations N] [--jobs N] + python3 tools/hash/measure.py --check --programs ... + python3 tools/hash/measure.py --capabilities + python3 tools/hash/measure.py --overrides + +Run from anywhere; paths in messages are relative to the superproject. Every cell of +libs/hash/doc/capabilities.json (a function on a backend; a key derivation over hmac_sha2_256 +and over hmac_sha2_512) has one program, test/measure/_.cpp, built on every +target of its backend at variant=release optimization=space (its size: the native executable +stripped with `strip`, or the .wasm) and at optimization=speed (its throughput, the median of +five runs per invocation, natively and on each WebAssembly target where the program ends within +BOUND seconds). + +--write builds every program with b2 (the target measure-programs of test/measure/Jamfile, in +--build-dir), measures each, and writes doc/measurements.json (the data, with the machine, +compilers, runtimes, date, pins and a digest of its content), doc/measurements.adoc (its tables, +the orders and the default the owner's rule gives), include/webcpp/hash/detail/ranking.hpp (per +target and algorithm, the backends by size and by throughput), and the files generated from the +capability table alone: detail/overrides.hpp (--overrides), doc/backends.adoc (--capabilities) +and test/measure/cells.jam (the programs). `--measured FILE` takes the measurements from FILE, +in the shape of doc/measurements.json, instead of making them. + +--check is the measure lane's (test/measure/Jamfile): it re-measures every program for size b2 +built (the lists the lane writes, one per target), each run once, and fails, naming +`python3 tools/hash/measure.py --write`, when a program of a cell is missing on a target (the +lane built nothing), when a result differs from the committed one or from the independent value +Python computes, when the order by size of any row differs from the committed one, when a +generated file differs from what the committed data renders (a hand edit), or when the data's +digest does not match (a hand edit of the data). With `--measured`, it compares those +measurements instead, throughput included. It also runs bench/'s correctness program, which the +lists name, on every target: it must exit 0. + +The orders follow spec 4.2 and nothing else. By size, the smallest program first. +By throughput, the lowest median (of the invocations' medians) first; a committed order changes +only where a backend's median is more than 10 percent below the median of the one ahead of it; +on a first measurement the medians alone order it, an exact tie keeping the capability table's +order of backends. A WebAssembly target orders by its own throughput where every backend of the +row ran within the bound, else by the native order. The native orders are those of the native +toolchain that measured them (native_toolchain in the data): a lane whose native toolchain is +another builds and checks every native program and result, and says in one line that it does not +compare the native orders; the WebAssembly orders, whose toolchains are pinned, are +always compared. +""" + +from __future__ import annotations + +import argparse +import concurrent.futures +import copy +import datetime +import hashlib +import hmac as python_hmac +import json +import os +import platform +import re +import shlex +import shutil +import statistics +import subprocess +import sys +import tempfile +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +WRITE = 'python3 tools/hash/measure.py --write' +TARGETS = ('native', 'wasip2', 'wasip3', 'emscripten') +OPTIMIZATIONS = ('space', 'speed') +WASM = ('wasip2', 'wasip3', 'emscripten') +# Spec 4.2: a key derivation is measured over these two hmacs. +MEASURED_HMACS = ('hmac_sha2_256', 'hmac_sha2_512') +# The library that every program names already (test/measure/Jamfile's project). +HASH_JAMFILE = '/webcpp/hash//hash' +# A WebAssembly program's throughput counts when one invocation ends within this many seconds. +BOUND = 120 +# bench/'s correctness program derives 1,000,000 iterations per variant: its own bound. +BENCH_BOUND = 900 +# The invocations of each program for throughput, the committed table's method. +INVOCATIONS = 5 +# Spec 4.2: a committed order by throughput changes only when a median moves past this fraction. +MARGIN = 0.10 + +LAUNCHERS = { + 'native': [], + 'wasip2': [str(ROOT / 'tools/boost/asio-wasip2/run.sh')], + 'wasip3': [str(ROOT / 'tools/boost/asio-wasip3/run.sh')], + 'emscripten': ['node'], # replaced by the toolset's node, which the lane's list names +} + +LICENCE_SLASHES = """// 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) +""" +LICENCE_HASH = '\n'.join('#' + line[2:] for line in LICENCE_SLASHES.splitlines()) + '\n' + +RULES = { + 'size': 'the bytes of the program built at variant=release optimization=space: natively the ' + 'executable stripped with strip, on WebAssembly the .wasm file', + 'throughput': 'the program built at variant=release optimization=speed, run with --time: one ' + 'computation to warm up, then five timed runs of the workload, each repeated ' + '`repetitions` times; per invocation the median of its five runs, per record ' + 'the median of its invocations\' medians, with the fastest and slowest run', + 'order': 'spec 4.2: by size, the smallest program first; by throughput, the lowest median ' + 'of the invocations\' medians first, a committed order changing only where a ' + 'median is more than 10 percent below the median of the backend ahead of it; on a ' + 'first measurement, the medians alone (an exact tie keeps the capability table\'s ' + 'order of backends). A WebAssembly target orders by its own throughput where every ' + 'backend of the row ran within the bound, else by the native order. The native ' + 'orders hold for the native toolchain that measured them (native_toolchain); the ' + 'lane compares them only on that toolchain.', + 'loaded': 'the larger of the two 1-minute load averages exceeds the core count', +} + +LAYOUT = { + 'schema': 'This description. The version of the layout is "version"; a change of layout ' + 'raises it. Written only by tools/hash/measure.py; "digest" is the SHA-256 of the ' + 'file without it, which the measure lane checks.', + 'date, machine, load_average_before_after, loaded, rules.loaded': 'when and where the ' + 'measurements were made; loaded says whether the machine was shared and loaded', + 'toolchains, runtimes, strip, pins, builds': 'the compiler per target, wasmtime and node, ' + 'the strip of the native sizes, each backend\'s library and pin (from ' + 'doc/capabilities.json), and the two builds', + 'native_toolchain': 'what the native orders were measured with: the compiler, the host\'s ' + 'operating system and processor, and the strip; the lane compares the native ' + 'size orders only where its own is the same', + 'workloads': 'per function, what one computation does (spec 4.2)', + 'records[]': 'one per cell and target: operation (the function of doc/capabilities.json), ' + 'hmac (or null), backend, target, size_bytes, result (the hexadecimal output, ' + 'the same for every backend and target of an operation and hmac), throughput ' + '(repetitions, invocations, runs_per_invocation, invocation_medians_ns, ' + 'median_ns, min_ns, max_ns: nanoseconds per computation) or null with ' + 'throughput_absent saying why. operation, hmac, backend and target are the keys ' + 'of doc/measurements.throughput.json\'s cases too, which the documentation joins ' + 'on them; constant time is doc/capabilities.json\'s.', + 'orders[]': 'per operation, hmac and target: by_size and by_throughput, the backends that ' + 'have it there in order, and throughput_from, the target whose throughput ' + 'ordered it; detail/ranking.hpp is generated from the rows of the key ' + 'derivations, one per operation (hkdf_extract and hkdf_expand their own)', + 'rules': 'how sizes, throughput and orders are made', +} + + +class Failure(Exception): + """A failure of the check or of a measurement, its message for the person.""" + + +class Usage(Exception): + """A wrong use of the command.""" + + +@dataclass(frozen=True) +class Cell: + """One program: a function on a backend, over an hmac or none.""" + + function: str + backend: str + hmac: str | None + targets: tuple[str, ...] + library: str | None + + @property + def id(self) -> str: + return f'{self.function}_{self.backend}' + (f'_{self.hmac}' if self.hmac else '') + + @property + def source(self) -> str: + return f'{self.function}_{self.backend}.cpp' + + @property + def key(self) -> tuple[str, str | None, str]: + return (self.function, self.hmac, self.backend) + + +class Table: + """doc/capabilities.json, read for what the measured table needs.""" + + def __init__(self, data: dict) -> None: + self.data = data + self.backends = data['backends'] + self.backend_names = [b['name'] for b in self.backends] + self.backend = {b['name']: b for b in self.backends} + self.tagged = [b['name'] for b in self.backends if b['tag']] + self.algorithms = data['algorithms'] + self.functions = [(a, f) for a in self.algorithms for f in a['functions']] + self.function_names = [f['name'] for _, f in self.functions] + + def cells(self) -> list[Cell]: + cells = [] + for _, function in self.functions: + for name in self.backend_names: + cell = function['backends'].get(name) + if cell is None: + continue + backend = self.backend[name] + hmacs = [h for h in MEASURED_HMACS if h in (cell['hmacs'] or [])] + library = None if backend['jamfile'] == HASH_JAMFILE else backend['jamfile'] + for hmac in hmacs or [None]: + cells.append(Cell(function['name'], name, hmac, tuple( + t for t in TARGETS if t in backend['targets']), library)) + return cells + + def kdf_rows(self) -> list[tuple[dict, dict]]: + """The (algorithm, function) whose rows ranking.hpp holds: every function of an + overridable algorithm that has a tag, each operation its own row (hkdf_extract and + hkdf_expand beside hkdf), which the default of that operation reads.""" + return [(a, f) for a, f in self.functions if a['overridable'] and f.get('tag')] + + def chapter_of(self, function: str) -> str: + return next(a['chapter'] for a, f in self.functions if f['name'] == function) + + def function(self, name: str) -> dict: + return next(f for _, f in self.functions if f['name'] == name) + + +def read_json(path: Path) -> dict: + with path.open(encoding='utf-8') as f: + return json.load(f) + + +def json_text(data: dict) -> str: + return json.dumps(data, indent=2, ensure_ascii=False) + '\n' + + +def relative(path: Path) -> str: + try: + return str(path.resolve().relative_to(ROOT)) + except ValueError: + return str(path) + + +# --------------------------------------------------------------------------------------------- +# The workloads, and the values Python computes independently. + + +def pattern(n: int, a: int, b: int) -> bytes: + return bytes((a * i + b) % 256 for i in range(n)) + + +MESSAGE = pattern(1 << 20, 31, 7) +KEY = pattern(32, 13, 1) +SALT = pattern(32, 17, 3) +SECRET = pattern(32, 19, 5) +INFO = pattern(16, 23, 11) +PRK = pattern(64, 29, 13) +OUTPUT = 32 +PBKDF2_ITERATIONS = 100_000 +SCRYPT = (16384, 8, 1) + +PYTHON_HASHES = { + 'md5_128': 'md5', 'sha1_160': 'sha1', 'sha2_224': 'sha224', 'sha2_256': 'sha256', + 'sha2_384': 'sha384', 'sha2_512': 'sha512', 'sha2_512_224': 'sha512_224', + 'sha2_512_256': 'sha512_256', 'sha3_224': 'sha3_224', 'sha3_256': 'sha3_256', + 'sha3_384': 'sha3_384', 'sha3_512': 'sha3_512', 'blake2b_512': 'blake2b', + 'blake2s_256': 'blake2s', 'ripemd_160': 'ripemd160', +} + + +def workload(table: Table, function: str) -> str: + chapter = table.chapter_of(function) + if function == 'hkdf_extract': + return 'HKDF-Extract of a 32-byte IKM with a 32-byte salt, repeated 1,000 times' + if function == 'hkdf_expand': + return ('HKDF-Expand of 32 bytes from a digest-size PRK and a 16-byte info, repeated ' + '1,000 times') + if function == 'hkdf': + return ('HKDF of 32 bytes from a 32-byte IKM, a 32-byte salt and a 16-byte info, ' + 'repeated 1,000 times') + if function == 'pbkdf2': + return 'PBKDF2 of 32 bytes from a 16-byte password and salt at 100,000 iterations' + if function == 'argon2id': + return ('Argon2id of 32 bytes from a 16-byte password and salt at libsodium\'s ' + 'interactive costs (2 passes over 64 MiB)') + if function == 'scrypt': + return 'scrypt of 32 bytes from a 16-byte password and salt at N=16384, r=8, p=1 (16 MiB)' + if chapter == 'macs': + return 'the MAC of 1 MiB under a 32-byte key' + return 'the hash of 1 MiB' + + +def python_value(function: str, hmac: str | None) -> str | None: + """The result Python computes for the function, or None when it has none of its own.""" + try: + if function in PYTHON_HASHES: + return hashlib.new(PYTHON_HASHES[function], MESSAGE).hexdigest() + if function in ('fnv1a_32', 'fnv1a_64'): + bits = int(function[6:]) + prime, value = ((0x01000193, 0x811c9dc5) if bits == 32 else + (0x100000001b3, 0xcbf29ce484222325)) + for byte in MESSAGE: + value = ((value ^ byte) * prime) % (1 << bits) + return f'{value:0{bits // 4}x}' + if function == 'shake_128': + return hashlib.shake_128(MESSAGE).hexdigest(168) + if function == 'shake_256': + return hashlib.shake_256(MESSAGE).hexdigest(136) + if function.startswith('hmac_') and function[5:] in PYTHON_HASHES: + name = PYTHON_HASHES[function[5:]] + return python_hmac.new(KEY, MESSAGE, lambda d=b'': hashlib.new(name, d)).hexdigest() + if function == 'hmac': + return python_hmac.new(KEY, MESSAGE, hashlib.sha256).hexdigest() + if hmac is not None: + name = PYTHON_HASHES[hmac[5:]] + digest = hashlib.new(name).digest_size + + def mac(key: bytes, data: bytes) -> bytes: + return python_hmac.new(key, data, lambda d=b'': hashlib.new(name, d)).digest() + + def expand(prk: bytes) -> bytes: + out, block = b'', b'' + for i in range(1, -(-OUTPUT // digest) + 1): + block = mac(prk, block + INFO + bytes([i])) + out += block + return out[:OUTPUT] + + if function == 'hkdf_extract': + return mac(SALT, SECRET).hex() + if function == 'hkdf_expand': + return expand(PRK[:digest]).hex() + if function == 'hkdf': + return expand(mac(SALT, SECRET)).hex() + if function == 'pbkdf2': + return hashlib.pbkdf2_hmac(name, SECRET[:16], SALT[:16], PBKDF2_ITERATIONS, + OUTPUT).hex() + if function == 'scrypt': + n, r, p = SCRYPT + return hashlib.scrypt(SECRET[:16], salt=SALT[:16], n=n, r=r, p=p, + maxmem=64 << 20, dklen=OUTPUT).hex() + except (ValueError, AttributeError, KeyError): + return None + return None + + +# --------------------------------------------------------------------------------------------- +# Measuring. + + +def tool_version(command: list[str]) -> str: + try: + done = subprocess.run(command, capture_output=True, text=True, check=False) + return (done.stdout or done.stderr).strip().splitlines()[0] + except (OSError, IndexError): + return 'unknown' + + +def sysctl(name: str) -> str: + try: + return subprocess.run(['sysctl', '-n', name], capture_output=True, text=True, + check=False).stdout.strip() + except OSError: + return '' + + +def machine() -> dict[str, Any]: + memory = sysctl('hw.memsize') + if not memory and hasattr(os, 'sysconf'): + try: + memory = str(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')) + except (ValueError, OSError): + memory = '0' + return { + 'cpu': sysctl('machdep.cpu.brand_string') or platform.processor() or platform.machine(), + 'cores': os.cpu_count(), + 'memory_gib': int(memory or 0) // 2**30, + 'os': f'{platform.system()} {platform.release()}', + } + + +@dataclass +class Program: + cell: Cell + target: str + optimization: str + path: Path + + +def programs_of(table: Table, lists: list[Path], required: tuple[str, ...] + ) -> tuple[list[Program], list[tuple[str, Path]]]: + """The programs the lane's lists name, and bench/'s (target, path); fails naming each cell + whose program of an optimization of required is missing on a target. A list + measure-launcher-emscripten.txt names the command that runs a program on Emscripten, the + node of b2's emscripten toolset.""" + cells = {c.id: c for c in table.cells()} + found: dict[tuple[str, str, str], Program] = {} + bench: list[tuple[str, Path]] = [] + for path in lists: + if path.name == 'measure-launcher-emscripten.txt': + words = path.read_text(encoding='utf-8').split(None, 1) + if len(words) != 2 or words[0] != 'launcher': + raise Failure(f'{relative(path)} names no launcher: b2\'s emscripten toolset ' + 'was configured without node') + LAUNCHERS['emscripten'] = shlex.split(words[1]) + continue + match = re.fullmatch(r'measure-programs-([a-z0-9]+)-([a-z]+)\.txt', path.name) + if not match or match[1] not in TARGETS or match[2] not in OPTIMIZATIONS + ('bench',): + raise Usage(f'{path}: not a list of the measure lane, ' + 'measure-programs--.txt') + target, optimization = match[1], match[2] + for line in path.read_text(encoding='utf-8').splitlines(): + if not line.strip(): + continue + program = Path(line.strip()) + if not program.is_absolute(): + program = ROOT / program + if optimization == 'bench': + bench.append((target, program)) + continue + stem = program.name + for suffix in ('.wasm', '.js', '.exe'): + stem = stem.removesuffix(suffix) + prefix, _, name = stem.removesuffix('-program').partition('-') + if prefix != optimization or name not in cells: + raise Failure(f'{relative(path)} names {program.name}, which is no program of ' + f'a cell of doc/capabilities.json: {WRITE}') + found[(name, target, optimization)] = Program(cells[name], target, optimization, + program) + missing = [f'{optimization}-{cell.id} on {target}' for cell in cells.values() + for target in cell.targets for optimization in required + if (cell.id, target, optimization) not in found] + if missing: + raise Failure('the measure lane built nothing for ' + ', '.join(missing) + + ': every cell of doc/capabilities.json has its program on every target ' + 'of its backend (a skipped program is a failure, not a missing row)') + bench_targets = {t for t, _ in bench} + if lists and bench_targets != set(TARGETS): + absent = ', '.join(t for t in TARGETS if t not in bench_targets) + raise Failure(f'the measure lane built nothing for bench/pbkdf2_sha512 on {absent}') + return list(found.values()), bench + + +def size_of(program: Program, strip: str) -> int: + if program.target == 'native': + with tempfile.TemporaryDirectory() as scratch: + copy_path = Path(scratch) / program.path.name + shutil.copy2(program.path, copy_path) + done = subprocess.run([strip, str(copy_path)], capture_output=True, text=True, + check=False) + if done.returncode != 0: + raise Failure(f'{strip} {program.path}: {done.stderr.strip()}') + return copy_path.stat().st_size + wasm = program.path.with_suffix('.wasm') + if not wasm.is_file(): + raise Failure(f'{program.path}: no {wasm.name} beside it') + return wasm.stat().st_size + + +def run_program(target: str, path: Path, args: list[str], timeout: float | None + ) -> subprocess.CompletedProcess[str] | None: + command = LAUNCHERS[target] + [str(path), *args] + try: + return subprocess.run(command, capture_output=True, text=True, check=False, + timeout=timeout) + except subprocess.TimeoutExpired: + return None + + +def parse_output(program: Program, text: str) -> dict[str, Any]: + out: dict[str, Any] = {} + for line in text.splitlines(): + word, _, rest = line.partition(' ') + if word == 'result': + out['result'] = rest.strip() + elif word == 'compiler': + out['compiler'] = rest.strip() + elif word == 'repetitions': + out['repetitions'] = int(rest) + elif word == 'runs_ns': + out['runs_ns'] = [int(x) for x in rest.split()] + if 'result' not in out: + raise Failure(f'{program.optimization}-{program.cell.id} on {program.target} printed ' + f'no result:\n{text}') + return out + + +def run_once(program: Program) -> dict[str, Any]: + done = run_program(program.target, program.path, [], BOUND) + if done is None: + raise Failure(f'{program.optimization}-{program.cell.id} on {program.target} did not ' + f'end within {BOUND} seconds') + if done.returncode != 0: + raise Failure(f'{program.optimization}-{program.cell.id} on {program.target}: exit ' + f'{done.returncode}\n{done.stdout}{done.stderr}') + return parse_output(program, done.stdout) + + +def run_timed(program: Program) -> dict[str, Any] | None: + bound = BOUND if program.target in WASM else None + done = run_program(program.target, program.path, ['--time'], bound) + if done is None: + return None + if done.returncode != 0: + raise Failure(f'{program.optimization}-{program.cell.id} on {program.target} --time: ' + f'exit {done.returncode}\n{done.stdout}{done.stderr}') + return parse_output(program, done.stdout) + + +def run_bench(target: str, path: Path) -> None: + done = run_program(target, path, [], BENCH_BOUND) + if done is None: + raise Failure(f'bench/pbkdf2_sha512 (pbkdf2_sha512_key) on {target} did not end within ' + f'{BENCH_BOUND} seconds') + if done.returncode != 0: + raise Failure(f'bench/pbkdf2_sha512 (pbkdf2_sha512_key) on {target}: exit ' + f'{done.returncode}\n{done.stdout}{done.stderr}') + + +def native_toolchain(bench: list[tuple[str, Path]], strip: str) -> dict[str, str]: + """What measures natively: the compiler, as bench/'s native program states it, the host's + operating system and processor, and the strip, by its resolved path.""" + compiler = 'unknown' + for target, path in bench: + if target != 'native': + continue + done = run_program(target, path, ['hash2', '--runs', '1'], BENCH_BOUND) + if done is not None and done.returncode == 0 and done.stdout.strip(): + try: + compiler = str(json.loads(done.stdout.strip().splitlines()[-1])['compiler']) + except (json.JSONDecodeError, KeyError): + pass + found = shutil.which(strip) + return {'compiler': compiler, 'os': platform.system(), 'processor': platform.machine(), + 'strip': str(Path(found).resolve()) if found else strip} + + +def parallel(function: Callable[[Any], Any], items: list[Any], jobs: int) -> list[Any]: + with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, jobs)) as pool: + return list(pool.map(function, items)) + + +def measure(table: Table, programs: list[Program], bench: list[tuple[str, Path]], + invocations: int, jobs: int, strip: str) -> dict[str, Any]: + """Sizes and results of every program (each run once, in parallel), and, with invocations, + the throughput of every program built for speed, invocation after invocation round-robin + over the programs, one at a time, so that a change of load falls on all alike.""" + space = [p for p in programs if p.optimization == 'space'] + speed = [p for p in programs if p.optimization == 'speed'] + sizes = dict(zip([(p.cell.id, p.target) for p in space], + parallel(lambda p: size_of(p, strip), space, jobs))) + once = dict(zip([(p.cell.id, p.target, p.optimization) for p in programs], + parallel(run_once, programs, jobs))) + parallel(lambda b: run_bench(*b), bench, jobs) + timed: dict[tuple[str, str], list[dict[str, Any] | None]] = {} + loads = [list(os.getloadavg())] + for _ in range(invocations): + for p in speed: + timed.setdefault((p.cell.id, p.target), []).append(run_timed(p)) + loads.append(list(os.getloadavg())) + toolchains: dict[str, str] = {} + records = [] + for p in space: + results = {once[(p.cell.id, p.target, o)]['result'] for o in OPTIMIZATIONS + if (p.cell.id, p.target, o) in once} + if len(results) != 1: + raise Failure(f'{p.cell.id} on {p.target}: its programs for size and for throughput ' + f'print different results, {sorted(results)}') + record: dict[str, Any] = { + 'operation': p.cell.function, 'hmac': p.cell.hmac, 'backend': p.cell.backend, + 'target': p.target, 'size_bytes': sizes[(p.cell.id, p.target)], + 'result': results.pop(), 'throughput': None} + runs = timed.get((p.cell.id, p.target)) + if invocations and runs is not None: + if any(r is None for r in runs): + record['throughput_absent'] = (f'an invocation did not end within {BOUND} ' + 'seconds, the lane\'s bound') + else: + record['throughput'] = summary([r for r in runs if r is not None]) + first = runs[0] + assert first is not None + toolchains.setdefault(p.target, str(first.get('compiler', 'unknown'))) + elif not invocations: + record['throughput_absent'] = 'not measured by this run' + records.append(record) + cores = os.cpu_count() or 1 + return { + 'date': datetime.date.today().isoformat(), + 'machine': machine(), + 'load_average_before_after': [[round(x, 2) for x in loads[0]], + [round(x, 2) for x in loads[-1]]], + 'loaded': max(loads[0][0], loads[-1][0]) > cores, + 'toolchains': {t: toolchains.get(t, 'unknown') for t in TARGETS}, + 'runtimes': {'wasip2': tool_version(['wasmtime', '--version']), + 'wasip3': tool_version(['wasmtime', '--version']), + 'emscripten': 'node ' + tool_version([LAUNCHERS['emscripten'][0], + '--version'])}, + 'strip': strip, + 'native_toolchain': native_toolchain(bench, strip), + 'records': records, + } + + +def summary(runs: list[dict[str, Any]]) -> dict[str, Any]: + repetitions = int(runs[0]['repetitions']) + per_run = [[t / repetitions for t in r['runs_ns']] for r in runs] + medians = [statistics.median(r) for r in per_run] + every = [t for r in per_run for t in r] + return {'repetitions': repetitions, 'invocations': len(runs), + 'runs_per_invocation': len(per_run[0]), + 'invocation_medians_ns': [round(m, 1) for m in medians], + 'median_ns': round(statistics.median(medians), 1), + 'min_ns': round(min(every), 1), 'max_ns': round(max(every), 1)} + + +# --------------------------------------------------------------------------------------------- +# The orders. + + +def ordered(values: dict[str, float], previous: list[str] | None, base: list[str], + margin: float) -> list[str]: + """The backends of values (each a median, or a size) in order, the lowest first (spec 4.2). + Without a previous order, the values alone order them, an exact tie keeping base's order. + With one, the previous order stands but where a backend's value is more than margin below + the value of the one ahead of it: it moves ahead, until no such pair is left.""" + if not previous: + return sorted((b for b in base if b in values), key=lambda b: values[b]) + start = [b for b in previous if b in values] + order = start + sorted((b for b in base if b in values and b not in start), + key=lambda b: values[b]) + + def beats(b: str, a: str) -> bool: + return values[b] < values[a] * (1 - margin) + + moved = True + while moved: + moved = False + for i in range(len(order) - 1): + if beats(order[i + 1], order[i]): + order[i], order[i + 1] = order[i + 1], order[i] + moved = True + return order + + +def orders_of(table: Table, records: list[dict], previous: list[dict] | None) -> list[dict]: + before = {(o['operation'], o['hmac'], o['target']): o for o in previous or []} + rows: dict[tuple[str, str | None], dict[str, dict]] = {} + for r in records: + rows.setdefault((r['operation'], r['hmac']), {}).setdefault(r['target'], {})[ + r['backend']] = r + base = table.backend_names + out = [] + for function in table.function_names: + for hmac in [None, *MEASURED_HMACS]: + per_target = rows.get((function, hmac)) + if not per_target: + continue + for target in TARGETS: + cells = per_target.get(target) + if not cells: + continue + old = before.get((function, hmac, target), {}) + sizes = {b: float(r['size_bytes']) for b, r in cells.items()} + by_size = ordered(sizes, old.get('by_size'), base, 0.0) + source = target + speeds = {b: r['throughput'] for b, r in cells.items()} + if any(s is None for s in speeds.values()): + source = 'native' + native = per_target.get('native', {}) + speeds = {b: native[b]['throughput'] for b in cells if b in native} + if speeds and all(s is not None for s in speeds.values()): + values = {b: float(s['median_ns']) for b, s in speeds.items()} + by_throughput = ordered(values, old.get('by_throughput'), base, MARGIN) + by_throughput += [b for b in by_size if b not in by_throughput] + else: + by_throughput, source = by_size, 'none: ordered by size' + out.append({'operation': function, 'hmac': hmac, 'target': target, + 'by_size': by_size, 'by_throughput': by_throughput, + 'throughput_from': source}) + return out + + +# --------------------------------------------------------------------------------------------- +# The data file. + + +def record_order(table: Table) -> Callable[[dict[str, Any]], tuple[int, ...]]: + functions = {f: i for i, f in enumerate(table.function_names)} + backends = {b: i for i, b in enumerate(table.backend_names)} + hmacs = {None: 0, **{h: i + 1 for i, h in enumerate(MEASURED_HMACS)}} + targets = {t: i for i, t in enumerate(TARGETS)} + return lambda r: (functions[r['operation']], hmacs[r['hmac']], backends[r['backend']], + targets[r['target']]) + + +def digest_of(data: dict) -> str: + body = {k: v for k, v in data.items() if k != 'digest'} + return 'sha256:' + hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + + +def data_file(table: Table, measured: dict, previous: dict | None) -> dict: + records = sorted(copy.deepcopy(measured['records']), key=record_order(table)) + for r in records: + r.setdefault('throughput_absent', None) + if r['throughput'] is not None: + r['throughput_absent'] = None + functions = sorted({r['operation'] for r in records}, key=table.function_names.index) + data = { + 'about': 'webcpp::hash\'s measured table (spec section 4.2): the size of one program per ' + 'cell of doc/capabilities.json on each target, and its throughput, which ' + 'detail/ranking.hpp orders the backends by. Written by tools/hash/measure.py ' + '--write; the documentation renders from it.', + 'version': 1, + 'layout': LAYOUT, + 'date': measured['date'], + 'machine': measured['machine'], + 'load_average_before_after': measured['load_average_before_after'], + 'loaded': measured['loaded'], + 'toolchains': measured['toolchains'], + 'runtimes': measured['runtimes'], + 'strip': measured['strip'], + 'native_toolchain': measured.get('native_toolchain', {}), + 'pins': {b['name']: b['library'] for b in table.backends}, + 'builds': {'size': 'variant=release optimization=space', + 'throughput': 'variant=release optimization=speed'}, + 'workloads': {f: workload(table, f) for f in functions}, + 'rules': RULES, + 'records': records, + 'orders': orders_of(table, records, previous['orders'] if previous else None), + } + data['digest'] = digest_of(data) + return data + + +# --------------------------------------------------------------------------------------------- +# Rendering. + + +def tag(table: Table, backend: str) -> str: + return table.backend[backend]['tag'] + + +def full_order(table: Table, order: list[str]) -> list[str]: + """An order of ranking.hpp: the row's backends with a tag, then every other backend with a + tag in the table's order, so that the walk of first_serving always reaches one that serves.""" + named = [b for b in order if table.backend[b]['tag']] + return named + [b for b in table.tagged if b not in named] + + +def backend_list(table: Table, order: list[str], indent: int) -> str: + names = ', '.join(tag(table, b) for b in full_order(table, order)) + return f'backend_list<{names}>;' + + +def using(name: str, value: str) -> str: + """`using = ` in a class, as clang-format breaks it at 100 columns.""" + line = f' using {name} = {value}' + return line if len(line) <= 100 else f' using {name} =\n {value}' + + +def render_ranking(table: Table, data: dict) -> str: + orders = {(o['operation'], o['hmac'], o['target']): o for o in data['orders']} + portable = ', '.join(table.backend[b]['tag'] for b in table.tagged + if table.backend[b]['portable']) + lines = [LICENCE_SLASHES.rstrip('\n'), '', + '// Generated by tools/hash/measure.py --write from doc/measurements.json: do not ' + 'edit. Per target', + '// and key derivation, the backends ordered by their programs\' size and by ' + 'their throughput', + '// (spec section 4.2); the measure lane fails when this file differs from what ' + 'the data renders.', '', + '#ifndef WEBCPP_HASH_DETAIL_RANKING_HPP', + '#define WEBCPP_HASH_DETAIL_RANKING_HPP', '', + '#include ', + '#include ', '', + 'namespace webcpp::hash::detail {', '', + '/**', ' An ordered list of backends, the first preferred.', '', + ' @tparam B The backends, tags of `backends`.', '*/', + 'template ', 'struct backend_list {};', '', + '/**', + ' The backends of the portable profile, in its order: those present on every ' + 'target (spec 4.1).', + '*/', + f'using portable_order = backend_list<{portable}>;', ''] + conditions = {'wasip2': '#ifdef WEBCPP_TARGET_WASIP2', + 'wasip3': '#elif defined(WEBCPP_TARGET_WASIP3)', + 'emscripten': '#elif defined(WEBCPP_TARGET_EMSCRIPTEN)', + 'native': '#else // native'} + for target in ('wasip2', 'wasip3', 'emscripten', 'native'): + lines += [conditions[target], ''] + lines += ['/**', + f' The measured orders of the backends of a key derivation on {target} ' + '(spec 4.2): `by_size`, the', + ' smallest program first, and `by_throughput`, the fastest first. This ' + 'primary template is an', + ' algorithm the table does not measure: the table\'s order of backends.', '', + ' @tparam Algorithm The algorithm\'s tag, as `kdfs::hkdf`. @tparam Hmac The ' + 'hmac of a key', + ' derivation, or `void`.', '*/', + 'template ', 'struct ranking {', + ' /** The smallest program first. */', + using('by_size', backend_list(table, [], 4)), + ' /** The fastest first. */', + using('by_throughput', backend_list(table, [], 4)), + '};', ''] + for _, function in table.kdf_rows(): + name = function['name'] + hmacs = [h for h in MEASURED_HMACS if (name, h, target) in orders] + if not hmacs and (name, None, target) in orders: + hmacs = [None] + for i, hmac in enumerate(hmacs): + order = orders[(name, hmac, target)] + spec_tag = function['tag'] + if i == 0: + what = (f'over {hmac}, and over every hmac the table does not measure' + if hmac else 'which takes no hmac') + head = ['template ', f'struct ranking<{spec_tag}, Hmac> {{'] + else: + what = f'over {hmac}' + head = ['template <>', f'struct ranking<{spec_tag}, {hmac}> {{'] + lines += ['/**', + f' {name} on {target}, {what}: by size ' + f'{", ".join(order["by_size"])}; by throughput ' + f'{", ".join(order["by_throughput"])} (measured on ' + f'{order["throughput_from"]}).', + '*/'] + head + [ + ' /** The smallest program first. */', + using('by_size', backend_list(table, order['by_size'], 4)), + ' /** The fastest first. */', + using('by_throughput', backend_list(table, order['by_throughput'], 4)), + '};', ''] + lines += ['#endif', '', '} // namespace webcpp::hash::detail', '', + '#endif // WEBCPP_HASH_DETAIL_RANKING_HPP', ''] + return wrap_comments('\n'.join(lines)) + + +def wrap_comments(text: str) -> str: + """Wraps the lines of Doc Comments (one leading space) at 100 columns.""" + out = [] + for line in text.split('\n'): + if line.startswith(' ') and not line.startswith(' ') and len(line) > 100: + words, current = line.split(' ')[1:], '' + for word in words: + if current and len(current) + 1 + len(word) > 99: + out.append(' ' + current) + current = word + else: + current = f'{current} {word}' if current else word + out.append(' ' + current) + else: + out.append(line) + return '\n'.join(out) + + +def render_overrides(table: Table) -> str: + lines = [LICENCE_SLASHES.rstrip('\n'), '', + '// The per-algorithm overrides of the default backend (spec section 4.1), one ' + 'block per overridable', + '// algorithm of doc/capabilities.json and one define per backend of it that has ' + 'a tag:', + '// WEBCPP_HASH_DEFAULT_BACKEND__ names the backend of every ' + 'function of the', + '// algorithm, whatever the profile. Two overrides of one algorithm, and ' + 'OpenSSL\'s on Emscripten,', + '// are an #error. An override names its backend even where the backend lacks the ' + 'function over', + '// the hmac used: the call then stops with that backend\'s refusal (spec 3.3); ' + 'and when the', + '// program does not link it, hkdf.hpp and pbkdf2.hpp include its header, which ' + 'stops with its', + '// "needs" message (spec 5.7). Generated by tools/hash/measure.py --overrides ' + 'from', + '// doc/capabilities.json: do not edit; test/overrides_list_test.cpp checks it ' + 'against the table', + '// too. kdf.hpp includes it, the one reader of override_choice, so the ' + 'overrides\' refusals come', + '// with every key derivation header.', '', + '#ifndef WEBCPP_HASH_DETAIL_OVERRIDES_HPP', '#define WEBCPP_HASH_DETAIL_OVERRIDES_HPP', + '', '#include ', '', + '/** The spelling of `x` as a string literal, unexpanded. @param x The tokens. */', + '#define WEBCPP_HASH_DETAIL_OVERRIDE_STRING_I(x) #x', + '/** The spelling of `x` as a string literal, once `x` is expanded. @param x The ' + 'macro. */', + '#define WEBCPP_HASH_DETAIL_OVERRIDE_STRING(x) ' + 'WEBCPP_HASH_DETAIL_OVERRIDE_STRING_I(x)', '', + 'namespace webcpp::hash::detail {', '', '/**', + ' The backend an override names for `Algorithm`, `void` without one.', '', + ' @tparam Algorithm A tag of `kdfs`, the algorithm (not one of its steps).', '*/', + 'template ', 'struct override_choice {', + ' /** No override. */', ' using type = void;', '};', ''] + backends = [b for b in table.backends if b['tag']] + for algorithm in table.algorithms: + if not algorithm['overridable']: + continue + macro = algorithm['macro'] + prefix = f'WEBCPP_HASH_DEFAULT_BACKEND_{macro}_' + names = ', '.join(f['name'] for f in algorithm['functions']) + lines += [f'// {macro}: {names}.', '// clang-format off'] + for i, a in enumerate(backends): + for b in backends[i + 1:]: + lines += [f'#if defined({prefix}{a["macro"]}) && defined({prefix}{b["macro"]})', + f'#error "webcpp::hash: {prefix}{a["macro"]} and {prefix}{b["macro"]} ' + 'are both defined. Keep one."', '#endif'] + for b in backends: + if 'emscripten' not in b['targets']: + lines += [f'#if defined(WEBCPP_TARGET_EMSCRIPTEN) && defined({prefix}{b["macro"]})', + f'#error "webcpp::hash: {prefix}{b["macro"]} selects {library_name(b)}, ' + 'which is not built for Emscripten. Remove that define."', '#endif'] + lines.append('// clang-format on') + override = f'WEBCPP_HASH_DETAIL_OVERRIDE_{macro}' + for i, b in enumerate(backends): + lines.append(f'#ifdef {prefix}{b["macro"]}' if i == 0 + else f'#elif defined({prefix}{b["macro"]})') + lines.append(f'#define {override} {b["name"]}') + if b['name'] != 'hash2': + lines.append(f'#define WEBCPP_HASH_DETAIL_OVERRIDES_{b["macro"]}') + tag_name = algorithm['tag'] + lowered = macro.lower() + lines += ['#endif', f'#ifdef {override}', + f'/** The backend the override of {macro} names. */', 'template <>', + f'struct override_choice<{tag_name}> {{', ' /** The named backend. */', + f' using type = backends::{override};', '};', '#ifdef _MSC_VER', + f'#pragma detect_mismatch("webcpp_hash_default_backend_{lowered}", \\', + f' WEBCPP_HASH_DETAIL_OVERRIDE_STRING({override}))', + '#endif', '#elif defined(_MSC_VER)', + f'#pragma detect_mismatch("webcpp_hash_default_backend_{lowered}", "none")', + '#endif', ''] + lines += ['} // namespace webcpp::hash::detail', '', + '#endif // WEBCPP_HASH_DETAIL_OVERRIDES_HPP', ''] + return '\n'.join(lines) + + +def library_name(backend: dict) -> str: + return 'OpenSSL' if backend['name'] == 'openssl' else str(backend['name']) + + +def render_cells(table: Table) -> str: + lines = [LICENCE_HASH.rstrip('\n'), '', + '# Generated by tools/hash/measure.py --write from doc/capabilities.json: do', + '# not edit. One program per cell, a function on a backend (a key derivation', + '# over each hmac of spec 4.2), as test/measure/Jamfile\'s measure-cell', + '# declares it: : : : : .', ''] + for cell in table.cells(): + lines += [f'measure-cell {cell.id} : {cell.source}', + f' : {cell.library or ""} : {cell.hmac or ""} : {" ".join(cell.targets)} ;' + .replace(': :', ': :').replace(': :', ': :')] + return '\n'.join(lines) + '\n' + + +def adoc_header(title: str, anchor: str, source: str) -> list[str]: + return [LICENCE_SLASHES.rstrip('\n'), '', + f'// Generated by tools/hash/measure.py from {source}: do not edit.', '', + f'[#{anchor}]', f'== {title}', ''] + + +def render_backends(table: Table) -> str: + """The capability table as the documentation shows it: per chapter, each + function on each backend, its hmacs and its constant time; per function, the targets each + backend has it on.""" + lines = adoc_header('Backends', 'hash-backends', 'doc/capabilities.json') + lines += ['Which backend implements each function, over which hmacs, on which targets, and ' + 'what upstream', 'states about its constant time. The backends:', '', + '[cols="1,3,1,2,3",options="header"]', '|===', + '| Backend | Library | Licence | Jamfile | Targets'] + for b in table.backends: + lines += ['', f'| {b["name"]}', f'| {b["library"]}', f'| {b["licence"]}', + f'| `{b["jamfile"]}`', f'| {", ".join(b["targets"])}'] + lines += ['|===', ''] + chapters: dict[str, list[dict]] = {} + for algorithm in table.algorithms: + chapters.setdefault(algorithm['chapter'], []).append(algorithm) + for chapter, algorithms in chapters.items(): + lines += [f'=== {chapter.replace("_", " ").capitalize()}', '', + '[cols="2,1,3,1,4",options="header"]', '|===', + '| Function | Backend | Hmacs | Constant time | Targets'] + for algorithm in algorithms: + for function in algorithm['functions']: + for name in table.backend_names: + c = function['backends'].get(name) + if c is None: + continue + hmacs = ', '.join(c['hmacs']) if c['hmacs'] else '-' + targets = ', '.join(table.backend[name]['targets']) + lines += ['', f'| {function["name"]}', f'| {name}', f'| {hmacs}', + f'| {c["constant_time"]["value"]}', f'| {targets}'] + lines += ['|===', ''] + lines += ['=== Constant time', '', 'What each backend\'s upstream states, and where:', ''] + seen = set() + for _, function in table.functions: + for name, c in function['backends'].items(): + key = (name, c['constant_time']['value'], c['constant_time']['source']) + if key in seen: + continue + seen.add(key) + lines.append(f'* {name}: {c["constant_time"]["value"]}. ' + f'{c["constant_time"]["source"]}') + return '\n'.join(lines) + '\n' + + +def fmt_time(ns: float) -> str: + if ns >= 1e6: + return f'{ns / 1e6:.2f} ms' + if ns >= 1e3: + return f'{ns / 1e3:.2f} µs' + return f'{ns:.0f} ns' + + +def fmt_speed(table: Table, operation: str, t: dict) -> str: + if table.chapter_of(operation) in ('digests', 'macs', 'non-cryptographic'): + def rate(ns: float) -> str: + return f'{1e9 / ns:.0f}' + return f'{rate(t["median_ns"])} MiB/s ({rate(t["max_ns"])} to {rate(t["min_ns"])})' + return (f'{fmt_time(t["median_ns"])} ({fmt_time(t["min_ns"])} to ' + f'{fmt_time(t["max_ns"])})') + + +def defaults_of(table: Table, data: dict) -> list[tuple]: + """The default the owner's rule gives (spec 4.1's auto: natively the fastest, on + WebAssembly the smallest), per target and key derivation operation, every backend linked: + the first of the operation's own order that has it.""" + sizes = {(r['operation'], r['hmac'], r['backend'], r['target']): r['size_bytes'] + for r in data['records']} + orders = {(o['operation'], o['hmac'], o['target']): o for o in data['orders']} + out = [] + for _, function in table.kdf_rows(): + name = function['name'] + for hmac in [None, *MEASURED_HMACS]: + for target in TARGETS: + order = orders.get((name, hmac, target)) + if order is None: + continue + chosen = (order['by_size'] if target in WASM else order['by_throughput'])[0] + smallest = order['by_size'][0] + out.append((name, hmac, target, chosen, sizes[(name, hmac, chosen, target)], + smallest, sizes[(name, hmac, smallest, target)])) + return out + + +def render_measurements(table: Table, data: dict) -> str: + m = data['machine'] + lines = adoc_header('Measured size and throughput', 'hash-measurements', + 'doc/measurements.json') + lines += ['What each backend costs a program on each target, in bytes and in time, as ' + 'webcpp measured it', + '(spec section 4.2). The size of a backend is what matters on WebAssembly, where ' + 'every byte is', + 'downloaded; its throughput is what matters natively. `detail/ranking.hpp`, ' + 'generated from the', + 'same data, orders the backends of each key derivation by both, and the default ' + 'backend follows it.', '', + f'Measured on {data["date"]} on {m["cpu"]}, {m["cores"]} cores, ' + f'{m["memory_gib"]} GiB, {m["os"]};', + f'WebAssembly under {data["runtimes"]["wasip2"]} (wasip2, wasip3) and ' + f'{data["runtimes"]["emscripten"]} (Emscripten).', + 'Compilers: ' + '; '.join(f'{t}: {c}' for t, c in data['toolchains'].items()) + + '.', ''] + native = data.get('native_toolchain') or {} + if native: + lines += [f'The native rows hold for {native["compiler"]} on {native["os"]} ' + f'{native["processor"]}, stripped with {Path(native["strip"]).name}; another', + 'native toolchain gives other native sizes and times.', ''] + if data['loaded']: + load = data['load_average_before_after'] + lines += ['WARNING: the machine was shared and loaded while this was measured (many ' + 'builds ran at once;', + '1, 5 and 15 minute load averages ' + + '/'.join(f'{x:.0f}' for x in load[0]) + ' before and ' + + '/'.join(f'{x:.0f}' for x in load[1]) + f' after, on {m["cores"]} cores).', + 'Every time is a median with its spread; read the spread, not a single ' + 'figure. Sizes do not', + 'depend on the load.', ''] + lines += [f'Sizes: {RULES["size"]}. Throughput: {RULES["throughput"]}. Orders: ' + f'{RULES["order"]}', ''] + by_cell: dict[tuple, dict[str, dict]] = {} + for r in data['records']: + by_cell.setdefault((r['operation'], r['hmac'], r['backend']), {})[r['target']] = r + lines += ['=== Size of a program, in bytes', '', + '[cols="3,2,1,1,1,1,1",options="header"]', '|===', + '| Function | Hmac | Backend | native | wasip2 | wasip3 | emscripten'] + for (operation, hmac, backend), targets in by_cell.items(): + lines += ['', f'| {operation}', f'| {hmac or "-"}', f'| {backend}'] + lines += [f'| {targets[t]["size_bytes"]}' if t in targets else '| -' for t in TARGETS] + lines += ['|===', '', '=== Throughput', '', + 'A hash or MAC in MiB per second over 1 MiB, a key derivation in time per ' + 'derivation: the median, then', + 'the range of its runs, the lower figure first. Per function, the workload:', ''] + lines += [f'* {f}: {w}.' for f, w in data['workloads'].items()] + lines += ['', '[cols="3,2,1,3,3,3,3",options="header"]', '|===', + '| Function | Hmac | Backend | native | wasip2 | wasip3 | emscripten'] + for (operation, hmac, backend), targets in by_cell.items(): + lines += ['', f'| {operation}', f'| {hmac or "-"}', f'| {backend}'] + for t in TARGETS: + r = targets.get(t) + if r is None: + lines.append('| -') + elif r['throughput'] is None: + lines.append(f'| not measured: {r["throughput_absent"]}') + else: + lines.append(f'| {fmt_speed(table, operation, r["throughput"])}') + lines += ['|===', '', '=== The orders of the key derivations', '', + 'The rows `detail/ranking.hpp` holds, one per operation: the default of ' + '`hkdf_extract`, `hkdf_expand` and `hkdf` each reads its own (spec 4.1).', '', + '[cols="2,2,1,3,3,1",options="header"]', '|===', + '| Function | Hmac | Target | By size | By throughput | Throughput of'] + kdf_names = {f['name'] for _, f in table.kdf_rows()} + for o in data['orders']: + if o['operation'] not in kdf_names: + continue + lines += ['', f'| {o["operation"]}', f'| {o["hmac"] or "-"}', f'| {o["target"]}', + f'| {", ".join(o["by_size"])}', f'| {", ".join(o["by_throughput"])}', + f'| {o["throughput_from"]}'] + lines += ['|===', '', '=== The default of each key derivation', '', + 'The owner\'s rule (spec 4.1, the profile `auto`): natively the fastest backend, ' + 'on WebAssembly the', + 'smallest, among those the program links. With every backend linked, the default ' + 'and the size of', + 'its program, beside the smallest program of the function on that target:', '', + '[cols="2,2,1,1,1,1,1",options="header"]', '|===', + '| Function | Hmac | Target | Default | Its size | Smallest | Its size'] + for name, hmac, target, chosen, size, smallest, small in defaults_of(table, data): + lines += ['', f'| {name}', f'| {hmac or "-"}', f'| {target}', f'| {chosen}', + f'| {size}', f'| {smallest}', f'| {small}'] + lines += ['|===', ''] + return '\n'.join(lines) + + +# --------------------------------------------------------------------------------------------- +# The modes. + + +class Library: + def __init__(self, path: Path) -> None: + self.path = path + capabilities = path / 'doc/capabilities.json' + if not capabilities.is_file(): + raise Usage(f'{capabilities}: no doc/capabilities.json, the capability table') + self.table = Table(read_json(capabilities)) + self.data_path = path / 'doc/measurements.json' + + def outputs(self) -> dict[str, Path]: + return { + 'measurements.adoc': self.path / 'doc/measurements.adoc', + 'ranking': self.path / 'include/webcpp/hash/detail/ranking.hpp', + 'overrides': self.path / 'include/webcpp/hash/detail/overrides.hpp', + 'backends': self.path / 'doc/backends.adoc', + 'cells': self.path / 'test/measure/cells.jam', + } + + def table_only(self) -> dict[str, str]: + return {'overrides': render_overrides(self.table), + 'backends': render_backends(self.table), + 'cells': render_cells(self.table)} + + def rendered(self, data: dict) -> dict[str, str]: + return {'measurements.adoc': render_measurements(self.table, data), + 'ranking': render_ranking(self.table, data), **self.table_only()} + + def committed(self) -> dict | None: + return read_json(self.data_path) if self.data_path.is_file() else None + + +def write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w', encoding='utf-8', newline='\n') as f: + f.write(text) + + +def b2_build(library: Library, build_dir: Path, jobs: int) -> list[Path]: + """Builds every program with b2 and returns the lists of programs this build wrote, which + the Jamfile's manifest names (-sWEBCPP_HASH_MEASURE_MANIFEST).""" + config = ROOT / '.local/user-config.jam' + build_dir.mkdir(parents=True, exist_ok=True) + manifest = build_dir / 'measure-manifest.txt' + if manifest.exists(): + manifest.unlink() + command = ['b2', f'-j{jobs}', f'--build-dir={build_dir}', + f'-sWEBCPP_HASH_MEASURE_MANIFEST={manifest}'] + if config.is_file(): + command.append(f'--user-config={config}') + command.append(f'{relative(library.path)}/test/measure//measure-programs') + environ = {k: v for k, v in os.environ.items() + if k not in ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH')} + print('measure: ' + ' '.join(command), flush=True) + done = subprocess.run(command, cwd=ROOT, env=environ, check=False) + if done.returncode != 0: + raise Failure(f'b2 exited with {done.returncode}') + if not manifest.is_file(): + raise Failure(f'b2 wrote no {manifest}: test/measure/Jamfile\'s measure-programs names it') + return [path if path.is_absolute() else ROOT / path + for path in (Path(line) for line in manifest.read_text(encoding='utf-8').split('\n') + if line.strip())] + + +def mode_write(library: Library, args: argparse.Namespace) -> None: + table = library.table + write_text(library.outputs()['cells'], render_cells(table)) + if args.measured: + measured = read_json(Path(args.measured)) + else: + lists = b2_build(library, Path(args.build_dir).resolve(), args.jobs) + programs, bench = programs_of(table, lists, OPTIMIZATIONS) + measured = measure(table, programs, bench, args.invocations, args.jobs, args.strip) + check_coverage(table, measured['records'], 'the measurements') + check_results(table, measured['records'], None) + data = data_file(table, measured, library.committed()) + write_text(library.data_path, json_text(data)) + for name, text in library.rendered(data).items(): + write_text(library.outputs()[name], text) + print(f'measure: wrote {relative(library.data_path)} and the files generated from it') + + +def check_coverage(table: Table, records: list[dict], what: str) -> None: + have = {(r['operation'], r['hmac'], r['backend'], r['target']) for r in records} + want = {(c.function, c.hmac, c.backend, t) for c in table.cells() for t in c.targets} + missing = sorted(want - have, key=str) + extra = sorted(have - want, key=str) + if missing or extra: + names = [f'{o}{"/" + h if h else ""} on {b}, {t}' for o, h, b, t in missing] + others = [f'{o}{"/" + h if h else ""} on {b}, {t}' for o, h, b, t in extra] + raise Failure(f'{what} do not cover doc/capabilities.json\'s cells: missing ' + f'{", ".join(names) or "none"}; not in the table ' + f'{", ".join(others) or "none"}: {WRITE}') + + +def check_results(table: Table, records: list[dict], committed: dict | None) -> None: + """Every record of an operation and hmac prints one result, Python's where it has one, and + the committed one.""" + before = {(r['operation'], r['hmac'], r['backend'], r['target']): r['result'] + for r in (committed or {}).get('records', [])} + by_row: dict[tuple, set[str]] = {} + for r in records: + by_row.setdefault((r['operation'], r['hmac']), set()).add(r['result']) + old = before.get((r['operation'], r['hmac'], r['backend'], r['target'])) + if committed and old is not None and old != r['result']: + raise Failure(f'{r["operation"]} over {r["hmac"]} on {r["backend"]}, {r["target"]}: ' + f'the result {r["result"]} is not the committed {old}') + for (operation, hmac), results in by_row.items(): + if len(results) != 1: + raise Failure(f'{operation} over {hmac}: its backends and targets disagree, ' + f'{sorted(results)}') + expected = python_value(operation, hmac) + if expected is not None and expected not in results: + raise Failure(f'{operation} over {hmac}: the result {results.pop()} is not Python\'s ' + f'{expected}') + + +def describe(toolchain: dict[str, str]) -> str: + """A native toolchain, as a message names it.""" + if not toolchain: + return 'an unrecorded toolchain' + return (f'{toolchain.get("compiler")} on {toolchain.get("os")} {toolchain.get("processor")} ' + f'(strip {toolchain.get("strip")})') + + +def mode_check(library: Library, args: argparse.Namespace) -> None: + table = library.table + committed = library.committed() + problems = [] + if committed is None: + raise Failure(f'{relative(library.data_path)} does not exist: {WRITE}') + if committed.get('digest') != digest_of(committed): + problems.append(f'{relative(library.data_path)} was edited by hand (its digest does not ' + f'match): only {WRITE} writes it') + for name, text in library.rendered(committed).items(): + path = library.outputs()[name] + if not path.is_file() or path.read_text(encoding='utf-8') != text: + problems.append(f'{relative(path)} is not what doc/measurements.json and ' + f'doc/capabilities.json render (edited by hand, or stale): {WRITE}') + if problems: + raise Failure('\n'.join(problems)) + check_coverage(table, committed['records'], relative(library.data_path)) + if args.measured: + measured = read_json(Path(args.measured)) + else: + programs, bench = programs_of(table, [Path(p) for p in args.programs], ('space',)) + measured = measure(table, programs, bench, 0, args.jobs, args.strip) + check_coverage(table, measured['records'], 'the new measurements') + check_results(table, measured['records'], committed) + with_throughput = all(r['throughput'] is not None for r in measured['records']) + if not with_throughput: + old = {(r['operation'], r['hmac'], r['backend'], r['target']): r + for r in committed['records']} + for r in measured['records']: + r['throughput'] = old[(r['operation'], r['hmac'], r['backend'], r['target'])][ + 'throughput'] + again = orders_of(table, measured['records'], committed['orders']) + before = {(o['operation'], o['hmac'], o['target']): o for o in committed['orders']} + ours = measured.get('native_toolchain') or {} + theirs = committed.get('native_toolchain') or {} + native = ours == theirs + if not native: + print('measure: the native orders were measured with ' + f'{describe(theirs)} and are not compared with {describe(ours)}; ' + 'every native program and result is checked', flush=True) + changes = [] + for o in again: + if o['target'] == 'native' and not native: + continue + old = before.get((o['operation'], o['hmac'], o['target'])) + for key, what in (('by_size', 'by size'), ('by_throughput', 'by throughput')): + if old is None or old[key] != o[key]: + changes.append(f'{o["operation"]} over {o["hmac"]} on {o["target"]}: {what} ' + f'{", ".join(o[key])}, committed ' + f'{", ".join(old[key]) if old else "nothing"}') + if changes: + raise Failure('the measured order changed:\n ' + '\n '.join(changes) + + f'\nmeasure again and commit the new table: {WRITE}') + count = len(measured['records']) + print(f'measure: {count} cells on their targets agree with {relative(library.data_path)}' + + ('' if with_throughput else ' (sizes and results; throughput is measured by --write)')) + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description='webcpp::hash\'s measured table (spec 4.2).') + modes = parser.add_mutually_exclusive_group() + modes.add_argument('--write', action='store_true', help='measure and write every file') + modes.add_argument('--check', action='store_true', help='the measure lane\'s check') + modes.add_argument('--capabilities', action='store_true', + help='write doc/backends.adoc from doc/capabilities.json') + modes.add_argument('--overrides', action='store_true', + help='write detail/overrides.hpp from doc/capabilities.json') + parser.add_argument('--library', default=str(ROOT / 'libs/hash')) + parser.add_argument('--measured', help='the measurements, instead of measuring') + parser.add_argument('--programs', nargs='+', default=[], + help='the lists of programs the measure lane wrote') + parser.add_argument('--build-dir', default=str(ROOT / 'bin/measure')) + parser.add_argument('--invocations', type=int, default=INVOCATIONS) + parser.add_argument('--jobs', type=int, default=4) + parser.add_argument('--strip', default='strip') + args = parser.parse_args(argv) + try: + if not (args.write or args.check or args.capabilities or args.overrides): + raise Usage('give one of --write, --check, --capabilities and --overrides') + if args.measured and args.programs: + raise Usage('--measured and --programs are two sources of measurements: give one') + if args.check and not (args.measured or args.programs): + raise Usage('--check compares --measured or the lists of --programs') + library = Library(Path(args.library).resolve()) + if args.capabilities: + write_text(library.outputs()['backends'], render_backends(library.table)) + elif args.overrides: + write_text(library.outputs()['overrides'], render_overrides(library.table)) + elif args.write: + mode_write(library, args) + else: + mode_check(library, args) + except Usage as e: + print(f'measure.py: {e}', file=sys.stderr) + return 2 + except Failure as e: + print(f'measure.py: {e}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index 491fba49..bb21bf10 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -24,7 +24,10 @@ without a word. Every line that compiles a .cpp file of the source tree becomes an entry of , once per distinct command: every native command, and, from the dry run of each other target, the commands of the sources that no earlier target compiles, which are analysed as the -first target that compiles them does, with its own --target. +first target that compiles them does, with its own --target. A native own lane that builds for +every target in one command (libs/hash's measure) gives the native run WebAssembly commands +too: those of a source the run also compiles natively are left out, as a later target's are, +and an em++ command of a source it compiles for WebAssembly alone is analysed as emscripten's. clang-tidy reads a WebAssembly command only with the --target and the sysroot it names, and the lint gives any other command the host's --target, as to a native one. A command of wasip2 or @@ -652,19 +655,44 @@ def imported_source(root: str, source: str) -> bool: return Path(root, source).resolve() in imported +def webassembly(compiler: str) -> bool: + """Whether compiler builds for WebAssembly: wasi-sdk's clang++ or Emscripten's em++.""" + return wasi_sdk(compiler) or emscripten(compiler) + + +def natively(root: str, target: str, commands: list[list[str]]) -> list[list[str]]: + """commands, less, in a native dry run, the WebAssembly commands of a source that the run + also compiles natively: a native own lane may build its programs for every target in one + command (libs/hash's measure), and such a source is analysed natively alone.""" + if target != 'native': + return commands + native = {source_path(root, words[-1]) for words in commands if not webassembly(words[0])} + return [words for words in commands + if not (webassembly(words[0]) and source_path(root, words[-1]) in native)] + + +def compiled_for(target: str, words: list[str]) -> str: + """The target the command words compiles for, as the lint analyses it: target itself, but + for an em++ command of a native dry run (a native own lane that builds for every target), + emscripten, so that it is analysed as em++ compiles it and never as a host command. A + wasi-sdk command names its own --target, and the lint tells it by its compiler.""" + return EMSCRIPTEN if target == 'native' and emscripten(words[0]) else target + + def read(root: str, target: str, lines: list[str], entries: list[dict[str, object]], seen: set[tuple[str, ...]], earlier: set[str], wasi_clang: str | None, request: list[str]) -> tuple[Units, set[str]]: """Adds to entries each command of lines, compiled for target, that compiles a .cpp file of the source tree that is not in earlier, a source an earlier target compiles, and that is not - in seen, as the lint analyses it (analysed); a WebAssembly command of a compiler other than + in seen, as the lint analyses it (analysed), leaving out, natively, the WebAssembly commands + of a source the same run also compiles natively; a WebAssembly command of a compiler other than wasi-sdk's clang++ or, on emscripten, Emscripten's em++ fails. Returns the commands of the headers-alone translation units, by library and by unit, and the sources of the tree that commands compile.""" units: Units = {} sources: set[str] = set() selected: list[list[str]] = [] - for words in compiles(lines): + for words in natively(root, target, compiles(lines)): source = words[-1] unit = ALONE.match(source) if unit: @@ -682,7 +710,8 @@ def read(root: str, target: str, lines: list[str], entries: list[dict[str, objec seen.add(key) selected.append(words) entries.append({'directory': root, 'file': os.path.join(root, source), - 'arguments': analysed(target, source, words, wasi_clang)}) + 'arguments': analysed(compiled_for(target, words), source, words, + wasi_clang)}) prepare_provider_headers(root, request, selected, lines) return units, sources @@ -784,7 +813,7 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni selected: list[list[str]] = [] request = [*TARGETS[target], WITHOUT_EXCEPTIONS, *PROGRAMS, *lanes, *handler, *requested] lines = dry_run(root, request) - for words in compiles(lines): + for words in natively(root, target, compiles(lines)): source = words[-1] unit = ALONE.match(source) if unit: @@ -807,7 +836,8 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni seen.add(key) selected.append(words) entries.append({'directory': root, 'file': os.path.join(root, source), - 'arguments': analysed(target, source, words, wasi_clang)}) + 'arguments': analysed(compiled_for(target, words), source, words, + wasi_clang)}) prepare_provider_headers(root, request, selected, lines) twinned.programs |= kept - compiled for library, theirs in aggregates.items(): diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index d9d8a741..fa1211ad 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -805,43 +805,49 @@ else fi # 19. Each canary's commit is its submodule's (CODING-GUIDELINES.md chapter 5, rule 11): -# every `#define WEBCPP_CRYPTO__COMMIT ` of crypto's detail/canary.h names -# the first seven digits of the commit the superproject records for +# every `#define WEBCPP___COMMIT ` of crypto's and of hash's +# detail/canary.h names the first seven digits of the commit the superproject records for # third_party/libs/, read from git, so that no checkout is needed. The -# submodule is the canary's name, except ctaes, which Bitcoin Core's submodule holds. +# submodule is the canary's name, except ctaes, which Bitcoin Core's submodule holds, and +# sodium, which libsodium's does. rule 'canary pins' -canary_header='libs/crypto/include/webcpp/crypto/detail/canary.h' -pins="$(grep -hoE '^#define WEBCPP_CRYPTO_[A-Z0-9]+_COMMIT [0-9a-f]{7}$' \ - "${canary_header}" 2>/dev/null || true)" pin_faults='' -# A line that starts like a pin and is not of the exact form is a fault too, never skipped; a -# test's override (the macro defined as another WEBCPP_CRYPTO_ macro) is no pin. -pin_form='#define WEBCPP_CRYPTO__COMMIT <7 hex>' -while IFS= read -r line; do - if ! printf '%s\n' "${pins}" | grep -qxF -- "${line}"; then - pin_faults="${pin_faults}${canary_header}: a pin is not of the form ${pin_form}: " - pin_faults="${pin_faults}${line} +for library in crypto hash; do + upper="$(printf '%s' "${library}" | tr 'a-z' 'A-Z')" + canary_header="libs/${library}/include/webcpp/${library}/detail/canary.h" + pins="$(grep -hoE "^#define WEBCPP_${upper}_[A-Z0-9]+_COMMIT [0-9a-f]{7}\$" \ + "${canary_header}" 2>/dev/null || true)" + # A line that starts like a pin and is not of the exact form is a fault too, never skipped; a + # test's override (the macro defined as another WEBCPP__ macro) is no pin. + pin_form="#define WEBCPP_${upper}__COMMIT <7 hex>" + while IFS= read -r line; do + if ! printf '%s\n' "${pins}" | grep -qxF -- "${line}"; then + pin_faults="${pin_faults}${canary_header}: a pin is not of the form ${pin_form}: " + pin_faults="${pin_faults}${line} " - fi -done < <(grep -E '^#define WEBCPP_CRYPTO_[A-Z0-9]+_COMMIT ' "${canary_header}" 2>/dev/null \ - | grep -vE ' WEBCPP_CRYPTO_[A-Z0-9_]+$' || true) -while read -r _ macro hex; do - [ -n "${macro}" ] || continue - name="$(printf '%s' "${macro}" | sed -E 's/^WEBCPP_CRYPTO_(.*)_COMMIT$/\1/' | tr 'A-Z' 'a-z')" - case "${name}" in - ctaes) submodule='bitcoin' ;; - *) submodule="${name}" ;; - esac - head="$(git rev-parse --short=7 "HEAD:third_party/libs/${submodule}" 2>/dev/null \ - || printf 'missing')" - if [ "${head}" != "${hex}" ]; then - pin_faults="${pin_faults}${canary_header}: ${name} is pinned at ${hex} and " - pin_faults="${pin_faults}third_party/libs/${submodule} is at ${head} + fi + done < <(grep -E "^#define WEBCPP_${upper}_[A-Z0-9]+_COMMIT " "${canary_header}" 2>/dev/null \ + | grep -vE " WEBCPP_${upper}_[A-Z0-9_]+\$" || true) + while read -r _ macro hex; do + [ -n "${macro}" ] || continue + name="$(printf '%s' "${macro}" | sed -E "s/^WEBCPP_${upper}_(.*)_COMMIT\$/\1/" \ + | tr 'A-Z' 'a-z')" + case "${name}" in + ctaes) submodule='bitcoin' ;; + sodium) submodule='libsodium' ;; + *) submodule="${name}" ;; + esac + head="$(git rev-parse --short=7 "HEAD:third_party/libs/${submodule}" 2>/dev/null \ + || printf 'missing')" + if [ "${head}" != "${hex}" ]; then + pin_faults="${pin_faults}${canary_header}: ${name} is pinned at ${hex} and " + pin_faults="${pin_faults}third_party/libs/${submodule} is at ${head} " - fi -done < str: + return (f'"{compiler}" {" ".join(words)} -std=c++20 -c -o "bin/{where}/x.o" "{file}"') + + native = line('clang++', 'native', source) + wasm = line(wasi, 'wasip2', source, '--target=wasm32-wasip2') + em = line(emxx, 'emscripten', source) + for lines in ([native, wasm, em], [em, wasm, native]): + entries: list[dict[str, object]] = [] + compile_commands.read(str(root), 'native', lines, entries, set(), set(), wasi, []) + compilers = [entry['arguments'][0] for entry in entries] # type: ignore[index] + assert compilers == ['clang++'], (lines, entries) + entries = [] + compile_commands.read(str(root), 'native', [native, line(emxx, 'emscripten', alone)], + entries, set(), set(), wasi, []) + by_file = {Path(str(entry['file'])).name: entry['arguments'] for entry in entries} + command = by_file['fails.cpp'] + assert compile_commands.wasi_sdk(command[0]), command # type: ignore[index] + assert 'wasm32-unknown-emscripten' in command, command # type: ignore[operator] + # The twins without exceptions, from the same kind of dry run. + twin_lines = [line(emxx, 'emscripten', source, '-fno-exceptions'), + line(wasi, 'wasip2', source, '--target=wasm32-wasip2', '-fno-exceptions'), + line('clang++', 'native', source, '-fno-exceptions')] + dry_run = compile_commands.dry_run + compile_commands.dry_run = lambda _root, _request: twin_lines # type: ignore[assignment] + try: + entries = [] + compile_commands.twins(str(root), 'native', {}, {}, [], {source: 'native'}, entries, + set(), wasi, compile_commands.Twinned()) + finally: + compile_commands.dry_run = dry_run # type: ignore[assignment] + compilers = [entry['arguments'][0] for entry in entries] # type: ignore[index] + assert compilers == ['clang++'], entries + + def test_clang_tidy_uses_shipped_cobalt_sources_on_a_clean_tree(root): harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') prepare(root) @@ -2359,6 +2409,14 @@ def test_changelog(root): '#define WEBCPP_CRYPTO_BEARSSL_COMMIT {bearssl}\n#endif\n' '#define WEBCPP_CRYPTO_CTAES_COMMIT {ctaes}\n#endif\n') CANARY_HEADER = 'libs/crypto/include/webcpp/crypto/detail/canary.h' +HASH_CANARY = (CPP + '\n#ifndef WEBCPP_HASH_DETAIL_CANARY_H\n#define WEBCPP_HASH_DETAIL_CANARY_H\n' + '#ifdef WEBCPP_HASH_XKCP_CANARY_COMMIT\n' + '#define WEBCPP_HASH_XKCP_COMMIT WEBCPP_HASH_XKCP_CANARY_COMMIT\n#else\n' + '#define WEBCPP_HASH_XKCP_COMMIT {xkcp}\n#endif\n' + '#define WEBCPP_HASH_SODIUM_COMMIT {sodium}\n' + '#define WEBCPP_HASH_BLAKE3_COMMIT {blake3}\n' + '#define WEBCPP_HASH_BEARSSL_COMMIT {bearssl}\n#endif\n') +HASH_CANARY_HEADER = 'libs/hash/include/webcpp/hash/detail/canary.h' def record_submodule(root: Path, name: str, commit_id: str) -> None: @@ -2378,6 +2436,8 @@ def commit_recorded(root: Path, message: str) -> None: """Commits the header and the gitlinks recorded, without commit's git add -A, which would drop a gitlink whose directory is not there.""" git(root, 'add', CANARY_HEADER) + if (root / HASH_CANARY_HEADER).exists(): + git(root, 'add', '-f', HASH_CANARY_HEADER) git(root, 'commit', '-q', '-m', message) @@ -2414,6 +2474,27 @@ def test_canary_pins(root): expect_alone(lint(root), 'canary pins', [ f'{CANARY_HEADER}: a pin is not of the form #define WEBCPP_CRYPTO__COMMIT <7 hex>: ' '#define WEBCPP_CRYPTO_CTAES_COMMIT 123456']) + # hash's detail/canary.h is read beside crypto's: sodium's submodule is libsodium, xkcp's, + # blake3's and bearssl's are their own names; a wrong pin fails at the header, naming both. + write(root, CANARY_HEADER, CANARY.format(bearssl='1234567', ctaes='1234567')) + xkcp = 'aaaaaaa' + '0' * 33 + libsodium = 'bbbbbbb' + '0' * 33 + blake3 = 'ccccccc' + '0' * 33 + record_submodule(root, 'xkcp', xkcp) + record_submodule(root, 'libsodium', libsodium) + record_submodule(root, 'blake3', blake3) + write(root, HASH_CANARY_HEADER, + HASH_CANARY.format(xkcp='aaaaaaa', sodium='bbbbbbb', blake3='ccccccc', + bearssl='1234567')) + commit_recorded(root, 'Hash canaries at the recorded commits') + expect_clean(lint(root)) + write(root, HASH_CANARY_HEADER, + HASH_CANARY.format(xkcp='aaaaaaa', sodium='bbbbbba', blake3='ccccccc', + bearssl='1234567')) + commit_recorded(root, 'A wrong hash pin') + expect_alone(lint(root), 'canary pins', [ + f'{HASH_CANARY_HEADER}: sodium is pinned at bbbbbba and ' + 'third_party/libs/libsodium is at bbbbbbb']) def test_pyright(root): @@ -2696,6 +2777,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_clang_tidy_reads_a_program_of_javascript_exceptions, test_a_dependency_s_warnings_are_not_ours, test_a_compiled_boost_library_s_sources_are_not_analysed, + test_a_native_lane_s_webassembly_commands_are_left_to_its_native_one, test_clang_tidy_uses_shipped_cobalt_sources_on_a_clean_tree, test_clang_tidy_refuses_a_throw_on_each_target_without_exceptions, test_a_native_header_that_needs_no_exceptions_has_its_twin, diff --git a/tools/test/crypto_jamfiles_format_test.py b/tools/test/crypto_jamfiles_format_test.py index 550eb2d3..162e2c9d 100644 --- a/tools/test/crypto_jamfiles_format_test.py +++ b/tools/test/crypto_jamfiles_format_test.py @@ -5,8 +5,9 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Checks crypto_jamfiles_test.py's own rules, without building anything: what an outcome file -may say, what a run that builds nothing is, and how a failure's lines are matched (whole lines). +"""Checks the rules of user_jamfiles.py, which crypto_jamfiles_test.py and hash_jamfiles_test.py +share, without building anything: what an outcome file may say, what a run that builds nothing +is, and how a failure's lines are matched (whole lines). """ from __future__ import annotations @@ -16,8 +17,9 @@ import tempfile from pathlib import Path -import crypto_jamfiles_test as jamfiles +import crypto_jamfiles_test import harness +import user_jamfiles as jamfiles TEST = Path(__file__).resolve().parent / 'crypto_jamfiles_test.py' @@ -140,8 +142,27 @@ def test_same_as_keeps_copies_identical(): assert parse('[all]\nsame-as: a/app.cpp app.cpp\nbuild: succeeds\n').succeeds +def test_a_native_block_applies_by_architecture(): + text = ('[all]\nbuild: fails\n[native-arm64]\ncontains: arm\n' + '[native-x86_64]\ncontains: x86\n') + expected = {'arm64': ['arm'], 'x86_64': ['x86']}.get(jamfiles.ARCHITECTURE, []) + assert parse(text).contains == expected, (jamfiles.ARCHITECTURE, parse(text)) + assert parse('[all]\ntargets: wasip2\nbuild: fails\nx\n[native-arm64]\ncontains: arm\n', + 'wasip2').contains == [] + + +def test_a_library_not_checked_out_is_named(): + result = subprocess.run( + [sys.executable, '-c', 'import sys, user_jamfiles; sys.exit(user_jamfiles.main(' + '"t", user_jamfiles.harness.FIXTURES, ("no_such_library",), {}, []))'], + capture_output=True, text=True, check=False, cwd=TEST.parent) + assert result.returncode == 2, result + assert ('libs/no_such_library is not checked out' in result.stderr + and 'git submodule update --init libs/no_such_library' in result.stderr), result + + def test_every_case_directory_is_read(): - cases = jamfiles.case_directories() + cases = jamfiles.case_directories(crypto_jamfiles_test.CASES) assert {c.name for c in cases} >= {'hello', 'broken'}, cases diff --git a/tools/test/crypto_jamfiles_test.py b/tools/test/crypto_jamfiles_test.py index 9b4cd1e5..cb478886 100644 --- a/tools/test/crypto_jamfiles_test.py +++ b/tools/test/crypto_jamfiles_test.py @@ -8,28 +8,19 @@ """Builds every fixture of tools/test/fixtures/crypto_jamfiles, a Jamfile as a user of webcpp::crypto writes it (b2's raw exe), with b2 as a user runs it, and checks its outcome file: the build's status, the lines a failure prints, and a program's output (CODING-GUIDELINES.md -chapter 8). One scratch superproject per target, with libs/crypto and the fixtures in it; every -case of a target shares one build directory, so BearSSL's 295 files are compiled once per -target. Run with the names of some cases to run only those, and with --target to run one -target.""" +chapter 8), through user_jamfiles.py. One scratch superproject per target, with libs/crypto and +the fixtures in it; every case of a target shares one build directory, so BearSSL's 295 files are +compiled once per target. Run with the names of some cases to run only those, and with +--target to run one target.""" from __future__ import annotations -import platform -import re -import shutil -import subprocess import sys -import time -from dataclasses import dataclass, field -from pathlib import Path import harness +import user_jamfiles CASES = harness.FIXTURES / 'crypto_jamfiles' -TOOLSETS = {'native': [], 'wasip2': ['toolset=clang-wasip2'], 'wasip3': ['toolset=clang-wasip3'], - 'emscripten': ['toolset=emscripten']} -SYSTEM = {'Linux': 'linux', 'Darwin': 'darwin', 'Windows': 'windows'}[platform.system()] # Cases whose outcome needs code that is not merged yet: a run without names leaves them out # (and says so), a run that names one builds it. Each entry names what it waits for. The @@ -37,271 +28,9 @@ # cases' outcome files as b2's whole output lines (a line: directive, if need be). NOT_YET: dict[str, str] = {} -BLOCKS = {'all', 'native', 'native-linux', 'native-darwin', 'native-windows', 'wasip2', 'wasip3', - 'emscripten'} - - -class OutcomeError(Exception): - """An outcome file or a case directory that does not follow the format.""" - - -def launcher(target: str) -> Path: - """The script the lanes run a WASI program with (tools/ci/matrix.py, wasm_lane).""" - return harness.ROOT / f'tools/boost/asio-{target}/run.sh' - - -@dataclass -class Outcome: - """What an outcome file says for one target.""" - targets: list[str] = field(default_factory=lambda: ['native']) - succeeds: bool | None = None - run: str | None = None - lines: list[str] = field(default_factory=list) - contains: list[str] = field(default_factory=list) - # (text, allowed): no line of b2's output contains text, unless it also contains allowed - # (none: not even then). - forbidden: list[tuple[str, str | None]] = field(default_factory=list) - arguments: list[str] = field(default_factory=list) - - -def outcome(path: Path, target: str) -> Outcome: - """The blocks of path that apply to target on this system, read into an Outcome. Every line - of the file is checked, whether its block applies or not, and so is the outcome that results - when target is one the case is built for (checked).""" - applying = {'all', target} | ({'native', 'native-' + SYSTEM} if target == 'native' else set()) - result = Outcome() - block = None - for number, raw in enumerate(path.read_text().splitlines(), 1): - where = f'{path.name}:{number}' - if not raw.strip() or raw.startswith('#'): - continue - if raw.startswith('[') and raw.endswith(']'): - block = raw[1:-1] - if block not in BLOCKS: - raise OutcomeError(f'{where}: no block [{block}]; the blocks are {sorted(BLOCKS)}') - continue - if block is None: - raise OutcomeError(f'{where}: a line before the first [block]: {raw!r}') - directive = re.match(r'([a-z]+(?:-[a-z]+)?):(?: |$)', raw) - key, value = (directive.group(1), raw[directive.end():]) if directive else ('', raw) - if key and key not in ('targets', 'build', 'run', 'arguments', 'line', 'contains', - 'not-contains', 'same-as'): - raise OutcomeError(f'{where}: no directive {key}: (a line of one lowercase word and ' - f'a colon is reserved for them): {raw!r}') - if key in ('targets', 'arguments', 'not-contains') and not value.split(): - raise OutcomeError(f'{where}: {key}: names nothing') - if key == 'targets': - unknown = [t for t in value.split() if t not in TOOLSETS] - if unknown: - raise OutcomeError( - f'{where}: no target {unknown}; the targets are {list(TOOLSETS)}') - elif key == 'build' and value not in ('succeeds', 'fails'): - raise OutcomeError(f'{where}: build: is succeeds or fails, not {value!r}') - elif key == 'run' and not value: - raise OutcomeError(f'{where}: run: names no program') - if block not in applying or key == 'same-as': - continue - if key == 'targets': - result.targets = value.split() - elif key == 'build': - result.succeeds = value == 'succeeds' - elif key == 'run': - result.run = value - elif key == 'arguments': - result.arguments += value.split() - elif key == 'contains': - result.contains.append(value) - elif key == 'not-contains': - text, separator, allowed = value.partition(' unless ') - if not text.strip() or (separator and not allowed.strip()): - raise OutcomeError(f'{where}: not-contains: needs a text, then ` unless ` ' - f'if any line may hold it: {raw!r}') - result.forbidden.append((text.strip(), allowed.strip() or None)) - else: - result.lines.append(value if key == 'line' else raw) - if target in result.targets: - checked(path, target, result) - return result - - -def checked(path: Path, target: str, result: Outcome) -> None: - """Raises an OutcomeError naming path and target unless result is coherent: a build is said - to succeed or fail; a failure has lines to find and no program to run; a success that - prints lines has a program.""" - if result.succeeds is None: - raise OutcomeError(f'{path.name} on {target}: no build: line') - if not result.succeeds and result.run is not None: - raise OutcomeError(f'{path.name} on {target}: run: after build: fails') - if result.succeeds and (result.contains or result.forbidden): - raise OutcomeError(f'{path.name} on {target}: contains: or not-contains: after build: ' - 'succeeds') - if not result.succeeds and not result.lines and not result.contains: - raise OutcomeError(f'{path.name} on {target}: build: fails with no line to find') - if result.succeeds and result.run is None and result.lines: - raise OutcomeError(f'{path.name} on {target}: lines after build: succeeds, with no run:') - - -def same_as_faults(case: Path, cases: Path = CASES) -> list[str]: - """Each `same-as: / ` of case's outcome file whose two files are not - byte-identical: the file of another case, and case's own copy of it. A fixture's program is - a copy, never a symbolic link (a checkout on Windows reads a link as a text file), and this - keeps the copies from drifting.""" - faults: list[str] = [] - for number, raw in enumerate((case / f'{case.name}.outcome').read_text().splitlines(), 1): - if not raw.startswith('same-as:'): - continue - names = raw[len('same-as:'):].split() - where = f'{case.name}.outcome:{number}' - if len(names) != 2: - faults.append(f'{where}: same-as: names / and , not {names}') - continue - original, copy = cases / names[0], case / names[1] - if not original.is_file() or not copy.is_file(): - faults.append(f'{where}: {names[0]} or {case.name}/{names[1]} does not exist') - elif original.read_bytes() != copy.read_bytes(): - faults.append(f'{where}: {case.name}/{names[1]} is not a copy of {names[0]}') - return faults - - -def case_directories() -> list[Path]: - """Every directory of CASES, each with its one outcome file named after it, and every - outcome file read for every target (so each line of each block is checked), else an - OutcomeError.""" - cases = sorted(p for p in CASES.iterdir() if p.is_dir()) - for case in cases: - found = sorted(p.name for p in case.glob('*.outcome')) - if found != [case.name + '.outcome']: - raise OutcomeError(f'{case.name}: the outcome files are {found}; ' - f'the one is {case.name}.outcome') - if not (case / 'Jamfile').is_file(): - raise OutcomeError(f'{case.name}: no Jamfile') - for target in TOOLSETS: - outcome(case / f'{case.name}.outcome', target) - faults = same_as_faults(case) - if faults: - raise OutcomeError('; '.join(faults)) - return cases - - -def program_command(build_dir: Path, case: str, name: str, target: str) -> list[str]: - """The command that runs the program name that the build of case made under build_dir, as its - lane runs one.""" - suffix = {'native': '.exe' if SYSTEM == 'windows' else '', 'wasip2': '.wasm', - 'wasip3': '.wasm', 'emscripten': '.js'}[target] - found = [p for p in build_dir.rglob(name + suffix) - if p.is_file() and f'user/{case}/' in p.relative_to(build_dir).as_posix()] - if len(found) != 1: - raise AssertionError(f'the build made {len(found)} files named {name}{suffix}') - if target == 'emscripten': - return ['node', str(found[0])] - if target.startswith('wasi'): - return [str(launcher(target)), str(found[0])] - return [str(found[0])] - - -def selected(cases: list[Path], names: list[str], target: str) -> list[Path]: - """The cases to build for target: the named ones, else every one that is not in NOT_YET, - each that its outcome file's targets line names target for.""" - return [case for case in cases - if (case.name in names if names else case.name not in NOT_YET) - and target in outcome(case / f'{case.name}.outcome', target).targets] - - -def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: - """Builds each of cases for target in root and returns the faults, one line each.""" - faults: list[str] = [] - build_dir = root / 'bin' / f'user-{target}' - for case in cases: - expected = outcome(case / f'{case.name}.outcome', target) - scratch = root / 'scratch' / case.name - scratch.mkdir(parents=True, exist_ok=True) - arguments = [a.replace('@scratch', str(scratch)) for a in expected.arguments] - # No testing.launcher: a user's exe is run by this test, not by b2. - built = harness.run_b2(root, '-j3', f'--build-dir={build_dir}', *TOOLSETS[target], - *arguments, f'user/{case.name}') - output = built.stdout - if (built.returncode == 0) != expected.succeeds: - faults.append(f'{case.name} on {target}: the build ' - f'{"succeeded" if built.returncode == 0 else "failed"}\n{output[-3000:]}') - continue - if not expected.succeeds: - printed = {line.rstrip() for line in output.splitlines()} - faults += [f'{case.name} on {target}: b2 printed no line {line!r}' - for line in expected.lines if line.rstrip() not in printed] - faults += [f'{case.name} on {target}: no line of b2 contains {text!r}' - for text in expected.contains - if not any(text in line for line in printed)] - faults += [f'{case.name} on {target}: b2 printed {line!r}, which contains {text!r}' - f'{"" if allowed is None else f" and not {allowed!r}"}' - for text, allowed in expected.forbidden for line in sorted(printed) - if text in line and (allowed is None or allowed not in line)] - continue - if expected.run is not None: - try: - command = program_command(build_dir, case.name, expected.run, target) - except AssertionError as error: - faults.append(f'{case.name} on {target}: {error}') - continue - ran = subprocess.run(command, capture_output=True, text=True, check=False) - printed = ran.stdout.replace('\r\n', '\n').splitlines() - if ran.returncode != 0 or printed != expected.lines: - faults.append(f'{case.name} on {target}: {expected.run} exited {ran.returncode} ' - f'and printed {printed!r}; the outcome says {expected.lines!r}') - return faults - def main(argv: list[str]) -> int: - targets = list(TOOLSETS) - if '--target' in argv: - position = argv.index('--target') - if position + 1 >= len(argv) or argv[position + 1] not in TOOLSETS: - print(f'crypto_jamfiles: --target takes one of {list(TOOLSETS)}', file=sys.stderr) - return 2 - targets = [argv[position + 1]] - argv = argv[:position] + argv[position + 2:] - names = [a for a in argv if not a.startswith('--')] - if len(names) != len(argv): - print(f'crypto_jamfiles: no option {[a for a in argv if a.startswith("--")]}; ' - 'the one is --target ', file=sys.stderr) - return 2 - try: - cases = case_directories() - except OutcomeError as error: - print(f'crypto_jamfiles: {error}', file=sys.stderr) - return 2 - missing = [n for n in names if n not in {c.name for c in cases}] - if missing: - print(f'crypto_jamfiles: no case named {missing}', file=sys.stderr) - return 2 - if not names and NOT_YET: - for case, reason in NOT_YET.items(): - print(f'left out until {reason}: {case}') - faults: list[str] = [] - built = 0 - for target in targets: - chosen = selected(cases, names, target) - if not chosen: - continue - built += len(chosen) - started = time.monotonic() - root = harness.scratch_superproject() - try: - harness.copy_integration_libraries(root, 'config', 'crypto') - shutil.copytree(CASES, root / 'user', ignore=harness.built) - if target == 'emscripten': - harness.link_emsdk(root) - elif target.startswith('wasi'): - harness.link_wasi_tools(root) - faults += run_target(root, target, chosen) - finally: - shutil.rmtree(root) - print(f'{target}: done in {time.monotonic() - started:.0f} s') - if not built: - faults.append(f'no case was built for {targets}; nothing was tested') - for fault in faults: - print(f'crypto_jamfiles: {fault}', file=sys.stderr) - print('crypto_jamfiles_test: ' + ('failed' if faults else 'ok')) - return 1 if faults else 0 + return user_jamfiles.main('crypto_jamfiles', CASES, ('config', 'crypto'), NOT_YET, argv) if __name__ == '__main__': diff --git a/tools/test/emscripten_test.py b/tools/test/emscripten_test.py index 1cfc1ca0..5e40f61b 100644 --- a/tools/test/emscripten_test.py +++ b/tools/test/emscripten_test.py @@ -8,13 +8,14 @@ """Checks emscripten as a target of the build, on the fixture library browser_demo: its tests and examples run under node, which b2's emscripten toolset runs itself, and a testing.launcher is refused there; a program that node runs reads the host's files and standard input (-sNODERAWFS=1), -and no other program gets the flag; every program is wasm32, whatever address model is asked for; a -program links at the level of optimization it compiles at, -O3 in a release build, which b2's -toolset leaves to em++'s default, -O0, and before its own linkflags; a failure reaches the report; -a program of webcpp.link is linked and never run, and fails on a symbol nothing defines; a test of -webcpp.drive runs its program through a script of node's on each of its targets, in an own lane, a -driver or a program that hangs fails it within its bound and leaves no process behind, and one that -no own lane names is refused; and a native build needs no Emscripten. +and no other program gets the flag, but one that asks for off, which links +Emscripten's NODEFS and mounts the host's directories itself; every program is wasm32, whatever +address model is asked for; a program links at the level of optimization it compiles at, -O3 in a +release build, which b2's toolset leaves to em++'s default, -O0, and before its own linkflags; a +failure reaches the report; a program of webcpp.link is linked and never run, and fails on a symbol +nothing defines; a test of webcpp.drive runs its program through a script of node's on each of its +targets, in an own lane, a driver or a program that hangs fails it within its bound and leaves no +process behind, and one that no own lane names is refused; and a native build needs no Emscripten. The suspension variant, jspi by default and asyncify on request, builds with the exceptions each needs, asyncify in a directory of its own, and natively adds nothing. Every program node runs links the test support (/webcpp//node-test), whose fixture library node_test_demo pins each case's exact @@ -180,6 +181,62 @@ def test_input_file_is_read_from_the_host(root): assert '-sENVIRONMENT=web' in link_line(root, result, 'page') +# A program that mounts a directory of the host where it reads it, as libsodium's tests read their +# expected results at /test-data: the fixture's test directory, by its absolute path. +MOUNTS_JAMFILE = """ +path-constant MOUNTED : . ; +webcpp.run mounts : mounts_test.cpp + : off "\\"WEBCPP_TEST_MOUNTED=\\\\\\"$(MOUNTED)\\\\\\"\\"" + : emscripten ; +""" + +MOUNTS_SOURCE = r'''// 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) + +// Mounts the host's directory WEBCPP_TEST_MOUNTED at /data, then reads input.txt there. + +#include + +#include +#include +#include + +int main() { + EM_ASM( + { + FS.mkdir('/data'); + FS.mount(NODEFS, {root : UTF8ToString($0)}, '/data'); + }, + WEBCPP_TEST_MOUNTED); + std::ifstream file("/data/input.txt"); + std::string line; + std::getline(file, line); + std::cout << "read " << line << "\n"; + return line == "hello" ? 0 : 1; +} +''' + + +def test_a_program_mounts_the_host_s_directories_itself(root): + # off: no -sNODERAWFS=1, under which a path is the host's and nothing can + # be mounted, but Emscripten's NODEFS, so that the program mounts a directory of the host + # where it reads it. + test = root / 'libs/browser_demo/test' + (test / 'Jamfile').write_text((test / 'Jamfile').read_text() + MOUNTS_JAMFILE) + (test / 'mounts_test.cpp').write_text(MOUNTS_SOURCE) + result = harness.run_b2(root, '-a', '-d+2', *EMSCRIPTEN, 'libs/browser_demo/test//mounts') + harness.expect(result, True) + assert passed(result) == {'mounts'}, (passed(result), result.stdout[-4000:]) + line = link_line(root, result, 'mounts') + assert '-sNODERAWFS=1' not in line, line + assert '-lnodefs.js' in line, line + output = built(root, 'mounts.output') + assert len(output) == 1 and output[0].read_text().startswith('read hello\n'), output + + def test_programs_are_wasm32(root): # Browsers do not all run memory64: a program is wasm32 even when address-model=64 is asked # for, which b2's toolset would build with -sMEMORY64=1. @@ -640,6 +697,7 @@ def run(root): test_size_table_ignores_linked_source_dependencies, test_a_launcher_is_refused_on_emscripten, test_input_file_is_read_from_the_host, + test_a_program_mounts_the_host_s_directories_itself, test_programs_are_wasm32, test_a_link_is_optimized_as_its_compile, test_suspend_variants_build_apart, diff --git a/tools/test/fixtures/hash_jamfiles/app/Jamfile b/tools/test/fixtures/hash_jamfiles/app/Jamfile new file mode 100644 index 00000000..5fea12fe --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/app/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1: Hash2's algorithms, HMAC, hkdf and pbkdf2 on backends::hash2. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/app/app.cpp b/tools/test/fixtures/hash_jamfiles/app/app.cpp new file mode 100644 index 00000000..24ea84da --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/app/app.cpp @@ -0,0 +1,75 @@ +// 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) + +// A program that names /webcpp/hash//hash alone: SHA-256 of "abc" (FIPS 180-2), HMAC-SHA-256 +// (RFC 4231, case 2), HKDF (RFC 5869, A.1) and PBKDF2-HMAC-SHA-256 (RFC 7914, section 11, its +// first case), each on Boost.Hash2 (backends::hash2, the default without a C library). + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +// RFC 5869, appendix A.1: SHA-256, a 22-byte IKM, a 13-byte salt, a 10-byte info, 42 bytes. +std::array rfc5869_a1_okm() { + std::array ikm{}; + ikm.fill(0x0b); + std::array salt{}; + std::iota(salt.begin(), salt.end(), std::uint8_t{0x00}); + std::array info{}; + std::iota(info.begin(), info.end(), std::uint8_t{0xf0}); + std::array okm{}; + if (!webcpp::hash::hkdf( + okm, salt, ikm, info)) { + okm.fill(0); + } + return okm; +} + +} // namespace + +int main() { + namespace hash = webcpp::hash; + std::string_view const abc = "abc"; + hash::sha2_256 sha; + sha.update(abc.data(), abc.size()); + print_hex("sha2_256", sha.result()); + + std::string_view const key = "Jefe"; + std::string_view const data = "what do ya want for nothing?"; + hash::hmac_sha2_256 mac(key.data(), key.size()); + mac.update(data.data(), data.size()); + print_hex("hmac_sha2_256", mac.result()); + + print_hex("hkdf", rfc5869_a1_okm()); + + std::string_view const password = "password"; + std::string_view const salt = "salt"; + std::array derived{}; + auto const done = hash::pbkdf2( + derived, std::span(reinterpret_cast(password.data()), password.size()), + std::span(reinterpret_cast(salt.data()), salt.size()), 1); + print_hex("pbkdf2", derived); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/app/app.outcome b/tools/test/fixtures/hash_jamfiles/app/app.outcome new file mode 100644 index 00000000..d45cd913 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/app/app.outcome @@ -0,0 +1,14 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: app +sha2_256 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +hmac_sha2_256 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843 +hkdf 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +pbkdf2 120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/Jamfile b/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/Jamfile new file mode 100644 index 00000000..6164276a --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/argon2id_on_hash2 of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/app.cpp b/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/app.cpp new file mode 100644 index 00000000..969844ce --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/app.cpp @@ -0,0 +1,21 @@ +// 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) + +// argon2id on another backend than backends::sodium stops with spec section 3.3's text. + +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array salt{}; + auto done = webcpp::hash::argon2id( + output, {}, salt, webcpp::hash::argon2id_interactive); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/argon2id_on_hash2.outcome b/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/argon2id_on_hash2.outcome new file mode 100644 index 00000000..f4583172 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_on_hash2/argon2id_on_hash2.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/argon2id_on_hash2, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: argon2id is in backends::sodium alone. Name backends::sodium and add /third_party//sodium to the program's Jamfile. diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/Jamfile b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/Jamfile new file mode 100644 index 00000000..7e76e229 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/Jamfile @@ -0,0 +1,10 @@ +# 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) + +# test/messages/argon2id_override_hash2 of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//sodium + : WEBCPP_HASH_DEFAULT_BACKEND_ARGON2ID_HASH2 ; diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/app.cpp b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/app.cpp new file mode 100644 index 00000000..e3438536 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/app.cpp @@ -0,0 +1,21 @@ +// 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) + +// An override of argon2id's default backend is honoured (spec 4.1), even with libsodium linked: +// WEBCPP_HASH_DEFAULT_BACKEND_ARGON2ID_HASH2 and a call that names no backend stop with +// backends::hash2's refusal of spec 3.3, and with no other error. + +#include + +#include +#include + +int main() { + std::array output{}; + std::array salt{}; + auto done = webcpp::hash::argon2id(output, {}, salt, webcpp::hash::argon2id_interactive); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/argon2id_override_hash2.outcome b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/argon2id_override_hash2.outcome new file mode 100644 index 00000000..70d695e0 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/argon2id_override_hash2.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/argon2id_override_hash2, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: argon2id is in backends::sodium alone. Name backends::sodium and add /third_party//sodium to the program's Jamfile. diff --git a/tools/test/fixtures/hash_jamfiles/b3/Jamfile b/tools/test/fixtures/hash_jamfiles/b3/Jamfile new file mode 100644 index 00000000..92bfdef6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/b3/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1: blake3. +exe b3 : b3.cpp /webcpp/hash//hash /third_party//blake3 ; diff --git a/tools/test/fixtures/hash_jamfiles/b3/b3.cpp b/tools/test/fixtures/hash_jamfiles/b3/b3.cpp new file mode 100644 index 00000000..a9bd3069 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/b3/b3.cpp @@ -0,0 +1,37 @@ +// 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) + +// A program over BLAKE3's C implementation: the digests of BLAKE3's official vectors of length 0 +// and 1 (test_vectors.json, whose input is the bytes 0, 1, 2, ... modulo 251). + +#include + +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +} // namespace + +int main() { + webcpp::hash::blake3 empty; + print_hex("blake3", empty.result()); + std::uint8_t const zero = 0; + webcpp::hash::blake3 hasher; + hasher.update(&zero, 1); + print_hex("blake3", hasher.result()); + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/b3/b3.outcome b/tools/test/fixtures/hash_jamfiles/b3/b3.outcome new file mode 100644 index 00000000..a498fd92 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/b3/b3.outcome @@ -0,0 +1,12 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: b3 +blake3 af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262 +blake3 2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213 diff --git a/tools/test/fixtures/hash_jamfiles/bearssl_hmac/Jamfile b/tools/test/fixtures/hash_jamfiles/bearssl_hmac/Jamfile new file mode 100644 index 00000000..3f363b5e --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/bearssl_hmac/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/bearssl_hmac of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//bearssl ; diff --git a/tools/test/fixtures/hash_jamfiles/bearssl_hmac/app.cpp b/tools/test/fixtures/hash_jamfiles/bearssl_hmac/app.cpp new file mode 100644 index 00000000..497092a9 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/bearssl_hmac/app.cpp @@ -0,0 +1,24 @@ +// 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) + +// hkdf on backends::bearssl over an hmac BearSSL has no hash for (SHA-512/256) stops with spec +// section 3.3's text, and with no other error. + +#include +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array input{}; + auto done = + webcpp::hash::hkdf( + output, input, input, input); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/bearssl_hmac/bearssl_hmac.outcome b/tools/test/fixtures/hash_jamfiles/bearssl_hmac/bearssl_hmac.outcome new file mode 100644 index 00000000..d53c765f --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/bearssl_hmac/bearssl_hmac.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/bearssl_hmac, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: backends::bearssl has HKDF over hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384 and hmac_sha2_512 alone. Over this hmac, name backends::hash2 (every hmac) or backends::openssl (every hmac but hmac_ripemd_128). diff --git a/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/Jamfile b/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/Jamfile new file mode 100644 index 00000000..7673453c --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/bearssl_not_linked of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/app.cpp b/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/app.cpp new file mode 100644 index 00000000..19e67a17 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// A program that names backends::bearssl and does not link BearSSL stops with the instruction to +// add /third_party//bearssl (spec section 5.7). + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/bearssl_not_linked.outcome b/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/bearssl_not_linked.outcome new file mode 100644 index 00000000..f0d000d4 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/bearssl_not_linked/bearssl_not_linked.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/bearssl_not_linked, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: backends::bearssl needs BearSSL. Add /third_party//bearssl to the program's Jamfile: exe app : app.cpp /webcpp/hash//hash /third_party//bearssl ; diff --git a/tools/test/fixtures/hash_jamfiles/blake3_not_linked/Jamfile b/tools/test/fixtures/hash_jamfiles/blake3_not_linked/Jamfile new file mode 100644 index 00000000..a4111661 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/blake3_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/blake3_not_linked of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/blake3_not_linked/app.cpp b/tools/test/fixtures/hash_jamfiles/blake3_not_linked/app.cpp new file mode 100644 index 00000000..b14c8427 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/blake3_not_linked/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// A program that uses blake3 without linking /third_party//blake3 stops with the instruction to +// add it (spec 5.7, the second row). + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/blake3_not_linked/blake3_not_linked.outcome b/tools/test/fixtures/hash_jamfiles/blake3_not_linked/blake3_not_linked.outcome new file mode 100644 index 00000000..ba5850ea --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/blake3_not_linked/blake3_not_linked.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/blake3_not_linked, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: blake3 needs BLAKE3's C implementation. Add /third_party//blake3 to the program's Jamfile: exe app : app.cpp /webcpp/hash//hash /third_party//blake3 ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/Jamfile new file mode 100644 index 00000000..c48463c9 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/Jamfile @@ -0,0 +1,10 @@ +# 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 header found, the library not linked. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_HAS_BEARSSL=1 + ../../third_party/libs/bearssl/inc ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/app.cpp new file mode 100644 index 00000000..6ca19480 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/app.cpp @@ -0,0 +1,25 @@ +// 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) + +// Derives 42 bytes with HKDF on backends::bearssl: the program reads the canary of +// /third_party//bearssl, so that a library missing from the link, or built at another commit, fails +// to link with the canary's name (spec 5.4). + +#include +#include +#include + +#include +#include + +int main() { + std::array okm{}; + std::array const ikm{}; + auto const done = + webcpp::hash::hkdf(okm, {}, + ikm, {}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/canary_bearssl_missing.outcome b/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/canary_bearssl_missing.outcome new file mode 100644 index 00000000..108021fa --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_bearssl_missing/canary_bearssl_missing.outcome @@ -0,0 +1,25 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_hash_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[native-linux] +contains: webcpp_hash_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +contains: undefined reference to `webcpp_hash_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/Jamfile new file mode 100644 index 00000000..a11d0ba6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/Jamfile @@ -0,0 +1,9 @@ +# 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 library linked, and a program that names another commit of it. +exe app : app.cpp /webcpp/hash//hash /third_party//bearssl + : WEBCPP_HASH_BEARSSL_CANARY_COMMIT=0000000 ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/app.cpp new file mode 100644 index 00000000..6ca19480 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/app.cpp @@ -0,0 +1,25 @@ +// 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) + +// Derives 42 bytes with HKDF on backends::bearssl: the program reads the canary of +// /third_party//bearssl, so that a library missing from the link, or built at another commit, fails +// to link with the canary's name (spec 5.4). + +#include +#include +#include + +#include +#include + +int main() { + std::array okm{}; + std::array const ikm{}; + auto const done = + webcpp::hash::hkdf(okm, {}, + ikm, {}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/canary_bearssl_other_commit.outcome b/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/canary_bearssl_other_commit.outcome new file mode 100644 index 00000000..876dee5e --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_bearssl_other_commit/canary_bearssl_other_commit.outcome @@ -0,0 +1,25 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_hash_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +[native-linux] +contains: webcpp_hash_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +contains: undefined reference to `webcpp_hash_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_bearssl_0000000_getentropy__add_third_party_bearssl_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/Jamfile new file mode 100644 index 00000000..6ae1bc34 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/Jamfile @@ -0,0 +1,10 @@ +# 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 header found, the library not linked. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_HAS_BLAKE3=1 + ../../third_party/libs/blake3/c ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/app.cpp new file mode 100644 index 00000000..97c42d55 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/app.cpp @@ -0,0 +1,17 @@ +// 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) + +// Hashes "abc" with BLAKE3: the program reads the canary of /third_party//blake3, so that a +// library missing from the link, or built at another commit, fails to link with the +// canary's name (spec 5.4). + +#include + +int main() { + webcpp::hash::blake3 hasher; + hasher.update("abc", 3); + return hasher.result()[0] == 0x64 ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/canary_blake3_missing.outcome b/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/canary_blake3_missing.outcome new file mode 100644 index 00000000..63ebb00a --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_blake3_missing/canary_blake3_missing.outcome @@ -0,0 +1,29 @@ +# 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) + +# BLAKE3's configuration, and so the canary's name, follows the machine natively: +# neon on arm64, x86 on x86-64; the linker's own words follow the system. +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +[native-linux] +contains: undefined reference to ` +[native-arm64] +contains: webcpp_hash_blake3_f3149ec_neon__add_third_party_blake3_to_your_link +[native-x86_64] +contains: webcpp_hash_blake3_f3149ec_x86__add_third_party_blake3_to_your_link +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_blake3_f3149ec_portable__add_third_party_blake3_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_blake3_f3149ec_portable__add_third_party_blake3_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_blake3_f3149ec_portable__add_third_party_blake3_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/Jamfile new file mode 100644 index 00000000..c426e980 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/Jamfile @@ -0,0 +1,9 @@ +# 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 library linked, and a program that names another commit of it. +exe app : app.cpp /webcpp/hash//hash /third_party//blake3 + : WEBCPP_HASH_BLAKE3_CANARY_COMMIT=0000000 ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/app.cpp new file mode 100644 index 00000000..97c42d55 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/app.cpp @@ -0,0 +1,17 @@ +// 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) + +// Hashes "abc" with BLAKE3: the program reads the canary of /third_party//blake3, so that a +// library missing from the link, or built at another commit, fails to link with the +// canary's name (spec 5.4). + +#include + +int main() { + webcpp::hash::blake3 hasher; + hasher.update("abc", 3); + return hasher.result()[0] == 0x64 ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/canary_blake3_other_commit.outcome b/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/canary_blake3_other_commit.outcome new file mode 100644 index 00000000..337eec99 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_blake3_other_commit/canary_blake3_other_commit.outcome @@ -0,0 +1,29 @@ +# 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) + +# BLAKE3's configuration, and so the canary's name, follows the machine natively: +# neon on arm64, x86 on x86-64; the linker's own words follow the system. +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +[native-linux] +contains: undefined reference to ` +[native-arm64] +contains: webcpp_hash_blake3_0000000_neon__add_third_party_blake3_to_your_link +[native-x86_64] +contains: webcpp_hash_blake3_0000000_x86__add_third_party_blake3_to_your_link +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_blake3_0000000_portable__add_third_party_blake3_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_blake3_0000000_portable__add_third_party_blake3_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_blake3_0000000_portable__add_third_party_blake3_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/Jamfile new file mode 100644 index 00000000..40f192e2 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/Jamfile @@ -0,0 +1,10 @@ +# 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 header found, the library not linked. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_HAS_SODIUM=1 + ../../third_party/libs/libsodium/src/libsodium/include ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/app.cpp new file mode 100644 index 00000000..3a81a88e --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/app.cpp @@ -0,0 +1,25 @@ +// 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) + +// Derives 42 bytes with HKDF on backends::sodium: the program reads the canary of +// /third_party//sodium, so that a library missing from the link, or built at another commit, fails +// to link with the canary's name (spec 5.4). + +#include +#include +#include + +#include +#include + +int main() { + std::array okm{}; + std::array const ikm{}; + auto const done = + webcpp::hash::hkdf(okm, {}, + ikm, {}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/canary_sodium_missing.outcome b/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/canary_sodium_missing.outcome new file mode 100644 index 00000000..644a0b40 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_sodium_missing/canary_sodium_missing.outcome @@ -0,0 +1,25 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link +[native-linux] +contains: webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link +contains: undefined reference to `webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/Jamfile new file mode 100644 index 00000000..1f6c3e56 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/Jamfile @@ -0,0 +1,9 @@ +# 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 library linked, and a program that names another commit of it. +exe app : app.cpp /webcpp/hash//hash /third_party//sodium + : WEBCPP_HASH_SODIUM_CANARY_COMMIT=0000000 ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/app.cpp new file mode 100644 index 00000000..3a81a88e --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/app.cpp @@ -0,0 +1,25 @@ +// 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) + +// Derives 42 bytes with HKDF on backends::sodium: the program reads the canary of +// /third_party//sodium, so that a library missing from the link, or built at another commit, fails +// to link with the canary's name (spec 5.4). + +#include +#include +#include + +#include +#include + +int main() { + std::array okm{}; + std::array const ikm{}; + auto const done = + webcpp::hash::hkdf(okm, {}, + ikm, {}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/canary_sodium_other_commit.outcome b/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/canary_sodium_other_commit.outcome new file mode 100644 index 00000000..7fe546c1 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_sodium_other_commit/canary_sodium_other_commit.outcome @@ -0,0 +1,25 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_hash_sodium_0000000_configured__add_third_party_sodium_to_your_link +[native-linux] +contains: webcpp_hash_sodium_0000000_configured__add_third_party_sodium_to_your_link +contains: undefined reference to `webcpp_hash_sodium_0000000_configured__add_third_party_sodium_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_sodium_0000000_configured__add_third_party_sodium_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_sodium_0000000_configured__add_third_party_sodium_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_sodium_0000000_configured__add_third_party_sodium_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/Jamfile new file mode 100644 index 00000000..09cb78f0 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/Jamfile @@ -0,0 +1,9 @@ +# 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 header found, the library not linked. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_HAS_XKCP=1 ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/app.cpp new file mode 100644 index 00000000..9a83efff --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/app.cpp @@ -0,0 +1,17 @@ +// 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) + +// Hashes "abc" with Keccak-256: the program reads the canary of /third_party//xkcp, so that a +// library missing from the link, or built at another commit, fails to link with the +// canary's name (spec 5.4). + +#include + +int main() { + webcpp::hash::keccak_256 hasher; + hasher.update("abc", 3); + return hasher.result()[0] == 0x4e ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/canary_xkcp_missing.outcome b/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/canary_xkcp_missing.outcome new file mode 100644 index 00000000..5d7c48b2 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_xkcp_missing/canary_xkcp_missing.outcome @@ -0,0 +1,25 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link +[native-linux] +contains: webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link +contains: undefined reference to `webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/Jamfile b/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/Jamfile new file mode 100644 index 00000000..ad25b86f --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/Jamfile @@ -0,0 +1,9 @@ +# 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 library linked, and a program that names another commit of it. +exe app : app.cpp /webcpp/hash//hash /third_party//xkcp + : WEBCPP_HASH_XKCP_CANARY_COMMIT=0000000 ; diff --git a/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/app.cpp b/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/app.cpp new file mode 100644 index 00000000..9a83efff --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/app.cpp @@ -0,0 +1,17 @@ +// 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) + +// Hashes "abc" with Keccak-256: the program reads the canary of /third_party//xkcp, so that a +// library missing from the link, or built at another commit, fails to link with the +// canary's name (spec 5.4). + +#include + +int main() { + webcpp::hash::keccak_256 hasher; + hasher.update("abc", 3); + return hasher.result()[0] == 0x4e ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/canary_xkcp_other_commit.outcome b/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/canary_xkcp_other_commit.outcome new file mode 100644 index 00000000..2fd089fc --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/canary_xkcp_other_commit/canary_xkcp_other_commit.outcome @@ -0,0 +1,25 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: fails +[native-darwin] +contains: Undefined symbols for architecture +contains: _webcpp_hash_xkcp_0000000_generic64__add_third_party_xkcp_to_your_link +[native-linux] +contains: webcpp_hash_xkcp_0000000_generic64__add_third_party_xkcp_to_your_link +contains: undefined reference to `webcpp_hash_xkcp_0000000_generic64__add_third_party_xkcp_to_your_link' +[wasip2] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_xkcp_0000000_generic64__add_third_party_xkcp_to_your_link +[wasip3] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_xkcp_0000000_generic64__add_third_party_xkcp_to_your_link +[emscripten] +contains: wasm-ld: error: +contains: undefined symbol: webcpp_hash_xkcp_0000000_generic64__add_third_party_xkcp_to_your_link +contains: em++: error: diff --git a/tools/test/fixtures/hash_jamfiles/eth/Jamfile b/tools/test/fixtures/hash_jamfiles/eth/Jamfile new file mode 100644 index 00000000..d6aba81f --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/eth/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1: keccak_256. +exe eth : eth.cpp /webcpp/hash//hash /third_party//xkcp ; diff --git a/tools/test/fixtures/hash_jamfiles/eth/eth.cpp b/tools/test/fixtures/hash_jamfiles/eth/eth.cpp new file mode 100644 index 00000000..50a7fb86 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/eth/eth.cpp @@ -0,0 +1,37 @@ +// 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) + +// A program over XKCP: Keccak-256 (Ethereum's, the original padding) of nothing and of "abc". + +#include + +#include +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +} // namespace + +int main() { + webcpp::hash::keccak_256 empty; + print_hex("keccak_256", empty.result()); + std::string_view const abc = "abc"; + webcpp::hash::keccak_256 hasher; + hasher.update(abc.data(), abc.size()); + print_hex("keccak_256", hasher.result()); + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/eth/eth.outcome b/tools/test/fixtures/hash_jamfiles/eth/eth.outcome new file mode 100644 index 00000000..79abc6d4 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/eth/eth.outcome @@ -0,0 +1,12 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: eth +keccak_256 c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 +keccak_256 4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45 diff --git a/tools/test/fixtures/hash_jamfiles/every_library/Jamfile b/tools/test/fixtures/hash_jamfiles/every_library/Jamfile new file mode 100644 index 00000000..aa13b996 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/every_library/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# Every C library of webcpp::hash, and OpenSSL, in one program. +exe app : app.cpp /webcpp/hash//hash /third_party//xkcp /third_party//blake3 + /third_party//sodium /third_party//bearssl /webcpp/hash//openssl ; diff --git a/tools/test/fixtures/hash_jamfiles/every_library/app.cpp b/tools/test/fixtures/hash_jamfiles/every_library/app.cpp new file mode 100644 index 00000000..b92cf047 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/every_library/app.cpp @@ -0,0 +1,61 @@ +// 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) + +// One program over every C library of webcpp::hash its target has: Keccak-256 and BLAKE3 of +// nothing, then HKDF (RFC 5869, A.1) on each linked backend and on the default backend. Each +// library is one archive, linked once; their symbols do not collide. + +#include + +#include +#include +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +template +std::array rfc5869_a1_okm() { + std::array ikm{}; + ikm.fill(0x0b); + std::array salt{}; + std::iota(salt.begin(), salt.end(), std::uint8_t{0x00}); + std::array info{}; + std::iota(info.begin(), info.end(), std::uint8_t{0xf0}); + std::array okm{}; + if (!webcpp::hash::hkdf(okm, salt, ikm, info)) { + okm.fill(0); + } + return okm; +} + +} // namespace + +int main() { + namespace hash = webcpp::hash; + hash::keccak_256 keccak; + print_hex("keccak_256", keccak.result()); + hash::blake3 blake; + print_hex("blake3", blake.result()); + print_hex("hkdf hash2", rfc5869_a1_okm()); + print_hex("hkdf sodium", rfc5869_a1_okm()); + print_hex("hkdf bearssl", rfc5869_a1_okm()); +#if defined(WEBCPP_HASH_HAS_OPENSSL) + print_hex("hkdf openssl", rfc5869_a1_okm()); +#endif + print_hex("hkdf default", rfc5869_a1_okm>()); + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/every_library/every_library.outcome b/tools/test/fixtures/hash_jamfiles/every_library/every_library.outcome new file mode 100644 index 00000000..5a0452a1 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/every_library/every_library.outcome @@ -0,0 +1,17 @@ +# 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) + +[all] +targets: native wasip2 wasip3 +build: succeeds +run: app +keccak_256 c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 +blake3 af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262 +hkdf hash2 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf sodium 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf bearssl 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf openssl 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf default 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 diff --git a/tools/test/fixtures/hash_jamfiles/every_library_emscripten/Jamfile b/tools/test/fixtures/hash_jamfiles/every_library_emscripten/Jamfile new file mode 100644 index 00000000..1e76e175 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/every_library_emscripten/Jamfile @@ -0,0 +1,10 @@ +# 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) + +# Every C library of webcpp::hash in one program, on Emscripten, where webcpp +# builds no OpenSSL: every_library's program. +exe app : ../every_library/app.cpp /webcpp/hash//hash /third_party//xkcp + /third_party//blake3 /third_party//sodium /third_party//bearssl ; diff --git a/tools/test/fixtures/hash_jamfiles/every_library_emscripten/every_library_emscripten.outcome b/tools/test/fixtures/hash_jamfiles/every_library_emscripten/every_library_emscripten.outcome new file mode 100644 index 00000000..2fba948f --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/every_library_emscripten/every_library_emscripten.outcome @@ -0,0 +1,16 @@ +# 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) + +[all] +targets: emscripten +build: succeeds +run: app +keccak_256 c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 +blake3 af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262 +hkdf hash2 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf sodium 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf bearssl 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +hkdf default 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 diff --git a/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/Jamfile b/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/Jamfile new file mode 100644 index 00000000..e350c3ce --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/expand_on_bearssl of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//bearssl ; diff --git a/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/app.cpp b/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/app.cpp new file mode 100644 index 00000000..5603dc06 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/app.cpp @@ -0,0 +1,24 @@ +// 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) + +// hkdf_expand on backends::bearssl, whose br_hkdf_* keeps the PRK inside its context, stops with +// spec section 3.3's text, and with no other error. + +#include +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array prk{}; + auto done = + webcpp::hash::hkdf_expand( + output, prk, prk); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/expand_on_bearssl.outcome b/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/expand_on_bearssl.outcome new file mode 100644 index 00000000..c66de0b6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/expand_on_bearssl/expand_on_bearssl.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/expand_on_bearssl, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: hkdf_extract and hkdf_expand are not in backends::bearssl, whose HKDF does both steps together: call hkdf, or name backends::hash2, backends::sodium or backends::openssl. diff --git a/tools/test/fixtures/hash_jamfiles/kdf/Jamfile b/tools/test/fixtures/hash_jamfiles/kdf/Jamfile new file mode 100644 index 00000000..7ba97aa2 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1: backends::openssl, where webcpp builds OpenSSL. +exe kdf : kdf.cpp /webcpp/hash//hash /webcpp/hash//openssl ; diff --git a/tools/test/fixtures/hash_jamfiles/kdf/kdf.cpp b/tools/test/fixtures/hash_jamfiles/kdf/kdf.cpp new file mode 100644 index 00000000..6bf70c08 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf/kdf.cpp @@ -0,0 +1,65 @@ +// 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) + +// A program over OpenSSL: HKDF (RFC 5869, A.1) and, where the backend has it, +// PBKDF2-HMAC-SHA-256 (RFC 7914, section 11, its first case). + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +// RFC 5869, appendix A.1: SHA-256, a 22-byte IKM, a 13-byte salt, a 10-byte info, 42 bytes. +std::array rfc5869_a1_okm() { + std::array ikm{}; + ikm.fill(0x0b); + std::array salt{}; + std::iota(salt.begin(), salt.end(), std::uint8_t{0x00}); + std::array info{}; + std::iota(info.begin(), info.end(), std::uint8_t{0xf0}); + std::array okm{}; + if (!webcpp::hash::hkdf( + okm, salt, ikm, info)) { + okm.fill(0); + } + return okm; +} + +} // namespace + +int main() { + namespace hash = webcpp::hash; +#if defined(WEBCPP_HASH_HAS_OPENSSL) + std::printf("HAS_OPENSSL=%d\n", WEBCPP_HASH_HAS_OPENSSL); +#endif + print_hex("hkdf", rfc5869_a1_okm()); + std::string_view const password = "password"; + std::string_view const salt = "salt"; + std::array derived{}; + auto const done = hash::pbkdf2( + derived, std::span(reinterpret_cast(password.data()), password.size()), + std::span(reinterpret_cast(salt.data()), salt.size()), 1); + print_hex("pbkdf2", derived); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/kdf/kdf.outcome b/tools/test/fixtures/hash_jamfiles/kdf/kdf.outcome new file mode 100644 index 00000000..d9be34a6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf/kdf.outcome @@ -0,0 +1,13 @@ +# 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) + +[all] +targets: native wasip2 wasip3 +build: succeeds +run: kdf +HAS_OPENSSL=1 +hkdf 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 +pbkdf2 120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b diff --git a/tools/test/fixtures/hash_jamfiles/kdf2/Jamfile b/tools/test/fixtures/hash_jamfiles/kdf2/Jamfile new file mode 100644 index 00000000..6d03ea60 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf2/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1: backends::bearssl. +exe kdf2 : kdf.cpp /webcpp/hash//hash /third_party//bearssl ; diff --git a/tools/test/fixtures/hash_jamfiles/kdf2/kdf.cpp b/tools/test/fixtures/hash_jamfiles/kdf2/kdf.cpp new file mode 100644 index 00000000..8c4eb976 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf2/kdf.cpp @@ -0,0 +1,51 @@ +// 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) + +// A program over BearSSL: HKDF (RFC 5869, A.1); BearSSL has no PBKDF2. + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +// RFC 5869, appendix A.1: SHA-256, a 22-byte IKM, a 13-byte salt, a 10-byte info, 42 bytes. +std::array rfc5869_a1_okm() { + std::array ikm{}; + ikm.fill(0x0b); + std::array salt{}; + std::iota(salt.begin(), salt.end(), std::uint8_t{0x00}); + std::array info{}; + std::iota(info.begin(), info.end(), std::uint8_t{0xf0}); + std::array okm{}; + if (!webcpp::hash::hkdf( + okm, salt, ikm, info)) { + okm.fill(0); + } + return okm; +} + +} // namespace + +int main() { + print_hex("hkdf", rfc5869_a1_okm()); + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/kdf2/kdf2.outcome b/tools/test/fixtures/hash_jamfiles/kdf2/kdf2.outcome new file mode 100644 index 00000000..ce7a1a35 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf2/kdf2.outcome @@ -0,0 +1,11 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: kdf2 +hkdf 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 diff --git a/tools/test/fixtures/hash_jamfiles/kdf_not_digest/Jamfile b/tools/test/fixtures/hash_jamfiles/kdf_not_digest/Jamfile new file mode 100644 index 00000000..06b1036f --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf_not_digest/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/kdf_not_digest of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/kdf_not_digest/app.cpp b/tools/test/fixtures/hash_jamfiles/kdf_not_digest/app.cpp new file mode 100644 index 00000000..03605f0e --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf_not_digest/app.cpp @@ -0,0 +1,24 @@ +// 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) + +// A key derivation over an hmac whose result is not a digest (FNV-1a's is a 64-bit integer) +// stops with spec section 3.3's text, and with no other error. + +#include + +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array input{}; + auto done = + webcpp::hash::hkdf>(output, input, input, input); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/kdf_not_digest/kdf_not_digest.outcome b/tools/test/fixtures/hash_jamfiles/kdf_not_digest/kdf_not_digest.outcome new file mode 100644 index 00000000..122cd977 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf_not_digest/kdf_not_digest.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/kdf_not_digest, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: the key derivations take a Boost.Hash2 hmac whose result is a digest, as hmac_sha2_256. diff --git a/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/Jamfile b/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/Jamfile new file mode 100644 index 00000000..44db733b --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/kdf_not_hmac of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/app.cpp b/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/app.cpp new file mode 100644 index 00000000..27363870 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/app.cpp @@ -0,0 +1,19 @@ +// 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) + +// hkdf_extract, whose result is the hmac's result_type, over a type that has none stops with +// spec section 3.3's text too, and with no "no matching function" error. + +#include + +#include +#include + +int main() { + std::array input{}; + auto prk = webcpp::hash::hkdf_extract(input, input); + return prk ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/kdf_not_hmac.outcome b/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/kdf_not_hmac.outcome new file mode 100644 index 00000000..411a84c1 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/kdf_not_hmac/kdf_not_hmac.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/kdf_not_hmac, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: the key derivations take a Boost.Hash2 hmac whose result is a digest, as hmac_sha2_256. diff --git a/tools/test/fixtures/hash_jamfiles/openssl_not_linked/Jamfile b/tools/test/fixtures/hash_jamfiles/openssl_not_linked/Jamfile new file mode 100644 index 00000000..e47f7403 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/openssl_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/openssl_not_linked of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/openssl_not_linked/app.cpp b/tools/test/fixtures/hash_jamfiles/openssl_not_linked/app.cpp new file mode 100644 index 00000000..33065efe --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/openssl_not_linked/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// A program that names backends::openssl without linking /webcpp/hash//openssl stops with the +// instruction to add it (spec 5.7, the fifth row). + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/openssl_not_linked/openssl_not_linked.outcome b/tools/test/fixtures/hash_jamfiles/openssl_not_linked/openssl_not_linked.outcome new file mode 100644 index 00000000..feca07d8 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/openssl_not_linked/openssl_not_linked.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/openssl_not_linked, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: backends::openssl needs OpenSSL. Add /webcpp/hash//openssl to the program's Jamfile (native, wasip2 and wasip3): exe app : app.cpp /webcpp/hash//hash /webcpp/hash//openssl ; diff --git a/tools/test/fixtures/hash_jamfiles/openssl_on_emscripten/Jamfile b/tools/test/fixtures/hash_jamfiles/openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..497af0f6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/openssl_on_emscripten/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1's line for OpenSSL, built for Emscripten (spec 5.6): kdf's program. +exe kdf : ../kdf/kdf.cpp /webcpp/hash//hash /webcpp/hash//openssl ; diff --git a/tools/test/fixtures/hash_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome b/tools/test/fixtures/hash_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome new file mode 100644 index 00000000..ff059600 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/openssl_on_emscripten/openssl_on_emscripten.outcome @@ -0,0 +1,12 @@ +# 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 compiler's line of the #error starts with the forced header's path on the +# machine, so the message is a contains: line. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: OpenSSL is not built for Emscripten. In the program's Jamfile, remove /webcpp/hash//openssl: hkdf and pbkdf2 then run on backends::hash2. diff --git a/tools/test/fixtures/hash_jamfiles/override_cannot_serve/Jamfile b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/Jamfile new file mode 100644 index 00000000..f04831bb --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/Jamfile @@ -0,0 +1,10 @@ +# 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) + +# test/messages/override_cannot_serve of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//sodium + : WEBCPP_HASH_DEFAULT_BACKEND_HKDF_SODIUM ; diff --git a/tools/test/fixtures/hash_jamfiles/override_cannot_serve/app.cpp b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/app.cpp new file mode 100644 index 00000000..dd732576 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/app.cpp @@ -0,0 +1,22 @@ +// 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) + +// An override whose backend lacks the function over the hmac used (spec 4.1): +// WEBCPP_HASH_DEFAULT_BACKEND_HKDF_SODIUM and hkdf over hmac_sha2_384 stop with libsodium's +// text of spec 3.3, and with no other error. + +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array input{}; + auto done = webcpp::hash::hkdf(output, input, input, input); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/override_cannot_serve/override_cannot_serve.outcome b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/override_cannot_serve.outcome new file mode 100644 index 00000000..b4e4a986 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/override_cannot_serve.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/override_cannot_serve, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: backends::sodium has HKDF over hmac_sha2_256 and hmac_sha2_512 alone. Over this hmac, name backends::hash2 (every hmac), backends::openssl (every hmac but hmac_ripemd_128) or backends::bearssl (MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512; hkdf alone). diff --git a/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/Jamfile b/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..dbc65be8 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/Jamfile @@ -0,0 +1,12 @@ +# 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) + +# Each operation's override, each selecting OpenSSL. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_DEFAULT_BACKEND_HKDF_OPENSSL + WEBCPP_HASH_DEFAULT_BACKEND_PBKDF2_OPENSSL + WEBCPP_HASH_DEFAULT_BACKEND_ARGON2ID_OPENSSL + WEBCPP_HASH_DEFAULT_BACKEND_SCRYPT_OPENSSL ; diff --git a/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/app.cpp b/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..d3159418 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/app.cpp @@ -0,0 +1,21 @@ +// 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) + +// A program that derives with HKDF on the default backend: the define its Jamfile gives stops +// it on Emscripten, where webcpp builds no OpenSSL. + +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array const input{}; + auto const done = webcpp::hash::hkdf(output, input, input, input); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/overrides_openssl_on_emscripten.outcome b/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/overrides_openssl_on_emscripten.outcome new file mode 100644 index 00000000..ad427d37 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/overrides_openssl_on_emscripten.outcome @@ -0,0 +1,16 @@ +# 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 compiler's lines of the #errors start with the header's path on the machine, +# so the messages are contains: lines; clang goes on after an #error, so each is +# printed. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: WEBCPP_HASH_DEFAULT_BACKEND_HKDF_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define. +contains: webcpp::hash: WEBCPP_HASH_DEFAULT_BACKEND_PBKDF2_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define. +contains: webcpp::hash: WEBCPP_HASH_DEFAULT_BACKEND_ARGON2ID_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define. +contains: webcpp::hash: WEBCPP_HASH_DEFAULT_BACKEND_SCRYPT_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define. diff --git a/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/Jamfile b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/Jamfile new file mode 100644 index 00000000..444dea05 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/pbkdf2_on_bearssl of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//bearssl ; diff --git a/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/app.cpp b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/app.cpp new file mode 100644 index 00000000..f2912ab6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/app.cpp @@ -0,0 +1,23 @@ +// 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) + +// pbkdf2 on backends::bearssl, which has no PBKDF2, stops with spec section 3.3's text for +// BearSSL, not the primary template's, and with no other error. + +#include +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array input{}; + auto done = webcpp::hash::pbkdf2( + output, input, input, 1); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/pbkdf2_on_bearssl.outcome b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/pbkdf2_on_bearssl.outcome new file mode 100644 index 00000000..66b9833b --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_bearssl/pbkdf2_on_bearssl.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/pbkdf2_on_bearssl, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: pbkdf2 is not in backends::bearssl: BearSSL has no PBKDF2. The backends that have pbkdf2: backends::hash2 (every hmac) and backends::openssl (every hmac but hmac_ripemd_128). diff --git a/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/Jamfile b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/Jamfile new file mode 100644 index 00000000..42ff3a8c --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/pbkdf2_on_sodium of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//sodium ; diff --git a/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/app.cpp b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/app.cpp new file mode 100644 index 00000000..9abfd279 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/app.cpp @@ -0,0 +1,20 @@ +// 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) + +// pbkdf2 on backends::sodium stops with spec section 3.3's text: libsodium has no PBKDF2. + +#include + +#include +#include + +int main() { + std::array output{}; + std::array input{}; + auto done = webcpp::hash::pbkdf2( + output, input, input, 1); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/pbkdf2_on_sodium.outcome b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/pbkdf2_on_sodium.outcome new file mode 100644 index 00000000..031900fc --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pbkdf2_on_sodium/pbkdf2_on_sodium.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/pbkdf2_on_sodium, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: pbkdf2 is not in backends::sodium: libsodium has no PBKDF2. The backends that have pbkdf2: backends::hash2 (every hmac) and backends::openssl (every hmac but hmac_ripemd_128). diff --git a/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/Jamfile b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/Jamfile new file mode 100644 index 00000000..11a1d4c5 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/Jamfile @@ -0,0 +1,8 @@ +# 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) + +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_PROFILE_BACKEND_OPENSSL ; diff --git a/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/app.cpp b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/app.cpp new file mode 100644 index 00000000..d3159418 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/app.cpp @@ -0,0 +1,21 @@ +// 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) + +// A program that derives with HKDF on the default backend: the define its Jamfile gives stops +// it on Emscripten, where webcpp builds no OpenSSL. + +#include +#include + +#include +#include + +int main() { + std::array output{}; + std::array const input{}; + auto const done = webcpp::hash::hkdf(output, input, input, input); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/profile_openssl_on_emscripten.outcome b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/profile_openssl_on_emscripten.outcome new file mode 100644 index 00000000..64e29172 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/profile_openssl_on_emscripten.outcome @@ -0,0 +1,12 @@ +# 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 compiler's line of the #error starts with the header's path on the machine, +# so the message is a contains: line. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: WEBCPP_HASH_PROFILE_BACKEND_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define. diff --git a/tools/test/fixtures/hash_jamfiles/pw/Jamfile b/tools/test/fixtures/hash_jamfiles/pw/Jamfile new file mode 100644 index 00000000..b40ffcb6 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pw/Jamfile @@ -0,0 +1,8 @@ +# 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) + +# Spec 5.1: argon2id, scrypt and backends::sodium. +exe pw : pw.cpp /webcpp/hash//hash /third_party//sodium ; diff --git a/tools/test/fixtures/hash_jamfiles/pw/pw.cpp b/tools/test/fixtures/hash_jamfiles/pw/pw.cpp new file mode 100644 index 00000000..077ad6bf --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pw/pw.cpp @@ -0,0 +1,82 @@ +// 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) + +// A program over libsodium: Argon2id on the first case of libsodium's own table +// (test/default/pwhash_argon2id.c at 77e1ce5: its salt's first 16 bytes, its memory limit +// rounded down to a multiple of 1,024), scrypt on RFC 7914's second case, and HKDF (RFC 5869, +// A.1) on backends::sodium. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +// Prints label, a space and bytes in lowercase hex, then a newline. +void print_hex(char const* label, std::span bytes) { + std::printf("%s ", label); + for (std::uint8_t const b : bytes) { + std::printf("%02x", static_cast(b)); + } + std::printf("\n"); +} + +// RFC 5869, appendix A.1: SHA-256, a 22-byte IKM, a 13-byte salt, a 10-byte info, 42 bytes. +std::array rfc5869_a1_okm() { + std::array ikm{}; + ikm.fill(0x0b); + std::array salt{}; + std::iota(salt.begin(), salt.end(), std::uint8_t{0x00}); + std::array info{}; + std::iota(info.begin(), info.end(), std::uint8_t{0xf0}); + std::array okm{}; + if (!webcpp::hash::hkdf( + okm, salt, ikm, info)) { + okm.fill(0); + } + return okm; +} + +std::span bytes(std::string_view text) { + return {reinterpret_cast(text.data()), text.size()}; +} + +} // namespace + +int main() { + namespace hash = webcpp::hash; + std::array const password{ + 0xa3, 0x47, 0xae, 0x92, 0xbc, 0xe9, 0xf8, 0x0f, 0x6f, 0x59, 0x5a, 0x44, 0x80, 0xfc, 0x9c, + 0x2f, 0xe7, 0xe7, 0xd7, 0x14, 0x8d, 0x37, 0x1e, 0x94, 0x87, 0xd7, 0x5f, 0x5c, 0x23, 0x00, + 0x8f, 0xfa, 0xe0, 0x65, 0x57, 0x7a, 0x92, 0x8f, 0xeb, 0xd9, 0xb1, 0x97, 0x3a, 0x5a, 0x95, + 0x07, 0x3a, 0xcd, 0xbe, 0xb6, 0xa0, 0x30, 0xcf, 0xc0, 0xd7, 0x9c, 0xaa, 0x2d, 0xc5, 0xcd, + 0x01, 0x1c, 0xef, 0x02, 0xc0, 0x8d, 0xa2, 0x32, 0xd7, 0x6d, 0x52, 0xdf, 0xbc, 0xa3, 0x8c, + 0xa8, 0xdc, 0xbd, 0x66, 0x5b, 0x17, 0xd1, 0x66, 0x5f, 0x7c, 0xf5, 0xfe, 0x59, 0x77, 0x2e, + 0xc9, 0x09, 0x73, 0x3b, 0x24, 0xde, 0x97, 0xd6, 0xf5, 0x8d, 0x22, 0x0b, 0x20, 0xc6, 0x0d, + 0x7c, 0x07, 0xec, 0x1f, 0xd9, 0x3c, 0x52, 0xc3, 0x10, 0x20, 0x30, 0x0c, 0x6c, 0x1f, 0xac, + 0xd7, 0x79, 0x37, 0xa5, 0x97, 0xc7, 0xa6}; + std::array const salt{0x55, 0x41, 0xfb, 0xc9, 0x95, 0xd5, 0xc1, 0x97, + 0xba, 0x29, 0x03, 0x46, 0xd2, 0xc5, 0x59, 0xde}; + std::array tag{}; + auto const argon2 = hash::argon2id(tag, password, salt, {5, 7256064}); + print_hex("argon2id", tag); + + std::array scrypted{}; + auto const scrypt = hash::scrypt(scrypted, bytes("password"), bytes("NaCl"), {1024, 8, 16}); + print_hex("scrypt", scrypted); + + print_hex("hkdf", rfc5869_a1_okm()); + return argon2 && scrypt ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/pw/pw.outcome b/tools/test/fixtures/hash_jamfiles/pw/pw.outcome new file mode 100644 index 00000000..16ae2f7a --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/pw/pw.outcome @@ -0,0 +1,13 @@ +# 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) + +[all] +targets: native wasip2 wasip3 emscripten +build: succeeds +run: pw +argon2id 18acec5d6507739f203d1f5d9f1d862f7c2cdac4f19d2bdff64487e60d969e3ced615337b9eec6ac4461c6ca07f0939741e57c24d0005c7ea171a0ee1e7348249d135b38f222e4dad7b9a033ed83f5ca27277393e316582033c74affe2566a2bea47f91f0fd9fe49ece7e1f79f3ad6e9b23e0277c8ecc4b313225748dd2a80f5679534a0700e246a79a49b3f74eb89ec6205fe1eeb941c73b1fcf1 +scrypt fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640 +hkdf 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865 diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/Jamfile b/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/Jamfile new file mode 100644 index 00000000..ec2f7afc --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/scrypt_on_hash2 of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/app.cpp b/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/app.cpp new file mode 100644 index 00000000..6ddaa95b --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/app.cpp @@ -0,0 +1,19 @@ +// 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) + +// scrypt on another backend than backends::sodium stops with spec section 3.3's text. + +#include +#include + +#include +#include + +int main() { + std::array output{}; + auto done = webcpp::hash::scrypt(output, {}, {}, {16, 1, 1}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/scrypt_on_hash2.outcome b/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/scrypt_on_hash2.outcome new file mode 100644 index 00000000..79e06c6e --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_on_hash2/scrypt_on_hash2.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/scrypt_on_hash2, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: scrypt is in backends::sodium alone. Name backends::sodium and add /third_party//sodium to the program's Jamfile. diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/Jamfile b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/Jamfile new file mode 100644 index 00000000..5ed40cbd --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/Jamfile @@ -0,0 +1,10 @@ +# 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) + +# test/messages/scrypt_override_hash2 of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//sodium + : WEBCPP_HASH_DEFAULT_BACKEND_SCRYPT_HASH2 ; diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/app.cpp b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/app.cpp new file mode 100644 index 00000000..89f773fe --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/app.cpp @@ -0,0 +1,20 @@ +// 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) + +// An override of scrypt's default backend is honoured (spec 4.1), even with libsodium linked: +// WEBCPP_HASH_DEFAULT_BACKEND_SCRYPT_HASH2 and a call that names no backend stop with +// backends::hash2's refusal of spec 3.3, and with no other error. + +#include + +#include +#include + +int main() { + std::array output{}; + auto done = webcpp::hash::scrypt(output, {}, {}, {.n = 16, .r = 1, .p = 1}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/scrypt_override_hash2.outcome b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/scrypt_override_hash2.outcome new file mode 100644 index 00000000..1faf4361 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/scrypt_override_hash2.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/scrypt_override_hash2, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: scrypt is in backends::sodium alone. Name backends::sodium and add /third_party//sodium to the program's Jamfile. diff --git a/tools/test/fixtures/hash_jamfiles/sodium_hmac/Jamfile b/tools/test/fixtures/hash_jamfiles/sodium_hmac/Jamfile new file mode 100644 index 00000000..6516e7f1 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/sodium_hmac/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/sodium_hmac of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash /third_party//sodium ; diff --git a/tools/test/fixtures/hash_jamfiles/sodium_hmac/app.cpp b/tools/test/fixtures/hash_jamfiles/sodium_hmac/app.cpp new file mode 100644 index 00000000..db10b589 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/sodium_hmac/app.cpp @@ -0,0 +1,21 @@ +// 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) + +// hkdf over an hmac libsodium has no HKDF for stops with spec section 3.3's text for +// backends::sodium. + +#include + +#include +#include + +int main() { + std::array output{}; + std::array input{}; + auto done = webcpp::hash::hkdf( + output, input, input, input); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/sodium_hmac/sodium_hmac.outcome b/tools/test/fixtures/hash_jamfiles/sodium_hmac/sodium_hmac.outcome new file mode 100644 index 00000000..9747cbbc --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/sodium_hmac/sodium_hmac.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/sodium_hmac, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: backends::sodium has HKDF over hmac_sha2_256 and hmac_sha2_512 alone. Over this hmac, name backends::hash2 (every hmac), backends::openssl (every hmac but hmac_ripemd_128) or backends::bearssl (MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512; hkdf alone). diff --git a/tools/test/fixtures/hash_jamfiles/sodium_not_linked/Jamfile b/tools/test/fixtures/hash_jamfiles/sodium_not_linked/Jamfile new file mode 100644 index 00000000..e03b00bb --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/sodium_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/sodium_not_linked of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/sodium_not_linked/app.cpp b/tools/test/fixtures/hash_jamfiles/sodium_not_linked/app.cpp new file mode 100644 index 00000000..0573b04a --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/sodium_not_linked/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// A program that names backends::sodium and does not link libsodium stops with the instruction to +// add /third_party//sodium (spec section 5.7, the third row). + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/sodium_not_linked/sodium_not_linked.outcome b/tools/test/fixtures/hash_jamfiles/sodium_not_linked/sodium_not_linked.outcome new file mode 100644 index 00000000..c0cf3516 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/sodium_not_linked/sodium_not_linked.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/sodium_not_linked, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: backends::sodium, argon2id and scrypt need libsodium. Add /third_party//sodium to the program's Jamfile: exe app : app.cpp /webcpp/hash//hash /third_party//sodium ; diff --git a/tools/test/fixtures/hash_jamfiles/two_overrides/Jamfile b/tools/test/fixtures/hash_jamfiles/two_overrides/Jamfile new file mode 100644 index 00000000..9802d87f --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_overrides/Jamfile @@ -0,0 +1,11 @@ +# 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) + +# test/messages/two_overrides of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_DEFAULT_BACKEND_HKDF_HASH2 + WEBCPP_HASH_DEFAULT_BACKEND_HKDF_SODIUM ; diff --git a/tools/test/fixtures/hash_jamfiles/two_overrides/app.cpp b/tools/test/fixtures/hash_jamfiles/two_overrides/app.cpp new file mode 100644 index 00000000..c3c0a5e3 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_overrides/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// Two overrides of HKDF's default backend (spec 4.1) stop the build with an #error naming both +// defines. + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/two_overrides/two_overrides.outcome b/tools/test/fixtures/hash_jamfiles/two_overrides/two_overrides.outcome new file mode 100644 index 00000000..1949f007 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_overrides/two_overrides.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/two_overrides, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: WEBCPP_HASH_DEFAULT_BACKEND_HKDF_HASH2 and WEBCPP_HASH_DEFAULT_BACKEND_HKDF_SODIUM are both defined. Keep one. diff --git a/tools/test/fixtures/hash_jamfiles/two_profiles/Jamfile b/tools/test/fixtures/hash_jamfiles/two_profiles/Jamfile new file mode 100644 index 00000000..8ddb1af4 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_profiles/Jamfile @@ -0,0 +1,11 @@ +# 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) + +# test/messages/two_profiles of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_HASH_PROFILE_FASTEST + WEBCPP_HASH_PROFILE_SMALLEST ; diff --git a/tools/test/fixtures/hash_jamfiles/two_profiles/app.cpp b/tools/test/fixtures/hash_jamfiles/two_profiles/app.cpp new file mode 100644 index 00000000..5bc57eb5 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_profiles/app.cpp @@ -0,0 +1,13 @@ +// 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) + +// Two library profiles (spec 4.1) stop the build with an #error naming both defines. + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/two_profiles/two_profiles.outcome b/tools/test/fixtures/hash_jamfiles/two_profiles/two_profiles.outcome new file mode 100644 index 00000000..ee7e5835 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_profiles/two_profiles.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/two_profiles, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: WEBCPP_HASH_PROFILE_FASTEST and WEBCPP_HASH_PROFILE_SMALLEST are both defined. Keep one. diff --git a/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/Jamfile b/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/Jamfile new file mode 100644 index 00000000..f58c6537 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/Jamfile @@ -0,0 +1,11 @@ +# 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) + +# test/messages/two_umbrella_profiles of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash + : WEBCPP_PROFILE_FASTEST + WEBCPP_PROFILE_PORTABLE ; diff --git a/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/app.cpp b/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/app.cpp new file mode 100644 index 00000000..5d49b9ba --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// Two of webcpp's umbrella profiles (spec 4.1) stop the build with an #error naming both +// defines. + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/two_umbrella_profiles.outcome b/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/two_umbrella_profiles.outcome new file mode 100644 index 00000000..8acadddf --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/two_umbrella_profiles.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/two_umbrella_profiles, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: WEBCPP_PROFILE_FASTEST and WEBCPP_PROFILE_PORTABLE are both defined. Keep one. diff --git a/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/Jamfile b/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/Jamfile new file mode 100644 index 00000000..2b89acc3 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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) + +# test/messages/xkcp_not_linked of webcpp::hash, built for Emscripten +# by a user's Jamfile. +exe app : app.cpp /webcpp/hash//hash ; diff --git a/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/app.cpp b/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/app.cpp new file mode 100644 index 00000000..b28b356b --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/app.cpp @@ -0,0 +1,14 @@ +// 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) + +// A program that names keccak_256 and does not link XKCP stops with the instruction to add +// /third_party//xkcp (spec section 5.7, the first row). + +#include + +int main() { + return 0; +} diff --git a/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/xkcp_not_linked.outcome b/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/xkcp_not_linked.outcome new file mode 100644 index 00000000..b7fa7b20 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/xkcp_not_linked/xkcp_not_linked.outcome @@ -0,0 +1,13 @@ +# 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 compiler's line starts with the header's path on the machine, so the +# message is a contains: line. Natively and on WASI the same text is +# test/messages/xkcp_not_linked, a compile-diagnostic. +[all] +targets: emscripten +build: fails +contains: webcpp::hash: keccak_256 needs XKCP. Add /third_party//xkcp to the program's Jamfile: exe app : app.cpp /webcpp/hash//hash /third_party//xkcp ; diff --git a/tools/test/hash_doc_tables_test.py b/tools/test/hash_doc_tables_test.py new file mode 100644 index 00000000..4576e9ad --- /dev/null +++ b/tools/test/hash_doc_tables_test.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python3 +# 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) + +"""Checks tools/hash/doc_tables.py, the generated tables of webcpp::hash's guide, on a copy of +the real library's doc/capabilities.json and doc/guide.json in a scratch library. `--write` +renders the comparison table of every chapter, the backends of every algorithm, the decision +table, the includes of the measured chapters and llms.txt, the same bytes each time; `--check` +passes on what it wrote, and fails naming `python3 tools/hash/doc_tables.py --write` when a +generated file was edited by hand, is missing or is left over. A guide that lacks a function of +the capability table, or describes one it does not have, fails, and so does a use case whose +example is not there. Without doc/measurements.json the tables say so and carry no measured +column; with it (a fixture in its shape) they carry the throughput and the size, and the default +of `hkdf_extract` on Emscripten follows the step's own measured order, not HKDF's, as +detail/ranking.hpp does. The includes of the measured chapters name only those present. And +`--check` passes on the real library's committed files. Run with the names of some cases to run +only those.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +import tempfile +from collections.abc import Callable +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +TOOL = ROOT / 'tools/hash/doc_tables.py' +LIBRARY = ROOT / 'libs/hash' +WRITE = 'python3 tools/hash/doc_tables.py --write' + + +def run(library: Path, mode: str) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(TOOL), mode, '--library', str(library)], + capture_output=True, text=True, check=False) + + +def expect(condition: bool, message: str) -> None: + if not condition: + raise AssertionError(message) + + +def scratch_library(scratch: Path) -> Path: + """A library with the real capability table and guide, and an example file for each use + case.""" + library = scratch / 'hash' + (library / 'doc').mkdir(parents=True) + (library / 'example').mkdir() + for name in ('capabilities.json', 'guide.json'): + shutil.copy(LIBRARY / 'doc' / name, library / 'doc' / name) + guide = json.loads((library / 'doc/guide.json').read_text(encoding='utf-8')) + for case in guide['use_cases']: + (library / 'example' / case['example']).write_text('// fixture\n', encoding='utf-8') + return library + + +def written(library: Path) -> dict[str, str]: + doc = library / 'doc' + files = {str(p.relative_to(doc)): p.read_text(encoding='utf-8') + for p in (doc / 'generated').glob('*.adoc')} + files['llms.txt'] = (doc / 'llms.txt').read_text(encoding='utf-8') + return files + + +def write_ok(library: Path) -> dict[str, str]: + done = run(library, '--write') + expect(done.returncode == 0, f'--write failed: {done.stderr}') + return written(library) + + +def measurements(library: Path) -> dict: + """doc/measurements.json's shape (tools/hash/measure.py), for HKDF's three operations and + sha2_256: HKDF is smallest on BearSSL, then sodium, then hash2; each step alone is smallest + on hash2, then sodium (an order of its own, which HKDF's must not replace).""" + records = [] + whole = {'hash2': 3000, 'sodium': 2000, 'bearssl': 1000, 'openssl': 9000} + step = {'hash2': 1500, 'sodium': 2000, 'openssl': 9000} + for operation, sizes in (('hkdf', whole), ('hkdf_extract', step), + ('hkdf_expand', step)): + for backend in sizes: + for target in ('native', 'wasip2', 'wasip3', 'emscripten'): + if backend == 'openssl' and target == 'emscripten': + continue + records.append({'operation': operation, 'hmac': 'hmac_sha2_256', + 'backend': backend, 'target': target, + 'size_bytes': sizes[backend], + 'throughput': {'median_ns': 1000.0 + sizes[backend], + 'min_ns': 1.0, 'max_ns': 2.0}, + 'throughput_absent': None}) + records.append({'operation': 'sha2_256', 'hmac': None, 'backend': 'hash2', + 'target': 'native', 'size_bytes': 33776, + 'throughput': {'median_ns': 1757469.0, 'min_ns': 1.0, 'max_ns': 2.0}, + 'throughput_absent': None}) + records.append({'operation': 'sha2_256', 'hmac': None, 'backend': 'hash2', + 'target': 'emscripten', 'size_bytes': 19235, + 'throughput': None, 'throughput_absent': 'fixture'}) + orders = [] + for operation, sizes in (('hkdf', whole), ('hkdf_extract', step), + ('hkdf_expand', step)): + for target in ('native', 'wasip2', 'wasip3', 'emscripten'): + have = [r['backend'] for r in records + if r['operation'] == operation and r['target'] == target] + orders.append({'operation': operation, 'hmac': 'hmac_sha2_256', 'target': target, + 'by_size': sorted(have, key=lambda b: sizes[b]), + 'by_throughput': sorted(have, key=lambda b: sizes[b]), + 'throughput_from': target}) + data = {'date': '2026-11-15', 'machine': {'cpu': 'Fixture CPU'}, 'loaded': True, + 'records': records, 'orders': orders} + (library / 'doc/measurements.json').write_text(json.dumps(data), encoding='utf-8') + return data + + +def test_write_is_deterministic(scratch: Path) -> None: + library = scratch_library(scratch) + first = write_ok(library) + second = write_ok(library) + expect(first == second, 'two --write runs differ') + for chapter in ('digests', 'macs', 'kdfs', 'password-hashing', 'non-cryptographic'): + expect(f'generated/compare-{chapter}.adoc' in first, f'no comparison table of {chapter}') + expect('generated/backends-hkdf.adoc' in first, 'no backends of HKDF') + expect('generated/choose.adoc' in first, 'no decision table') + expect('generated/measured.adoc' in first, 'no includes of the measured chapters') + for text in first.values(): + expect(chr(0x2014) not in text, 'an em dash in a generated file') + + +def test_check_passes_on_what_write_wrote(scratch: Path) -> None: + library = scratch_library(scratch) + write_ok(library) + done = run(library, '--check') + expect(done.returncode == 0, f'--check failed: {done.stderr}') + + +def test_a_hand_edit_fails(scratch: Path) -> None: + library = scratch_library(scratch) + write_ok(library) + path = library / 'doc/generated/compare-digests.adoc' + path.write_text(path.read_text(encoding='utf-8') + 'edited\n', encoding='utf-8') + done = run(library, '--check') + expect(done.returncode == 1, 'a hand edit passed --check') + expect('compare-digests.adoc differs' in done.stderr and WRITE in done.stderr, + f'the fault does not name the file and the command: {done.stderr}') + + +def test_a_missing_or_left_over_file_fails(scratch: Path) -> None: + library = scratch_library(scratch) + write_ok(library) + (library / 'doc/llms.txt').unlink() + (library / 'doc/generated/backends-gone.adoc').write_text('x\n', encoding='utf-8') + done = run(library, '--check') + expect(done.returncode == 1, 'a missing and a left-over file passed --check') + expect('doc/llms.txt is missing' in done.stderr, done.stderr) + expect('backends-gone.adoc is left over' in done.stderr, done.stderr) + write_ok(library) + expect(not (library / 'doc/generated/backends-gone.adoc').exists(), + '--write left a file no data renders') + + +def test_the_guide_covers_the_capability_table(scratch: Path) -> None: + library = scratch_library(scratch) + path = library / 'doc/guide.json' + guide = json.loads(path.read_text(encoding='utf-8')) + del guide['functions']['blake3'] + guide['functions']['sha4_256'] = guide['functions']['sha2_256'] + path.write_text(json.dumps(guide), encoding='utf-8') + done = run(library, '--write') + expect(done.returncode == 1, 'an incomplete guide was rendered') + expect('no entry for blake3' in done.stderr, done.stderr) + expect('describes sha4_256' in done.stderr, done.stderr) + + +def test_a_use_case_names_an_example_that_is_there(scratch: Path) -> None: + library = scratch_library(scratch) + (library / 'example/hkdf.cpp').unlink() + done = run(library, '--write') + expect(done.returncode == 1, 'a use case with no example was rendered') + expect('example/hkdf.cpp, which is not there' in done.stderr, done.stderr) + + +def test_without_measurements_the_tables_say_so(scratch: Path) -> None: + library = scratch_library(scratch) + files = write_ok(library) + expect('Fastest natively' not in files['generated/compare-digests.adoc'], + 'a measured column without measurements') + expect('does not have yet' in files['generated/compare-digests.adoc'], + 'the comparison table does not say its measurements are missing') + expect('detail/ranking.hpp' in files['generated/backends-hkdf.adoc'], + 'the backends of HKDF do not say which order applies') + expect('Backends: hash2 (/webcpp/hash//hash' in files['llms.txt'], 'llms.txt has no backends') + + +def test_with_measurements_the_tables_carry_them(scratch: Path) -> None: + library = scratch_library(scratch) + measurements(library) + files = write_ok(library) + digests = files['generated/compare-digests.adoc'] + expect('Fastest natively' in digests, 'no measured column') + expect('569 MiB/s (hash2)' in digests, 'sha2_256 throughput: 1 MiB in 1.757 ms') + expect('19,235 bytes (hash2)' in digests, 'sha2_256 size on Emscripten') + hkdf = files['generated/backends-hkdf.adoc'] + # Each step on Emscripten: its own order hash2, sodium; HKDF's would give sodium, hash2. + for name in ('hkdf_extract', 'hkdf_expand'): + rows = hkdf.split(f'default backend of `{name}`')[1].split('|===')[1] + emscripten = rows.split('| emscripten')[1].split('\n\n')[0] + expect('| hash2, sodium\n| hash2, sodium\n| hash2, sodium\n| hash2' in emscripten, + f'{name} on Emscripten does not follow its own order: {emscripten!r}') + expect('own orders' in hkdf and '`hmac_sha2_512`' in hkdf, + 'HKDF\'s note does not say that another hmac has its own orders') + expect('hmac_sha2_256' not in files['generated/backends-argon2id.adoc'], + 'Argon2id\'s note names an hmac it does not have') + expect('a loaded, shared machine' in digests, 'the note hides that the machine was loaded') + expect('libsodium 1.0.22: its headers state constant time' in hkdf, + 'the constant-time column does not give its source') + whole = hkdf.split('default backend of `hkdf`')[1].split('|===')[1] + native = whole.split('| native')[1].split('\n\n')[0] + expect('| bearssl, sodium, hash2, openssl' in native, f'hkdf natively: {native!r}') + + +def test_no_table_is_a_matrix(scratch: Path) -> None: + # The page scrolls a table of eight columns or more, a matrix, in its box rather than stack + # it (tools/doc/postprocess.mjs, MATRIX), at 1440px too. A chapter's comparison is two tables + # instead, what each function is and how to choose it, each led by the name and each under + # eight columns, with the measured columns or without them. + library = scratch_library(scratch) + for measured in (False, True): + if measured: + measurements(library) + files = write_ok(library) + for name, text in files.items(): + for table in text.split('|===')[1::2]: + header = table.strip().split('\n')[0] + expect(header.count('| ') < 8, f'{name} ({measured}): a matrix: {header}') + digests = files['generated/compare-digests.adoc'] + headers = [table.strip().split('\n')[0] for table in digests.split('|===')[1::2]] + expect(len(headers) == 2 and all(h.startswith('| Name |') for h in headers), str(headers)) + expect('Security' in headers[0] and 'Choose it when' in headers[1], str(headers)) + expect(('Fastest natively' in headers[1]) == measured, str(headers)) + + +def test_measured_chapters_are_included_when_present(scratch: Path) -> None: + library = scratch_library(scratch) + (library / 'doc/performance.adoc').write_text('x\n', encoding='utf-8') + files = write_ok(library) + measured = files['generated/measured.adoc'] + expect('include::../performance.adoc[]' in measured, 'performance.adoc not included') + expect('include::../backends.adoc[]' not in measured, 'an absent chapter is included') + expect('`doc/backends.adoc` (tools/hash/measure.py --capabilities)' in measured, + 'the absent chapter is not named') + for name in ('backends.adoc', 'measurements.adoc', 'allocation.adoc'): + (library / 'doc' / name).write_text('x\n', encoding='utf-8') + measured = write_ok(library)['generated/measured.adoc'] + expect('NOTE' not in measured, 'a note with every chapter present') + expect(measured.index('backends.adoc') < measured.index('measurements.adoc') + < measured.index('performance.adoc') < measured.index('allocation.adoc'), + 'the measured chapters are out of order') + + +def test_the_real_library_s_files_are_its_data_s(scratch: Path) -> None: + del scratch + done = run(LIBRARY, '--check') + expect(done.returncode == 0, f'the committed files are stale: {done.stderr}') + + +CASES: list[Callable[[Path], None]] = [ + test_write_is_deterministic, + test_check_passes_on_what_write_wrote, + test_a_hand_edit_fails, + test_a_missing_or_left_over_file_fails, + test_the_guide_covers_the_capability_table, + test_a_use_case_names_an_example_that_is_there, + test_without_measurements_the_tables_say_so, + test_with_measurements_the_tables_carry_them, + test_no_table_is_a_matrix, + test_measured_chapters_are_included_when_present, + test_the_real_library_s_files_are_its_data_s, +] + + +def main(argv: list[str]) -> int: + unknown = set(argv) - {case.__name__ for case in CASES} + if unknown: + print(f'hash_doc_tables_test: no case named {", ".join(sorted(unknown))}', + file=sys.stderr) + return 2 + for case in CASES: + if argv and case.__name__ not in argv: + continue + with tempfile.TemporaryDirectory(prefix='webcpp hash doc tables ') as scratch: + case(Path(scratch)) + print(f'{case.__name__}: ok') + print('hash_doc_tables_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/hash_jamfiles_format_test.py b/tools/test/hash_jamfiles_format_test.py new file mode 100644 index 00000000..ff0b1748 --- /dev/null +++ b/tools/test/hash_jamfiles_format_test.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +# 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) + +"""Checks, without building anything, that every message of libs/hash/test/messages has its +Emscripten fixture in tools/test/fixtures/hash_jamfiles with the same source and text, and that +hash_jamfiles_test.py's check finds each kind of drift: a message without a fixture, a changed +source, a changed text, and a fixture that names a message with no directory.""" + +from __future__ import annotations + +import shutil +import sys +import tempfile +from collections.abc import Callable +from pathlib import Path + +import hash_jamfiles_test as jamfiles +import user_jamfiles + + +def faults_of_copies(change: Callable[[Path, Path], None]) -> list[str]: + """message_faults over copies of the messages and the fixtures, after change(messages, + fixtures) has altered the copies.""" + with tempfile.TemporaryDirectory() as directory: + messages = Path(directory) / 'messages' + fixtures = Path(directory) / 'fixtures' + shutil.copytree(jamfiles.MESSAGES, messages) + shutil.copytree(jamfiles.CASES, fixtures) + change(messages, fixtures) + original = jamfiles.MESSAGES + jamfiles.MESSAGES = messages + try: + return jamfiles.message_faults(user_jamfiles.case_directories(fixtures)) + finally: + jamfiles.MESSAGES = original + + +def test_the_tree_has_no_fault(): + faults = jamfiles.message_faults(user_jamfiles.case_directories(jamfiles.CASES)) + assert faults == [], faults + + +def test_a_message_without_fixture_is_a_fault(): + def change(messages: Path, _: Path) -> None: + shutil.copytree(messages / 'two_profiles', messages / 'three_profiles') + (messages / 'three_profiles' / 'two_profiles.cpp').rename( + messages / 'three_profiles' / 'three_profiles.cpp') + + faults = faults_of_copies(change) + assert any('three_profiles has no fixture' in f for f in faults), faults + + +def test_a_changed_source_is_a_fault(): + def change(messages: Path, _: Path) -> None: + source = messages / 'two_profiles' / 'two_profiles.cpp' + source.write_text(source.read_text().replace('return 0;', 'return 1;')) + + faults = faults_of_copies(change) + assert any(f.startswith('two_profiles: app.cpp') for f in faults), faults + + +def test_a_changed_text_is_a_fault(): + def change(messages: Path, _: Path) -> None: + source = messages / 'xkcp_not_linked' / 'xkcp_not_linked.cpp' + source.write_text(source.read_text().replace('needs XKCP', 'needs Keccak')) + + faults = faults_of_copies(change) + assert any(f.startswith('xkcp_not_linked: the outcome') for f in faults), faults + + +def test_a_fixture_of_no_message_is_a_fault(): + def change(messages: Path, _: Path) -> None: + shutil.rmtree(messages / 'two_overrides') + + faults = faults_of_copies(change) + assert any(f.startswith('two_overrides: its Jamfile names') for f in faults), faults + + +def main() -> int: + if not jamfiles.MESSAGES.is_dir(): + print('hash_jamfiles_format: libs/hash is not checked out. Check it out with ' + '`git submodule update --init libs/hash`.', file=sys.stderr) + return 2 + for name, case in sorted(globals().items()): + if name.startswith('test_'): + case() + print(f'{name}: ok') + print('hash_jamfiles_format_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/test/hash_jamfiles_test.py b/tools/test/hash_jamfiles_test.py new file mode 100644 index 00000000..50b868f5 --- /dev/null +++ b/tools/test/hash_jamfiles_test.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +# 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) + +"""Builds every fixture of tools/test/fixtures/hash_jamfiles, a Jamfile as a user of webcpp::hash +writes it (b2's raw exe), with b2 as a user runs it, and checks its outcome file: the build's +status, the lines a failure prints, and a program's output (CODING-GUIDELINES.md chapter 8), +through user_jamfiles.py. The cases are each line of the library's spec 5.1, one program with +every C library, and each stop of the build: the canaries at link time on every target, and the +messages raised on Emscripten. + +Each message of libs/hash/test/messages// (a compile-diagnostic, natively and on WASI) has +the fixture , its Emscripten case: before building anything, the test checks that the +fixture's app.cpp is the message's source without its expected-error directive, and that its +outcome's one contains: line is the directive's text, unless the message is in NO_FIXTURE. + +The scratch superproject holds libs/config, libs/hash and libs/crypto (whose canary +/third_party//bearssl compiles). Run with the names of some cases to run only those, and with +--target to run one target.""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +import harness +import user_jamfiles + +CASES = harness.FIXTURES / 'hash_jamfiles' +MESSAGES = harness.ROOT / 'libs/hash/test/messages' + +# Cases whose outcome needs code that is not merged yet, as crypto_jamfiles_test.py's NOT_YET. +NOT_YET: dict[str, str] = {} + +# The messages of libs/hash/test/messages without an Emscripten fixture, each with its reason. +NO_FIXTURE = { + 'ripemd128_on_openssl': 'it names /webcpp/hash//openssl, which Emscripten refuses before ' + 'the message (the fixture openssl_on_emscripten)', +} + +DIRECTIVE = re.compile(r'^// expected-error@\S+ \{\{(.*)\}\}$', re.MULTILINE) +# The Jamfile's first line after the licence names the message a fixture builds. +CLAIM = re.compile(r'^# test/messages/(\S+) of webcpp::hash', re.MULTILINE) + + +def program_of(source: str) -> str: + """A message's source as a user's program: without its expected-error directive, the + clang-format guards around it and the note on clang's -verify, which only the + compile-diagnostic rule reads, and with no run of blank lines left behind.""" + text = re.sub(r'^// expected-error@.*\n', '', source, flags=re.MULTILINE) + text = text.replace('// clang-format off\n// clang-format on\n', '') + text = re.sub(r"^// clang's -verify reads.*\n(?://.*\n)*", '', text, flags=re.MULTILINE) + return re.sub(r'\n\n\n+', '\n\n', text) + + +def message_faults(cases: list[Path]) -> list[str]: + """The faults between libs/hash/test/messages and the fixtures, found without b2: a message + with no fixture and no entry in NO_FIXTURE, a fixture whose source or text is not its + message's, and a fixture that claims a message there is no directory of.""" + faults: list[str] = [] + by_name = {case.name: case for case in cases} + messages = sorted(p for p in MESSAGES.iterdir() if p.is_dir()) + for message in messages: + name = message.name + case = by_name.get(name) + if name in NO_FIXTURE: + if case is not None: + faults.append(f'{name}: a fixture of a message in NO_FIXTURE') + continue + if case is None: + faults.append(f'test/messages/{name} has no fixture {name} (an Emscripten case), ' + 'nor an entry in NO_FIXTURE') + continue + source = (message / f'{name}.cpp').read_text() + texts = DIRECTIVE.findall(source) + if (case / 'app.cpp').read_text() != program_of(source): + faults.append(f'{name}: app.cpp is not test/messages/{name}/{name}.cpp without its ' + 'directive') + expected = user_jamfiles.outcome(case / f'{name}.outcome', 'emscripten') + if expected.targets != ['emscripten'] or expected.contains != texts: + faults.append(f'{name}: the outcome is not the text {texts!r} on emscripten alone') + names = {m.name for m in messages} + for case in cases: + claimed = CLAIM.search((case / 'Jamfile').read_text()) + if claimed and (claimed.group(1) != case.name or case.name not in names): + faults.append(f'{case.name}: its Jamfile names test/messages/{claimed.group(1)}, ' + 'which is not its own message directory') + return faults + + +def main(argv: list[str]) -> int: + return user_jamfiles.main('hash_jamfiles', CASES, ('config', 'hash', 'crypto'), NOT_YET, argv, + message_faults) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/hash_measure_test.py b/tools/test/hash_measure_test.py new file mode 100644 index 00000000..a6d5cf16 --- /dev/null +++ b/tools/test/hash_measure_test.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python3 +# 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) + +"""Checks tools/hash/measure.py, webcpp::hash's measured table (spec section 4.2), on a fixture +library: a capability table of four backends and five functions, and measurements made up for +it. `--write --measured` renders doc/measurements.json, doc/measurements.adoc, +detail/ranking.hpp, detail/overrides.hpp, doc/backends.adoc and test/measure/cells.jam, the same +bytes each time; `--check` passes on what it wrote, and fails naming +`python3 tools/hash/measure.py --write` when the size order of a row changes, when a throughput +median moves more than 10 percent past the one ahead of it (spec 4.2's rule alone: a +first measurement orders by the medians, and the runs' spread plays no part), when a generated +file or the data was edited by hand, and when a program of a cell is missing on a target (a lane +that built nothing); a median that moves by under 10 percent changes nothing. Each key +derivation operation has its own ranking (hkdf_extract and hkdf_expand beside hkdf); every order +names every backend with a tag, so that the per-operation default always finds one; the +portable order is hash2, sodium, bearssl. Native orders measured with another native toolchain +are not compared, said in one line, while WebAssembly's are. `--capabilities` renders the +capability table; `--overrides`, run on the real library, gives detail/overrides.hpp byte for +byte; and `--check` passes on the real library's committed data, without a build. Run with the names +of some cases to run only those.""" + +from __future__ import annotations + +import copy +import functools +import json +import re +import runpy +import shutil +import subprocess +import sys +import tempfile +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +MEASURE = ROOT / 'tools/hash/measure.py' +LIBRARY = ROOT / 'libs/hash' +WRITE = 'python3 tools/hash/measure.py --write' + +TARGETS = ('native', 'wasip2', 'wasip3', 'emscripten') +ALL = list(TARGETS) +NOT_EMSCRIPTEN = ['native', 'wasip2', 'wasip3'] + +# The outputs of --write, relative to the library. +OUTPUTS = ( + 'doc/measurements.json', + 'doc/measurements.adoc', + 'doc/backends.adoc', + 'include/webcpp/hash/detail/ranking.hpp', + 'include/webcpp/hash/detail/overrides.hpp', + 'test/measure/cells.jam', +) + +STATED = {'value': 'not stated', 'source': 'the fixture states nothing.'} + + +def cell(hmacs: list[str] | None) -> dict[str, Any]: + return {'since': 1, 'hmacs': hmacs, 'constant_time': STATED} + + +def capabilities() -> dict[str, Any]: + """A capability table in the layout of doc/capabilities.json, version 2: SHA-256 on hash2; + HKDF's three functions on hash2, libsodium, OpenSSL and (whole) BearSSL; PBKDF2 on hash2 + and OpenSSL; Argon2id on libsodium.""" + hmacs = ['hmac_sha2_256', 'hmac_sha2_512'] + + def backend(name: str, tag: str | None, targets: Sequence[str], portable: bool) -> dict: + return {'name': name, 'tag': tag, 'macro': name.upper(), 'library': f'{name} 1.0', + 'licence': 'BSL-1.0', 'targets': list(targets), + 'jamfile': '/webcpp/hash//hash' if name == 'hash2' else f'/third_party//{name}', + 'portable': portable} + + def function(name: str, tag: str | None, kind: str, cells: dict) -> dict: + return {'name': name, 'kind': kind, 'tag': tag, 'header': f'webcpp/hash/{name}.hpp', + 'backends': cells} + + hkdf_steps = {'hash2': cell(hmacs), 'sodium': cell(hmacs), 'openssl': cell(hmacs)} + return { + 'about': 'the fixture', 'version': 2, 'layout': {}, + 'targets': ALL, + 'backends': [ + backend('hash2', 'backends::hash2', ALL, True), + backend('xkcp', None, ALL, True), + backend('sodium', 'backends::sodium', ALL, True), + backend('bearssl', 'backends::bearssl', ALL, True), + backend('openssl', 'backends::openssl', NOT_EMSCRIPTEN, False), + ], + 'hmacs': hmacs + ['other'], + 'algorithms': [ + {'name': 'sha2', 'macro': 'SHA2', 'tag': None, 'chapter': 'digests', + 'standard': 'FIPS 180-4', 'overridable': False, + 'functions': [function('sha2_256', None, 'type', {'hash2': cell(None)})]}, + {'name': 'hkdf', 'macro': 'HKDF', 'tag': 'kdfs::hkdf', 'chapter': 'kdfs', + 'standard': 'RFC 5869', 'overridable': True, + 'functions': [ + function('hkdf_extract', 'kdfs::hkdf_extract', 'function', hkdf_steps), + function('hkdf_expand', 'kdfs::hkdf_expand', 'function', + copy.deepcopy(hkdf_steps)), + function('hkdf', 'kdfs::hkdf', 'function', + {'hash2': cell(hmacs), 'sodium': cell(hmacs), + 'bearssl': cell(hmacs), 'openssl': cell(hmacs)})]}, + {'name': 'pbkdf2', 'macro': 'PBKDF2', 'tag': 'kdfs::pbkdf2', 'chapter': 'kdfs', + 'standard': 'RFC 8018', 'overridable': True, + 'functions': [function('pbkdf2', 'kdfs::pbkdf2', 'function', + {'hash2': cell(hmacs), 'openssl': cell(hmacs)})]}, + {'name': 'argon2id', 'macro': 'ARGON2ID', 'tag': 'kdfs::argon2id', + 'chapter': 'password_hashing', 'standard': 'RFC 9106', 'overridable': True, + 'functions': [function('argon2id', 'kdfs::argon2id', 'function', + {'sodium': cell(None)})]}, + ], + } + + +# Made-up sizes and times per backend: hash2 the smallest, OpenSSL the fastest natively. +SIZES = {'hash2': 20000, 'sodium': 30000, 'bearssl': 40000, 'openssl': 900000} +TIMES = {'hash2': 1000.0, 'sodium': 1500.0, 'bearssl': 2000.0, 'openssl': 400.0} + + +def throughput(median: float, spread: float = 0.02) -> dict[str, Any]: + runs = [median * (1 - spread), median, median * (1 + spread)] + return {'repetitions': 1, 'invocations': 1, 'runs_per_invocation': 3, + 'invocation_medians_ns': [median], 'median_ns': median, + 'min_ns': min(runs), 'max_ns': max(runs)} + + +@functools.cache +def result_of(operation: str, hmac: str | None) -> str: + """The value Python computes for the operation, as measure.py checks it, else one made up; + measure.py is loaded once, and each value computed once.""" + python_value = measure_module()['python_value'] + return python_value(operation, hmac) or f'{operation}-{hmac}'.encode().hex() + + +@functools.cache +def measure_module() -> dict[str, Any]: + """measure.py's names, loaded once.""" + return runpy.run_path(str(MEASURE)) + + +def measured(table: dict[str, Any]) -> dict[str, Any]: + """Measurements of every cell of the table on every target of its backend, as the fixture's + SIZES and TIMES say, every result the same per operation and hmac.""" + records = [] + targets_of = {b['name']: b['targets'] for b in table['backends']} + for algorithm in table['algorithms']: + for function in algorithm['functions']: + for name, c in function['backends'].items(): + hmacs = [h for h in ('hmac_sha2_256', 'hmac_sha2_512') + if c['hmacs'] and h in c['hmacs']] or [None] + for hmac in hmacs: + for target in targets_of[name]: + scale = 1 if target == 'native' else 2 + records.append({ + 'operation': function['name'], 'hmac': hmac, 'backend': name, + 'target': target, 'size_bytes': SIZES[name] * scale, + 'result': result_of(function['name'], hmac), + 'throughput': throughput(TIMES[name] * scale)}) + return { + 'date': '2026-11-15', + 'machine': {'cpu': 'fixture', 'cores': 18, 'memory_gib': 128, 'os': 'fixture'}, + 'load_average_before_after': [[30.0, 30.0, 30.0], [31.0, 30.0, 30.0]], + 'loaded': True, + 'toolchains': {t: f'{t} compiler 1.0' for t in TARGETS}, + 'runtimes': {'wasip2': 'wasmtime 1', 'wasip3': 'wasmtime 1', 'emscripten': 'node 1'}, + 'strip': 'strip', + 'records': records, + } + + +def library(scratch: Path, name: str = 'hash') -> Path: + directory = scratch / name + (directory / 'doc').mkdir(parents=True) + (directory / 'include/webcpp/hash/detail').mkdir(parents=True) + (directory / 'test/measure').mkdir(parents=True) + (directory / 'doc/capabilities.json').write_text(json.dumps(capabilities(), indent=4) + '\n') + return directory + + +def run(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(MEASURE), *args], cwd=ROOT, capture_output=True, + text=True, check=False) + + +def passes(done: subprocess.CompletedProcess[str]) -> None: + if done.returncode != 0: + raise AssertionError(f'exit {done.returncode}\n{done.stdout}{done.stderr}') + + +def fails(done: subprocess.CompletedProcess[str], *texts: str, status: int = 1) -> None: + if done.returncode != status: + raise AssertionError(f'exit {done.returncode}, not {status}\n{done.stdout}{done.stderr}') + for text in texts: + if text not in done.stderr: + raise AssertionError(f'{text!r} is not in the error:\n{done.stderr}') + + +def write_measured(scratch: Path, data: dict[str, Any], name: str = 'measured.json') -> Path: + path = scratch / name + path.write_text(json.dumps(data, indent=2) + '\n') + return path + + +def written(directory: Path, data: dict[str, Any], scratch: Path) -> None: + passes(run('--library', str(directory), '--write', '--measured', + str(write_measured(scratch, data, f'{directory.name}.json')))) + + +def changed(data: dict[str, Any], keep: Callable[[dict], bool], + change: Callable[[dict], None]) -> dict[str, Any]: + data = copy.deepcopy(data) + for record in data['records']: + if keep(record): + change(record) + return data + + +def row(operation: str, hmac: str | None, target: str) -> Callable[[dict], bool]: + return lambda r: (r['operation'], r['hmac'], r['target']) == (operation, hmac, target) + + +def test_write_renders_deterministically(scratch: Path) -> None: + data = measured(capabilities()) + one, two = library(scratch, 'one'), library(scratch, 'two') + written(one, data, scratch) + written(two, data, scratch) + for output in OUTPUTS: + a, b = (one / output).read_bytes(), (two / output).read_bytes() + if a != b: + raise AssertionError(f'{output} differs between two writes of the same data') + ranking = (one / 'include/webcpp/hash/detail/ranking.hpp').read_text() + expected = ('struct ranking {', 'Generated by', + 'backend_list', 'WEBCPP_TARGET_EMSCRIPTEN') + for text in expected: + if text not in ranking: + raise AssertionError(f'{text!r} is not in ranking.hpp:\n{ranking}') + table = json.loads((one / 'doc/measurements.json').read_text()) + keys = {(r['operation'], r['hmac'], r['backend'], r['target']) for r in table['records']} + if ('pbkdf2', 'hmac_sha2_512', 'openssl', 'wasip3') not in keys: + raise AssertionError('measurements.json lacks a record of its measured data') + page = (one / 'doc/measurements.adoc').read_text() + for text in ('WARNING: the machine was shared and loaded', '| hkdf_extract', + 'The default of each key derivation'): + if text not in page: + raise AssertionError(f'{text!r} is not in measurements.adoc') + cells = (one / 'test/measure/cells.jam').read_text() + for text in ('measure-cell hkdf_bearssl_hmac_sha2_256 : hkdf_bearssl.cpp\n', + 'measure-cell pbkdf2_openssl_hmac_sha2_512 : pbkdf2_openssl.cpp\n' + ' : /third_party//openssl : hmac_sha2_512 : native wasip2 wasip3 ;\n', + 'measure-cell sha2_256_hash2 : sha2_256_hash2.cpp\n' + ' : : : native wasip2 wasip3 emscripten ;\n'): + if text not in cells: + raise AssertionError(f'{text!r} is not in cells.jam:\n{cells}') + + +def test_check_passes_on_its_own_write(scratch: Path) -> None: + data = measured(capabilities()) + directory = library(scratch) + written(directory, data, scratch) + passes(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, data)))) + + +def test_check_fails_when_a_size_order_changes(scratch: Path) -> None: + data = measured(capabilities()) + directory = library(scratch) + written(directory, data, scratch) + + def smaller(record: dict) -> None: + if record['backend'] == 'sodium': + record['size_bytes'] = 100 + + again = changed(data, row('hkdf', 'hmac_sha2_256', 'wasip3'), smaller) + fails(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, again))), + 'hkdf over hmac_sha2_256 on wasip3', 'by size', WRITE) + + +def test_throughput_moving_under_ten_percent_keeps_the_order(scratch: Path) -> None: + data = measured(capabilities()) + for record in data['records']: + if record['operation'] == 'pbkdf2' and record['target'] == 'native': + record['throughput'] = throughput(1000.0 if record['backend'] == 'openssl' + else 1200.0) + directory = library(scratch) + written(directory, data, scratch) + table = json.loads((directory / 'doc/measurements.json').read_text()) + order = next(o for o in table['orders'] if (o['operation'], o['hmac'], o['target']) + == ('pbkdf2', 'hmac_sha2_256', 'native')) + if order['by_throughput'] != ['openssl', 'hash2']: + raise AssertionError(f'the first order is {order["by_throughput"]}') + + def faster(median: float) -> Callable[[dict], None]: + def change(record: dict) -> None: + if record['backend'] == 'hash2': + record['throughput'] = throughput(median) + return change + + # hash2 now 5 percent faster than OpenSSL: noise, the order stays. + a_little = changed(data, row('pbkdf2', 'hmac_sha2_256', 'native'), faster(952.0)) + passes(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, a_little)))) + # 9.5 percent below OpenSSL's median: not more than 10 percent, the order stays. + just_under = changed(data, row('pbkdf2', 'hmac_sha2_256', 'native'), faster(905.0)) + passes(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, just_under)))) + # 10.5 percent below: the order changes. + just_past = changed(data, row('pbkdf2', 'hmac_sha2_256', 'native'), faster(895.0)) + fails(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, just_past))), + 'pbkdf2 over hmac_sha2_256 on native', 'by throughput', WRITE) + # 25 percent faster, the spreads apart: the order changes. + much = changed(data, row('pbkdf2', 'hmac_sha2_256', 'native'), faster(750.0)) + fails(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, much))), + 'pbkdf2 over hmac_sha2_256 on native', 'by throughput', WRITE) + + +def test_the_spread_plays_no_part_in_an_order(scratch: Path) -> None: + # Spec 4.2's rule alone. A first measurement orders by the medians, however + # close (OpenSSL 5 percent faster leads); a committed order changes when a median is more + # than 10 percent below the one ahead of it, however wide the runs' spread. + data = measured(capabilities()) + for record in data['records']: + if record['operation'] == 'pbkdf2' and record['target'] == 'native': + record['throughput'] = throughput(1000.0 if record['backend'] == 'openssl' + else 1050.0) + directory = library(scratch) + written(directory, data, scratch) + table = json.loads((directory / 'doc/measurements.json').read_text()) + order = next(o for o in table['orders'] if (o['operation'], o['hmac'], o['target']) + == ('pbkdf2', 'hmac_sha2_256', 'native')) + if order['by_throughput'] != ['openssl', 'hash2']: + raise AssertionError(f'the medians do not order a first measurement: {order}') + + def noisy(record: dict) -> None: + if record['backend'] == 'hash2': + record['throughput'] = throughput(800.0, spread=0.5) + + again = changed(data, row('pbkdf2', 'hmac_sha2_256', 'native'), noisy) + fails(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, again))), + 'pbkdf2 over hmac_sha2_256 on native', 'by throughput', WRITE) + + +def test_each_operation_has_its_own_ranking(scratch: Path) -> None: + # hkdf_extract's default reads its own row (spec 4.1's smallest per operation): libsodium's + # extract program is the smaller on emscripten while whole HKDF's order puts hash2 first. + data = measured(capabilities()) + + def sodium_smaller(record: dict) -> None: + if record['backend'] == 'sodium': + record['size_bytes'] = 100 + + data = changed(data, lambda r: (r['operation'], r['target']) == ('hkdf_extract', + 'emscripten'), + sodium_smaller) + directory = library(scratch) + written(directory, data, scratch) + ranking = ' '.join((directory / 'include/webcpp/hash/detail/ranking.hpp').read_text() + .split()) + emscripten = ranking.split('#elif defined(WEBCPP_TARGET_EMSCRIPTEN)')[1].split('#else')[0] + for text in ('struct ranking { /** The smallest program first. */ ' + 'using by_size = backend_list {', + 'struct ranking { /** The smallest program first. */ ' + 'using by_size = backend_list None: + # The native orders hold for the toolchain that measured them. Measured with + # another, a native order that differs is said in one line and not compared; a WebAssembly + # order still is. + data = measured(capabilities()) + data['native_toolchain'] = {'compiler': 'A 1', 'os': 'Darwin', 'processor': 'arm64', + 'strip': '/usr/bin/strip'} + directory = library(scratch) + written(directory, data, scratch) + + def smaller(record: dict) -> None: + if record['backend'] == 'openssl': + record['size_bytes'] = 1 + + other = changed(data, row('hkdf', 'hmac_sha2_256', 'native'), smaller) + other['native_toolchain'] = {'compiler': 'B 2', 'os': 'Linux', 'processor': 'x86_64', + 'strip': '/usr/bin/strip'} + done = run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, other))) + passes(done) + if 'measured with A 1 on Darwin arm64' not in done.stdout or 'B 2 on Linux' not in done.stdout: + raise AssertionError(f'no line says the native orders are not compared:\n{done.stdout}') + fails(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, changed(other, row('hkdf', 'hmac_sha2_256', 'wasip2'), + smaller)))), + 'hkdf over hmac_sha2_256 on wasip2', 'by size', WRITE) + same = copy.deepcopy(other) + same['native_toolchain'] = data['native_toolchain'] + fails(run('--library', str(directory), '--check', '--measured', + str(write_measured(scratch, same))), + 'hkdf over hmac_sha2_256 on native', 'by size', WRITE) + + +def test_a_hand_edit_fails(scratch: Path) -> None: + data = measured(capabilities()) + directory = library(scratch) + written(directory, data, scratch) + measured_file = str(write_measured(scratch, data)) + for output in OUTPUTS[1:]: + path = directory / output + original = path.read_text() + path.write_text(original.replace('hash2', 'hash3', 1)) + fails(run('--library', str(directory), '--check', '--measured', measured_file), + output, WRITE) + path.write_text(original) + path = directory / 'doc/measurements.json' + original = path.read_text() + path.write_text(original.replace('"size_bytes": 20000', '"size_bytes": 20001', 1)) + fails(run('--library', str(directory), '--check', '--measured', measured_file), + 'doc/measurements.json', 'edited by hand', WRITE) + path.write_text(original) + passes(run('--library', str(directory), '--check', '--measured', measured_file)) + + +def test_a_missing_program_fails(scratch: Path) -> None: + data = measured(capabilities()) + directory = library(scratch) + written(directory, data, scratch) + lists = scratch / 'lists' + lists.mkdir() + programs = [] + for target in TARGETS: + for optimization in ('space', 'speed'): + names = [f'{optimization}-{r["operation"]}_{r["backend"]}' + + (f'_{r["hmac"]}' if r['hmac'] else '') + for r in data['records'] if r['target'] == target] + if (target, optimization) == ('wasip2', 'space'): + names = [n for n in names if 'hkdf_sodium_hmac_sha2_512' not in n] + suffix = '.wasm' if target in ('wasip2', 'wasip3') else ( + '.js' if target == 'emscripten' else '') + path = lists / f'measure-programs-{target}-{optimization}.txt' + path.write_text(''.join(f'{lists}/{name}{suffix}\n' for name in names)) + programs.append(str(path)) + fails(run('--library', str(directory), '--check', '--programs', *programs), + 'space-hkdf_sodium_hmac_sha2_512 on wasip2', 'built nothing') + # A target whose list is missing altogether. + fails(run('--library', str(directory), '--check', '--programs', *programs[2:]), + 'native', 'built nothing') + + +def test_every_order_names_every_backend(scratch: Path) -> None: + data = measured(capabilities()) + for record in data['records']: + if record['operation'] == 'hkdf' and record['backend'] == 'bearssl': + record['size_bytes'] = 1 + record['throughput'] = throughput(1.0) + directory = library(scratch) + written(directory, data, scratch) + ranking = (directory / 'include/webcpp/hash/detail/ranking.hpp').read_text() + orders = [line for line in ranking.splitlines() if 'backend_list<' in line + or line.strip().startswith('backends::')] + joined = ' '.join(ranking.split()) + if 'using portable_order = backend_list;' not in joined: + raise AssertionError(f'the portable order is not hash2, sodium, bearssl:\n{ranking}') + lists = [part.split('>;')[0] for part in joined.split('= backend_list<')[1:]] + if not orders or not lists: + raise AssertionError('ranking.hpp holds no order') + for order in lists: + named = {b.strip() for b in order.split(',')} + if order.startswith('backends::hash2, backends::sodium, backends::bearssl') and \ + len(named) == 3: + continue # portable_order + wanted = {'backends::hash2', 'backends::sodium', 'backends::bearssl', + 'backends::openssl'} + if named != wanted: + raise AssertionError(f'an order names {sorted(named)}, not every backend') + if 'backend_list None: + directory = library(scratch) + passes(run('--library', str(directory), '--capabilities')) + page = (directory / 'doc/backends.adoc').read_text() + for text in ('| hkdf_extract', '| argon2id', 'not stated', 'emscripten', 'openssl', + 'Generated by'): + if text not in page: + raise AssertionError(f'{text!r} is not in backends.adoc:\n{page}') + first = page + passes(run('--library', str(directory), '--capabilities')) + if (directory / 'doc/backends.adoc').read_text() != first: + raise AssertionError('--capabilities renders differently twice') + + +def test_the_real_library_s_generated_files_are_its_data_s(_: Path) -> None: + # Review Focus 9 without the lane: every generated file of libs/hash is what its committed + # data and capability table render, and the data's digest holds (no b2, no program). + passes(run('--library', str(LIBRARY), '--check', '--measured', + str(LIBRARY / 'doc/measurements.json'))) + + +def test_overrides_regenerate_the_committed_file(scratch: Path) -> None: + directory = scratch / 'hash' + (directory / 'include/webcpp/hash/detail').mkdir(parents=True) + (directory / 'doc').mkdir() + shutil.copy(LIBRARY / 'doc/capabilities.json', directory / 'doc/capabilities.json') + passes(run('--library', str(directory), '--overrides')) + ours = (directory / 'include/webcpp/hash/detail/overrides.hpp').read_text() + committed = (LIBRARY / 'include/webcpp/hash/detail/overrides.hpp').read_text() + if ours != committed: + raise AssertionError('--overrides does not give the committed detail/overrides.hpp') + + +def test_usage_errors_exit_2(scratch: Path) -> None: + directory = library(scratch) + fails(run('--library', str(directory)), 'one of', status=2) + fails(run('--library', str(directory), '--check', '--measured', 'a', '--programs', 'b'), + '--measured and --programs', status=2) + fails(run('--library', str(scratch / 'nowhere'), '--capabilities'), + 'capabilities.json', status=2) + + +def test_no_tracked_file_cites_a_controller_ruling(_: Path) -> None: + # The plan's rulings are not in the repository, so a reader cannot open one: a comment, a + # page or a generated file says the reason or the spec section instead. The check reads the + # tracked files of the library (its own repository) and of tools/hash. + cite = re.compile(r'\b[Rr]ulings?\s+R?[0-9]|\(R[0-9]+\)') + found = [] + for base in (LIBRARY, ROOT / 'tools/hash'): + listed = subprocess.run(['git', '-C', str(base), 'ls-files', '-z', '--', '.'], + capture_output=True, text=True, check=True).stdout + for name in filter(None, listed.split('\0')): + path = base / name + if not path.is_file() or 'third_party' in path.relative_to(base).parts: + continue + try: + text = path.read_text(encoding='utf-8') + except UnicodeDecodeError: + continue + for number, line in enumerate(text.splitlines(), 1): + if cite.search(line): + found.append(f'{path.relative_to(ROOT)}:{number}') + assert not found, 'a controller ruling is cited in ' + ', '.join(found) + + +CASES = [ + test_write_renders_deterministically, + test_check_passes_on_its_own_write, + test_check_fails_when_a_size_order_changes, + test_throughput_moving_under_ten_percent_keeps_the_order, + test_the_spread_plays_no_part_in_an_order, + test_each_operation_has_its_own_ranking, + test_another_native_toolchain_compares_no_native_order, + test_a_hand_edit_fails, + test_a_missing_program_fails, + test_every_order_names_every_backend, + test_capabilities_renders_the_table, + test_the_real_library_s_generated_files_are_its_data_s, + test_overrides_regenerate_the_committed_file, + test_usage_errors_exit_2, + test_no_tracked_file_cites_a_controller_ruling, +] + + +def main(argv: list[str]) -> int: + unknown = set(argv) - {case.__name__ for case in CASES} + if unknown: + print(f'hash_measure_test: no case named {", ".join(sorted(unknown))}', file=sys.stderr) + return 2 + for case in CASES: + if argv and case.__name__ not in argv: + continue + with tempfile.TemporaryDirectory(prefix='webcpp hash measure ') as scratch: + case(Path(scratch)) + print(f'{case.__name__}: ok') + print('hash_measure_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/test/openssl_one_copy_test.py b/tools/test/openssl_one_copy_test.py index 3b96200d..ceed6234 100644 --- a/tools/test/openssl_one_copy_test.py +++ b/tools/test/openssl_one_copy_test.py @@ -4,12 +4,14 @@ # 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) -"""Checks that asio's and crypto's OpenSSL aliases in one program link libssl.a and libcrypto.a -once each, from one directory (CODING-GUIDELINES.md chapter 5 rule 10). +"""Checks that the OpenSSL aliases of several libraries in one program link libssl.a and +libcrypto.a once each, from one directory (CODING-GUIDELINES.md chapter 5 rule 10): asio's and +crypto's in libs/crypto/test//openssl_one_copy, and, when libs/hash is checked out, hash's and +crypto's in libs/hash/test//openssl_one_copy. -It reads the link line b2 prints (-d+2 with -n, so nothing is rebuilt) for -libs/crypto/test//openssl_one_copy and its _no_exceptions twin, and fails on any archive count -other than one per program, or on archives from two directories. +It reads the link line b2 prints (-d+2 with -n, so nothing is rebuilt) for each program and its +_no_exceptions twin, and fails on any archive count other than one per program, or on archives +from two directories. """ import os import re @@ -19,7 +21,8 @@ ROOT = Path(__file__).resolve().parents[2] ARCHIVE = re.compile(r'[^\s"]*/lib(ssl|crypto)\.a') -LINK = re.compile(r'-o "?[^\s"]*/openssl_one_copy(_no_exceptions)?"?(\s|$)') +# A program's name, with .wasm on WASI. +LINK = re.compile(r'-o "?[^\s"]*/openssl_one_copy(_no_exceptions)?(\.wasm)?"?(\s|$)') def check_link_line(line: str) -> list[str]: @@ -44,16 +47,24 @@ def self_test() -> None: split = '-o "x/openssl_one_copy" /a/config-1/libssl.a /b/config-2/libcrypto.a' assert 'different directories' in ' '.join(check_link_line(split)) assert check_link_line('-o "x/openssl_one_copy"') != [] + assert LINK.search('-o "x/openssl_one_copy.wasm" y') and LINK.search('-o x/openssl_one_copy z') + assert not LINK.search('-o "x/openssl_one_copy_test.o"') + + +def programs() -> list[str]: + """The b2 targets checked: crypto's pair always, hash's when its library is checked out.""" + libraries = ['crypto'] + (['hash'] if (ROOT / 'libs/hash/build.jam').is_file() else []) + return [f'libs/{library}/test//openssl_one_copy{suffix}' + for library in libraries for suffix in ('', '_no_exceptions')] def main() -> int: self_test() + targets = programs() unset = ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH') env = {k: v for k, v in os.environ.items() if k not in unset} command = ['b2', f'--user-config={ROOT}/.local/user-config.jam', '-a', '-n', '-d+2', '-j3', - '--build-dir=' + str(ROOT / 'bin/lane-onecopy'), *sys.argv[1:], - 'libs/crypto/test//openssl_one_copy', - 'libs/crypto/test//openssl_one_copy_no_exceptions'] + '--build-dir=' + str(ROOT / 'bin/lane-onecopy'), *sys.argv[1:], *targets] result = subprocess.run(command, cwd=ROOT, env=env, capture_output=True, text=True, check=False) if result.returncode != 0: print(result.stdout + result.stderr, file=sys.stderr) @@ -65,8 +76,8 @@ def main() -> int: text = result.stdout commands = [chunk for chunk in re.split(r'\n\s*\n', text) if LINK.search(chunk) and ARCHIVE.search(chunk)] - if len(commands) != 2: - print(f'openssl_one_copy: expected 2 link commands, found {len(commands)} ' + if len(commands) != len(targets): + print(f'openssl_one_copy: expected {len(targets)} link commands, found {len(commands)} ' f'({len(lines)} lines)', file=sys.stderr) return 1 faults = [fault for chunk in commands for fault in check_link_line(chunk)] diff --git a/tools/test/third_party_test.py b/tools/test/third_party_test.py index 893513ca..8c851ea5 100755 --- a/tools/test/third_party_test.py +++ b/tools/test/third_party_test.py @@ -16,11 +16,18 @@ stops the build that needs it, naming the command; and that loading third_party/Jamfile prints nothing b2 warns of. libsecp256k1, pinned, is built file by file with every module and webcpp::crypto's canary, with the large tables natively and the small ones on request and on -emscripten. Run with the names of some cases to run only those.""" +emscripten. XKCP, pinned, is built from its one file of Keccak-p[1600] with webcpp::hash's adapter +and canary, and an XKCP or a libs/hash that is not checked out stops it, naming the command. +libsodium, pinned, is built file by file with the defines its own configure finds on each target and +webcpp::hash's canary, its version.h copied into the build directory and its checkout left as it +was. BLAKE3's C implementation, pinned, is built file by file with webcpp::hash's canary: natively +with the intrinsics files of the machine's instruction sets, each with its own flag, and on +WebAssembly with the portable code alone. Run with the names of some cases to run only those.""" from __future__ import annotations import os +import platform import re import shutil import subprocess @@ -44,6 +51,23 @@ # The commit ctaes's submodule, Bitcoin Core v31.1, is pinned at. BITCOIN_COMMIT = '9be056a8a72b624dae9623b2f7bded92c2a21c91' +BLAKE3 = 'third_party/libs/blake3' + +# BLAKE3 1.8.7, the commit it is pinned at. +BLAKE3_COMMIT = 'f3149ec5bb5449af877ba20377a11008ff499fa2' + +# The C files /third_party//blake3 compiles on every target: BLAKE3's three and webcpp::hash's +# canary. +BLAKE3_FILES = ['blake3.c', 'blake3_dispatch.c', 'blake3_portable.c', 'canary_blake3.c'] + +# The intrinsics files of x86-64, each with the flags of its instruction set. +BLAKE3_X86 = {'blake3_sse2.c': ['-msse2'], 'blake3_sse41.c': ['-msse4.1'], + 'blake3_avx2.c': ['-mavx2'], 'blake3_avx512.c': ['-mavx512f', '-mavx512vl']} + +# What leaves BLAKE3's portable code alone, on WebAssembly. +BLAKE3_PORTABLE = ['-DBLAKE3_NO_SSE2', '-DBLAKE3_NO_SSE41', '-DBLAKE3_NO_AVX2', + '-DBLAKE3_NO_AVX512'] + PASSED = re.compile(r'^\*\*passed\*\* (.*)$', re.MULTILINE) SUITE = 'third_party/libs/JSON-Schema-Test-Suite' @@ -77,9 +101,76 @@ ('ECDH', 'RECOVERY', 'EXTRAKEYS', 'SCHNORRSIG', 'MUSIG', 'ELLSWIFT', 'SILENTPAYMENTS')] +XKCP = 'third_party/libs/xkcp' + +# The commit XKCP is pinned at, of 2026-11-10 (XKCP has no release tags). +XKCP_COMMIT = 'd20c8fcaecc543f816a0721d0dfc13b4cf27c14d' + +# The C files /third_party//xkcp compiles: XKCP's Keccak-p[1600] in the plain-64bits +# implementation, and webcpp::hash's adapter and canary. +XKCP_FILES = ['KeccakP-1600-opt64.c', 'xkcp_adapter.c', 'canary_xkcp.c'] + +# The adapter's four functions (spec section 2.6). +XKCP_ADAPTER = ['webcpp_hash_xkcp_initialize', 'webcpp_hash_xkcp_add_bytes', + 'webcpp_hash_xkcp_permute', 'webcpp_hash_xkcp_extract_bytes'] + # The small tables: window 2 and comb 2x5. SECP256K1_SMALL = ['-DECMULT_WINDOW_SIZE=2', '-DCOMB_BLOCKS=2', '-DCOMB_TEETH=5'] +SODIUM = 'third_party/libs/libsodium' + +# libsodium 1.0.22, the commit it is pinned at. +SODIUM_COMMIT = '77e1ce5d6dee871c49ef211222ba18ef0c486bda' + +# The canary /third_party//sodium defines when its defines are the ones third_party/Jamfile derives +# from libsodium's configure. +SODIUM_CANARY = ('webcpp_hash_sodium_77e1ce5_configured__add_third_party_sodium_to_your_link') + +# The defines of every target: webcpp's three, then those libsodium's configure finds on every +# target and its C files read. +SODIUM_COMMON = {'CONFIGURED=1', 'SODIUM_STATIC=1', 'NATIVE_LITTLE_ENDIAN=1', 'HAVE_ALLOCA=1', + 'HAVE_ALLOCA_H=1', 'HAVE_ATOMIC_OPS=1', 'HAVE_C11_MEMORY_FENCES=1', + 'HAVE_C_VARARRAYS=1', 'HAVE_GCC_MEMORY_FENCES=1', 'HAVE_INLINE_ASM=1', + 'HAVE_NANOSLEEP=1', 'HAVE_POSIX_MEMALIGN=1', 'HAVE_SYS_PARAM_H=1', + 'HAVE_SYS_RANDOM_H=1'} + +# What configure finds natively, on macOS and Linux alike. +SODIUM_POSIX = {'HAVE_GETENTROPY=1', 'HAVE_GETPID=1', 'HAVE_MADVISE=1', 'HAVE_MLOCK=1', + 'HAVE_MMAP=1', 'HAVE_MPROTECT=1', 'HAVE_PTHREAD=1', 'HAVE_RAISE=1', + 'HAVE_SYSCONF=1', 'HAVE_SYS_MMAN_H=1', 'HAVE_TI_MODE=1', 'HAVE_WEAK_SYMBOLS=1', + 'TLS=_Thread_local'} + +# The intrinsics' headers and RDRAND, which configure finds on x86-64 alone; ARM's crypto +# extensions, on arm64 alone. +SODIUM_X86_64 = {'HAVE_MMINTRIN_H=1', 'HAVE_EMMINTRIN_H=1', 'HAVE_PMMINTRIN_H=1', + 'HAVE_TMMINTRIN_H=1', 'HAVE_SMMINTRIN_H=1', 'HAVE_AVXINTRIN_H=1', + 'HAVE_AVX2INTRIN_H=1', 'HAVE_AVX512FINTRIN_H=1', 'HAVE_WMMINTRIN_H=1', + 'HAVE_RDRAND=1'} +SODIUM_ARM64 = {'HAVE_ARMCRYPTO=1'} + +SODIUM_DEFINES = { + 'wasi': SODIUM_COMMON | {'HAVE_GETENTROPY=1', 'HAVE_THREADS_H=1'}, + 'emscripten': SODIUM_COMMON | {'HAVE_EXPLICIT_BZERO=1', 'HAVE_GETPID=1', + 'HAVE_SYS_MMAN_H=1', 'HAVE_THREADS_H=1'}, + 'darwin': SODIUM_COMMON | SODIUM_POSIX | {'HAVE_MEMSET_S=1'}, + 'linux': SODIUM_COMMON | SODIUM_POSIX | {'HAVE_EXPLICIT_BZERO=1', 'HAVE_GETAUXVAL=1', + 'HAVE_GETRANDOM=1', 'HAVE_SYS_AUXV_H=1', + 'HAVE_THREADS_H=1'}, +} + + +def sodium_native_defines() -> set[str]: + """The defines libsodium's configure finds on this machine.""" + found = SODIUM_DEFINES[sys.platform if sys.platform == 'darwin' else 'linux'] + machine = platform.machine().lower() + return found | (SODIUM_ARM64 if machine in ('arm64', 'aarch64') else SODIUM_X86_64) + + +def defines_of(line: str) -> set[str]: + """The -D options of a compile line, without -D, unquoted.""" + return {word[2:].strip('"\'') for word in line.split() if word.startswith('-D')} + + # The compile line of a C file, as b2 prints it at -d+2. C_COMPILE = re.compile(r'^\s*"?\S*(?:clang|gcc|emcc|em\+\+)\S*"? -x c .*$', re.MULTILINE) @@ -211,14 +302,14 @@ def test_bearssl_is_pinned(_: Path) -> None: assert listed.stdout.split()[:2] == ['160000', BEARSSL_COMMIT], listed.stdout -def test_bearssl_is_built_file_by_file(root: Path) -> None: - harness.copy_integration_libraries(root, 'config', 'crypto') +def bearssl_compiles(root: Path, expected: int) -> str: + """Builds /third_party//bearssl in the scratch superproject, checks that each of its + `expected` compiles has BearSSL's flags, and returns the symbols of its archive.""" result = harness.run_b2(root, '-a', '-d+2', 'third_party//bearssl') harness.expect(result, True) compiles = [line for line in result.stdout.splitlines() if re.search(r'(clang|gcc)\S* .*-x c ', line) and ' -c ' in line] - # The 294 files of BearSSL's src/ and webcpp::crypto's canary. - assert len(compiles) == 295, (len(compiles), result.stdout[-4000:]) + assert len(compiles) == expected, (len(compiles), result.stdout[-4000:]) required = ['-ffunction-sections', '-fdata-sections', '-DBR_RDRAND=0', '-DBR_USE_URANDOM=0', '-DBR_USE_GETENTROPY=1', '-D_DEFAULT_SOURCE'] if sys.platform == 'darwin': @@ -230,10 +321,29 @@ def test_bearssl_is_built_file_by_file(root: Path) -> None: archive = sorted((root / 'bin').rglob('libbearssl.a')) assert len(archive) == 1, archive symbols = subprocess.run(['nm', str(archive[0])], capture_output=True, text=True, check=True) + return symbols.stdout + + +def bearssl_canary(library: str) -> str: prefix = '_' if sys.platform == 'darwin' else '' - canary = (f'{prefix}webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl' - '_to_your_link') - assert canary in symbols.stdout.split(), symbols.stdout[-2000:] + return (f'{prefix}webcpp_{library}_bearssl_7bea48e_getentropy__add_third_party_bearssl' + '_to_your_link') + + +def test_bearssl_is_built_file_by_file(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'crypto', 'hash') + # The 294 files of BearSSL's src/, webcpp::crypto's canary and webcpp::hash's. + symbols = bearssl_compiles(root, 296) + for library in ('crypto', 'hash'): + assert bearssl_canary(library) in symbols.split(), symbols[-2000:] + + +def test_bearssl_without_hash_has_cryptos_canary_alone(root: Path) -> None: + # A checkout without libs/hash builds crypto's BearSSL as before: 294 files and one canary. + harness.copy_integration_libraries(root, 'config', 'crypto') + symbols = bearssl_compiles(root, 295) + assert bearssl_canary('crypto') in symbols.split(), symbols[-2000:] + assert 'webcpp_hash_' not in symbols, symbols[-2000:] def test_third_party_jamfile_loads_without_noise(root: Path) -> None: @@ -363,6 +473,326 @@ def test_secp256k1_not_checked_out_is_refused(root: Path) -> None: 'git submodule update --init third_party/libs/secp256k1') +def test_xkcp_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', XKCP], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', XKCP_COMMIT], listed.stdout + + +def test_xkcp_is_built_file_by_file(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'hash') + result = harness.run_b2(root, '-a', '-d+2', 'third_party//xkcp') + harness.expect(result, True) + lines = C_COMPILE.findall(result.stdout) + compiled = sorted(Path(line.rsplit(' ', 1)[-1].strip('"')).name for line in lines) + # XKCP's one file and webcpp::hash's two: nothing else of XKCP's tree. + assert compiled == sorted(XKCP_FILES), (compiled, result.stdout[-4000:]) + for line in lines: + for flag in ('-ffunction-sections', '-fdata-sections'): + assert flag in line.split(), (flag, line) + assert '-std=' not in line, line + archive = sorted((root / 'bin').rglob('libxkcp.a')) + assert len(archive) == 1, archive + symbols = subprocess.run(['nm', '-g', str(archive[0])], capture_output=True, text=True, + check=True).stdout.split() + prefix = '_' if sys.platform == 'darwin' else '' + canary = 'webcpp_hash_xkcp_d20c8fc_generic64__add_third_party_xkcp_to_your_link' + for name in [canary, *XKCP_ADAPTER]: + assert f'{prefix}{name}' in symbols, (name, symbols[-200:]) + + +def test_xkcp_not_checked_out_is_refused(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'hash') + harness.third_party_of_its_own(root, 'xkcp', checked_out=False) + result = harness.run_b2(root, 'third_party//xkcp') + harness.expect(result, False, 'third_party/libs/xkcp is not checked out', + 'git submodule update --init third_party/libs/xkcp') + # A build that needs no XKCP never looks for it. + harness.expect(harness.run_b2(root, 'libs/demo/test//pass'), True) + + +def test_hash_not_checked_out_is_refused(root: Path) -> None: + # No libs/hash in the scratch superproject: XKCP's adapter and canary are missing. + result = harness.run_b2(root, 'third_party//xkcp') + harness.expect(result, False, 'libs/hash is not checked out', + 'git submodule update --init libs/hash') + + +def compiled_sodium(result: subprocess.CompletedProcess) -> list[str]: + """The C compile lines of /third_party//sodium that b2 printed at -d+2.""" + return [line for line in C_COMPILE.findall(result.stdout) + if '/libsodium/' in line or 'canary_sodium.c' in line] + + +def expect_sodium_defines(lines: list[str], expected: set[str] | None) -> None: + """Asserts that every line compiles in the library's own dialect, without assembly, with the + expected defines (this machine's natively, when expected is None) and no other of + libsodium's.""" + for line in lines: + assert '-std=' not in line, line + # NDEBUG is the variant's, BOOST_ALL_NO_LIB the Jamroot's, for every program. + defines = {define for define in defines_of(line) + if define.split('=')[0] not in ('NDEBUG', 'BOOST_ALL_NO_LIB')} + wanted = expected if expected is not None else sodium_native_defines() + assert defines == wanted, (sorted(defines ^ wanted), line) + assert 'HAVE_AMD64_ASM' not in line and 'HAVE_AVX_ASM' not in line, line + + +def test_sodium_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', SODIUM], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', SODIUM_COMMIT], listed.stdout + + +def test_sodium_is_built_file_by_file(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'hash') + result = harness.run_b2(root, '-a', '-d+2', 'third_party//sodium') + harness.expect(result, True) + lines = compiled_sodium(result) + # The 141 C files of libsodium's src/libsodium and webcpp::hash's canary. + assert len(lines) == 142, (len(lines), result.stdout[-4000:]) + for line in lines: + for flag in ('-ffunction-sections', '-fdata-sections'): + assert flag in line, (flag, line) + expect_sodium_defines(lines, None) + copies = sorted((root / 'bin').rglob('version.h')) + upstream = (harness.ROOT / SODIUM / 'builds/msvc/version.h').read_bytes() + assert copies and all(copy.read_bytes() == upstream for copy in copies), copies + assert any(copy.parent.name == 'sodium' for copy in copies), copies + status = subprocess.run(['git', '-C', str(harness.ROOT / SODIUM), 'status', '--porcelain'], + capture_output=True, text=True, check=True) + assert status.stdout == '', status.stdout + archive = sorted((root / 'bin').rglob('libsodium.a')) + assert len(archive) == 1, archive + symbols = subprocess.run(['nm', str(archive[0])], capture_output=True, text=True, check=True) + prefix = '_' if sys.platform == 'darwin' else '' + assert f'{prefix}{SODIUM_CANARY}' in symbols.stdout.split(), symbols.stdout[-2000:] + + +def test_sodium_defines_on_each_webassembly_target(root: Path) -> None: + # -n prints each command without running it: the defines, not the build, are the case's. + harness.link_emsdk(root) + harness.copy_integration_libraries(root, 'config', 'hash') + for request, defines in ((WASIP2, SODIUM_DEFINES['wasi']), (WASIP3, SODIUM_DEFINES['wasi']), + (EMSCRIPTEN, SODIUM_DEFINES['emscripten'])): + result = harness.run_b2(root, '-a', '-n', '-d+2', *request, 'third_party//sodium') + harness.expect(result, True) + lines = compiled_sodium(result) + assert len(lines) == 142, (request, len(lines), result.stdout[-4000:]) + expect_sodium_defines(lines, defines) + + +def test_sodium_test_config_reaches_the_private_headers(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'hash') + harness.add_library(root, 'sodium_private', 'import webcpp ;\n' + '\n' + 'webcpp.run private : private.c\n' + ' : /third_party//sodium-test-config\n' + ' /third_party//sodium ;\n', + {'private.c': '#include \n' + '#include "private/common.h"\n' + '#include "argon2.h"\n' + '#include "version.h"\n' + '\n' + 'int main(void) {\n' + ' return sodium_init() < 0 ||\n' + ' sodium_library_version_major() !=\n' + ' SODIUM_LIBRARY_VERSION_MAJOR;\n' + '}\n'}) + result = harness.run_b2(root, '-a', '-d+2', 'libs/sodium_private/test') + harness.expect(result, True, '**passed**') + # The program compiles with the library's defines, the test-only ones too. + line = [line for line in C_COMPILE.findall(result.stdout) if 'private.c' in line] + assert len(line) == 1, result.stdout[-4000:] + assert {'CONFIGURED=1', 'SODIUM_STATIC=1', 'HAVE_CLOCK_GETTIME=1'} <= defines_of(line[0]), line + + +def test_sodium_msvc_inline_reaches_c_alone(root: Path) -> None: + # MSVC's build of libsodium defines inline as __inline for its C files; a C++ translation unit + # of a program that uses sodium-test-config never gets it, since the standard library's headers + # refuse a macro named after a keyword. A dry run with a stand-in MSVC prints the commands. + harness.copy_integration_libraries(root, 'config', 'hash') + harness.add_library(root, 'sodium_msvc', 'import webcpp ;\n' + '\n' + 'webcpp.run both : both.cpp private.c\n' + ' : /third_party//sodium-test-config\n' + ' /third_party//sodium ;\n', + {'both.cpp': 'int main() { return 0; }\n', + 'private.c': 'int sodium_private(void) { return 0; }\n'}) + config = harness.user_config(root).read_text() + harness.configure(root, config + f'\nusing msvc : 14.3 : "{sys.executable}"' + ' : off ;\n') + jamroot = root / 'Jamroot' + original = jamroot.read_text() + # A foreign-toolset dry run cannot run cmd.exe for the configuration checks. + jamroot.write_text(original.replace('@boost-check', 'off')) + try: + result = harness.run_b2(root, '-a', '-n', '-d+2', 'toolset=msvc-14.3', + 'target-os=windows', 'architecture=x86', 'address-model=64', + 'libs/sodium_msvc/test') + finally: + jamroot.write_text(original) + harness.configure(root, config) + harness.expect(result, True) + lines = result.stdout.splitlines() + c_files = [line for line in lines if ' -TC ' in line and ('/libsodium/' in line + or 'private.c' in line)] + cpp_files = [line for line in lines if ' -TP ' in line and 'both.cpp' in line] + # The 141 files of libsodium, the canary and the program's own C file. + assert len(c_files) == 143, (len(c_files), result.stdout[-4000:]) + assert len(cpp_files) == 1, result.stdout[-4000:] + for line in c_files: + assert '/Dinline=__inline' in line, line + assert 'inline=' not in cpp_files[0], cpp_files[0] + + +def test_sodium_unknown_architecture_is_refused(root: Path) -> None: + # No configure run covers a 32-bit build, and a model is never guessed for an architecture + # given alone: each stops, naming what it is for. + harness.copy_integration_libraries(root, 'config', 'hash') + for request, named in ((('address-model=32',), 'on unknown-32'), + (('architecture=arm',), 'on arm-unknown')): + result = harness.run_b2(root, '-n', *request, 'third_party//sodium') + harness.expect(result, False, "libsodium's configuration is derived for", named) + + +def test_sodium_not_checked_out_is_refused(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'hash') + harness.third_party_of_its_own(root, 'libsodium', checked_out=False) + result = harness.run_b2(root, 'third_party//sodium') + harness.expect(result, False, 'third_party/libs/libsodium is not checked out', + 'git submodule update --init third_party/libs/libsodium') + # A build that needs no libsodium never looks for it. + harness.expect(harness.run_b2(root, 'libs/demo/test//pass'), True) + + +def test_hash_not_checked_out_is_refused_by_sodium(root: Path) -> None: + # No libs/hash in the scratch superproject: the canary is missing. + result = harness.run_b2(root, 'third_party//sodium') + harness.expect(result, False, 'libs/hash is not checked out', + 'git submodule update --init libs/hash') + + +def build_blake3(root: Path, *request: str) -> tuple[dict[str, str], Path]: + """Builds /third_party//blake3 with every action shown, from libs/hash's real canary, and + returns its C compile lines by file name and its archive.""" + harness.copy_integration_libraries(root, 'config', 'hash') + result = harness.run_b2(root, '-a', '-d+2', *request, 'third_party//blake3') + harness.expect(result, True) + lines = C_COMPILE.findall(result.stdout) + compiled = {Path(line.rsplit(' ', 1)[-1].strip('"')).name: line for line in lines} + assert len(compiled) == len(lines), lines + archives = sorted((root / 'bin').rglob('libblake3.a')) + assert len(archives) == 1, archives + return compiled, archives[0] + + +def blake3_canary(configuration: str) -> str: + """The symbol of BLAKE3's canary for configuration.""" + return (f'webcpp_hash_blake3_f3149ec_{configuration}' + '__add_third_party_blake3_to_your_link') + + +def expect_blake3_portable(compiled: dict[str, str], archive: Path) -> None: + """Asserts that the three portable files and the canary alone were compiled, each with the + four BLAKE3_NO_* and no flag of an instruction set, and that the archive holds the canary of + the portable configuration.""" + assert sorted(compiled) == sorted(BLAKE3_FILES), sorted(compiled) + for line in compiled.values(): + for define in BLAKE3_PORTABLE: + assert define in line.split(), (define, line) + assert '-DBLAKE3_USE_NEON=1' not in line.split(), line + assert not re.search(r' -m(sse|avx)', line), line + assert '-std=' not in line, line + assert blake3_canary('portable').encode() in archive.read_bytes() + + +def test_blake3_is_pinned(_: Path) -> None: + listed = subprocess.run(['git', '-C', str(harness.ROOT), 'ls-files', '-s', BLAKE3], + capture_output=True, text=True, check=True) + assert listed.stdout.split()[:2] == ['160000', BLAKE3_COMMIT], listed.stdout + + +def test_blake3_natively_has_the_machines_simd_files(root: Path) -> None: + compiled, archive = build_blake3(root) + machine = platform.machine().lower() + if machine in ('arm64', 'aarch64'): + expected = BLAKE3_FILES + ['blake3_neon.c'] + configuration = 'neon' + else: + assert machine in ('x86_64', 'amd64'), machine + expected = BLAKE3_FILES + list(BLAKE3_X86) + configuration = 'x86' + assert sorted(compiled) == sorted(expected), sorted(compiled) + for name, line in compiled.items(): + words = line.split() + for flag in ('-ffunction-sections', '-fdata-sections'): + assert flag in words, (flag, line) + assert '-std=' not in line, line + for define in BLAKE3_PORTABLE: + assert define not in words, (define, line) + assert ('-DBLAKE3_USE_NEON=1' in words) == (configuration == 'neon'), line + # Each intrinsics file has its own flags, and no other file has any. + own = BLAKE3_X86.get(name, []) + for flags in BLAKE3_X86.values(): + for flag in flags: + assert (flag in words) == (flag in own), (flag, line) + symbols = subprocess.run(['nm', str(archive)], capture_output=True, text=True, check=True) + prefix = '_' if sys.platform == 'darwin' else '' + canary = prefix + blake3_canary(configuration) + assert canary in symbols.stdout.split(), symbols.stdout[-2000:] + + +def test_blake3_on_x86_64_declares_the_intrinsics_files(root: Path) -> None: + # Whatever the machine, a native x86-64 build, shown and not run, compiles the four + # intrinsics files, each with its own flags. + harness.copy_integration_libraries(root, 'config', 'hash') + result = harness.run_b2(root, '-n', '-a', 'architecture=x86', 'address-model=64', + 'third_party//blake3') + harness.expect(result, True) + lines = C_COMPILE.findall(result.stdout) + compiled = {Path(line.rsplit(' ', 1)[-1].strip('"')).name: line for line in lines} + assert sorted(compiled) == sorted(BLAKE3_FILES + list(BLAKE3_X86)), sorted(compiled) + for name, line in compiled.items(): + words = line.split() + own = BLAKE3_X86.get(name, []) + for flags in BLAKE3_X86.values(): + for flag in flags: + assert (flag in words) == (flag in own), (flag, line) + assert '-DBLAKE3_USE_NEON=1' not in words, line + for define in BLAKE3_PORTABLE: + assert define not in words, (define, line) + + +def test_blake3_on_wasi_is_portable(root: Path) -> None: + for request in (WASIP2, WASIP3): + expect_blake3_portable(*build_blake3(root, *request)) + shutil.rmtree(root / 'bin') + + +def test_blake3_on_emscripten_is_portable(root: Path) -> None: + harness.link_emsdk(root) + expect_blake3_portable(*build_blake3(root, *EMSCRIPTEN)) + + +def test_blake3_not_checked_out_is_refused(root: Path) -> None: + harness.third_party_of_its_own(root, 'blake3', checked_out=False) + harness.copy_integration_libraries(root, 'config', 'hash') + for target in ('third_party//blake3', 'third_party//blake3_vectors'): + result = harness.run_b2(root, target) + harness.expect(result, False, 'third_party/libs/blake3 is not checked out', + 'git submodule update --init third_party/libs/blake3') + # A build that needs no BLAKE3 never looks for it. + harness.expect(harness.run_b2(root, 'libs/demo/test//pass'), True) + + +def test_hash_not_checked_out_stops_blake3(root: Path) -> None: + # No libs/hash in the scratch superproject: the canary is missing. + result = harness.run_b2(root, 'third_party//blake3') + harness.expect(result, False, 'libs/hash is not checked out', + 'git submodule update --init libs/hash') + + CASES = [ test_the_suite_is_pinned, test_wycheproof_is_pinned, @@ -374,6 +804,7 @@ def test_secp256k1_not_checked_out_is_refused(root: Path) -> None: test_bips_is_pinned, test_bearssl_is_pinned, test_bearssl_is_built_file_by_file, + test_bearssl_without_hash_has_cryptos_canary_alone, test_third_party_jamfile_loads_without_noise, test_bearssl_not_checked_out_is_refused, test_crypto_not_checked_out_is_refused, @@ -385,6 +816,25 @@ def test_secp256k1_not_checked_out_is_refused(root: Path) -> None: test_secp256k1_small_tables_on_request, test_secp256k1_on_emscripten_has_the_small_tables, test_secp256k1_not_checked_out_is_refused, + test_xkcp_is_pinned, + test_xkcp_is_built_file_by_file, + test_xkcp_not_checked_out_is_refused, + test_hash_not_checked_out_is_refused, + test_sodium_is_pinned, + test_sodium_is_built_file_by_file, + test_sodium_defines_on_each_webassembly_target, + test_sodium_test_config_reaches_the_private_headers, + test_sodium_msvc_inline_reaches_c_alone, + test_sodium_unknown_architecture_is_refused, + test_sodium_not_checked_out_is_refused, + test_hash_not_checked_out_is_refused_by_sodium, + test_blake3_is_pinned, + test_blake3_natively_has_the_machines_simd_files, + test_blake3_on_x86_64_declares_the_intrinsics_files, + test_blake3_on_wasi_is_portable, + test_blake3_on_emscripten_is_portable, + test_blake3_not_checked_out_is_refused, + test_hash_not_checked_out_stops_blake3, ] diff --git a/tools/test/user_jamfiles.py b/tools/test/user_jamfiles.py new file mode 100644 index 00000000..3d48f1a1 --- /dev/null +++ b/tools/test/user_jamfiles.py @@ -0,0 +1,316 @@ +# 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 user's Jamfiles as fixtures (CODING-GUIDELINES.md chapter 8), shared by +crypto_jamfiles_test.py and hash_jamfiles_test.py: the outcome file's format, the build of a +case with b2 as a user runs it, the run of its program, and the command line of a test. + +A test names its directory of cases under tools/test/fixtures, the libraries of libs/ its +scratch superproject holds, and the cases it leaves out until code they need is merged. Each +target gets one scratch superproject, with those libraries and the cases in its user/; every case +of a target shares one build directory, so each C library is compiled once per target.""" + +from __future__ import annotations + +import platform +import re +import shutil +import subprocess +import sys +import time +from collections.abc import Callable +from dataclasses import dataclass, field +from pathlib import Path + +import harness + +TOOLSETS = {'native': [], 'wasip2': ['toolset=clang-wasip2'], 'wasip3': ['toolset=clang-wasip3'], + 'emscripten': ['toolset=emscripten']} +SYSTEM = {'Linux': 'linux', 'Darwin': 'darwin', 'Windows': 'windows'}[platform.system()] +# The machine's architecture, as a native block names it. +ARCHITECTURE = {'arm64': 'arm64', 'aarch64': 'arm64', 'x86_64': 'x86_64', + 'amd64': 'x86_64'}.get(platform.machine().lower(), platform.machine().lower()) + +BLOCKS = {'all', 'native', 'native-linux', 'native-darwin', 'native-windows', 'native-arm64', + 'native-x86_64', 'wasip2', 'wasip3', 'emscripten'} + + +class OutcomeError(Exception): + """An outcome file or a case directory that does not follow the format.""" + + +def launcher(target: str) -> Path: + """The script the lanes run a WASI program with (tools/ci/matrix.py, wasm_lane).""" + return harness.ROOT / f'tools/boost/asio-{target}/run.sh' + + +@dataclass +class Outcome: + """What an outcome file says for one target.""" + targets: list[str] = field(default_factory=lambda: ['native']) + succeeds: bool | None = None + run: str | None = None + lines: list[str] = field(default_factory=list) + contains: list[str] = field(default_factory=list) + # (text, allowed): no line of b2's output contains text, unless it also contains allowed + # (none: not even then). + forbidden: list[tuple[str, str | None]] = field(default_factory=list) + arguments: list[str] = field(default_factory=list) + + +def outcome(path: Path, target: str) -> Outcome: + """The blocks of path that apply to target on this system, read into an Outcome. Every line + of the file is checked, whether its block applies or not, and so is the outcome that results + when target is one the case is built for (checked).""" + applying = {'all', target} | ({'native', 'native-' + SYSTEM, 'native-' + ARCHITECTURE} + if target == 'native' else set()) + result = Outcome() + block = None + for number, raw in enumerate(path.read_text().splitlines(), 1): + where = f'{path.name}:{number}' + if not raw.strip() or raw.startswith('#'): + continue + if raw.startswith('[') and raw.endswith(']'): + block = raw[1:-1] + if block not in BLOCKS: + raise OutcomeError(f'{where}: no block [{block}]; the blocks are {sorted(BLOCKS)}') + continue + if block is None: + raise OutcomeError(f'{where}: a line before the first [block]: {raw!r}') + directive = re.match(r'([a-z]+(?:-[a-z]+)?):(?: |$)', raw) + key, value = (directive.group(1), raw[directive.end():]) if directive else ('', raw) + if key and key not in ('targets', 'build', 'run', 'arguments', 'line', 'contains', + 'not-contains', 'same-as'): + raise OutcomeError(f'{where}: no directive {key}: (a line of one lowercase word and ' + f'a colon is reserved for them): {raw!r}') + if key in ('targets', 'arguments', 'not-contains') and not value.split(): + raise OutcomeError(f'{where}: {key}: names nothing') + if key == 'targets': + unknown = [t for t in value.split() if t not in TOOLSETS] + if unknown: + raise OutcomeError( + f'{where}: no target {unknown}; the targets are {list(TOOLSETS)}') + elif key == 'build' and value not in ('succeeds', 'fails'): + raise OutcomeError(f'{where}: build: is succeeds or fails, not {value!r}') + elif key == 'run' and not value: + raise OutcomeError(f'{where}: run: names no program') + if block not in applying or key == 'same-as': + continue + if key == 'targets': + result.targets = value.split() + elif key == 'build': + result.succeeds = value == 'succeeds' + elif key == 'run': + result.run = value + elif key == 'arguments': + result.arguments += value.split() + elif key == 'contains': + result.contains.append(value) + elif key == 'not-contains': + text, separator, allowed = value.partition(' unless ') + if not text.strip() or (separator and not allowed.strip()): + raise OutcomeError(f'{where}: not-contains: needs a text, then ` unless ` ' + f'if any line may hold it: {raw!r}') + result.forbidden.append((text.strip(), allowed.strip() or None)) + else: + result.lines.append(value if key == 'line' else raw) + if target in result.targets: + checked(path, target, result) + return result + + +def checked(path: Path, target: str, result: Outcome) -> None: + """Raises an OutcomeError naming path and target unless result is coherent: a build is said + to succeed or fail; a failure has lines to find and no program to run; a success that + prints lines has a program.""" + if result.succeeds is None: + raise OutcomeError(f'{path.name} on {target}: no build: line') + if not result.succeeds and result.run is not None: + raise OutcomeError(f'{path.name} on {target}: run: after build: fails') + if result.succeeds and (result.contains or result.forbidden): + raise OutcomeError(f'{path.name} on {target}: contains: or not-contains: after build: ' + 'succeeds') + if not result.succeeds and not result.lines and not result.contains: + raise OutcomeError(f'{path.name} on {target}: build: fails with no line to find') + if result.succeeds and result.run is None and result.lines: + raise OutcomeError(f'{path.name} on {target}: lines after build: succeeds, with no run:') + + +def same_as_faults(case: Path, cases_directory: Path) -> list[str]: + """Each `same-as: / ` of case's outcome file whose two files are not + byte-identical: the file of another case of cases_directory, and case's own copy of it. A + fixture's program is a copy, never a symbolic link (a checkout on Windows reads a link as a + text file), and this keeps the copies from drifting.""" + faults: list[str] = [] + for number, raw in enumerate((case / f'{case.name}.outcome').read_text().splitlines(), 1): + if not raw.startswith('same-as:'): + continue + names = raw[len('same-as:'):].split() + where = f'{case.name}.outcome:{number}' + if len(names) != 2: + faults.append(f'{where}: same-as: names / and , not {names}') + continue + original, copy = cases_directory / names[0], case / names[1] + if not original.is_file() or not copy.is_file(): + faults.append(f'{where}: {names[0]} or {case.name}/{names[1]} does not exist') + elif original.read_bytes() != copy.read_bytes(): + faults.append(f'{where}: {case.name}/{names[1]} is not a copy of {names[0]}') + return faults + + +def case_directories(cases_directory: Path) -> list[Path]: + """Every directory of cases_directory, each with its one outcome file named after it, and + every outcome file read for every target (so each line of each block is checked), else an + OutcomeError.""" + cases = sorted(p for p in cases_directory.iterdir() if p.is_dir()) + for case in cases: + found = sorted(p.name for p in case.glob('*.outcome')) + if found != [case.name + '.outcome']: + raise OutcomeError(f'{case.name}: the outcome files are {found}; ' + f'the one is {case.name}.outcome') + if not (case / 'Jamfile').is_file(): + raise OutcomeError(f'{case.name}: no Jamfile') + for target in TOOLSETS: + outcome(case / f'{case.name}.outcome', target) + faults = same_as_faults(case, cases_directory) + if faults: + raise OutcomeError('; '.join(faults)) + return cases + + +def program_command(build_dir: Path, case: str, name: str, target: str) -> list[str]: + """The command that runs the program name that the build of case made under build_dir, as its + lane runs one.""" + suffix = {'native': '.exe' if SYSTEM == 'windows' else '', 'wasip2': '.wasm', + 'wasip3': '.wasm', 'emscripten': '.js'}[target] + found = [p for p in build_dir.rglob(name + suffix) + if p.is_file() and f'user/{case}/' in p.relative_to(build_dir).as_posix()] + if len(found) != 1: + raise AssertionError(f'the build made {len(found)} files named {name}{suffix}') + if target == 'emscripten': + return ['node', str(found[0])] + if target.startswith('wasi'): + return [str(launcher(target)), str(found[0])] + return [str(found[0])] + + +def selected(cases: list[Path], names: list[str], target: str, + not_yet: dict[str, str]) -> list[Path]: + """The cases to build for target: the named ones, else every one that is not in not_yet, + each that its outcome file's targets line names target for.""" + return [case for case in cases + if (case.name in names if names else case.name not in not_yet) + and target in outcome(case / f'{case.name}.outcome', target).targets] + + +def run_target(root: Path, target: str, cases: list[Path]) -> list[str]: + """Builds each of cases for target in root and returns the faults, one line each.""" + faults: list[str] = [] + build_dir = root / 'bin' / f'user-{target}' + for case in cases: + expected = outcome(case / f'{case.name}.outcome', target) + scratch = root / 'scratch' / case.name + scratch.mkdir(parents=True, exist_ok=True) + arguments = [a.replace('@scratch', str(scratch)) for a in expected.arguments] + # No testing.launcher: a user's exe is run by this test, not by b2. + built = harness.run_b2(root, '-j3', f'--build-dir={build_dir}', *TOOLSETS[target], + *arguments, f'user/{case.name}') + output = built.stdout + if (built.returncode == 0) != expected.succeeds: + faults.append(f'{case.name} on {target}: the build ' + f'{"succeeded" if built.returncode == 0 else "failed"}\n{output[-3000:]}') + continue + if not expected.succeeds: + printed = {line.rstrip() for line in output.splitlines()} + faults += [f'{case.name} on {target}: b2 printed no line {line!r}' + for line in expected.lines if line.rstrip() not in printed] + faults += [f'{case.name} on {target}: no line of b2 contains {text!r}' + for text in expected.contains + if not any(text in line for line in printed)] + faults += [f'{case.name} on {target}: b2 printed {line!r}, which contains {text!r}' + f'{"" if allowed is None else f" and not {allowed!r}"}' + for text, allowed in expected.forbidden for line in sorted(printed) + if text in line and (allowed is None or allowed not in line)] + continue + if expected.run is not None: + try: + command = program_command(build_dir, case.name, expected.run, target) + except AssertionError as error: + faults.append(f'{case.name} on {target}: {error}') + continue + ran = subprocess.run(command, capture_output=True, text=True, check=False) + printed = ran.stdout.replace('\r\n', '\n').splitlines() + if ran.returncode != 0 or printed != expected.lines: + faults.append(f'{case.name} on {target}: {expected.run} exited {ran.returncode} ' + f'and printed {printed!r}; the outcome says {expected.lines!r}') + return faults + + +def main(label: str, cases_directory: Path, libraries: tuple[str, ...], + not_yet: dict[str, str], argv: list[str], + check: Callable[[list[Path]], list[str]] | None = None) -> int: + """The command line of a test of label: [--target ] [case ...]. It builds the cases of + cases_directory in scratch superprojects that hold libs/ for each of libraries, and + prints `