Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 74 additions & 10 deletions tools/hash/measure.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
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/<function>_<backend>.cpp, built on every
target of its backend at variant=release optimization=space (its size: the native executable
stripped with `strip`, or the .wasm) and at optimization=speed (its throughput, the median of
five runs per invocation, natively and on each WebAssembly target where the program ends within
BOUND seconds).
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,
Expand All @@ -32,12 +32,13 @@
--check is the measure lane's (test/measure/Jamfile): it re-measures every program for size b2
built (the lists the lane writes, one per target), each run once, and fails, naming
`python3 tools/hash/measure.py --write`, when a program of a cell is missing on a target (the
lane built nothing), when a result differs from the committed one or from the independent value
Python computes, when the order by size of any row differs from the committed one, when a
generated file differs from what the committed data renders (a hand edit), or when the data's
digest does not match (a hand edit of the data). With `--measured`, it compares those
measurements instead, throughput included. It also runs bench/'s correctness program, which the
lists name, on every target: it must exit 0.
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
Expand Down Expand Up @@ -109,7 +110,8 @@

RULES = {
'size': 'the bytes of the program built at variant=release optimization=space: natively the '
'executable stripped with strip, on WebAssembly the .wasm file',
'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 '
Expand Down Expand Up @@ -441,6 +443,67 @@ def programs_of(table: Table, lists: list[Path], required: tuple[str, ...]
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:
Expand Down Expand Up @@ -547,6 +610,7 @@ def measure(table: Table, programs: list[Program], bench: list[tuple[str, Path]]
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],
Expand Down
69 changes: 64 additions & 5 deletions tools/test/hash_measure_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@
`python3 tools/hash/measure.py --write` when the size order of a row changes, when a throughput
median moves more than 10 percent past the one ahead of it (spec 4.2's rule alone: a
first measurement orders by the medians, and the runs' spread plays no part), when a generated
file or the data was edited by hand, and when a program of a cell is missing on a target (a lane
that built nothing); a median that moves by under 10 percent changes nothing. Each key
derivation operation has its own ranking (hkdf_extract and hkdf_expand beside hkdf); every order
names every backend with a tag, so that the per-operation default always finds one; the
portable order is hash2, sodium, bearssl. Native orders measured with another native toolchain
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
Expand Down Expand Up @@ -455,6 +456,63 @@ def test_a_missing_program_fails(scratch: Path) -> None:
'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']:
Expand Down Expand Up @@ -561,6 +619,7 @@ def test_no_tracked_file_cites_a_controller_ruling(_: Path) -> None:
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,
Expand Down