From c6d706ea150598219f3030001c1d422763ea86f4 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 18:05:26 -0300 Subject: [PATCH] tools: webcpp::hash defaults to backends::hash2, and its measure lane and tools/hash/measure.py are retired The owner's decisions of 2026-11-16 (libs/hash at 3c9505a). tools/hash/doc_tables.py renders hash's backends.adoc and measurements.adoc, the reference measured on 2026-11-16, and fails on a hand edit of its data or a function without a default; tools/hash/measure.py and its test are removed, with the CI's setup of an own lane that builds every target and the lint's handling of its WebAssembly commands, which only hash's measure lane used. The fixtures of the removed profile and override messages go; argon2id_default_not_linked and scrypt_default_not_linked come. --- doc/releases/0.1.0.adoc | 11 +- libs/hash | 2 +- tools/ci/matrix.py | 38 +- tools/ci/matrix_test.py | 32 - tools/hash/doc_tables.py | 350 ++-- tools/hash/measure.py | 1421 ----------------- tools/lint/compile_commands.py | 42 +- tools/lint/lint_test.py | 51 - tools/test/fixtures/hash_jamfiles/app/app.cpp | 2 +- .../argon2id_default_not_linked/Jamfile | 9 + .../app.cpp | 5 +- .../argon2id_default_not_linked.outcome} | 4 +- .../argon2id_override_hash2/Jamfile | 10 - .../argon2id_override_hash2.outcome | 13 - .../override_cannot_serve/Jamfile | 10 - .../override_cannot_serve/app.cpp | 22 - .../override_cannot_serve.outcome | 13 - .../overrides_openssl_on_emscripten/Jamfile | 12 - .../overrides_openssl_on_emscripten/app.cpp | 21 - .../overrides_openssl_on_emscripten.outcome | 16 - .../profile_openssl_on_emscripten/app.cpp | 21 - .../profile_openssl_on_emscripten.outcome | 12 - .../Jamfile | 5 +- .../scrypt_default_not_linked/app.cpp | 20 + .../scrypt_default_not_linked.outcome} | 4 +- .../scrypt_override_hash2/Jamfile | 10 - .../scrypt_override_hash2/app.cpp | 20 - .../hash_jamfiles/two_overrides/Jamfile | 11 - .../hash_jamfiles/two_overrides/app.cpp | 14 - .../hash_jamfiles/two_profiles/Jamfile | 11 - .../hash_jamfiles/two_profiles/app.cpp | 13 - .../two_profiles/two_profiles.outcome | 13 - .../two_umbrella_profiles/Jamfile | 11 - .../two_umbrella_profiles/app.cpp | 14 - .../two_umbrella_profiles.outcome | 13 - tools/test/hash_doc_tables_test.py | 132 +- tools/test/hash_jamfiles_format_test.py | 16 +- tools/test/hash_measure_test.py | 648 -------- 38 files changed, 398 insertions(+), 2674 deletions(-) delete mode 100644 tools/hash/measure.py create mode 100644 tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/Jamfile rename tools/test/fixtures/hash_jamfiles/{argon2id_override_hash2 => argon2id_default_not_linked}/app.cpp (65%) rename tools/test/fixtures/hash_jamfiles/{scrypt_override_hash2/scrypt_override_hash2.outcome => argon2id_default_not_linked/argon2id_default_not_linked.outcome} (59%) delete mode 100644 tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/argon2id_override_hash2.outcome delete mode 100644 tools/test/fixtures/hash_jamfiles/override_cannot_serve/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/override_cannot_serve/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/override_cannot_serve/override_cannot_serve.outcome delete mode 100644 tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/overrides_openssl_on_emscripten.outcome delete mode 100644 tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/profile_openssl_on_emscripten.outcome rename tools/test/fixtures/hash_jamfiles/{profile_openssl_on_emscripten => scrypt_default_not_linked}/Jamfile (57%) create mode 100644 tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/app.cpp rename tools/test/fixtures/hash_jamfiles/{two_overrides/two_overrides.outcome => scrypt_default_not_linked/scrypt_default_not_linked.outcome} (59%) delete mode 100644 tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/two_overrides/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/two_overrides/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/two_profiles/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/two_profiles/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/two_profiles/two_profiles.outcome delete mode 100644 tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/Jamfile delete mode 100644 tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/app.cpp delete mode 100644 tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/two_umbrella_profiles.outcome delete mode 100644 tools/test/hash_measure_test.py diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 1a729f51..3a833afb 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -300,15 +300,8 @@ 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. +* Added tools/hash/doc_tables.py, which generates webcpp::hash's tables, data chapters and +llms.txt from its capability table and 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. diff --git a/libs/hash b/libs/hash index 46b19892..3c9505a7 160000 --- a/libs/hash +++ b/libs/hash @@ -1 +1 @@ -Subproject commit 46b1989216813bf85ba42610b4c571a3310e80eb +Subproject commit 3c9505a78305856a1c8664bf92f235cb3cc69c63 diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 7ae37a21..bfd47d2c 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -83,12 +83,9 @@ 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), 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. +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. 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 @@ -189,16 +186,6 @@ ('document', 'js'), ('trystero', 'interop'), ('webrtc', 'browser'), ('webrtc', '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, @@ -634,16 +621,6 @@ 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 @@ -659,10 +636,7 @@ 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' - 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, + entry.update(kind=own.kind, name=own.name, os=base.os, wasm=base.wasm, emsdk=base.emsdk, node=node, cc=base.cc, cxx=base.cxx, external=needs_external(own.library), chrome=(own.library, own.lane) in CHROME_LANES) return entry @@ -912,9 +886,7 @@ 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.""" - # 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) + register(resolved(own_lane_profile(own)), 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 cfd79e60..954af306 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -523,37 +523,6 @@ 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'] @@ -1572,7 +1541,6 @@ 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/hash/doc_tables.py b/tools/hash/doc_tables.py index a99f19ab..e9fa3261 100644 --- a/tools/hash/doc_tables.py +++ b/tools/hash/doc_tables.py @@ -12,11 +12,12 @@ 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/: +which targets, over which hmacs, with its constant time, and each function's default backend: +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 it is there, measurements.json (each program's size per target and its throughput, a +reference measured once, on 2026-11-16, that decides nothing: the default backend is fixed, spec +4.1). 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 @@ -24,26 +25,30 @@ 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; + table (backend, the Jamfile line, targets, hmacs, constant time), and each function's default; - 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; +- generated/measured.adoc: the includes of the data chapters, backends.adoc and + measurements.adoc (this tool), performance.adoc (bench/collect.py) and allocation.adoc + (bench/allocation_collect.py), each one that is there; +- backends.adoc: the capability table as the guide's data chapter shows it; +- measurements.adoc: measurements.json's tables, labelled as the dated reference they are; - 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. +an example that example/ does not hold; when a function of the capability table has no default +or a type has one; and when measurements.json's digest does not match its content (a hand edit +of the reference). 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 hashlib import json import sys from pathlib import Path @@ -56,18 +61,17 @@ '// 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. +# The chapters of the measured data, in the order the guide shows them, and what writes each: +# this tool writes the first two, from doc/capabilities.json and doc/measurements.json. MEASURED_CHAPTERS = ( - ('backends.adoc', 'tools/hash/measure.py --capabilities'), - ('measurements.adoc', 'tools/hash/measure.py --write'), + ('backends.adoc', 'this tool, from doc/capabilities.json'), + ('measurements.adoc', 'this tool, from doc/measurements.json'), ('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). +OWN_CHAPTERS = ('backends.adoc', 'measurements.adoc') +TARGETS = ('native', 'wasip2', 'wasip3', 'emscripten') +# The chapters whose throughput is a rate over 1 MiB (the measured table's workloads). RATE_CHAPTERS = ('digests', 'macs', 'non-cryptographic') @@ -111,6 +115,34 @@ def __init__(self, library: Path) -> None: for function in algorithm['functions']: self.functions[function['name']] = (algorithm, function) self.check_guide() + self.check_defaults() + self.check_digest() + + def check_defaults(self) -> None: + """A function (a template with a Backend parameter) names its default, a backend that + has it; a type has none.""" + faults = [] + for name, (_, function) in self.functions.items(): + default = function.get('default') + if function['kind'] == 'function' and default not in function['backends']: + faults.append(f'doc/capabilities.json: the function {name} has no default ' + f'among its backends ({default})') + if function['kind'] != 'function' and default is not None: + faults.append(f'doc/capabilities.json: the type {name} has a default, {default}') + if faults: + raise Failure('\n'.join(faults)) + + def check_digest(self) -> None: + """measurements.json's digest, the SHA-256 of its content without it: the reference is + never edited by hand.""" + if self.measurements is None: + return + body = {k: v for k, v in self.measurements.items() if k != 'digest'} + digest = 'sha256:' + hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + if self.measurements.get('digest') != digest: + raise Failure('doc/measurements.json: its digest does not match its content, which ' + 'was edited by hand; the reference measured on 2026-11-16 is kept as ' + 'measured') def check_guide(self) -> None: facts = self.guide['functions'] @@ -139,14 +171,6 @@ def records(self, operation: str) -> list[dict]: 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' @@ -230,11 +254,11 @@ def compare_table(data: Data, chapter: dict) -> str: 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.' + + out.append(f'The measured columns are doc/measurements.json\'s, a reference measured ' + f'on {m["date"]} on {m["machine"]["cpu"]} that decides nothing: 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: @@ -256,42 +280,8 @@ def hmacs_text(hmacs: list[str] | None) -> str: 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 = [generated_header('doc/capabilities.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 \ @@ -319,40 +309,24 @@ def backends_table(data: Data, algorithm: dict) -> str: out.append('') out.extend(f'* `{backend}`: {cell(source)}' for backend, source in sources) out.append('') - if not algorithm['overridable']: + defaults = [(f['name'], f['default']) for f in algorithm['functions'] if f['default']] + if not defaults: 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(f'One backend, {", ".join(f"`{n}`" for n in names)}: the types take no backend.') 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('|===') + by_backend: dict[str, list[str]] = {} + for name, default in defaults: + by_backend.setdefault(default, []).append(f'`{name}`') + for default, names in by_backend.items(): + named = names[0] if len(names) == 1 else \ + ', '.join(names[:-1]) + f' and {names[-1]}' + others = sorted({b for f in algorithm['functions'] for b in f['backends']} - {default}) + tail = (f'; {", ".join(f"`{b}`" for b in others)} only where the call names it, as its ' + 'second template argument') if others else '' + out.append(f'The default of {named}: `{default}` on every target, whatever the program ' + f'links{tail} (<>).') 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) @@ -361,7 +335,7 @@ def choose_table(data: Data) -> str: 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 ' + out.append('| I need to ... | Use | Its backends: the Jamfile names | Backend ' '| Example') for case in data.guide['use_cases']: _, function = data.functions[case['function']] @@ -371,18 +345,25 @@ def choose_table(data: Data) -> str: 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'| {cell(case["backend"])}') out.append(f'| `example/{case["example"]}`') out.append('|===') out.append('') return '\n'.join(out) +def rendered_chapters(data: Data) -> set[str]: + """The data chapters this tool renders: backends.adoc always, measurements.adoc with its + data.""" + return {'backends.adoc'} | ({'measurements.adoc'} if data.measurements is not None else set()) + + 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(): + if name in rendered_chapters(data) or (name not in OWN_CHAPTERS and + (data.library / 'doc' / name).is_file()): out.append(f'include::../{name}[]') out.append('') else: @@ -405,7 +386,10 @@ def llms_txt(data: Data) -> str: '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.', '', + 'program links /webcpp/hash//hash and the library of each backend it uses. Every ' + 'key derivation runs on backends::hash2 unless the call names another backend as ' + 'its second template argument; argon2id and scrypt run on backends::sodium, their ' + 'only backend.', '', '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.', '', @@ -435,7 +419,7 @@ def llms_txt(data: Data) -> str: 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"]}; ' + lines.append(f'- I need to {case["need"]}: {case["use"]}; backend: {case["backend"]}; ' f'example libs/hash/example/{case["example"]}. ' f'[Section]({page}#{case["anchor"]})') lines.append('') @@ -443,12 +427,166 @@ def llms_txt(data: Data) -> str: 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/capabilities.json also names each function\'s default backend') lines.append('- doc/measurements.json: each backend\'s program size per target and its ' - 'throughput') + 'throughput, a reference measured on 2026-11-16 that decides nothing') lines.append('') return '\n'.join(lines) +def chapter_header(title: str, anchor: str, sources: str) -> list[str]: + return [generated_header(sources), f'[#{anchor}]', f'== {title}', ''] + + +def backends_chapter(data: Data) -> str: + """The capability table as the guide's data chapter shows it: the backends; per chapter, + each function on each backend, its hmacs, its constant time and its targets; each + function's default; and what each upstream states on constant time.""" + table = data.capabilities + names = [b['name'] for b in table['backends']] + lines = chapter_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 names: + c = function['backends'].get(name) + if c is None: + continue + hmacs = ', '.join(c['hmacs']) if c['hmacs'] else '-' + targets = ', '.join(data.backends[name]['targets']) + lines += ['', f'| {function["name"]}', f'| {name}', f'| {hmacs}', + f'| {c["constant_time"]["value"]}', f'| {targets}'] + lines += ['|===', ''] + lines += ['=== The default backends', '', + 'The backend a call that names none uses, on every target, whatever the program ' + 'links (<>):', '', + '[cols="2,1",options="header"]', '|===', '| Function | Default'] + for _, function in data.functions.values(): + if function['default'] is not None: + lines += ['', f'| {function["name"]}', f'| {function["default"]}'] + lines += ['|===', '', '=== Constant time', '', + 'What each backend\'s upstream states, and where:', ''] + seen = set() + for _, function in data.functions.values(): + 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 measured_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 measured_speed(data: Data, operation: str, t: dict) -> str: + algorithm, _ = data.functions[operation] + if algorithm['chapter'] in RATE_CHAPTERS: + def per_second(ns: float) -> str: + return f'{1e9 / ns:.0f}' + return (f'{per_second(t["median_ns"])} MiB/s ({per_second(t["max_ns"])} to ' + f'{per_second(t["min_ns"])})') + return (f'{measured_time(t["median_ns"])} ({measured_time(t["min_ns"])} to ' + f'{measured_time(t["max_ns"])})') + + +def measurements_chapter(data: Data) -> str: + """measurements.json's tables, the size and the throughput of each cell on each target, + under the label of the dated reference they are.""" + m = data.measurements + assert m is not None + machine = m['machine'] + lines = chapter_header('Measured size and throughput', 'hash-measurements', + 'doc/measurements.json') + lines += [f'A reference measured once, on {m["date"]}, that decides nothing: what each ' + 'backend cost a program on each', + 'target, in bytes and in time, when webcpp measured it. Every key derivation\'s ' + 'default is', + '`backends::hash2`, Argon2id\'s and scrypt\'s `backends::sodium`, whatever these ' + 'tables say', + '(<>): `hash2` is the only backend that covers every hmac, ' + 'operation and', + 'target; it is header-only, so a program carries only what it calls and shares the ' + 'SHA code it', + 'already uses; and the differences measured here for HKDF are nanoseconds natively ' + 'and a few KB', + 'of an isolated program on WebAssembly. No lane measures these figures again, and ' + 'a move of a', + 'C library\'s pin leaves them as they were.', '', + f'Measured on {m["date"]} on {machine["cpu"]}, {machine["cores"]} cores, ' + f'{machine["memory_gib"]} GiB, {machine["os"]};', + f'WebAssembly under {m["runtimes"]["wasip2"]} (wasip2, wasip3) and ' + f'{m["runtimes"]["emscripten"]} (Emscripten).', + 'Compilers: ' + '; '.join(f'{t}: {c}' for t, c in m['toolchains'].items()) + + '.', ''] + native = m.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 m['loaded']: + load = m['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 {machine["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: {m["rules"]["size"]}. Throughput: {m["rules"]["throughput"]}.', ''] + by_cell: dict[tuple, dict[str, dict]] = {} + for r in m['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 m['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'| {measured_speed(data, operation, r["throughput"])}') + lines += ['|===', ''] + 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] = {} @@ -460,6 +598,9 @@ def render(data: Data) -> dict[str, str]: backends_table(data, algorithm) files['generated/choose.adoc'] = choose_table(data) files['generated/measured.adoc'] = measured_includes(data) + files['backends.adoc'] = backends_chapter(data) + if data.measurements is not None: + files['measurements.adoc'] = measurements_chapter(data) files['llms.txt'] = llms_txt(data) return files @@ -479,6 +620,7 @@ def main(argv: list[str]) -> int: print(f'doc_tables.py: {failure}', file=sys.stderr) return 1 present = {str(p.relative_to(doc)) for p in (doc / 'generated').glob('*.adoc')} + present |= {name for name in OWN_CHAPTERS if (doc / name).is_file()} if arguments.write: (doc / 'generated').mkdir(exist_ok=True) for name in present - set(files): diff --git a/tools/hash/measure.py b/tools/hash/measure.py deleted file mode 100644 index d74dba73..00000000 --- a/tools/hash/measure.py +++ /dev/null @@ -1,1421 +0,0 @@ -#!/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, linked without debug information) 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 WebAssembly program for size carries debug information (whose paths -are those of the host that built its libraries), 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, which carries no ' - 'debug information', - '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 leb128(data: bytes, at: int) -> tuple[int, int]: - """The unsigned LEB128 at data[at:], and the offset after it.""" - value, shift = 0, 0 - while True: - if at >= len(data): - raise ValueError('a LEB128 runs past the end') - byte = data[at] - at += 1 - value |= (byte & 0x7f) << shift - shift += 7 - if not byte & 0x80: - return value, at - - -def custom_sections(data: bytes) -> list[str]: - """The names of the custom sections of a WebAssembly binary, a core module or a component, - and of every core module and component it nests.""" - if data[:4] != b'\0asm' or len(data) < 8: - raise ValueError('not a WebAssembly binary') - component = data[4:8] != b'\x01\0\0\0' - names, at = [], 8 - while at < len(data): - section = data[at] - size, start = leb128(data, at + 1) - end = start + size - if end > len(data): - raise ValueError('a section runs past the end') - if section == 0: - length, name = leb128(data, start) - names.append(data[name:name + length].decode('utf-8', 'replace')) - elif component and section in (1, 4): - # A component's core module section (1) and component section (4) each hold one - # whole binary. - names += custom_sections(data[start:end]) - at = end - return names - - -def check_stripped(programs: list[Program]) -> None: - """Fails naming each WebAssembly program for size that carries debug information: DWARF - holds the paths of the machine that built its libraries (wasi-sdk's libc++ was built at - /Users/runner/... for macOS and at /src/... for Linux), so its size would depend on the host - that measures it, and a WebAssembly order is compared on every host.""" - found = [] - for program in programs: - if program.target == 'native' or program.optimization != 'space': - continue - wasm = program.path.with_suffix('.wasm') - try: - sections = custom_sections(wasm.read_bytes()) - except (OSError, ValueError) as error: - raise Failure(f'{wasm}: {error}') from error - debug = sorted({s for s in sections if s.startswith('.debug')}) - if debug: - found.append(f'space-{program.cell.id} on {program.target} ({", ".join(debug)})') - if found: - raise Failure('debug information, whose paths depend on the host that built the ' - 'libraries, is in ' + ', '.join(found) + ': test/measure/Jamfile links ' - 'every WebAssembly program for size without it') - - -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'] - check_stripped(space) - 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 bb21bf10..491fba49 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -24,10 +24,7 @@ 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. 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. +first target that compiles them does, with its own --target. 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 @@ -655,44 +652,19 @@ 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), leaving out, natively, the WebAssembly commands - of a source the same run also compiles natively; a WebAssembly command of a compiler other than + in seen, as the lint analyses it (analysed); 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 natively(root, target, compiles(lines)): + for words in compiles(lines): source = words[-1] unit = ALONE.match(source) if unit: @@ -710,8 +682,7 @@ 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(compiled_for(target, words), source, words, - wasi_clang)}) + 'arguments': analysed(target, source, words, wasi_clang)}) prepare_provider_headers(root, request, selected, lines) return units, sources @@ -813,7 +784,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 natively(root, target, compiles(lines)): + for words in compiles(lines): source = words[-1] unit = ALONE.match(source) if unit: @@ -836,8 +807,7 @@ 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(compiled_for(target, words), source, words, - wasi_clang)}) + 'arguments': analysed(target, 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_test.py b/tools/lint/lint_test.py index d3f4b369..22acf3a2 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -1077,56 +1077,6 @@ def test_a_compiled_boost_library_s_sources_are_not_analysed(root): expect_clean(lint(root)) -def test_a_native_lane_s_webassembly_commands_are_left_to_its_native_one(root): - # An own lane that names no target runs natively, and may build its programs for every - # target in one command (libs/hash's measure lane does): its dry run then compiles one - # source natively, with wasi-sdk's clang++ and with em++. The source is analysed natively, - # as the first target that compiles it, and its WebAssembly commands are left out, so that - # no file of the database is compiled by both kinds of compiler; in either order, and in the - # twins without exceptions too. A source that such a run compiles for WebAssembly alone is - # analysed as its compiler's target: an em++ command as emscripten's, by wasi-sdk's clang++ - # with em++'s target, never as a host command. - prepare(root) - harness.link_emsdk(root) - wasi = wasi_sdk_tool('clang++') - emxx = str(root / '.local/emsdk/upstream/emscripten/em++') - source = 'libs/demo/test/pass.cpp' - alone = 'libs/demo/test/fails.cpp' - - def line(compiler: str, where: str, file: str, *words: str) -> 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) @@ -2909,7 +2859,6 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_a_dependency_s_warnings_are_not_ours, test_clang_tidy_reads_boost_unordered_on_every_host, 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/fixtures/hash_jamfiles/app/app.cpp b/tools/test/fixtures/hash_jamfiles/app/app.cpp index 24ea84da..9fcfca51 100644 --- a/tools/test/fixtures/hash_jamfiles/app/app.cpp +++ b/tools/test/fixtures/hash_jamfiles/app/app.cpp @@ -6,7 +6,7 @@ // 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). +// first case), each on Boost.Hash2 (backends::hash2, the default on every target). #include #include diff --git a/tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/Jamfile b/tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/Jamfile new file mode 100644 index 00000000..712d5644 --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/argon2id_default_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/argon2id_default_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/argon2id_override_hash2/app.cpp b/tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/app.cpp similarity index 65% rename from tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/app.cpp rename to tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/app.cpp index e3438536..b49021cb 100644 --- a/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/app.cpp +++ b/tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/app.cpp @@ -4,9 +4,8 @@ // 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. +// argon2id on its default backend, backends::sodium, in a program that does not link libsodium +// stops with the instruction to add /third_party//sodium (spec section 5.7, the third row). #include diff --git a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/scrypt_override_hash2.outcome b/tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/argon2id_default_not_linked.outcome similarity index 59% rename from tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/scrypt_override_hash2.outcome rename to tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/argon2id_default_not_linked.outcome index 1faf4361..cab59234 100644 --- a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/scrypt_override_hash2.outcome +++ b/tools/test/fixtures/hash_jamfiles/argon2id_default_not_linked/argon2id_default_not_linked.outcome @@ -6,8 +6,8 @@ # 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. +# test/messages/argon2id_default_not_linked, 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. +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/argon2id_override_hash2/Jamfile b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/Jamfile deleted file mode 100644 index 7e76e229..00000000 --- a/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/Jamfile +++ /dev/null @@ -1,10 +0,0 @@ -# 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/argon2id_override_hash2.outcome b/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/argon2id_override_hash2.outcome deleted file mode 100644 index 70d695e0..00000000 --- a/tools/test/fixtures/hash_jamfiles/argon2id_override_hash2/argon2id_override_hash2.outcome +++ /dev/null @@ -1,13 +0,0 @@ -# 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/override_cannot_serve/Jamfile b/tools/test/fixtures/hash_jamfiles/override_cannot_serve/Jamfile deleted file mode 100644 index f04831bb..00000000 --- a/tools/test/fixtures/hash_jamfiles/override_cannot_serve/Jamfile +++ /dev/null @@ -1,10 +0,0 @@ -# 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 deleted file mode 100644 index dd732576..00000000 --- a/tools/test/fixtures/hash_jamfiles/override_cannot_serve/app.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// 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 deleted file mode 100644 index b4e4a986..00000000 --- a/tools/test/fixtures/hash_jamfiles/override_cannot_serve/override_cannot_serve.outcome +++ /dev/null @@ -1,13 +0,0 @@ -# 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 deleted file mode 100644 index dbc65be8..00000000 --- a/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/Jamfile +++ /dev/null @@ -1,12 +0,0 @@ -# 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 deleted file mode 100644 index d3159418..00000000 --- a/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/app.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// 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 deleted file mode 100644 index ad427d37..00000000 --- a/tools/test/fixtures/hash_jamfiles/overrides_openssl_on_emscripten/overrides_openssl_on_emscripten.outcome +++ /dev/null @@ -1,16 +0,0 @@ -# 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/profile_openssl_on_emscripten/app.cpp b/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/app.cpp deleted file mode 100644 index d3159418..00000000 --- a/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/app.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// 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 deleted file mode 100644 index 64e29172..00000000 --- a/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/profile_openssl_on_emscripten.outcome +++ /dev/null @@ -1,12 +0,0 @@ -# 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/profile_openssl_on_emscripten/Jamfile b/tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/Jamfile similarity index 57% rename from tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/Jamfile rename to tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/Jamfile index 11a1d4c5..76de710a 100644 --- a/tools/test/fixtures/hash_jamfiles/profile_openssl_on_emscripten/Jamfile +++ b/tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/Jamfile @@ -4,5 +4,6 @@ # 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 ; +# test/messages/scrypt_default_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/scrypt_default_not_linked/app.cpp b/tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/app.cpp new file mode 100644 index 00000000..654f579d --- /dev/null +++ b/tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/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) + +// scrypt on its default backend, backends::sodium, in a program that does not link libsodium stops +// with the instruction to add /third_party//sodium (spec section 5.7, the third row). + +#include + +#include +#include + +int main() { + std::array output{}; + std::array salt{}; + auto done = webcpp::hash::scrypt(output, {}, salt, webcpp::hash::scrypt_parameters{1024, 8, 1}); + return done ? 0 : 1; +} diff --git a/tools/test/fixtures/hash_jamfiles/two_overrides/two_overrides.outcome b/tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/scrypt_default_not_linked.outcome similarity index 59% rename from tools/test/fixtures/hash_jamfiles/two_overrides/two_overrides.outcome rename to tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/scrypt_default_not_linked.outcome index 1949f007..99688c29 100644 --- a/tools/test/fixtures/hash_jamfiles/two_overrides/two_overrides.outcome +++ b/tools/test/fixtures/hash_jamfiles/scrypt_default_not_linked/scrypt_default_not_linked.outcome @@ -6,8 +6,8 @@ # 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. +# test/messages/scrypt_default_not_linked, 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. +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/scrypt_override_hash2/Jamfile b/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/Jamfile deleted file mode 100644 index 5ed40cbd..00000000 --- a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/Jamfile +++ /dev/null @@ -1,10 +0,0 @@ -# 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 deleted file mode 100644 index 89f773fe..00000000 --- a/tools/test/fixtures/hash_jamfiles/scrypt_override_hash2/app.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// 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/two_overrides/Jamfile b/tools/test/fixtures/hash_jamfiles/two_overrides/Jamfile deleted file mode 100644 index 9802d87f..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_overrides/Jamfile +++ /dev/null @@ -1,11 +0,0 @@ -# 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 deleted file mode 100644 index c3c0a5e3..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_overrides/app.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// 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_profiles/Jamfile b/tools/test/fixtures/hash_jamfiles/two_profiles/Jamfile deleted file mode 100644 index 8ddb1af4..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_profiles/Jamfile +++ /dev/null @@ -1,11 +0,0 @@ -# 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 deleted file mode 100644 index 5bc57eb5..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_profiles/app.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// 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 deleted file mode 100644 index ee7e5835..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_profiles/two_profiles.outcome +++ /dev/null @@ -1,13 +0,0 @@ -# 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 deleted file mode 100644 index f58c6537..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/Jamfile +++ /dev/null @@ -1,11 +0,0 @@ -# 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 deleted file mode 100644 index 5d49b9ba..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/app.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// 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 deleted file mode 100644 index 8acadddf..00000000 --- a/tools/test/fixtures/hash_jamfiles/two_umbrella_profiles/two_umbrella_profiles.outcome +++ /dev/null @@ -1,13 +0,0 @@ -# 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/hash_doc_tables_test.py b/tools/test/hash_doc_tables_test.py index 4576e9ad..e3936b07 100644 --- a/tools/test/hash_doc_tables_test.py +++ b/tools/test/hash_doc_tables_test.py @@ -12,15 +12,18 @@ 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.""" +example is not there, and so does a function of the capability table without a default. Every +function's default is the capability table's, `hash2` for HKDF whatever the measurements say. +Without doc/measurements.json the tables say so, carry no measured column and render no +measurements.adoc; with it (a fixture in its shape) they carry the throughput and the size, and +measurements.adoc renders it as the dated reference that decides nothing; a hand edit of the +data, which its digest tells, fails. 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 hashlib import json import shutil import subprocess @@ -64,6 +67,9 @@ def written(library: Path) -> dict[str, str]: 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') + for name in ('backends.adoc', 'measurements.adoc'): + if (doc / name).is_file(): + files[name] = (doc / name).read_text(encoding='utf-8') return files @@ -73,10 +79,14 @@ def write_ok(library: Path) -> dict[str, str]: return written(library) +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 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).""" + """doc/measurements.json's shape, for HKDF's three operations and sha2_256: HKDF is smallest + and fastest on BearSSL, then sodium, then hash2, which must not move its default.""" records = [] whole = {'hash2': 3000, 'sodium': 2000, 'bearssl': 1000, 'openssl': 9000} step = {'hash2': 1500, 'sodium': 2000, 'openssl': 9000} @@ -99,18 +109,15 @@ def measurements(library: Path) -> dict: 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} + data = {'date': '2026-11-15', + 'machine': {'cpu': 'Fixture CPU', 'cores': 2, 'memory_gib': 4, 'os': 'Fixture OS'}, + 'loaded': True, 'load_average_before_after': [[9.0, 8.0, 7.0], [6.0, 5.0, 4.0]], + 'toolchains': {'native': 'Fixture clang'}, + 'runtimes': {'wasip2': 'Fixture wasmtime', 'emscripten': 'Fixture node'}, + 'native_toolchain': {}, 'workloads': {'hkdf': 'one derivation'}, + 'rules': {'size': 'fixture sizes', 'throughput': 'fixture throughput'}, + 'records': records} + data['digest'] = digest_of(data) (library / 'doc/measurements.json').write_text(json.dumps(data), encoding='utf-8') return data @@ -182,6 +189,23 @@ def test_a_use_case_names_an_example_that_is_there(scratch: Path) -> None: expect('example/hkdf.cpp, which is not there' in done.stderr, done.stderr) +def test_every_function_names_its_default(scratch: Path) -> None: + library = scratch_library(scratch) + path = library / 'doc/capabilities.json' + table = json.loads(path.read_text(encoding='utf-8')) + for algorithm in table['algorithms']: + for function in algorithm['functions']: + if function['name'] == 'pbkdf2': + function['default'] = None + if function['name'] == 'sha2_256': + function['default'] = 'hash2' + path.write_text(json.dumps(table), encoding='utf-8') + done = run(library, '--write') + expect(done.returncode == 1, 'a function without a default was rendered') + expect('the function pbkdf2 has no default' in done.stderr, done.stderr) + expect('the type sha2_256 has a default' in done.stderr, done.stderr) + + def test_without_measurements_the_tables_say_so(scratch: Path) -> None: library = scratch_library(scratch) files = write_ok(library) @@ -189,9 +213,21 @@ def test_without_measurements_the_tables_say_so(scratch: Path) -> None: '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('measurements.adoc' not in files, 'measurements.adoc without its data') + hkdf = files['generated/backends-hkdf.adoc'] + expect('The default of `hkdf_extract`, `hkdf_expand` and `hkdf`: `hash2` on every target' + in hkdf, f'the backends of HKDF do not name the default: {hkdf}') + expect('`bearssl`, `openssl`, `sodium` only where the call names it' in hkdf, hkdf) + expect('The default of `argon2id`: `sodium` on every target' + in files['generated/backends-argon2id.adoc'], 'Argon2id\'s default') + expect('One backend, `hash2`: the types take no backend.' + in files['generated/backends-blake2.adoc'], 'a type\'s backend') + backends = files['backends.adoc'] + expect('| pbkdf2\n| hash2' in backends and '| scrypt\n| sodium' in backends, + 'backends.adoc does not list the defaults') expect('Backends: hash2 (/webcpp/hash//hash' in files['llms.txt'], 'llms.txt has no backends') + expect('Every key derivation runs on backends::hash2' in files['llms.txt'], + 'llms.txt does not say the default') def test_with_measurements_the_tables_carry_them(scratch: Path) -> None: @@ -202,23 +238,34 @@ def test_with_measurements_the_tables_carry_them(scratch: Path) -> None: 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 reference measured on 2026-11-15 on Fixture CPU that decides nothing' in digests, + 'the measured columns are not labelled as the reference') expect('a loaded, shared machine' in digests, 'the note hides that the machine was loaded') + hkdf = files['generated/backends-hkdf.adoc'] + # BearSSL is the smallest and the fastest HKDF of the fixture: the default stays hash2. + expect('`hkdf`: `hash2` on every target' in hkdf, 'the measurements moved a default') 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}') + page = files['measurements.adoc'] + expect('A reference measured once, on 2026-11-15, that decides nothing' in page, + 'measurements.adoc is not labelled as the dated reference') + expect('`backends::hash2`' in page and 'header-only' in page, + 'measurements.adoc does not say why hash2 is the default') + expect('WARNING: the machine was shared and loaded' in page, 'the load is hidden') + expect('| hkdf\n| hmac_sha2_256\n| bearssl\n| 1000\n| 1000\n| 1000\n| 1000' in page, + 'the size table') + expect('| 569 MiB/s (500000000 to 1000000000)' in page, 'the throughput table') + expect('orders' not in page.lower(), 'measurements.adoc still shows the orders') + + +def test_a_hand_edit_of_the_measurements_fails(scratch: Path) -> None: + library = scratch_library(scratch) + data = measurements(library) + data['records'][0]['size_bytes'] = 1 + (library / 'doc/measurements.json').write_text(json.dumps(data), encoding='utf-8') + done = run(library, '--write') + expect(done.returncode == 1, 'measurements edited by hand were rendered') + expect('its digest does not match its content' in done.stderr, done.stderr) def test_no_table_is_a_matrix(scratch: Path) -> None: @@ -248,11 +295,12 @@ def test_measured_chapters_are_included_when_present(scratch: Path) -> None: 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, + expect('include::../backends.adoc[]' in measured, 'backends.adoc, always rendered, is left out') + expect('include::../measurements.adoc[]' not in measured, 'an absent chapter is included') + expect('`doc/measurements.adoc` (this tool, from doc/measurements.json)' 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') + measurements(library) + (library / 'doc/allocation.adoc').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') @@ -273,8 +321,10 @@ def test_the_real_library_s_files_are_its_data_s(scratch: Path) -> None: 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_every_function_names_its_default, test_without_measurements_the_tables_say_so, test_with_measurements_the_tables_carry_them, + test_a_hand_edit_of_the_measurements_fails, test_no_table_is_a_matrix, test_measured_chapters_are_included_when_present, test_the_real_library_s_files_are_its_data_s, diff --git a/tools/test/hash_jamfiles_format_test.py b/tools/test/hash_jamfiles_format_test.py index ff0b1748..b7566f09 100644 --- a/tools/test/hash_jamfiles_format_test.py +++ b/tools/test/hash_jamfiles_format_test.py @@ -46,21 +46,21 @@ def test_the_tree_has_no_fault(): 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') + shutil.copytree(messages / 'sodium_hmac', messages / 'other_hmac') + (messages / 'other_hmac' / 'sodium_hmac.cpp').rename( + messages / 'other_hmac' / 'other_hmac.cpp') faults = faults_of_copies(change) - assert any('three_profiles has no fixture' in f for f in faults), faults + assert any('other_hmac 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 = messages / 'sodium_not_linked' / 'sodium_not_linked.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 + assert any(f.startswith('sodium_not_linked: app.cpp') for f in faults), faults def test_a_changed_text_is_a_fault(): @@ -74,10 +74,10 @@ def change(messages: Path, _: Path) -> None: def test_a_fixture_of_no_message_is_a_fault(): def change(messages: Path, _: Path) -> None: - shutil.rmtree(messages / 'two_overrides') + shutil.rmtree(messages / 'pbkdf2_on_sodium') faults = faults_of_copies(change) - assert any(f.startswith('two_overrides: its Jamfile names') for f in faults), faults + assert any(f.startswith('pbkdf2_on_sodium: its Jamfile names') for f in faults), faults def main() -> int: diff --git a/tools/test/hash_measure_test.py b/tools/test/hash_measure_test.py deleted file mode 100644 index 2fcf8013..00000000 --- a/tools/test/hash_measure_test.py +++ /dev/null @@ -1,648 +0,0 @@ -#!/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, when a program of a cell is missing on a target (a lane -that built nothing), and when a WebAssembly program for size carries debug information, whose -paths are the host's that built its libraries; 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 wasm_section(name: str, payload: bytes) -> bytes: - """A custom section of a WebAssembly binary: id 0, its size, its name and its payload (each - length one LEB128 byte, as the fixtures' are short).""" - body = bytes([len(name)]) + name.encode() + payload - return bytes([0, len(body)]) + body - - -# A core module (version 1) and a component (layer 1, version 0x0d) with no section, and a -# component holding a core module, the shape wasip2's programs have. -WASM_MODULE = b'\0asm\x01\0\0\0' -WASM_COMPONENT = b'\0asm\x0d\0\x01\0' - - -def test_a_webassembly_program_with_debug_information_fails(scratch: Path) -> None: - # A .wasm's size is host-independent only without DWARF: wasi-sdk's prebuilt libc++ carries - # its include paths, /Users/runner/... in the macOS release and /src/... in the Linux one, - # so a debug section makes the same program's size depend on the host that measures it. - data = measured(capabilities()) - directory = library(scratch) - written(directory, data, scratch) - lists = scratch / 'lists' - lists.mkdir() - debug = WASM_MODULE + wasm_section('.debug_info', b'/Users/runner/work/wasi-sdk') - nested = WASM_COMPONENT + bytes([1, len(debug)]) + debug - programs = [] - for target in TARGETS: - names = [f'space-{r["operation"]}_{r["backend"]}' - + (f'_{r["hmac"]}' if r['hmac'] else '') - for r in data['records'] if r['target'] == target] - suffix = {'native': '', 'emscripten': '.js'}.get(target, '.wasm') - (lists / target).mkdir() - for name in names: - stem = lists / target / name - if target == 'native': - stem.write_bytes(b'program') - else: - content = WASM_COMPONENT if target in ('wasip2', 'wasip3') else WASM_MODULE - if name == 'space-hkdf_sodium_hmac_sha2_512' and target == 'wasip2': - content = nested - if name == 'space-hkdf_hash2_hmac_sha2_256' and target == 'emscripten': - content = debug - stem.with_suffix('.wasm').write_bytes(content) - if target == 'emscripten': - stem.with_suffix('.js').write_text('') - path = lists / f'measure-programs-{target}-space.txt' - path.write_text(''.join(f'{lists}/{target}/{name}{suffix}\n' for name in names)) - programs.append(str(path)) - for target in TARGETS: - path = lists / f'measure-programs-{target}-bench.txt' - path.write_text(f'{lists}/bench-{target}\n') - programs.append(str(path)) - fails(run('--library', str(directory), '--check', '--strip', 'true', '--programs', - *programs), - 'space-hkdf_sodium_hmac_sha2_512 on wasip2', '.debug_info', - 'space-hkdf_hash2_hmac_sha2_256 on emscripten', 'test/measure/Jamfile') - - -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_a_webassembly_program_with_debug_information_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:]))