From 684c4feed137af2e1912fecff75119bad8c509c8 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 2 Nov 2026 23:03:58 -0500 Subject: [PATCH 01/32] build: adopt Wasmtime 50.0.1 and fix validation failures [skip ci] Update the shared runtime and library instructions, validate every declared WASI target, and correct allocation and example regressions found by the broader matrix. Restore source-built OpenSSL recipes, P3 network capabilities, Cobalt lint overlays and container prerequisites. Record local validation and retain historical measurements. --- AGENTS.md | 20 ++- CODING-GUIDELINES.md | 158 ++++++----------- README.md | 4 +- doc/releases/0.1.0.adoc | 5 + .../plans/2026-11-02-wasmtime-50.md | 106 ++++++++++++ libs/asio | 2 +- libs/config | 2 +- libs/document | 2 +- libs/lexical | 2 +- libs/wasi | 2 +- third_party/Jamfile | 1 + tools/boost/asio-wasip3/README.md | 4 +- tools/boost/asio-wasip3/run.sh | 3 +- tools/boost/cobalt-wasip3/Jamfile | 4 +- tools/boost/cobalt-wasip3/acceptor.cpp | 4 +- tools/boost/cobalt-wasip3/endpoint.cpp | 4 +- tools/ci/actions/wasmtime/action.yml | 4 +- tools/ci/actions/wasmtime/install.sh | 26 +-- tools/ci/actions_test.py | 82 ++++++++- tools/ci/container/Dockerfile | 6 +- tools/ci/matrix.py | 7 +- tools/ci/matrix_test.py | 49 +++++- tools/component/serve.py | 6 +- tools/component/serve_test.py | 4 +- tools/lint/compile_commands.py | 41 ++++- tools/lint/lint_test.py | 44 ++++- tools/openssl/build.py | 160 +++++++++++++---- tools/openssl/build_test.py | 162 ++++++++++++++++++ tools/openssl/msvc.conf | 22 +++ tools/openssl/pin.json | 162 +++++++++++++++++- tools/openssl/source.py | 28 ++- tools/openssl/source_test.py | 18 ++ tools/openssl/update.py | 3 +- tools/test/openssl_test.py | 66 ++++++- tools/webcpp-openssl.jam | 57 ++++-- 35 files changed, 1048 insertions(+), 222 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-02-wasmtime-50.md create mode 100644 tools/openssl/build_test.py create mode 100644 tools/openssl/msvc.conf diff --git a/AGENTS.md b/AGENTS.md index dcb231a3..b3c1b386 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -221,7 +221,7 @@ Jamroot is its build configuration, and `libs/` is its repository. - b2 (B2 5.5.3 measured); - a C++20 compiler; - Python 3.9 or newer; -- for WebAssembly: wasi-sdk 34 and wasmtime 47 (47.0.3 measured); +- for WebAssembly: wasi-sdk 34 and wasmtime 50.0.1; - for WebAssembly components, such as wasi's: wit-bindgen 0.62.0, which generates a world's C bindings, and the `wasi:http` WIT of WASI 0.2.12 and 0.3.0, the `wit/deps` directories of the Rust crates `wasip2` 1.0.4 and @@ -443,7 +443,8 @@ told: `b2 --user-config=.local/user-config.jam ...`. | `b2 libs//test` | one library's tests; `libs//example` and `libs//doc` likewise | | `b2 libs//test//` | one test, while working on it (`scheduler`) | | `b2 libs//doc//reference` | one library's API reference alone, MrDocs strict | -| `b2 toolset=clang-wasip2 testing.launcher=wasmtime libs//test libs//example` | the same for wasm32-wasip2; `clang-wasip3` for wasm32-wasip3; one toolset per command | +| `b2 toolset=clang-wasip2 testing.launcher=wasmtime libs//test libs//example` | the same for wasm32-wasip2; one toolset per command | +| `b2 toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh libs//test libs//example` | wasm32-wasip3 with the test networking capabilities | | `b2 toolset=emscripten libs//test libs//example` | the same for emscripten, whose programs b2's toolset runs with node itself: never with a `testing.launcher` (chapter 4) | | `b2 install --prefix=` | copies every library's headers to `/include/webcpp/`, and its licence files, `LICENSE_1_0.txt` and a port's `LICENSE-.txt`, beside them in `/include/webcpp//` | | `b2 declared-targets -d0` | prints each ` ` pair the libraries declare: the CI's lanes | @@ -850,7 +851,7 @@ A target is what a program is built for: | `native` | any toolset not below: gcc, clang, msvc, darwin | the host | | `emscripten` | b2's `emscripten`, wasm32, single-threaded, static | node, run by the toolset itself; no `testing.launcher` | | `wasip2` | `clang-wasip2`, a clang registered against wasi-sdk with version `wasip2` | `testing.launcher=wasmtime`; a component, `wasmtime serve` (below) | -| `wasip3` | `clang-wasip3`, likewise | `testing.launcher=wasmtime`; a component, `wasmtime serve` (below) | +| `wasip3` | `clang-wasip3`, likewise | `testing.launcher=tools/boost/asio-wasip3/run.sh`; a component, `wasmtime serve` (below) | A Jamfile declares its default with `webcpp.targets`, a program can override it with its own targets, and with no declaration a program is built for @@ -1237,7 +1238,8 @@ scratch, and records what it built and ran: b2 -a --dump-tests --out-xml=.xml toolset= libs//test libs//example ``` -A wasip2 or wasip3 lane adds `testing.launcher=wasmtime`, which applies to +A wasip2 lane adds `testing.launcher=wasmtime`; a wasip3 lane adds +`testing.launcher=tools/boost/asio-wasip3/run.sh` for network-capable tests. Both apply to every toolset of one b2 request, so a lane is always one toolset. An emscripten lane adds nothing: b2's toolset runs its programs with node. The lane runs from the superproject's root. `--dump-tests` is required: it lists every @@ -1503,7 +1505,7 @@ jobs: | `msvc-14.3` | windows-2022 | Visual Studio 2022 | | `msvc-14.5` | windows-2025 | Visual Studio 2026 | | `emscripten` | ubuntu-24.04 | `emscripten`: Emscripten 6.0.11 from emsdk, its system libraries built in the cache the action restores, and Node 26.7.0 through the wrapper of the emsdk action (its entry's `node`) | - | `wasip2`, `wasip3` | ubuntu-24.04 | `clang-wasip2`, `clang-wasip3`: wasi-sdk 34, wasmtime 47.0.3, wit-bindgen 0.62.0 and the WASI WIT, for every library | + | `wasip2`, `wasip3` | ubuntu-24.04 | `clang-wasip2`, `clang-wasip3`: wasi-sdk 34, wasmtime 50.0.1, wit-bindgen 0.62.0 and the WASI WIT, for every library | The Clang lanes on libstdc++ stay: a regression of xactor's guarantee 28 is caught only there. The MSVC lanes add `address-model=64 @@ -1511,13 +1513,17 @@ jobs: a toolset directory, and `msvc-14.3` and `msvc-14.5` are their own abbreviations, which `tools/ci/matrix_test.py` checks with b2's own rule. + The WASIp3 lane uses `tools/boost/asio-wasip3/run.sh`, which grants network + and name lookup for the loopback tests and enables the pinned runtime + component features. WASIp2 retains the plain `wasmtime` launcher. + **The container lanes,** `gcc-14` and `clang-linux-18` (their entries' `container`), run the lane's b2 in a Linux container with no network but the loopback, so that a test that reaches beyond the machine fails there: every library's tests hold it, and trystero's guarantee 6 rests on it. The image is `tools/ci/container/Dockerfile`'s: Ubuntu 24.04, the runner's release, pinned by the digest of its image index, with `g++-14`, - `clang-18`, OpenSSL's development files and Python, every package, + `clang-18`, OpenSSL's development files, Python, Git, Make and Perl, every package, `ca-certificates` included, from Ubuntu's snapshot of the archive at the date its `ARG SNAPSHOT` names (`Snapshot: yes` on the sources, `apt-get --snapshot`), so that one Dockerfile is one set of packages. The snapshot @@ -1672,7 +1678,7 @@ wrapper each quoted as one word of Jam. an empty `--prefix` installs into `/usr/local`. `install.sh source ` fills such a tree alone, for a machine whose Boost comes from elsewhere. - `wasi-sdk` installs wasi-sdk 34 into `.local/wasi-sdk`, `wasmtime` - installs wasmtime 47.0.3 on `PATH`, `mrdocs` installs MrDocs 2026.9.29 into + installs wasmtime 50.0.1 on `PATH`, `mrdocs` installs MrDocs 2026.9.29 into `.local/mrdocs`, and `node` sets up Node 26.7.0, with npm's cache keyed on the lock files of `tools/doc`, `tools/lint`, every library's `test/oracle` and the site's, `site/`. diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index c77ab140..34e4bd6e 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -90,7 +90,7 @@ Not built yet: - every declared lane from scratch: `b2 -a libs//test libs//example` natively, and with `toolset=clang-wasip2 testing.launcher=wasmtime` and `toolset=clang-wasip3 - testing.launcher=wasmtime` where declared, and every own lane the + testing.launcher=tools/boost/asio-wasip3/run.sh` where declared, and every own lane the library declares, `b2 -a libs//test/oracle//oracle` for an oracle and, on each target it names, `b2 -a toolset=clang-wasip2 testing.launcher=wasmtime libs/wasi/test//http` for one on wasip2; @@ -367,7 +367,11 @@ exactly its authors' and the program carries only what it calls. with another OpenSSL copy. The Asio alias links this dependency explicitly. Its headers are upstream's, so this adapter uses B2 dependency ordering and exact archive paths instead of injecting canary calls into upstream APIs. - Native Clang/GCC recipes cover macOS/Linux; MSVC/nmake is not implemented. + Native Clang/GCC recipes cover macOS/Linux. MSVC uses upstream Configure + with nmake, explicit B2 runtime/debug flags and static `.lib` outputs; + its initial profile uses portable C (`no-asm`) without a NASM dependency. + Recipe/staging tests run locally; real Windows compilation remains a + separate CI validation, not inferred from a dry run. WASIp3 single and cooperative profiles must agree with the consumer's threading choice. Keep explicit host entropy seeding and fail-closed tests. Other libraries with external dependencies still use `webcpp.external`. @@ -871,7 +875,7 @@ update --init third_party/libs/`; a build that needs none never looks. | Target | What it is | Licence | | --- | --- | --- | | `ca_certificates` | Dated Mozilla/curl CA data snapshot under `third_party/ca_certificates`, verified against its manifest and embedded by a build-generated header; updated explicitly by `tools/ca_certificates/update.py` | MPL-2.0 | -| `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC and WASIp3 | Apache-2.0 | +| `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC and WASIp3 | Apache-2.0 | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | @@ -1219,7 +1223,7 @@ site's own decisions follow in the next sections. `organization/openspec/changes/archive/2026-10-07-genesis/design.md` (proposals). - **Every tool has one pinned version: Boost 1.92.0 and the b2 it bootstraps - (B2 5.5.3), wasi-sdk 34, wasmtime 47.0.3, wit-bindgen 0.62.0 with the WASI + (B2 5.5.3), wasi-sdk 34, wasmtime 50.0.1, wit-bindgen 0.62.0 with the WASI WIT of the crates `wasip2` 1.0.4 and `wasip3` 0.9.0, Emscripten 6.0.11, MrDocs 2026.9.29 and Node 26.7.0.** The lint takes clang-format and clang-tidy from the pinned wasi-sdk so that every machine and the CI lint @@ -3259,7 +3263,7 @@ built, is recorded apart. recorded) Source: `doc/build.adoc` (libs/wasi). - **wasi targets `wasi:http` 0.2.12 and 0.3.0 alone, as measured with - wasi-sdk 34, wit-bindgen 0.62.0 and wasmtime 47.0.3, and the page names + wasi-sdk 34, wit-bindgen 0.62.0 and wasmtime 50.0.1, and the page names each version as measured.** WASI 0.3 is young: a toolchain update may move the names the bindings' glue calls. Source: @@ -3337,8 +3341,8 @@ built, is recorded apart. the version is not recorded. Source: `include/webcpp/wasi/http/entrypoint.hpp` (libs/wasi). - **A component is linked as a reactor, `-mexec-model=reactor`.** It exports - a handler and has no C `main`; wasmtime 47 also serves it linked as a - command, but webcpp builds and tests reactors. + a handler and has no C `main`. Historical tests with wasmtime 47 also + served it linked as a command; current webcpp builds and tests reactors. Source: `doc/build.adoc` (libs/wasi). - **b2 looks for wit-bindgen, the `wasi:http` WIT and wasmtime only when a target needs them, each at its `-s` variable first, then under `.local/` @@ -3382,8 +3386,9 @@ built, is recorded apart. Source: `include/webcpp/wasi/http/entrypoint.hpp` (libs/wasi). - **On wasip3 the handler returns the response, then writes to the body's stream until the stream has taken every byte, then resolves the trailers - future.** wasmtime 47 takes a whole body, 1 MiB too, in one write; the loop - stands for a host that takes less per write. + future.** Historical tests with wasmtime 47 took a whole body, 1 MiB too, + in one write; the loop stands for a host that takes less per write. The + 50.0.1 regression verifies delivery, not a particular number of writes. Source: `doc/guarantees.adoc` (libs/wasi). - **On wasip3 the future of whether the host sent the response is dropped unread.** The guest could change nothing about a response already sent. @@ -3407,7 +3412,7 @@ built, is recorded apart. **Exceptions and configuration.** - **The handler throws, tries and catches nothing: an exception that escapes - the main traps the instance, and wasmtime 47 answers its own HTML 500 and + the main traps the instance, and wasmtime 50.0.1 answers its own HTML 500 and keeps serving.** The owner decided it on 2026-10-08, settling the open item of catching `std::exception` in the handler to print its `what()`: the host answers, and wasi needs neither exceptions nor RTTI and imposes @@ -3418,11 +3423,13 @@ built, is recorded apart. - **wasi's programs, and the by-hand commands its page shows, build wasip2 with exceptions as wasip3: `-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false`, linked with `-fwasm-exceptions -lunwind`.** - Measured for wasi: wasmtime 47 runs the exnref encoding with its default - flags and refuses the legacy one wasi-sdk 34 emits by default, and - exceptions cost about 20% of a stripped component and nothing at a warm - start, while their absence cost Boost.Locale, a second Boost configuration - and a wasip2-only path in every header. + Wasmtime 50.0.1 runs the exnref encoding with its default flags. Historical + measurements with wasmtime 47 showed rejection of the legacy encoding + wasi-sdk 34 emits by default, about 20% extra stripped component size + with exceptions and no measured warm-start cost. Those measurements were + not repeated for the runtime upgrade. The absence of exceptions cost + Boost.Locale, a second Boost configuration and a wasip2-only path in + every header. Source: `libraries/wasi/openspec/changes/archive/2026-10-08-genesis/reference/research/WASIP2_EXCEPTIONS_SPIKE.md` (proposals). @@ -3481,7 +3488,7 @@ built, is recorded apart. pass only on the guard's own error (`expected-error` of clang's `-verify`).** A compile that fails for another reason fails the test. Source: `libraries/wasi/openspec/specs/wasi/spec.md` (proposals). -- **`http_bad_status` and `http_bad_content_type` hold wasmtime 47's HTML +- **`http_bad_status` and `http_bad_content_type` hold wasmtime 50.0.1's HTML 500 verbatim.** They fail when wasmtime changes how it answers an internal error, and are regenerated knowingly. Source: @@ -6566,7 +6573,7 @@ The original proposal has not been amended and no CI ran. exception runtime. Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md`, `tools/webcpp-wasi.jam` (superproject, uncommitted). -- **The WASIp3 tests run under Wasmtime 49.0.3 through the launcher +- **The WASIp3 tests use the project-pinned Wasmtime 50.0.1 through the launcher `tools/boost/asio-wasip3/run.sh`, which grants network and name lookup and bounds a run to 15 s.** Wasmtime 47.0.3 cannot load the cooperative component, and the loopback tests need the network; the launcher is no @@ -8061,92 +8068,32 @@ The proposals not yet decided, each briefly, with the questions they leave for the owner. A draft decides nothing: it is here so that a contributor sees what is coming, and its proposal holds it in full. -### beast (draft, not decided) - -webcpp::beast would be a header-only C++20 wrapper over Boost.Beast and -webcpp::asio, for native and Emscripten only: Boost.Beast itself natively, and -in the browser the same names and layered code driving `WebSocket` -(increment 1) and `fetch` (increment 2). What exists is the draft -specification of 2026-10-10 (`reference/spec.md`) with four decisions of the -owner of that day; there is no plan and no reference code, and both are -required before the proposal can be accepted. - -- **webcpp::beast is a library of its own on webcpp::asio, not a part of it: - the WebSocket client first, then the HTTP client in the browser.** Beast is - a library on Asio, so webcpp::beast is a library on webcpp::asio (the - owner's decision 1 of 2026-10-10). - Source: `libraries/beast/openspec/changes/genesis/design.md` D1 (proposals). -- **Natively it is Boost.Beast (aliases of Beast's types, and a - `websocket::stream` derived from Beast's that adds an allocator - constructor); the browser classes exist only on Emscripten; every name that - touches no network is Beast's own on both targets.** Natively there is no - cost and no difference: Beast's own types, one derived class and two - functions; the derived stream gives the two targets one constructor set. - Source: `libraries/beast/openspec/changes/genesis/design.md` D2 (proposals). -- **What the browser cannot honour fails as a value, - `boost::asio::error::operation_not_supported` at the operation that depends - on it, under the default `WEBCPP_BEAST_UNSUPPORTED_ERROR`; - `WEBCPP_BEAST_UNSUPPORTED_IGNORE` ignores it; every setting is classified - honoured, unsupported, or ignored with its reason.** Silent divergence was - rejected: a program that asks for a client certificate or a ping must learn - so (the owner's decision 2). - Source: `libraries/beast/openspec/changes/genesis/design.md` D3 (proposals). -- **On Emscripten the resolver is webcpp::asio's: it completes with one entry - that carries the host and the service and an unspecified endpoint, which - only webcpp::beast's browser streams accept.** A resolver of webcpp::beast's - own, with webcpp::asio's failing like its sockets, was rejected: every Beast - client would change a line (the owner's decision 4). - Source: `libraries/beast/openspec/changes/genesis/design.md` D4 (proposals). -- **The layers record and the last one opens: `async_connect` records the host - and service, the TLS handshake judges the recorded settings, and - `async_handshake(host, target)` calls `new WebSocket(url, subprotocols)`.** - It is the only way to keep Beast's code shape, because the browser has one - call that does resolution, connection, TLS and the upgrade together. - Source: `libraries/beast/openspec/changes/genesis/design.md` D5 (proposals). -- **Back-pressure is the library's: a bound on `bufferedAmount` (default 4 - MiB) fails a write with `error::send_limit`, and a bounded receive queue in - the stream's allocator closes the stream past its bound, the next read - completing with `error::receive_limit`.** The browser's `send` never blocks - and messages arrive whether a read is pending or not, and the goal is - bounded memory in the browser; `WebSocketStream`, which would pause - receiving, exists in Chromium only and doubles the surface, so it is a later - increment. - Source: `libraries/beast/openspec/changes/genesis/design.md` D7 (proposals). -- **The HTTP client reuses Beast's algorithms by making the browser - `tcp_stream` a byte stream: the bytes Beast's serializer writes are parsed - back, sent as one `fetch` per whole request, and the response is serialized - into the bytes the reads yield.** webcpp::beast then overloads no HTTP - algorithm; the cost is one parse and one serialization per message, for - Beast's code unchanged. - Source: `libraries/beast/openspec/changes/genesis/design.md` D8 (proposals). -- **The unsupported setting is read once, in ``, both - macros defined is an `#error`, a propagated b2 feature - `webcpp-beast-unsupported` sets it for a whole program, and the browser - classes live in an inline namespace named after the setting.** The two - macros change inline code, so translation units that disagree would break - the one definition rule; in the inline namespace they name different types - and fail at link, never silently. - Source: `libraries/beast/openspec/changes/genesis/reference/spec.md` section - 7 (proposals). - -**Open questions for the owner.** - -- O1, the header layout: the public headers and the convenience header, and - whether `` leaves `ssl` out natively, as webcpp::asio's - convenience header does because it brings OpenSSL. -- O2, the default bound of the receive queue (the send bound is 4 MiB) and the - names of the two options, to measure and decide in the plan. -- O3, how the decorator is called on an empty `websocket::request_type`: - whether any field other than `User-Agent` can be told apart by name alone, - or every field but the subprotocols is unsupported, as the specification - says (to confirm with a test). -- O4, streaming request bodies: the specification buffers a body whole before - the `fetch`; a streaming upload (Chromium only) belongs to a later change. -- O5, the proposal to Boost, made when both webcpp::asio and webcpp::beast - have run in real programs, trystero first. - -Source: `libraries/beast/openspec/changes/genesis/design.md` Open Questions -(proposals). +### beast (implementation started locally) + +The owner authorized implementation on 2026-11-02 after expanding the proposal +in `libraries/beast/openspec/changes/genesis` to WASIp2, WASIp3, Emscripten and all +53 upstream executable examples. That proposal governs over the older +2026-10-10 baseline. Upstream Beast data types are reused; host transports do not +need upstream network/protocol execution. The library currently exists as a local +repository at `libs/beast`, with no organization repository or release yet. + +The first increment separates portable messages/parsers/serializers from explicit +socket algorithm headers and optional TLS. Native and WASIp3 use the existing +Asio socket backend; browser WebSocket/fetch and WASI host HTTP remain subsequent +work, with application adaptation distinguished from exact transport parity. +The feature matrix is in the library guide; only recorded build/runtime evidence +establishes a supported profile. The remaining proposal must not be marked complete +from this initial backend. + +The unsupported-setting policy is a propagated B2 feature, default error. Native +WebSocket state keeps upstream allocation while accepting the portable allocator +constructor syntax. `set_server_name` configures guest TLS SNI only and rejects +empty, overlong and embedded-NUL names; it does not perform certificate verification. + +The implementation plan and current decisions are in the proposal's +`reference/plan.md` and `design.md`. No change adds guest OpenSSL or a missing +Asio WASIp2 reactor as a prerequisite to host HTTP. Missing Unix socket facilities +receive explicit host-stream counterparts where meaningful. ### webrtc (draft, not decided) @@ -8663,11 +8610,6 @@ tasks 22/23 or approve the remaining conformance departures. implementation, local tests, and an AsciiDoc feature matrix" (`docs/superpowers/specs/2026-10-15-asio-wasip3.md`); no proposal amends D16. -- **The WASI runtime and launcher.** `AGENTS.md` chapter 1: "wasi-sdk 34 and - wasmtime 47 (47.0.3 measured)"; `AGENTS.md` chapter 4: a WASI lane "adds - `testing.launcher=wasmtime`". The WASIp3 tests need Wasmtime 49.0.3 and - `testing.launcher=tools/boost/asio-wasip3/run.sh`, which grants network - access. Not approved beyond the plan's record of the tested configuration. - **Tests run on every declared target.** Chapter 8: "Every test runs on every target its Jamfile declares." `cobalt_thread` and `wasi_core_threads` (asio, uncommitted) are explicit, in no lane, so only a request by name runs them. diff --git a/README.md b/README.md index 3e0f5dd6..5da2ae3d 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ library on every target are published at . - Python 3.9 or newer, which compares the examples with their expected output and runs the tests of the build itself; - for WebAssembly, wasi-sdk 34, whose clang builds for wasm32-wasip2 and - wasm32-wasip3, and wasmtime 47, which runs what it builds; + wasm32-wasip3, and wasmtime 50.0.1, which runs what it builds; - for emscripten, Emscripten 6.0.11 from emsdk, and Node, which runs what it builds; - for trystero, libsecp256k1 0.8.0, natively and built with Emscripten, and, @@ -159,7 +159,7 @@ wasi-sdk 34 in `~/user-config.jam`: and run the tests and the examples with wasmtime, one toolset per command: b2 toolset=clang-wasip2 testing.launcher=wasmtime test example - b2 toolset=clang-wasip3 testing.launcher=wasmtime test example + b2 toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh test example Every target builds with exceptions: whether a program uses them is the choice of whoever builds it, every library supports a build without them, diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 5282c78b..d771cbf0 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -49,6 +49,11 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Updated Wasmtime to 50.0.1 for every library's WASI targets. +* Fixed WASIp3 network tests lacking the required runtime capabilities. +* Fixed OpenSSL source builds with symlinked compilers and Windows checkouts. +* Added native MSVC OpenSSL build recipes with B2 runtime settings. +* Fixed Cobalt lint builds requiring pre-existing generated Boost overlays. * Fixed source distributions rejecting pinned site and third-party dependencies. * Changed release checks to accept the tested compiler subset. * Added agent skills with validated metadata for common contributor workflows. diff --git a/docs/superpowers/plans/2026-11-02-wasmtime-50.md b/docs/superpowers/plans/2026-11-02-wasmtime-50.md new file mode 100644 index 00000000..2b6ce0e6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-02-wasmtime-50.md @@ -0,0 +1,106 @@ +# Wasmtime 50.0.1 project-wide upgrade + +The owner requested Wasmtime 50 across the project and every library during the +initial Beast implementation. The latest official patch is 50.0.1, released on +2026-10-29. This upgrade continues the active implementation and CI corrections; +it does not authorize a new remote CI run or change the user's Homebrew installation. + +## Scope and decisions + +- Pin 50.0.1 in the shared installer for Linux/macOS, x64/ARM64, using each official + release asset's SHA-256. Download and verify all four archives. +- Use the same runtime for WASIp2, WASIp3 single and WASIp3 cooperative variants. + Keep the P3 capability-aware launcher and the SDK's cooperative EH restriction. +- Update current build instructions, tool diagnostics, lane names, test expectations + and library runtime contracts. Preserve dated measurements and generated report + samples as history; do not relabel old measurements as new results. +- Install into the isolated checkout's ignored `.local/wasmtime-50/` and select it + explicitly through PATH and WASMTIME for every verification command. + +## Work and validation + +- [x] Verify official latest release and obtain the four asset digests. +- [x] Observe installer regressions fail against the old pin, then update installer, + action and tests. Validate real macOS ARM64 installation and all four archive hashes. +- [x] Run the complete action suite: 48 cases passed, plus shell syntax and Pyright. +- [x] Initialize every pinned library in the isolated checkout and inventory declared + targets and own lanes. No existing checkout was reset. +- [x] Run fresh Release tests/examples for all nine libraries declaring WASIp2 and + all ten declaring WASIp3, with exceptions on/off and threads disabled. +- [x] Run WASI HTTP test/example lanes for P2/P3 and Asio Cobalt/TLS lanes for P3. +- [x] Run available P3 cooperative Asio/Beast/Cobalt tests with exceptions off. +- [x] Run affected component runner and CI matrix suites under 50.0.1. +- [x] Render affected library documentation, run combined lint, inspect remaining + old-version references, review and record exact results before committing. + +## Reproducibility + +The logs and isolated build directories are under `.local/wasmtime-50-validation/`. +The actual runtime is `.local/wasmtime-50/wasmtime/wasmtime`: + +```text +wasmtime 50.0.1 (c307ec81d 2026-10-29) +``` + +The installer and actions suite log is `/tmp/webcpp-wasmtime50-actions-test.log`. +The shared runtime's previous pin was 47.0.3; prior cooperative tests used 49.0.3. +These remain historical evidence, not the selected toolchain after this upgrade. + +## Regressions found by the wider matrix + +- Lexical's allocation control was optimized away in Release. The same component + failed under 47.0.3 and 50.0.1. Test-scoped `-fno-builtin` preserves its exact + counting assertion; `allocation_release` now exercises this in default Debug + requests too. Twenty fresh native/P2/P3/Emscripten executions passed. +- Config's quick-start example correctly printed `exceptions off`, but compared it + with an `on` transcript. Complementary example targets now share the original + implementation and select the recorded output for each exception mode. Ten fresh + native/P2/P3/Emscripten executions passed, with no forced exception mode. +- The whole-tree lint passed 897 compilation commands over 406 translation units. + The later Lexical flags and Config wrapper passed focused lint with refreshed B2 + commands. Independent review accepted these changes and the runtime upgrade. +- Four general P3 instructions still bypassed the network-capable launcher. The + same Beast socket program failed with plain Wasmtime and passed with the shared + launcher; the general README, agent guide and coding guide now use it. + +## Final local verification + +The broad commands used fresh Release builds, `-a`, a separate build directory, +and Wasmtime 50.0.1 selected explicitly. Their original logs are retained: + +| Group | Observed result | Log under `.local/wasmtime-50-validation/` | +| --- | --- | --- | +| All nine WASIp2 libraries, single, exceptions on/off | 470 checks passed and 376 example actions; three failing actions before the fixes below | `wasip2-single-all.log` | +| All ten WASIp3 libraries, single, exceptions on/off | 548 checks passed and 384 example actions; the same three failing actions | `wasip3-single-all.log` | +| Served HTTP, P2/P3, exceptions on/off | 38 checks, exit 0 | `http-both-all.log` | +| P3 cooperative Asio/Beast, including Cobalt/thread/TLS, exceptions off | 55 checks and six examples, exit 0 | `wasip3-coop-all.log` | +| P3 Cobalt/TLS own lanes, single, exceptions on/off | Exit 0 | `wasip3-own-single-all.log` | + +Each broad command exited 1: Lexical allocation failed in both exception modes, +and the Config quick-start transcript failed with exceptions off. No other failure +appeared. These original commands are not reported as successful reruns. After the +two fixes, fresh focused executions passed for every affected target and variant: +20 Lexical executions and ten Config executions across native, P2, P3 and +Emscripten. Their logs are `/tmp/webcpp-lexical-allocation-*.log` and +`/tmp/webcpp-config-example-*.log`. + +Additional local results: + +- The 48-case action suite, matrix suite and component serve suite passed. The + actual installer verified all four official archive hashes and installed the + macOS ARM64 runtime used here. +- Combined lint passed, including the 59-case lint framework suite. Focused lint + passed after refreshing commands for the later Lexical/Config changes. +- Config, Asio, WASI and Beast documentation rendered with MrDocs and passed the + source and rendered checks; `.local/beast-implementation/docs-50-final.log` + records the successful build. +- Independent review found no remaining critical or important issue. Dated + measurements, minimum-supported-runtime descriptions and generated report + samples retain their original versions. + +Library commits: Asio `3c72eea`, Config `9fb4210`, Document `458d592`, Lexical +`4991536`, WASI `27aafae` (including runtime update `8e98c0a`), and the initial +local Beast repository `c7dfe2b`. +The existing Homebrew runtime was not replaced. No new remote CI run, push or +merge was performed. The separate OpenSSL MSVC recipe has local orchestration +coverage; actual Windows compilation/execution still requires a Windows runner. diff --git a/libs/asio b/libs/asio index 3611a6ed..3c72eea5 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 3611a6ed78dcde4a3da3f314d3aba5453ff99428 +Subproject commit 3c72eea579690c131cae36528ea8b0d8793cb628 diff --git a/libs/config b/libs/config index cf72ef80..9fb4210b 160000 --- a/libs/config +++ b/libs/config @@ -1 +1 @@ -Subproject commit cf72ef808375d78fd21b5bd2a008f4f590a228d1 +Subproject commit 9fb4210bdd9099d0f825732daf9b34afa9f5e6e8 diff --git a/libs/document b/libs/document index 3f78d0b2..458d592f 160000 --- a/libs/document +++ b/libs/document @@ -1 +1 @@ -Subproject commit 3f78d0b2b6b107d37e916949386a4ed4c8dd5554 +Subproject commit 458d592fe5f0cf373350abd926f4e16d7d4205e3 diff --git a/libs/lexical b/libs/lexical index 1a0556da..49915361 160000 --- a/libs/lexical +++ b/libs/lexical @@ -1 +1 @@ -Subproject commit 1a0556da6a43f8a1864a368c76d418e09714efa5 +Subproject commit 49915361dc2e50fd244284ef17ce0fdb22d8d49c diff --git a/libs/wasi b/libs/wasi index 983119bd..27aafae0 160000 --- a/libs/wasi +++ b/libs/wasi @@ -1 +1 @@ -Subproject commit 983119bde46a6d20235eaca8c03fe9631f019d18 +Subproject commit 27aafae0a7693b80bd69ff0052cb4f9eebd6aa4b diff --git a/third_party/Jamfile b/third_party/Jamfile index c5de848d..0b6eec11 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -87,6 +87,7 @@ import webcpp-openssl ; webcpp-openssl.declare $(WEBCPP_ROOT) : $(.openssl-headers:B).h $(.openssl-templates:B) : ../tools/openssl/build.py ../tools/openssl/source.py ../tools/openssl/wasip3.conf + ../tools/openssl/msvc.conf ../tools/openssl/pin.json [ glob-tree-ex libs/openssl : *.c *.h *.in *.pl *.pm *.S *.s *.conf *.num build.info Configure VERSION.dat *.tmpl : .git ] ; explicit openssl ; diff --git a/tools/boost/asio-wasip3/README.md b/tools/boost/asio-wasip3/README.md index 424bb00d..c215093e 100644 --- a/tools/boost/asio-wasip3/README.md +++ b/tools/boost/asio-wasip3/README.md @@ -36,8 +36,8 @@ missing constants globally or implement UDP sequences as multiple sends. The tested SDK is wasi-sdk 34.0 (wasi-libc `2e6fb9d8ee0cdf9e431fbcabe8af3115de000a13`). The cooperative C++ sysroot currently -contains the no-exceptions runtime only. Wasmtime 49.0.3 runs both profiles; -47.0.3 could not load the cooperative component. `run.sh` is a bounded local-test +contains the no-exceptions runtime only. The project selects Wasmtime 50.0.1 for both profiles. Earlier tests found that +47.0.3 could not load the cooperative component, while 49.0.3 could. `run.sh` is a bounded local-test launcher, using `wasmtime` on `PATH` and granting network/name-lookup access. It is not a production capability policy. diff --git a/tools/boost/asio-wasip3/run.sh b/tools/boost/asio-wasip3/run.sh index a3dbe7fc..06702b0a 100755 --- a/tools/boost/asio-wasip3/run.sh +++ b/tools/boost/asio-wasip3/run.sh @@ -5,7 +5,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# Local test launcher for both WASIp3 profiles, tested with Wasmtime 49.0.3. +# Test launcher for local builds and CI using the project-pinned Wasmtime 50.0.1. +# Both single and cooperative thread profiles use the same runtime. # Enabling the runtime's threading feature does not create application threads. # Tests use loopback sockets and localhost resolution. Production applications # should grant only the network capabilities they need. diff --git a/tools/boost/cobalt-wasip3/Jamfile b/tools/boost/cobalt-wasip3/Jamfile index d8ac59c2..4297bc5c 100644 --- a/tools/boost/cobalt-wasip3/Jamfile +++ b/tools/boost/cobalt-wasip3/Jamfile @@ -34,9 +34,11 @@ alias headers : : : : prepared.stamp explicit headers ; # These objects are built separately from boost_cobalt. Its free include flags -# do not reach them, so they must explicitly share the composition fix. +# and source markers do not reach them, so they explicitly share both. obj endpoint : endpoint.cpp : headers /webcpp/cobalt-common//headers + BOOST_COBALT_SOURCE=1 BOOST_COBALT_IO_SOURCE=1 off off ; obj acceptor : acceptor.cpp : headers /webcpp/cobalt-common//headers + BOOST_COBALT_SOURCE=1 BOOST_COBALT_IO_SOURCE=1 off off ; explicit endpoint acceptor ; diff --git a/tools/boost/cobalt-wasip3/acceptor.cpp b/tools/boost/cobalt-wasip3/acceptor.cpp index 78e66c24..78ba21a1 100644 --- a/tools/boost/cobalt-wasip3/acceptor.cpp +++ b/tools/boost/cobalt-wasip3/acceptor.cpp @@ -4,9 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Compile the checked private source copy with the consumer's configuration. -#define BOOST_COBALT_SOURCE 1 -#define BOOST_COBALT_IO_SOURCE 1 +// The object target supplies Boost's source markers and the consumer's configuration. // This wrapper intentionally compiles the verified upstream implementation. // NOLINTNEXTLINE(bugprone-suspicious-include) #include diff --git a/tools/boost/cobalt-wasip3/endpoint.cpp b/tools/boost/cobalt-wasip3/endpoint.cpp index 6df65527..71638bb9 100644 --- a/tools/boost/cobalt-wasip3/endpoint.cpp +++ b/tools/boost/cobalt-wasip3/endpoint.cpp @@ -4,9 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Compile the checked private source copy with the consumer's configuration. -#define BOOST_COBALT_SOURCE 1 -#define BOOST_COBALT_IO_SOURCE 1 +// The object target supplies Boost's source markers and the consumer's configuration. // This wrapper intentionally compiles the verified upstream implementation. // NOLINTNEXTLINE(bugprone-suspicious-include) #include diff --git a/tools/ci/actions/wasmtime/action.yml b/tools/ci/actions/wasmtime/action.yml index d1123826..e6ced315 100644 --- a/tools/ci/actions/wasmtime/action.yml +++ b/tools/ci/actions/wasmtime/action.yml @@ -6,13 +6,13 @@ name: wasmtime description: >- - Installs wasmtime 47.0.3, checked against its SHA-256, and puts it on PATH: it runs the + Installs wasmtime 50.0.1, checked against its SHA-256, and puts it on PATH: it runs the programs of the wasip2 and wasip3 lanes, and serves the HTTP components of the own lanes on those targets and of the tests of the tools. runs: using: composite steps: - - name: Install wasmtime 47.0.3 + - name: Install wasmtime 50.0.1 shell: bash run: bash tools/ci/actions/wasmtime/install.sh diff --git a/tools/ci/actions/wasmtime/install.sh b/tools/ci/actions/wasmtime/install.sh index e5419136..70e23a93 100755 --- a/tools/ci/actions/wasmtime/install.sh +++ b/tools/ci/actions/wasmtime/install.sh @@ -5,35 +5,35 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# The step of tools/ci/actions/wasmtime: wasmtime 47.0.3 in RUNNER_TEMP/wasmtime, put on PATH +# The step of tools/ci/actions/wasmtime: wasmtime 50.0.1 in RUNNER_TEMP/wasmtime, put on PATH # (GITHUB_PATH), for the runner's system and processor (RUNNER_OS, RUNNER_ARCH). It runs the -# programs of the wasip2 and wasip3 lanes, as testing.launcher=wasmtime, and serves the HTTP -# components of the own lanes on those targets and of the tests of the tools, as +# programs of the wasip2 lane directly and wasip3 through its launcher with network access, and +# serves the HTTP components of the own lanes on those targets and of the tests of the tools, as # tools/component/serve.py's `wasmtime serve`. # # Usage: install.sh set -euo pipefail -base=https://github.com/bytecodealliance/wasmtime/releases/download/v47.0.3 +base=https://github.com/bytecodealliance/wasmtime/releases/download/v50.0.1 case "${RUNNER_OS}-${RUNNER_ARCH}" in Linux-X64) - asset=wasmtime-v47.0.3-x86_64-linux.tar.xz - sha256=ca1fc56d1afc40c8782e96c297fd182a0da162f9a8f52a1e7b094e1dd648e178 + asset=wasmtime-v50.0.1-x86_64-linux.tar.xz + sha256=685466455dd42a14774a86c36c8f2e45cbb9bd6d92a850139315df60a75498a5 ;; Linux-ARM64) - asset=wasmtime-v47.0.3-aarch64-linux.tar.xz - sha256=497b518db00ae585f04390758eaa99ad555bee50612dce7d102602778fb46ff0 + asset=wasmtime-v50.0.1-aarch64-linux.tar.xz + sha256=d737e077416d78fbfb0a008229ec27d6a0fd5a4924874b8c38b293c850cf4094 ;; macOS-ARM64) - asset=wasmtime-v47.0.3-aarch64-macos.tar.xz - sha256=c2684249e5d9ef9351942cf2d315982cf201fe0300f05d63bc1527446f0cd37f + asset=wasmtime-v50.0.1-aarch64-macos.tar.xz + sha256=960e5216c7ebd7e9b45e6561d15821b8b801b7d54aee28c7b91921aeb30c65c8 ;; macOS-X64) - asset=wasmtime-v47.0.3-x86_64-macos.tar.xz - sha256=424a50f76a9dcf4d02dab326b2374be1ad404030576ee915866e4af106058b35 + asset=wasmtime-v50.0.1-x86_64-macos.tar.xz + sha256=ea1818fa8cbb51524847ab2ad22197e0051594fdc96cbd0cc2afb65832e11925 ;; *) - printf 'install.sh: no wasmtime 47.0.3 is pinned for %s on %s\n' "${RUNNER_OS}" \ + printf 'install.sh: no wasmtime 50.0.1 is pinned for %s on %s\n' "${RUNNER_OS}" \ "${RUNNER_ARCH}" >&2 exit 1 ;; diff --git a/tools/ci/actions_test.py b/tools/ci/actions_test.py index ed8852f8..679ec337 100755 --- a/tools/ci/actions_test.py +++ b/tools/ci/actions_test.py @@ -20,8 +20,11 @@ when it fails. The wit-bindgen action installs the build of the runner's system and processor, the program alone, in .local/wit-bindgen, where the build looks for it, in place of what was there, and refuses a runner it pins no build -for before it downloads anything; the wasi-wit action installs the wit/deps directory of each -crate, wasip2's and wasip3's, in .local/wasi-wit/p2 and .local/wasi-wit/p3, in place of what was +for before it downloads anything; the wasmtime action installs the pinned build for each runner +in RUNNER_TEMP/wasmtime, replaces an earlier install, exports its directory through GITHUB_PATH, +and refuses an unsupported runner before downloading; the wasi-wit action installs the wit/deps +directory of each crate, wasip2's and wasip3's, in .local/wasi-wit/p2 and .local/wasi-wit/p3, +in place of what was there, and fails, naming the crate, on one that holds no WIT. The emsdk action installs the emsdk repository at its pinned commit, fetched with git, in .local/emsdk, in place of what was there, and fails when another commit is checked out; every archive emsdk installs is downloaded and @@ -72,6 +75,7 @@ DOWNLOAD = CI / 'download.sh' BOOST = CI / 'actions/boost/install.sh' WIT_BINDGEN = CI / 'actions/wit-bindgen/install.sh' +WASMTIME = CI / 'actions/wasmtime/install.sh' WASI_WIT = CI / 'actions/wasi-wit/install.sh' EMSDK = CI / 'actions/emsdk/install.sh' HELPERS = CI / 'helpers.sh' @@ -567,6 +571,78 @@ def test_wit_bindgen_refuses_a_runner_it_pins_no_build_for(scratch: Path) -> Non assert not (scratch / '.local').exists() +WASMTIME_RELEASE = 'https://github.com/bytecodealliance/wasmtime/releases/download/v50.0.1' + +# Official release asset digests, also verified against the four downloaded archives. +WASMTIME_BUILDS = { + ('Linux', 'X64'): ( + 'x86_64-linux', '685466455dd42a14774a86c36c8f2e45cbb9bd6d92a850139315df60a75498a5'), + ('Linux', 'ARM64'): ( + 'aarch64-linux', 'd737e077416d78fbfb0a008229ec27d6a0fd5a4924874b8c38b293c850cf4094'), + ('macOS', 'ARM64'): ( + 'aarch64-macos', '960e5216c7ebd7e9b45e6561d15821b8b801b7d54aee28c7b91921aeb30c65c8'), + ('macOS', 'X64'): ( + 'x86_64-macos', 'ea1818fa8cbb51524847ab2ad22197e0051594fdc96cbd0cc2afb65832e11925'), +} + + +def wasmtime_archive(scratch: Path, build: str) -> Path: + """The release's layout, with an executable identifying the selected build.""" + top = f'wasmtime-v50.0.1-{build}' + tree = scratch / 'archive' + tree.mkdir() + program = tree / 'wasmtime' + program.write_text(f'#!/bin/sh\necho "wasmtime 50.0.1 (stand-in {build})"\n') + program.chmod(0o755) + (tree / 'LICENSE').write_text('licence\n') + archive = scratch / f'{top}.tar.xz' + with tarfile.open(archive, 'w:xz') as tar: + tar.add(tree, arcname=top) + return archive + + +def test_wasmtime_installs_the_pinned_runners_build(scratch: Path) -> None: + for (system, processor), (build, digest) in WASMTIME_BUILDS.items(): + root = scratch / build + root.mkdir() + asset = f'wasmtime-v50.0.1-{build}.tar.xz' + url = f'{WASMTIME_RELEASE}/{asset}' + script = serving_tree(root, 'wasmtime', WASMTIME, + {url: wasmtime_archive(root, build)}) + installed = root / 'temp/wasmtime' + installed.mkdir() + (installed / 'stale').write_text('stale\n') + unrelated = root / 'temp/keep' + unrelated.write_text('keep\n') + github_path = root / 'github-path' + github_path.write_text('/earlier/path\n') + result = run(script, env={'RUNNER_OS': system, 'RUNNER_ARCH': processor, + 'RUNNER_TEMP': str(root / 'temp'), + 'GITHUB_PATH': str(github_path)}) + assert result.returncode == 0, (build, result.returncode, result.stderr) + assert f'wasmtime 50.0.1 (stand-in {build})' in result.stdout, (build, result.stdout) + assert sorted(path.name for path in installed.iterdir()) == ['LICENSE', 'wasmtime'] + assert os.access(installed / 'wasmtime', os.X_OK), build + assert github_path.read_text() == f'/earlier/path\n{installed}\n', build + assert downloads(root) == [(url, digest)], (build, downloads(root)) + assert unrelated.read_text() == 'keep\n', build + assert not (root / 'temp' / asset).exists(), build + + +def test_wasmtime_refuses_a_runner_it_pins_no_build_for(scratch: Path) -> None: + script = serving_tree(scratch, 'wasmtime', WASMTIME, {}) + github_path = scratch / 'github-path' + for system, processor in (('Windows', 'X64'), ('Linux', 'ARM'), ('', '')): + result = run(script, env={'RUNNER_OS': system, 'RUNNER_ARCH': processor, + 'RUNNER_TEMP': str(scratch / 'temp'), + 'GITHUB_PATH': str(github_path)}) + assert result.returncode == 1, (system, processor, result.returncode, result.stderr) + assert f'no wasmtime 50.0.1 is pinned for {system} on {processor}' in result.stderr + assert downloads(scratch) == [] + assert not github_path.exists() + assert not (scratch / 'temp/wasmtime').exists() + + # Each version's crate, the URL it is downloaded from, and its top directory. WASI_CRATES = { 'p2': ('https://static.crates.io/crates/wasip2/wasip2-1.0.4+wasi-0.2.12.crate', @@ -1784,6 +1860,8 @@ def helper(call: str, **variables: str) -> str: test_boost_source_that_fails_leaves_the_tree_and_no_files, test_wit_bindgen_installs_the_runners_build_alone, test_wit_bindgen_refuses_a_runner_it_pins_no_build_for, + test_wasmtime_installs_the_pinned_runners_build, + test_wasmtime_refuses_a_runner_it_pins_no_build_for, test_wasi_wit_installs_each_crates_wit_deps, test_wasi_wit_fails_on_a_crate_without_its_wit, test_emsdk_installs_the_pinned_emsdk_into_local_emsdk, diff --git a/tools/ci/container/Dockerfile b/tools/ci/container/Dockerfile index a41ee035..99b16f9f 100644 --- a/tools/ci/container/Dockerfile +++ b/tools/ci/container/Dockerfile @@ -8,7 +8,8 @@ # 24.04, the release of their runner, pinned by the digest of its image index (docker-library's # repo-info, repos/ubuntu/remote/24.04.md), with the two compilers, the development files of the # OpenSSL 3 that trystero's native backend is built against, as on the runner, and Python, which -# runs the examples. b2, Boost's headers, the superproject and the libraries the CI's actions build +# runs the examples. Git applies the checked Boost and OpenSSL patches; Make and Perl build +# OpenSSL from its pinned source. b2, Boost's headers and the libraries the CI's actions build # are the runner's, mounted at their own paths; the lane runs in it with no network but the # loopback, which the packages are installed before. # @@ -45,5 +46,6 @@ RUN sed -i 's/^Signed-By: .*/&\nSnapshot: yes/' /etc/apt/sources.list.d/ubuntu.s && apt-get -o Acquire::Retries=5 -o APT::Update::Error-Mode=any update \ --snapshot "${SNAPSHOT}" \ && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 install --yes \ - --no-install-recommends --snapshot "${SNAPSHOT}" g++-14 clang-18 libssl-dev python3 \ + --no-install-recommends --snapshot "${SNAPSHOT}" \ + g++-14 clang-18 libssl-dev python3 git make perl \ && rm -rf /var/lib/apt/lists/* diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index ba82337d..8e82b4b6 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -320,9 +320,12 @@ def emscripten_lines() -> str: def wasm_lane(target: str) -> Lane: - return Lane(id=target, name=f'wasm32-{target} (wasi-sdk 34, wasmtime 47.0.3)', + # WASIp3 programs exercise Asio sockets on loopback; Wasmtime needs explicit network + # capabilities even there. Reuse the bounded launcher used by the library's own tests. + launcher = 'tools/boost/asio-wasip3/run.sh' if target == 'wasip3' else 'wasmtime' + return Lane(id=target, name=f'wasm32-{target} (wasi-sdk 34, wasmtime 50.0.1)', os='ubuntu-24.04', target=target, lane=target, toolset=f'clang-{target}', - using=WASI_TOOLSET, options=('testing.launcher=wasmtime',), wasm=True) + using=WASI_TOOLSET, options=(f'testing.launcher={launcher}',), wasm=True) # Every lane the CI knows, by target. GCC and Clang on Linux build with libstdc++, the system's diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index fd0ccada..c84e5e6d 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -94,7 +94,8 @@ def test_plan_of_one_library(root): 'msvc-14.3', 'msvc-14.5'], lanes assert by_id['apple-clang']['detect'] == 'clang++', by_id['apple-clang'] assert by_id['wasip2']['toolset'] == 'clang-wasip2', by_id['wasip2'] - assert by_id['wasip3']['options'] == ['testing.launcher=wasmtime'], by_id['wasip3'] + assert by_id['wasip3']['options'] == [ + 'testing.launcher=tools/boost/asio-wasip3/run.sh'], by_id['wasip3'] assert by_id['wasip3']['wasm'] and not by_id['gcc-14']['wasm'], lanes assert by_id['msvc-14.5']['os'] == 'windows-2025', by_id['msvc-14.5'] assert by_id['clang-22']['os'] == 'ubuntu-26.04', by_id['clang-22'] @@ -518,6 +519,44 @@ def test_an_own_lanes_command(root): assert (lane.id, lane.os) == (lane_id, 'ubuntu-24.04'), lane +def test_a_wasip3_lane_can_bind_a_loopback_socket(root): + # Run the planned lane, including its launcher: Wasmtime refuses even a loopback bind + # without an explicit network grant, which a successful compile cannot establish. + harness.add_library(root, 'network', + 'import webcpp ;\nwebcpp.targets wasip3 ;\n' + 'webcpp.run loopback : loopback.cpp ;\n', { + 'loopback.cpp': r'''#include +#include +#include + +int main() { + int const descriptor = socket(AF_INET, SOCK_STREAM, 0); + if (descriptor < 0) return 1; + sockaddr_in address{}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + int const result = bind(descriptor, reinterpret_cast(&address), sizeof(address)); + close(descriptor); + return result == 0 ? 0 : 1; +} +'''}) + (root / 'libs/network/example').mkdir() + (root / 'libs/network/example/Jamfile').write_text( + 'import webcpp ;\nwebcpp.targets wasip3 ;\n') + boost_only(root) + (root / '.local/wasi-sdk').symlink_to((matrix.ROOT / '.local/wasi-sdk').resolve()) + entries = planned(root, '--library', 'network') + assert len(entries) == 1 and entries[0]['id'] == 'wasip3', entries + result = run(root, 'lane', json.dumps(entries[0])) + assert result.returncode == 0, (result.stdout[-4000:], result.stderr) + # --out-xml makes b2 return success on a test failure: read the verdict as CI does. + result = subprocess.run([ + sys.executable, str(root / 'tools/report/report.py'), '--lane', + f'wasip3={root / "bin/ci/wasip3.xml"}', '--out', str(root / 'report')], + capture_output=True, text=True, check=False) + assert result.returncode == 0, (result.stdout, result.stderr) + + def test_an_own_lane_on_a_target_writes_its_xml_and_the_report_merges_it(root): jamfile = root / 'libs/demo/test/Jamfile' jamfile.write_text(jamfile.read_text() + 'webcpp.lane served : pass : wasip2 ;\n') @@ -906,7 +945,7 @@ def test_the_report_names_a_planned_lane_that_wrote_nothing(root): report = run(root, 'report', '--plan', json.dumps({'include': entries}), '--lanes', str(lanes), '--out', str(root / 'report')) assert report.returncode == 2, (report.returncode, report.stdout, report.stderr) - assert 'the lane wasip3 (wasm32-wasip3 (wasi-sdk 34, wasmtime 47.0.3)) wrote no XML' in ( + assert 'the lane wasip3 (wasm32-wasip3 (wasi-sdk 34, wasmtime 50.0.1)) wrote no XML' in ( report.stderr), report.stderr # The lanes that did write are still reported. assert 'data-lane="wasip2"' in (root / 'report/index.html').read_text() @@ -1191,8 +1230,9 @@ def test_a_container_lane_runs_b2_with_no_network(root): assert re.search(r'install[^&]*--snapshot "\$\{SNAPSHOT\}" ca-certificates', code), code digest = hashlib.sha256(dockerfile.encode()).hexdigest() assert matrix.CONTAINER_IMAGE == f'webcpp-lane:{digest[:16]}', matrix.CONTAINER_IMAGE - for package in ('g++-14', 'clang-18', 'libssl-dev', 'python3'): - assert f' {package}' in dockerfile, (package, dockerfile) + for package in ('g++-14', 'clang-18', 'libssl-dev', 'python3', 'git', 'make', 'perl'): + assert re.search(r'install\b[^&]*\s' + re.escape(package) + r'(?=\s|$)', code), ( + package, code) entry = host_lane(root) entry['container'] = True # A lane of a library that needs external libraries: the build requires them, and is given @@ -1302,6 +1342,7 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): test_own_lanes_of_every_library_and_of_one, test_own_lanes_on_targets, test_an_own_lanes_command, + test_a_wasip3_lane_can_bind_a_loopback_socket, test_a_lane_is_named_by_the_compiler_version, test_abbreviated_paths_keep_the_lane_name, test_register_writes_the_lanes_toolsets_in_order, diff --git a/tools/component/serve.py b/tools/component/serve.py index 9c492883..80040dbc 100755 --- a/tools/component/serve.py +++ b/tools/component/serve.py @@ -71,7 +71,7 @@ from dataclasses import dataclass, field from pathlib import Path -# The headers wasmtime 47.0.3 adds to a response, whatever the component sets, measured with +# The headers wasmtime 50.0.1 adds to a response, whatever the component sets, measured with # `wasmtime serve` on a component whose answers carry content-type and x-method only: date on # every response, and transfer-encoding: chunked on every response that has a body (all but the # answer to HEAD). @@ -80,7 +80,7 @@ # What a transcript says the server is: one host and port on every machine. SHOWN_ORIGIN = 'http://localhost:8080' -# The line in which wasmtime 47.0.3 says it listens, on its standard error: +# The line in which wasmtime 50.0.1 says it listens, on its standard error: # `Serving HTTP on http://127.0.0.1:53187/`. SERVING = re.compile(r'Serving HTTP on http://([0-9.]+):([0-9]+)/') @@ -375,7 +375,7 @@ def find_wasmtime(given: str | None, program: str) -> str: found = shutil.which('wasmtime') if found is None: raise UsageError(f'{what} no -sWASMTIME= was given, and there is none on PATH. ' - 'Install wasmtime 47.0.3 on PATH, or give its path with ' + 'Install wasmtime 50.0.1 on PATH, or give its path with ' '-sWASMTIME=.') return found diff --git a/tools/component/serve_test.py b/tools/component/serve_test.py index 682b5a04..fe7a5459 100755 --- a/tools/component/serve_test.py +++ b/tools/component/serve_test.py @@ -6,7 +6,7 @@ # https://www.boost.org/LICENSE_1_0.txt) """Checks tools/component/serve.py with a stand-in for wasmtime: a small Python program, given as ---wasmtime, that serves fixed answers on the address it is given and says so as wasmtime 47.0.3 +--wasmtime, that serves fixed answers on the address it is given and says so as wasmtime 50.0.1 does, so that the runner is checked without a component. The stand-in reads what to do from the file given as the component: when to say it serves, whether to answer, to ignore SIGTERM or to start a child in its process group, and where to record its process, its port and the requests it got, with @@ -377,7 +377,7 @@ def test_a_server_that_never_serves_exits_2(scratch: Path) -> None: result = subprocess.run(arguments, capture_output=True, text=True, check=False, timeout=60, env={**os.environ, 'PATH': str(empty)}) assert result.returncode == 2, outcome(result) - assert ('no -sWASMTIME= was given, and there is none on PATH. Install wasmtime 47.0.3 ' + assert ('no -sWASMTIME= was given, and there is none on PATH. Install wasmtime 50.0.1 ' 'on PATH, or give its path with -sWASMTIME=.') in result.stderr, outcome(result) (empty / 'wasmtime').symlink_to(run.stand_in) result = subprocess.run(arguments, capture_output=True, text=True, check=False, timeout=60, diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index b58c5297..b7ac85b5 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -98,8 +98,10 @@ Before selecting each aggregate command, its compile-only headers-alone targets are built through B2. This materializes generated dependencies, including OpenSSL configuration and CA -data, on a clean checkout. The corresponding exception-free units are prepared too. No test -program is executed by this preparation. +data, on a clean checkout. The corresponding exception-free units are prepared too. Selected +program commands may also need checked Boost overlays on a target no aggregate uses; their +include paths select the overlays' B2 preparation targets before analysis. Neither preparation +executes a test program. b2 runs with root/.local/user-config.jam when it exists, else with $WEBCPP_USER_CONFIG when it is set, else with its own search; and without CPATH, CPLUS_INCLUDE_PATH and C_INCLUDE_PATH, @@ -136,6 +138,13 @@ 'emscripten': ['toolset=emscripten'], } +# Checked overlays owned by tools/boost: each include directory's B2 preparation target. +# A program can need one on a target that the library's native aggregate never prepares. +BOOST_OVERLAYS = { + f'bin/boost-{name}/include': f'tools/boost/{name}//prepared.stamp' + for name in ('asio-wasip3', 'cobalt-common', 'cobalt-wasip3', 'cobalt-ssl') +} + # The property of the request that builds a program without exceptions as a user asks b2 for one, # and what the native request builds besides the headers-alone translation unit of each library # whose aggregate builds natively: the handler such a program links. @@ -576,6 +585,28 @@ def of_the_tree(root: str, source: str) -> bool: Units = dict[str, dict[str, list[list[str]]]] +def prepare_boost_overlays(root: str, target: str, commands: list[list[str]]) -> None: + """Build the checked Boost overlays selected commands include, without compiling programs.""" + includes: set[Path] = set() + for words in commands: + for index, word in enumerate(words): + if word in ('-I', '-isystem') and index + 1 < len(words): + directory = words[index + 1] + elif word.startswith('-I'): + directory = word[2:] + else: + continue + includes.add(Path(root, directory).resolve()) + requested = sorted(preparation for directory, preparation in BOOST_OVERLAYS.items() + if Path(root, directory).resolve() in includes) + if not requested: + return + command, completed = run_b2(root, ['-d0', *TARGETS[target], *requested]) + if completed.returncode != 0: + raise Failure(f'{completed.stdout}{" ".join(command)} exited {completed.returncode} ' + 'while preparing checked Boost overlays') + + def read(root: str, target: str, commands: list[list[str]], entries: list[dict[str, object]], seen: set[tuple[str, ...]], earlier: set[str], wasi_clang: str | None) -> tuple[Units, set[str]]: @@ -587,6 +618,7 @@ def read(root: str, target: str, commands: list[list[str]], entries: list[dict[s commands compile.""" units: Units = {} sources: set[str] = set() + selected: list[list[str]] = [] for words in commands: source = words[-1] unit = ALONE.match(source) @@ -599,8 +631,10 @@ def read(root: str, target: str, commands: list[list[str]], entries: list[dict[s if source in earlier or key in seen: continue seen.add(key) + selected.append(words) entries.append({'directory': root, 'file': os.path.join(root, source), 'arguments': analysed(target, source, words, wasi_clang)}) + prepare_boost_overlays(root, target, selected) return units, sources @@ -698,6 +732,7 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni without: Units = {} kept: set[str] = set() compiled: set[str] = set() + selected: list[list[str]] = [] for words in compiles(dry_run(root, [*TARGETS[target], WITHOUT_EXCEPTIONS, *PROGRAMS, *lanes, *handler, *requested])): source = words[-1] @@ -715,8 +750,10 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni if key in seen: continue seen.add(key) + selected.append(words) entries.append({'directory': root, 'file': os.path.join(root, source), 'arguments': analysed(target, source, words, wasi_clang)}) + prepare_boost_overlays(root, target, selected) twinned.programs |= kept - compiled for library, theirs in aggregates.items(): index = next(index for index, aggregate in enumerate(theirs) diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 9607291f..ae841760 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -779,6 +779,39 @@ def test_a_compiled_boost_library_s_sources_are_not_analysed(root): expect_clean(lint(root)) +def test_clang_tidy_prepares_cobalt_wrappers_on_a_clean_tree(root): + # The library's aggregate is native, but a WASIp3-only program also compiles + # webcpp's Cobalt wrappers. Their checked source overlay must exist before + # clang-tidy reads them, even when no public header needs that overlay. + prepare(root) + append(root, 'libs/demo/test/Jamfile', + 'webcpp.run cobalt : cobalt.cpp : /webcpp//boost_cobalt : wasip3 ;\n') + write(root, 'libs/demo/test/cobalt.cpp', CPP + '\n' + 'int main() {\n' + ' return 1;\n' + '}\n') + overlay = root / 'bin/boost-cobalt-wasip3/include/libs/cobalt/src/io' + assert not overlay.exists(), overlay + completed = compile_database(root) + assert completed.returncode == 0, completed.stdout[-6000:] + entries = json.loads((root / 'compile database/compile_commands.json').read_text()) + wrappers = [entry for entry in entries + if '/tools/boost/cobalt-wasip3/' in entry['file']] + assert len(wrappers) == 4, wrappers + for entry in wrappers: + for marker in ('-DBOOST_COBALT_SOURCE=1', '-DBOOST_COBALT_IO_SOURCE=1'): + assert marker in entry['arguments'], entry + expect_clean(lint(root)) + for name in ('acceptor', 'endpoint'): + assert (overlay / f'{name}.cpp').is_file(), name + result = harness.run_b2(root, '-a', 'toolset=clang-wasip3', + 'tools/boost/cobalt-wasip3//acceptor', + 'tools/boost/cobalt-wasip3//endpoint') + harness.expect(result, True) + # Preparing lint inputs must not execute the deliberately failing program. + assert not list((root / 'bin/libs/demo/test').rglob('cobalt.run')) + + def test_clang_tidy_refuses_a_throw_on_each_target_without_exceptions(root): prepare(root) add_browser_demo(root) @@ -1409,8 +1442,10 @@ def test_world_rule(root): def test_bare_throw(root): prepare(root) # A library header raises through boost::throw_exception alone. A throw in a template that - # nothing instantiates, which no build compiles, fails, and so does a rethrow inside the - # region a build with exceptions compiles; what only reads as a throw does not: the + # nothing instantiates fails, as does a rethrow. Both sit behind the exceptions guard: + # Clang 18 diagnoses an unguarded nondependent throw even without instantiating its template. + # The separate clang-tidy case proves an unguarded throw fails compilation too. + # What only reads as a throw does not: the # function, a string, a comment, a Doc Comment, a raw string, noexcept(false), a name # that holds the word, and JavaScript's throw in an EM_JS body, after which C++ is read # again. A test or an example may throw: catches.cpp does. @@ -1443,6 +1478,8 @@ def test_bare_throw(root): '\n' 'namespace webcpp::demo {\n' '\n' + '#ifndef WEBCPP_DEMO_NO_EXCEPTIONS\n' + '\n' '/** Returns the count it is given, refusing a negative one.\n' '\n' ' @tparam Count A signed type.\n' @@ -1457,8 +1494,6 @@ def test_bare_throw(root): ' return count;\n' '}\n' '\n' - '#ifndef WEBCPP_DEMO_NO_EXCEPTIONS\n' - '\n' '/** Runs the work it is given, and lets what it throws go on.\n' '\n' ' @tparam Work A callable.\n' @@ -2096,6 +2131,7 @@ def test_third_party_code_is_never_read(root): test_clang_tidy_reads_a_program_of_javascript_exceptions, test_a_dependency_s_warnings_are_not_ours, test_a_compiled_boost_library_s_sources_are_not_analysed, + test_clang_tidy_prepares_cobalt_wrappers_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, test_a_library_webcpp_does_not_build_missing_is_named, diff --git a/tools/openssl/build.py b/tools/openssl/build.py index 75b7622d..cfd632c7 100644 --- a/tools/openssl/build.py +++ b/tools/openssl/build.py @@ -49,11 +49,48 @@ def c_driver(command: str) -> Path: driver = Path(found) name = driver.name.replace('clang++', 'clang').replace('g++', 'gcc') candidate = driver.with_name(name) + if not candidate.is_file() and driver.is_symlink(): + # CI and package managers may expose only a C++ symlink. Follow it to + # its installation, preserving a wrapper's C sibling when one exists. + driver = driver.resolve() + name = driver.name.replace('clang++', 'clang').replace('g++', 'gcc') + candidate = driver.with_name(name) if not candidate.is_file(): raise RuntimeError(f'configured compiler has no C driver: {candidate}') return candidate.absolute() +def windows_target(compiler: Path, flags: list[str], scratch: Path, env: dict[str, str]) -> str: + """Select upstream's architecture from the compiler B2 actually configured.""" + probe = scratch / 'architecture.c' + probe.write_text('#if defined(_MSC_VER) && defined(_WIN32)\n' + '#if defined(_M_ARM64)\nWEBCPP_OPENSSL_ARM64\n' + '#elif defined(_M_X64)\nWEBCPP_OPENSSL_X64\n' + '#elif defined(_M_IX86)\nWEBCPP_OPENSSL_X86\n' + '#endif\n#endif\n') + result = subprocess.check_output([str(compiler), *flags, '/nologo', '/EP', '/TC', str(probe)], + env=env, text=True) + for marker, target in (('WEBCPP_OPENSSL_ARM64', 'VC-WIN64-ARM'), + ('WEBCPP_OPENSSL_X64', 'VC-WIN64A'), + ('WEBCPP_OPENSSL_X86', 'VC-WIN32')): + if marker in result.split(): + return target + raise RuntimeError('OpenSSL recipe requires an x86, x64 or ARM64 MSVC target') + + +def windows_perl(env: dict[str, str]) -> str: + """Find native Perl even when a Git Bash or MSYS Perl precedes it on PATH.""" + for directory in env.get('PATH', '').split(os.pathsep): + perl = shutil.which('perl', path=directory) + if not perl: + continue + platform = subprocess.check_output([perl, '-e', 'print $^O'], env=env, text=True) + if platform.strip() == 'MSWin32': + return perl + raise RuntimeError('MSVC OpenSSL requires native Windows Perl (for example Strawberry Perl) ' + 'on PATH; a Git Bash or MSYS Perl cannot generate nmake files') + + def main() -> None: arguments = sys.argv[1:] if len(arguments) == 1: @@ -61,28 +98,51 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) - parser.add_argument('--platform', choices=('darwin', 'linux', 'wasi'), required=True) + parser.add_argument('--platform', choices=('darwin', 'linux', 'wasi', 'windows'), required=True) parser.add_argument('--threading', choices=('single', 'multi'), required=True) parser.add_argument('--cc', required=True) parser.add_argument('--ar', default='') + parser.add_argument('--variant', default='release') parser.add_argument('flags', nargs=argparse.REMAINDER) args = parser.parse_args(arguments) source, output = args.source.resolve(), args.output.resolve() output.mkdir(parents=True, exist_ok=True) pin = json.loads((HERE / 'pin.json').read_text()) check_checkout(source, pin) + # Verify the source before probing or invoking any configured build tool. + # A broken toolchain must never mask a corrupted source archive. + temporary_root = Path(tempfile.gettempdir()) + if any(character.isspace() for character in str(temporary_root)): + if sys.platform == 'win32': + raise RuntimeError('OpenSSL needs a writable TEMP directory without spaces') + temporary_root = Path('/tmp') + with tempfile.TemporaryDirectory(prefix='webcpp-openssl-', dir=temporary_root) as temporary: + scratch = Path(temporary) + stage_source(source, scratch / 'source', pin) + build_source(args, output, pin, scratch) + + +def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Path) -> None: + """Build verified sources, then publish archives and headers to B2 together.""" compiler = c_driver(args.cc) flags = args.flags[1:] if args.flags[:1] == ['--'] else args.flags - flags += ['-ffunction-sections', '-fdata-sections'] + windows = args.platform == 'windows' + flags += ['/Gy', '/Gw'] if windows else ['-ffunction-sections', '-fdata-sections'] archiver = args.ar or str(compiler.with_name('llvm-ar') if args.platform == 'wasi' else 'ar') env = os.environ.copy() for variable in ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH', 'CPPFLAGS', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS', 'LD_LIBRARY_PATH', - 'OPENSSL_CONF', 'OPENSSL_MODULES', 'CROSS_COMPILE'): + 'OPENSSL_CONF', 'OPENSSL_MODULES', 'CROSS_COMPILE', 'CL', '_CL_'): env.pop(variable, None) env.setdefault('SOURCE_DATE_EPOCH', str(pin['source_date_epoch'])) - options = ['--openssldir=/etc/ssl', 'no-shared', 'no-tests', 'no-apps', 'no-docs', 'no-module', + options = ['no-shared', 'no-tests', 'no-apps', 'no-docs', 'no-module', '--libdir=lib', 'threads' if args.threading == 'multi' else 'no-threads'] + # MSVC's /MDd and /MTd define _DEBUG themselves. Upstream --debug would + # force it even when the user explicitly selects runtime-debugging=off. + if args.variant == 'debug' and not windows: + options += ['--debug'] + if not windows: + options += ['--openssldir=/etc/ssl'] if args.platform == 'wasi': if '--target=wasm32-wasip3' not in flags: raise RuntimeError('WASIp3 OpenSSL requires --target=wasm32-wasip3 ' @@ -102,6 +162,13 @@ def main() -> None: options += ['--with-rand-seed=getrandom', 'no-asm', 'no-dso', 'no-ui-console', 'no-afalgeng', 'no-quic', '-DOPENSSL_NO_UNIX_SOCK'] target = ['--config=' + str(HERE / 'wasip3.conf'), 'webcpp-wasip3'] + elif windows: + native = windows_target(compiler, flags, scratch, env) + target = ['--config=' + str(HERE / 'msvc.conf'), native + '-webcpp'] + # A deterministic portable C profile needs only the MSVC toolchain, + # including ml64 for upstream's x64 uplink shim, and no separate NASM. + options += ['no-asm'] + archiver = args.ar or 'link' else: triple = subprocess.check_output([str(compiler), *flags, '-dumpmachine'], text=True).strip() @@ -124,43 +191,66 @@ def main() -> None: raise RuntimeError(f'OpenSSL recipe has no reviewed native target for {triple}') target = [supported[args.platform, arch]] # Inherit compiler options from B2 but not webcpp's C++ warning policy. - env.update(CC=shlex.quote(str(compiler)), AR=shlex.quote(archiver), - RANLIB=shlex.quote(archiver) + ' s', CFLAGS=shlex.join(flags)) + if windows: + # The upstream nmake template quotes tool paths itself. + env.update(CC=str(compiler), AR=archiver, CFLAGS=subprocess.list2cmdline(flags)) + env['ARFLAGS'] = '/lib /nologo' + else: + env.update(CC=shlex.quote(str(compiler)), AR=shlex.quote(archiver), + CFLAGS=shlex.join(flags)) + env['RANLIB'] = shlex.quote(archiver) + ' s' record = {'pin': pin, 'platform': args.platform, 'threading': args.threading, + 'variant': args.variant, 'compiler': str(compiler), 'archiver': archiver, 'flags': flags, 'configure': target + options} started = time.monotonic() - # Do not use a potentially space-containing TMPDIR for upstream make. - temporary_root = Path(tempfile.gettempdir()) - if any(character.isspace() for character in str(temporary_root)): - temporary_root = Path('/tmp') - with tempfile.TemporaryDirectory(prefix='webcpp-openssl-', dir=temporary_root) as temporary: - scratch = Path(temporary) - # Configure canonicalizes source symlinks. A real, unmodified copy is - # needed to keep spaces in the user's checkout out of its Makefiles. - stage_source(source, scratch / 'source', pin) - build = scratch / 'build' - build.mkdir() - install = scratch / 'install' - # External config is reached through the same space-free staging area. - (scratch / 'wasip3.conf').symlink_to(HERE / 'wasip3.conf') - actual_target = (['--config=' + str(scratch / 'wasip3.conf'), 'webcpp-wasip3'] - if args.platform == 'wasi' else target) - run(['perl', str(scratch / 'source/Configure'), *actual_target, *options, - '--prefix=' + str(install)], cwd=build, env=env, log=output / 'configure.log') - run(['make', '-j' + str(min(8, os.cpu_count() or 1)), 'build_libs'], - cwd=build, env=env, log=output / 'build.log') - run(['make', 'install_dev'], cwd=build, env=env, log=output / 'install.log') - # Copy headers before archives: consumers cannot compile against a - # different configuration while the new archives are being produced. - shutil.copytree(install / 'include', output / 'include', dirs_exist_ok=True) - for name in ('libssl.a', 'libcrypto.a'): - staged = output / (name + '.new') - shutil.copyfile(install / 'lib' / name, staged) - staged.replace(output / name) + build = scratch / 'build' + build.mkdir() + install = scratch / 'install' + actual_target = target + if args.platform == 'wasi': + # Copying also works when symlink creation needs Windows privileges. + shutil.copyfile(HERE / 'wasip3.conf', scratch / 'wasip3.conf') + actual_target = ['--config=' + str(scratch / 'wasip3.conf'), 'webcpp-wasip3'] + elif windows: + shutil.copyfile(HERE / 'msvc.conf', scratch / 'msvc.conf') + actual_target = ['--config=' + str(scratch / 'msvc.conf'), target[-1]] + perl = windows_perl(env) if windows else 'perl' + run([perl, str(scratch / 'source/Configure'), *actual_target, *options, + '--prefix=' + str(install)], cwd=build, env=env, log=output / 'configure.log') + make = ['nmake', '/nologo'] if windows else ['make'] + jobs = [] if windows else ['-j' + str(min(8, os.cpu_count() or 1))] + run([*make, *jobs, 'build_libs'], cwd=build, env=env, log=output / 'build.log') + if windows: + # Upstream install_dev requires an external PDB even with B2's /Z7 + # embedded symbols or debug-symbols=off. Stage exactly its public and + # generated headers and archives, without the unrelated exporters. + headers = install / 'include/openssl' + headers.mkdir(parents=True) + for directory in (scratch / 'source/include/openssl', build / 'include/openssl'): + for header in directory.glob('*.h'): + if not header.name.startswith('__DECC_'): + shutil.copyfile(header, headers / header.name) + shutil.copyfile(scratch / 'source/ms/applink.c', headers / 'applink.c') + (install / 'lib').mkdir() + for name in ('libssl.lib', 'libcrypto.lib'): + shutil.copyfile(build / name, install / 'lib' / name) + symbols = build / 'ossl_static.pdb' + if symbols.is_file(): + shutil.copyfile(symbols, output / symbols.name) + else: + run([*make, 'install_dev'], cwd=build, env=env, log=output / 'install.log') + # Copy headers before archives: consumers cannot compile against a + # different configuration while the new archives are being produced. + shutil.copytree(install / 'include', output / 'include', dirs_exist_ok=True) + names = ('libssl.lib', 'libcrypto.lib') if windows else ('libssl.a', 'libcrypto.a') + for name in names: + staged = output / (name + '.new') + shutil.copyfile(install / 'lib' / name, staged) + staged.replace(output / name) record['seconds'] = time.monotonic() - started record['sha256'] = {name: hashlib.sha256((output / name).read_bytes()).hexdigest() - for name in ('libssl.a', 'libcrypto.a')} + for name in names} (output / 'build.json').write_text(json.dumps(record, indent=2) + '\n') print(f'OpenSSL {pin["version"]}: {args.platform}/{args.threading} built from source ' f'in {record["seconds"]:.1f}s', flush=True) diff --git a/tools/openssl/build_test.py b/tools/openssl/build_test.py new file mode 100644 index 00000000..07edfd35 --- /dev/null +++ b/tools/openssl/build_test.py @@ -0,0 +1,162 @@ +#!/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) +"""Check build orchestration at the unavailable native Windows tool boundary.""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import build +from source import inventory_digest + + +class WindowsBuildTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix='openssl windows ') + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.source = self.root / 'source' + self.source.mkdir() + data = b'# source fixture\n' + (self.source / 'Configure').write_bytes(data) + (self.source / 'ms').mkdir() + (self.source / 'ms/applink.c').write_bytes(data) + (self.root / 'msvc.conf').write_text('# configuration fixture\n') + self.pin = {'version': 'fixture', 'source_date_epoch': 1700000000, + 'omitted_submodules': {}, 'executable_files': [], + 'source_sha256': inventory_digest([ + (name, '100644', hashlib.sha256(data).hexdigest()) + for name in ('Configure', 'ms/applink.c')])} + (self.root / 'pin.json').write_text(json.dumps(self.pin)) + self.compiler = self.root / 'Visual Studio/cl.exe' + self.compiler.parent.mkdir() + self.compiler.write_bytes(b'compiler boundary fixture\n') + self.compiler.chmod(0o755) + + def test_windows_build_installs_static_libraries_and_matching_headers(self) -> None: + for arch, target in (('x86', 'VC-WIN32'), ('x64', 'VC-WIN64A'), + ('arm64', 'VC-WIN64-ARM')): + with self.subTest(arch=arch): + commands = [] + environments = [] + output = self.root / arch + + def command(command: list[str], *, cwd: Path, env: dict, log: Path) -> None: + commands.append(command) + environments.append(env) + log.write_text('completed\n') + if command[-1] == 'build_libs': + (cwd / 'include/openssl').mkdir(parents=True) + (cwd / 'include/openssl/configuration.h').write_text(arch) + (cwd / 'libssl.lib').write_bytes(b'ssl-' + arch.encode()) + (cwd / 'libcrypto.lib').write_bytes(b'crypto-' + arch.encode()) + + args = ['build.py', '--source', str(self.source), '--output', str(output), + '--platform', 'windows', '--threading', 'multi', '--cc', str(self.compiler), + '--ar', 'link', '--variant', 'debug', '--', '/MDd', '/Od', '/Z7', '/GL'] + with patch.object(build, 'HERE', self.root), patch.object(sys, 'argv', args), \ + patch.object(build, 'run', side_effect=command), \ + patch.object(build, 'windows_target', return_value=target), \ + patch.object(build, 'windows_perl', return_value='native-perl.exe'): + build.main() + self.assertEqual(commands[0][0], 'native-perl.exe') + self.assertIn(target + '-webcpp', commands[0]) + self.assertNotIn('--debug', commands[0]) + self.assertIn('no-shared', commands[0]) + self.assertIn('no-asm', commands[0]) + self.assertEqual(commands[1], ['nmake', '/nologo', 'build_libs']) + self.assertEqual(len(commands), 2) + self.assertEqual((output / 'libssl.lib').read_bytes(), b'ssl-' + arch.encode()) + self.assertEqual((output / 'include/openssl/configuration.h').read_text(), arch) + self.assertEqual((output / 'include/openssl/applink.c').read_bytes(), + b'# source fixture\n') + self.assertFalse((output / 'ossl_static.pdb').exists()) + record = json.loads((output / 'build.json').read_text()) + self.assertEqual(set(record['sha256']), {'libssl.lib', 'libcrypto.lib'}) + self.assertEqual(record['flags'], ['/MDd', '/Od', '/Z7', '/GL', '/Gy', '/Gw']) + self.assertEqual(environments[0]['CFLAGS'], '/MDd /Od /Z7 /GL /Gy /Gw') + self.assertEqual(environments[0]['CC'], str(self.compiler.absolute())) + self.assertEqual(environments[0]['AR'], 'link') + self.assertEqual(environments[0]['ARFLAGS'], '/lib /nologo') + self.assertNotIn('CL', environments[0]) + self.assertNotIn('_CL_', environments[0]) + + def test_windows_target_uses_the_configured_compilers_architecture(self) -> None: + for output, target in (('WEBCPP_OPENSSL_X86', 'VC-WIN32'), + ('WEBCPP_OPENSSL_X64', 'VC-WIN64A'), + ('WEBCPP_OPENSSL_ARM64', 'VC-WIN64-ARM')): + with patch.object(build.subprocess, 'check_output', return_value=output) as compiler: + self.assertEqual(build.windows_target(Path('cl.exe'), ['/MDd'], self.root, + os.environ.copy()), target) + command = compiler.call_args.args[0] + self.assertEqual(command[:4], ['cl.exe', '/MDd', '/nologo', '/EP']) + self.assertTrue(Path(command[-1]).is_file()) + with patch.object(build.subprocess, 'check_output', return_value='not MSVC'): + with self.assertRaisesRegex(RuntimeError, 'MSVC target'): + build.windows_target(Path('cl.exe'), [], self.root, os.environ.copy()) + + def test_native_perl_is_selected_after_git_bash_perl(self) -> None: + env = {'PATH': os.pathsep.join(('git-bash', 'strawberry'))} + with patch.object(build.shutil, 'which', side_effect=['git-perl', 'native-perl']), \ + patch.object(build.subprocess, 'check_output', + side_effect=['msys', 'MSWin32']): + self.assertEqual(build.windows_perl(env), 'native-perl') + with patch.object(build.shutil, 'which', return_value='git-perl'), \ + patch.object(build.subprocess, 'check_output', return_value='msys'): + with self.assertRaisesRegex(RuntimeError, 'native Windows Perl'): + build.windows_perl(env) + + def test_msvc_profile_keeps_upstream_windows_features_and_b2_flags(self) -> None: + root = Path(__file__).resolve().parents[2] + source = root / 'third_party/libs/openssl/Configure' + profile = root / 'tools/openssl/msvc.conf' + for name in ('VC-WIN32', 'VC-WIN64A', 'VC-WIN64-ARM'): + directory = self.root / name + directory.mkdir() + probe = directory / 'probe.conf' + # Resolve the actual Windows inheritance with upstream Configure. + # Only rendering uses the host's Perl platform, since nmake and + # native Windows Perl cannot run on the Unix tool-test runners. + probe.write_text('my %targets = ("VC-probe" => {\n' + f' inherit_from => ["{name}-webcpp"],\n' + + (' build_scheme => ["unified", "unix"],\n' + ' build_file => "Makefile", perl_platform => "Unix"\n' + if sys.platform != 'win32' else '') + '});\n') + flags = '/MDd /Z7 /Od /DWEBCPP_TEST_OPENSSL_CONFIGURATION=17' + perl = build.windows_perl(os.environ.copy()) if sys.platform == 'win32' else 'perl' + result = subprocess.run( + [perl, str(source), '--config=' + str(profile), '--config=' + str(probe), + 'VC-probe', 'no-asm', 'no-shared', 'no-tests', 'no-apps', 'no-docs', + 'no-module', '--prefix=' + str(directory / 'install')], cwd=directory, + env={**os.environ, 'CC': 'cl.exe', 'CFLAGS': flags}, + capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + data = subprocess.check_output( + [perl, '-I.', '-Mconfigdata', '-MJSON::PP', '-e', + 'print encode_json({flags => $configdata::config{CFLAGS}, ' + 'lib_flags => $configdata::target{lib_cflags}, ' + 'defines => $configdata::target{defines}, ' + 'threads => $configdata::target{thread_scheme}});'], + cwd=directory, text=True, timeout=30) + configuration = json.loads(data) + self.assertEqual(configuration['flags'], [flags]) + self.assertNotIn('/MT', configuration['lib_flags']) + self.assertNotIn('/Zi', configuration['lib_flags']) + self.assertIn('OPENSSL_SYS_WIN32', configuration['defines']) + self.assertNotIn('_DEBUG', configuration['defines']) + self.assertEqual(configuration['threads'], 'winthreads') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/openssl/msvc.conf b/tools/openssl/msvc.conf new file mode 100644 index 00000000..edcc7499 --- /dev/null +++ b/tools/openssl/msvc.conf @@ -0,0 +1,22 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Keep B2's runtime and debug configuration. Upstream otherwise forces /MT +# and /Zi for static objects, even when their consumer selected /MDd or /Z7. +my %targets = ( + "VC-WIN32-webcpp" => { + inherit_from => [ "VC-WIN32" ], + lib_cflags => "/Zl /Fdossl_static.pdb", + }, + "VC-WIN64A-webcpp" => { + inherit_from => [ "VC-WIN64A" ], + lib_cflags => "/Zl /Fdossl_static.pdb", + }, + "VC-WIN64-ARM-webcpp" => { + inherit_from => [ "VC-WIN64-ARM" ], + lib_cflags => "/Zl /Fdossl_static.pdb", + }, +); diff --git a/tools/openssl/pin.json b/tools/openssl/pin.json index 7428e9b5..e62a97b6 100644 --- a/tools/openssl/pin.json +++ b/tools/openssl/pin.json @@ -16,5 +16,165 @@ "tlsfuzzer": "61f45d9701294fd87ef92d2a7e3dfb076653a562", "tlslite-ng": "77ef321dde1a9e6bcf94d73c80f8789a770d8031", "wycheproof": "2196000605e45d91097147c9c71f26b72af58003" - } + }, + "executable_files": [ + "Configure", + "config", + "crypto/aes/asm/aes-586.pl", + "crypto/aes/asm/aes-sparcv9.pl", + "crypto/aes/asm/aes-x86_64.pl", + "crypto/aes/asm/aesp8-ppc.pl", + "crypto/aes/asm/aesv8-armx.pl", + "crypto/aes/asm/vpaes-armv8.pl", + "crypto/arm64cpuid.pl", + "crypto/bn/asm/armv8-mont.pl", + "crypto/bn/asm/ppc64-mont-fixed.pl", + "crypto/bn/asm/rsaz-avx2.pl", + "crypto/bn/asm/rsaz-x86_64.pl", + "crypto/bn/asm/sparct4-mont.pl", + "crypto/bn/asm/sparcv9a-mont.pl", + "crypto/bn/asm/x86-mont.pl", + "crypto/bn/asm/x86_64-mont.pl", + "crypto/bn/asm/x86_64-mont5.pl", + "crypto/chacha/asm/chacha-armv4.pl", + "crypto/chacha/asm/chacha-armv8-sve.pl", + "crypto/chacha/asm/chacha-armv8.pl", + "crypto/chacha/asm/chacha-c64xplus.pl", + "crypto/chacha/asm/chacha-ppc.pl", + "crypto/chacha/asm/chacha-riscv64-v-zbb.pl", + "crypto/chacha/asm/chacha-s390x.pl", + "crypto/chacha/asm/chacha-x86.pl", + "crypto/chacha/asm/chacha-x86_64.pl", + "crypto/chacha/asm/chachap10-ppc.pl", + "crypto/ec/asm/ecp_nistp384-ppc64.pl", + "crypto/ec/asm/ecp_nistp521-ppc64.pl", + "crypto/ec/asm/ecp_nistz256-armv4.pl", + "crypto/ec/asm/ecp_nistz256-ppc64.pl", + "crypto/ec/asm/ecp_nistz256-sparcv9.pl", + "crypto/ec/asm/ecp_nistz256-x86.pl", + "crypto/ec/asm/ecp_nistz256-x86_64.pl", + "crypto/ec/asm/x25519-ppc64.pl", + "crypto/ec/asm/x25519-x86_64.pl", + "crypto/md5/asm/md5-aarch64.pl", + "crypto/md5/asm/md5-loongarch64.pl", + "crypto/md5/asm/md5-x86_64.pl", + "crypto/modes/asm/aes-gcm-armv8_64.pl", + "crypto/modes/asm/ghash-ia64.pl", + "crypto/modes/asm/ghashp8-ppc.pl", + "crypto/perlasm/arm-xlate.pl", + "crypto/perlasm/ppc-xlate.pl", + "crypto/perlasm/x86_64-xlate.pl", + "crypto/poly1305/asm/poly1305-armv4.pl", + "crypto/poly1305/asm/poly1305-armv8.pl", + "crypto/poly1305/asm/poly1305-c64xplus.pl", + "crypto/poly1305/asm/poly1305-mips.pl", + "crypto/poly1305/asm/poly1305-ppc.pl", + "crypto/poly1305/asm/poly1305-ppcfp.pl", + "crypto/poly1305/asm/poly1305-s390x.pl", + "crypto/poly1305/asm/poly1305-sparcv9.pl", + "crypto/poly1305/asm/poly1305-x86.pl", + "crypto/poly1305/asm/poly1305-x86_64.pl", + "crypto/ppccpuid.pl", + "crypto/rc4/asm/rc4-x86_64.pl", + "crypto/s390xcpuid.pl", + "crypto/sha/asm/keccak1600-armv4.pl", + "crypto/sha/asm/keccak1600-armv8.pl", + "crypto/sha/asm/keccak1600-avx2.pl", + "crypto/sha/asm/keccak1600-avx512.pl", + "crypto/sha/asm/keccak1600-avx512vl.pl", + "crypto/sha/asm/keccak1600-c64x.pl", + "crypto/sha/asm/keccak1600-mmx.pl", + "crypto/sha/asm/keccak1600-ppc64.pl", + "crypto/sha/asm/keccak1600-s390x.pl", + "crypto/sha/asm/keccak1600-x86_64.pl", + "crypto/sha/asm/keccak1600p8-ppc.pl", + "crypto/sha/asm/sha1-ppc.pl", + "crypto/sha/asm/sha1-x86_64.pl", + "crypto/sha/asm/sha512-ia64.pl", + "crypto/sha/asm/sha512-parisc.pl", + "crypto/sha/asm/sha512-ppc.pl", + "crypto/sha/asm/sha512-x86_64.pl", + "crypto/sha/asm/sha512p8-ppc.pl", + "crypto/sm3/asm/sm3-riscv64-zvksh.pl", + "crypto/sm4/asm/sm4-armv8.pl", + "crypto/sm4/asm/vpsm4-armv8.pl", + "demos/http3/gen_nghttp3.pl", + "dev/release.sh", + "doc/man3/SSL_CTX_set1_curves.pod", + "external/perl/Text-Template-1.56/t/basic.t", + "external/perl/Text-Template-1.56/t/broken.t", + "external/perl/Text-Template-1.56/t/delimiters.t", + "external/perl/Text-Template-1.56/t/error.t", + "external/perl/Text-Template-1.56/t/exported.t", + "external/perl/Text-Template-1.56/t/hash.t", + "external/perl/Text-Template-1.56/t/inline-comment.t", + "external/perl/Text-Template-1.56/t/nested-tags.t", + "external/perl/Text-Template-1.56/t/ofh.t", + "external/perl/Text-Template-1.56/t/out.t", + "external/perl/Text-Template-1.56/t/prepend.t", + "external/perl/Text-Template-1.56/t/preprocess.t", + "external/perl/Text-Template-1.56/t/rt29928.t", + "external/perl/Text-Template-1.56/t/safe.t", + "external/perl/Text-Template-1.56/t/safe2.t", + "external/perl/Text-Template-1.56/t/safe3.t", + "external/perl/Text-Template-1.56/t/strict.t", + "external/perl/Text-Template-1.56/t/taint.t", + "external/perl/Text-Template-1.56/t/template-encoding.t", + "external/perl/Text-Template-1.56/t/warnings.t", + "fuzz/helper.py", + "fuzz/mkfuzzoids.pl", + "ms/cmp.pl", + "ms/uplink-common.pl", + "ms/uplink-ia64.pl", + "ms/uplink-x86.pl", + "ms/uplink-x86_64.pl", + "test/bntests.pl", + "test/certs/mkcert.sh", + "test/certs/setup.sh", + "test/cms-msg/make_missing_kdf_der.py", + "test/mldsa_parse.py", + "test/mldsa_wycheproof_parse.py", + "test/mlkem_parse.py", + "test/ocsp-tests/mk-ocsp-cert-chain.sh", + "test/recipes/20-test_kdf.t", + "test/recipes/20-test_legacy_okay.t", + "test/recipes/25-test_eai_data/kdc.sh", + "test/recipes/70-test_quic_multistream_data/verify-qlog.py", + "test/recipes/95-test_external_cf_quiche_data/quiche-build.sh", + "test/recipes/95-test_external_cf_quiche_data/quiche-server.sh", + "test/recipes/95-test_external_gost_engine_data/gost_engine.sh", + "test/recipes/95-test_external_krb5_data/krb5.sh", + "test/recipes/95-test_external_oqsprovider_data/oqsprovider-ca.sh", + "test/recipes/95-test_external_oqsprovider_data/oqsprovider.sh", + "test/recipes/95-test_external_pkcs11_provider_data/pkcs11-provider.sh", + "test/recipes/95-test_external_pyca_data/cryptography.sh", + "test/slhdsa_parse.py", + "test/smime-certs/mksmime-certs.sh", + "util/c-compress-test.pl", + "util/check-malloc-errs", + "util/checkplatformsyms.pl", + "util/ck_errf.pl", + "util/ctags.sh", + "util/err-to-raise", + "util/find-doc-nits", + "util/find-unused-errs", + "util/fips-checksums.sh", + "util/fix-includes", + "util/help.pl", + "util/lang-compress.pl", + "util/merge-err-lines", + "util/mkbuildinf.pl", + "util/mkdef.pl", + "util/mkdir-p.pl", + "util/mkerr.pl", + "util/mkpod2html.pl", + "util/mkrc.pl", + "util/mktar.sh", + "util/opensslwrap.sh", + "util/perl/OpenSSL/config.pm", + "util/shlib_wrap.sh.in", + "util/update_abi_check.sh", + "util/withlibctx.pl", + "util/write-man-symlinks" + ] } diff --git a/tools/openssl/source.py b/tools/openssl/source.py index ad2221f1..55ff950e 100644 --- a/tools/openssl/source.py +++ b/tools/openssl/source.py @@ -19,6 +19,7 @@ import shutil import stat import subprocess +import sys def inventory_digest(records: list[tuple[str, str, str]]) -> str: @@ -52,6 +53,20 @@ def excluded(directory: str, names: list[str]) -> set[str]: (relative / name).as_posix() in omitted} shutil.copytree(source, destination, symlinks=True, ignore=excluded) + windows = sys.platform == 'win32' + executable = set(pin.get('executable_files', ())) + normalize_eol = set() + if windows and (source / '.git').exists(): + # Git for Windows may check text out as CRLF. Restore only paths Git + # identifies as LF in its index and CRLF in the checkout, then verify + # their canonical bytes against the same digest as every other host. + entries = subprocess.check_output(['git', '-C', str(source), 'ls-files', '--eol', '-z']) + for entry in entries.split(b'\0'): + if not entry: + continue + metadata, name = entry.decode('utf-8').split('\t', 1) + if metadata.split()[:2] == ['i/lf', 'w/crlf']: + normalize_eol.add(name) records = [] for directory, directories, files in os.walk(destination, followlinks=False): for name in directories + files: @@ -62,9 +77,16 @@ def excluded(directory: str, names: list[str]) -> set[str]: if not stat.S_ISREG(mode): raise RuntimeError('OpenSSL source tree differs from tools/openssl/pin.json: ' f'unsupported file type: {path.relative_to(destination)}') - records.append((path.relative_to(destination).as_posix(), - '100755' if mode & 0o111 else '100644', - hashlib.sha256(path.read_bytes()).hexdigest())) + relative = path.relative_to(destination).as_posix() + data = path.read_bytes() + if relative in normalize_eol: + data = data.replace(b'\r\n', b'\n') + path.write_bytes(data) + # Windows has no POSIX executable bit. The pinned path inventory + # supplies that metadata; paths, file types and bytes still match. + is_executable = relative in executable if windows else bool(mode & 0o111) + records.append((relative, '100755' if is_executable else '100644', + hashlib.sha256(data).hexdigest())) if inventory_digest(records) != pin['source_sha256']: raise RuntimeError('OpenSSL source tree differs from tools/openssl/pin.json; ' 'restore the pinned source checkout or distribution') diff --git a/tools/openssl/source_test.py b/tools/openssl/source_test.py index 9d6d1541..96e0f132 100644 --- a/tools/openssl/source_test.py +++ b/tools/openssl/source_test.py @@ -14,6 +14,7 @@ import sys import tempfile import unittest +from unittest.mock import patch from source import check_checkout, stage_source from update import regenerate @@ -85,6 +86,23 @@ def test_checkout_and_generator_reject_mismatched_revision(self) -> None: with self.assertRaisesRegex(RuntimeError, 'checkout differs'): validate(self.source, self.pin) + def test_windows_staging_verifies_bytes_without_executable_file_modes(self) -> None: + pin = regenerate(self.source, self.pin) + (self.source / 'Configure').chmod(0o644) + with patch('source.sys.platform', 'win32'): + stage_source(self.source, self.root / 'windows', pin) + (self.source / 'crypto/input.c').write_text('int tampered;\n') + with self.assertRaisesRegex(RuntimeError, 'source tree differs'): + stage_source(self.source, self.root / 'tampered', pin) + + def test_windows_staging_normalizes_git_checkout_line_endings(self) -> None: + pin = regenerate(self.source, self.pin) + self.git('config', 'core.autocrlf', 'true') + (self.source / 'Configure').write_bytes(b'#!/usr/bin/env perl\r\n') + with patch('source.sys.platform', 'win32'): + stage_source(self.source, self.root / 'windows', pin) + self.assertEqual((self.root / 'windows/Configure').read_bytes(), b'#!/usr/bin/env perl\n') + def test_checkout_and_generator_reject_dirty_tracked_sources(self) -> None: (self.source / 'crypto/input.c').write_text('int changed;\n') for validate in (check_checkout, regenerate): diff --git a/tools/openssl/update.py b/tools/openssl/update.py index cff92a72..be778b48 100644 --- a/tools/openssl/update.py +++ b/tools/openssl/update.py @@ -58,7 +58,8 @@ def regenerate(source: Path, pin: dict) -> dict: timestamp = subprocess.check_output( ['git', '-C', str(source), 'show', '-s', '--format=%ct', pin['commit']], text=True) return {**pin, 'source_sha256': inventory_digest(records), - 'source_date_epoch': int(timestamp.strip()), 'omitted_submodules': omitted} + 'source_date_epoch': int(timestamp.strip()), 'omitted_submodules': omitted, + 'executable_files': sorted(name for name, mode, _ in files if mode == '100755')} def main() -> None: diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index 6d9965b6..c07d1c2e 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -9,6 +9,7 @@ import sys import io import json +import shutil import subprocess import tarfile import harness @@ -68,6 +69,65 @@ def test_native_source_dependency(root: Path) -> None: harness.expect(result, True, 'webcpp-openssl.build', '**passed**') +def test_symlinked_compiler_without_c_sibling(root: Path) -> None: + compiler = shutil.which('clang++') + assert compiler + alias = root / 'toolchain/bin/clang++' + alias.parent.mkdir(parents=True) + alias.symlink_to(compiler) + config = harness.user_config(root).read_text() + harness.configure(root, config + f'\nusing clang : alias : "{alias.as_posix()}" ;\n') + harness.add_library(root, 'openssl_user', JAM, {'uses_openssl.cpp': SOURCE}) + result = harness.run_b2(root, '-a', 'toolset=clang-alias', 'variant=release', + 'threading=single', 'libs/openssl_user/test') + harness.expect(result, True, '**passed**') + + +def test_msvc_build_commands_preserve_the_consumers_configuration(root: Path) -> None: + # Dry-run the real B2 toolset on any host. The Windows lanes run these + # commands with MSVC; this checks the adapter's configuration boundary. + compiler = root / 'Visual Studio/bin/cl.exe' + compiler.parent.mkdir(parents=True) + compiler.write_text('') + setup = compiler.parent / 'vcvarsall.bat' + setup.write_text('') + harness.configure(root, f'using msvc : 14.3 : "{compiler.as_posix()}"\n' + f' : "{setup.as_posix()}" off ;\n') + (root / 'Jamroot').write_text( + 'import webcpp-openssl ;\n' + 'project : build-dir bin ;\n' + f'webcpp-openssl.declare "{root.as_posix()}" : ssl.h configuration.h\n' + ' : tools/openssl/build.py ;\n' + 'exe consumer : uses_openssl.cpp openssl ;\n') + (root / 'uses_openssl.cpp').write_text(SOURCE) + for variant, runtime, flag in (('debug', 'shared', '/MDd'), ('debug', 'static', '/MTd'), + ('release', 'shared', '/MD'), ('release', 'static', '/MT')): + result = harness.run_b2( + root, '-n', '-a', 'consumer', 'toolset=msvc-14.3', 'target-os=windows', + 'architecture=x86', 'address-model=64', 'threading=multi', f'variant={variant}', + f'runtime-link={runtime}', 'cflags=/DWEBCPP_TEST_OPENSSL_CONFIGURATION=17', + env_extra={'BOOST_BUILD_PATH': str(root / 'tools')}) + harness.expect(result, True, 'webcpp-openssl.build', 'libssl.lib', 'libcrypto.lib', + flag, '--platform "windows"', 'vcvarsall.bat', + '--cc "cl"', '/DWEBCPP_TEST_OPENSSL_CONFIGURATION=17', + 'ws2_32.lib', 'crypt32.lib', '/OPT:REF') + assert 'libssl.a' not in result.stdout, result.stdout + command = next(line for line in result.stdout.splitlines() if ' python3 "' in line) + assert command.count('vcvarsall.bat') == 1, command + # Windows normally asks MSVC to generate a reusable setup script. Exercise + # that path too, even though B2 uses direct setup calls on Unix hosts. + harness.configure(root, 'import modules ;\nimport os ;\n' + 'local host = [ os.name ] ;\nmodules.poke os : .name : NT ;\n' + f'using msvc : 14.3 : "{compiler.as_posix()}"\n' + f' : "{setup.as_posix()}" ;\n' + 'modules.poke os : .name : $(host) ;\n') + result = harness.run_b2( + root, '-n', '-a', '-d2', '-d+6', 'consumer', 'toolset=msvc-14.3', 'target-os=windows', + 'architecture=x86', 'address-model=64', 'debug-store=database', + env_extra={'BOOST_BUILD_PATH': str(root / 'tools')}) + harness.expect(result, True, 'msvc-setup.bat', '--cc "cl"', '/Zi', 'ossl_static.pdb') + + def test_pin_mismatch_fails_before_compilation(root: Path) -> None: pin = root / 'tools/openssl/pin.json' data = json.loads(pin.read_text()) @@ -156,7 +216,7 @@ def test_source_archive_tampering_fails_before_configuration(root: Path) -> None result = subprocess.run( [sys.executable, str(root / 'tools/openssl/build.py'), '--source', str(source), '--output', str(root / 'rejected'), '--platform', platform, - '--threading', 'single', '--cc', 'clang++'], + '--threading', 'single', '--cc', str(root / 'missing-clang++')], capture_output=True, text=True, timeout=60) assert result.returncode != 0, change assert 'source tree differs' in result.stderr, result.stderr @@ -168,7 +228,9 @@ def test_source_archive_tampering_fails_before_configuration(root: Path) -> None (source / 'unexpected.pm').unlink(missing_ok=True) -CASES = [test_native_source_dependency, test_missing_checkout_is_lazy_and_actionable, +CASES = [test_native_source_dependency, test_symlinked_compiler_without_c_sibling, + test_msvc_build_commands_preserve_the_consumers_configuration, + test_missing_checkout_is_lazy_and_actionable, test_unsupported_target_is_rejected, test_pin_mismatch_fails_before_compilation, test_source_checkout_with_spaces, test_source_archive_without_git_and_inside_parent_checkout, diff --git a/tools/webcpp-openssl.jam b/tools/webcpp-openssl.jam index 6e50c270..22e5c194 100644 --- a/tools/webcpp-openssl.jam +++ b/tools/webcpp-openssl.jam @@ -42,11 +42,12 @@ class openssl-target : basic-target local os = [ $(properties).get ] ; local tool = [ $(properties).get ] ; local version = [ $(properties).get ] ; - if ! $(tool) in clang gcc || ! $(os) in darwin linux wasi - || ( $(os) = wasi && $(version) != wasip3 ) + if ! ( ( $(tool) in clang gcc && $(os) in darwin linux ) + || ( $(tool) = clang && $(os) = wasi && $(version) = wasip3 ) + || ( $(tool) = msvc && $(os) = windows ) ) { - errors.user-error "Source-built OpenSSL supports native Clang/GCC on macOS/Linux and clang-wasip3." - "WASIp2, browser targets, and the MSVC/nmake build are not supported by this recipe." ; + errors.user-error "Source-built OpenSSL supports native Clang/GCC on macOS/Linux, MSVC on Windows, and clang-wasip3." + "Other targets are not supported by this recipe." ; } # B2's normal directory omits free flags. Add the effective compiler # configuration so changing cflags or a user-config tool cannot reuse @@ -55,12 +56,14 @@ class openssl-target : basic-target properties = [ $(properties).add $(relevant) ] ; local fingerprint = [ modules.call-in webcpp-openssl : fingerprint $(properties) ] ; local action = [ new action $(source-targets) : webcpp-openssl.build : $(properties) ] ; - local ssl = [ new file-target libssl.a exact : STATIC_LIB : $(self.project) : $(action) ] ; + local extension = a ; + if $(os) = windows { extension = lib ; } + local ssl = [ new file-target libssl.$(extension) exact : STATIC_LIB : $(self.project) : $(action) ] ; local directory = [ path.root [ path.make [ $(ssl).path ] ] [ path.pwd ] ] ; directory = $(directory)/config-$(fingerprint) ; $(ssl).set-path $(directory) ; ssl = [ virtual-target.register $(ssl) ] ; - local crypto = [ new file-target libcrypto.a exact : STATIC_LIB : $(self.project) : $(action) ] ; + local crypto = [ new file-target libcrypto.$(extension) exact : STATIC_LIB : $(self.project) : $(action) ] ; $(crypto).set-path $(directory) ; crypto = [ virtual-target.register $(crypto) ] ; local headers ; @@ -71,6 +74,14 @@ class openssl-target : basic-target $(generated).set-path $(directory) ; headers += [ virtual-target.register $(generated) ] ; } + if $(os) = windows && [ $(properties).get ] = "on" + && [ $(properties).get ] = database + { + local symbols = [ new file-target ossl_static.pdb exact + : PDB : $(self.project) : $(action) ] ; + $(symbols).set-path $(directory) ; + headers += [ virtual-target.register $(symbols) ] ; + } return [ property-set.create [ $(relevant).raw ] $(directory)/include $(headers) ] $(ssl) $(crypto) ; } @@ -86,11 +97,12 @@ rule declare ( root : headers * : sources * ) : : darwin:-Wl,-dead_strip linux:-Wl,--gc-sections linux:-ldl + windows:"/OPT:REF ws2_32.lib gdi32.lib advapi32.lib crypt32.lib user32.lib" @webcpp-openssl.configuration wasi:"-lwasi-emulated-getpid -lwasi-emulated-signal -lwasi-emulated-process-clocks -lwasi-emulated-mman" ; } -toolset.uses-features webcpp-openssl.build : ; +toolset.uses-features webcpp-openssl.build : ; rule configuration ( properties * ) { @@ -110,7 +122,7 @@ rule fingerprint ( ps ) } local settings = openssl-settings-$(ps) ; compiler-settings $(settings) : $(ps) ; - local values = [ on $(settings) return $(CONFIG_COMMAND) $(OPTIONS) $(USER_OPTIONS) $(DEFINES) $(.AR) ] ; + local values = [ on $(settings) return $(DRIVER) $(C_OPTIONS) $(DEFINES) $(ARCHIVER) $(.SETUP) $(.SETUP-SCRIPT) $(.SETUP-OPTIONS) ] ; .fingerprint.$(ps) = [ MD5 "$(values:J=|)" ] ; return $(.fingerprint.$(ps)) ; } @@ -124,20 +136,41 @@ rule compiler-settings ( outputs * : ps ) compiler = clang-$(platform) ; } toolset.set-target-variables $(compiler).compile.c $(outputs) : $(ps) ; - toolset.set-target-variables $(compiler).archive $(outputs) : $(ps) ; + if $(compiler) = msvc + { + # Both operations inherit MSVC's setup flags. Read the archiver on a + # separate target so the setup script and its arguments occur once. + local archive-settings = $(outputs[1])-archive ; + toolset.set-target-variables msvc.archive $(archive-settings) : $(ps) ; + DRIVER on $(outputs) = [ on $(outputs[1]) return $(.CC[1]) ] ; + ARCHIVER on $(outputs) = [ on $(archive-settings) return $(.LD[1]) ] ; + C_OPTIONS on $(outputs) = [ on $(outputs[1]) return $(.CC[2-]) $(OPTIONS) $(CFLAGS) $(USER_CFLAGS) ] ; + } + else + { + toolset.set-target-variables $(compiler).archive $(outputs) : $(ps) ; + DRIVER on $(outputs) = [ on $(outputs[1]) return $(CONFIG_COMMAND[1]) ] ; + ARCHIVER on $(outputs) = [ on $(outputs[1]) return $(.AR:E=ar) ] ; + C_OPTIONS on $(outputs) = [ on $(outputs[1]) return $(OPTIONS) $(USER_OPTIONS) ] ; + } } rule build ( outputs * : inputs * : properties * ) { local ps = [ property-set.create $(properties) ] ; compiler-settings $(outputs) : $(ps) ; - SCRIPT on $(outputs) = $(.root)/tools/openssl/build.py ; - SOURCE on $(outputs) = $(.root)/third_party/libs/openssl ; + if [ $(ps).get ] = msvc + { + modules.call-in msvc : set-setup-command $(outputs) : $(properties) ; + } + SCRIPT on $(outputs) = [ path.native $(.root)/tools/openssl/build.py ] ; + SOURCE on $(outputs) = [ path.native $(.root)/third_party/libs/openssl ] ; PLATFORM on $(outputs) = [ $(ps).get ] ; THREADING on $(outputs) = [ $(ps).get ] ; + VARIANT on $(outputs) = [ $(ps).get ] ; } actions build { - python3 "$(SCRIPT)" "@($(<[1]).rsp:E=--source "$(SOURCE)" --output "$(<[1]:D)" --platform "$(PLATFORM)" --threading "$(THREADING)" --cc "$(CONFIG_COMMAND[1])" --ar "$(.AR:E=ar)" -- $(OPTIONS) $(USER_OPTIONS) -D$(DEFINES))" + $(.SETUP) python3 "$(SCRIPT)" "@($(<[1]:W).rsp:E=--source "$(SOURCE)" --output "$(<[1]:DW)" --platform "$(PLATFORM)" --threading "$(THREADING)" --variant "$(VARIANT)" --cc "$(DRIVER)" --ar "$(ARCHIVER)" -- $(C_OPTIONS) -D$(DEFINES))" } From 91af39e291966bc1cec8f1c147280a265be145c8 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 01:03:39 -0500 Subject: [PATCH 02/32] build: integrate Beast backends and complete CI validation coverage [skip ci] --- .github/workflows/library.yml | 38 ++++++ .gitmodules | 3 + AGENTS.md | 10 ++ CODING-GUIDELINES.md | 85 +++++++++----- Jamroot | 2 +- README.md | 6 +- doc/releases/0.1.0.adoc | 9 ++ .../plans/2026-11-02-beast-completion.md | 52 +++++++++ libs/asio | 2 +- libs/beast | 1 + libs/trystero | 2 +- libs/wasi | 2 +- tools/boost/Jamfile | 103 +++++++++++++++++ tools/boost/asio-wasip3/Jamfile | 7 ++ tools/boost/asio-wasip3/README.md | 22 ++++ tools/boost/asio-wasip3/boost-1.92.patch | 4 +- tools/boost/asio-wasip3/manifest.json | 2 +- tools/boost/asio-wasip3/prepare.py | 13 ++- tools/boost/asio-wasip3/prepare_test.py | 5 + tools/boost/asio-wasip3/run.sh | 18 ++- tools/boost/asio-wasip3/run_test.py | 108 ++++++++++++++++++ tools/boost/asio-windows/Jamfile | 33 ++++++ tools/boost/asio-windows/README.md | 19 +++ tools/boost/asio-windows/boost-1.92.patch | 22 ++++ tools/boost/asio-windows/manifest.json | 9 ++ tools/boost/cobalt-common/boost-1.92.patch | 37 ++++++ tools/boost/cobalt-common/manifest.json | 4 + tools/boost/cobalt-wasip3/boost-1.92.patch | 20 ---- tools/boost/cobalt-wasip3/manifest.json | 4 - tools/ci/actions/boost/install.sh | 2 +- tools/ci/actions/chrome/action.yml | 13 ++- tools/ci/actions/chrome/install.sh | 45 +++++--- tools/ci/actions_test.py | 50 +++++++- tools/ci/matrix.py | 6 +- tools/ci/matrix_test.py | 40 ++++++- tools/component/component.jam | 8 +- tools/doc/counts.py | 2 +- tools/doc/counts_test.py | 12 ++ tools/lint/compile_commands.py | 16 ++- tools/lint/lint.sh | 14 +++ tools/lint/lint_test.py | 47 +++++++- tools/lint/rules.py | 2 +- tools/openssl/build.py | 19 ++- tools/openssl/build_test.py | 14 ++- tools/test/asio_wasip3_test.py | 29 ++++- tools/test/boost_libraries_test.py | 63 ++++++++++ tools/test/component_jam_test.py | 17 +++ tools/test/webcpp_jam_test.py | 42 +++++++ tools/webcpp.jam | 45 +++++++- 49 files changed, 1017 insertions(+), 111 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-02-beast-completion.md create mode 160000 libs/beast create mode 100644 tools/boost/asio-wasip3/run_test.py create mode 100644 tools/boost/asio-windows/Jamfile create mode 100644 tools/boost/asio-windows/README.md create mode 100644 tools/boost/asio-windows/boost-1.92.patch create mode 100644 tools/boost/asio-windows/manifest.json diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 968fe55e..dc697f20 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -341,6 +341,44 @@ jobs: # (its entry's chrome), as trystero's interop does. - if: matrix.chrome uses: ./tools/ci/actions/chrome + with: + product: ${{ matrix.library == 'beast' && 'chrome' || 'chrome-headless-shell' }} + + - name: Build the native Beast interoperability peer + if: matrix.library == 'beast' && (matrix.lane == 'browser' || matrix.lane == 'browser-node') + shell: bash + run: | + python3 tools/ci/matrix.py register clang-18 + b2 --user-config=.local/user-config.jam \ + libs/beast/test/browser/peer//native_peer-program \ + toolset=clang-18 threading=multi -j2 + + # This embedding adds a private test CA through Wasmtime's supported host hook. + # Stock Wasmtime uses its bundled public roots and has no CLI test-CA option. + - name: Restore the isolated WASI HTTPS host fixture + if: matrix.library == 'beast' && matrix.lane == 'applications-host-tls' + id: host-tls-cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .local/beast-host-tls + key: beast-host-tls-${{ runner.os }}-${{ runner.arch }}-rust-1.97.1-${{ hashFiles('libs/beast/test/applications/host-tls/Cargo.lock', 'libs/beast/test/applications/host-tls/Cargo.toml', 'libs/beast/test/applications/host-tls/src/**') }} + + - name: Build the isolated WASI HTTPS host fixture + if: matrix.library == 'beast' && matrix.lane == 'applications-host-tls' + shell: bash + run: | + rustup toolchain install 1.97.1 --profile minimal + cargo +1.97.1 build --locked --jobs 2 \ + --manifest-path libs/beast/test/applications/host-tls/Cargo.toml \ + --target-dir .local/beast-host-tls + echo "WEBCPP_WASI_TLS_FIXTURE=$PWD/.local/beast-host-tls/debug/webcpp-beast-host-tls-fixture" >> "$GITHUB_ENV" + + - name: Save the isolated WASI HTTPS host fixture + if: matrix.library == 'beast' && matrix.lane == 'applications-host-tls' && steps.host-tls-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .local/beast-host-tls + key: ${{ steps.host-tls-cache.outputs.cache-primary-key }} # It registers its toolset in .local/user-config.jam, prints its b2 command and runs it. - name: Own lane diff --git a/.gitmodules b/.gitmodules index 269eeffc..443a0c73 100644 --- a/.gitmodules +++ b/.gitmodules @@ -40,3 +40,6 @@ [submodule "libs/asio"] path = libs/asio url = ../asio.git +[submodule "libs/beast"] + path = libs/beast + url = ../beast.git diff --git a/AGENTS.md b/AGENTS.md index b3c1b386..473f2e48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,6 +74,7 @@ for web developers and for AI developers (`CODING-GUIDELINES.md` chapter 16). | Library | What it is | Targets | State | | --- | --- | --- | --- | | asio | Boost.Asio and Cobalt with browser event-loop suspension, WASIp3 networking and optional source-built TLS | native, emscripten, wasip3 | a submodule at `libs/asio`; see its feature matrix for variants | +| beast | HTTP and WebSocket applications using native/WASIp3 sockets, browser WebSocket/fetch, WASI host HTTP or supplied streams | native, emscripten, wasip2, wasip3, by backend | a submodule at `libs/beast`; all 53 upstream applications remain in its compatibility matrix | | config | webcpp's configuration, which every library includes first: the target, exceptions and webcpp's version, as Boost.Config is Boost's; webcpp's own | native, wasip2, wasip3, emscripten | a submodule at `libs/config` | | xactor | a deterministic actor system, webcpp's own | native, wasip2, wasip3 (`xactor_asio` native only) | a submodule at `libs/xactor`; the model for every port | | xstate | a port of XState 5.33.2's state machines and actors; depends on xactor and Boost.JSON | native, wasip2, wasip3; its oracle lane | a submodule at `libs/xstate`; the first user of the shared oracle (`CODING-GUIDELINES.md` chapter 12) | @@ -989,7 +990,9 @@ webcpp.boost-test : + : * ; webcpp.example : * : * ; webcpp.headers-alone : : * : * : * ; webcpp.link : + : * : * ; +webcpp.link-fail : + : * : * ; webcpp.data + ; (requirements) +webcpp.source-only + ; (reference source trees) ``` | Rule | Passes when | Notes | @@ -999,8 +1002,10 @@ webcpp.data + ; (requirements) | `webcpp.run-fail` | the program exits with another status | built and run as `webcpp.run`'s, and links `/webcpp//node-test` likewise | | `webcpp.compile` | the sources compile | no program is linked; takes `/webcpp//node-test` for its header | | `webcpp.compile-fail` | the sources do not compile | left out of clang-tidy; any error passes it, the wrong one included; takes `/webcpp//node-test` for its header | +| `webcpp.link-fail` | the compiled sources fail to link | use a matching successful control to distinguish the intended incompatibility from unrelated failures; the sources remain in clang-tidy | | `webcpp.compile-diagnostic` | the sources stop with every error they state in clang's `-verify` comments, `// expected-error@:* {{}}` for a header they include or `// expected-error@+1 {{}}` for the next line | compiled with `-Xclang -verify -Xclang -verify-ignore-unexpected=error,note`, so an error not stated and a note are ignored; built on b2's `clang` toolset only (native clang, `clang-wasip2`, `clang-wasip3`) and skipped elsewhere, since `-verify` is clang's: a refusal would turn every gcc and msvc lane red for a declaration that holds; left out of clang-tidy; takes `/webcpp//node-test` for its header | | `webcpp.boost-test` | every case of the Boost.Test suite passes | native only, whatever the Jamfile declares; the header-only framework, `tools/boost_test_runner.cpp`, is one object of the suite's, always compiled with exceptions | +| `webcpp.source-only` | | declares child source directories whose original Jamfiles are not WebCPP projects; use in `build.jam` before discovery; it changes neither explicit compilation nor lint | | `webcpp.example` | the program exits with 0, and its standard output, carriage returns removed, equals `.expected` beside it | its standard input is `.input` beside it, else empty, never the terminal, on every target (wasmtime passes it through, and node under `-sNODERAWFS=1`); run through `testing.launcher` for WASI, and on emscripten with the node on `PATH`, not the one b2's toolset registered, which b2 gives only to its own testing rules, by `tools/example/run_example.py`, which names a failing exit status (or the signal) before the diff; always run again, and `.input` is a source of the run; links `/webcpp//node-test` on every target (Targets, above) | | `webcpp.link` | the program links | never run: a program for a browser, which node refuses to run (`-sENVIRONMENT=web`), or one that needs the network; b2's `link` test, which `--dump-tests` lists and the report shows as a link test; never linked with `-sNODERAWFS=1`. The explicit target `-program` is the same program, an `exe` of the same sources and requirements, `-program.js` on emscripten, for a target that needs its files, such as a page that loads it. An example Jamfile's is shown on the page by its code, and has no `.expected` (chapter 3) | | `webcpp.headers-alone` | each public header compiles alone | one test per header, `alone-` with `/` as `-` (`alone-xactor-scheduler`), against `/webcpp///` and the requirements given, for the targets given or the Jamfile's; `only` restricts a call to the public headers its globs match, relative to `/webcpp/` (`wasi/http/response.hpp`), a glob that matches none stopping the build; a library may call it several times, and a header two calls take stops the build, naming it | @@ -1823,6 +1828,11 @@ wrapper each quoted as one word of Jam. `CHROME_DEVEL_SANDBOX` naming the image's setuid helper, `/opt/google/chrome/chrome-sandbox`. The headless shell sends nothing to Google of its own (measured). + Beast browser lanes select `product: chrome` at the same pinned version, + installed into `.local/chrome`. Its certificate tests need full Chrome's + isolated profile trust store. Test CAs are installed only in disposable + profiles; no host trust store or certificate-validation bypass is used. + The drivers disable background networking and operate against local fixtures. - `container` gives a job the container lanes' image (above): built from `tools/ci/container/Dockerfile` when the cache does not hold it, saved there under the Dockerfile's digest, and loaded from there otherwise. diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 34e4bd6e..9ba9a406 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -6722,6 +6722,64 @@ The original proposal has not been amended and no CI ran. Its conflicts with chapters 1 to 13 are in chapter 19. +### beast (Boost.Beast portability facade) + +The owner's expanded Beast genesis proposal in +`libraries/beast/openspec/changes/genesis` governs this implementation. The +library is the `webcpporg/beast` submodule at `libs/beast`. The proposal records +source compatibility, explicit environment counterparts and unavailable +facilities separately; a successful compile never proves runtime parity. + +- Portable HTTP messages, parsers and serializers reuse Boost.Beast 1.92. + `http.hpp` remains independent of a socket reactor. Byte-stream algorithms + are explicit `http/read.hpp` and `http/write.hpp` includes. +- Native and WASIp3 guest sockets use webcpp::asio. Guest TLS is optional and + explicitly links the project's source-built OpenSSL through `//tls`. + `set_server_name` sets SNI only; peer verification and hostname validation + remain explicit. Native and WASIp3 stream internals retain upstream Beast's + allocation behavior, even when accepting the portable allocator constructor. +- The browser backend uses JavaScript WebSocket and fetch. Its TCP-shaped + lowest layer records an authority rather than opening a raw socket, and its + TLS-shaped layer records intent rather than running guest OpenSSL. The + browser owns trust, handshake headers, framing, DNS and redirects. +- Browser stream state, retained metadata and payloads use the stream allocator; + operation completions use their associated allocator and executor. The + intrusive Asio bridge registration avoids an independent lookup allocation. + Receive limits account for retained message records as well as payloads, + including browser arrivals before the application drains its executor. + Terminal registrations and queued events are scoped to one connection or + request generation, so cancellation and reuse cannot deliver stale results. +- `browser::http_byte_stream` is an explicit synthetic HTTP/1.1 adapter for + algorithms that require bytes. Fetch has already decoded the body. Its + internal parser, fields and body use the stream resource; synthetic chunk + sizes use fixed storage because upstream's helper has no allocator hook. +- The propagated B2 feature `webcpp-beast-unsupported=error|ignore` selects the + unsupported-setting policy, defaulting to error. Translation units with + different policies must fail to link. Ignoring a setting never enables an + unavailable transport or conceals an operational network failure. +- WASI host HTTP is independent of guest sockets and OpenSSL. The `//wasi-http` + target uses webcpp::wasi's independent host bindings on P2/P3, preserving + full messages, trailers, cancellation and explicit host ownership. Supplied + stdin/stdout streams are meaningful counterparts for local-socket examples; + they do not supply Unix-domain addressing. Host HTTP does not provide a + WebSocket upgrade or a guest TCP listener. +- The immutable upstream application corpus contains all 53 executable + definitions at its pinned commit. Inventory checks validate original hashes, + Jamfiles, CMake definitions and entry points. All adaptations are generated + by checked-in generators and inspectable patches; never edit their output. + Preserve each application's algorithm where possible, and record every + scheduling, resolver, transport or error-handling adaptation explicitly. +- Feature and application matrices in the guide keep compilation and execution + separate for every target, exception mode and supported threading profile. + Unavailable stackful Wasm coroutines, browser listeners, WASIp2 guest sockets + and cooperative WASIp3 exceptions remain unavailable, never counted as passes. +- Native upstream programs are the oracle. Browser validation runs in real + Chrome with a disposable CA profile, independently of Node. WASI host HTTPS + uses a pinned Wasmtime host fixture with normal trust and hostname checks; + guest TLS evidence cannot substitute for it. Positive and negative trust + controls accompany TLS application evidence. Documentation follows Diataxis + in AsciiDoc with MrDocs API reference and executable examples. + ## 16. Roadmap What webcpp does not have yet, and the chapters that mention it: @@ -8068,33 +8126,6 @@ The proposals not yet decided, each briefly, with the questions they leave for the owner. A draft decides nothing: it is here so that a contributor sees what is coming, and its proposal holds it in full. -### beast (implementation started locally) - -The owner authorized implementation on 2026-11-02 after expanding the proposal -in `libraries/beast/openspec/changes/genesis` to WASIp2, WASIp3, Emscripten and all -53 upstream executable examples. That proposal governs over the older -2026-10-10 baseline. Upstream Beast data types are reused; host transports do not -need upstream network/protocol execution. The library currently exists as a local -repository at `libs/beast`, with no organization repository or release yet. - -The first increment separates portable messages/parsers/serializers from explicit -socket algorithm headers and optional TLS. Native and WASIp3 use the existing -Asio socket backend; browser WebSocket/fetch and WASI host HTTP remain subsequent -work, with application adaptation distinguished from exact transport parity. -The feature matrix is in the library guide; only recorded build/runtime evidence -establishes a supported profile. The remaining proposal must not be marked complete -from this initial backend. - -The unsupported-setting policy is a propagated B2 feature, default error. Native -WebSocket state keeps upstream allocation while accepting the portable allocator -constructor syntax. `set_server_name` configures guest TLS SNI only and rejects -empty, overlong and embedded-NUL names; it does not perform certificate verification. - -The implementation plan and current decisions are in the proposal's -`reference/plan.md` and `design.md`. No change adds guest OpenSSL or a missing -Asio WASIp2 reactor as a prerequisite to host HTTP. Missing Unix socket facilities -receive explicit host-stream counterparts where meaningful. - ### webrtc (draft, not decided) webcpp::webrtc would be a header-only C++20 library of webcpp's own diff --git a/Jamroot b/Jamroot index 8c9f4680..4d2e53c7 100644 --- a/Jamroot +++ b/Jamroot @@ -423,7 +423,7 @@ use-project /webcpp/boost-libraries : tools/boost ; # Boost.JSON does with boost_json. Each alias checks the sources before anything # is built; what Boost.Locale gives on each target is the table of # CODING-GUIDELINES.md chapter 10. -for local name in boost_url boost_charconv boost_locale boost_cobalt boost_cobalt_io_ssl +for local name in boost_url boost_charconv boost_locale boost_cobalt boost_cobalt_io_ssl boost_context { alias $(name) : tools/boost//$(name) : @boost-source-usable ; } diff --git a/README.md b/README.md index 5da2ae3d..474808c5 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ system. | Library | What it is | Targets | | --- | --- | --- | | [asio](https://github.com/webcpporg/asio) | Boost.Asio and Cobalt with browser event-loop suspension, WASIp3 networking and optional source-built TLS. | native, emscripten, wasip3 | +| [beast](https://github.com/webcpporg/beast) | Beast-compatible HTTP and WebSocket applications, with native/WASIp3 sockets, browser WebSocket and fetch, WASI host HTTP and supplied streams. Its guide records compatibility and results for all 53 upstream applications. | native, emscripten, wasip2, wasip3, by backend | | [xactor](https://github.com/webcpporg/xactor) | A header-only, deterministic actor system: actors that handle one message at a time, with fuel per execution, timers and a lifecycle. | native, wasip2, wasip3 | | [xstate](https://github.com/webcpporg/xstate) | A header-only port of XState's state machines and actors: machines read from XState's JSON config, stepped by XState's pure functions or run as actors on xactor. Ports XState 5.33.2, and is proven against it. | native, wasip2, wasip3 | | [pratt](https://github.com/webcpporg/pratt) | A header-only Pratt parser engine, generic through concepts, with a calculator built on it, exact in decimal by default; a library of webcpp's own. | native, emscripten, wasip2, wasip3 | @@ -38,7 +39,7 @@ library on every target are published at . ## Prerequisites - Boost 1.92 or newer, installed, and for a library that links Boost.URL, - Boost.Charconv or Boost.Locale its sources, which `bash + Boost.Charconv, Boost.Locale, Boost.Cobalt or Boost.Context its sources, which `bash tools/ci/actions/boost/install.sh source .local/boost-source` fetches; - b2; - a C++20 compiler; @@ -61,6 +62,9 @@ library on every target are published at . native backends; - for a library's oracle lane, which runs the original it ports against the same cases and examples, Node and npm; +- for Beast's browser contracts, Node 26 and full Chrome for Testing with a + disposable CA profile; its WASI HTTPS host fixture builds with Rust 1.97.1 + and the checked-in Cargo lockfile, as its verification guide describes; - for the lint, wasi-sdk 34, whose clang-format and clang-tidy it runs, the wasip2, wasip3 and emscripten toolsets below, wit-bindgen, the WIT and trystero's libraries, since it reads what those toolsets compile, and Node, diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index d771cbf0..7fc2c998 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -10,6 +10,9 @@ [#webcpp-0-1-0-new-libraries] == New Libraries +* link:{library-pages}beast/{library-page}[beast]: HTTP messages and WebSocket +applications for native, WASI and browser targets, with socket transports, +browser WebSocket and fetch, WASI host HTTP and supplied byte streams, from R. * link:{library-pages}config/{library-page}[config]: webcpp's configuration, which every library includes first: the target, exceptions and the version, from R. @@ -49,9 +52,15 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Added source-built Boost.Context for native stackful coroutine applications. +* Added negative link tests and explicit reference-source build discovery. +* Added hash-verified Beast application inputs and browser CI dependencies. +* Added isolated CA trust tests with pinned full Chrome and a Wasmtime host fixture. +* Fixed duplicate source paths selecting conflicting targets in the lint database. * Updated Wasmtime to 50.0.1 for every library's WASI targets. * Fixed WASIp3 network tests lacking the required runtime capabilities. * Fixed OpenSSL source builds with symlinked compilers and Windows checkouts. +* Fixed serial Windows OpenSSL builds exhausting the parallel-build time budget. * Added native MSVC OpenSSL build recipes with B2 runtime settings. * Fixed Cobalt lint builds requiring pre-existing generated Boost overlays. * Fixed source distributions rejecting pinned site and third-party dependencies. diff --git a/docs/superpowers/plans/2026-11-02-beast-completion.md b/docs/superpowers/plans/2026-11-02-beast-completion.md new file mode 100644 index 00000000..ec6df48a --- /dev/null +++ b/docs/superpowers/plans/2026-11-02-beast-completion.md @@ -0,0 +1,52 @@ +# Complete the Beast portability implementation + +The owner requests completion, publication and integration after the complete CI +passes. This continues the approved design in the Beast genesis proposal, not a +new reduction to the first working backend. Baseline: superproject `684c4fe`, +Beast `c7dfe2b`, proposals `853ce39`. + +The binding specification is +`../../../../proposals/libraries/beast/openspec/changes/genesis/specs/beast/spec.md`; +its design and existing reference plan remain applicable. + +## Execution and completion contract + +- Work in the existing isolated checkout. The parent owns integration, TLS + protocol tests, shared build/lint/CI changes and publication. +- Independent workers own browser adapters, WASI host APIs, and the application + corpus. They use separate source/test paths and report required shared edits. +- Every promised supported profile requires real runtime evidence. Preserve the + complete inventory, source adaptations and unavailable facilities explicitly. +- Native upstream applications provide the behavioural oracle. Browser results + require a browser, not Node alone. Host HTTP must not import guest TCP/OpenSSL. +- Fresh local checks precede publication. Remote checks must run on the exact + candidate commits before the main branches are merged. No bypass of checks or + claim of self-approval as independent review. +- A partial backend, successful compilation alone, or an expected unsupported + diagnostic cannot count as a completed application. + +## Tasks + +1. Complete browser layers, WebSocket and fetch, including cancellation, lifetime, + allocators, limits, unsupported settings and JSPI/Asyncify real-browser tests. +2. Complete independent WASI host HTTP client/server APIs, full messages and + supplied-stream counterparts for P2/P3, including resource and failure tests. +3. Verify Beast HTTP/WebSocket over guest TLS, peer identity, timeout, cancellation + during transfer, normal/error/cancelled shutdown, with both exception modes. +4. Reconcile and implement all 53 applications or explicitly documented + environment counterparts; resolve prerequisites in their owning libraries. +5. Complete the Diataxis/AsciiDoc/MrDocs guide and feature/application matrices; + run every local lane, affected tool suite, lint and independent review. +6. Publish library candidate commits, register the Beast submodule, run library + and superproject CI on the candidate, fix failures, then integrate only when + the complete acceptance criteria and required checks pass. + +## Decisions and evidence + +- WASI host HTTP uses new independent worlds and a `host-http` target; existing + export-only HTTP worlds remain unchanged for current consumers. +- The original upstream application corpus is immutable and hash-verified; + adaptations remain inspectable and separately validated. +- Logs and per-domain progress are retained in `.local/beast-completion/`. +- Remote publication and CI are now authorized by the owner's current request; + earlier no-CI restrictions do not apply to this completion phase. diff --git a/libs/asio b/libs/asio index 3c72eea5..e551f9cf 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 3c72eea579690c131cae36528ea8b0d8793cb628 +Subproject commit e551f9cf14abb66e79e5fe04960c704762b19a44 diff --git a/libs/beast b/libs/beast new file mode 160000 index 00000000..9ee7ca4b --- /dev/null +++ b/libs/beast @@ -0,0 +1 @@ +Subproject commit 9ee7ca4b3c50db26a7926a1a6deba1cc35f35f6f diff --git a/libs/trystero b/libs/trystero index a9af9325..3d8939bc 160000 --- a/libs/trystero +++ b/libs/trystero @@ -1 +1 @@ -Subproject commit a9af9325695e64994c9e5fbb14a4abcbd328b616 +Subproject commit 3d8939bce007dae58403a42d727dc5994666f7f4 diff --git a/libs/wasi b/libs/wasi index 27aafae0..edf8c319 160000 --- a/libs/wasi +++ b/libs/wasi @@ -1 +1 @@ -Subproject commit 27aafae0a7693b80bd69ff0052cb4f9eebd6aa4b +Subproject commit edf8c3191f88d4c7c758a251aeb4637c5f004093 diff --git a/tools/boost/Jamfile b/tools/boost/Jamfile index e95cd6f4..05070d22 100644 --- a/tools/boost/Jamfile +++ b/tools/boost/Jamfile @@ -15,12 +15,14 @@ # read as system ones. import errors ; import feature ; +import os ; import property-set ; import sequence ; import set ; import webcpp-target ; use-project /webcpp/asio-wasip3 : asio-wasip3 ; +use-project /webcpp/asio-windows : asio-windows ; use-project /webcpp/cobalt-wasip3 : cobalt-wasip3 ; use-project /webcpp/cobalt-ssl : cobalt-ssl ; use-project /webcpp/cobalt-common : cobalt-common ; @@ -86,6 +88,105 @@ compiled boost_charconv : [ glob libs/charconv/src/*.cpp ] : BOOST_CHARCONV_SOURCE=1 : BOOST_CHARCONV_NO_LIB=1 ; +# The pinned Context fcontext recipe keeps its C++ wrapper and assembly +# together. Windows ARM64 uses upstream's WinFiber default. Wasm has no +# proven Context backend, independently of JSPI or Asyncify suspension. +rule context-architecture ( properties * ) +{ + local architecture = [ feature.get-values : $(properties) ] ; + if ! $(architecture) + { + local host = [ os.platform ] ; + switch $(host:L) + { + case arm* : architecture = arm ; + case aarch64 : architecture = arm ; + case * : architecture = x86 ; + } + } + return $(architecture) ; +} + +rule context-configuration ( properties * ) +{ + local target = [ webcpp-target.target-of $(properties) ] ; + if $(target) != native + { + errors.user-error "Boost.Context has no verified $(target) backend; stackful" + "coroutines remain blocked. JSPI, Asyncify and C++20 awaitables do not" + "supply a Boost.Context backend." ; + } + local architecture = [ context-architecture $(properties) ] ; + local model = [ feature.get-values : $(properties) ] ; + local system = [ feature.get-values : $(properties) ] ; + local compiler = [ feature.get-values : $(properties) ] ; + if $(model) && $(model) != 64 + { + errors.user-error "webcpp's Boost.Context recipe currently requires address-model=64" ; + } + local directory = $(WEBCPP_BOOST_SOURCE)/libs/context/src ; + local sources = $(directory)/fcontext.cpp ; + local suffix ; + if $(system) = windows + { + sources += $(directory)/windows/stack_traits.cpp ; + if $(architecture) = arm + { + return $(directory)/continuation.cpp $(directory)/fiber.cpp + $(directory)/windows/stack_traits.cpp BOOST_USE_WINFIB + _WIN32_WINNT=0x0601 ; + } + if $(architecture) = x86 && $(compiler) = msvc + { + suffix = x86_64_ms_pe_masm.asm ; + } + else if $(architecture) = x86 + { + suffix = x86_64_ms_pe_gas.asm ; + } + } + else + { + sources += $(directory)/posix/stack_traits.cpp ; + if $(system) = darwin + { + suffix = combined_sysv_macho_gas.S ; + } + else if $(system) = linux && $(architecture) = arm + { + suffix = arm64_aapcs_elf_gas.S ; + } + else if $(system) = linux && $(architecture) = x86 + { + suffix = x86_64_sysv_elf_gas.S ; + } + } + if ! $(suffix) + { + errors.user-error "No Boost.Context recipe for" $(system) $(architecture) $(compiler) ; + } + for local operation in make jump ontop + { + sources += $(directory)/asm/$(operation)_$(suffix) ; + } + return $(sources) ; +} + +rule context-usage ( properties * ) +{ + if windows in $(properties) && [ context-architecture $(properties) ] = arm + { + return BOOST_USE_WINFIB _WIN32_WINNT=0x0601 ; + } +} + +compiled boost_context : [ glob libs/context/src/fcontext.cpp ] + : libs/context/src/fcontext.cpp is missing + : @context-configuration BOOST_CONTEXT_SOURCE + BOOST_CONTEXT_STATIC_LINK=1 BOOST_CONTEXT_NO_LIB=1 + : BOOST_CONTEXT_STATIC_LINK=1 BOOST_CONTEXT_NO_LIB=1 + @context-usage ; + # The system's iconv, which macOS keeps in a library of its own; glibc and # wasi-libc have it in libc. lib iconv : : iconv ; @@ -235,11 +336,13 @@ compiled boost_cobalt : [ cobalt-sources ] : libs/cobalt/src holds no .cpp file : BOOST_COBALT_SOURCE=1 BOOST_COBALT_IO_SOURCE=1 /webcpp/cobalt-common//headers + windows:/webcpp/asio-windows//headers emscripten:BOOST_ASIO_DISABLE_THREADS @cobalt-configuration @cobalt-platform-sources : BOOST_COBALT_NO_LIB=1 /webcpp/cobalt-common//headers + windows:/webcpp/asio-windows//headers clang-wasip3:/webcpp/cobalt-wasip3//headers emscripten:BOOST_ASIO_DISABLE_THREADS ; diff --git a/tools/boost/asio-wasip3/Jamfile b/tools/boost/asio-wasip3/Jamfile index 689e6f7a..d6e03f0f 100644 --- a/tools/boost/asio-wasip3/Jamfile +++ b/tools/boost/asio-wasip3/Jamfile @@ -45,3 +45,10 @@ alias headers : : : : prepared.stamp "-I\"$(OVERLAY)/include\"" @configuration ; explicit headers ; + +# Association and completion-token traits for a host-owned HTTP scheduler. +# This alias does not enable a socket reactor or cooperative threads on WASIp2. +alias host-headers : : : : prepared.stamp + "-I\"$(OVERLAY)/include\"" + BOOST_ASIO_DISABLE_THREADS ; +explicit host-headers ; diff --git a/tools/boost/asio-wasip3/README.md b/tools/boost/asio-wasip3/README.md index c215093e..592c3cbd 100644 --- a/tools/boost/asio-wasip3/README.md +++ b/tools/boost/asio-wasip3/README.md @@ -15,6 +15,13 @@ Stale extra files or symlinks in the private overlay stop preparation; clean tha private directory and rebuild after changing the set of patched headers. Only patched headers are copied; other headers continue to come from Boost. +`/webcpp/asio-wasip3//host-headers` exposes association and completion-token +traits to the single-threaded WASIp2 host HTTP scheduler. The only platform +change selected on WASIp2 is the signal-free wait in `null_event`: WASI uses +`poll` instead of the unavailable POSIX `pause`. This does not enable the Asio +socket reactor on WASIp2. Host operations supply their own executor and never +fall back to `system_executor` or an operating-system thread pool. + The changes address missing POSIX signals/interface names, no-thread waiting, thread-safe signal-blocker selection, shutdown error mapping, unavailable socket options, scalar socket I/O, and resolver thread-pool initiation without threads. @@ -41,10 +48,25 @@ contains the no-exceptions runtime only. The project selects Wasmtime 50.0.1 for launcher, using `wasmtime` on `PATH` and granting network/name-lookup access. It is not a production capability policy. +The launcher bounds each guest's execution to 600 seconds by default. The global +WASIp3 lane includes finite document and Unicode workloads, not only short +network tests: unchanged debug document tests took 127-147 seconds locally +under concurrent build load, and the benchmark smoke pass completed in 155 +seconds. A benchmark run under heavier contention exceeded even 180 seconds. +The earlier 15-second limit interrupted these tests. The default provides +about four times the longest completed measurement for shared runners while +still terminating a stuck guest. Set +`WEBCPP_WASIP3_TEST_TIMEOUT` to a positive integer number of seconds to change +the bound. Empty, zero, negative and noninteger values fail before launch. +For focused loopback tests, use `WEBCPP_WASIP3_TEST_TIMEOUT=15`. This setting +changes only the execution bound; all runtime options and guest arguments are +forwarded unchanged. + Run from the superproject root: ```bash python3 tools/boost/asio-wasip3/prepare_test.py +python3 tools/boost/asio-wasip3/run_test.py python3 tools/test/asio_wasip3_test.py b2 -a toolset=clang-wasip3 variant=release threading=single \ testing.launcher=tools/boost/asio-wasip3/run.sh libs/asio/test libs/asio/example diff --git a/tools/boost/asio-wasip3/boost-1.92.patch b/tools/boost/asio-wasip3/boost-1.92.patch index e439720e..949fb2d2 100644 --- a/tools/boost/asio-wasip3/boost-1.92.patch +++ b/tools/boost/asio-wasip3/boost-1.92.patch @@ -75,7 +75,7 @@ # include #else # include -+# if defined(__wasip3__) ++# if defined(__wasip2__) || defined(__wasip3__) +# include +# endif # if defined(__hpux) @@ -85,7 +85,7 @@ #elif defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) ::Sleep(INFINITE); #else -+#if defined(__wasip3__) ++#if defined(__wasip2__) || defined(__wasip3__) + // Wait through the Component Model rather than a nonexistent POSIX signal. + ::poll(0, 0, -1); +#else diff --git a/tools/boost/asio-wasip3/manifest.json b/tools/boost/asio-wasip3/manifest.json index 691b5d90..ee4d4d75 100644 --- a/tools/boost/asio-wasip3/manifest.json +++ b/tools/boost/asio-wasip3/manifest.json @@ -11,7 +11,7 @@ }, "boost/asio/detail/impl/null_event.ipp": { "before": "00b0ffc7de583ed07afe02ca249d630414c118ac2d68948cbc1a51d47c583617", - "after": "0aac40516a78403d514ec7ee98ae867a20eac3fbef683c8be556c4c7f4630447" + "after": "52999ae8533645b9d897df9cca045bccb132f57001494922443e1f50f2c5ad26" }, "boost/asio/detail/impl/resolver_thread_pool.ipp": { "before": "2c1488b04ea5cb139f0a632aa908b9ce7fe01e7c95464af2f9a16541cab31cb8", diff --git a/tools/boost/asio-wasip3/prepare.py b/tools/boost/asio-wasip3/prepare.py index 1718a008..77e121a4 100644 --- a/tools/boost/asio-wasip3/prepare.py +++ b/tools/boost/asio-wasip3/prepare.py @@ -4,7 +4,7 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Apply the checked Asio port to private headers, never to installed Boost.""" +"""Apply a checked Asio patch to private headers, never to installed Boost.""" from __future__ import annotations import argparse @@ -29,7 +29,7 @@ def prepare(source: Path, output: Path, bundle: Path) -> None: version = (source / 'boost/version.hpp').read_text() if not re.search(r'^#define BOOST_VERSION ' + str(manifest['boost_version']) + r'\s*$', version, re.MULTILINE): - raise ValueError('this WASIp3 patch requires Boost 1.92; rebase and verify the patch') + raise ValueError('this Asio patch requires Boost 1.92; rebase and verify the patch') inputs = {} for name, hashes in manifest['files'].items(): path = Path(name) @@ -37,7 +37,7 @@ def prepare(source: Path, output: Path, bundle: Path) -> None: raise ValueError('invalid patch manifest path: ' + name) data = (source / path).read_bytes() if digest(data) != hashes['before']: - raise ValueError('incompatible Boost header: ' + name + '; rebase the WASIp3 patch') + raise ValueError('incompatible Boost header: ' + name + '; rebase the Asio patch') inputs[name] = data # An obsolete patched header would still shadow its upstream replacement. # Refuse stale output rather than deleting files from a developer's checkout. @@ -73,14 +73,15 @@ def main() -> int: parser.add_argument('--boost', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--stamp', type=Path) + parser.add_argument('--bundle', type=Path, default=Path(__file__).parent) arguments = parser.parse_args() try: - prepare(arguments.boost, arguments.output, Path(__file__).parent) + prepare(arguments.boost, arguments.output, arguments.bundle) except (ValueError, OSError, subprocess.CalledProcessError) as error: - parser.exit(1, f'Asio WASIp3 preparation failed: {error}\n') + parser.exit(1, f'Asio preparation failed: {error}\n') if arguments.stamp: arguments.stamp.parent.mkdir(parents=True, exist_ok=True) - arguments.stamp.write_text('Boost.Asio WASIp3 headers verified\n') + arguments.stamp.write_text('Boost.Asio patched headers verified\n') return 0 diff --git a/tools/boost/asio-wasip3/prepare_test.py b/tools/boost/asio-wasip3/prepare_test.py index 077c8e58..6f576430 100644 --- a/tools/boost/asio-wasip3/prepare_test.py +++ b/tools/boost/asio-wasip3/prepare_test.py @@ -10,6 +10,8 @@ import importlib.machinery import importlib.util import json +import subprocess +import sys import tempfile import unittest @@ -45,6 +47,9 @@ def test_exact_inputs_idempotence_and_mismatch(self): modified = result.stat().st_mtime_ns prepare.prepare(source, output, bundle) self.assertEqual(result.stat().st_mtime_ns, modified) + subprocess.run([sys.executable, str(HERE / 'prepare.py'), '--boost', str(source), + '--output', str(output), '--bundle', str(bundle)], + check=True, capture_output=True) stale = output / 'boost/asio/removed.hpp' stale.write_text('old patch still shadows Boost\n') with self.assertRaisesRegex(ValueError, 'unexpected overlay file'): diff --git a/tools/boost/asio-wasip3/run.sh b/tools/boost/asio-wasip3/run.sh index 06702b0a..1e7f244f 100755 --- a/tools/boost/asio-wasip3/run.sh +++ b/tools/boost/asio-wasip3/run.sh @@ -10,5 +10,21 @@ # Enabling the runtime's threading feature does not create application threads. # Tests use loopback sockets and localhost resolution. Production applications # should grant only the network capabilities they need. + +# The global lane includes large finite document and Unicode workloads. Keep a +# finite default with room for shared CI workers; focused tests can lower it. +webcpp_wasip3_timeout=${WEBCPP_WASIP3_TEST_TIMEOUT-600} +case "$webcpp_wasip3_timeout" in + ''|*[!0-9]*) webcpp_wasip3_timeout= ;; +esac +case "$webcpp_wasip3_timeout" in + *[1-9]*) ;; + *) + echo 'WEBCPP_WASIP3_TEST_TIMEOUT must be a positive integer number of seconds' >&2 + exit 2 + ;; +esac + exec wasmtime run -S p3 -S inherit-network=y -S allow-ip-name-lookup=y \ - -W component-model-async=y -W component-model-threading=y -W timeout=15s "$@" + -W component-model-async=y -W component-model-threading=y \ + -W "timeout=${webcpp_wasip3_timeout}s" "$@" diff --git a/tools/boost/asio-wasip3/run_test.py b/tools/boost/asio-wasip3/run_test.py new file mode 100644 index 00000000..d7169b93 --- /dev/null +++ b/tools/boost/asio-wasip3/run_test.py @@ -0,0 +1,108 @@ +# 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) + +"""Exercise the launcher boundary without compiling a Wasm guest in every tools job.""" + +from __future__ import annotations + +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +LAUNCHER = Path(__file__).resolve().with_name('run.sh') +TIMEOUT = 'WEBCPP_WASIP3_TEST_TIMEOUT' + + +class Launcher(unittest.TestCase): + def invoke(self, timeout: str | None = None, *arguments: str, + status: int = 0) -> tuple[subprocess.CompletedProcess[str], list[str] | None]: + with tempfile.TemporaryDirectory(prefix='wasip3 launcher ') as directory: + root = Path(directory) + capture = root / 'arguments' + runtime = root / 'wasmtime' + runtime.write_text( + '#!/usr/bin/env sh\n' + 'printf "%s\\0" "$@" > "$WEBCPP_RUN_TEST_CAPTURE"\n' + 'exit "$WEBCPP_RUN_TEST_STATUS"\n') + runtime.chmod(0o755) + environment = dict(os.environ) + environment.pop(TIMEOUT, None) + environment.update({ + 'PATH': str(root) + os.pathsep + environment.get('PATH', ''), + 'WEBCPP_RUN_TEST_CAPTURE': str(capture), + 'WEBCPP_RUN_TEST_STATUS': str(status), + }) + if timeout is not None: + environment[TIMEOUT] = timeout + result = subprocess.run( + ['sh', str(LAUNCHER), *arguments], env=environment, + capture_output=True, text=True, check=False, timeout=10) + received = (capture.read_bytes().decode().split('\0')[:-1] + if capture.exists() else None) + return result, received + + def test_default_allows_the_complete_suite_and_preserves_capabilities(self): + result, arguments = self.invoke(None, 'finite workload.wasm') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(arguments, [ + 'run', '-S', 'p3', '-S', 'inherit-network=y', + '-S', 'allow-ip-name-lookup=y', '-W', 'component-model-async=y', + '-W', 'component-model-threading=y', '-W', 'timeout=600s', + 'finite workload.wasm', + ]) + + def test_a_focused_test_can_choose_a_shorter_finite_timeout(self): + result, arguments = self.invoke('15', 'loopback.wasm') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIsNotNone(arguments) + self.assertIn('timeout=15s', arguments or []) + + def test_a_large_workload_can_choose_a_longer_finite_timeout(self): + result, arguments = self.invoke('900', 'large.wasm') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIsNotNone(arguments) + self.assertIn('timeout=900s', arguments or []) + + def test_invalid_bounds_fail_before_starting_the_guest(self): + for timeout in ('', '0', '000', '-1', '1.5', '15s', 'none', ' 15', '15\n'): + with self.subTest(timeout=timeout): + result, arguments = self.invoke(timeout, 'guest.wasm') + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn(TIMEOUT, result.stderr) + self.assertIn('positive integer', result.stderr) + self.assertIsNone(arguments) + + def test_forwards_runtime_options_guest_arguments_and_exit_status(self): + forwarded = ['--dir', 'host path::guest path', 'program.wasm', '--', + 'argument with spaces', '', '*'] + result, arguments = self.invoke('30', *forwarded, status=7) + self.assertEqual(result.returncode, 7, result.stderr) + self.assertIsNotNone(arguments) + self.assertEqual((arguments or [])[-len(forwarded):], forwarded) + + @unittest.skipUnless(shutil.which('wasmtime'), 'wasmtime is not on PATH') + def test_real_runtime_completes_a_guest_and_interrupts_an_infinite_loop(self): + with tempfile.TemporaryDirectory(prefix='wasip3 execution ') as directory: + guest = Path(directory) / 'guest.wat' + environment = {**os.environ, TIMEOUT: '1'} + for body, succeeds in (('', True), ('(loop $forever (br $forever))', False)): + with self.subTest(succeeds=succeeds): + guest.write_text(f'(module (func (export "_start") {body}))\n') + result = subprocess.run( + ['sh', str(LAUNCHER), str(guest)], env=environment, + capture_output=True, text=True, check=False, timeout=30) + if succeeds: + self.assertEqual(result.returncode, 0, result.stderr) + else: + self.assertNotEqual(result.returncode, 0) + self.assertIn('wasm trap: interrupt', result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/boost/asio-windows/Jamfile b/tools/boost/asio-windows/Jamfile new file mode 100644 index 00000000..6c800fa4 --- /dev/null +++ b/tools/boost/asio-windows/Jamfile @@ -0,0 +1,33 @@ +# 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) + +import make ; + +project /webcpp/asio-windows ; +path-constant BUNDLE : . ; +path-constant OVERLAY : ../../../bin/boost-asio-windows ; + +make prepared.stamp : ../asio-wasip3/prepare.py manifest.json boost-1.92.patch : @prepare + : $(OVERLAY) off ; +always prepared.stamp ; +explicit prepared.stamp ; + +rule prepare ( targets * : sources * : properties * ) +{ + SCRIPT on $(targets) = $(BUNDLE)/../asio-wasip3/prepare.py ; + BUNDLE on $(targets) = $(BUNDLE) ; + HEADERS on $(targets) = $(WEBCPP_BOOST_HEADERS) ; + OUTPUT on $(targets) = $(OVERLAY)/include ; +} + +actions prepare +{ + python3 "$(SCRIPT)" --boost "$(HEADERS)" --output "$(OUTPUT)" --bundle "$(BUNDLE)" --stamp "$(<)" +} + +alias headers : : : : prepared.stamp + "-I\"$(OVERLAY)/include\"" ; +explicit headers ; diff --git a/tools/boost/asio-windows/README.md b/tools/boost/asio-windows/README.md new file mode 100644 index 00000000..00f9f654 --- /dev/null +++ b/tools/boost/asio-windows/README.md @@ -0,0 +1,19 @@ +# Boost.Asio 1.92 Windows allocator correction + +The IOCP context starts an internal worker when requested and starts its timer +thread on the first timer registration. Both upstream thread constructors use +the default allocator for their callable state, even when the context has a +supplied allocator. The patch passes the context allocator into `win_thread`'s +existing allocator-aware overload. Thread scheduling and shutdown are unchanged. + +The Asio and compiled Cobalt targets select this private overlay only for +`target-os=windows`. Its manifest pins both the original and resulting file +hashes. Preparation reuses the checked Asio patch tool and never edits installed +Boost. An incompatible Boost version or modified header is rejected. + +`allocation_native` and `allocation_native_release` remain the runtime +regressions. They construct a new context and its first timer inside the counted +window and require zero allocations through global `operator new`. The build +regression `test_asio_windows_allocator_overlay_reaches_sources_and_consumers` +checks that the overlay reaches both consumers and compiled Cobalt and is absent +for other targets. diff --git a/tools/boost/asio-windows/boost-1.92.patch b/tools/boost/asio-windows/boost-1.92.patch new file mode 100644 index 00000000..4fe0249d --- /dev/null +++ b/tools/boost/asio-windows/boost-1.92.patch @@ -0,0 +1,22 @@ +--- a/boost/asio/detail/impl/win_iocp_io_context.ipp ++++ b/boost/asio/detail/impl/win_iocp_io_context.ipp +@@ -108,7 +108,8 @@ + if (own_thread) + { + ::InterlockedIncrement(&outstanding_work_); +- thread_ = thread(thread_function(this)); ++ thread_ = thread(std::allocator_arg, execution_context::allocator(ctx), ++ thread_function(this)); + } + } + +@@ -598,7 +599,8 @@ + if (!timer_thread_.joinable()) + { + timer_thread_function thread_function = { this }; +- timer_thread_ = thread(thread_function, 65536); ++ timer_thread_ = thread(std::allocator_arg, ++ execution_context::allocator(this->context()), thread_function, 65536); + } + } + diff --git a/tools/boost/asio-windows/manifest.json b/tools/boost/asio-windows/manifest.json new file mode 100644 index 00000000..4a18d42d --- /dev/null +++ b/tools/boost/asio-windows/manifest.json @@ -0,0 +1,9 @@ +{ + "boost_version": 109200, + "files": { + "boost/asio/detail/impl/win_iocp_io_context.ipp": { + "before": "d05a5e4fbb540eb13eb8e3165614177407fbed564e3a3bbbeca0b5b9ae0247f3", + "after": "0d77d743e222e71145abdfc8d968d275b66b9550f8416aa4724561f86085ba19" + } + } +} diff --git a/tools/boost/cobalt-common/boost-1.92.patch b/tools/boost/cobalt-common/boost-1.92.patch index a65cb319..3813acd7 100644 --- a/tools/boost/cobalt-common/boost-1.92.patch +++ b/tools/boost/cobalt-common/boost-1.92.patch @@ -9,3 +9,40 @@ } void unhandled_exception() { throw ; } +--- a/boost/cobalt/detail/main.hpp ++++ b/boost/cobalt/detail/main.hpp +@@ -13,6 +13,7 @@ + #include + + #include ++#include + + + namespace boost::asio +@@ -26,10 +27,17 @@ + namespace boost::cobalt::detail + { + ++#if defined(__clang__) && defined(__wasip3__) ++#pragma clang diagnostic push ++#pragma clang diagnostic ignored "-Wmain" ++#endif + extern "C" + { + int main(int argc, char * argv[]); + } ++#if defined(__clang__) && defined(__wasip3__) ++#pragma clang diagnostic pop ++#endif + + struct signal_helper + { +@@ -92,6 +100,8 @@ + + #if !defined(BOOST_NO_EXCEPTIONS) + void unhandled_exception() { throw ; } ++#else ++ void unhandled_exception() noexcept { std::terminate(); } + #endif + void return_value(int res = 0) + { diff --git a/tools/boost/cobalt-common/manifest.json b/tools/boost/cobalt-common/manifest.json index 03409026..6035f0a8 100644 --- a/tools/boost/cobalt-common/manifest.json +++ b/tools/boost/cobalt-common/manifest.json @@ -4,6 +4,10 @@ "boost/cobalt/composition.hpp": { "before": "4f89225430772cc39a82e37ec1b67069b342fa77423b3f6ad74edc3d8d1a77c5", "after": "a4d22f4619cad58063473d0e86a31dfbbfd4856b57d59c22e1c18ec0ccfabe1b" + }, + "boost/cobalt/detail/main.hpp": { + "before": "fbdcb0ca58d8a368b8e4ec680dc99bcdd6ce2a2c5375770e278dec1dec91afcb", + "after": "2a55b2e808068c0aaef80ab257f462ab9d61f7d3d59ef0ede23ed6b56046bdf5" } } } diff --git a/tools/boost/cobalt-wasip3/boost-1.92.patch b/tools/boost/cobalt-wasip3/boost-1.92.patch index f70e24d4..73517bdf 100644 --- a/tools/boost/cobalt-wasip3/boost-1.92.patch +++ b/tools/boost/cobalt-wasip3/boost-1.92.patch @@ -1,23 +1,3 @@ ---- a/boost/cobalt/detail/main.hpp -+++ b/boost/cobalt/detail/main.hpp -@@ -26,10 +26,17 @@ - namespace boost::cobalt::detail - { - -+#if defined(__clang__) -+#pragma clang diagnostic push -+#pragma clang diagnostic ignored "-Wmain" -+#endif - extern "C" - { - int main(int argc, char * argv[]); - } -+#if defined(__clang__) -+#pragma clang diagnostic pop -+#endif - - struct signal_helper - { --- a/boost/cobalt/io/acceptor.hpp +++ b/boost/cobalt/io/acceptor.hpp @@ -54,6 +54,7 @@ diff --git a/tools/boost/cobalt-wasip3/manifest.json b/tools/boost/cobalt-wasip3/manifest.json index a1fc9448..9b9b2d9d 100644 --- a/tools/boost/cobalt-wasip3/manifest.json +++ b/tools/boost/cobalt-wasip3/manifest.json @@ -1,10 +1,6 @@ { "boost_version": 109200, "files": { - "boost/cobalt/detail/main.hpp": { - "before": "fbdcb0ca58d8a368b8e4ec680dc99bcdd6ce2a2c5375770e278dec1dec91afcb", - "after": "8626f94300962cc0ff674c8f5df5e6ca171254aad34f8964a159d2e327684fe9" - }, "boost/cobalt/io/acceptor.hpp": { "before": "d4288bd7bfd6953c15fdfac09a8caff56c7e78fceebe2c5b9f232daff8736c18", "after": "33c3aa0fa45184a555353153c08f4950b81209221791ec43759ab783fc7ba6fd" diff --git a/tools/ci/actions/boost/install.sh b/tools/ci/actions/boost/install.sh index 870f2a51..9f9f6eca 100755 --- a/tools/ci/actions/boost/install.sh +++ b/tools/ci/actions/boost/install.sh @@ -189,7 +189,7 @@ check() { missing=1 else local library - for library in url charconv locale cobalt; do + for library in url charconv locale cobalt context; do [ -d "${prefix}/source/libs/${library}/src" ] || missing=1 done fi diff --git a/tools/ci/actions/chrome/action.yml b/tools/ci/actions/chrome/action.yml index ccd3a4a8..7dac8ca5 100644 --- a/tools/ci/actions/chrome/action.yml +++ b/tools/ci/actions/chrome/action.yml @@ -6,14 +6,21 @@ name: Chrome description: >- - Installs Chrome for Testing's chrome-headless-shell 155.0.8059.39 in .local/chrome-headless-shell, + Installs Chrome for Testing 155.0.8059.39 in .local/, checked against its SHA-256, and gives the later steps CHROME, a wrapper that runs it without its sandbox (install.sh says why): the Chrome a driven test runs when its driver meets a browser, - as trystero's interop lane does. On Linux. + as trystero's interop lane does. Full Chrome supports isolated certificate trust profiles. On Linux. + +inputs: + product: + description: chrome-headless-shell, or chrome for certificate-profile tests + default: chrome-headless-shell runs: using: composite steps: - - name: chrome-headless-shell 155.0.8059.39 + - name: Chrome for Testing 155.0.8059.39 shell: bash + env: + WEBCPP_CHROME_PRODUCT: ${{ inputs.product }} run: bash tools/ci/actions/chrome/install.sh diff --git a/tools/ci/actions/chrome/install.sh b/tools/ci/actions/chrome/install.sh index 52592512..ab7fdb65 100644 --- a/tools/ci/actions/chrome/install.sh +++ b/tools/ci/actions/chrome/install.sh @@ -5,8 +5,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# The step of tools/ci/actions/chrome: Chrome for Testing's chrome-headless-shell at a pinned -# version, in .local/chrome-headless-shell, and CHROME given to the job's later steps, the Chrome +# The step of tools/ci/actions/chrome: Chrome for Testing at a pinned +# version, in .local/, and CHROME given to the job's later steps, the Chrome # that a driven test runs when its driver meets a browser (trystero's interop lane), on Linux, X64 # and ARM64. # @@ -38,48 +38,59 @@ set -euo pipefail version=155.0.8059.39 +product="${WEBCPP_CHROME_PRODUCT:-chrome-headless-shell}" +case "${product}" in + chrome-headless-shell|chrome) ;; + *) printf 'install.sh: unsupported Chrome product: %s\n' "${product}" >&2; exit 1 ;; +esac base="https://storage.googleapis.com/chrome-for-testing-public/${version}" case "${RUNNER_OS-}-${RUNNER_ARCH-}" in Linux-X64) build=linux64 sha256=39dcb8c46550632a3d911850ab3b8af840b4e3f6d8622faa2018eb8756278786 + if [ "${product}" = chrome ]; then + sha256=55672d1f392fd3e7b7a08621b6e804e6bcb39d40cf155504abb74b3a021ea8ea + fi ;; Linux-ARM64) build=linux-arm64 sha256=9fb86f7c0b2734c5febc0bbb4e85f37da43553f3f8a7970949828c5713e87e94 + if [ "${product}" = chrome ]; then + sha256=b9d44e5d183260ca941a4c4d8d21c8a437d81ef778a489047ef98968b0475dc5 + fi ;; *) - printf 'install.sh: no chrome-headless-shell %s is pinned for %s on %s: the action ' \ - "${version}" "${RUNNER_OS-}" "${RUNNER_ARCH-}" >&2 + printf 'install.sh: no %s %s is pinned for %s on %s: the action ' \ + "${product}" "${version}" "${RUNNER_OS-}" "${RUNNER_ARCH-}" >&2 printf 'runs on Linux, on X64 and ARM64\n' >&2 exit 1 ;; esac here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -asset="chrome-headless-shell-${build}.zip" +asset="${product}-${build}.zip" "${here}/../../download.sh" "${base}/${build}/${asset}" "${sha256}" "${RUNNER_TEMP}/${asset}" -rm -rf .local/chrome-headless-shell -mkdir -p .local/chrome-headless-shell -unzip -q "${RUNNER_TEMP}/${asset}" -d .local/chrome-headless-shell +rm -rf ".local/${product}" +mkdir -p ".local/${product}" +unzip -q "${RUNNER_TEMP}/${asset}" -d ".local/${product}" rm "${RUNNER_TEMP}/${asset}" -directory="$(cd ".local/chrome-headless-shell/chrome-headless-shell-${build}" && pwd -P)" -shell="${directory}/chrome-headless-shell" +directory="$(cd ".local/${product}/${product}-${build}" && pwd -P)" +shell="${directory}/${product}" [ -x "${shell}" ] || { - printf 'install.sh: %s holds no chrome-headless-shell-%s/chrome-headless-shell\n' "${asset}" \ - "${build}" >&2 - rm -rf .local/chrome-headless-shell + printf 'install.sh: %s holds no %s-%s/%s\n' "${asset}" \ + "${product}" "${build}" "${product}" >&2 + rm -rf ".local/${product}" exit 1 } -wrapper="$(cd .local/chrome-headless-shell && pwd -P)/chrome" +wrapper="$(cd ".local/${product}" && pwd -P)/chrome" { printf '#!/bin/sh\n' - printf '# Written by tools/ci/actions/chrome: chrome-headless-shell %s, without its sandbox ' \ - "${version}" + printf '# Written by tools/ci/actions/chrome: %s %s, without its sandbox ' \ + "${product}" "${version}" printf '(install.sh says why).\n' printf 'exec "%s" --no-sandbox "$@"\n' "${shell}" } > "${wrapper}" chmod 755 "${wrapper}" printf 'CHROME=%s\n' "${wrapper}" >> "${GITHUB_ENV}" -printf 'install.sh: chrome-headless-shell %s in %s, CHROME=%s\n' "${version}" "${directory}" \ +printf 'install.sh: %s %s in %s, CHROME=%s\n' "${product}" "${version}" "${directory}" \ "${wrapper}" diff --git a/tools/ci/actions_test.py b/tools/ci/actions_test.py index 679ec337..fe0b9af7 100755 --- a/tools/ci/actions_test.py +++ b/tools/ci/actions_test.py @@ -260,6 +260,8 @@ def boost_archive(scratch: Path) -> Path: ('libs/cobalt/src/detail/util.cpp', '// cobalt detail\n'), ('libs/cobalt/src/io/sleep.cpp', '// cobalt io\n'), ('libs/cobalt/src/io/ssl.cpp', '// cobalt ssl\n'), + ('libs/context/src/asm/jump_arm64_aapcs_macho_gas.S', '// context asm\n'), + ('libs/context/src/posix/stack_traits.cpp', '// context stack\n'), ('libs/url/doc/index.html', '

not kept

\n')): (tree / path).parent.mkdir(parents=True, exist_ok=True) (tree / path).write_text(text) @@ -322,7 +324,9 @@ def test_boost_install_fails_when_the_prefix_is_incomplete(scratch: Path) -> Non KEPT_SOURCES = [MARKER, 'boost/version.hpp', 'libs/charconv/src/from_chars.cpp', 'libs/cobalt/src/detail/util.cpp', 'libs/cobalt/src/io/sleep.cpp', 'libs/cobalt/src/io/ssl.cpp', 'libs/cobalt/src/main.cpp', - 'libs/cobalt/src/this_thread.cpp', 'libs/json/src/src.cpp', + 'libs/cobalt/src/this_thread.cpp', + 'libs/context/src/asm/jump_arm64_aapcs_macho_gas.S', + 'libs/context/src/posix/stack_traits.cpp', 'libs/json/src/src.cpp', 'libs/locale/src/message.cpp', 'libs/url/src/detail/pattern.hpp', 'libs/url/src/url.cpp'] @@ -368,7 +372,8 @@ def test_boost_configure_refuses_a_cached_prefix_with_stale_sources(scratch: Pat prefix = scratch / 'prefix' result = run(script, 'install', prefix, env=runner) assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) - for stale in ((prefix / 'source' / MARKER), (prefix / 'source/libs/cobalt/src')): + for stale in ((prefix / 'source' / MARKER), (prefix / 'source/libs/cobalt/src'), + (prefix / 'source/libs/context/src')): kept = scratch / 'kept' shutil.move(stale, kept) result = subprocess.run(['bash', str(script), 'configure', str(prefix)], @@ -1673,15 +1678,15 @@ def test_openssl_on_macos_installs_openssl_3_when_the_image_lacks_it(scratch: Pa } -def chrome_archive(scratch: Path, build: str) -> Path: +def chrome_archive(scratch: Path, build: str, product: str = 'chrome-headless-shell') -> Path: """A stand-in of the shell's zip: its top directory, a program that prints its arguments, and the files beside it.""" - archive = scratch / f'chrome-headless-shell-{build}.zip' + archive = scratch / f'{product}-{build}.zip' with zipfile.ZipFile(archive, 'w') as zipped: - program = zipfile.ZipInfo(f'chrome-headless-shell-{build}/chrome-headless-shell') + program = zipfile.ZipInfo(f'{product}-{build}/{product}') program.external_attr = 0o755 << 16 zipped.writestr(program, '#!/bin/sh\necho "shell $*"\n') - zipped.writestr(f'chrome-headless-shell-{build}/ABOUT', 'about\n') + zipped.writestr(f'{product}-{build}/ABOUT', 'about\n') return archive @@ -1711,6 +1716,38 @@ def test_chrome_installs_the_pinned_headless_shell(scratch: Path) -> None: assert f'chrome-headless-shell {CHROME_VERSION}' in result.stdout, result.stdout +def test_chrome_installs_full_chrome_for_isolated_certificate_trust(scratch: Path) -> None: + builds = { + 'X64': ('linux64', '55672d1f392fd3e7b7a08621b6e804e6bcb39d40cf155504abb74b3a021ea8ea'), + 'ARM64': ('linux-arm64', + 'b9d44e5d183260ca941a4c4d8d21c8a437d81ef778a489047ef98968b0475dc5'), + } + for processor, (build, digest) in builds.items(): + root = scratch / processor + root.mkdir() + url = (f'https://storage.googleapis.com/chrome-for-testing-public/{CHROME_VERSION}/{build}/' + f'chrome-{build}.zip') + archive = chrome_archive(root, build, 'chrome') + script = serving_tree(root, 'chrome', CHROME, {url: archive}) + runner = dependency_runner(root, 'Linux', processor, stand_ins(root, {})) + runner['WEBCPP_CHROME_PRODUCT'] = 'chrome' + result = dependency_step(root, script, runner) + assert result.returncode == 0, (processor, result.stderr) + assert downloads(root) == [(url, digest)], downloads(root) + wrapper = root.resolve() / '.local/chrome/chrome' + assert (root / 'github-env').read_text() == f'CHROME={wrapper}\n' + ran = subprocess.run([str(wrapper), '--headless=new'], capture_output=True, + text=True, check=False) + assert (ran.returncode, ran.stdout) == (0, 'shell --no-sandbox --headless=new\n'), ran + (root / 'tools/ci/download.sh').write_text( + f'#!/bin/sh\nexec bash "{DOWNLOAD}" "{archive.as_uri()}" "$2" "$3"\n') + result = dependency_step(root, script, runner) + assert result.returncode == 1 and f'and {digest} is pinned' in result.stderr, result + runner['WEBCPP_CHROME_PRODUCT'] = '../invalid' + result = dependency_step(root, script, runner) + assert result.returncode == 1 and 'unsupported Chrome product' in result.stderr, result + + def test_chrome_refuses_a_shell_it_does_not_pin_or_a_runner_it_has_none_for(scratch: Path) -> None: build, digest = CHROME_BUILDS['X64'] url = (f'https://storage.googleapis.com/chrome-for-testing-public/{CHROME_VERSION}/{build}/' @@ -1891,6 +1928,7 @@ def helper(call: str, **variables: str) -> str: test_openssl_refuses_one_that_is_not_3_or_a_runner_it_has_none_for, test_container_builds_the_image_once_and_loads_it_after, test_chrome_installs_the_pinned_headless_shell, + test_chrome_installs_full_chrome_for_isolated_certificate_trust, test_chrome_refuses_a_shell_it_does_not_pin_or_a_runner_it_has_none_for, ] diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 8e82b4b6..09bcf84f 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -190,8 +190,10 @@ def container_tag() -> str: # The own lanes whose driver meets a browser, (library, lane), which the CI's chrome action gives # its pinned chrome-headless-shell, as CHROME: trystero's interop, natively and on emscripten, and -# document's js, whose examples Playwright runs in Chrome, and asio's browser lane. -CHROME_LANES = {('asio', 'browser'), ('document', 'js'), ('trystero', 'interop')} +# document's js, whose examples Playwright runs in Chrome, and the browser and +# chat applications whose fixture connects Chrome to native or WASI servers. +CHROME_LANES = {('asio', 'browser'), ('beast', 'browser'), ('beast', 'applications-browser'), + ('beast', 'applications-chat'), ('document', 'js'), ('trystero', 'interop')} # 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 diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index c84e5e6d..4ac7244b 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -1140,6 +1140,14 @@ def test_asio_browser_lane_receives_chrome(root): entry = own_lane_entry_of(own) assert entry['chrome'] is True, entry + for lane, platform in (('browser', 'emscripten'), + ('applications-browser', 'emscripten'), + ('applications-chat', 'native'), + ('applications-chat', 'wasip3')): + beast = matrix.OwnLane('beast', lane, ('libs/beast/test/browser',), + platform, 'original') + assert own_lane_entry_of(beast)['chrome'] is True, (lane, platform) + def test_a_browser_lane_has_the_pinned_chrome(root): # An own lane whose driver meets a browser, asio's browser, trystero's interop and document's js @@ -1147,7 +1155,9 @@ def test_a_browser_lane_has_the_pinned_chrome(root): # chrome-headless-shell, which gives CHROME; no other own lane does, and no job names the # image's Chrome. assert matrix.CHROME_LANES == { - ('asio', 'browser'), ('document', 'js'), ('trystero', 'interop')}, matrix.CHROME_LANES + ('asio', 'browser'), ('beast', 'browser'), ('beast', 'applications-browser'), + ('beast', 'applications-chat'), ('document', 'js'), + ('trystero', 'interop')}, matrix.CHROME_LANES boost_only(root) external_library(root) oracle_library(root, 'beta') @@ -1157,6 +1167,7 @@ def test_a_browser_lane_has_the_pinned_chrome(root): steps = job_steps(workflow_jobs()['own-lanes']) chrome = [step for step in steps if 'uses: ./tools/ci/actions/chrome' in step] assert len(chrome) == 1 and 'if: matrix.chrome\n' in chrome[0], chrome + assert "matrix.library == 'beast' && 'chrome' || 'chrome-headless-shell'" in chrome[0], chrome workflow = (harness.ROOT / '.github/workflows/library.yml').read_text() assert '/usr/bin/google-chrome' not in workflow # AGENTS.md names the shell's version once, the action's. @@ -1170,6 +1181,31 @@ def test_a_browser_lane_has_the_pinned_chrome(root): assert set(re.findall(r'\d+\.\d+\.\d+\.\d+', action)) == {pinned.group(1)}, action +def test_host_tls_fixture_is_isolated_to_its_own_lane(root): + steps = job_steps(workflow_jobs()['own-lanes']) + fixture = [step for step in steps if 'WASI HTTPS host fixture' in step] + assert len(fixture) == 3, fixture + assert all("matrix.library == 'beast' && matrix.lane == 'applications-host-tls'" + in step for step in fixture), fixture + build = next(step for step in fixture if 'cargo +1.97.1 build' in step) + assert 'build --locked --jobs 2' in build and 'WEBCPP_WASI_TLS_FIXTURE=' in build, build + assert 'rustup toolchain install 1.97.1 --profile minimal' in build, build + restore = next(step for step in fixture if 'cache/restore' in step) + assert 'Cargo.lock' in restore and 'Cargo.toml' in restore and 'src/**' in restore, restore + + +def test_browser_contract_lanes_build_a_native_beast_peer(root): + steps = job_steps(workflow_jobs()['own-lanes']) + peers = [step for step in steps if 'Build the native Beast interoperability peer' in step] + assert len(peers) == 1, peers + peer = peers[0] + assert "matrix.library == 'beast'" in peer and "matrix.lane == 'browser-node'" in peer, peer + assert "matrix.lane == 'browser'" in peer, peer + assert 'tools/ci/matrix.py register clang-18' in peer, peer + assert 'libs/beast/test/browser/peer//native_peer-program' in peer, peer + assert 'toolset=clang-18 threading=multi' in peer, peer + + # A stand-in of docker: each call's words to docker.log, quoted as a shell reads them, one line # each; `image inspect` succeeds when STAND_IN_IMAGE_PRESENT is set, `build` builds nothing, and # `run` runs, on the host, the command after the image. @@ -1361,6 +1397,8 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): test_a_container_lane_has_its_image_from_the_cache, test_asio_browser_lane_receives_chrome, test_a_browser_lane_has_the_pinned_chrome, + test_host_tls_fixture_is_isolated_to_its_own_lane, + test_browser_contract_lanes_build_a_native_beast_peer, test_container_apt_get_retries_transient_failures, test_a_container_lane_runs_b2_with_no_network, test_a_container_lane_whose_image_does_not_build_fails, diff --git a/tools/component/component.jam b/tools/component/component.jam index 69745c2f..fb9a9374 100644 --- a/tools/component/component.jam +++ b/tools/component/component.jam @@ -637,7 +637,13 @@ rule serve-and-compare ( target : source : properties * ) local version = [ version-of $(properties) ] ; PYTHON on $(target) = $(.python) ; SERVER on $(target) = $(.server) ; - FLAGS on $(target) = $(.wasmtime-flags.$(version)) ; + local flags = $(.wasmtime-flags.$(version)) ; + if $(version) = p3 && multi in $(properties) + { + # Cooperative wasi-sdk libc uses context slot 1 in a component task. + flags = "$(flags) -W component-model-threading" ; + } + FLAGS on $(target) = $(flags) ; PROGRAM on $(target) = [ quoted $(.served.$(key)) ] ; # Empty, or the two words --wasmtime '': a word made only of an # empty variable disappears, as run-and-compare's LAUNCHER_ARGS does. diff --git a/tools/doc/counts.py b/tools/doc/counts.py index 8365a4a0..c4a90a4a 100755 --- a/tools/doc/counts.py +++ b/tools/doc/counts.py @@ -61,7 +61,7 @@ SELF = 'tools/doc/counts.py' KINDS = ('example', 'run', 'run-fail', 'compile', 'compile-fail', 'compile-diagnostic', - 'boost-test', 'headers-alone', 'serve', 'link', 'drive') + 'boost-test', 'headers-alone', 'serve', 'link', 'link-fail', 'drive') TARGETS = ('native', 'emscripten', 'wasip2', 'wasip3') # What each generic count is counted from, by its name, as a fault names it. diff --git a/tools/doc/counts_test.py b/tools/doc/counts_test.py index 1e660223..3bf72f53 100755 --- a/tools/doc/counts_test.py +++ b/tools/doc/counts_test.py @@ -280,6 +280,17 @@ def test_a_compile_diagnostic_is_a_test(root: Path) -> None: found['n-tests-wasip3']) == ('10', '10', '7', '6'), found +def test_a_negative_link_is_counted_on_its_declared_targets(root: Path) -> None: + directory = library(root, 'demo') + baseline = counted(count(directory, DEMO_PROGRAMS)) + more = (*DEMO_PROGRAMS, 'link-fail policy_boundary native emscripten') + found = counted(count(directory, more)) + for key in ('n-tests', 'n-tests-native', 'n-tests-emscripten'): + assert int(found[key]) == int(baseline[key]) + 1, found + for key in ('n-tests-wasip2', 'n-tests-wasip3', 'n-headers', 'n-examples'): + assert found[key] == baseline[key], found + + def test_library_counts_are_added(root: Path) -> None: directory = library(root, 'demo') own_counts(directory, 'import sys\n' @@ -361,6 +372,7 @@ def test_usage_errors_exit_2(root: Path) -> None: test_twins_list_faults_fail, test_headers_are_those_compiled_alone, test_a_compile_diagnostic_is_a_test, + test_a_negative_link_is_counted_on_its_declared_targets, test_served_programs_are_tests_and_counted, test_linked_and_driven_programs_are_tests_and_counted, test_library_counts_are_added, diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index b7ac85b5..3f0188a5 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -142,7 +142,7 @@ # A program can need one on a target that the library's native aggregate never prepares. BOOST_OVERLAYS = { f'bin/boost-{name}/include': f'tools/boost/{name}//prepared.stamp' - for name in ('asio-wasip3', 'cobalt-common', 'cobalt-wasip3', 'cobalt-ssl') + for name in ('asio-wasip3', 'asio-windows', 'cobalt-common', 'cobalt-wasip3', 'cobalt-ssl') } # The property of the request that builds a program without exceptions as a user asks b2 for one, @@ -607,6 +607,11 @@ def prepare_boost_overlays(root: str, target: str, commands: list[list[str]]) -> 'while preparing checked Boost overlays') +def source_path(root: str, source: str) -> str: + """The physical source's path relative to root, independent of its Jamfile's spelling.""" + return os.path.relpath(os.path.realpath(os.path.join(root, source)), os.path.realpath(root)) + + def read(root: str, target: str, commands: list[list[str]], entries: list[dict[str, object]], seen: set[tuple[str, ...]], earlier: set[str], wasi_clang: str | None) -> tuple[Units, set[str]]: @@ -626,6 +631,8 @@ def read(root: str, target: str, commands: list[list[str]], entries: list[dict[s units.setdefault(unit.group(1), {}).setdefault(unit.group(2), []).append(words) if source.startswith(f'{BUILD_DIR}/') or not of_the_tree(root, source): continue + source = source_path(root, source) + words = [*words[:-1], source] sources.add(source) key = tuple(without_output(words)) if source in earlier or key in seen: @@ -739,8 +746,11 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni unit = ALONE.match(source) if unit: without.setdefault(unit.group(1), {}).setdefault(unit.group(2), []).append(words) - if (source.startswith(f'{BUILD_DIR}/') or not of_the_tree(root, source) - or first.setdefault(source, target) != target): + if source.startswith(f'{BUILD_DIR}/') or not of_the_tree(root, source): + continue + source = source_path(root, source) + words = [*words[:-1], source] + if first.setdefault(source, target) != target: continue if NO_EXCEPTIONS not in words: kept.add(source) diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index fa920419..42584d93 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -134,6 +134,18 @@ for library in libs/*/; do fi done +# Keep the exact upstream Beast oracle's notices and style. Its pinned inventory +# must validate before this one directory is excluded; adaptations remain linted. +beast_corpus_verified=false +if [ -d libs/beast/example/upstream ]; then + rule 'upstream corpus integrity' + if python3 libs/beast/test/applications/inventory.py --check; then + beast_corpus_verified=true + else + fail 'the pinned Boost.Beast application corpus failed its integrity check' + fi +fi + # Every file of the repositories that is there, relative to the root, sorted, NUL-separated. # The index can name a path a move has not been staged for yet, and a submodule is listed as a # directory; neither is a file. A symbolic link is not read either: its text is a path. @@ -146,6 +158,8 @@ for repository in "${repositories[@]}"; do fi case "${path}" in third_party/libs/*) continue ;; + libs/beast/example/upstream/*) + if [ "${beast_corpus_verified}" = true ]; then continue; fi ;; esac if [ -f "${path}" ] && [ ! -L "${path}" ]; then printf '%s\0' "${path}" diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index ae841760..d9ce26f2 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -372,6 +372,29 @@ def test_compile_database_lists_what_b2_builds(root): WORLD = 'libs/component_demo/include/webcpp/component_demo/world.hpp' +def test_compile_database_normalizes_shared_source_paths(root): + # Separate Jamfiles can name the same physical source through different ../ paths. + # The native command must win over WASI, including its exception-free twin. + prepare(root) + write(root, 'libs/demo/example/shared.cpp', CPP + '\nint main() {\n return 0;\n}\n') + for directory, target in (('native_shared', 'native'), ('wasi_shared', 'wasip2')): + write(root, f'libs/demo/test/{directory}/Jamfile', HASH + '\nimport webcpp ;\n' + f'webcpp.targets {target} ;\n' + 'webcpp.compile shared : ../../example/shared.cpp ;\n') + append(root, 'libs/demo/test/Jamfile', f'build-project {directory} ;\n') + completed = compile_database(root) + assert completed.returncode == 0, completed.stdout[-6000:] + source = (root / 'libs/demo/example/shared.cpp').resolve() + entries = [entry for entry in json.loads( + (root / 'compile database/compile_commands.json').read_text()) + if Path(entry['file']).resolve() == source] + assert len(entries) == 2, entries + assert ['-fno-exceptions' in entry['arguments'] for entry in entries] == [False, True] + for entry in entries: + assert entry['file'] == str(root / 'libs/demo/example/shared.cpp'), entry + assert not any(word.startswith('--target=wasm') for word in entry['arguments']), entry + + def test_compile_database_prepares_generated_header_dependencies(root): # A clean checkout must analyse headers that depend on generated data. # A dry run alone lists the include path but never creates its header. @@ -1608,7 +1631,7 @@ def test_raw_rules(root): f"{at(root, test, 'raw_link ;')} link is b2's own rule; a test or example Jamfile " 'declares its programs with the rules of tools/webcpp.jam, here webcpp.link\n', f"{at(root, test, 'raw_link_fail')} link-fail is b2's own rule; a test or example " - 'Jamfile declares its programs with the rules of tools/webcpp.jam, here webcpp.link\n', + 'Jamfile declares its programs with the rules of tools/webcpp.jam, here webcpp.link-fail\n', f"{at(root, example, 'raw_exe')} exe is b2's own rule; a test or example Jamfile " 'declares its programs with the rules of tools/webcpp.jam, here webcpp.example, ' 'webcpp.run or webcpp.serve\n', @@ -2109,7 +2132,29 @@ def test_third_party_code_is_never_read(root): spared=('third_party/libs/',)) +def test_beast_corpus_is_verified_before_excluding_upstream_style(root): + prepare(root) + corpus = 'libs/beast/example/upstream/original.cpp' + verifier = 'libs/beast/test/applications/inventory.py' + # Deliberately invalid WebCPP style: only a verified upstream snapshot is exempt. + write(root, corpus, 'int original(){return 42;}\n') + write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') + expect_clean(lint(root)) + # A failed integrity check must fail lint, never silently waive the corpus. + write(root, verifier, HASH + '\nimport sys\n\nsys.exit(1)\n') + result = lint(root) + assert result.returncode != 0, result.stdout + assert 'upstream corpus integrity' in FAILED.findall(result.stdout), result.stdout + # The port itself keeps normal checks, even when the upstream snapshot is valid. + write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') + adapted = 'libs/beast/example/applications/notes.txt' + write(root, adapted, EM_DASH + '\n') + expect_alone(lint(root), 'em dash', [adapted + ':1:']) + + CASES = [ + test_compile_database_normalizes_shared_source_paths, + test_beast_corpus_is_verified_before_excluding_upstream_style, test_clean_tree_passes, test_no_library_passes, test_a_user_config_the_environment_names_is_read, diff --git a/tools/lint/rules.py b/tools/lint/rules.py index d96ec412..a6f29689 100755 --- a/tools/lint/rules.py +++ b/tools/lint/rules.py @@ -119,7 +119,7 @@ def licence(path: str, text: str) -> Iterator[Finding]: 'exe': 'webcpp.example, webcpp.run or webcpp.serve', 'unit-test': 'webcpp.boost-test', 'link': 'webcpp.link', - 'link-fail': 'webcpp.link', + 'link-fail': 'webcpp.link-fail', } # The names b2 loads as a directory's Jamfile. diff --git a/tools/openssl/build.py b/tools/openssl/build.py index cfd632c7..46796fa3 100644 --- a/tools/openssl/build.py +++ b/tools/openssl/build.py @@ -30,11 +30,16 @@ HERE = Path(__file__).resolve().parent -def run(command: list[str], *, cwd: Path, env: dict[str, str], log: Path) -> None: +def run(command: list[str], *, cwd: Path, env: dict[str, str], log: Path, + timeout: float = 600) -> None: print('+ ' + shlex.join(command), flush=True) - with log.open('w') as stream: - result = subprocess.run(command, cwd=cwd, env=env, stdout=stream, - stderr=subprocess.STDOUT, timeout=600) + try: + with log.open('w') as stream: + result = subprocess.run(command, cwd=cwd, env=env, stdout=stream, + stderr=subprocess.STDOUT, timeout=timeout) + except subprocess.TimeoutExpired as error: + print(log.read_text(errors='replace')[-14000:], file=sys.stderr) + raise RuntimeError(f'command timed out after {timeout:g}s; full log: {log}') from error if result.returncode: print(log.read_text(errors='replace')[-14000:], file=sys.stderr) raise RuntimeError(f'command failed ({result.returncode}); full log: {log}') @@ -220,7 +225,11 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat '--prefix=' + str(install)], cwd=build, env=env, log=output / 'configure.log') make = ['nmake', '/nologo'] if windows else ['make'] jobs = [] if windows else ['-j' + str(min(8, os.cpu_count() or 1))] - run([*make, *jobs, 'build_libs'], cwd=build, env=env, log=output / 'build.log') + # nmake builds one translation unit at a time. Windows CI exceeded ten + # minutes while still compiling normally; retain a bounded thirty-minute + # budget for this phase. Parallel Make retains the shorter budget. + run([*make, *jobs, 'build_libs'], cwd=build, env=env, log=output / 'build.log', + timeout=1800 if windows else 600) if windows: # Upstream install_dev requires an external PDB even with B2's /Z7 # embedded symbols or debug-symbols=off. Stage exactly its public and diff --git a/tools/openssl/build_test.py b/tools/openssl/build_test.py index 07edfd35..38e14b69 100644 --- a/tools/openssl/build_test.py +++ b/tools/openssl/build_test.py @@ -50,11 +50,14 @@ def test_windows_build_installs_static_libraries_and_matching_headers(self) -> N with self.subTest(arch=arch): commands = [] environments = [] + timeouts = [] output = self.root / arch - def command(command: list[str], *, cwd: Path, env: dict, log: Path) -> None: + def command(command: list[str], *, cwd: Path, env: dict, log: Path, + timeout: float = 600) -> None: commands.append(command) environments.append(env) + timeouts.append(timeout) log.write_text('completed\n') if command[-1] == 'build_libs': (cwd / 'include/openssl').mkdir(parents=True) @@ -77,6 +80,7 @@ def command(command: list[str], *, cwd: Path, env: dict, log: Path) -> None: self.assertIn('no-asm', commands[0]) self.assertEqual(commands[1], ['nmake', '/nologo', 'build_libs']) self.assertEqual(len(commands), 2) + self.assertEqual(timeouts, [600, 1800]) self.assertEqual((output / 'libssl.lib').read_bytes(), b'ssl-' + arch.encode()) self.assertEqual((output / 'include/openssl/configuration.h').read_text(), arch) self.assertEqual((output / 'include/openssl/applink.c').read_bytes(), @@ -92,6 +96,14 @@ def command(command: list[str], *, cwd: Path, env: dict, log: Path) -> None: self.assertNotIn('CL', environments[0]) self.assertNotIn('_CL_', environments[0]) + def test_a_stalled_command_keeps_its_diagnostic_log(self) -> None: + log = self.root / 'stalled.log' + with self.assertRaisesRegex(RuntimeError, r'command timed out after 2s; full log:'): + build.run([sys.executable, '-u', '-c', + 'import time; print("last compiler output"); time.sleep(10)'], + cwd=self.root, env=os.environ.copy(), log=log, timeout=2) + self.assertEqual(log.read_text(), 'last compiler output\n') + def test_windows_target_uses_the_configured_compilers_architecture(self) -> None: for output, target in (('WEBCPP_OPENSSL_X86', 'VC-WIN32'), ('WEBCPP_OPENSSL_X64', 'VC-WIN64A'), diff --git a/tools/test/asio_wasip3_test.py b/tools/test/asio_wasip3_test.py index 9708baf7..e3d3ca41 100644 --- a/tools/test/asio_wasip3_test.py +++ b/tools/test/asio_wasip3_test.py @@ -41,6 +41,15 @@ ''' TARGET = 'libs/demo/test//wasi_configuration' +HOST_SOURCE = '''#include +#include +#include +#include +#include +#include +void host_traits() {} +''' + def fixture(root: Path) -> None: directory = root / 'libs/demo/test' @@ -82,8 +91,26 @@ def test_cooperative_profile_and_missing_exception_runtime(root: Path) -> None: harness.expect(result, False, 'requires wasi-sdk', 'experimental-coop-threads sysroot') +def test_wasip2_host_traits_without_socket_reactor(root: Path) -> None: + fixture(root) + directory = root / 'libs/demo/test' + jam = directory / 'Jamfile' + jam.write_text(jam.read_text() + ''' +webcpp.compile host_traits : host_traits.cpp + : clang-wasip2:/webcpp/asio-wasip3//host-headers ; +''') + (directory / 'host_traits.cpp').write_text(HOST_SOURCE) + for toolset in ('clang', 'clang-wasip2'): + for handling in ('on', 'off'): + result = harness.run_b2(root, '-a', f'toolset={toolset}', + f'exception-handling={handling}', + 'libs/demo/test//host_traits') + harness.expect(result, True, '**passed**') + + CASES = [test_overlay_is_wasi_only_and_precedes_stock_headers, - test_cooperative_profile_and_missing_exception_runtime] + test_cooperative_profile_and_missing_exception_runtime, + test_wasip2_host_traits_without_socket_reactor] if __name__ == '__main__': sys.exit(harness.run_cases('asio_wasip3_test', CASES, sys.argv[1:])) diff --git a/tools/test/boost_libraries_test.py b/tools/test/boost_libraries_test.py index a7ace816..0653cabf 100755 --- a/tools/test/boost_libraries_test.py +++ b/tools/test/boost_libraries_test.py @@ -683,6 +683,29 @@ def test_boost_cobalt_warns_only_for_disabled_exceptions(root: Path) -> None: assert issue not in result.stdout, result.stdout +def test_asio_windows_allocator_overlay_reaches_sources_and_consumers(root: Path) -> None: + # Windows-only private headers must reach Asio applications and compiled Cobalt alike. + harness.add_library(root, 'asio', + 'import webcpp ;\nwebcpp.targets native ;\n' + 'webcpp.run context : context.cpp : /webcpp/asio//asio ;\n', + {'context.cpp': '#include \nint main() {}\n'}) + original = harness.ROOT / 'libs/asio' + (root / 'libs/asio/build.jam').write_text((original / 'build.jam').read_text()) + for name in ('include', 'src'): + shutil.copytree(original / name, root / 'libs/asio' / name) + harness.add_library(root, 'coroutines', COBALT_JAMFILE, {'coroutines.cpp': COBALT_SOURCE}) + for request, selected in (((), False), (('target-os=windows',), True)): + result = harness.run_b2(root, '-a', '-n', '-d+2', *request, + 'libs/asio/test//context', 'libs/coroutines/test') + harness.expect(result, True) + commands = [line for line in result.stdout.splitlines() + if ' -c ' in line and any(name in line for name in + ('context.cpp', 'coroutines.cpp', '/cobalt/src/'))] + assert commands, result.stdout[-4000:] + for command in commands: + assert ('boost-asio-windows/include' in command) == selected, command + + def test_boost_cobalt_preserves_exception_setting(root: Path) -> None: # A blanket exception requirement would reject a valid result-based consumer. # Build the real archive and execute eager promises and cancellation in each mode. @@ -717,11 +740,51 @@ def test_boost_cobalt_preserves_exception_setting(root: Path) -> None: print(f'cobalt {request or ("native",)} exceptions={exceptions}: passed', flush=True) +def test_boost_context_unwinds_native_stack(root: Path) -> None: + source = r'''#include +#include +int main() { + int count = 0; + struct guard { int& value; ~guard() { ++value; } }; + { + boost::context::fiber fiber([&](boost::context::fiber caller) { + guard instance{count}; + caller = std::move(caller).resume(); + return caller; + }); + fiber = std::move(fiber).resume(); + if (count != 0) return 1; + } + return count == 1 ? 0 : 2; +} +''' + harness.add_library(root, 'context_probe', + 'import webcpp ;\nwebcpp.run fiber : fiber.cpp : ' + '/webcpp//boost_context on ;\n', + {'fiber.cpp': source}) + result = harness.run_b2(root, '-a', '-d+2', 'libs/context_probe/test') + harness.expect(result, True) + assert passed(result) == {'fiber'}, result.stdout[-4000:] + assert '-lboost_context' not in result.stdout, result.stdout[-4000:] + assert 'BOOST_CONTEXT_STATIC_LINK=1' in result.stdout + assert 'BOOST_CONTEXT_NO_LIB=1' in result.stdout + + +def test_boost_context_refuses_unverified_wasm(root: Path) -> None: + for target in ('wasip2', 'wasip3'): + result = harness.run_b2(root, f'toolset=clang-{target}', '/webcpp//boost_context') + harness.expect(result, False, f'Boost.Context has no verified {target} backend', + 'JSPI, Asyncify and C++20 awaitables do not') + + CASES = [ + test_boost_context_unwinds_native_stack, + test_boost_context_refuses_unverified_wasm, test_boost_cobalt_names_missing_or_mismatched_sources, test_boost_cobalt_omits_main_and_ssl_from_supplied_sources, test_boost_cobalt_warns_only_for_disabled_exceptions, test_boost_cobalt_preserves_exception_setting, + test_asio_windows_allocator_overlay_reaches_sources_and_consumers, test_boost_url_links_on_every_target, test_boost_charconv_links_on_every_target, test_boost_locale_on_every_target, diff --git a/tools/test/component_jam_test.py b/tools/test/component_jam_test.py index d7ca99ce..160b3bd3 100755 --- a/tools/test/component_jam_test.py +++ b/tools/test/component_jam_test.py @@ -403,6 +403,22 @@ def test_served_component_green_on_wasip2_and_wasip3(root): assert len(components) == 1 and components[0].read_bytes()[:8] == COMPONENT, components +def test_cooperative_p3_serve_enables_component_threading(root): + # The SDK's cooperative libc uses context slot 1, accepted only with this runtime feature. + # Enable it for the corresponding P3 profile, preserving P2 and single-task flags. + harness.link_wasi_tools(root) + for toolset, threading, expected in ( + (WASIP2, 'single', '-S cli'), + (WASIP3, 'single', '-S cli,p3 -W component-model-async'), + (WASIP3, 'multi', '-S cli,p3 -W component-model-async -W component-model-threading'), + ): + result = harness.run_b2(root, '-a', '-n', toolset, f'threading={threading}', + f'{TEST}//answers') + harness.expect(result, True) + command = next(line for line in result.stdout.splitlines() if ' --flags=' in line) + assert f'--flags="{expected}"' in command, command + + def test_wrong_expected_is_a_run_failure_in_the_report(root): harness.link_wasi_tools(root) wasmtime = linked_wasmtime(root) @@ -787,6 +803,7 @@ def test_a_b2_that_kills_its_action_leaves_no_wasmtime(root): test_a_name_declared_twice_is_refused, test_shell_characters_in_arguments_reach_wit_bindgen, test_served_component_green_on_wasip2_and_wasip3, + test_cooperative_p3_serve_enables_component_threading, test_wrong_expected_is_a_run_failure_in_the_report, test_serve_refuses_native, test_native_lane_skips_served_tests, diff --git a/tools/test/webcpp_jam_test.py b/tools/test/webcpp_jam_test.py index 50787236..71d5d152 100755 --- a/tools/test/webcpp_jam_test.py +++ b/tools/test/webcpp_jam_test.py @@ -1070,7 +1070,49 @@ def test_data_the_shell_would_read_is_refused(root): f'{character}') +def test_source_only_corpus_is_not_loaded_as_a_build(root): + corpus = root / 'libs/demo/example/upstream' + corpus.mkdir() + (corpus / 'Jamfile').write_text('EXIT upstream-corpus-must-not-be-loaded : 1 ;\n') + build = root / 'libs/demo/build.jam' + build.write_text(build.read_text() + '\nimport webcpp ;\n' + 'webcpp.source-only example/upstream ;\n') + for target in ('declared-targets', 'declared-lanes'): + harness.expect(harness.run_b2(root, '-d0', target), True) + # A similarly named adjacent directory is still scanned. + adjacent = corpus.with_name('upstream-adapted') + adjacent.mkdir() + (adjacent / 'Jamfile').write_text('EXIT adapted-code-must-still-be-loaded : 1 ;\n') + harness.expect(harness.run_b2(root, '-d0', 'declared-targets'), False, + 'adapted-code-must-still-be-loaded') + # A declaration may not hide its own project or a sibling project's sources. + for directory in ('.', '../../tools'): + build.write_text('project /webcpp/demo ;\nimport webcpp ;\n' + f'webcpp.source-only {directory} ;\n') + harness.expect(harness.run_b2(root, '-d0', 'declared-targets'), False, + 'webcpp.source-only requires a child directory') + + +def test_link_fail_checks_linking_and_keeps_success_controls(root): + harness.add_library(root, 'linkage', + 'import webcpp ;\nwebcpp.targets native ;\n' + 'webcpp.link-fail mismatch : caller.cpp ;\n' + 'webcpp.link matching : caller.cpp provider.cpp ;\n', + {'caller.cpp': 'int supplied(); int main() { return supplied(); }\n', + 'provider.cpp': 'int supplied() { return 0; }\n'}) + result = harness.run_b2(root, 'libs/linkage/test') + harness.expect(result, True) + assert '(failed-as-expected)' in result.stdout, result.stdout + # A definition arriving must make the negative test fail, not silently pass. + jamfile = root / 'libs/linkage/test/Jamfile' + jamfile.write_text(jamfile.read_text().replace('mismatch : caller.cpp ;', + 'mismatch : caller.cpp provider.cpp ;')) + harness.expect(harness.run_b2(root, 'libs/linkage/test'), False) + + CASES = [ + test_link_fail_checks_linking_and_keeps_success_controls, + test_source_only_corpus_is_not_loaded_as_a_build, test_native_builds_exactly_the_declared_programs, test_wasip2_skips_native_only_and_has_exceptions, test_wasip3_catches_a_throw, diff --git a/tools/webcpp.jam b/tools/webcpp.jam index 67c2e3b3..3b10003a 100644 --- a/tools/webcpp.jam +++ b/tools/webcpp.jam @@ -19,7 +19,9 @@ # webcpp.headers-alone library : include-root : only * : requirements * # : targets * ; # webcpp.link name : sources + : requirements * : targets * ; +# webcpp.link-fail name : sources + : requirements * : targets * ; # webcpp.data directories + ; (requirements: a run's data on WASI) +# webcpp.source-only directories + ; (upstream corpus, not a build) # # the rules of a program a page loads, on emscripten alone, in both # suspension variants, its manifest and the table of their sizes: @@ -431,6 +433,14 @@ local rule node-runnable ( kind name : requirements * ) # an exe of the same sources and requirements, for a target that needs its # files, such as a page that loads it. Each source of a program an example # Jamfile links is recorded for linked-of: the library's page shows its code. +# A negative link test: its translation units must compile, but their +# combination must not produce an executable. Sources remain in lint. +rule link-fail ( name : sources + : requirements * : targets * ) +{ + testing.link-fail $(sources) : $(requirements) + [ program link-fail : $(name) : $(targets) ] $(.handler) : $(name) ; +} + rule link ( name : sources + : requirements * : targets * ) { local only = [ program link : $(name) : $(targets) ] ; @@ -806,12 +816,45 @@ rule declared ( directories * ) # Loads the Jamfiles under directories (absolute, in b2's form), at any # depth, which a build loads only once it reaches them. +# Marks child directories as source material whose original build files are +# not WebCPP projects. This affects discovery only, never lint or compilation +# of sources explicitly named by a WebCPP target. +rule source-only ( directories + ) +{ + local found = [ where ] ; + for local directory in $(directories) + { + local absolute = [ path.root [ path.make $(directory) ] $(found[2]) ] ; + local child = [ path.relative $(absolute) $(found[2]) : no-error ] ; + if $(child) in . not-a-child + { + errors.user-error "webcpp.source-only requires a child directory: $(directory)" ; + } + if ! [ path.exists [ path.native $(absolute) ] ] + { + errors.user-error "webcpp.source-only directory does not exist: $(directory)" ; + } + .source-only += $(absolute) ; + } +} + local rule load-jamfiles ( directories * ) { local names = [ modules.peek project : JAMFILE ] ; for local jamfile in [ path.glob-tree $(directories) : $(names) ] { - project.load $(jamfile:D) ; + local source-only ; + for local directory in $(.source-only) + { + if [ path.relative $(jamfile) $(directory) : no-error ] != not-a-child + { + source-only = true ; + } + } + if ! $(source-only) + { + project.load $(jamfile:D) ; + } } } From 14faa5f9a10563543c184aa54d4fddb4ef4324d8 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 01:06:40 -0500 Subject: [PATCH 03/32] test: pin final Beast cancellation and startup regressions [skip ci] --- libs/beast | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/beast b/libs/beast index 9ee7ca4b..83d570eb 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 9ee7ca4b3c50db26a7926a1a6deba1cc35f35f6f +Subproject commit 83d570eb8a715e8fae9807e5935275fd9e95603b From a8064a1c3907bc16a70930f12a1f92f9fef27632 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 01:16:08 -0500 Subject: [PATCH 04/32] test: close Beast environment coverage and fix annotated accessor lint [skip ci] --- libs/beast | 2 +- libs/wasi | 2 +- tools/lint/lint.sh | 4 +++- tools/lint/lint_test.py | 7 +++++++ 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/libs/beast b/libs/beast index 83d570eb..4da3e791 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 83d570eb8a715e8fae9807e5935275fd9e95603b +Subproject commit 4da3e791c30a5ffb2598009828ab0a2b59e8d58c diff --git a/libs/wasi b/libs/wasi index edf8c319..fb551ae6 160000 --- a/libs/wasi +++ b/libs/wasi @@ -1 +1 @@ -Subproject commit edf8c3191f88d4c7c758a251aeb4637c5f004093 +Subproject commit fb551ae6dc31e0ee9f3b9b90243c08fb673b4ef4 diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index 42584d93..ed75d6b7 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -400,12 +400,14 @@ self_returns="$(on_files "${work_directory}/sources" awk ' marked = 0 } pending && code ~ /\{[ ]*$/ { pending = 0; exempt = 1 } + pending && code ~ /\{.*\}[ ]*$/ { pending = 0; exempt = 1; inline_body = 1 } pending && code ~ /[;}][ ]*$/ { pending = 0 } /return \*this;/ { if (!exempt && !spared_head(signature)) { printf "%s:%d: %s\n", FILENAME, FNR, $0 } - }' || true)" + } + inline_body { exempt = 0; inline_body = 0 }' || true)" if [ -n "${self_returns}" ]; then printf '%s\n' "${self_returns}" fail 'a function returns *this outside an assignment, a prefix ++ or --, or lint-std' diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index d9ce26f2..61894d33 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -1327,6 +1327,11 @@ def test_returns_this_spares_what_the_standard_specifies(root): ' return *this; // after a marked function\n' ' }\n' '\n' + ' // lint-std: std::basic_regex::assign returns *this\n' + ' stepper& assign() noexcept { return *this; } // compact marked\n' + '\n' + ' stepper& after_compact() { return *this; } // after compact marked\n' + '\n' ' // lint-std:\n' ' stepper& unexplained() {\n' ' advance();\n' @@ -1341,9 +1346,11 @@ def test_returns_this_spares_what_the_standard_specifies(root): '};\n') expect_alone(lint(root), 'returns *this', [at(root, path, '// postfix'), at(root, path, '// after a marked function'), + at(root, path, '// after compact marked'), at(root, path, '// marked without a reason')], spared=(at(root, path, '// prefix increment'), at(root, path, '// prefix decrement'), + at(root, path, '// compact marked'), at(root, path, '// marked, with a reason'))) From adb5fa32658b73f45ea44c25b3af55bb0b19de60 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 01:33:21 -0500 Subject: [PATCH 05/32] test: cover Beast browser modes and HTTP fixture ordering in CI [skip ci] --- .github/workflows/library.yml | 6 ++++++ libs/beast | 2 +- tools/ci/matrix.py | 13 +++++++++++-- tools/ci/matrix_test.py | 22 ++++++++++++++++++++++ 4 files changed, 40 insertions(+), 3 deletions(-) diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index dc697f20..2f0363aa 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -380,6 +380,12 @@ jobs: path: .local/beast-host-tls key: ${{ steps.host-tls-cache.outputs.cache-primary-key }} + - name: Verify Beast application inventory and HTTP fixtures + if: matrix.library == 'beast' && matrix.lane == 'applications-host-clients' && matrix.platform == 'wasip2' + run: | + python3 libs/beast/test/applications/inventory_test.py + python3 libs/beast/test/applications/driver_test.py + # It registers its toolset in .local/user-config.jam, prints its b2 command and runs it. - name: Own lane id: lane diff --git a/libs/beast b/libs/beast index 4da3e791..adeb2026 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 4da3e791c30a5ffb2598009828ab0a2b59e8d58c +Subproject commit adeb202693d927d8865e2102aeee97c4911ff40b diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 09bcf84f..663b1c2b 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -513,6 +513,14 @@ def has_external(library: str | None) -> bool: OWN_LANE_BASES = {None: 'clang-18', 'native': 'clang-18', 'emscripten': 'emscripten', 'wasip2': 'wasip2', 'wasip3': 'wasip3'} +# Suspension variants expand inside B2; these lanes also exercise both policy and EH modes. +OWN_LANE_OPTIONS = { + ('beast', 'browser', 'emscripten'): + ('exception-handling=on,off', 'webcpp-beast-unsupported=error,ignore'), + ('beast', 'browser-node', 'emscripten'): + ('exception-handling=on,off', 'webcpp-beast-unsupported=error,ignore'), +} + @dataclass(frozen=True) class OwnLane: @@ -755,14 +763,15 @@ def own_lane_command(own: OwnLane, user_config: Path, xml: Path | None, extra: list[str]) -> list[str]: """The own lane's command: b2, from scratch, on // for each of its directories; with Clang 18 when it names no target, and otherwise with the toolset and the - options of the lane it shares, writing xml, as that lane does.""" + options of the lane it shares plus its own mode coverage, writing xml, as that lane does.""" base = own_lane_base(own.target) external = external_arguments(needs_external(own.library)) if own.target is None: return ['b2', f'--user-config={user_config}', '-a', f'toolset={base.toolset}', *external, *extra, *own.requests] + options = OWN_LANE_OPTIONS.get((own.library, own.lane, own.target), ()) return ['b2', f'--user-config={user_config}', '-a', '--dump-tests', f'--out-xml={xml}', - f'toolset={base.toolset}', *external, *base.options, *extra, *own.requests] + f'toolset={base.toolset}', *external, *base.options, *options, *extra, *own.requests] def run_b2(label: str, command: list[str]) -> int: diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 4ac7244b..6d444c77 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -519,6 +519,27 @@ def test_an_own_lanes_command(root): assert (lane.id, lane.os) == (lane_id, 'ubuntu-24.04'), lane +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'] + for name in ('browser', 'browser-node'): + own = matrix.parsed_own_lanes( + f'beast {name} libs/beast/test/browser emscripten original')[0] + xml = root / f'{own.id}.xml' + command = matrix.own_lane_command(own, config, xml, ['-j2']) + assert command == [ + 'b2', f'--user-config={config}', '-a', '--dump-tests', f'--out-xml={xml}', + 'toolset=emscripten', *options, '-j2', f'libs/beast/test/browser//{name}'], command + # The policy is Beast-specific; application lanes select their own exception mode. + for declaration in ('asio browser libs/asio/test/browser emscripten original', + 'beast applications-browser libs/beast/test/applications/browser ' + 'emscripten original', + 'beast browser libs/beast/test/browser native original'): + own = matrix.parsed_own_lanes(declaration)[0] + command = matrix.own_lane_command(own, config, root / 'other.xml', []) + assert all(option not in command for option in options), command + + def test_a_wasip3_lane_can_bind_a_loopback_socket(root): # Run the planned lane, including its launcher: Wasmtime refuses even a loopback bind # without an explicit network grant, which a successful compile cannot establish. @@ -1378,6 +1399,7 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): test_own_lanes_of_every_library_and_of_one, test_own_lanes_on_targets, test_an_own_lanes_command, + test_beast_browser_lanes_cover_policies_and_exception_modes, test_a_wasip3_lane_can_bind_a_loopback_socket, test_a_lane_is_named_by_the_compiler_version, test_abbreviated_paths_keep_the_lane_name, From 5bb4825ee8889f52149829141926dbb6f7f669f9 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 02:08:12 -0500 Subject: [PATCH 06/32] test: pin bounded Beast WASI client startup checks [skip ci] --- libs/beast | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/beast b/libs/beast index adeb2026..0a881969 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit adeb202693d927d8865e2102aeee97c4911ff40b +Subproject commit 0a881969d2be2e635d2f89a61f258a8d80a4d393 From 55a72c056de1e6522e1fc6dbc3ee2b9ef3715327 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 02:32:05 -0500 Subject: [PATCH 07/32] fix: restore MSVC overlay precedence and static Context assembly [skip ci] --- Jamroot | 5 +- libs/asio | 2 +- libs/beast | 2 +- tools/boost/Jamfile | 2 + tools/test/boost_libraries_test.py | 73 ++++++++++++++++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) diff --git a/Jamroot b/Jamroot index 4d2e53c7..e156aa76 100644 --- a/Jamroot +++ b/Jamroot @@ -248,7 +248,10 @@ project /webcpp gcc:"-isystem\"$(.boost-include)\"" clang:"--system-header-prefix=\"boost/\"" emscripten:"--system-header-prefix=\"boost/\"" - msvc:"\"/external:I$(.boost-include)\"" + # MSVC searches ordinary and external directories in command order. + # Quote the path alone so b2 orders private -I overlays before this + # /external:I option; quoting the whole option moves Boost first. + msvc:"/external:I\"$(.boost-include)\"" msvc:"/external:W0" # Boost.Container's auto-link (reached through Boost.JSON) would ask # for a compiled library on MSVC. diff --git a/libs/asio b/libs/asio index e551f9cf..9ed4ba85 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit e551f9cf14abb66e79e5fe04960c704762b19a44 +Subproject commit 9ed4ba8597467a1d4348cf974a0a99ee161b70e4 diff --git a/libs/beast b/libs/beast index 0a881969..c1738586 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 0a881969d2be2e635d2f89a61f258a8d80a4d393 +Subproject commit c1738586d8b7b0f4f24ad528840433bf100cdf57 diff --git a/tools/boost/Jamfile b/tools/boost/Jamfile index 05070d22..e3c7f5eb 100644 --- a/tools/boost/Jamfile +++ b/tools/boost/Jamfile @@ -184,6 +184,8 @@ compiled boost_context : [ glob libs/context/src/fcontext.cpp ] : libs/context/src/fcontext.cpp is missing : @context-configuration BOOST_CONTEXT_SOURCE BOOST_CONTEXT_STATIC_LINK=1 BOOST_CONTEXT_NO_LIB=1 + # Upstream's static MSVC recipe removes the MASM PROC export qualifier. + msvc:BOOST_CONTEXT_EXPORT= : BOOST_CONTEXT_STATIC_LINK=1 BOOST_CONTEXT_NO_LIB=1 @context-usage ; diff --git a/tools/test/boost_libraries_test.py b/tools/test/boost_libraries_test.py index 0653cabf..2d15d022 100755 --- a/tools/test/boost_libraries_test.py +++ b/tools/test/boost_libraries_test.py @@ -22,6 +22,7 @@ from __future__ import annotations import re +import shlex import shutil import struct import sys @@ -706,6 +707,77 @@ def test_asio_windows_allocator_overlay_reaches_sources_and_consumers(root: Path assert ('boost-asio-windows/include' in command) == selected, command +def test_msvc_overlays_win_actual_header_lookup(root: Path) -> None: + # MSVC searches /I and /external:I in command order. Unlike GCC/Clang, + # an earlier external path shadows a later ordinary overlay path. + harness.add_library(root, 'coroutines', COBALT_JAMFILE, {'coroutines.cpp': COBALT_SOURCE}) + config = harness.user_config(root).read_text() + configured = re.search(r'(?m)^\s*using\s+boost\b[^\n]*' + r'(?:"([^"]+)"|([^";\s]+))', config) + assert configured, config + headers = root / 'Boost headers with spaces' + headers.symlink_to(Path(configured.group(1) or configured.group(2))) + libraries = root / 'Boost libraries with spaces' + libraries.mkdir() + config = harness.USING_BOOST.sub('', config) + \ + f'using boost : 1.92 : "{headers}" "{libraries}" ;\n' + harness.configure(root, config + f'\nusing msvc : 14.3 : "{sys.executable}"' + ' : off ;\n') + jamroot = root / 'Jamroot' + original = jamroot.read_text() + # A foreign-toolset dry run emits commands but cannot execute cmd.exe for + # configuration checks. Restore those checks before the real native compile. + jamroot.write_text(original.replace('@boost-check', 'off')) + try: + result = harness.run_b2(root, '-a', '-n', '-d+2', 'toolset=msvc-14.3', + 'target-os=windows', 'architecture=x86', 'address-model=64', + 'exception-handling=off', 'libs/coroutines/test') + finally: + jamroot.write_text(original) + harness.configure(root, config) + harness.expect(result, True) + result_commands = result.stdout + commands = [line for line in result.stdout.splitlines() + if ' -c ' in line and 'coroutines.cpp' in line] + assert len(commands) == 1, result.stdout[-4000:] + includes = [] + for word in shlex.split(commands[0]): + for prefix in ('/external:I', '-I', '/I'): + if word.startswith(prefix): + includes.append(word[len(prefix):]) + break + assert any('boost-asio-windows/include' in path for path in includes), commands + assert any('boost-cobalt-common/include' in path for path in includes), commands + # Preparing the real common overlay and compiling against the emitted order + # proves which promise definition wins, including a checkout containing spaces. + harness.expect(harness.run_b2(root, '/webcpp/cobalt-common//prepared.stamp'), True) + assert (root / 'bin/boost-cobalt-common/include/boost/cobalt/detail/main.hpp').is_file() + flags = ' '.join(f'-I\\"{path}\\"' for path in includes) + source = ('#include \n' + 'static_assert(requires(boost::cobalt::detail::main_promise& promise) {\n' + ' promise.unhandled_exception();\n' + '});\n') + harness.add_library(root, 'selected', + 'import webcpp ;\nwebcpp.targets native ;\n' + 'webcpp.compile promise : promise.cpp : off ' + f'"{flags}" ;\n', {'promise.cpp': source}) + result = harness.run_b2(root, '-a', 'libs/selected/test//promise') + harness.expect(result, True, '**passed**') + # The same precedence must reach every separately compiled Cobalt source. + compiled = [line for line in result_commands.splitlines() + if ' -c ' in line and '/cobalt/src/' in line] + assert compiled, result_commands[-4000:] + for command in [*commands, *compiled]: + words = shlex.split(command) + external = next(index for index, word in enumerate(words) + if word.startswith('/external:I')) + for overlay in ('boost-asio-windows/include', 'boost-cobalt-common/include'): + selected = next(index for index, word in enumerate(words) if overlay in word) + assert selected < external, command + assert '/external:W0' in words, command + assert '/external:anglebrackets' not in words, command + + def test_boost_cobalt_preserves_exception_setting(root: Path) -> None: # A blanket exception requirement would reject a valid result-based consumer. # Build the real archive and execute eager promises and cancellation in each mode. @@ -785,6 +857,7 @@ def test_boost_context_refuses_unverified_wasm(root: Path) -> None: test_boost_cobalt_warns_only_for_disabled_exceptions, test_boost_cobalt_preserves_exception_setting, test_asio_windows_allocator_overlay_reaches_sources_and_consumers, + test_msvc_overlays_win_actual_header_lookup, test_boost_url_links_on_every_target, test_boost_charconv_links_on_every_target, test_boost_locale_on_every_target, From 6d7dda70cd9dab20074dbf59f504475c535dc793 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 04:00:37 -0500 Subject: [PATCH 08/32] build: unify TLS providers and complete Asio Beast review fixes --- .github/workflows/library.yml | 72 +- .gitmodules | 3 + AGENTS.md | 258 +++---- CODING-GUIDELINES.md | 673 +++++++++--------- Jamroot | 3 +- doc/releases/0.1.0.adoc | 6 + .../plans/2026-11-03-asio-beast-closure.md | 102 +++ libs/asio | 2 +- libs/beast | 2 +- libs/trystero | 2 +- libs/wasi | 2 +- third_party/Jamfile | 13 +- third_party/libs/libdatachannel | 1 + tools/boost/cobalt-common/boost-1.92.patch | 19 + tools/boost/cobalt-common/manifest.json | 4 + tools/ca_certificates/generate.py | 6 +- tools/ci/actions/libdatachannel/action.yml | 65 -- tools/ci/actions/libdatachannel/install.sh | 152 ---- tools/ci/actions/openssl/action.yml | 20 - tools/ci/actions/openssl/install.sh | 189 ----- tools/ci/actions_test.py | 347 +-------- tools/ci/container/Dockerfile | 9 +- tools/ci/matrix.py | 25 +- tools/ci/matrix_test.py | 51 +- tools/libdatachannel/build.py | 175 +++++ tools/libdatachannel/build_test.py | 38 + tools/libdatachannel/msvc.cmake | 17 + tools/libdatachannel/pin.json | 94 +++ tools/libdatachannel/source.py | 104 +++ tools/libdatachannel/source_test.py | 151 ++++ tools/libdatachannel/update.py | 86 +++ tools/openssl/build.py | 53 +- tools/openssl/build_test.py | 47 ++ tools/openssl/test/Jamfile | 11 +- tools/openssl/test/combined_provider.cpp | 33 + tools/openssl/test/tls_client_embedded.cpp | 10 + tools/release/release.py | 66 +- tools/release/release_test.py | 71 ++ tools/test/boost_libraries_test.py | 36 + tools/test/ca_certificates_b2_test.py | 6 +- tools/test/jamroot_test.py | 2 +- tools/test/libdatachannel_test.py | 135 ++++ tools/test/openssl_test.py | 81 ++- tools/webcpp-ca-certificates.jam | 2 +- tools/webcpp-libdatachannel.jam | 203 ++++++ tools/webcpp-openssl.jam | 24 +- 46 files changed, 2090 insertions(+), 1381 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-03-asio-beast-closure.md create mode 160000 third_party/libs/libdatachannel delete mode 100644 tools/ci/actions/libdatachannel/action.yml delete mode 100644 tools/ci/actions/libdatachannel/install.sh delete mode 100644 tools/ci/actions/openssl/action.yml delete mode 100644 tools/ci/actions/openssl/install.sh create mode 100644 tools/libdatachannel/build.py create mode 100644 tools/libdatachannel/build_test.py create mode 100644 tools/libdatachannel/msvc.cmake create mode 100644 tools/libdatachannel/pin.json create mode 100644 tools/libdatachannel/source.py create mode 100644 tools/libdatachannel/source_test.py create mode 100644 tools/libdatachannel/update.py create mode 100644 tools/openssl/test/combined_provider.cpp create mode 100644 tools/openssl/test/tls_client_embedded.cpp create mode 100644 tools/test/libdatachannel_test.py create mode 100644 tools/webcpp-libdatachannel.jam diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 2f0363aa..3df50c07 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -25,8 +25,8 @@ # runs b2 declared-lanes and writes the matrix of own lanes, those a library # declares with webcpp.lane, such as its oracle's, and says whether a library # needs libraries that webcpp does not build yet (external), trystero's -# libsecp256k1, libdatachannel and OpenSSL, which the CI's actions of those names -# install, until webcpp builds them from third_party/. +# libsecp256k1, installed by its action. B2 builds OpenSSL and +# libdatachannel from pinned sources with one provider per program. # lanes one job per lane, which runs the lane command, b2 -a --dump-tests # --out-xml=.xml for one toolset, and uploads the XML. With --out-xml, b2 # exits 0 even when a test fails: the report gives the verdict. A wasip2 or @@ -145,6 +145,15 @@ jobs: persist-credentials: false path: libs/${{ inputs.library }} + # Only these pinned nested sources are needed. Do not fetch the unused + # JSON fixtures or the benchmark repository's unrelated submodules. + - &transport-sources + name: Check out the transport source dependencies + shell: bash + run: | + git -C third_party/libs/libdatachannel submodule update --init \ + deps/libjuice deps/libsrtp deps/plog deps/usrsctp + - &boost uses: ./tools/ci/actions/boost @@ -216,6 +225,7 @@ jobs: - *superproject-for-library - *make-room - *library + - *transport-sources - *boost # What a WASI lane installs, which the own-lanes job installs too, by these anchors, for an @@ -252,16 +262,8 @@ jobs: if: matrix.node uses: ./tools/ci/actions/node - # The libraries a library of the lane needs and webcpp does not build yet, for an entry - # that says external, which the own-lanes job installs too, by these anchors: OpenSSL - # first, which libdatachannel is built against; libsecp256k1, for emscripten too, after - # emsdk, on an entry that has it; and libdatachannel, with the lane's compilers, since a - # program shares the types of its C++ API. Only the native backend needs OpenSSL and - # libdatachannel, so an entry on emscripten has neither. - - &openssl - if: matrix.external && !matrix.emsdk - uses: ./tools/ci/actions/openssl - + # libsecp256k1 remains external. OpenSSL and libdatachannel are source-built + # by B2 with the consuming target's toolchain and threading properties. - &secp256k1 if: matrix.external uses: ./tools/ci/actions/secp256k1 @@ -269,13 +271,6 @@ jobs: cc: ${{ matrix.cc }} emscripten: ${{ matrix.emsdk }} - - &libdatachannel - if: matrix.external && !matrix.emsdk - uses: ./tools/ci/actions/libdatachannel - with: - cc: ${{ matrix.cc }} - cxx: ${{ matrix.cxx }} - # The image a container lane runs b2 in (its entry's container), which the container job # built and cached, restored from the cache, so that the lane builds none. - if: matrix.container @@ -326,6 +321,7 @@ jobs: - *superproject-for-library - *make-room - *library + - *transport-sources - *boost - *wasi-sdk - *wasmtime @@ -333,9 +329,7 @@ jobs: - *wasi-wit - *emsdk - *node - - *openssl - *secp256k1 - - *libdatachannel # The pinned chrome-headless-shell, as CHROME, for a lane whose driver meets a browser # (its entry's chrome), as trystero's interop does. @@ -411,6 +405,18 @@ jobs: path: bin/**/*.sizes.md if-no-files-found: ignore + - name: Upload OpenSSL upstream test evidence + if: always() && matrix.library == 'asio' && startsWith(matrix.lane, 'openssl-upstream') + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: openssl-upstream-${{ matrix.id }} + path: | + bin/**/upstream-tests.log + bin/**/upstream-tests.json + bin/**/build.json + if-no-files-found: warn + retention-days: 7 + docs: name: Documentation needs: plan @@ -423,6 +429,7 @@ jobs: - *superproject-for-library - *make-room - *library + - *transport-sources - *boost - uses: ./tools/ci/actions/node @@ -446,20 +453,11 @@ jobs: # The libraries the library, or one it uses, needs and webcpp does not build yet (the # plan's external), whose headers its reference parses with the native backend's: with Clang 18, # the compiler that parses them. - - if: needs.plan.outputs.external == 'true' - uses: ./tools/ci/actions/openssl - - if: needs.plan.outputs.external == 'true' uses: ./tools/ci/actions/secp256k1 with: cc: clang-18 - - if: needs.plan.outputs.external == 'true' - uses: ./tools/ci/actions/libdatachannel - with: - cc: clang-18 - cxx: clang++-18 - # clang++ reads the headers for tools/doc/doc_comments.py; the Boost check compiles with # the same Clang. The index links each library's page where the site serves it. # A page whose library needs external libraries requires them, as a lane does, and is @@ -476,8 +474,7 @@ jobs: fi if [ "$EXTERNAL" = true ]; then request=(webcpp-require-external=on "${request[@]}") - for variable in SECP256K1_ROOT SECP256K1_EMSCRIPTEN_ROOT LIBDATACHANNEL_ROOT \ - OPENSSL_ROOT; do + for variable in SECP256K1_ROOT SECP256K1_EMSCRIPTEN_ROOT; do if [ -n "${!variable-}" ]; then request=("-s$variable=${!variable}" "${request[@]}") fi @@ -548,6 +545,7 @@ jobs: persist-credentials: false path: libs/${{ inputs.library }} fetch-depth: 0 + - *transport-sources - *boost - uses: ./tools/ci/actions/wasi-sdk @@ -570,21 +568,12 @@ jobs: # lint-external), which the dry runs name and clang-tidy reads, built with Clang 18; and # libsecp256k1's emscripten build too when a library declares emscripten, for the commands # of that target. - - if: needs.plan.outputs.lint-external == 'true' - uses: ./tools/ci/actions/openssl - - if: needs.plan.outputs.lint-external == 'true' uses: ./tools/ci/actions/secp256k1 with: cc: clang-18 emscripten: ${{ needs.plan.outputs.has-emscripten }} - - if: needs.plan.outputs.lint-external == 'true' - uses: ./tools/ci/actions/libdatachannel - with: - cc: clang-18 - cxx: clang++-18 - # The compilation database is what b2 compiles with its default toolset, the first that # user-config.jam registers, Clang 18, and, for what only a WASI target or emscripten # builds, with the toolset of that target: a WASI dry run generates the bindings its @@ -614,6 +603,7 @@ jobs: shard: [1, 2, 3, 4, 5, 6, 7, 8] steps: - *superproject + - *transport-sources - *boost - uses: ./tools/ci/actions/wasi-sdk diff --git a/.gitmodules b/.gitmodules index 443a0c73..23e77683 100644 --- a/.gitmodules +++ b/.gitmodules @@ -43,3 +43,6 @@ [submodule "libs/beast"] path = libs/beast url = ../beast.git +[submodule "third_party/libs/libdatachannel"] + path = third_party/libs/libdatachannel + url = https://github.com/paullouisageneau/libdatachannel.git diff --git a/AGENTS.md b/AGENTS.md index 473f2e48..c8c32529 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,7 +161,7 @@ webcpp/ and emsdk.jam (the lines that register the WASI and emscripten toolsets), container/Dockerfile (the image of the container lanes), and actions/{boost,wasi-sdk,wasmtime,wit-bindgen,wasi-wit,emsdk, - secp256k1,libdatachannel,openssl,chrome,container,mrdocs,node}/ + secp256k1,chrome,container,mrdocs,node}/ (chapter 4) site/ site.jam, the rules of b2 site and b2 site-serve, catalogue.py (the site's libraries.json), redirect.py (the old address's two pages) and @@ -240,26 +240,28 @@ Jamroot is its build configuration, and `libs/` is its repository. toolsets compile; - for emscripten: Emscripten 6.0.11, from emsdk, and Node, which runs its programs; the tests of the build need it too; -- for trystero, until webcpp builds them from `third_party/` - (`CODING-GUIDELINES.md` chapter 16): libsecp256k1 0.8.0, static, with its - `schnorrsig` and `extrakeys` modules, natively and, for emscripten, built - with Emscripten; and, for its native backend, libdatachannel 0.24.6, built - with the compiler and the standard library that build the programs, and - OpenSSL 3. Each is found in the directory of its `include/` and `lib/` that - `-sSECP256K1_ROOT=`, `-sSECP256K1_EMSCRIPTEN_ROOT=`, - `-sLIBDATACHANNEL_ROOT=` and `-sOPENSSL_ROOT=` on b2's command - line name, never the environment, else in `.local/secp256k1-native`, - `.local/secp256k1-emscripten`, `.local/libdatachannel` and `.local/openssl` - when it holds the library's header (below), else, natively outside Windows, - in `/usr/include` or `/usr/local/include`, where a system install is - legitimate; a relative `-s` is read from b2's working directory. When none - holds a library's header, trystero is left out, its programs skipped, with - one line that names the library and every place it looked, so that `b2 test` - builds every other library, and the index names trystero without a link to - its page; with `webcpp-require-external=on` on b2's command line, as the CI - and the lint build, the build stops instead, naming both libraries - (`webcpp.external` and its kin, chapter 4). trystero's page says how each is - built. The CI's actions build them so (chapter 4). +- for trystero: libsecp256k1 0.8.0, static, with `schnorrsig` and + `extrakeys`, built natively and, for browser programs, with Emscripten. + Only this dependency remains externally provisioned. B2 reads + `-sSECP256K1_ROOT=` and `-sSECP256K1_EMSCRIPTEN_ROOT=` from its + command line, never the environment; otherwise it searches + `.local/secp256k1-native` and `.local/secp256k1-emscripten`, then the native + system include paths outside Windows. A missing dependency leaves trystero + out with a diagnostic, or fails when `webcpp-require-external=on`, as in CI; +- for native Trystero: CMake and Make (nmake on Windows), and the pinned + `third_party/libs/libdatachannel` checkout with its required nested sources. + Initialize it with `git submodule update --init --recursive + third_party/libs/libdatachannel`. B2 builds static libdatachannel and its + nested dependencies with the consumer's compiler and runtime settings. + Native Trystero requires `threading=multi` and exceptions; a single-thread + request is refused because this backend uses worker threads; +- for native or WASIp3 guest TLS: Python 3, Perl, Make (nmake on Windows), + the selected compiler and `third_party/libs/openssl`, initialized with + `git submodule update --init third_party/libs/openssl`. B2 builds the pinned + OpenSSL sources and matching generated headers. Native Trystero's + libdatachannel uses that same provider. Neither `OPENSSL_ROOT` nor + `LIBDATACHANNEL_ROOT` selects a separate installed copy. Source archives + contain the required sources and do not require Git for these builds. Each toolchain is installed by hand and configured in `user-config.jam`, until webcpp bundles the toolchains (`CODING-GUIDELINES.md` chapter 16). b2 reads @@ -352,6 +354,9 @@ Boost headers and sources remain untouched. Every Cobalt target also uses the checked `tools/boost/cobalt-common` header overlay: Boost 1.92's composition promise must connect its cancellation source to the received completion handler. Both compiled operations and application-defined compositions receive this fix. +The common overlay also supplies `unhandled_exception` for main and thread +promises in no-exceptions builds; the thread coroutine is exercised by Asio's +`threads` own lane, natively and on cooperative WASIp3. Rebase and verify the common patch before using a different Boost version. TLS consumers combine the Cobalt target with `/webcpp/asio//tls` and await Asio SSL operations with Cobalt tokens. `/webcpp//boost_cobalt_io_ssl` optionally @@ -361,15 +366,30 @@ associations, fixes handshake state and callback constraints, and exposes a borrowed `native_ssl_handle()` for SNI. `/webcpp/asio//cobalt_ssl` adds the runner and CA factory. Native and WASIp3 consumers share these SSL corrections; browser/WASIp2 are refused. Plain Cobalt does not acquire an OpenSSL dependency. -Run `cobalt_ssl_cancel` through `tools/openssl/test/tls.py --state-test` for -primitive/composed TLS transfer cancellation, truncated shutdown and cancelled -shutdown. Require actual pending operations and transport/protocol observations, +Asio's `tls-integration` own lane drives the real OpenSSL/Cobalt fixtures on +native and WASIp3 profiles, including primitive/composed transfer cancellation, +truncated shutdown and cancelled shutdown. Its native `openssl-upstream` lane +requests `webcpp-openssl-tests=on`: the exact archives pass upstream's full +`alltests` suite before the TLS consumer links. The upstream harness cannot run +on WASIp3; its separate TLS/entropy integration tests do not substitute for it. +The `openssl-upstream-msvc-14.3` and `openssl-upstream-msvc-14.5` aliases +select their matching Windows runners/toolsets; the default native upstream +lane uses Linux. CI uploads upstream logs, proof and build manifests even on +failure. Lane declarations describe recurring coverage, not a successful CI run. Require actual pending operations and transport/protocol observations, not guessed sleeps. Terminal transfer cancellation does not promise safe reuse. Its sources define `BOOST_COBALT_SOURCE=1` and `BOOST_COBALT_IO_SOURCE=1`, while consumers receive `BOOST_COBALT_NO_LIB=1`. On Emscripten, both sources and consumers define `BOOST_ASIO_DISABLE_THREADS`; native thread support is unchanged. Use the shared `BOOST_SOURCE` setup above, not a separate Cobalt source tree. +**Windows Asio allocator overlay.** `tools/boost/asio-windows` passes the +context allocator into Boost 1.92's existing `win_thread` constructor for the +IOCP worker and timer thread. Asio and compiled Cobalt use the same checked +private headers on Windows only. The manifest verifies the original and patched +hashes, without modifying installed Boost. Native allocation tests construct the +context and its first timer inside the counted window. A prepared overlay or a +dry run alone is not evidence that a Windows program ran. + **Cobalt without exceptions.** A build that uses `/webcpp//boost_cobalt` with `exception-handling=off` emits a non-fatal configuration warning with https://github.com/boostorg/cobalt/issues/287 and recommends enabling exception @@ -387,16 +407,13 @@ verified, rather than assuming a newer Boost release fixes the issue. needs: `.local/user-config.jam`, `.local/wasi-sdk/`, `.local/mrdocs/`, `.local/wit-bindgen/` and `.local/wasi-wit/p2` and `p3`, `.local/emsdk` (an install of emsdk, or a link to one) with Emscripten's cache in -`.local/emscripten-cache`, and trystero's libraries in -`.local/secp256k1-native`, `.local/secp256k1-emscripten`, -`.local/libdatachannel` and `.local/openssl` (`include/openssl` and the two -libraries of the system's OpenSSL 3, linked, as the CI's `openssl` action -lays them out), where the CI's actions install them too (chapter 4). The -build finds each of them there with no `-s`: `b2 -a doc`, whose reference -parses trystero's native backend, runs as it is. Another directory is named -with `-sSECP256K1_ROOT=` and its kin on b2's command line, never with -the environment, as for the emsdk below: a variable a shell keeps from -another day would replace `.local/` without a word. A tool the build looks up itself is +`.local/emscripten-cache`, and trystero's external libsecp256k1 installs in +`.local/secp256k1-native` and `.local/secp256k1-emscripten`. The CI action +uses those same paths. B2 finds them without `-s`; another prefix is named +with `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=` on its +command line. Source-built OpenSSL and libdatachannel instead live under the +B2 build directory, separated by the effective compiler configuration. +A tool the build looks up itself is taken from the path its `-s` option gives, else from `.local/`, else from `PATH`: MrDocs (`-sMRDOCS`), wit-bindgen and the WIT (above); wasi-sdk is where the `using clang` lines of `user-config.jam` name it, and, for a @@ -1160,7 +1177,7 @@ too, and `.local/` found, the environment never read, a wrong `-s` refused, a missing library left out once while another library builds, the index's row without a link, and the stop under `webcpp-require-external=on`; `tools/lint/lint_test.py` that the lint's dry -runs require them and name the two libraries. +runs require the declared external dependencies and name any that are missing. **Generated files** (`tools/generated/generated.jam`). A file that a script writes from inputs it pins, such as a table of Unicode data, is committed and @@ -1222,10 +1239,9 @@ webcpp.example xactor_drivers.cpp ; webcpp.example xactor_testing.cpp ; # A static actor, whose behaviour is a Boost.MSM state machine. webcpp.example xactor_msm.cpp ; -# Native only: Boost.Asio 1.92 does not compile for wasm32-wasip2 or -# wasm32-wasip3 with wasi-sdk 34 (no ESHUTDOWN, no ::pause, and a signal.h -# that stops with #error), so drivers.hpp declares asio_driver only outside -# WASI. +# Native only: xactor's Asio driver has not adopted webcpp::asio's checked +# WASIp3 integration. That separate adaptation is not implied by Asio's +# WASIp3 support. webcpp.example xactor_asio.cpp : : native ; ``` @@ -1244,8 +1260,13 @@ b2 -a --dump-tests --out-xml=.xml toolset= libs//test li ``` A wasip2 lane adds `testing.launcher=wasmtime`; a wasip3 lane adds -`testing.launcher=tools/boost/asio-wasip3/run.sh` for network-capable tests. Both apply to -every toolset of one b2 request, so a lane is always one toolset. An +`testing.launcher=tools/boost/asio-wasip3/run.sh`. The latter is the global +WASIp3 test launcher: it grants inherited network and IP name lookup, enables +component async/threading support, and defaults to 600 seconds per process. +`WEBCPP_WASIP3_TEST_TIMEOUT` overrides that finite bound with a positive integer. +These are test-harness settings, not production permissions or a guarantee that +tests never contact an external host. Both launchers apply to every toolset of +one b2 request, so a lane is always one toolset. An emscripten lane adds nothing: b2's toolset runs its programs with node. The lane runs from the superproject's root. `--dump-tests` is required: it lists every test, those the lane skips included, and the report refuses a file without @@ -1528,7 +1549,7 @@ jobs: every library's tests hold it, and trystero's guarantee 6 rests on it. The image is `tools/ci/container/Dockerfile`'s: Ubuntu 24.04, the runner's release, pinned by the digest of its image index, with `g++-14`, - `clang-18`, OpenSSL's development files, Python, Git, Make and Perl, every package, + `clang-18`, Python, Git, Make, Perl and CMake, every package, `ca-certificates` included, from Ubuntu's snapshot of the archive at the date its `ARG SNAPSHOT` names (`Snapshot: yes` on the sources, `apt-get --snapshot`), so that one Dockerfile is one set of packages. The snapshot @@ -1536,9 +1557,9 @@ jobs: reaches it once without verifying the server's certificate, to install `ca-certificates` from the snapshot, and verifies it from then on; apt checks the signed `InRelease` and every index and package against it - whatever the transport. A `ca-certificates` from the live archive would - pull `libssl3t64` forward, and the snapshot's `libssl-dev`, which depends - on its own, would no longer install once Ubuntu updates OpenSSL (measured). + whatever the transport. Mixing a live `ca-certificates` package with snapshot dependencies previously + produced incompatible OpenSSL package versions; the image keeps all packages + on the same snapshot. Consumer OpenSSL is now built from the pinned sources. Ubuntu keeps no snapshot of `ports.ubuntu.com`, so the image builds for x86-64 alone (measured: apt 2.8.3 refuses arm64's sources). It is tagged `webcpp-lane:`. The @@ -1554,25 +1575,16 @@ jobs: docker; the external libraries it runs against are built before, on the runner, with the same compilers. - **External libraries.** A library may need libraries webcpp does not build - yet: `EXTERNAL_DEPENDENCIES` in `tools/ci/matrix.py` names them, trystero's - `secp256k1`, `libdatachannel` and `openssl`, each the CI's action of that - name, until webcpp builds them from `third_party/` (`CODING-GUIDELINES.md` - chapter 16). A lane that builds such a library, or one that uses it, has - `external` in its entry, and so does an own lane of it; such a job runs the - actions after the lane's own setup, by their YAML anchors in both jobs: - `openssl`, then `secp256k1`, with `emscripten: true` on an entry that has - emsdk, then `libdatachannel`, built with the lane's compilers, its entry's - `cc` and `cxx` (`gcc-14` and `g++-14`; Visual Studio for MSVC, CMake's own - choice there). An entry on emscripten has neither OpenSSL nor - libdatachannel, which only the native backend needs. Its b2 command, the - lane's or the own lane's, then has `webcpp-require-external=on`, so that a - library not found stops it rather than leave the library out, and - `-s=` for each variable the actions exported - (`EXTERNAL_VARIABLES`), on the command line, where a library's `build.jam` - reads them; the docs job gives its b2 the same when the plan's `external` is - `true`. A container lane passes no variable of the environment into its - container. + **External libraries.** `EXTERNAL_DEPENDENCIES` in `tools/ci/matrix.py` + currently names only trystero's `secp256k1`. A lane that needs it has + `external` in its entry, including own lanes. Its job runs that action after + toolchain setup, with `emscripten: true` when applicable and the lane's + compiler settings. B2 receives `webcpp-require-external=on` and explicit + `-sSECP256K1_ROOT` / `-sSECP256K1_EMSCRIPTEN_ROOT` arguments from the action's + outputs (`EXTERNAL_VARIABLES`); docs use the same setup when required. + OpenSSL and libdatachannel have no provisioning actions: their pinned source + targets build in the consumer's B2 variant, including inside container lanes. + A container lane passes no variable of the environment into its container. - **own lanes,** one job per entry, named and placed as the entry says (`name`, `os`), which runs `matrix.py own-lane `: it registers the lane's toolset, prints its b2 command and runs it, on the lane in each of @@ -1747,65 +1759,20 @@ wrapper each quoted as one word of Jam. local node = /path/to/node ; using emscripten : : $(emsdk)/upstream/emscripten/em++ : $(node) ; ``` -- `openssl`, `secp256k1` and `libdatachannel` install trystero's external - libraries where its `build.jam` looks for them, in `.local/`, and give the - later steps their variables (`$GITHUB_ENV`), on Linux and macOS, x86-64 - and arm64, and on Windows x86-64: - - `openssl` lays out the runner's own OpenSSL 3 in `.local/openssl` and - exports `OPENSSL_ROOT`: on Linux the system's, which `pkg-config` names, - and on macOS Homebrew's `openssl@3`, each as links to its - `include/openssl` and its two libraries, so that a compiler is given a - directory of its own, never `/usr/include` (GCC 14 and Clang 18 given - `-isystem /usr/include` no longer find the C library's headers through - libstdc++'s `#include_next`, as a reference parses its dependencies' - directories); Debian and Ubuntu keep the headers of OpenSSL's build - configuration, `opensslconf.h` and `configuration.h`, in the - architecture's `/usr/include//openssl`, which - `dpkg-architecture` names, and which a parse for another target, as - trystero's reference is (chapter 2), does not search: there - `include/openssl` is a directory of links to each header of both, and a - layout without `opensslconf.h` fails the action; on Windows, copies of the headers and of the import - libraries `libssl.lib` and `libcrypto.lib` of the image's installation in - `%ProgramFiles%\OpenSSL` (from the first of `lib/VC/x64/MD`, - `lib/VC/x64/MDd` and `lib` that holds both), whose `bin`, with the DLLs, - it puts on `PATH`. The image's is always preferred; only an image without - one has the installer of Shining Light Productions, pinned by the SHA-256 - that `slproweb/opensslhashes` records, which Shining Light removes once - superseded, so that fallback then fails at `download.sh`, naming the URL, - until the pin moves. On macOS, when the image lacks `openssl@3`, which it - has today only as a dependency of other formulae, the action installs it - with `brew`, which checks its bottle against its formula's SHA-256, and - says so in its log. It fails, naming it, on one that is not OpenSSL 3. - - `secp256k1` builds libsecp256k1 0.8.0 from GitHub's archive of its - commit `6e2c8bc`, checked against its SHA-256, with CMake, static, with - its `schnorrsig` and `extrakeys` modules and the small tables trystero's - page builds it with, into `.local/secp256k1-native`, with the input - `cc` (the lane's C compiler, else CMake's own), and with `emscripten: - true` also with Emscripten's `emcmake`, after the emsdk action, into - `.local/secp256k1-emscripten`; it exports `SECP256K1_ROOT` and - `SECP256K1_EMSCRIPTEN_ROOT`. The emscripten build's cache key names the - Emscripten version the emsdk action installs, read from its - `install.sh`, so that a bump of emsdk builds it again. - - `libdatachannel` clones the tag `v0.24.6`, fails unless `git rev-parse - HEAD` is the tag's commit `6b1e2e6`, read with `gh api`, and only then - fetches its submodules, at the commits that commit's gitlinks name, so a - tag that moved never has git fetch from the URLs its `.gitmodules` would - name; it builds it shared, `NO_WEBSOCKET`, `NO_EXAMPLES` and - `NO_TESTS` on and `NO_MEDIA` off, against the OpenSSL `OPENSSL_ROOT` - names (the `openssl` action runs first), with the inputs `cc` and `cxx`, - into `.local/libdatachannel`; it exports `LIBDATACHANNEL_ROOT`, and on - Windows puts its `bin`, with `datachannel.dll`, on `PATH`, where a test - b2 runs finds it. - - The two that build are cached, keyed on the version, the runner, the - compilers' own `--version` (else the image), the emscripten build or - OpenSSL's version, and the action's files. On Windows they build CMake's - Debug configuration: b2's debug variant, the lanes', builds with `/MDd`, - whose standard types differ from `/MD`'s, and a DLL whose C++ API a - program shares must match it. CMake names libsecp256k1's library - `libsecp256k1.lib` there, and a program that links it statically defines - `SECP256K1_STATIC`, which trystero's `build.jam` does on `msvc`, with - OpenSSL's `libssl` and `libcrypto`. +- `secp256k1` builds libsecp256k1 0.8.0 from GitHub's archive of commit + `6e2c8bc`, checked against its SHA-256, with CMake, static, with `schnorrsig` + and `extrakeys` and the small tables trystero's page specifies. It installs + in `.local/secp256k1-native`, using the lane's C compiler, and, when requested, + builds with Emscripten's `emcmake` into `.local/secp256k1-emscripten` after + emsdk setup. It exports `SECP256K1_ROOT` and `SECP256K1_EMSCRIPTEN_ROOT`. + The cache key includes its version, runner, compiler identity, action files + and the emsdk version for a browser build. Windows uses CMake's Debug + configuration for the CI's debug runtime and the static library name + `libsecp256k1.lib`; trystero defines `SECP256K1_STATIC` there. + OpenSSL and libdatachannel instead build from source through B2. The latter's + static datachannel, juice, usrsctp and srtp2 archives stay separate; it never + bundles another OpenSSL archive into them. Its CMake recipe uses the exact + OpenSSL headers and archive bytes selected by the B2 dependency. - `chrome` installs Chrome for Testing's `chrome-headless-shell` 155.0.8059.39, the Stable channel of Google's `last-known-good-versions-with-downloads.json` when it was pinned, from @@ -1855,18 +1822,15 @@ they leave out, and their refusals: a runner no build of wit-bindgen or emsdk is pinned for, a crate that holds no WIT, an emsdk at another commit, a release without its `node_modules`, an archive emsdk would download unpinned, and an emcc that is not 6.0.11; the emsdk action's node wrapper, -`EM_CACHE`, warmed cache and system libraries; for the external -libraries, the commands each action builds with, where it installs, what it -exports and its cache key (the emscripten build's from the emsdk action's -version), libdatachannel's submodules fetched only after its commit is -checked, macOS's `openssl@3` installed with `brew` when absent, and the -headers of Debian's `include//openssl` linked beside the others; the -chrome action's shell and its `--no-sandbox` wrapper; the container action's -image, built and saved once, then loaded; and their refusals: an archive of libsecp256k1 -whose SHA-256 is not the pinned one, a libdatachannel at another commit, -libdatachannel without `OPENSSL_ROOT`, an OpenSSL that is not 3, one -whose headers hold no `opensslconf.h`, a chrome-headless-shell whose SHA-256 is not the pinned one, and a -runner none of them builds for. +`EM_CACHE`, warmed cache and system libraries; libsecp256k1's pinned archive, +compiler settings, install prefixes, exports, cache key and Windows runtime; +the chrome action's shell and its `--no-sandbox` wrapper; and the container +image, built and saved once, then loaded. Their refusal tests cover bad hashes +and unsupported runners. Source-provider tests live in +`tools/openssl/build_test.py`, `tools/test/openssl_test.py` and +`tools/test/libdatachannel_test.py`: they cover source pins, staged content, +compiler variants and the single OpenSSL provider. They are separate from +runtime evidence and the full upstream OpenSSL suite. **The site.** On every run of the superproject's CI, the job `site` runs `b2 site`, the preview ("The site", above), with the pages the docs job built @@ -1956,14 +1920,22 @@ targets, which run only when named: --init` runs first: a submodule of HEAD not checked out fails it by name (`git submodule update --init libs/`). -`dist` also bundles the tracked sources and upstream licences of the root -source submodules `site` and `third_party/libs/`, at their recorded -commits, with no dot files. Each must be checked out at that commit and hold -no uncommitted changes. It never initializes submodules. The unused upstream -nested submodules of `third_party/libs/nativejson-benchmark` are omitted, as -`CODING-GUIDELINES.md` chapter 10 requires; its own sources, benchmark data -and licence are bundled. Every other unsupported root or nested submodule is -refused by name, so required sources are never silently omitted. +`dist` also bundles the tracked sources and upstream licences of `site` and +`third_party/libs/` at their recorded commits, with no dot files. Required +libdatachannel nested repositories (`libjuice`, `libsrtp`, `plog`, `usrsctp`) +are included at the exact gitlinks recorded in `tools/libdatachannel/pin.json`. +The policy applies only when its parent commit matches the root's source pin. +Each included checkout must be clean and at its recorded commit; initialize +libdatachannel recursively before packaging. `dist` never initializes sources. +Unused nativejson-benchmark submodules and the exact optional OpenSSL and +libdatachannel gitlinks listed in their pin files are omitted. A changed or +unknown nested gitlink is refused, never silently skipped. Source builders +validate the distributed paths, file modes and content hashes before executing +upstream build code, so an unpacked archive needs no Git metadata. + +A successful release check or source archive is preparation evidence. It neither +publishes 0.1.0 nor proves the final candidate's CI. Keep `In preparation` and +`Unreleased` until the separately authorized release procedure below. Nothing is released until the owner asks. Then: diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 9ba9a406..89c24db9 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -231,8 +231,10 @@ A test's helpers that are shared between tests go in `webcpp::test` ## 4. The language -- C++20, header-only. The Jamroot sets `20`, `extra` and - `on` for everything. +- C++20, header-only except the explicitly documented units that must be linked + once per program, such as Asio's JavaScript imports and Cobalt entry point + (chapter 15). B2 supplies those units; users do not copy them into applications. + The Jamroot sets `20`, `extra` and `on`. - **What a library builds on, in this order:** what webcpp already has; then Boost (boost.org); then the C++ Alliance's libraries ([cppalliance](https://github.com/cppalliance)), whose authors are Boost's; @@ -297,7 +299,9 @@ A test's helpers that are shared between tests go in `webcpp::test` parameter or a `std::pmr::memory_resource`, with no requirement to live in a shared segment. - Each library's page says which of its types are shareable, and a test - that counts allocations proves that none goes elsewhere. + counts allocations. An approved exception for runtime or wrapped-library + storage is named in chapter 15 and the guide, measured separately where a + hook exists, and never hidden by a tolerance for unexplained allocations. A library ported or written from now on is born with this rule, as pratt is: its calculator's environment takes the user's `Allocator`; and as @@ -307,11 +311,12 @@ A test's helpers that are shared between tests go in `webcpp::test` resource, which a counting test proves natively and on emscripten. The libraries written before it are brought to it by a review (chapter 16). -- **Asynchronous code is built on xactor.** A library that ports anything - asynchronous runs it as actors on xactor, whose scheduler drives every - library the same way, deterministically, and in a browser from the page's - event loop, which owns the system's events. How such a library meets - Boost.Asio and Boost.Cobalt is still to be designed (chapter 16). +- **Asynchronous code runs on the executor its user supplies.** Libraries use + Asio-compatible executors and completion mechanisms without driving the run + family internally. A library whose model is actors uses xactor; its application + drives that scheduler from its event loop. This records the owner's accepted + Asio decision of 2026-10-11, rather than requiring the event loop itself to be + implemented as actors. - **Text** is passed and held as `std::string_view` where nothing must own it; `std::string` only where something does. - **A function starts with its guards:** every condition it needs is checked @@ -394,7 +399,11 @@ exactly its authors' and the program carries only what it calls. ## 6. Exceptions and RTTI -- **Every target builds with exceptions on.** Whether a program uses them is +- **Every supported target profile with a C++ exception runtime builds with + exceptions on.** A threading profile whose SDK supplies no such runtime + refuses `exception-handling=on` by name; the feature matrix identifies that + limitation. WASI SDK 34's experimental cooperative sysroot is one such + profile, to be rechecked on SDK upgrades. Whether a program uses exceptions is the choice of whoever builds it, never an imposition of a library or of webcpp. Natively the compiler's default holds. On wasip2 and wasip3 the Jamroot compiles with `-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false` @@ -875,6 +884,7 @@ update --init third_party/libs/`; a build that needs none never looks. | Target | What it is | Licence | | --- | --- | --- | | `ca_certificates` | Dated Mozilla/curl CA data snapshot under `third_party/ca_certificates`, verified against its manifest and embedded by a build-generated header; updated explicitly by `tools/ca_certificates/update.py` | MPL-2.0 | +| `libdatachannel` | libdatachannel 0.24.6 at `6b1e2e620f1e37f0eafeee702eaea0043cb305fd`, with pinned libjuice, libsrtp, plog and usrsctp sources; static native archives built by upstream CMake through B2 against the same source-built OpenSSL | MPL-2.0 and the nested dependencies' own licences | | `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC and WASIp3 | Apache-2.0 | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | @@ -889,6 +899,17 @@ After explicitly updating the source commit, regenerate this metadata with `python3 tools/openssl/update.py`; never edit the generated inventory by hand. The pinned commit timestamp supplies the default reproducible-build epoch. +Libdatachannel follows the same source-integrity boundary with +`tools/libdatachannel/pin.json`. Its required nested repositories are included +at their pinned gitlinks in source archives; only the explicitly listed unused +nested sources are omitted. A checkout needs recursive initialization, while an +archive builds without Git. B2 invokes upstream CMake for separate static +archives, with system dependency discovery disabled and the exact OpenSSL +provider's headers and archive hashes checked first. Native consumers select +`threading=multi` and matching compiler/runtime settings. This provider decision +permits Asio, Beast and native Trystero in one program; it does not complete +Trystero's later API migration or prove libdatachannel's upstream test suite. + The CA bundle is an authorized exception to the source-submodule rule: curl publishes dated PEM artifacts, preserved byte-for-byte with source URL, SHA-256, certificate inventory and MPL notices. It is data, not copied implementation @@ -1142,10 +1163,13 @@ site's own decisions follow in the next sections. Source: `organization/openspec/specs/organization/spec.md` (proposals). - **The compiled Boost libraries a library needs, Boost.URL, Boost.Charconv, Boost.Locale without ICU and Boost.Cobalt, are built by webcpp from Boost's - own source archive, for every target, as `/webcpp//boost_url` and its kin.** - Native, wasip2, wasip3 and emscripten then build the same sources with the - same macros; an installed Boost cannot be relied on (Homebrew's has no - `libs/url/src`), and the sources' version must equal the configured Boost's. + own source archive for their supported targets, as `/webcpp//boost_url` and + its kin.** Each archive follows its consumer's target, macros and compiler + configuration; Cobalt is unavailable on WASIp2. Checked Asio/Cobalt overlays + apply only to private copies, with original and patched hashes and an exact + Boost-version check (AGENTS.md chapter 1). An installed Boost cannot be + relied on for sources (Homebrew's has no `libs/url/src`), and the sources' + version must equal the configured Boost's. Source: `organization/openspec/changes/archive/2026-10-07-genesis/design.md` (proposals). - **Boost.JSON's definitions and Boost.Test's header-only framework are @@ -1170,13 +1194,14 @@ site's own decisions follow in the next sections. a lane's toolset from those regions and a page includes them, so that neither drifts from the other; bundled toolchains are on the roadmap. Source: `AGENTS.md` (webcpp). -- **A library webcpp does not build yet (trystero's libsecp256k1, - libdatachannel and OpenSSL) is declared with `webcpp.external`: a build that +- **A library webcpp does not build yet (currently trystero's libsecp256k1) + is declared with `webcpp.external`: a build that does not find it leaves its owner out with one line, and the CI and the lint, with `webcpp-require-external=on`, stop instead.** Left out, every other library still builds with `b2 test`; required, a library not found stops the build rather than leave the library out. The CI's actions build - them until webcpp builds them from `third_party/`. + that remaining dependency until it moves to `third_party/`. OpenSSL and + native libdatachannel already use pinned source targets. Source: `AGENTS.md` (webcpp). **Targets and toolchains.** @@ -1233,8 +1258,8 @@ site's own decisions follow in the next sections. - **Every archive the CI downloads is checked against a recorded SHA-256, every third-party action is pinned by its full commit SHA, and a tool fetched with git is checked against its pinned commit.** emsdk checks none - of its downloads, a tag that moved (libdatachannel's) would otherwise have - git fetch from the URLs its `.gitmodules` names, and the interop lanes get a + of its downloads itself. Source dependencies also validate their required + nested gitlinks before building. The interop lanes get a pinned chrome-headless-shell so that a red lane is never a browser nobody chose. Source: `AGENTS.md` (webcpp). @@ -5950,12 +5975,14 @@ which includes the change `shared-connection` (trystero `2e2dcd4`, webcpp includes the native backend, so `/webcpp/trystero//trystero` depends on neither, as OpenSSL is optional for Asio. Source: `doc/design.adoc` (libs/trystero). -- **The external libraries are found where `-s_ROOT` on b2's command - line says, else in the superproject's `.local/`, else natively in - `/usr/include` or `/usr/local/include`; the environment is never read.** - `.local/` is where webcpp's CI installs them, until webcpp builds them from - `third_party/`, and a variable a shell keeps from another day must never - replace `.local/` without a word. +- **Only libsecp256k1 is externally provisioned, through command-line + `SECP256K1_ROOT` / `SECP256K1_EMSCRIPTEN_ROOT`, then `.local/`, then native + system paths outside Windows; the environment is never read.** Native + libdatachannel and its nested dependencies are now pinned source targets, + built statically against the same OpenSSL provider as Asio and Beast. + Native Trystero requires `threading=multi` and exceptions because its backend + uses worker threads. These dependency changes prepare the later migration; + they do not claim that Trystero already uses the webcpp facades. Source: `doc/building.adoc` (libs/trystero). - **A library found nowhere leaves trystero out with one message, unless `webcpp-require-external=on`, as the CI builds, stops the build.** `b2 test` @@ -5970,9 +5997,9 @@ which includes the change `shared-connection` (trystero `2e2dcd4`, webcpp requirements (measured: a program then fails to link, `_embind_register_function` undefined). Source: `build.jam` (libs/trystero). -- **On MSVC the libraries take CMake's and Shining Light's names - (`libsecp256k1` with `SECP256K1_STATIC`, `libssl`, `libcrypto`, also in - `lib/VC/x64/MD`), and the tests and examples add `/bigobj`.** A static +- **On MSVC the external library is `libsecp256k1` with + `SECP256K1_STATIC`, the source providers export their static `.lib` archives + with the consumer's runtime settings, and tests and examples add `/bigobj`.** A static libsecp256k1 on Windows declares every function imported from a DLL without the define, and a test of rooms over Asio holds more sections than the default object format allows (C1128). @@ -6090,33 +6117,36 @@ which includes the change `shared-connection` (trystero `2e2dcd4`, webcpp example needs the public relays or a browser. Source: `doc/differences.adoc` (libs/trystero). -### asio (Boost.Asio and Cobalt on native, Emscripten and WASIp3; integrated locally on 2026-11-02) +### asio (Boost.Asio and Cobalt on native, Emscripten and WASIp3; implemented for 0.1.0 in preparation) -webcpp::asio is a header-only C++20 wrapper over Boost.Asio: natively it is +webcpp::asio is a C++20 wrapper over Boost.Asio: natively it is Boost.Asio itself, and on Emscripten it is Boost's own `io_context`, whose run family suspends into the browser's event loop and yields to it after every turn of `max_handlers_per_turn` handlers, with a bridge through which browser events post, promises and DOM events as Asio operations, sockets and a resolver that fail as values, and Boost.Cobalt's `co_main` on that loop. The implementation, source-built OpenSSL, embedded CAs and Cobalt SSL are integrated -locally with the owner's authorization. The verification and integration record -is [the local closeout](docs/superpowers/plans/2026-11-02-local-integration.md). -No CI validation is claimed. The remaining proposal-wide documentation and -conformance items of tasks 22 and 23 are separate from this integration; the -unresolved items in chapter 19 remain open. +with the owner's authorization in superproject `2ba5116`. The published library +repository is `webcpporg/asio`. The original integration record is +[the local closeout](docs/superpowers/plans/2026-11-02-local-integration.md); +[the joint closure](docs/superpowers/plans/2026-11-03-asio-beast-closure.md) covers +tasks 22/23, the complete review and final CI. Version 0.1.0 is in preparation, +not a published release. Pending gates are not claimed complete here. The source labels below retain the design inventory read on 2026-10-26: `genesis/` means `libraries/asio/openspec/changes/genesis/` in proposals; (asio) was `f5fd7a8`, (superproject branch) was `d159022`, and (main) was -`ddb6cb2`. References labelled "uncommitted" describe that historical working -tree, subsequently committed as Asio `6a7f3fe` and superproject `c07c212`. -The dated observations are not the current Git status. +`ddb6cb2`. Those historical sources were subsequently committed as Asio `6a7f3fe` and +superproject `c07c212`. Current contracts below include the owner's 2026-11-03 +amendments; old dates and commits identify evidence, not the current Git status. +Baseline CI 41597577370 at root `55a72c0` does not validate the closure tree. +Asio's first library-main CI and the final joint candidate remain separate gates. **Decided.** **Interface and names.** -- **`webcpp::asio::io_context` derives from `boost::asio::io_context` on both +- **`webcpp::asio::io_context` derives from `boost::asio::io_context` on its supported targets, shares its executor type and converts to `boost::asio::io_context&`; the timers are aliases of Boost's, and a program keeps naming `post`, `co_spawn`, `use_awaitable` and `bind_executor` from @@ -6137,11 +6167,16 @@ The dated observations are not the current Git status. of the rest should not pay for. Source: `genesis/specs/asio/spec.md`, Library: Convenience header (proposals). -- **`` includes `` and defines - `WEBCPP_ASIO_NO_EXCEPTIONS` exactly when `BOOST_NO_EXCEPTIONS` is defined, - keeping a developer's own definition; an API that throws sits behind it and - raises through `boost::throw_exception`.** Code that uses a throwing API - then does not compile without exceptions. +- **`` includes `` first and + derives `WEBCPP_ASIO_NO_EXCEPTIONS` from the collection's exception policy, + preserving an explicit library override.** The public target and browser + source target depend on `/webcpp/config//config`. `WEBCPP_NO_EXCEPTIONS` + and compiler exception settings agree with the library macro; `config_all_off` + exercises a real global-disable consumer. Public headers include config first, + and public platform selections use the collection's target macros. + The compiler-forced `src/openssl_on_webassembly.hpp` refusal intentionally + tests the compiler macro before normal configuration headers are available. + Throwing APIs stay guarded and raise through `boost::throw_exception`. Source: `genesis/specs/asio/spec.md`, Library: Configuration header (proposals). - **On Emscripten `/webcpp/asio//asio` gives every translation unit, @@ -6151,11 +6186,12 @@ The dated observations are not the current Git status. supported!"; its inline namespace differs with and without threads, so a unit that missed it fails at link, never silently. Source: `genesis/specs/asio/spec.md`, Build (proposals). -- **The library's targets are native and Emscripten, and a library built on it - declares native and Emscripten at most.** Boost.Asio 1.92 does not compile - for wasm32-wasip2 or wasm32-wasip3 with wasi-sdk 34; a WASI backend is a - later increment with its own specification. The local WASIp3 port departs - from this (below). +- **The library supports native, Emscripten and WASIp3 through the checked + Boost 1.92 overlay; guest sockets on WASIp2 remain unavailable.** A library + may declare only the targets its actual APIs support. Beast's portable + messages and WASI host HTTP do not require guest sockets. xactor's existing + Asio driver stays native until separately adapted; Asio's port does not + silently extend that driver's target set. Source: `genesis/design.md`, D16 (proposals). - **A library built on webcpp::asio is given an executor and never calls `run`, `run_one` or `run_for`; a program's own call says why after @@ -6375,10 +6411,11 @@ The dated observations are not the current Git status. claims no safety. Source: `genesis/reference/STATUS.md` (proposals); `AGENTS.md`, chapter 1 (superproject branch). -- **Exception-free Cobalt consumers suppress Clang's - `coroutine-missing-unhandled-exception` diagnostic, and no other.** Boost - omits `main_promise::unhandled_exception` without exceptions. - Source: `build.jam`, `AGENTS.md` (asio). +- **The checked common Cobalt overlay supplies `unhandled_exception` for + main and thread promises when exceptions are disabled.** Boost 1.92 omits + these hooks; the overlay uses `std::terminate` for the unreachable exception + path, keeping strict compiler diagnostics and actual worker/join tests. + Source: `tools/boost/cobalt-common/boost-1.92.patch` (superproject). **Allocation.** @@ -6403,10 +6440,10 @@ The dated observations are not the current Git status. **Timers, promises and events.** -- **Timers are Boost's on both targets, in the reactor's timer queue: Beast's - timeouts fire, and an idle program holds the reactor's one `setTimeout`, of - at most 300 s, and schedules nothing else.** The program's code runs only - when the browser delivers an event, never by polling. +- **Timers are Boost's on every supported target, in the reactor's timer + queue: Beast's timeouts fire.** On Emscripten an idle program holds the + reactor's one `setTimeout`, of at most 300 s, and schedules nothing else. + Its code resumes when the browser delivers an event, never by polling. Source: `genesis/specs/asio/spec.md`, Timers and Browser (proposals). - **`async_await(executor, promise, token)` and `async_wait_event(executor, target, type, token)` initiate through @@ -6445,19 +6482,19 @@ The dated observations are not the current Git status. not forwarded and moved-from transports unusable. Source: `genesis/design.md`, D13, and `genesis/reference/STATUS.md` (proposals). -- **The resolver resolves nothing (option A): one entry with the host and +- **The browser resolver resolves nothing (option A): one entry with the host and service names, an unspecified address and the service's port; reverse resolution, and a plain socket's connect on the entry, fail with `operation_not_supported`.** Only webcpp::beast's browser streams accept the entry, so Beast's layered client code runs unchanged; a resolver that failed like the sockets would change a line of every Beast client. Source: `genesis/design.md`, D14 (proposals). -- **`` is Boost's `ssl` natively and on Emscripten a - record of the program's TLS settings, its host name in `std::pmr` storage, - which only webcpp::beast's browser streams read; a program names - `/webcpp/asio//openssl` for its native builds alone, and naming it for - WebAssembly stops the compile with an instruction.** The browser owns TLS - there, and the owner rejected ignoring the target on WebAssembly. +- **`` is Boost's `ssl` on native and WASIp3; on + Emscripten it records TLS settings and a host name in `std::pmr` storage + for webcpp::beast's browser streams.** Guest TLS explicitly names + `/webcpp/asio//openssl` on native or WASIp3. Naming that source provider for + Emscripten or WASIp2 fails with an instruction; the browser owns TLS in its + profile, and WASIp2 host HTTP uses the host's independent TLS implementation. Source: `genesis/design.md`, D15 (proposals); `include/webcpp/asio/ssl.hpp` (asio). @@ -6466,7 +6503,8 @@ The dated observations are not the current Git status. - **Cobalt's `main_promise::run_main` and `final_suspend` are webcpp's (`src/cobalt_main.cpp`, `/webcpp/asio//cobalt`), with Cobalt's steps over a `webcpp::asio::io_context{BOOST_ASIO_CONCURRENCY_HINT_1}`, and - `/webcpp//boost_cobalt` compiles every Cobalt source but `main.cpp`.** + `/webcpp//boost_cobalt` excludes `main.cpp` and the optional `io/ssl.cpp`, + with additional unsupported sources omitted for WASIp3 as listed below.** `co_main` cannot be replaced from a header: `main` is a hidden friend that calls `run_main`, compiled in Cobalt's `src/main.cpp`, which calls Boost's `run`; compiling against the pinned Boost probes the private members it @@ -6494,62 +6532,69 @@ The dated observations are not the current Git status. pipeline. Source: `genesis/reference/STATUS.md`, task 14 (proposals); `doc/guarantees.adoc` (asio). -- **Nothing is published before the whole-branch review is fixed and the owner - has taken the three gates (G1 the repository, G2 the submodule, G3 the - library pushed before the superproject); no agent pushes, creates a - repository or changes a GitHub setting.** The rulebook's checklist makes the - repository and the submodule the owner's. - Source: `genesis/specs/asio/spec.md`, Release (proposals). - -**Departures the owner approved.** The owner approved all five on 2026-10-11; -recording that approval in the ledger is task 23.4, open. - -- **1. The own lane `asyncify` runs on every push, not at the nightly and - release levels the spec settled.** The CI's levels do not exist, and no - Asyncify in the CI would break the owner's "every variant tested"; running - it on every push tests more, not less. Status: in effect in `test/Jamfile`; - no CI has run it; it moves when the levels come, which task 22 writes into - the roadmap (chapter 16). - Source: `genesis/reference/plan.md`, Departures from the spec, and - `genesis/tasks.md` (proposals). -- **2. `io_context` has two constructors more than the spec's three, - forwarding Boost's concurrency hint with and without an allocator.** Boost's - idiom `io_context io{1}` compiles, and webcpp's Cobalt `run_main` keeps - Cobalt's `BOOST_ASIO_CONCURRENCY_HINT_1`. Status: implemented in task 4 - (`names_test`), used by task 16. - Source: `genesis/reference/plan.md`, Departures from the spec (proposals). -- **3. `/webcpp//boost_cobalt` leaves out Cobalt's `io/ssl.cpp`.** It needs - OpenSSL, which the program names, so `boost::cobalt::io::ssl_stream` does - not link until Cobalt's TLS sources are built against the program's OpenSSL. - Status: implemented in superproject `8829e99`; the uncommitted - `/webcpp//boost_cobalt_io_ssl` of 2026-10-16 now builds that source as a - library of its own, natively and on WASIp3. - Source: `genesis/reference/plan.md`, Departures from the spec (proposals); - `tools/boost/cobalt-ssl/Jamfile` (superproject, uncommitted). -- **4. `/webcpp/asio//openssl` links the system's OpenSSL, shared, with no - static choice, until webcpp::crypto's `/third_party//openssl` exists, and - the target is refused on WebAssembly.** The shared-or-static feature of - chapter 5's rule 7 comes with `/third_party//openssl`, which - webcpp::crypto's plan builds; the owner approved this part a and rejected - ignoring the target on WebAssembly. Status: implemented in `d438a61` through - `webcpp.external`; superseded in the uncommitted tree by OpenSSL 3.5.9 built - from source, static only, natively and on WASIp3, without webcpp::crypto. - Source: `genesis/reference/plan.md`, Departures from the spec (proposals); - `build.jam` (asio, uncommitted). -- **5. Native suites without exceptions run only on Emscripten for now.** - Native runs without exceptions wait for the CI's native no-exceptions lane, - a levels item, while every browser test has its no-exceptions twins and the - lint analyses every native program without exceptions. Status: in effect; - `flag_scope_no_exceptions`, `ssl_no_exceptions` and the Cobalt programs - already run natively without exceptions, and the local matrices of - 2026-10-16 ran native profiles with exceptions off. - Source: `genesis/reference/plan.md`, Departures from the spec (proposals); - `test/Jamfile` (asio). +- **The release record distinguishes repository integration, CI and a + published release.** The repository and submodule exist, and the owner + authorized the joint closure's pushes and merges on 2026-11-03. That does + not authorize a release tag. Final review and CI must describe the exact + candidate, with root workflow integration before library-main CI because + those workflows consume `library.yml@main`. Baseline CI is not evidence for + later edits. The AsciiDoc changelog and 0.1.0 New Libraries entry remain + preparation metadata until a release is requested. + Source: `docs/superpowers/plans/2026-11-03-asio-beast-closure.md` (superproject). + +**Earlier approved departures and their current scope.** The owner approved +five bounded departures on 2026-10-11. The later source-provider decision +supersedes the temporary system-OpenSSL choice; it does not reopen every rule. + +- The `asyncify` own lane runs on every push while nightly/release CI levels + remain roadmap work. Declaring it does not establish that Asio main has run it. +- The concurrency-hint `io_context` constructors remain intentional extensions, + with and without an allocator, including Cobalt's `io_context{1}` use. +- Plain `/webcpp//boost_cobalt` omits `io/ssl.cpp`; the explicit + `/webcpp//boost_cobalt_io_ssl` target now supplies it for native and WASIp3. +- The former shared system OpenSSL/native-only bridge is superseded by the + pinned static source provider on native and WASIp3, without waiting for crypto. + Chapter 5 rule 7 retains its Configure/Make and exact-archive canary exception. +- Dedicated no-exceptions programs and local complete suites run natively; + the general CI-level expansion remains chapter 16 work. Do not mistake those + programs for proof of every native compiler and profile. + +**Compatibility and allocation boundaries.** The existing +`webcpp.asio.tls` category and `tls_context_error` values 1 to 3 remain public +identities alongside `webcpp.asio`. Preserving callers' comparisons is a bounded +compatibility departure from chapter 4's single-category naming convention; +merging or renumbering those errors is not an approved cleanup. +TLS category identity uses the fixed Boost.System ID `0x6173696f2e746c73` +(ASCII `asio.tls`), so codes compare equally across hidden native shared-library +boundaries. This does not make category virtual functions safe after a provider +library is unloaded; callers retain that library while using its error values. + +The browser resolver owns host/service copies through the completion token's +associated allocator, captured when `async_resolve` creates the operation. It +still resolves inside initiation, so deferred tokens remain lazy and inputs +survive caller mutation. A deferred operation needs its allocator bound at +creation; binding only when starting it cannot retroactively select storage. +Boost resolver result entries have no allocator hook and remain a named boundary, +as do Emscripten's select poll storage and Asyncify unwind storage. OpenSSL's +process-global allocator is a separate boundary below, never installed by the +TLS context factory. + +Allocation witnesses now execute on WASIp3 single with exceptions on/off and +cooperative with exceptions off. They distinguish supplied allocator storage, +global C++ allocation and wrapped C allocation. The narrowly attributed wasi-libc +pipe creation and writes to tracked pipe descriptors have positive controls; +the witness does not classify arbitrary Boost allocations as runtime storage. +This proves the exercised operations, not all possible library paths. +The `threads` own lane contains `cobalt_thread`, `wasi_core_threads` and the +threaded allocation witness on native/WASIp3. Real exception unwinding in the +single profile and standalone `ssl.hpp` are also tested on WASIp3. **WASIp3 and TLS beyond the original proposal.** These increments were implemented with local specs and plans under `docs/superpowers/` and integrated on 2026-11-02 after the owner's instruction to finish the remaining integration. -The original proposal has not been amended and no CI ran. +The owner ratified these additions to the proposal on 2026-11-03. Its amended +D15/D16 now distinguish WASIp3 sockets and guest TLS from the browser adapters. +The closure record distinguishes the baseline CI from validation of later changes. - **Asio runs on WASIp3 (`clang-wasip3`) through a checked patch of Boost 1.92's platform layer, applied to private headers under @@ -6559,12 +6604,11 @@ The original proposal has not been amended and no CI ran. untouched, and the preparation refuses another Boost version or a modified input rather than compile unpatched headers. Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md`, - `tools/boost/asio-wasip3/README.md` (superproject, uncommitted). + `tools/boost/asio-wasip3/README.md` (superproject). - **On WASIp3 the io_context uses Boost's own run family, with no turn limit, bridge or yield.** Its system calls suspend through wasi-libc and the host's Component Model. - Source: `doc/capabilities.adoc`, `include/webcpp/asio/io_context.hpp` (asio, - uncommitted). + Source: `doc/capabilities.adoc`, `include/webcpp/asio/io_context.hpp` (asio). - **`threading=single` disables Asio's threads, with exceptions on or off; `threading=multi` selects wasi-sdk's experimental cooperative sysroot with `-pthread`, exceptions off, and a combination the SDK cannot supply stops @@ -6572,13 +6616,15 @@ The original proposal has not been amended and no CI ran. implementation in silence, and wasi-sdk 34's cooperative sysroot has no C++ exception runtime. Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md`, - `tools/webcpp-wasi.jam` (superproject, uncommitted). + `tools/webcpp-wasi.jam` (superproject). - **The WASIp3 tests use the project-pinned Wasmtime 50.0.1 through the launcher `tools/boost/asio-wasip3/run.sh`, which grants network and name lookup and - bounds a run to 15 s.** Wasmtime 47.0.3 cannot load the cooperative - component, and the loopback tests need the network; the launcher is no - production capability policy. - Source: `tools/boost/asio-wasip3/README.md` (superproject, uncommitted). + defaults to 600 s per process.** This launcher is used by the global WASIp3 + lanes, including non-network workloads. `WEBCPP_WASIP3_TEST_TIMEOUT` can + select another positive finite bound. Wasmtime 47.0.3 cannot load the + cooperative component. These grants and limits are test-harness settings; + they neither configure production capabilities nor enforce network isolation. + Source: `tools/boost/asio-wasip3/README.md` (superproject). - **UDP `send_to` and `async_send_to` gather several nonempty buffers into one datagram, in storage from the context's allocator (synchronous) or the handler's (asynchronous), released before the handler runs; a receive or a @@ -6586,22 +6632,20 @@ The original proposal has not been amended and no CI ran. `operation_not_supported`.** wasi-libc has no `sendmsg`, datagram boundaries never change to make a buffer sequence compile, and no hidden allocation emulates scatter/gather. - Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md` (superproject, - uncommitted); `AGENTS.md` (asio, uncommitted). + Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md` (superproject); `AGENTS.md` (asio). - **What WASI lacks is explicit: Asio's `shut_down` error maps to `EPIPE`, interface-name scopes are refused, a missing socket option reports `operation_not_supported`, and an asynchronous resolve without threads posts `operation_not_supported`.** WASI has no `ESHUTDOWN`, no interface names and, in the single profile, no thread for Boost's resolver; the port does not pretend those entry points exist. - Source: `doc/capabilities.adoc` (asio, uncommitted). + Source: `doc/capabilities.adoc` (asio). - **The library's test and example Jamfiles declare `wasip3` beside native and Emscripten, Cobalt and OpenSSL refuse WASIp2 by name, and `doc/capabilities.adoc` with `doc/feature-matrix.adoc` is kept current for every feature, target and variant, telling unavailable from unverified.** The owner approved an AsciiDoc feature matrix that links its evidence. - Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md` (superproject, - uncommitted); `AGENTS.md` (asio, uncommitted). + Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md` (superproject); `AGENTS.md` (asio). - **`/webcpp/asio//cobalt` builds on WASIp3 from a checked patch of private copies of Cobalt's headers and sources (`tools/boost/cobalt-wasip3`): its signal, serial-port and seqpacket sources are left out, `thread.cpp` comes @@ -6610,15 +6654,17 @@ The original proposal has not been amended and no CI ran. ports must not break the IP APIs, and an archive and its program must agree about headers, threads and exceptions. Source: `docs/superpowers/plans/2026-10-16-cobalt-wasip3.md`, - `tools/boost/Jamfile` (superproject, uncommitted). + `tools/boost/Jamfile` (superproject). - **On WASIp3 `run_main` sets the promise's `signal_set` to null and includes no POSIX signal service, keeping the executor, the initial post, the status and Cobalt's internal cancellation.** WASIp3 delivers no process signal; a host's graceful shutdown needs a protocol of the program's. - Source: `src/cobalt_main.cpp`, `AGENTS.md` (asio, uncommitted). + Source: `src/cobalt_main.cpp`, `AGENTS.md` (asio). - **On WASIp3 the Cobalt status driver expects host exit status 1 for a - nonzero `co_return`.** (reason not recorded) - Source: `test/cobalt_status_driver.mjs` (asio, uncommitted). + nonzero `co_return`.** The component command reports failure to the host; + the driver verifies that outcome rather than assuming a native integer exit + status is preserved by the component interface. + Source: `test/cobalt_status_driver.mjs` (asio). - **OpenSSL 3.5.9 (`45e844f`) is a pinned, unmodified submodule at `third_party/libs/openssl`, built as static `libssl.a` and `libcrypto.a` with their generated headers by upstream Configure and `make build_libs`, @@ -6627,44 +6673,47 @@ The original proposal has not been amended and no CI ran. own manifests, which B2 would otherwise duplicate, and the headers and archives of one configuration must stay paired. Source: `docs/superpowers/plans/2026-10-16-openssl-source-build.md`, - `tools/webcpp-openssl.jam` (superproject, uncommitted). + `tools/webcpp-openssl.jam` (superproject). - **The OpenSSL recipe covers native Clang and GCC on macOS and Linux and - WASIp3, single and cooperative; WASIp2, Emscripten and MSVC stop the build, - and a host OpenSSL is never a fallback.** Windows needs an nmake integration - of its own, and a silent system fallback could link a second copy. + WASIp3, single and cooperative, plus native MSVC using Configure/nmake; + WASIp2 and Emscripten stop the build, and a host OpenSSL is never a fallback.** + Windows recipes preserve B2 runtime settings. Windows runtime results must + be tied to their tested candidate, not inferred from recipe tests or older + CI. A silent system fallback could link a second copy. Source: `docs/superpowers/plans/2026-10-16-openssl-source-build.md` - (superproject, uncommitted). + (superproject). - **On WASIp3 OpenSSL uses the external Configure target `webcpp-wasip3` (no assembly, no DSO, no QUIC, `getrandom` seeding) and fails closed when host entropy fails.** wasi-libc's `getentropy` reaches `wasi:random`; the tests show entropy is requested and that its failure stops key generation, not its quality. - Source: `tools/openssl/wasip3.conf`, `tools/openssl/build.py` (superproject, - uncommitted); `doc/building.adoc` (asio, uncommitted). + Source: `tools/openssl/wasip3.conf`, `tools/openssl/build.py` (superproject); `doc/building.adoc` (asio). - **`/webcpp/asio//openssl` forwards `/webcpp/third_party//openssl` with `WEBCPP_ASIO_HAS_OPENSSL` natively and on WASIp3, Emscripten keeps the forced-include refusal, and asio's tests that need OpenSSL fail rather than being left out.** A missing checkout is named (`git submodule update --init third_party/libs/openssl`), never skipped. - Source: `build.jam`, `doc/building.adoc` (asio, uncommitted). + Source: `build.jam`, `doc/building.adoc` (asio). - **The OpenSSL build copies the unchanged sources to a temporary directory before Configure, and caches its configuration fingerprint per property set.** Configure canonicalizes source symlinks, which would bring a checkout path with spaces into the Makefiles, and an uncached fingerprint built two archives for one configuration, two OpenSSL copies in one program. Source: `docs/superpowers/plans/2026-10-16-openssl-source-build.md`, - `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject, - uncommitted). + `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject). - **A dated curl export of Mozilla's root certificates (2026-09-25, 121 CAs) is checked in under `third_party/ca_certificates`, with a manifest of its URL, SHA-256 and DER fingerprints and its MPL-2.0 licence, verified and embedded as a generated header by `/webcpp/third_party//ca_certificates`, - and changed only by `tools/ca_certificates/update.py`.** It is a published + and changed only by `tools/ca_certificates/update.py`.** Its generated private + header is `` and its namespace is + `webcpp::asio::detail::ca_certificates`, in build and installed consumers. + It is a published data artifact, not implementation code, so a snapshot rather than a submodule; builds need no network, and an update is a reviewed trust-policy change that lists removals beside additions. Source: `docs/superpowers/plans/2026-10-16-ca-certificates.md`, - `third_party/ca_certificates/README.md` (superproject, uncommitted). + `third_party/ca_certificates/README.md` (superproject). - **`/webcpp/asio//tls` and `make_tls_client_context()` return a `boost::system::result` that verifies peers, requires TLS 1.2 or newer and trusts the embedded roots, never the system's; the @@ -6673,13 +6722,16 @@ The original proposal has not been amended and no CI ran. `unsupported_target`.** Replacing roots must remove public trust, not add to it, and the browser owns trust there; hostname verification and SNI stay the program's, per connection. - Source: `include/webcpp/asio/tls_client_context.hpp` (asio, uncommitted); - `docs/superpowers/plans/2026-10-16-ca-certificates.md` (superproject, - uncommitted). + Source: `include/webcpp/asio/tls_client_context.hpp` (asio); + `docs/superpowers/plans/2026-10-16-ca-certificates.md` (superproject). - **The TLS client context and its trust store allocate through OpenSSL, not - through an Asio allocator.** (reason not recorded) + through an Asio allocator.** OpenSSL's allocation hook is process-global and + must be selected before its first allocation. Installing it from a context + factory would mutate other users' policy and cannot honor independent + per-operation allocators. The factory therefore states the allocation boundary; + a future explicit process-wide crypto policy is separate work. Source: `docs/superpowers/plans/2026-10-16-ca-certificates.md` - (superproject, uncommitted). + (superproject). - **`/webcpp//boost_cobalt_io_ssl` compiles Cobalt's `io/ssl.cpp` as a library of its own with a checked patch (`tools/boost/cobalt-ssl`), and `/webcpp/asio//cobalt_ssl` adds it and `/webcpp/asio//tls` to @@ -6688,23 +6740,23 @@ The original proposal has not been amended and no CI ran. handshake with `secure` false and then wrote plaintext, and its verification callback's constraint named `ssl::context` for `ssl::verify_context`; the patch fixes both and adds the borrowed `native_ssl_handle()` for SNI. - Source: `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject, - uncommitted). + Source: `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject). - **Cobalt's SSL stream allows plaintext only before the first TLS attempt: a failed or cancelled handshake and a completed shutdown block application I/O, and the wrapper keeps the handler's associations.** A failed handshake must never fall back to plaintext, and an unbound lambda in their place would lose cancellation. - Source: `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject, - uncommitted). + Source: `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject). - **Every Cobalt target, native and Emscripten included, uses the checked overlay `tools/boost/cobalt-common`, whose composition promise connects its cancellation source to the handler's slot.** Reproduced: a composed read's cancellation hung, because Boost 1.92's composition promise did not attach to the received handler's slot; the overlay pins the integration to Boost - 1.92 until the patch is rebased and verified. + 1.92 until the patch is rebased and verified. The overlay also supplies the + required main/thread promise exception hooks in no-exceptions builds; + thread coroutine runtime tests cover worker dispatch and join. Source: `docs/superpowers/plans/2026-10-16-cobalt-ssl-cancellation.md` - (superproject, uncommitted). + (superproject). - **TLS transfer cancellation is terminal: the connection is closed afterwards, with no promise of rollback or reuse, and the tests require a real `operation_aborted` from a Cobalt promise, one write per cancellable @@ -6713,14 +6765,29 @@ The original proposal has not been amended and no CI ran. review reproduced, and an abort manufactured from coroutine state would prove nothing. Source: `docs/superpowers/plans/2026-10-16-cobalt-ssl-cancellation.md` - (superproject, uncommitted). + (superproject). - **The superproject's README names Crossbind's OpenSSL recipe as an engineering reference for WASIp3 builds.** Its source-based recipes and WASI ports help to bring low-level libraries to the web; webcpp still validates the toolchain, the entropy and the features itself. - Source: `README.md` (superproject, uncommitted). - -Its conflicts with chapters 1 to 13 are in chapter 19. + Source: `README.md` (superproject). + +Windows uses the checked `tools/boost/asio-windows` allocator overlay for +IOCP worker and timer thread state; installed Boost remains untouched, and the +same headers reach Cobalt sources and consumers. + +The `tls-integration` own lane drives real TLS, embedded trust, Cobalt state and +cancellation fixtures on native and WASIp3 profiles. The native +`openssl-upstream` lane opts into `webcpp-openssl-tests=on`, which runs the full +upstream `alltests` suite against the exact archive configuration before linking +the consumer. The `openssl-upstream-msvc-14.3` and +`openssl-upstream-msvc-14.5` aliases select the matching Windows CI toolsets; +real execution on the final Windows candidate remains a validation gate. +OpenSSL's upstream harness is unavailable on WASIp3, and the integration +witnesses do not claim to replace it. Native combined-provider +coverage belongs to Trystero's `test/provider//provider-integration`, where its +external secp256k1 dependency is provisioned. Final-candidate CI and remaining +coverage limitations are tracked in chapter 19. ### beast (Boost.Beast portability facade) @@ -6730,6 +6797,10 @@ library is the `webcpporg/beast` submodule at `libs/beast`. The proposal records source compatibility, explicit environment counterparts and unavailable facilities separately; a successful compile never proves runtime parity. +- The existing `webcpp.beast.wasi` category and its enum values remain public + identities beside `webcpp.beast`. As with Asio's TLS category, preserving + error comparisons is a bounded compatibility departure from chapter 4; + it does not authorize renumbering or merging categories. - Portable HTTP messages, parsers and serializers reuse Boost.Beast 1.92. `http.hpp` remains independent of a socket reactor. Byte-stream algorithms are explicit `http/read.hpp` and `http/write.hpp` includes. @@ -6763,6 +6834,10 @@ facilities separately; a successful compile never proves runtime parity. stdin/stdout streams are meaningful counterparts for local-socket examples; they do not supply Unix-domain addressing. Host HTTP does not provide a WebSocket upgrade or a guest TCP listener. + Posted completions release their associated allocation before user code runs; + a per-operation PMR resource may be destroyed inside that callback. Supplied + HTTP reads respect the remaining DynamicBuffer maximum capacity and report + `http::error::buffer_overflow` when an incomplete parser exhausts it. - The immutable upstream application corpus contains all 53 executable definitions at its pinned commit. Inventory checks validate original hashes, Jamfiles, CMake definitions and entry points. All adaptations are generated @@ -6801,17 +6876,15 @@ What webcpp does not have yet, and the chapters that mention it: library of a kind, wrapped outside libraries, and fixed-width types (chapter 4); the lint then checks the last (no plain `int`, `long`, `short` or `unsigned` in a public header where no interface asks for it). -- **Asynchronous libraries on xactor with Boost.Asio and Boost.Cobalt.** An - example library shows how a library built on xactor's scheduler meets - Boost.Asio and Boost.Cobalt, so that asynchronous libraries are easy to - write and are all driven from the browser's event loop (chapter 4); its - design is still to be done. -- **webcpp::asio, webcpp::beast, webcpp::webrtc, webcpp::crypto.** Boost.Asio - and Boost.Beast natively, and their interfaces over the browser's event - loop, `WebSocket` and `fetch` on emscripten; WebRTC peer connections and - data channels on both; authenticated encryption and randomness in C++ on - every target. trystero then holds only its protocol. Their specifications - are in review. +- **Trystero on Asio and Beast.** Asio's executor integration and Beast's + native/WASI/browser adapters are implemented for 0.1.0 in preparation. The + owner reiterated on 2026-11-03 that they are foundations for Trystero's later + migration. Their coexistence is required; dependency provenance must not be + addressed by prohibiting a combined program. Actor-based libraries use + xactor's scheduler through an application-owned loop. +- **webcpp::webrtc and webcpp::crypto.** WebRTC peer connections and data + channels, and authenticated encryption/randomness, remain separate proposals. + Trystero can then retain its protocol over those shared facilities. - **The libraries web developers use most,** brought to C++: a JavaScript interpreter (QuickJS), libp2p, HTTP fetch. - **The site, increments 2 to 8.** Increment 1 is done: the site's @@ -6836,12 +6909,11 @@ What webcpp does not have yet, and the chapters that mention it: - **Documentation for web developers and for AI developers,** beside the documentation for C++ developers every library has today, and webcpp's integrations with the AIs. -- **External libraries built from `third_party/`.** trystero needs - libsecp256k1, libdatachannel and OpenSSL, which webcpp does not build: a - machine installs them by hand and the CI's actions build them, each found - where a variable names it, else in `.local/` (`AGENTS.md` chapters 1 and 4), - until webcpp builds them from `third_party/`, each pinned there by a commit - or a SHA-256. +- **External libraries built from `third_party/`.** Only trystero's + libsecp256k1 remains externally provisioned. OpenSSL and native libdatachannel, + including its required nested dependencies, now build from pinned sources + against one OpenSSL provider. Moving secp256k1 into `third_party/` remains + future work; this closure does not implement crypto or WebRTC. - **Every library on ``.** Each library's `config.hpp` includes it first: trystero (held with config's publication), and wasi with its redesign, which brings Boost into it. @@ -6887,6 +6959,16 @@ on the owner's gates G1 and G2 (the repository and its submodule), O2 (the CI's nightly level), O3 (NIST's archives), O5 (the departures C14, C16 and C17, and `brew install botan`) and G4 (every push). +**Provider amendment, 2026-11-03.** The owner's explicit source-build request +supersedes this accepted design's old OpenSSL provisioning and default-link +choices (D15 and reference sections 3.3/4.4). Future crypto uses the shared +pinned `/webcpp/third_party//openssl` provider, whose current support is native +and WASIp3, static, with chapter 5 rule 7's exact-archive boundary. Statements +below about finding a machine OpenSSL, refusing all WebAssembly or defaulting +to shared linkage record the older design, not current provider requirements. +Botan's provisioning, future algorithms, APIs and explicit allocator policy +are unchanged. No crypto implementation or new backend coverage is claimed. + **Scope.** - **Hashing and HMAC stay with Boost.Hash2, and HKDF, when a library needs it, @@ -8539,153 +8621,57 @@ Source: `libraries/trystero/openspec/changes/bounded-json-parse/design.md` ## 19. Conflicts and open questions -What this chapter lists breaks a rule of chapters 1 to 13, or makes a design -document disagree with the tree it describes. Each was found on 2026-10-26, -when this file was written, by reading the superproject at `ddb6cb2`, each -library at the commit 0.1.0 pins, asio at its local branch and the open -proposals; each names where it is. None is resolved here. A conflict of a -proposal is the owner's to decide, in that proposal; a library that does not -keep a rule is brought to it, or the rule records an exemption with its -reason; a text that is wrong is corrected by a change of its own. The change -that resolves an entry removes it from this chapter. - -### asio and the work beyond its proposal - -asio's proposal (chapter 15) and the local work of 2026-10-15 and 2026-10-16 -beyond it break these rules, each approved by the owner or not as it says. -Paths are asio's or the superproject branch's, as chapter 15's entry gives -them. - -The remaining entries preserve the 2026-10-26 audit and its proposal references. -The source snapshots it called "uncommitted" were committed as Asio `6a7f3fe` -and superproject `c07c212`, then integrated locally on 2026-11-02. Statements -about what was absent from main describe that audit date; they do not imply -that the current implementation is unpublished. This integration resolves the -entries explicitly removed from this list, but does not complete proposal -tasks 22/23 or approve the remaining conformance departures. - -- **Asynchronous code on xactor.** Chapter 4: "A library that ports anything - asynchronous runs it as actors on xactor"; chapter 4 and the roadmap - (chapter 16) leave the meeting with Boost.Asio and Cobalt to be designed. - asio makes Boost.Asio's own `io_context`, suspended into the page, the event - loop, and xactor a user (its `asio_driver`), not a dependency - (`genesis/proposal.md`, Impact). Approved: the owner's decision 4 of - 2026-10-10 limits xactor's scheduler to "where a library has actors" - (`genesis/reference/spec.md`, section 2), accepted with the spec on - 2026-10-11; the amendment of chapter 4's item is planned in - `genesis/reference/plan.md`, task 22, not made. Chapter 16 still calls - asio's specification "in review". -- **Header-only.** Chapter 4: "C++20, header-only." asio compiles - `src/browser_src.cpp`, an object every Emscripten program links, and - `src/cobalt_main.cpp`, the static library `cobalt-main` of every Cobalt - program. Approved: the spec's requirement "Header-only library in its - namespace" names both units (`genesis/specs/asio/spec.md`), accepted - 2026-10-11. -- **`config.hpp` on ``.** Chapter 3: "which includes - `` first"; chapters 10, 6 and 16 add config's - b2 target, `WEBCPP_NO_EXCEPTIONS` and the test `config_all_off`. asio's - `config.hpp` includes `` alone, ignores - `WEBCPP_NO_EXCEPTIONS`, builds its test twice, and `build.jam` names no - `/webcpp/config//config`. Not approved: the spec's requirement - "Configuration header" omits it, and the rule's commit `a369f7a` is of - 2026-10-11, the day the plan was approved. -- **`config.hpp` first.** Chapter 3: "which every public header includes - first". `browser/async_await.hpp`, `browser/async_wait_event.hpp` and - `browser/error.hpp` (asio) and `tls_client_context.hpp` (asio, uncommitted) - include Boost and standard headers before it. Not approved; asio's own spec - requires it first. -- **The changelog.** Chapter 10: "`doc/changelog.adoc` (its changelog, the - page's last appendix". asio has no `doc/changelog.adoc`, and its spec's list - of repository files omits it. Not approved. -- **The error category.** Chapter 4: "an error category of the - library's own (`webcpp.`)". `tls_client_context.hpp` (asio, - uncommitted) defines a second category, `webcpp.asio.tls`, values 1 to 3, - beside `webcpp.asio`. Not approved: the CA plan names no category. -- **Namespaces and headers.** Chapter 3: namespace "`webcpp::`", - headers "`/...>`". The generated - `` declares `webcpp::detail::ca_certificates`, - outside any library's namespace (`tools/ca_certificates/generate.py`, - superproject, uncommitted). Not approved. -- **Allocation, the runtime's own.** Chapter 4: "routes every - allocation through an allocator its user gives", and a test "proves that - none goes elsewhere". asio names three allocations it cannot route: - Emscripten's `select` poll array, Asyncify's unwind data, - `basic_resolver_results`' entries (`doc/allocation.adoc`). Approved with the - spec (requirement "The counters see an unbound handler and the runtime's own - allocations are named"), 2026-10-11. -- **Allocation, the resolver's names.** The same rule. The Emscripten - resolver's asynchronous form copies the host and service names with the - standard allocator, not the handler's (`doc/allocation.adoc`, commit - `557d452`). Not approved: the spec names only the result entries. -- **Allocation, OpenSSL.** The same rule. The TLS client context and its - trust store allocate through OpenSSL (`tls_client_context.hpp`, asio, - uncommitted), and webcpp::crypto's accepted D16 offers a memory resource for - OpenSSL that asio does not use. Approved locally: "OpenSSL owns its - allocations" is in the CA plan's contract - (`docs/superpowers/plans/2026-10-16-ca-certificates.md`); not in main. -- **Allocation, unproven on WASIp3.** Chapter 4: a test "proves that - none goes elsewhere". `allocation_test` runs natively and on Emscripten - only, and `doc/capabilities.adoc` (asio, uncommitted) marks WASIp3's - counters "unverified". Not approved. -- **Exceptions, WASIp3 cooperative.** Chapter 6: "Every target builds with - exceptions on." `threading=multi` on WASIp3 refuses `exception-handling=on` - (`tools/webcpp-wasi.jam`), for asio, Cobalt, OpenSSL and TLS alike. Approved - locally: the WASIp3 spec makes exceptions "subject to the runtimes actually - supplied by the SDK"; not in main. -- **A WASI target.** `AGENTS.md` chapter 4 (xactor's Jamfile): "Boost.Asio - 1.92 does not compile for wasm32-wasip2 or wasm32-wasip3"; `AGENTS.md` - chapter 1: `xactor_asio` native only. asio's own D16 and spec ("MUST NOT - declare wasm32-wasip2 or wasm32-wasip3") agree, yet `test/Jamfile`, - `example/Jamfile` and `example/tls/Jamfile` (asio, uncommitted) declare - `wasip3` over patched Asio headers. Approved locally: "The owner approved - implementation, local tests, and an AsciiDoc feature matrix" - (`docs/superpowers/specs/2026-10-15-asio-wasip3.md`); no proposal amends - D16. -- **Tests run on every declared target.** Chapter 8: "Every test runs on every - target its Jamfile declares." `cobalt_thread` and `wasi_core_threads` (asio, - uncommitted) are explicit, in no lane, so only a request by name runs them. - Not approved. -- **Boost from Boost's own sources.** `AGENTS.md` chapter 1: "built from - Boost's own sources, for every target". Asio's headers on WASIp3 and Cobalt - on every target compile from patched private copies - (`tools/boost/asio-wasip3`, `cobalt-common`, `cobalt-wasip3`, `cobalt-ssl`, - superproject, uncommitted). Approved locally by the WASIp3 spec, the Cobalt - SSL plan and the cancellation plan's ruling; not in main. -- **OpenSSL found, not built.** Chapter 5: "found by - `webcpp.external`, linked shared or static by a propagated feature, refused - on WebAssembly". OpenSSL 3.5.9 is built from source, static only, natively - and for WASIp3 (`tools/webcpp-openssl.jam`; `build.jam`, asio, uncommitted), - which also supersedes departure 4 and contradicts webcpp::crypto's accepted - D15 ("OpenSSL and Botan are found, not built", native only). Approved - locally: the OpenSSL plan's "Approved scope and design" and the rewritten - rule 7 of the uncommitted `AGENTS.md`; departure 4 and crypto's D15 are not - amended. -- **A C library built file by file, on every target.** Chapter 5: - "builds it from its own sources, file by file" and "on every target and with - every file". Upstream Configure and Make compile OpenSSL; WASIp2, Emscripten - and MSVC are refused. Approved locally: the uncommitted rule 7 calls it "a - deliberate exception to spelling out its source list in B2". -- **The link-time canary.** Chapter 5: "every function that calls the - C library references a canary". OpenSSL has none; B2 ordering and exact - archive paths stand in (uncommitted `AGENTS.md`, rule 7). Approved only by - that uncommitted text. -- **The C library's own tests.** Chapter 5: "the C library's own tests - pass on webcpp's build". OpenSSL is configured `no-tests`, and its suite is - not run (`docs/superpowers/plans/2026-10-16-openssl-source-build.md`, - "Explicit limits"). Not approved. -- **One copy per program.** Chapter 5: "webcpp's build of a C library - is never linked together with another copy of it." asio links the - source-built OpenSSL while trystero's native backend links the system's - through `webcpp.external` (`libs/trystero/build.jam`, line 38, main), so a - program on both carries two copies, which asio's `doc/building.adoc` - (uncommitted) forbids without a remedy. Not approved; unresolved. - -Open for the owner: whether asynchronous code is built on Boost.Asio's model -rather than on xactor (chapter 4's item, which asio's task 22 is to amend); -whether a proposal is written for the WASIp3 port, OpenSSL built from source -and the CA bundle, which no proposal holds, and whether it amends asio's D15, -D16 and departure 4, crypto's D15, and chapter 5's rules 1, 2, 6, 7, 10 and -11; and how a program that uses asio and trystero together holds one OpenSSL. +This chapter records unresolved rule conflicts, design discrepancies and +validation gates. The original inventory was read on 2026-10-26 at superproject +`ddb6cb2` and the then-current library/proposal snapshots. The Asio/Beast portion +was reconciled against the owner's 2026-11-03 decisions and current code; +unrelated entries below retain their dated scope. A recommendation in an audit +is not an approval. Fixed discrepancies leave the active inventory; a bounded +compatibility departure belongs with its rationale in chapter 15. + +### Asio/Beast closure: remaining gates and limits + +Chapter 15 now records the implemented configuration, allocator and private-header +corrections, native/Emscripten/WASIp3 target contract, default turn limit 100, +Diataxis guide, source-built OpenSSL, checked Boost overlays and recurring thread +and TLS lanes. Chapter 4's executor contract and compiled-unit exceptions and +chapter 6's SDK-limited exception profiles reflect the existing approvals. +Public `webcpp.asio.tls` and `webcpp.beast.wasi` identities remain compatible. +The proposed resolver eager-evaluation workaround, category renumbering, +Asio/Beast/Trystero combination ban and new OpenSSL canary requirement were not +adopted. Chapter 5 rule 7's existing exact-archive exception stays in force. + +- **Final candidate and main CI.** Root `55a72c0` / baseline CI 41597577370 + predates closure edits. Local passes and lane registration do not prove the + final candidate or Asio's first library-main CI. The whole-branch review, + proposal gates and integration sequence remain explicit in + `docs/superpowers/plans/2026-11-03-asio-beast-closure.md`. Keep 0.1.0 in + preparation until a separately authorized release. +- **Upstream dependency test coverage.** Native `openssl-upstream` runs + upstream's full suite when `webcpp-openssl-tests=on`. WASIp3 cannot execute + that upstream harness; real TLS/entropy integration is narrower evidence. + This is an explicit remaining limit against chapter 5 rule 11, not a claim + that the rule has been satisfied on WASI or an approved general exemption. + Libdatachannel's source recipe currently disables its upstream tests; + OpenSSL and combined-consumer witnesses do not prove that C++ library's own + suite or every nested C dependency's suite. Keep that distinction in closure + and CI reports without broadening this change to unrelated library work. +- **Upstream overlay follow-up.** Checked input/output hashes, version refusal + and runtime witnesses bound the Asio/Cobalt corrections. They do not prove + that every patch has an upstream issue or has been accepted there. Preserve + existing issue references and verify provenance when rebasing; do not invent + an upstream acceptance claim. Cobalt's pending-task no-exceptions limitation + remains the separately documented warning for issue 287. +- **Historical subjects.** Earlier commits use conventional subjects rather + than chapter 2's part convention. Retain history; the current work follows + the convention for new commits. This observation does not justify rewriting + already published commits or changing the general rule. + +The global WASIp3 launcher grants network/name lookup and defaults to 600 seconds +for tests; it establishes no production capability policy. Native Trystero +requires multiple threads and uses the same source-built OpenSSL through pinned +libdatachannel. Its later migration onto Asio/Beast remains roadmap work, and +coexistence is required now. ### The libraries against the rules @@ -8713,19 +8699,18 @@ it says. - **What a library builds on (chapter 4).** document hashes with an FNV-1a of its own rather than Boost.Hash2's; lexical has a UTF-8 decoder of its own in `detail`, the third in webcpp. -- **Asynchronous code on xactor (chapter 4).** trystero runs on Asio's - executors, which its genesis ruling 6 defers; document's - `` is on Asio, not xactor; xactor itself declares - no Emscripten target (`test/Jamfile:11`), with no reason recorded, although - chapter 4 has asynchronous code run in a browser from the page's event - loop. asio's entry above holds the decision these wait on. +- **xactor's browser target.** xactor still declares no Emscripten target + (`test/Jamfile:11`), with no reason recorded. Executor-based Trystero and + document adapters are no longer conflicts merely because they use Asio: + chapter 4 now distinguishes executors from libraries that contain actors. - **Errors as values (chapter 4).** lexical has no error category of its own. - **Text (chapter 4).** lexical passes text as `boost::core::string_view`, where the rule asks for `std::string_view`. -- **Bringing a C library (chapter 5).** trystero's libsecp256k1 and - libdatachannel are not submodules under `third_party/libs/`, and have no - `HAS` define and no canary (`build.jam:31-38`); the roadmap's external - libraries built from `third_party/` covers it. +- **Bringing a C library (chapter 5).** trystero's libsecp256k1 remains + externally provisioned, without the source-target `HAS`/canary contract; + the roadmap retains that migration. Libdatachannel is now a pinned C++ + source target with nested dependencies; its remaining upstream-test limit + is recorded above, not confused with the external secp256k1 case. - **Exceptions (chapter 6).** lexical's throwing IRI functions (`uri.hpp:281-325`) and document's throwing conveniences are not behind their library's `NO_EXCEPTIONS` macro; xstate's `machine.hpp:1213,1233` @@ -8861,20 +8846,12 @@ says what the tree does. shorthand, `C/`, for Trystero's source files. The draft bounded parse (chapter 18) claims guarantee 9, which 9 to 11 now hold, rebases on `160f431`, and says "about sixty times" where its own figures give 87. -- **asio.** The proposal's design, specification and impact give the default - turn limit as 1000; the tree's is 100 (`24c1e2c`). They cite library and - superproject commits (`7cfd449`, `df52767`) that the re-import replaced - (tip `f5fd7a8`), and `STATUS.md` a superproject commit (`063343d`) behind - the branch (`d159022`). Its open questions on task 9's re-review, the - Chrome measurement and Cobalt's stack are answered. D16 and the - specification have no WASI target; the uncommitted Jamfiles declare - `wasip3`. D15 and departure 4 link the system's shared OpenSSL; the - uncommitted `build.jam` links one built from source, statically. Three - headers do not include `config.hpp` first; `doc/allocation.adoc` names - allocations beyond the specification's three; four examples are - Emscripten-only, against the specification, and the TLS examples have no - page variants; the lanes `cobalt`, `cobalt_asyncify` and `cobalt_wasip3` - are added; on WASIp3 Cobalt's `co_main` drops SIGINT and SIGTERM. +- **asio.** The 2026-11-03 amendment reconciles default turn limit 100, + supported targets, source-built TLS, private configuration/allocation fixes + and guide order. Proposal source snapshots must name the final committed + library/root trees, and archive/status gates must wait for their actual + integration and CI evidence. Historical snapshot commits remain provenance, + never substitutes for validation of the current candidate. - **The site.** The site's specification names `.htmlvalidate*.json`, which the site's `d113e38` renamed, and that commit broke the wrapping of `site/Jamfile`'s comments. The proposal of increments 4 and 5 (chapter 17) diff --git a/Jamroot b/Jamroot index e156aa76..61d333b8 100644 --- a/Jamroot +++ b/Jamroot @@ -25,6 +25,7 @@ import type ; import tools/webcpp ; import tools/webcpp-wasi ; import tools/webcpp-openssl ; +import tools/webcpp-libdatachannel ; import tools/webcpp-ca-certificates ; # A shell with CPATH (Homebrew sets it) puts its headers before the @@ -569,7 +570,7 @@ for local build in [ glob libs/*/build.jam ] # Keep the generated trust header usable outside this source checkout, along # with the exact certificate source and notices of the embedded snapshot. install install-ca-certificates : third_party//ca_certificates-header - : $(.includedir) ; + : $(.includedir)/webcpp/asio/detail ; install install-ca-certificates-notices : third_party/ca_certificates/LICENSE-MPL-2.0.txt third_party/ca_certificates/README.md third_party/ca_certificates/cacert.pem diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 7fc2c998..d4fa6c05 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -7,9 +7,14 @@ [#webcpp-0-1-0] = webcpp 0.1.0 +// Frozen candidate only; publishing the release and tag is a separate owner action. + [#webcpp-0-1-0-new-libraries] == New Libraries +* link:{library-pages}asio/{library-page}[asio]: Boost.Asio and Cobalt with +browser event-loop suspension, WASIp3 networking and optional source-built TLS, +from R. * link:{library-pages}beast/{library-page}[beast]: HTTP messages and WebSocket applications for native, WASI and browser targets, with socket transports, browser WebSocket and fetch, WASI host HTTP and supplied byte streams, from R. @@ -52,6 +57,7 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Fixed embedded CA headers using an unowned namespace and include path. * Added source-built Boost.Context for native stackful coroutine applications. * Added negative link tests and explicit reference-source build discovery. * Added hash-verified Beast application inputs and browser CI dependencies. diff --git a/docs/superpowers/plans/2026-11-03-asio-beast-closure.md b/docs/superpowers/plans/2026-11-03-asio-beast-closure.md new file mode 100644 index 00000000..ceb1ce29 --- /dev/null +++ b/docs/superpowers/plans/2026-11-03-asio-beast-closure.md @@ -0,0 +1,102 @@ +# Asio and Beast closure + +**Goal:** Close the approved Asio and Beast integration together, including the owner's +2026-11-03 scope decisions and the independently verified findings in the Claude audit. + +**Architecture:** Keep native and WASIp3 socket/TLS transport in Asio. Beast's socket +profiles follow Asio's supported targets; portable messages, host HTTP and supplied +streams remain independent. Preserve the browser's native WebSocket and fetch adapters. + +**Tech Stack:** C++20, Boost 1.92, B2, Emscripten, WASI SDK 34, Wasmtime 50.0.1, +OpenSSL, Python, AsciiDoc, MrDocs and OpenSpec. + +**Spec:** `proposals/libraries/{asio,beast}/openspec/changes/genesis`, reconciled with +the owner's later approvals. The sibling proposals checkout is an independent repository. + +## Global constraints + +- Keep the primary checkout and unrelated work intact. Never force-push. +- Treat the Claude audit as evidence to verify, not as authority for new rules. +- Preserve the 53 upstream Beast applications and explicit variant classifications. +- Asio and Beast are intended foundations for a later Trystero migration. The owner + clarified this on 2026-11-03; never introduce a ban on combining those libraries. +- Reproduce behavioral defects through a real consumer before fixing them. +- Run final B2 checks with `-a` and unset inherited compiler include paths. +- Change generated artifacts only through their generators. +- Record prior approvals without asking for them again or inventing new approvals. +- CI, push and merge are authorized; publishing a release or tag is not. +- Merge only a tree identical to the successful final CI candidate. Library CI uses + the superproject's `library.yml@main`, so integrate the root before library mains. + +## Work and interfaces + +### 1. Verify and reconcile Beast scope + +- [x] Compare the actual Claude artifact, code, requirements and test evidence. +- [ ] Remove the P2 socket prerequisite tasks and amend the normative requirement. +- [x] Generate the application matrix: 567 passed, 122 blocked, 530 unavailable. +- [x] Preserve P2 host HTTP/messages/streams and explain every remaining blocked cell. +- [ ] Validate generators and OpenSpec; submit the proposal as proposed, not accepted. + +Produces: Beast source and proposal changes. Its source reference snapshot is refreshed +only after the library changes are committed, preserving exact blobs and modes. + +### 2. Fix Asio configuration and allocator conformance + +- [x] Reproduce global configuration propagation and repair the config dependency. +- [x] Put config first in the affected public headers. +- [x] Reproduce resolver input allocations and route owned inputs through the associated + allocator without changing deferred initiation or input lifetime. +- [x] Measure allocations on the supported WASIp3 profiles with explicit categories. +- [x] Connect thread tests and applicable exception/header tests to recurring lanes. + +Produces: Asio headers, tests and lane declarations. Root CI consumes those declarations; +coordinate any cooperative SDK provisioning changes before changing CI. + +### 3. Reconcile TLS and dependency contracts + +- [ ] Generate embedded CA data under the owning library's private namespace and path; + prove build-tree and installed consumers work. +- [x] Preserve public error identities and document any bounded compatibility departure. +- [x] Inspect the claimed Cobalt SSL state defect against the existing overlay and tests. +- [x] Reproduce mixed OpenSSL provenance with Trystero and choose a single provider for + combined programs, including libdatachannel's transitive dependency. +- [x] Add upstream native OpenSSL test coverage and recurring TLS integration coverage; + name harness limitations explicitly for WASI. + +Produces: root dependency tooling, TLS contracts and test lanes. Do not hide a dependency +conflict by banning useful library combinations or silently selecting system libraries. + +### 4. Reconcile rules, release preparation and Asio records + +- [x] Disposition every current chapter 19 item and each additional audit claim using + code changes, existing approved decisions or an explicit documented departure. +- [ ] Amend Asio targets, default turn limit 100, source-built OpenSSL and Diataxis order. +- [x] Add Asio's maintained AsciiDoc changelog and New Libraries entry. +- [ ] Reconcile preparation metadata without claiming a published release. +- [ ] Update gates, dates and status with actual repository, integration and CI evidence. +- [ ] Run release checks and every strict OpenSpec root plus proposal tooling tests. + +### 5. Review and verify the final candidate + +- [x] Finish collecting baseline CI 41597577370; it is not evidence for later edits. +- [x] Perform one fresh whole-branch review covering Asio, Beast and root integration. +- [x] Fix important findings with RED/GREEN tests and run the relevant complete suites. +- [ ] Commit explicit paths, refresh reference snapshots and publish the final candidate. +- [ ] Run and inspect full CI, including report XML, docs, lint and site, on that exact tree. + +### 6. Integrate and close + +- [ ] Recheck remote heads and merge root with the tested tree preserved. +- [ ] Create Beast main at its tested commit and make it the default branch. +- [ ] Merge library updates and verify their main CI, especially Asio's first run. +- [ ] Finish proposal records/archive only when their stated gates are actually met. +- [ ] Report merged commits, CI links and any explicit remaining limitations. + +## Review focus + +Check deferred token timing and allocator lifetime, cross-library error-code identity, +installed generated headers, one OpenSSL provider across shared/static boundaries, +TLS state transitions and shutdown cancellation, cooperative-thread SDK limitations, +WASI host versus guest transport dependencies, browser direct adapters, exact matrix +coverage and whether metadata claims more than the executed tests prove. diff --git a/libs/asio b/libs/asio index 9ed4ba85..69482921 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 9ed4ba8597467a1d4348cf974a0a99ee161b70e4 +Subproject commit 6948292165c436a51b0f254de1c7486e92759979 diff --git a/libs/beast b/libs/beast index c1738586..1cffa163 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit c1738586d8b7b0f4f24ad528840433bf100cdf57 +Subproject commit 1cffa1634811b7bf2f754a7b188bf66015ce22a0 diff --git a/libs/trystero b/libs/trystero index 3d8939bc..5ace772e 160000 --- a/libs/trystero +++ b/libs/trystero @@ -1 +1 @@ -Subproject commit 3d8939bce007dae58403a42d727dc5994666f7f4 +Subproject commit 5ace772e352bf245586633dfed141f4c2ca7bd63 diff --git a/libs/wasi b/libs/wasi index fb551ae6..80f573a1 160000 --- a/libs/wasi +++ b/libs/wasi @@ -1 +1 @@ -Subproject commit fb551ae6dc31e0ee9f3b9b90243c08fb673b4ef4 +Subproject commit 80f573a1a35062866efd2367e41e7cff6dad7a63 diff --git a/third_party/Jamfile b/third_party/Jamfile index 0b6eec11..c1895c4a 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -88,10 +88,21 @@ webcpp-openssl.declare $(WEBCPP_ROOT) : $(.openssl-headers:B).h $(.openssl-templates:B) : ../tools/openssl/build.py ../tools/openssl/source.py ../tools/openssl/wasip3.conf ../tools/openssl/msvc.conf - ../tools/openssl/pin.json [ glob-tree-ex libs/openssl : *.c *.h *.in *.pl *.pm *.S *.s + ../tools/openssl/pin.json [ glob-tree-ex libs/openssl : *.c *.h *.in *.pl *.pm *.t *.S *.s *.conf *.num build.info Configure VERSION.dat *.tmpl : .git ] ; explicit openssl ; +# libdatachannel and its pinned nested dependencies use upstream CMake, with +# the exact OpenSSL archives above. Each archive reaches the program once. +import webcpp-libdatachannel ; +.libdatachannel-headers = [ glob libs/libdatachannel/include/rtc/*.hpp libs/libdatachannel/include/rtc/*.h ] ; +webcpp-libdatachannel.declare $(WEBCPP_ROOT) + : $(.libdatachannel-headers:BS) + : ../tools/libdatachannel/build.py ../tools/libdatachannel/source.py + ../tools/libdatachannel/pin.json ../tools/libdatachannel/msvc.cmake + [ glob-tree-ex libs/libdatachannel : *.c *.cpp *.h *.hpp *.in *.cmake CMakeLists.txt : .git ] ; +explicit libdatachannel ; + # A dated, digest-pinned Mozilla/curl data export, not third-party source code. import webcpp-ca-certificates ; webcpp-ca-certificates.declare ca_certificates/cacert.pem ca_certificates/manifest.json diff --git a/third_party/libs/libdatachannel b/third_party/libs/libdatachannel new file mode 160000 index 00000000..6b1e2e62 --- /dev/null +++ b/third_party/libs/libdatachannel @@ -0,0 +1 @@ +Subproject commit 6b1e2e620f1e37f0eafeee702eaea0043cb305fd diff --git a/tools/boost/cobalt-common/boost-1.92.patch b/tools/boost/cobalt-common/boost-1.92.patch index 3813acd7..03f21dfb 100644 --- a/tools/boost/cobalt-common/boost-1.92.patch +++ b/tools/boost/cobalt-common/boost-1.92.patch @@ -46,3 +46,22 @@ #endif void return_value(int res = 0) { +--- a/boost/cobalt/detail/thread.hpp ++++ b/boost/cobalt/detail/thread.hpp +@@ -17,6 +17,7 @@ + + #include + ++#include + #include + + namespace boost::cobalt +@@ -84,6 +85,8 @@ + + #if !defined(BOOST_NO_EXCEPTIONS) + void unhandled_exception() { throw; } ++#else ++ void unhandled_exception() noexcept { std::terminate(); } + #endif + void return_void() { } + diff --git a/tools/boost/cobalt-common/manifest.json b/tools/boost/cobalt-common/manifest.json index 6035f0a8..32d42332 100644 --- a/tools/boost/cobalt-common/manifest.json +++ b/tools/boost/cobalt-common/manifest.json @@ -8,6 +8,10 @@ "boost/cobalt/detail/main.hpp": { "before": "fbdcb0ca58d8a368b8e4ec680dc99bcdd6ce2a2c5375770e278dec1dec91afcb", "after": "2a55b2e808068c0aaef80ab257f462ab9d61f7d3d59ef0ede23ed6b56046bdf5" + }, + "boost/cobalt/detail/thread.hpp": { + "before": "e8dc12b4145c9903ac7f87dd50d87f4b3d742819ee653cdd84e84d92c3c8c37d", + "after": "670b2c403b2e75d70ade9dd95bfe34834ce49ea2c1f875559071fd6fd4a2812b" } } } diff --git a/tools/ca_certificates/generate.py b/tools/ca_certificates/generate.py index cc127cb7..aaf7de7c 100644 --- a/tools/ca_certificates/generate.py +++ b/tools/ca_certificates/generate.py @@ -21,10 +21,10 @@ def main() -> None: output.write_text( '// Generated by tools/ca_certificates/generate.py. Do not edit.\n' '// Certificate data: Mozilla/curl, MPL-2.0; see third_party/ca_certificates.\n' - '#ifndef WEBCPP_DETAIL_CA_CERTIFICATES_HPP\n' - '#define WEBCPP_DETAIL_CA_CERTIFICATES_HPP\n' + '#ifndef WEBCPP_ASIO_DETAIL_CA_CERTIFICATES_HPP\n' + '#define WEBCPP_ASIO_DETAIL_CA_CERTIFICATES_HPP\n' '#include \n' - 'namespace webcpp::detail::ca_certificates {\n' + 'namespace webcpp::asio::detail::ca_certificates {\n' 'inline constexpr char pem[] =\n' + lines + ';\n' f'inline constexpr char date[] = {json.dumps(pin["date"])};\n' f'inline constexpr char sha256[] = {json.dumps(pin["sha256"])};\n' diff --git a/tools/ci/actions/libdatachannel/action.yml b/tools/ci/actions/libdatachannel/action.yml deleted file mode 100644 index 8932f947..00000000 --- a/tools/ci/actions/libdatachannel/action.yml +++ /dev/null @@ -1,65 +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) - -name: libdatachannel -description: >- - Builds libdatachannel 0.24.6, shared, without its WebSocket, examples and tests and with its - media transport, from its tag, checked against the tag's commit before its submodules are - fetched, with CMake, the lane's compilers and the OpenSSL that OPENSSL_ROOT names (the openssl - action runs first), in .local/libdatachannel; cached per version, runner, compilers and OpenSSL; and - gives the later steps LIBDATACHANNEL_ROOT, and on Windows PATH its DLL. On Linux, macOS and - Windows. trystero's native backend needs it, until webcpp builds it from third_party/. - -inputs: - cc: - description: >- - The C compiler to build with, as the lane names it (gcc-14, clang-18), or empty for CMake's - own choice: Visual Studio's on Windows. - required: false - default: '' - cxx: - description: >- - The C++ compiler to build with, as the lane names it (g++-14, clang++-18), or empty for - CMake's own choice. - required: false - default: '' - -runs: - using: composite - steps: - - name: Cache key - id: key - shell: bash - env: - CC: ${{ inputs.cc }} - CXX: ${{ inputs.cxx }} - run: bash tools/ci/actions/libdatachannel/install.sh key - - - name: Restore libdatachannel - id: restore - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .local/libdatachannel - key: ${{ steps.key.outputs.key }} - - - name: Build libdatachannel 0.24.6 - if: steps.restore.outputs.cache-hit != 'true' - shell: bash - env: - CC: ${{ inputs.cc }} - CXX: ${{ inputs.cxx }} - run: bash tools/ci/actions/libdatachannel/install.sh install - - - name: Save libdatachannel - if: steps.restore.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .local/libdatachannel - key: ${{ steps.key.outputs.key }} - - - name: Configure libdatachannel - shell: bash - run: bash tools/ci/actions/libdatachannel/install.sh configure diff --git a/tools/ci/actions/libdatachannel/install.sh b/tools/ci/actions/libdatachannel/install.sh deleted file mode 100644 index 4b7b6614..00000000 --- a/tools/ci/actions/libdatachannel/install.sh +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env bash -# 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 steps of tools/ci/actions/libdatachannel: libdatachannel 0.24.6, shared, in -# .local/libdatachannel, where trystero's build.jam looks for it when LIBDATACHANNEL_ROOT names no -# other directory, until webcpp builds it from third_party/. On Linux and macOS, on X64 and ARM64, -# and on Windows on X64, built with the lane's compilers against the OpenSSL that OPENSSL_ROOT -# names, which the openssl action gives first. -# -# Usage, from the superproject's root, with the variables a runner sets (RUNNER_OS, RUNNER_ARCH, -# ImageOS, ImageVersion, GITHUB_OUTPUT, GITHUB_ENV, GITHUB_PATH), OPENSSL_ROOT, and the action's -# inputs, CC and CXX, the C and C++ compilers of the lane (empty for CMake's own choice, Visual -# Studio's on Windows): -# -# install.sh key writes the cache key to GITHUB_OUTPUT: the version, the runner, the -# compilers, OpenSSL's version and this action's files; -# install.sh install clones the tag v0.24.6, checks that HEAD is the tag's commit, then -# fetches its submodules, and builds and installs it with CMake; -# install.sh configure checks the installed header and library, and gives the job's later -# steps LIBDATACHANNEL_ROOT, and, on Windows, PATH its DLL's directory. -# -# A program links libdatachannel's C++ API, whose types it shares, so it is built with the -# program's compiler and standard library: a program built with GCC and libstdc++ does not link -# against one built with libc++, and the cache is keyed on the compilers. Its own WebSocket, its -# examples and its tests are left out (NO_WEBSOCKET, NO_EXAMPLES, NO_TESTS), and its media -# transport is kept (NO_MEDIA off). Windows builds the Debug configuration: b2's debug variant, -# the lanes', builds a program with /MDd, whose standard types differ from /MD's, and a DLL that -# shares them must match. -set -euo pipefail - -version=0.24.6 -repository=https://github.com/paullouisageneau/libdatachannel.git -# The commit of the tag v0.24.6 (gh api repos/paullouisageneau/libdatachannel/git/ref/tags/v0.24.6, -# then the tag object): the pin. The submodules are the commits it records. -commit=6b1e2e620f1e37f0eafeee702eaea0043cb305fd - -here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# The functions every action shares: digest, mixed, configuration, compiler_identity. -# shellcheck source=SCRIPTDIR/../../helpers.sh -. "${here}/../../helpers.sh" - -# Stops, before anything is fetched, on a runner this action builds nothing for, or without the -# OpenSSL it builds against. -check_runner() { - case "${RUNNER_OS-}-${RUNNER_ARCH-}" in - Linux-X64 | Linux-ARM64 | macOS-X64 | macOS-ARM64 | Windows-X64) ;; - *) - printf 'install.sh: libdatachannel %s is built for Linux and macOS on X64 and ' \ - "${version}" >&2 - printf 'ARM64, and Windows on X64, not for %s on %s\n' "${RUNNER_OS-}" \ - "${RUNNER_ARCH-}" >&2 - exit 1 - ;; - esac - if [ -z "${OPENSSL_ROOT-}" ] || [ ! -f "${OPENSSL_ROOT}/include/openssl/opensslv.h" ]; then - printf 'install.sh: OPENSSL_ROOT names no OpenSSL (%s): the openssl action runs first\n' \ - "${OPENSSL_ROOT-}" >&2 - exit 1 - fi -} - -key() { - check_runner - local files compiler openssl - files="$(digest "${here}/action.yml" "${here}/install.sh" "${here}/../../helpers.sh")" - compiler="$(compiler_identity | digest)" - openssl="$(grep -h 'OPENSSL_VERSION_TEXT\|OPENSSL_VERSION_STR' \ - "${OPENSSL_ROOT}/include/openssl/opensslv.h" | digest)" - printf 'key=libdatachannel-%s-%s-%s-%s-%s-%s-%s\n' "${version}" "${RUNNER_OS}" \ - "${RUNNER_ARCH}" "${ImageOS:-image}" "${compiler:0:16}" "${openssl:0:16}" \ - "${files:0:16}" >> "${GITHUB_OUTPUT}" -} - -# Fails the install, naming why, and leaves nothing to be cached. -refuse() { - printf 'install.sh: %s\n' "$1" >&2 - rm -rf .local/.build/libdatachannel .local/libdatachannel - exit 1 -} - -install() { - check_runner - rm -rf .local/.build/libdatachannel .local/libdatachannel - mkdir -p .local/.build - local source=.local/.build/libdatachannel/source - git clone --quiet --depth 1 --branch "v${version}" "${repository}" "${source}" - local head - head="$(git -C "${source}" rev-parse HEAD)" - [ "${head}" = "${commit}" ] \ - || refuse "${repository} at v${version} checked out ${head}, and ${commit} is pinned" - # Only now the submodules, at the commits the pinned commit's gitlinks name: a tag that moved - # never has git fetch from the URLs its own .gitmodules would name. - git -C "${source}" submodule update --quiet --init --recursive --depth 1 - local compilers=() - if [ -n "${CC-}" ]; then - compilers+=(-DCMAKE_C_COMPILER="${CC}") - fi - if [ -n "${CXX-}" ]; then - compilers+=(-DCMAKE_CXX_COMPILER="${CXX}") - fi - local config work=.local/.build/libdatachannel/build - local prefix - config="$(configuration)" - prefix="$(mixed "${PWD}/.local/libdatachannel")" - # Bash 3.2, macOS's, reads an empty array as unset under set -u. - cmake -S "${source}" -B "${work}" ${compilers[@]+"${compilers[@]}"} \ - -DCMAKE_BUILD_TYPE="${config}" -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_SHARED_LIBS=ON \ - -DNO_WEBSOCKET=ON -DNO_EXAMPLES=ON -DNO_TESTS=ON -DNO_MEDIA=OFF \ - -DOPENSSL_ROOT_DIR="$(mixed "${OPENSSL_ROOT}")" -DCMAKE_INSTALL_PREFIX="${prefix}" - cmake --build "${work}" --config "${config}" --parallel - cmake --install "${work}" --config "${config}" --prefix "${prefix}" - rm -rf .local/.build/libdatachannel -} - -configure() { - check_runner - local library=lib/libdatachannel.so - case "${RUNNER_OS}" in - macOS) library=lib/libdatachannel.dylib ;; - Windows) library=lib/datachannel.lib ;; - esac - if [ ! -f .local/libdatachannel/include/rtc/rtc.hpp ] \ - || [ ! -e ".local/libdatachannel/${library}" ]; then - printf 'install.sh: .local/libdatachannel holds no include/rtc/rtc.hpp or %s\n' \ - "${library}" >&2 - exit 1 - fi - printf 'LIBDATACHANNEL_ROOT=%s\n' "$(mixed "${PWD}/.local/libdatachannel")" >> "${GITHUB_ENV}" - if [ "${RUNNER_OS}" = Windows ]; then - [ -f .local/libdatachannel/bin/datachannel.dll ] || { - printf 'install.sh: .local/libdatachannel holds no bin/datachannel.dll\n' >&2 - exit 1 - } - # A program finds the DLL on PATH, as a test b2 runs does. - cygpath -w "${PWD}/.local/libdatachannel/bin" >> "${GITHUB_PATH}" - fi - printf 'install.sh: libdatachannel %s in .local/libdatachannel\n' "${version}" -} - -case "${1-}" in - key) key ;; - install) install ;; - configure) configure ;; - *) - printf 'usage: install.sh key | install | configure\n' >&2 - exit 2 - ;; -esac diff --git a/tools/ci/actions/openssl/action.yml b/tools/ci/actions/openssl/action.yml deleted file mode 100644 index 313e3d05..00000000 --- a/tools/ci/actions/openssl/action.yml +++ /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) - -name: OpenSSL -description: >- - Lays out the runner's own OpenSSL 3 in .local/openssl, its headers and its libraries, and gives - the later steps OPENSSL_ROOT: the system's on Linux, Homebrew's openssl@3 on macOS, and on - Windows the image's, else a pinned installer checked against its SHA-256, whose DLLs it puts on - PATH. trystero's native backend and libdatachannel need it, until webcpp builds it from - third_party/. - -runs: - using: composite - steps: - - name: OpenSSL 3 - shell: bash - run: bash tools/ci/actions/openssl/install.sh diff --git a/tools/ci/actions/openssl/install.sh b/tools/ci/actions/openssl/install.sh deleted file mode 100644 index 8b04dc2d..00000000 --- a/tools/ci/actions/openssl/install.sh +++ /dev/null @@ -1,189 +0,0 @@ -#!/usr/bin/env bash -# 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 step of tools/ci/actions/openssl: the runner's own OpenSSL 3, laid out in .local/openssl as -# include/openssl and lib/, where trystero's build.jam looks for it when OPENSSL_ROOT names no -# other directory, and OPENSSL_ROOT given to the job's later steps, until webcpp builds it from -# third_party/. On Linux, the system's, which pkg-config names; on macOS, Homebrew's openssl@3, -# installed with brew when the image lacks it; on Windows on X64, the one the image installs in -# %ProgramFiles%\OpenSSL, always preferred, else the installer pinned here, checked against its -# SHA-256. -# -# Usage, from the superproject's root, with the variables a runner sets (RUNNER_OS, RUNNER_ARCH, -# RUNNER_TEMP, GITHUB_ENV, GITHUB_PATH, and ProgramFiles on Windows): install.sh -# -# On Linux and macOS, .local/openssl holds links: include/openssl to the system's headers, and -# lib/ the two libraries, so that a directory of its own, never the system's /usr/include, is -# given to a compiler: GCC and Clang given -isystem /usr/include no longer find the C library's -# headers through libstdc++'s #include_next (measured with g++-14 and clang++-18 on Ubuntu 24.04), -# as a reference parses its dependencies' directories. Debian and Ubuntu keep the two headers of -# OpenSSL's build configuration, opensslconf.h and configuration.h, apart, in the architecture's -# /usr/include//openssl, which a native compiler searches and a parse for another -# target, as trystero's reference is, does not: there include/openssl is a directory of links to -# each header of both, so that it holds every header of OpenSSL. On Windows it holds copies: the -# headers, and the import libraries libssl.lib and libcrypto.lib from the first of -# lib/VC/x64/MD, lib/VC/x64/MDd and lib that holds both (CMake's FindOpenSSL reads the same -# layout); their DLLs are in the installation's bin, which is put on PATH. -set -euo pipefail - -# The installer of Shining Light Productions that the image installs from, as -# slproweb/opensslhashes's win32_openssl_hashes.json names it (gh api -# repos/slproweb/opensslhashes/contents/win32_openssl_hashes.json): a fallback for an image without -# OpenSSL alone. Shining Light removes a superseded installer from /download/, so once 3.6.5 is -# superseded this URL answers 404 and the fallback fails at download.sh, naming the URL: the pin -# is then moved to the release the JSON lists, with its SHA-256. -installer=Win64OpenSSL-3_6_5.exe -installer_url="https://slproweb.com/download/${installer}" -installer_sha256=8b2fcf66088fa0d13fa5729ef374a182adf72edfffde89089b3b1bf48c3f257f - -here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# The functions every action shares: digest, mixed, configuration, compiler_identity. -# shellcheck source=SCRIPTDIR/../../helpers.sh -. "${here}/../../helpers.sh" - -# Fails the step, naming why, and leaves no .local/openssl. -refuse() { - printf 'install.sh: %s\n' "$1" >&2 - rm -rf .local/openssl - exit 1 -} - -# The major version include/openssl/opensslv.h of prefix states, or nothing: OpenSSL 1.1's states -# none. -major() { - sed -n 's/^#[[:space:]]*define[[:space:]]*OPENSSL_VERSION_MAJOR[[:space:]]*\([0-9]*\).*/\1/p' \ - "$1/openssl/opensslv.h" 2>/dev/null | head -n 1 -} - -# Stops unless the headers in include hold OpenSSL 3. -check_headers() { - local include="$1" - [ -f "${include}/openssl/ssl.h" ] || refuse "${include} holds no openssl/ssl.h" - local found - found="$(major "${include}")" - [ "${found}" = 3 ] || refuse "${include}/openssl/opensslv.h is not OpenSSL 3's: \ -OPENSSL_VERSION_MAJOR is '${found}'" -} - -# Links include/openssl and the two libraries of libdir with extension into .local/openssl; with -# configured, the directory that holds the headers of the build's configuration apart, -# include/openssl is a directory of links to each header of both. -link() { - local include="$1" libdir="$2" extension="$3" configured="${4-}" - check_headers "${include}" - local library - for library in libssl libcrypto; do - [ -e "${libdir}/${library}.${extension}" ] \ - || refuse "${libdir} holds no ${library}.${extension}" - done - rm -rf .local/openssl - mkdir -p .local/openssl/include .local/openssl/lib - if [ -n "${configured}" ]; then - mkdir .local/openssl/include/openssl - ln -s "${include}/openssl/"* "${configured}/"* .local/openssl/include/openssl/ \ - || refuse "${include}/openssl and ${configured} could not be linked together" - else - ln -s "${include}/openssl" .local/openssl/include/openssl - fi - [ -f .local/openssl/include/openssl/opensslconf.h ] \ - || refuse "${include}/openssl holds no opensslconf.h" - for library in libssl libcrypto; do - ln -s "${libdir}/${library}.${extension}" ".local/openssl/lib/${library}.${extension}" - done -} - -linux() { - command -v pkg-config >/dev/null 2>&1 || refuse 'pkg-config, which names the system OpenSSL, \ -is not on PATH' - local include libdir configured='' - include="$(pkg-config --variable=includedir openssl)" \ - || refuse 'pkg-config knows no openssl: install the development files of OpenSSL 3' - libdir="$(pkg-config --variable=libdir openssl)" - if [ ! -f "${include}/openssl/opensslconf.h" ]; then - command -v dpkg-architecture >/dev/null 2>&1 || refuse "${include}/openssl holds no \ -opensslconf.h, and dpkg-architecture, which names Debian's directory of the architecture's \ -headers, is not on PATH" - local multiarch - multiarch="$(dpkg-architecture -qDEB_HOST_MULTIARCH)" \ - || refuse 'dpkg-architecture names no multiarch tuple' - configured="${include}/${multiarch}/openssl" - [ -f "${configured}/opensslconf.h" ] \ - || refuse "neither ${include}/openssl nor ${configured} holds opensslconf.h" - fi - link "${include}" "${libdir}" so "${configured}" -} - -macos() { - command -v brew >/dev/null 2>&1 || refuse 'brew, which names openssl@3, is not on PATH' - local prefix - prefix="$(brew --prefix openssl@3)" - # The macOS images have openssl@3 only as a dependency of other formulae, which Homebrew moves - # to openssl@4 one by one: when it is gone, it is installed, its bottle checked by Homebrew - # against the SHA-256 its formula records, at the version Homebrew has then. - if [ ! -d "${prefix}" ]; then - printf "install.sh: Homebrew's openssl@3 is not installed in %s: " "${prefix}" - printf 'installing it with brew\n' - brew install openssl@3 || refuse 'brew install openssl@3 failed' - fi - [ -d "${prefix}" ] || refuse "Homebrew's openssl@3 is not installed in ${prefix}" - link "${prefix}/include" "${prefix}/lib" dylib -} - -# The image's OpenSSL, else the pinned installer's, installed in RUNNER_TEMP. -windows_prefix() { - local programs - programs="$(cygpath -u "${ProgramFiles:-C:\\Program Files}")" - if [ -f "${programs}/OpenSSL/include/openssl/ssl.h" ]; then - printf '%s\n' "${programs}/OpenSSL" - return - fi - local temp - temp="$(cygpath -u "${RUNNER_TEMP}")" - "${here}/../../download.sh" "${installer_url}" "${installer_sha256}" "${temp}/${installer}" \ - >&2 || refuse "${installer_url} could not be downloaded as pinned" - # Inno Setup's options, as the image's own install passes them. - "${temp}/${installer}" /verysilent /sp- /suppressmsgboxes \ - "/DIR=$(cygpath -w "${temp}/openssl")" >&2 \ - || refuse "${installer} did not install" - rm -f "${temp}/${installer}" - printf '%s\n' "${temp}/openssl" -} - -windows() { - local prefix - prefix="$(windows_prefix)" - check_headers "${prefix}/include" - local found='' directory - for directory in lib/VC/x64/MD lib/VC/x64/MDd lib; do - if [ -f "${prefix}/${directory}/libssl.lib" ] \ - && [ -f "${prefix}/${directory}/libcrypto.lib" ]; then - found="${prefix}/${directory}" - break - fi - done - [ -n "${found}" ] || refuse "${prefix} holds no libssl.lib and libcrypto.lib in lib/VC/x64/MD, \ -lib/VC/x64/MDd or lib" - rm -rf .local/openssl - mkdir -p .local/openssl/include .local/openssl/lib - cp -R "${prefix}/include/openssl" .local/openssl/include/openssl - cp "${found}/libssl.lib" "${found}/libcrypto.lib" .local/openssl/lib/ - cygpath -w "${prefix}/bin" >> "${GITHUB_PATH}" -} - -case "${RUNNER_OS-}-${RUNNER_ARCH-}" in - Linux-X64 | Linux-ARM64) linux ;; - macOS-X64 | macOS-ARM64) macos ;; - Windows-X64) windows ;; - *) - printf 'install.sh: no OpenSSL 3 is found or pinned for %s on %s: the action runs on ' \ - "${RUNNER_OS-}" "${RUNNER_ARCH-}" >&2 - printf 'Linux and macOS, on X64 and ARM64, and on Windows on X64\n' >&2 - exit 1 - ;; -esac -printf 'OPENSSL_ROOT=%s\n' "$(mixed "${PWD}/.local/openssl")" >> "${GITHUB_ENV}" -printf 'install.sh: OpenSSL %s in .local/openssl\n' "$(major .local/openssl/include)" diff --git a/tools/ci/actions_test.py b/tools/ci/actions_test.py index fe0b9af7..fc38daec 100755 --- a/tools/ci/actions_test.py +++ b/tools/ci/actions_test.py @@ -40,13 +40,8 @@ of its pinned commit, refuses one whose SHA-256 is not the pin before CMake runs, builds it with the lane's C compiler, natively and with emcmake, Debug on Windows, installs it in .local/secp256k1-native and .local/secp256k1-emscripten, exports their variables, and keys its -cache on the compiler and the emscripten build; libdatachannel clones the tag, refuses another -commit before CMake runs, builds it with the lane's compilers against OPENSSL_ROOT, which it -refuses without, Debug on Windows, where it puts its DLL on PATH, and keys its cache on the -compilers and OpenSSL's version; openssl lays out the system's OpenSSL 3 as links on Linux and -macOS, those of Debian's include//openssl too, copies the image's on Windows, from -lib/VC/x64/MD first, downloads the pinned installer when the image has none, and refuses one that -is not OpenSSL 3; and each refuses a runner it builds nothing for. The node action keys npm's +cache on the compiler and the emscripten build, and refuses a runner it builds nothing for. +The node action keys npm's cache on the lock file of every directory a job runs npm ci in: tools/doc, tools/lint, every library's oracle and the site. Nothing is fetched from the network: the downloads are file:// URLs or a server of the test's own on the loopback, git @@ -1108,16 +1103,10 @@ def test_emsdk_refuses_a_runner_it_pins_nothing_for(scratch: Path) -> None: # The external dependencies, which the lanes of a library that needs them build or lay out in # .local/, until webcpp builds them from third_party/. SECP256K1 = CI / 'actions/secp256k1/install.sh' -LIBDATACHANNEL = CI / 'actions/libdatachannel/install.sh' -OPENSSL = CI / 'actions/openssl/install.sh' SECP256K1_COMMIT = '6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d' SECP256K1_URL = f'https://github.com/bitcoin-core/secp256k1/archive/{SECP256K1_COMMIT}.tar.gz' SECP256K1_SHA256 = '3fe9fd705f4fdf2fe90d6e04b6c1fedd7e8f244a119315886f6468f52c2dfc33' -LIBDATACHANNEL_COMMIT = '6b1e2e620f1e37f0eafeee702eaea0043cb305fd' -LIBDATACHANNEL_REPOSITORY = 'https://github.com/paullouisageneau/libdatachannel.git' -OPENSSL_INSTALLER = 'https://slproweb.com/download/Win64OpenSSL-3_6_5.exe' -OPENSSL_INSTALLER_SHA256 = '8b2fcf66088fa0d13fa5729ef374a182adf72edfffde89089b3b1bf48c3f257f' # The options each build is configured with, as trystero's page builds it. SECP256K1_OPTIONS = [ @@ -1127,10 +1116,6 @@ def test_emsdk_refuses_a_runner_it_pins_nothing_for(scratch: Path) -> None: '-DSECP256K1_BUILD_TESTS=OFF', '-DSECP256K1_BUILD_EXHAUSTIVE_TESTS=OFF', '-DSECP256K1_BUILD_BENCHMARK=OFF', '-DSECP256K1_BUILD_CTIME_TESTS=OFF', ] -LIBDATACHANNEL_OPTIONS = ['-DCMAKE_INSTALL_LIBDIR=lib', '-DBUILD_SHARED_LIBS=ON', - '-DNO_WEBSOCKET=ON', '-DNO_EXAMPLES=ON', '-DNO_TESTS=ON', - '-DNO_MEDIA=OFF'] - # A stand-in of cmake: each call's words to cmake.log, one line each; --install --config # --prefix also writes every file STAND_IN_INSTALLS names, relative to the # prefix. @@ -1155,28 +1140,6 @@ def test_emsdk_refuses_a_runner_it_pins_nothing_for(scratch: Path) -> None: # A stand-in of a compiler, which says what it is as gcc's --version's first line does. FAKE_COMPILER = '#!/bin/sh\necho "$(basename "$0") (stand-in) ${STAND_IN_VERSION:-14.2.0}"\n' -# A stand-in of git for the libdatachannel action: `clone ... ` logs its words -# and makes the directory, `-C submodule ...` logs its words, and `-C rev-parse HEAD` -# prints STAND_IN_HEAD, else the pin. -FAKE_CLONE = r"""#!/usr/bin/env bash -set -euo pipefail -if [ "$1" = clone ]; then - printf '%s\n' "git $*" >> "${STAND_IN_LOG}" - mkdir -p "${@: -1}" - exit 0 -fi -if [ "$1 $3" = '-C submodule' ]; then - printf '%s\n' "git $*" >> "${STAND_IN_LOG}" - exit 0 -fi -if [ "$1 $3 $4" != '-C rev-parse HEAD' ]; then - echo "git: not a command of the stand-in: $*" >&2 - exit 1 -fi -echo "${STAND_IN_HEAD:-""" + LIBDATACHANNEL_COMMIT + r"""}" -""" - -# A stand-in of cygpath, which a Windows runner's Git Bash has: the path as it is. FAKE_CYGPATH = '#!/bin/sh\nprintf \'%s\\n\' "$2"\n' @@ -1374,302 +1337,6 @@ def test_secp256k1_refuses_a_runner_it_builds_nothing_for(scratch: Path) -> None assert not (scratch / '.local/secp256k1-native').exists() -def openssl_root(scratch: Path, name: str = 'openssl', major: str | None = '3', - configuration: str = '') -> Path: - """A stand-in installation of OpenSSL: include/openssl/ssl.h, opensslv.h, which states major - as its OPENSSL_VERSION_MAJOR, or none, as OpenSSL 1.1's, and opensslconf.h, there or, with - configuration, a multiarch tuple, in include//openssl, as Debian keeps it.""" - root = scratch / name - (root / 'include/openssl').mkdir(parents=True) - (root / 'include/openssl/ssl.h').write_text('/* ssl.h */\n') - configured = root / 'include' / configuration / 'openssl' - configured.mkdir(parents=True, exist_ok=True) - (configured / 'opensslconf.h').write_text('/* opensslconf.h */\n') - version = f'# define OPENSSL_VERSION_MAJOR {major}\n' if major else '' - (root / 'include/openssl/opensslv.h').write_text( - f'{version}# define OPENSSL_VERSION_TEXT "OpenSSL {major or "1.1"}.0.13"\n') - (root / 'lib').mkdir() - return root - - -def libdatachannel_tree(scratch: Path, system: str = 'Linux', processor: str = 'X64', - **extra: str) -> tuple[Path, dict[str, str]]: - """The libdatachannel action where it lives, with stand-ins of git, cmake and the compilers, - an OpenSSL where OPENSSL_ROOT names it, and a runner's variables.""" - directory = scratch / 'tools/ci/actions/libdatachannel' - directory.mkdir(parents=True) - shutil.copy2(LIBDATACHANNEL, directory / 'install.sh') - place_helpers(scratch) - shutil.copy2(LIBDATACHANNEL.parent / 'action.yml', directory / 'action.yml') - tools = stand_ins(scratch, {'git': FAKE_CLONE, 'cmake': FAKE_CMAKE, 'gcc-14': FAKE_COMPILER, - 'g++-14': FAKE_COMPILER, 'clang-18': FAKE_COMPILER, - 'clang++-18': FAKE_COMPILER, 'cygpath': FAKE_CYGPATH}) - installs = {'Linux': 'lib/libdatachannel.so', 'macOS': 'lib/libdatachannel.dylib', - 'Windows': 'lib/datachannel.lib bin/datachannel.dll'}.get(system, '') - return directory / 'install.sh', dependency_runner( - scratch, system, processor, tools, OPENSSL_ROOT=str(openssl_root(scratch)), - STAND_IN_INSTALLS=f'include/rtc/rtc.hpp {installs}', **extra) - - -def test_libdatachannel_builds_the_pinned_tag_with_the_lanes_compilers(scratch: Path) -> None: - script, runner = libdatachannel_tree(scratch, CC='gcc-14', CXX='g++-14') - result = dependency_step(scratch, script, runner, 'install') - assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) - work = '.local/.build/libdatachannel/build' - prefix = f'{scratch.resolve()}/.local/libdatachannel' - assert logged(scratch) == [ - # The submodules are fetched only once HEAD is the pin, at the commits its gitlinks name. - f'git clone --quiet --depth 1 --branch v0.24.6 {LIBDATACHANNEL_REPOSITORY} ' - '.local/.build/libdatachannel/source', - 'git -C .local/.build/libdatachannel/source submodule update --quiet --init --recursive ' - '--depth 1', - f'cmake -S .local/.build/libdatachannel/source -B {work} -DCMAKE_C_COMPILER=gcc-14 ' - f'-DCMAKE_CXX_COMPILER=g++-14 -DCMAKE_BUILD_TYPE=Release ' - f'{" ".join(LIBDATACHANNEL_OPTIONS)} -DOPENSSL_ROOT_DIR={scratch}/openssl ' - f'-DCMAKE_INSTALL_PREFIX={prefix}', - f'cmake --build {work} --config Release --parallel', - f'cmake --install {work} --config Release --prefix {prefix}'], logged(scratch) - assert not (scratch / '.local/.build/libdatachannel').exists() - result = dependency_step(scratch, script, runner, 'configure') - assert result.returncode == 0, (result.returncode, result.stderr) - assert (scratch / 'github-env').read_text() == f'LIBDATACHANNEL_ROOT={prefix}\n' - assert not (scratch / 'github-path').exists() - # The key names the compilers and the OpenSSL it is built against. - keys = [] - for extra in ({'CC': 'gcc-14', 'CXX': 'g++-14'}, {'CC': 'clang-18', 'CXX': 'clang++-18'}, - {'CC': 'gcc-14', 'CXX': 'g++-14', 'STAND_IN_VERSION': '14.3.0'}, - {'CC': '', 'CXX': ''}): - (scratch / 'github-output').unlink(missing_ok=True) - result = dependency_step(scratch, script, {**runner, **extra}, 'key') - assert result.returncode == 0, (result.returncode, result.stderr) - keys.append((scratch / 'github-output').read_text()) - (scratch / 'openssl/include/openssl/opensslv.h').write_text( - '# define OPENSSL_VERSION_MAJOR 3\n# define OPENSSL_VERSION_TEXT "OpenSSL 3.5.5"\n') - (scratch / 'github-output').unlink() - dependency_step(scratch, script, runner, 'key') - keys.append((scratch / 'github-output').read_text()) - assert all(key.startswith('key=libdatachannel-0.24.6-Linux-X64-ubuntu24-') for key in keys) - assert len(set(keys)) == len(keys), keys - - -def test_libdatachannel_on_windows_builds_debug_and_puts_its_dll_on_path(scratch: Path) -> None: - script, runner = libdatachannel_tree(scratch, 'Windows', 'X64') - result = dependency_step(scratch, script, runner, 'install') - assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) - assert '-DCMAKE_C_COMPILER' not in logged(scratch)[2], logged(scratch) - assert '-DCMAKE_BUILD_TYPE=Debug ' in logged(scratch)[2], logged(scratch) - result = dependency_step(scratch, script, runner, 'configure') - assert result.returncode == 0, (result.returncode, result.stderr) - assert (scratch / 'github-path').read_text() == ( - f'{scratch.resolve()}/.local/libdatachannel/bin\n'), (scratch / 'github-path').read_text() - - -def test_libdatachannel_refuses_another_commit(scratch: Path) -> None: - # The tag's commit is the pin: a clone that checks out another fails, naming both, before - # CMake runs, and leaves nothing to be cached. - script, runner = libdatachannel_tree(scratch, CC='gcc-14', CXX='g++-14') - other = '1' * 40 - result = dependency_step(scratch, script, {**runner, 'STAND_IN_HEAD': other}, 'install') - assert result.returncode == 1, (result.returncode, result.stdout, result.stderr) - assert (f'install.sh: {LIBDATACHANNEL_REPOSITORY} at v0.24.6 checked out {other}, and ' - f'{LIBDATACHANNEL_COMMIT} is pinned') in result.stderr, result.stderr - # Nothing but the clone ran: no submodule was fetched, and CMake never ran. - assert logged(scratch) == [ - f'git clone --quiet --depth 1 --branch v0.24.6 {LIBDATACHANNEL_REPOSITORY} ' - '.local/.build/libdatachannel/source'], logged(scratch) - assert not (scratch / '.local/libdatachannel').exists() - assert not (scratch / '.local/.build/libdatachannel').exists() - - -def test_libdatachannel_refuses_a_runner_or_no_openssl(scratch: Path) -> None: - script, runner = libdatachannel_tree(scratch) - for system, processor in (('Linux', 'ARM'), ('Windows', 'ARM64'), ('', '')): - result = dependency_step(scratch, script, {**runner, 'RUNNER_OS': system, - 'RUNNER_ARCH': processor}, 'install') - assert result.returncode == 1, (system, processor, result.returncode) - assert f'and Windows on X64, not for {system} on {processor}' in result.stderr, ( - result.stderr) - for openssl in ('', str(scratch / 'nothing')): - result = dependency_step(scratch, script, {**runner, 'OPENSSL_ROOT': openssl}, 'install') - assert result.returncode == 1, (openssl, result.returncode) - assert (f'install.sh: OPENSSL_ROOT names no OpenSSL ({openssl}): the openssl action runs ' - 'first') in result.stderr, result.stderr - assert logged(scratch) == [] - - -def openssl_tree(scratch: Path, system: str, processor: str, - tools: dict[str, str]) -> tuple[Path, dict[str, str]]: - """The openssl action where it lives, beside a download.sh that only says it was called, with - the stand-ins tools names, and a runner's variables.""" - directory = scratch / 'tools/ci/actions/openssl' - directory.mkdir(parents=True) - shutil.copy2(OPENSSL, directory / 'install.sh') - place_helpers(scratch) - download = scratch / 'tools/ci/download.sh' - download.write_text(f'#!/bin/sh\nprintf \'%s %s\\n\' "$1" "$2" >> "{scratch}/downloads.log"\n' - f'echo "{CALLED}" >&2\nexit {CALLED_STATUS}\n') - download.chmod(0o755) - (scratch / 'temp').mkdir() - return directory / 'install.sh', dependency_runner( - scratch, system, processor, stand_ins(scratch, {'cygpath': FAKE_CYGPATH, **tools})) - - -def test_openssl_lays_out_the_runners_own(scratch: Path) -> None: - # On Linux the system's, which pkg-config names; on macOS Homebrew's openssl@3: links to its - # headers and its two libraries, in a directory of their own, and OPENSSL_ROOT. - for system, tool, extension in (('Linux', 'pkg-config', 'so'), ('macOS', 'brew', 'dylib')): - root = scratch / system - root.mkdir() - system_openssl = openssl_root(root, 'system openssl') - for library in ('libssl', 'libcrypto'): - (system_openssl / 'lib' / f'{library}.{extension}').write_text(library) - answers = {'pkg-config': '#!/bin/sh\ncase "$1" in\n' - f' --variable=includedir) echo "{system_openssl}/include" ;;\n' - f' --variable=libdir) echo "{system_openssl}/lib" ;;\n' - ' *) exit 1 ;;\nesac\n', - 'brew': '#!/bin/sh\n[ "$*" = "--prefix openssl@3" ] && ' - f'echo "{system_openssl}"\n'} - script, runner = openssl_tree(root, system, 'ARM64', {tool: answers[tool]}) - result = dependency_step(root, script, runner) - assert result.returncode == 0, (system, result.returncode, result.stderr) - laid = root.resolve() / '.local/openssl' - assert (laid / 'include/openssl').resolve() == ( - system_openssl.resolve() / 'include/openssl'), system - assert sorted(p.name for p in (laid / 'lib').iterdir()) == [ - f'libcrypto.{extension}', f'libssl.{extension}'], system - assert (laid / f'lib/libssl.{extension}').resolve() == ( - system_openssl.resolve() / f'lib/libssl.{extension}'), system - assert (root / 'github-env').read_text() == f'OPENSSL_ROOT={laid}\n', ( - system, (root / 'github-env').read_text()) - assert 'install.sh: OpenSSL 3 in .local/openssl' in result.stdout, result.stdout - assert downloads(root) == [], system - - -def test_openssl_on_debian_links_the_headers_of_its_configuration_too(scratch: Path) -> None: - # Debian and Ubuntu keep opensslconf.h and configuration.h in the architecture's - # include//openssl, which dpkg-architecture names: include/openssl is then a - # directory of links to each header of both, which a parse for another target, which does not - # search the architecture's directory, reads whole. - system_openssl = openssl_root(scratch, 'system openssl', configuration='x86_64-linux-gnu') - (system_openssl / 'include/x86_64-linux-gnu/openssl/configuration.h').write_text('/* c */\n') - for library in ('libssl', 'libcrypto'): - (system_openssl / 'lib' / f'{library}.so').write_text(library) - tools = {'pkg-config': '#!/bin/sh\ncase "$1" in\n' - f' --variable=includedir) echo "{system_openssl}/include" ;;\n' - f' --variable=libdir) echo "{system_openssl}/lib" ;;\n' - ' *) exit 1 ;;\nesac\n', - 'dpkg-architecture': '#!/bin/sh\n[ "$*" = -qDEB_HOST_MULTIARCH ] && ' - 'echo x86_64-linux-gnu\n'} - script, runner = openssl_tree(scratch, 'Linux', 'X64', tools) - result = dependency_step(scratch, script, runner) - assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) - laid = scratch.resolve() / '.local/openssl/include/openssl' - assert laid.is_dir() and not laid.is_symlink(), laid - real = system_openssl.resolve() / 'include' - assert {entry.name: entry.resolve() for entry in laid.iterdir()} == { - 'ssl.h': real / 'openssl/ssl.h', 'opensslv.h': real / 'openssl/opensslv.h', - 'opensslconf.h': real / 'x86_64-linux-gnu/openssl/opensslconf.h', - 'configuration.h': real / 'x86_64-linux-gnu/openssl/configuration.h'}, ( - sorted(laid.iterdir())) - # Without the architecture's directory, the action refuses, naming where it looked. - shutil.rmtree(system_openssl / 'include/x86_64-linux-gnu') - result = dependency_step(scratch, script, runner) - assert result.returncode == 1, (result.returncode, result.stderr) - assert (f'install.sh: neither {system_openssl}/include/openssl nor {system_openssl}/include/' - 'x86_64-linux-gnu/openssl holds opensslconf.h') in result.stderr, result.stderr - assert not (scratch / '.local/openssl').exists() - - -def test_openssl_on_windows_copies_the_images_and_puts_its_dlls_on_path(scratch: Path) -> None: - # The image's, in %ProgramFiles%\OpenSSL: its headers, and the import libraries of the first - # of lib/VC/x64/MD, lib/VC/x64/MDd and lib that holds both. - programs = scratch / 'Program Files' - installed = openssl_root(programs, 'OpenSSL') - (installed / 'lib/VC/x64/MD').mkdir(parents=True) - for library in ('libssl.lib', 'libcrypto.lib'): - (installed / 'lib/VC/x64/MD' / library).write_text(f'MD {library}') - (installed / 'lib' / library).write_text(f'top {library}') - script, runner = openssl_tree(scratch, 'Windows', 'X64', {}) - runner['ProgramFiles'] = str(programs) - result = dependency_step(scratch, script, runner) - assert result.returncode == 0, (result.returncode, result.stderr) - laid = scratch.resolve() / '.local/openssl' - assert (laid / 'include/openssl/ssl.h').is_file() - assert not (laid / 'include/openssl').is_symlink() - assert (laid / 'lib/libssl.lib').read_text() == 'MD libssl.lib' - assert (laid / 'lib/libcrypto.lib').read_text() == 'MD libcrypto.lib' - assert (scratch / 'github-path').read_text() == f'{installed}/bin\n', ( - (scratch / 'github-path').read_text()) - assert (scratch / 'github-env').read_text() == f'OPENSSL_ROOT={laid}\n' - assert downloads(scratch) == [] - - -def test_openssl_on_windows_without_one_downloads_the_pinned_installer(scratch: Path) -> None: - script, runner = openssl_tree(scratch, 'Windows', 'X64', {}) - runner['ProgramFiles'] = str(scratch / 'Program Files') - result = dependency_step(scratch, script, runner) - assert result.returncode == 1, (result.returncode, result.stderr) - assert CALLED in result.stderr, result.stderr - assert downloads(scratch) == [(OPENSSL_INSTALLER, OPENSSL_INSTALLER_SHA256)] - assert not (scratch / '.local/openssl').exists() - - -def test_openssl_refuses_one_that_is_not_3_or_a_runner_it_has_none_for(scratch: Path) -> None: - root = scratch / 'old' - root.mkdir() - old = openssl_root(root, 'openssl@1.1', None) - brew = f'#!/bin/sh\necho "{old}"\n' - script, runner = openssl_tree(root, 'macOS', 'X64', {'brew': brew}) - result = dependency_step(root, script, runner) - assert result.returncode == 1, (result.returncode, result.stderr) - assert (f"install.sh: {old}/include/openssl/opensslv.h is not OpenSSL 3's: " - "OPENSSL_VERSION_MAJOR is ''") in result.stderr, result.stderr - assert not (root / '.local/openssl').exists() and not (root / 'github-env').exists() - for system, processor in (('Windows', 'ARM64'), ('Linux', 'ARM'), ('', '')): - result = dependency_step(root, script, {**runner, 'RUNNER_OS': system, - 'RUNNER_ARCH': processor}) - assert result.returncode == 1, (system, processor, result.returncode) - assert (f'install.sh: no OpenSSL 3 is found or pinned for {system} on {processor}' - in result.stderr), result.stderr - assert downloads(root) == [] - - -def test_openssl_on_macos_installs_openssl_3_when_the_image_lacks_it(scratch: Path) -> None: - # Homebrew's openssl@3 is in the image today only as a dependency of other formulae: when it - # is not installed, the action installs it with brew (whose bottle Homebrew checks against its - # SHA-256), says so, and lays it out as it would the image's. - staged = openssl_root(scratch, 'staged') - for library in ('libssl', 'libcrypto'): - (staged / 'lib' / f'{library}.dylib').write_text(library) - prefix = scratch / 'homebrew/opt/openssl@3' - brew = ('#!/bin/sh\n' - f'printf \'%s\\n\' "brew $*" >> "{scratch}/stand-in.log"\n' - 'case "$*" in\n' - f' "--prefix openssl@3") echo "{prefix}" ;;\n' - f' "install openssl@3") mkdir -p "{prefix.parent}" && ' - f'cp -R "{staged}" "{prefix}" ;;\n' - ' *) exit 1 ;;\n' - 'esac\n') - script, runner = openssl_tree(scratch, 'macOS', 'ARM64', {'brew': brew}) - result = dependency_step(scratch, script, runner) - assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) - assert logged(scratch) == ['brew --prefix openssl@3', 'brew install openssl@3'], ( - logged(scratch)) - assert (f"install.sh: Homebrew's openssl@3 is not installed in {prefix}: installing it with " - 'brew') in result.stdout, result.stdout - laid = scratch.resolve() / '.local/openssl' - assert (laid / 'include/openssl').resolve() == (prefix.resolve() / 'include/openssl') - # A brew that cannot install it fails the step, naming the formula. - (scratch / 'stand-in.log').unlink() - shutil.rmtree(prefix) - failing = brew.replace('cp -R', 'false && cp -R') - (scratch / 'tools-on-path/brew').write_text(failing) - result = dependency_step(scratch, script, runner) - assert result.returncode == 1, (result.returncode, result.stderr) - assert 'install.sh: brew install openssl@3 failed' in result.stderr, result.stderr - assert not (scratch / '.local/openssl').exists() - - CHROME = CI / 'actions/chrome/install.sh' CHROME_VERSION = '155.0.8059.39' CHROME_BUILDS = { @@ -1916,16 +1583,6 @@ def helper(call: str, **variables: str) -> str: test_secp256k1_on_windows_builds_debug_with_visual_studio, test_secp256k1_refuses_an_archive_it_does_not_pin, test_secp256k1_refuses_a_runner_it_builds_nothing_for, - test_libdatachannel_builds_the_pinned_tag_with_the_lanes_compilers, - test_libdatachannel_on_windows_builds_debug_and_puts_its_dll_on_path, - test_libdatachannel_refuses_another_commit, - test_libdatachannel_refuses_a_runner_or_no_openssl, - test_openssl_lays_out_the_runners_own, - test_openssl_on_debian_links_the_headers_of_its_configuration_too, - test_openssl_on_macos_installs_openssl_3_when_the_image_lacks_it, - test_openssl_on_windows_copies_the_images_and_puts_its_dlls_on_path, - test_openssl_on_windows_without_one_downloads_the_pinned_installer, - test_openssl_refuses_one_that_is_not_3_or_a_runner_it_has_none_for, test_container_builds_the_image_once_and_loads_it_after, test_chrome_installs_the_pinned_headless_shell, test_chrome_installs_full_chrome_for_isolated_certificate_trust, diff --git a/tools/ci/container/Dockerfile b/tools/ci/container/Dockerfile index 99b16f9f..84bf8c6b 100644 --- a/tools/ci/container/Dockerfile +++ b/tools/ci/container/Dockerfile @@ -6,10 +6,9 @@ # The image of the container lanes (tools/ci/matrix.py), GCC 14 and Clang 18 on libstdc++: Ubuntu # 24.04, the release of their runner, pinned by the digest of its image index (docker-library's -# repo-info, repos/ubuntu/remote/24.04.md), with the two compilers, the development files of the -# OpenSSL 3 that trystero's native backend is built against, as on the runner, and Python, which -# runs the examples. Git applies the checked Boost and OpenSSL patches; Make and Perl build -# OpenSSL from its pinned source. b2, Boost's headers and the libraries the CI's actions build +# repo-info, repos/ubuntu/remote/24.04.md), with the two compilers and Python, which runs +# the examples. Git applies checked overlays; Make and Perl build pinned OpenSSL, and CMake +# builds pinned libdatachannel against that exact provider. b2, Boost's headers and the libraries the CI's actions build # are the runner's, mounted at their own paths; the lane runs in it with no network but the # loopback, which the packages are installed before. # @@ -47,5 +46,5 @@ RUN sed -i 's/^Signed-By: .*/&\nSnapshot: yes/' /etc/apt/sources.list.d/ubuntu.s --snapshot "${SNAPSHOT}" \ && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 install --yes \ --no-install-recommends --snapshot "${SNAPSHOT}" \ - g++-14 clang-18 libssl-dev python3 git make perl \ + g++-14 clang-18 python3 git make perl cmake pkg-config \ && rm -rf /var/lib/apt/lists/* diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 663b1c2b..beada8bb 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -162,13 +162,12 @@ # until webcpp builds them from third_party/ (CODING-GUIDELINES.md chapter 16): the CI's actions # of these names, tools/ci/actions/, install each where the build looks, in .local/, # before a lane, an own lane, the docs or the lint that builds such a library runs. -EXTERNAL_DEPENDENCIES = {'trystero': ('secp256k1', 'libdatachannel', 'openssl')} +EXTERNAL_DEPENDENCIES = {'trystero': ('secp256k1',)} # The variables that name those libraries' directories, which the actions give a job, and a lane # of such a library passes to b2 as -s=: a library's build.jam reads them from b2's # command line alone, never from the environment. -EXTERNAL_VARIABLES = ('SECP256K1_ROOT', 'SECP256K1_EMSCRIPTEN_ROOT', 'LIBDATACHANNEL_ROOT', - 'OPENSSL_ROOT') +EXTERNAL_VARIABLES = ('SECP256K1_ROOT', 'SECP256K1_EMSCRIPTEN_ROOT') # The directory of the Dockerfile a container lane's image is built from, and the image, tagged # with the start of the Dockerfile's SHA-256: an image of another Dockerfile is never taken for it. @@ -596,12 +595,22 @@ def own_lane_base(target: str | None) -> Lane: return known[OWN_LANE_BASES[target]] +def own_lane_profile(own: OwnLane) -> Lane: + """Select a compiler-specific dependency suite or the target's default lane.""" + if own.library == 'asio' and own.target == 'native': + profiles = {'openssl-upstream-msvc-14.3': 'msvc-14.3', + 'openssl-upstream-msvc-14.5': 'msvc-14.5'} + if own.lane in profiles: + return next(lane for lane in LANES if lane.id == profiles[own.lane]) + return own_lane_base(own.target) + + 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 of its job, the image, the setup and the compilers of the lane it shares, and whether its library needs a library webcpp does not build, which the job reads from here alone.""" - base = own_lane_base(own.target) + base = own_lane_profile(own) entry: dict[str, object] = {'library': own.library, 'lane': own.lane, 'directories': list(own.directories)} if own.target is not None: @@ -627,7 +636,7 @@ def own_lanes(user_config: Path, library: str | None) -> list[OwnLane]: lanes = [lane for lane in lanes if library is None or lane.library == library] for own in lanes: try: - own_lane_base(own.target) + own_lane_profile(own) except Failure as failure: raise Failure(f'{own.library} declares its own lane {own.lane} in ' f'{" and ".join(own.directories)} on {own.target}, which the CI cannot ' @@ -764,7 +773,7 @@ def own_lane_command(own: OwnLane, user_config: Path, xml: Path | None, """The own lane's command: b2, from scratch, on // for each of its directories; with Clang 18 when it names no target, and otherwise with the toolset and the options of the lane it shares plus its own mode coverage, writing xml, as that lane does.""" - base = own_lane_base(own.target) + base = own_lane_profile(own) external = external_arguments(needs_external(own.library)) if own.target is None: return ['b2', f'--user-config={user_config}', '-a', f'toolset={base.toolset}', *external, @@ -875,7 +884,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.""" - register(resolved(own_lane_base(own.target)), 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)) @@ -1031,7 +1040,7 @@ def main(arguments: list[str]) -> int: # writes none, and its job is its verdict. for own in (parsed_own_lane(json.dumps(entry)) for entry in owned): if own.target is not None: - lanes.append(replace(own_lane_base(own.target), id=own.id, name=own.name, + lanes.append(replace(own_lane_profile(own), id=own.id, name=own.name, lane=own.id)) return run_report(lanes, options.lanes, options.out) except Failure as failure: diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 6d444c77..46e01a40 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -540,6 +540,25 @@ def test_beast_browser_lanes_cover_policies_and_exception_modes(root): assert all(option not in command for option in options), command +def test_openssl_upstream_lanes_use_the_windows_builds(root): + # Exercise the public planner and command builder. A native-only lane used + # to select Linux even when its purpose was to validate the MSVC recipe. + for version in ('14.3', '14.5'): + name = f'openssl-upstream-msvc-{version}' + own = matrix.parsed_own_lanes( + f'asio {name} libs/asio/test/tls native original')[0] + entry = own_lane_entry_of(own) + base = next(lane for lane in matrix.LANES if lane.id == f'msvc-{version}') + assert entry['os'] == base.os, entry + command = matrix.own_lane_command(own, root / 'config.jam', root / 'test.xml', []) + assert f'toolset={base.toolset}' in command, command + assert all(option in command for option in matrix.MSVC_OPTIONS), command + assert matrix.parsed_own_lane(json.dumps(entry)) == own + ordinary = matrix.parsed_own_lanes( + 'asio openssl-upstream libs/asio/test/tls native original')[0] + assert own_lane_entry_of(ordinary)['os'] == 'ubuntu-24.04' + + def test_a_wasip3_lane_can_bind_a_loopback_socket(root): # Run the planned lane, including its launcher: Wasmtime refuses even a loopback bind # without an explicit network grant, which a successful compile cannot establish. @@ -1005,7 +1024,7 @@ def test_a_lane_of_a_library_with_external_dependencies_says_so(root): # the CI's actions of their names, on a lane or an own lane that builds trystero: its entry # says external, and no other does. assert matrix.EXTERNAL_DEPENDENCIES == { - 'trystero': ('secp256k1', 'libdatachannel', 'openssl')}, matrix.EXTERNAL_DEPENDENCIES + 'trystero': ('secp256k1',)}, matrix.EXTERNAL_DEPENDENCIES # Asio builds the pinned OpenSSL sources through its B2 dependency. assert not matrix.needs_external('asio') for dependencies in matrix.EXTERNAL_DEPENDENCIES.values(): @@ -1080,19 +1099,18 @@ def job_steps(job: str) -> list[str]: def test_the_jobs_install_the_external_dependencies(_): - # The lanes and the own lanes run the dependency actions for an entry that says external, - # OpenSSL first, which libdatachannel builds against, and secp256k1 for emscripten too after - # emsdk on an entry that has it; libdatachannel and OpenSSL, which only the native backend - # needs, not on emscripten. The docs and lint jobs run them when the plan's external is true, - # with Clang 18, the toolset they parse with, and the lint, which analyses emscripten's - # commands, with secp256k1's emscripten build when a library declares emscripten. + # Only secp256k1 remains external. B2 builds transport and TLS from source, + # so independent binary-install actions must not inject a second provider. jobs = workflow_jobs() + for job in jobs.values(): + assert 'uses: ./tools/ci/actions/openssl' not in job + assert 'uses: ./tools/ci/actions/libdatachannel' not in job plan = jobs['plan'] assert 'external: ${{ steps.plan.outputs.external }}' in plan, plan assert 'lint-external: ${{ steps.plan.outputs.lint-external }}' in plan, plan assert 'python3 tools/ci/matrix.py external "${arguments[@]}"' in plan, plan assert 'lint_external="$(python3 tools/ci/matrix.py external)"' in plan, plan - actions = ('emsdk', 'openssl', 'secp256k1', 'libdatachannel') + actions = ('emsdk', 'secp256k1') steps = job_steps(jobs['lanes']) uses = [next((action for action in actions if f'./tools/ci/actions/{action}' in step), None) for step in steps] @@ -1100,24 +1118,20 @@ def test_the_jobs_install_the_external_dependencies(_): by_action = {action: step for action, step in zip(uses, steps) if action} for action in actions: assert by_action[action].lstrip().startswith(f'- &{action}\n'), by_action[action] - assert 'if: matrix.external && !matrix.emsdk' in by_action['openssl'], by_action assert 'if: matrix.external\n' in by_action['secp256k1'], by_action assert 'emscripten: ${{ matrix.emsdk }}' in by_action['secp256k1'], by_action assert 'cc: ${{ matrix.cc }}' in by_action['secp256k1'], by_action - assert 'if: matrix.external && !matrix.emsdk' in by_action['libdatachannel'], by_action - assert 'cxx: ${{ matrix.cxx }}' in by_action['libdatachannel'], by_action # The own lanes install them by the same anchors, in the same order. firsts = [step.strip().splitlines()[0] for step in job_steps(jobs['own-lanes'])] aliases = [first for first in firsts if first in {f'- *{action}' for action in actions}] assert aliases == [f'- *{action}' for action in actions], aliases for name, output in (('docs', 'external'), ('lint', 'lint-external')): steps = job_steps(jobs[name]) - for action in ('openssl', 'secp256k1', 'libdatachannel'): + for action in ('secp256k1',): found = [step for step in steps if f'uses: ./tools/ci/actions/{action}' in step] assert len(found) == 1, (name, action, found) assert f"if: needs.plan.outputs.{output} == 'true'" in found[0], (name, found) - if action != 'openssl': - assert 'cc: clang-18' in found[0], (name, found) + assert 'cc: clang-18' in found[0], (name, found) emsdk = next(index for index, step in enumerate(steps) if 'actions/emsdk' in step) secp256k1 = next(index for index, step in enumerate(steps) if 'actions/secp256k1' in step) assert emsdk < secp256k1, name @@ -1287,7 +1301,7 @@ def test_a_container_lane_runs_b2_with_no_network(root): assert re.search(r'install[^&]*--snapshot "\$\{SNAPSHOT\}" ca-certificates', code), code digest = hashlib.sha256(dockerfile.encode()).hexdigest() assert matrix.CONTAINER_IMAGE == f'webcpp-lane:{digest[:16]}', matrix.CONTAINER_IMAGE - for package in ('g++-14', 'clang-18', 'libssl-dev', 'python3', 'git', 'make', 'perl'): + for package in ('g++-14', 'clang-18', 'python3', 'git', 'make', 'perl', 'cmake', 'pkg-config'): assert re.search(r'install\b[^&]*\s' + re.escape(package) + r'(?=\s|$)', code), ( package, code) entry = host_lane(root) @@ -1307,7 +1321,7 @@ def test_a_container_lane_runs_b2_with_no_network(root): for name in matrix.EXTERNAL_VARIABLES: environment.pop(name, None) environment.update(PATH=f'{tools}:{environment["PATH"]}', STAND_IN_DOCKER_LOG=str(log), - STAND_IN_IMAGE=matrix.CONTAINER_IMAGE, LIBDATACHANNEL_ROOT='/somewhere') + STAND_IN_IMAGE=matrix.CONTAINER_IMAGE, SECP256K1_ROOT='/somewhere') result = subprocess.run([sys.executable, str(root / 'tools/ci/matrix.py'), 'lane', json.dumps(entry), '--', '--build-dir=bin/lane'], cwd=root, env=environment, capture_output=True, text=True, check=False, @@ -1337,8 +1351,8 @@ def test_a_container_lane_runs_b2_with_no_network(root): assert command[1:4] == [f'--user-config={config.resolve()}', '-a', '--dump-tests'], command toolset = command.index(next(word for word in command if word.startswith('toolset='))) assert command[toolset + 1:toolset + 3] == ['webcpp-require-external=on', - '-sLIBDATACHANNEL_ROOT=/somewhere'], command - assert not any(word.startswith('-sSECP256K1_ROOT') for word in command), command + '-sSECP256K1_ROOT=/somewhere'], command + assert not any(word.startswith('-sLIBDATACHANNEL_ROOT') for word in command), command version = matrix.major_version('clang++') system = 'darwin' if sys.platform == 'darwin' else 'linux' assert (resolved / f'bin/ci/clang-{system}-{version}.xml').is_file() @@ -1400,6 +1414,7 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): test_own_lanes_on_targets, test_an_own_lanes_command, test_beast_browser_lanes_cover_policies_and_exception_modes, + test_openssl_upstream_lanes_use_the_windows_builds, test_a_wasip3_lane_can_bind_a_loopback_socket, test_a_lane_is_named_by_the_compiler_version, test_abbreviated_paths_keep_the_lane_name, diff --git a/tools/libdatachannel/build.py b/tools/libdatachannel/build.py new file mode 100644 index 00000000..33c3d106 --- /dev/null +++ b/tools/libdatachannel/build.py @@ -0,0 +1,175 @@ +#!/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) +"""Build pinned static WebRTC dependencies against B2's exact OpenSSL provider.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import sys +import tempfile +import time + +from source import check_checkout, stage_source + +HERE = Path(__file__).resolve().parent + + +def run(command: list[str], directory: Path, env: dict[str, str], log: Path) -> None: + """Keep bounded upstream diagnostics outside the disposable source/build tree.""" + print('+ ' + shlex.join(command), flush=True) + try: + with log.open('w') as stream: + result = subprocess.run(command, cwd=directory, env=env, stdout=stream, + stderr=subprocess.STDOUT, timeout=1800) + except subprocess.TimeoutExpired as error: + raise RuntimeError(f'command timed out; full log: {log}') from error + if result.returncode: + print(log.read_text(errors='replace')[-14000:], file=sys.stderr) + raise RuntimeError(f'command failed ({result.returncode}); full log: {log}') + + +def provider(root: Path, windows: bool) -> dict: + """Require the source-built threaded provider, never a discovered system library.""" + record = json.loads((root / 'build.json').read_text()) + expected = json.loads((HERE.parent / 'openssl/pin.json').read_text()) + if record['pin'] != expected or record['threading'] != 'multi': + raise RuntimeError('libdatachannel requires the pinned OpenSSL built with threading=multi') + names = ('libssl.lib', 'libcrypto.lib') if windows else ('libssl.a', 'libcrypto.a') + for name in names: + if hashlib.sha256((root / name).read_bytes()).hexdigest() != record['sha256'][name]: + raise RuntimeError(f'OpenSSL provider differs from its build record: {name}') + return record + + +def build(args: argparse.Namespace) -> None: + source, output, openssl = args.source.resolve(), args.output.resolve(), args.openssl.resolve() + pin = json.loads((HERE / 'pin.json').read_text()) + check_checkout(source, pin) + windows = args.platform == 'windows' + ssl = provider(openssl, windows) + output.mkdir(parents=True, exist_ok=True) + driver = shutil.which(args.cxx) + if driver is None: + raise RuntimeError(f'configured C++ compiler is missing: {args.cxx}') + cxx = Path(driver).absolute() + cc = cxx.with_name(cxx.name.replace('clang++', 'clang').replace('g++', 'gcc')) + if not cc.is_file() and cxx.is_symlink(): + resolved = cxx.resolve() + cc = resolved.with_name(resolved.name.replace('clang++', 'clang').replace('g++', 'gcc')) + if not cc.is_file(): + raise RuntimeError(f'configured compiler has no C driver: {cc}') + arguments = args.flags[1:] if args.flags[:1] == ['--'] else args.flags + separator = arguments.index('--cxx-flags') + cflags, flags = arguments[:separator], arguments[separator + 1:] + # Upstream WebRTC uses exceptions and RTTI internally even when a consumer + # only uses Trystero's exception-free timer, sealer or WebSocket adapters. + flags = [flag for flag in flags if flag not in ('-fno-exceptions', '-fno-rtti', + '-D_HAS_EXCEPTIONS=0', '/D_HAS_EXCEPTIONS=0', '/GR-')] + flags += ['/EHsc', '/GR', '/Gy', '/Gw'] if windows else [ + '-fexceptions', '-frtti', '-ffunction-sections', '-fdata-sections'] + # C dependencies receive B2's compile.c settings, without unrelated C++ ABI + # or language options. Both languages retain their explicit runtime flags. + cflags += ['/Gy', '/Gw'] if windows else ['-ffunction-sections', '-fdata-sections'] + quote = subprocess.list2cmdline if windows else shlex.join + env = os.environ.copy() + for variable in ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH', 'CPPFLAGS', + 'CFLAGS', 'CXXFLAGS', 'LDFLAGS', 'LD_LIBRARY_PATH', 'CL', '_CL_', + 'OPENSSL_ROOT_DIR', 'OPENSSL_ROOT', 'CMAKE_PREFIX_PATH', + 'CMAKE_TOOLCHAIN_FILE', + 'CMAKE_GENERATOR', 'CC', 'CXX'): + env.pop(variable, None) + env.setdefault('SOURCE_DATE_EPOCH', str(pin['source_date_epoch'])) + started = time.monotonic() + with tempfile.TemporaryDirectory(prefix='webcpp-libdatachannel-') as temporary: + scratch = Path(temporary) + stage_source(source, scratch / 'source', pin) + # Upstream's macOS workaround constructs ROOT/lib paths. Supply an + # isolated prefix with exactly the already-verified B2 provider bytes. + ssl_prefix = scratch / 'openssl' + (ssl_prefix / 'lib').mkdir(parents=True) + shutil.copytree(openssl / 'include', ssl_prefix / 'include') + names = ('libssl.lib', 'libcrypto.lib') if windows else ('libssl.a', 'libcrypto.a') + for name in names: + shutil.copyfile(openssl / name, ssl_prefix / 'lib' / name) + configuration = 'Debug' if args.variant == 'debug' else 'Release' + generator = 'NMake Makefiles' if windows else 'Unix Makefiles' + command = ['cmake', '-S', str(scratch / 'source'), '-B', str(scratch / 'build'), + '-G', generator, '-DCMAKE_C_COMPILER=' + str(cc), + '-DCMAKE_CXX_COMPILER=' + str(cxx), + '-DCMAKE_BUILD_TYPE=' + configuration, + '-DCMAKE_C_FLAGS=' + quote(cflags), '-DCMAKE_CXX_FLAGS=' + quote(flags), + '-DCMAKE_C_FLAGS_DEBUG=', '-DCMAKE_CXX_FLAGS_DEBUG=', + '-DCMAKE_C_FLAGS_RELEASE=', '-DCMAKE_CXX_FLAGS_RELEASE=', + '-DCMAKE_POLICY_DEFAULT_CMP0091=NEW', '-DCMAKE_MSVC_RUNTIME_LIBRARY=', + '-DCMAKE_POLICY_VERSION_MINIMUM=3.5', + '-DBUILD_SHARED_LIBS=OFF', '-DBUILD_SHARED_DEPS_LIBS=OFF', + '-DPREFER_SYSTEM_LIB=OFF', '-DUSE_SYSTEM_SRTP=OFF', + '-DUSE_SYSTEM_JUICE=OFF', '-DUSE_SYSTEM_USRSCTP=OFF', '-DUSE_SYSTEM_PLOG=OFF', + '-DUSE_GNUTLS=OFF', '-DUSE_MBEDTLS=OFF', '-DUSE_NICE=OFF', + '-DNO_WEBSOCKET=ON', '-DNO_EXAMPLES=ON', '-DNO_TESTS=ON', '-DNO_MEDIA=OFF', + '-DOPENSSL_USE_STATIC_LIBS=TRUE', '-DOPENSSL_ROOT_DIR=' + str(ssl_prefix), + '-DOPENSSL_INCLUDE_DIR=' + str(ssl_prefix / 'include'), + '-DOPENSSL_SSL_LIBRARY=' + str(ssl_prefix / 'lib' / names[0]), + '-DOPENSSL_CRYPTO_LIBRARY=' + str(ssl_prefix / 'lib' / names[1]), + '-DCMAKE_INSTALL_PREFIX=' + str(scratch / 'install'), + '-DCMAKE_INSTALL_LIBDIR=lib'] + if windows and any(flag.lower() == '/zi' for flag in flags): + command += ['-DCMAKE_PROJECT_libdatachannel_INCLUDE=' + str(HERE / 'msvc.cmake'), + '-DWEBCPP_SYMBOL_DIRECTORY=' + str(output)] + run(command, scratch, env, output / 'configure.log') + run(['cmake', '--build', str(scratch / 'build'), '--target', 'datachannel', + '--parallel', str(min(4, os.cpu_count() or 1))], scratch, env, output / 'build.log') + # Each static archive remains separate. OpenSSL is never inserted in + # these archives, so B2 gives the final link one ssl/crypto pair. + archives = {} + for library in ('datachannel', 'juice', 'usrsctp', 'srtp2'): + name = library + '.lib' if windows else 'lib' + library + '.a' + matches = list((scratch / 'build').rglob(name)) + if len(matches) != 1: + raise RuntimeError(f'expected one built {name}, found {matches}') + archives[name] = matches[0] + shutil.copytree(scratch / 'source/include/rtc', output / 'include/rtc', + dirs_exist_ok=True, copy_function=shutil.copyfile) + for name, archive in archives.items(): + shutil.copyfile(archive, output / (name + '.new')) + (output / (name + '.new')).replace(output / name) + record = {'pin': pin, 'platform': args.platform, 'variant': args.variant, + 'compiler': str(cxx), 'flags': flags, 'c_flags': cflags, 'openssl': str(openssl), + 'openssl_sha256': ssl['sha256'], 'seconds': time.monotonic() - started, + 'sha256': {name: hashlib.sha256((output / name).read_bytes()).hexdigest() + for name in archives}} + (output / 'build.json').write_text(json.dumps(record, indent=2) + '\n') + print(f'libdatachannel {pin["version"]}: static provider built in ' + f'{record["seconds"]:.1f}s', flush=True) + + +def main() -> None: + arguments = sys.argv[1:] + if len(arguments) == 1: + arguments = shlex.split(Path(arguments[0]).read_text()) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--openssl', type=Path, required=True) + parser.add_argument('--platform', choices=('darwin', 'linux', 'windows'), required=True) + parser.add_argument('--cxx', required=True) + parser.add_argument('--variant', required=True) + parser.add_argument('flags', nargs=argparse.REMAINDER) + build(parser.parse_args(arguments)) + + +if __name__ == '__main__': + try: + main() + except (RuntimeError, subprocess.SubprocessError, OSError, KeyError, ValueError) as error: + sys.exit(f'libdatachannel build: {error}') diff --git a/tools/libdatachannel/build_test.py b/tools/libdatachannel/build_test.py new file mode 100644 index 00000000..5acb54e8 --- /dev/null +++ b/tools/libdatachannel/build_test.py @@ -0,0 +1,38 @@ +#!/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) +"""Check the native dependency build's persistent symbol boundary through CMake.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + + +class BuildTest(unittest.TestCase): + def test_each_static_library_keeps_its_own_compiler_database(self) -> None: + with tempfile.TemporaryDirectory(prefix='libdatachannel symbols ') as directory: + root = Path(directory) + script = Path(__file__).with_name('msvc.cmake').resolve() + (root / 'source.c').write_text('int symbol_fixture(void) { return 42; }\n') + (root / 'CMakeLists.txt').write_text( + 'cmake_minimum_required(VERSION 3.21)\nproject(libdatachannel LANGUAGES C)\n' + 'foreach(library IN ITEMS datachannel juice usrsctp srtp2)\n' + ' add_library(${library} STATIC source.c)\n' + ' file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/${library}.txt"\n' + ' CONTENT "$\\n' + '$\\n")\n' + 'endforeach()\n') + subprocess.run(['cmake', '-S', str(root), '-B', str(root / 'build'), + '-DCMAKE_PROJECT_libdatachannel_INCLUDE=' + str(script), + '-DWEBCPP_SYMBOL_DIRECTORY=' + str(root / 'persistent symbols')], + check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + for library in ('datachannel', 'juice', 'usrsctp', 'srtp2'): + self.assertEqual((root / 'build' / (library + '.txt')).read_text().splitlines(), + ['webcpp-' + library, str(root / 'persistent symbols')]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/libdatachannel/msvc.cmake b/tools/libdatachannel/msvc.cmake new file mode 100644 index 00000000..f4be3b51 --- /dev/null +++ b/tools/libdatachannel/msvc.cmake @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# This external project hook leaves every upstream CMake input unchanged. +# Preserve /Zi databases outside the disposable build tree. Give each +# dependency a separate file so concurrent compilers cannot overwrite it. +function(webcpp_libdatachannel_symbols) + foreach(library IN ITEMS datachannel juice usrsctp srtp2) + set_target_properties(${library} PROPERTIES + COMPILE_PDB_NAME "webcpp-${library}" + COMPILE_PDB_OUTPUT_DIRECTORY "${WEBCPP_SYMBOL_DIRECTORY}") + endforeach() +endfunction() +cmake_language(DEFER CALL webcpp_libdatachannel_symbols) diff --git a/tools/libdatachannel/pin.json b/tools/libdatachannel/pin.json new file mode 100644 index 00000000..5b0d8725 --- /dev/null +++ b/tools/libdatachannel/pin.json @@ -0,0 +1,94 @@ +{ + "version": "0.24.6", + "repository": "https://github.com/paullouisageneau/libdatachannel.git", + "commit": "6b1e2e620f1e37f0eafeee702eaea0043cb305fd", + "required_submodules": { + "deps/libjuice": "b89c792e3612faf2f12cf35bcc56857313a06be3", + "deps/libsrtp": "24b3bf8f19b6f5ab4cd2bcceb4f4064efca86fd5", + "deps/plog": "94899e0b926ac1b0f4750bfbd495167b4a6ae9ef", + "deps/usrsctp": "fec583d54493f879d2ae44a743423bf8a04371ab" + }, + "source_sha256": "2a05e1d2cdde412d65d733461c93d5c03bbb80c8788581bfd06c9a205fa2b7b2", + "source_date_epoch": 1790460966, + "omitted_submodules": { + "deps/json": "55f93686c01528224f448c19128836e7df245f72" + }, + "executable_files": [ + "deps/libsrtp/config.guess", + "deps/libsrtp/config.sub", + "deps/libsrtp/configure", + "deps/libsrtp/format.sh", + "deps/libsrtp/install-sh", + "deps/libsrtp/test/rtpw_test.sh", + "deps/libsrtp/test/rtpw_test_gcm.sh", + "deps/libsrtp/update.sh", + "deps/usrsctp/bootstrap", + "deps/usrsctp/fuzzer/build-fuzzer.sh", + "deps/usrsctp/fuzzer/check-input.sh", + "deps/usrsctp/fuzzer/crashtest.py", + "deps/usrsctp/fuzzer/fuzzer_connect_multi.sh", + "deps/usrsctp/fuzzer/fuzzer_listen.sh", + "deps/usrsctp/usrsctplib/netinet/sctp.h", + "deps/usrsctp/usrsctplib/netinet/sctp_asconf.c", + "deps/usrsctp/usrsctplib/netinet/sctp_asconf.h", + "deps/usrsctp/usrsctplib/netinet/sctp_auth.c", + "deps/usrsctp/usrsctplib/netinet/sctp_auth.h", + "deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.c", + "deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.h", + "deps/usrsctp/usrsctplib/netinet/sctp_callout.c", + "deps/usrsctp/usrsctplib/netinet/sctp_callout.h", + "deps/usrsctp/usrsctplib/netinet/sctp_cc_functions.c", + "deps/usrsctp/usrsctplib/netinet/sctp_constants.h", + "deps/usrsctp/usrsctplib/netinet/sctp_crc32.c", + "deps/usrsctp/usrsctplib/netinet/sctp_crc32.h", + "deps/usrsctp/usrsctplib/netinet/sctp_header.h", + "deps/usrsctp/usrsctplib/netinet/sctp_indata.c", + "deps/usrsctp/usrsctplib/netinet/sctp_indata.h", + "deps/usrsctp/usrsctplib/netinet/sctp_input.c", + "deps/usrsctp/usrsctplib/netinet/sctp_input.h", + "deps/usrsctp/usrsctplib/netinet/sctp_lock_userspace.h", + "deps/usrsctp/usrsctplib/netinet/sctp_os.h", + "deps/usrsctp/usrsctplib/netinet/sctp_os_userspace.h", + "deps/usrsctp/usrsctplib/netinet/sctp_output.c", + "deps/usrsctp/usrsctplib/netinet/sctp_output.h", + "deps/usrsctp/usrsctplib/netinet/sctp_pcb.c", + "deps/usrsctp/usrsctplib/netinet/sctp_pcb.h", + "deps/usrsctp/usrsctplib/netinet/sctp_peeloff.c", + "deps/usrsctp/usrsctplib/netinet/sctp_peeloff.h", + "deps/usrsctp/usrsctplib/netinet/sctp_process_lock.h", + "deps/usrsctp/usrsctplib/netinet/sctp_sha1.c", + "deps/usrsctp/usrsctplib/netinet/sctp_sha1.h", + "deps/usrsctp/usrsctplib/netinet/sctp_ss_functions.c", + "deps/usrsctp/usrsctplib/netinet/sctp_structs.h", + "deps/usrsctp/usrsctplib/netinet/sctp_sysctl.c", + "deps/usrsctp/usrsctplib/netinet/sctp_sysctl.h", + "deps/usrsctp/usrsctplib/netinet/sctp_timer.c", + "deps/usrsctp/usrsctplib/netinet/sctp_timer.h", + "deps/usrsctp/usrsctplib/netinet/sctp_uio.h", + "deps/usrsctp/usrsctplib/netinet/sctp_userspace.c", + "deps/usrsctp/usrsctplib/netinet/sctp_usrreq.c", + "deps/usrsctp/usrsctplib/netinet/sctp_var.h", + "deps/usrsctp/usrsctplib/netinet/sctputil.c", + "deps/usrsctp/usrsctplib/netinet/sctputil.h", + "deps/usrsctp/usrsctplib/netinet6/sctp6_var.h", + "deps/usrsctp/usrsctplib/user_atomic.h", + "deps/usrsctp/usrsctplib/user_environment.c", + "deps/usrsctp/usrsctplib/user_environment.h", + "deps/usrsctp/usrsctplib/user_inpcb.h", + "deps/usrsctp/usrsctplib/user_ip6_var.h", + "deps/usrsctp/usrsctplib/user_ip_icmp.h", + "deps/usrsctp/usrsctplib/user_malloc.h", + "deps/usrsctp/usrsctplib/user_mbuf.c", + "deps/usrsctp/usrsctplib/user_mbuf.h", + "deps/usrsctp/usrsctplib/user_queue.h", + "deps/usrsctp/usrsctplib/user_recv_thread.c", + "deps/usrsctp/usrsctplib/user_recv_thread.h", + "deps/usrsctp/usrsctplib/user_route.h", + "deps/usrsctp/usrsctplib/user_socket.c", + "deps/usrsctp/usrsctplib/user_socketvar.h", + "deps/usrsctp/usrsctplib/user_uma.h", + "examples/signaling-server-python/signaling-server.py", + "examples/streamer/samples/generate_h264.py", + "examples/streamer/samples/generate_opus.py" + ] +} diff --git a/tools/libdatachannel/source.py b/tools/libdatachannel/source.py new file mode 100644 index 00000000..4abd7d64 --- /dev/null +++ b/tools/libdatachannel/source.py @@ -0,0 +1,104 @@ +# 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) +"""Verify the exact distributable libdatachannel source tree before running upstream code. + +The source digest covers sorted (POSIX path, Git file mode, content SHA-256) +records encoded as compact ASCII JSON. The required pinned nested source trees +are included. Dot paths and explicitly omitted unused dependencies match +tools/release/release.py distributions. +Only this verified tree enters CMake, for checkouts and source archives alike. +""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import shutil +import stat +import subprocess +import sys + + +def inventory_digest(records: list[tuple[str, str, str]]) -> str: + """Hash paths, file types, executable bits and bytes without trusting timestamps.""" + data = json.dumps(sorted(records), ensure_ascii=True, separators=(',', ':')).encode('ascii') + return hashlib.sha256(b'webcpp-libdatachannel-source-v1\0' + data).hexdigest() + + +def check_checkout(source: Path, pin: dict) -> None: + """Keep Git pin and clean-tree checks only for a source checkout of its own.""" + if not os.path.lexists(source / '.git'): + return + top = subprocess.check_output(['git', '-C', str(source), 'rev-parse', '--show-toplevel'], + text=True).strip() + revision = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], + text=True).strip() + if Path(top).resolve() != source or revision != pin['commit']: + raise RuntimeError('libdatachannel checkout differs from tools/libdatachannel/pin.json; ' + 'update the submodule') + subprocess.run(['git', '-C', str(source), 'diff', '--exit-code', 'HEAD', '--'], + check=True, stdout=subprocess.DEVNULL) + for relative, revision in pin.get('required_submodules', {}).items(): + nested = source / relative + if not (nested / '.git').exists(): + raise RuntimeError(f'libdatachannel source dependency is missing: {relative}; ' + 'run git submodule update --init --recursive ' + 'third_party/libs/libdatachannel') + check_checkout(nested, {'commit': revision}) + + +def stage_source(source: Path, destination: Path, pin: dict) -> None: + """Copy distributable inputs, then verify the actual bytes CMake will consume.""" + omitted = pin['omitted_submodules'] + + def excluded(directory: str, names: list[str]) -> set[str]: + relative = Path(directory).relative_to(source) + return {name for name in names if name.startswith('.') or + (relative / name).as_posix() in omitted} + + shutil.copytree(source, destination, symlinks=True, ignore=excluded) + windows = sys.platform == 'win32' + executable = set(pin.get('executable_files', ())) + normalize_eol = set() + if windows and (source / '.git').exists(): + # Git for Windows may check text out as CRLF. Restore only paths Git + # identifies as LF in its index and CRLF in the checkout, then verify + # their canonical bytes against the same digest as every other host. + for prefix in ('', *pin.get('required_submodules', {})): + checkout = source / prefix + entries = subprocess.check_output( + ['git', '-C', str(checkout), 'ls-files', '--eol', '-z']) + for entry in entries.split(b'\0'): + if not entry: + continue + metadata, name = entry.decode('utf-8').split('\t', 1) + if metadata.split()[:2] == ['i/lf', 'w/crlf']: + normalize_eol.add((Path(prefix) / name).as_posix()) + records = [] + for directory, directories, files in os.walk(destination, followlinks=False): + for name in directories + files: + path = Path(directory) / name + mode = path.lstat().st_mode + if stat.S_ISDIR(mode): + continue + if not stat.S_ISREG(mode): + raise RuntimeError('libdatachannel source tree differs from ' + 'tools/libdatachannel/pin.json: ' + f'unsupported file type: {path.relative_to(destination)}') + relative = path.relative_to(destination).as_posix() + data = path.read_bytes() + if relative in normalize_eol: + data = data.replace(b'\r\n', b'\n') + path.write_bytes(data) + # Windows has no POSIX executable bit. The pinned path inventory + # supplies that metadata; paths, file types and bytes still match. + is_executable = relative in executable if windows else bool(mode & 0o111) + records.append((relative, '100755' if is_executable else '100644', + hashlib.sha256(data).hexdigest())) + if inventory_digest(records) != pin['source_sha256']: + raise RuntimeError('libdatachannel source tree differs from tools/libdatachannel/pin.json; ' + 'restore the pinned source checkout or distribution') diff --git a/tools/libdatachannel/source_test.py b/tools/libdatachannel/source_test.py new file mode 100644 index 00000000..cdcaea25 --- /dev/null +++ b/tools/libdatachannel/source_test.py @@ -0,0 +1,151 @@ +#!/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) +"""Exercise committed source pin generation and the verified build staging boundary.""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from source import check_checkout, stage_source +from update import regenerate + + +class SourceTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix='libdatachannel source ') + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name).resolve() + self.source = self.root / 'source' + self.source.mkdir() + self.git('init', '--quiet') + (self.source / 'CMakeLists.txt').write_text('#!/usr/bin/env perl\n') + (self.source / 'CMakeLists.txt').chmod(0o755) + (self.source / 'crypto').mkdir() + (self.source / 'crypto/input.c').write_text('int source_value = 7;\n') + (self.source / '.metadata').write_text('not distributed\n') + self.git('add', '.') + self.git('commit', '--quiet', '-m', 'Create source fixture') + self.nested = self.git('rev-parse', 'HEAD') + self.git('update-index', '--add', '--cacheinfo', '160000', self.nested, 'external') + (self.source / 'external').mkdir() + self.git('commit', '--quiet', '-m', 'Record unused upstream fixture') + self.pin = {'version': 'fixture', 'commit': self.git('rev-parse', 'HEAD'), + 'repository': 'https://example.invalid/source.git', 'required_submodules': {}} + + def git(self, *arguments: str) -> str: + env = {**os.environ, 'GIT_AUTHOR_DATE': '1700000000 +0000', + 'GIT_COMMITTER_DATE': '1700000000 +0000'} + result = subprocess.run( + ['git', '-C', str(self.source), '-c', 'user.name=Source test', + '-c', 'user.email=source@example.invalid', '-c', 'commit.gpgsign=false', + *arguments], env=env, check=True, capture_output=True, text=True) + return result.stdout.strip() + + def test_generator_is_repeatable_and_uses_committed_metadata(self) -> None: + manifest = self.root / 'pin.json' + manifest.write_text(json.dumps(self.pin)) + command = [sys.executable, str(Path(__file__).with_name('update.py')), + '--source', str(self.source), '--pin', str(manifest)] + subprocess.run(command, check=True, capture_output=True) + original = manifest.read_bytes() + pin = json.loads(original) + self.assertEqual(pin['source_date_epoch'], 1700000000) + self.assertEqual(pin['omitted_submodules'], {'external': self.nested}) + # Untracked bytes cannot enter a generated pin, even if Git ignores them. + (self.source / 'extra.c').write_text('int untracked;\n') + subprocess.run(command, check=True, capture_output=True) + self.assertEqual(manifest.read_bytes(), original) + with self.assertRaisesRegex(RuntimeError, 'source tree differs'): + stage_source(self.source, self.root / 'rejected', pin) + + def test_staging_omits_hidden_and_unused_nested_inputs(self) -> None: + pin = regenerate(self.source, self.pin) + (self.source / 'external/untrusted.c').write_text('not a build input\n') + (self.source / '.untracked').write_text('not a build input\n') + destination = self.root / 'staged' + stage_source(self.source, destination, pin) + self.assertEqual(sorted(path.relative_to(destination).as_posix() + for path in destination.rglob('*') if path.is_file()), + ['CMakeLists.txt', 'crypto/input.c']) + self.assertEqual((destination / 'CMakeLists.txt').read_bytes(), b'#!/usr/bin/env perl\n') + self.assertEqual((destination / 'CMakeLists.txt').stat().st_mode & 0o777, 0o755) + + def test_checkout_and_generator_reject_mismatched_revision(self) -> None: + self.pin['commit'] = '0' * 40 + for validate in (check_checkout, regenerate): + with self.assertRaisesRegex(RuntimeError, 'checkout differs'): + validate(self.source, self.pin) + + def test_windows_staging_verifies_bytes_without_executable_file_modes(self) -> None: + pin = regenerate(self.source, self.pin) + (self.source / 'CMakeLists.txt').chmod(0o644) + with patch('source.sys.platform', 'win32'): + stage_source(self.source, self.root / 'windows', pin) + (self.source / 'crypto/input.c').write_text('int tampered;\n') + with self.assertRaisesRegex(RuntimeError, 'source tree differs'): + stage_source(self.source, self.root / 'tampered', pin) + + def test_windows_staging_normalizes_git_checkout_line_endings(self) -> None: + pin = regenerate(self.source, self.pin) + self.git('config', 'core.autocrlf', 'true') + (self.source / 'CMakeLists.txt').write_bytes(b'#!/usr/bin/env perl\r\n') + with patch('source.sys.platform', 'win32'): + stage_source(self.source, self.root / 'windows', pin) + self.assertEqual((self.root / 'windows/CMakeLists.txt').read_bytes(), + b'#!/usr/bin/env perl\n') + + def test_checkout_and_generator_reject_dirty_tracked_sources(self) -> None: + (self.source / 'crypto/input.c').write_text('int changed;\n') + for validate in (check_checkout, regenerate): + with self.assertRaises(subprocess.CalledProcessError): + validate(self.source, self.pin) + + def test_generator_requires_a_source_checkout_of_its_own(self) -> None: + pin = regenerate(self.source, self.pin) + stage_source(self.source, self.root / 'archive', pin) + with self.assertRaisesRegex(RuntimeError, 'requires its Git checkout'): + regenerate(self.root / 'archive', pin) + + def test_required_nested_sources_are_verified_in_checkouts_and_archives(self) -> None: + nested = self.source / 'deps/required' + nested.mkdir(parents=True) + subprocess.run(['git', '-C', str(nested), 'init', '--quiet'], check=True) + (nested / 'input.c').write_text('int nested_source = 42;\n') + subprocess.run(['git', '-C', str(nested), 'add', '.'], check=True) + subprocess.run(['git', '-C', str(nested), '-c', 'user.name=Source test', + '-c', 'user.email=source@example.invalid', '-c', 'commit.gpgsign=false', + 'commit', '--quiet', '-m', 'Create required source fixture'], check=True) + revision = subprocess.check_output(['git', '-C', str(nested), 'rev-parse', 'HEAD'], + text=True).strip() + self.git('update-index', '--add', '--cacheinfo', '160000', revision, 'deps/required') + self.git('commit', '--quiet', '-m', 'Record required nested source') + self.pin.update(commit=self.git('rev-parse', 'HEAD'), + required_submodules={'deps/required': revision}) + pin = regenerate(self.source, self.pin) + archive = self.root / 'archive' + stage_source(self.source, archive, pin) + self.assertEqual((archive / 'deps/required/input.c').read_text(), + 'int nested_source = 42;\n') + self.assertFalse((archive / 'deps/required/.git').exists()) + check_checkout(archive, pin) + stage_source(archive, self.root / 'from-archive', pin) + (archive / 'deps/required/input.c').write_text('int tampered;\n') + with self.assertRaisesRegex(RuntimeError, 'source tree differs'): + stage_source(archive, self.root / 'rejected-archive', pin) + pin['required_submodules']['deps/required'] = '0' * 40 + with self.assertRaisesRegex(RuntimeError, 'checkout differs'): + check_checkout(self.source, pin) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/libdatachannel/update.py b/tools/libdatachannel/update.py new file mode 100644 index 00000000..ff410f5d --- /dev/null +++ b/tools/libdatachannel/update.py @@ -0,0 +1,86 @@ +#!/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) +"""Regenerate source integrity metadata from the commit already named in pin.json. + +Run python3 tools/libdatachannel/update.py after explicitly updating the libdatachannel pin. +Read committed Git objects, never working-tree bytes or downloaded artifacts. +""" +from __future__ import annotations + +import argparse +import hashlib +import io +import json +from pathlib import Path +import subprocess + +from source import check_checkout, inventory_digest + +HERE = Path(__file__).resolve().parent + + +def regenerate(source: Path, pin: dict) -> dict: + """Derive the distribution inventory and timestamp from the exact pinned commit.""" + if not (source / '.git').exists(): + raise RuntimeError('regenerating the libdatachannel pin requires its Git checkout') + check_checkout(source, pin) + records, executable, omitted = [], [], {} + for prefix, revision in [('', pin['commit']), *pin['required_submodules'].items()]: + checkout = source / prefix + tree = subprocess.check_output(['git', '-C', str(checkout), 'ls-tree', '-r', '-z', + revision]) + files = [] + for entry in tree.split(b'\0'): + if not entry: + continue + metadata, name = entry.decode('utf-8').split('\t', 1) + mode, kind, oid = metadata.split() + relative = (Path(prefix) / name).as_posix() + if any(part.startswith('.') for part in Path(relative).parts): + continue + if mode == '160000': + required = pin['required_submodules'].get(relative) + if required is None: + omitted[relative] = oid + elif required != oid: + raise RuntimeError(f'libdatachannel nested pin differs: {relative}') + elif kind == 'blob' and mode in ('100644', '100755'): + files.append((relative, mode, oid)) + else: + raise RuntimeError(f'unsupported libdatachannel source entry: {relative} ({mode})') + objects = subprocess.run(['git', '-C', str(checkout), 'cat-file', '--batch'], + input=''.join(oid + '\n' for _, _, oid in files).encode('ascii'), + stdout=subprocess.PIPE, check=True) + stream = io.BytesIO(objects.stdout) + for name, mode, oid in files: + actual, kind, size = stream.readline().decode('ascii').split() + data = stream.read(int(size)) + if actual != oid or kind != 'blob' or stream.read(1) != b'\n': + raise RuntimeError(f'invalid Git object for {name}') + records.append((name, mode, hashlib.sha256(data).hexdigest())) + if mode == '100755': + executable.append(name) + timestamp = subprocess.check_output( + ['git', '-C', str(source), 'show', '-s', '--format=%ct', pin['commit']], text=True) + return {**pin, 'source_sha256': inventory_digest(records), + 'source_date_epoch': int(timestamp.strip()), 'omitted_submodules': omitted, + 'executable_files': sorted(executable)} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, + default=HERE.parents[1] / 'third_party/libs/libdatachannel') + parser.add_argument('--pin', type=Path, default=HERE / 'pin.json') + args = parser.parse_args() + pin = regenerate(args.source.resolve(), json.loads(args.pin.read_text())) + args.pin.write_text(json.dumps(pin, indent=2) + '\n') + print(f'libdatachannel {pin["version"]}: {pin["source_sha256"]}') + + +if __name__ == '__main__': + main() diff --git a/tools/openssl/build.py b/tools/openssl/build.py index 46796fa3..93b13083 100644 --- a/tools/openssl/build.py +++ b/tools/openssl/build.py @@ -18,6 +18,7 @@ import json import os from pathlib import Path +import re import shlex import shutil import subprocess @@ -96,6 +97,21 @@ def windows_perl(env: dict[str, str]) -> str: 'on PATH; a Git Bash or MSYS Perl cannot generate nmake files') +def suite_result(log: str, recipes: list[str]) -> dict: + """Reject empty or partial TAP runs, retaining upstream's configuration skips.""" + # Upstream runs preparation recipes first, with a separate TAP summary. + # A non-FIPS build legitimately skips that phase with Tests=0. + summaries = list(re.finditer(r'Files=(\d+), Tests=(\d+)', log)) + summary = summaries[-1] if summaries else None + missing = [name for name in recipes if name not in log] + if ('All tests successful.' not in log or not summary or int(summary[2]) == 0 + or not recipes or missing): + raise RuntimeError('upstream suite did not report a complete passing run; ' + f'missing recipes: {missing}') + return {'result': 'passed', 'selection': 'alltests', 'recipes': len(recipes), + 'files': int(summary[1]), 'tests': int(summary[2])} + + def main() -> None: arguments = sys.argv[1:] if len(arguments) == 1: @@ -108,10 +124,17 @@ def main() -> None: parser.add_argument('--cc', required=True) parser.add_argument('--ar', default='') parser.add_argument('--variant', default='release') + parser.add_argument('--test', action='store_true', + help='run the complete native upstream suite before publishing libraries') parser.add_argument('flags', nargs=argparse.REMAINDER) args = parser.parse_args(arguments) + if args.test and args.platform == 'wasi': + raise RuntimeError('the OpenSSL upstream test harness requires native executables; ' + 'WASIp3 uses the separately declared TLS integration tests') source, output = args.source.resolve(), args.output.resolve() output.mkdir(parents=True, exist_ok=True) + for name in ('build.json', 'upstream-tests.json'): + (output / name).unlink(missing_ok=True) pin = json.loads((HERE / 'pin.json').read_text()) check_checkout(source, pin) # Verify the source before probing or invoking any configured build tool. @@ -137,10 +160,17 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat env = os.environ.copy() for variable in ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH', 'CPPFLAGS', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS', 'LD_LIBRARY_PATH', - 'OPENSSL_CONF', 'OPENSSL_MODULES', 'CROSS_COMPILE', 'CL', '_CL_'): + 'OPENSSL_CONF', 'OPENSSL_MODULES', 'CROSS_COMPILE', 'CL', '_CL_', + 'MAKEFLAGS', 'MFLAGS', 'TESTS', 'EXE_SHELL', 'TOP', 'SRCTOP', 'BLDTOP', + 'BIN_D', 'TEST_D', 'RESULT_D', 'STOPTEST', 'FIPS_MODE'): env.pop(variable, None) + for variable in list(env): + if variable.startswith(('HARNESS_', 'OPENSSL_TEST_')): + env.pop(variable) env.setdefault('SOURCE_DATE_EPOCH', str(pin['source_date_epoch'])) - options = ['no-shared', 'no-tests', 'no-apps', 'no-docs', 'no-module', + # Native ordinary and tested builds use the same library configuration. + # Only the opt-in action builds the upstream apps and test executables. + options = ['no-shared', 'no-docs', 'no-module', '--libdir=lib', 'threads' if args.threading == 'multi' else 'no-threads'] # MSVC's /MDd and /MTd define _DEBUG themselves. Upstream --debug would # force it even when the user explicitly selects runtime-debugging=off. @@ -149,6 +179,7 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat if not windows: options += ['--openssldir=/etc/ssl'] if args.platform == 'wasi': + options += ['no-tests', 'no-apps'] if '--target=wasm32-wasip3' not in flags: raise RuntimeError('WASIp3 OpenSSL requires --target=wasm32-wasip3 ' 'in the configured C flags') @@ -224,12 +255,23 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat run([perl, str(scratch / 'source/Configure'), *actual_target, *options, '--prefix=' + str(install)], cwd=build, env=env, log=output / 'configure.log') make = ['nmake', '/nologo'] if windows else ['make'] - jobs = [] if windows else ['-j' + str(min(8, os.cpu_count() or 1))] + jobs = [] if windows else ['-j2'] # nmake builds one translation unit at a time. Windows CI exceeded ten # minutes while still compiling normally; retain a bounded thirty-minute # budget for this phase. Parallel Make retains the shorter budget. run([*make, *jobs, 'build_libs'], cwd=build, env=env, log=output / 'build.log', timeout=1800 if windows else 600) + suite = None + if args.test: + env['HARNESS_JOBS'] = '2' + run([*make, *jobs, 'test', 'TESTS=alltests'], cwd=build, env=env, + log=output / 'upstream-tests.log', timeout=2400) + log = (output / 'upstream-tests.log').read_text(errors='replace') + recipes = sorted(path.name for path in (scratch / 'source/test/recipes').glob('*.t')) + try: + suite = suite_result(log, recipes) + except RuntimeError as error: + raise RuntimeError(f'{error}; full log: {output / "upstream-tests.log"}') from error if windows: # Upstream install_dev requires an external PDB even with B2's /Z7 # embedded symbols or debug-symbols=off. Stage exactly its public and @@ -261,6 +303,11 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat record['sha256'] = {name: hashlib.sha256((output / name).read_bytes()).hexdigest() for name in names} (output / 'build.json').write_text(json.dumps(record, indent=2) + '\n') + if suite: + suite.update(pin=pin['commit'], configure=record['configure'], sha256=record['sha256']) + (output / 'upstream-tests.json').write_text(json.dumps(suite, indent=2) + '\n') + print(f'OpenSSL upstream suite passed: {suite["files"]} recipes, ' + f'{suite["tests"]} tests', flush=True) print(f'OpenSSL {pin["version"]}: {args.platform}/{args.threading} built from source ' f'in {record["seconds"]:.1f}s', flush=True) diff --git a/tools/openssl/build_test.py b/tools/openssl/build_test.py index 38e14b69..a9bb4805 100644 --- a/tools/openssl/build_test.py +++ b/tools/openssl/build_test.py @@ -21,6 +21,25 @@ from source import inventory_digest +class UpstreamResultsTest(unittest.TestCase): + def test_skipped_preparation_does_not_hide_the_full_suite_summary(self) -> None: + log = ('00-prep_fipsmodule_cnf.t .. skipped: FIPS is disabled\n' + 'Files=1, Tests=0, 0 wallclock secs\nResult: NOTESTS\n' + '01-test_sanity.t .. ok\n02-test_errstr.t .. ok\n' + 'All tests successful.\nFiles=2, Tests=21, 1 wallclock secs\nResult: PASS\n') + proof = build.suite_result(log, ['00-prep_fipsmodule_cnf.t', '01-test_sanity.t', + '02-test_errstr.t']) + self.assertEqual(proof['files'], 2) + self.assertEqual(proof['tests'], 21) + self.assertEqual(proof['recipes'], 3) + + def test_a_successful_subset_is_not_a_successful_suite(self) -> None: + log = ('01-test_sanity.t .. ok\nAll tests successful.\n' + 'Files=1, Tests=6, 1 wallclock secs\nResult: PASS\n') + with self.assertRaisesRegex(RuntimeError, 'missing recipes.*02-test_errstr.t'): + build.suite_result(log, ['01-test_sanity.t', '02-test_errstr.t']) + + class WindowsBuildTest(unittest.TestCase): def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory(prefix='openssl windows ') @@ -104,6 +123,34 @@ def test_a_stalled_command_keeps_its_diagnostic_log(self) -> None: cwd=self.root, env=os.environ.copy(), log=log, timeout=2) self.assertEqual(log.read_text(), 'last compiler output\n') + def test_windows_suite_failure_does_not_publish_libraries(self) -> None: + output = self.root / 'failed-suite' + + def command(command: list[str], *, cwd: Path, env: dict, log: Path, + timeout: float = 600) -> None: + log.write_text('completed\n') + if command[-1] == 'build_libs': + (cwd / 'include/openssl').mkdir(parents=True) + (cwd / 'include/openssl/configuration.h').write_text('matching headers\n') + (cwd / 'libssl.lib').write_bytes(b'ssl') + (cwd / 'libcrypto.lib').write_bytes(b'crypto') + if 'test' in command: + self.assertEqual(command, ['nmake', '/nologo', 'test', 'TESTS=alltests']) + self.assertEqual(env['HARNESS_JOBS'], '2') + raise RuntimeError('upstream Windows test failed') + + args = ['build.py', '--source', str(self.source), '--output', str(output), + '--platform', 'windows', '--threading', 'multi', '--cc', str(self.compiler), + '--test'] + with patch.object(build, 'HERE', self.root), patch.object(sys, 'argv', args), \ + patch.object(build, 'run', side_effect=command), \ + patch.object(build, 'windows_target', return_value='VC-WIN64A'), \ + patch.object(build, 'windows_perl', return_value='native-perl.exe'): + with self.assertRaisesRegex(RuntimeError, 'upstream Windows test failed'): + build.main() + for name in ('libssl.lib', 'libcrypto.lib', 'build.json', 'upstream-tests.json'): + self.assertFalse((output / name).exists(), name) + def test_windows_target_uses_the_configured_compilers_architecture(self) -> None: for output, target in (('WEBCPP_OPENSSL_X86', 'VC-WIN32'), ('WEBCPP_OPENSSL_X64', 'VC-WIN64A'), diff --git a/tools/openssl/test/Jamfile b/tools/openssl/test/Jamfile index e8beef8e..f4c13340 100644 --- a/tools/openssl/test/Jamfile +++ b/tools/openssl/test/Jamfile @@ -11,9 +11,8 @@ exe entropy : entropy.c /webcpp/third_party//openssl exe threads : threads.cpp /webcpp/third_party//openssl : multi ; explicit tls_client entropy threads ; -exe tls_client_embedded : tls_client.cpp /webcpp/asio//tls - : WEBCPP_TEST_EMBEDDED_CA - off:/webcpp//throw_exception ; +exe tls_client_embedded : tls_client_embedded.cpp /webcpp/asio//tls + : off:/webcpp//throw_exception ; explicit tls_client_embedded ; exe cobalt_tls_client : cobalt_tls_client.cpp /webcpp/asio//cobalt /webcpp/asio//tls @@ -33,3 +32,9 @@ exe cobalt_ssl_cancel : cobalt_ssl_cancel.cpp /webcpp/asio//cobalt_ssl : ../../node-test/include off:/webcpp//throw_exception ; explicit cobalt_ssl_cancel ; + +# The native WebRTC backend needs worker threads and exceptions. +exe combined_provider : combined_provider.cpp /webcpp/asio//asio /webcpp/asio//openssl + /webcpp/beast//beast /webcpp/trystero//native + : multi on ; +explicit combined_provider ; diff --git a/tools/openssl/test/combined_provider.cpp b/tools/openssl/test/combined_provider.cpp new file mode 100644 index 00000000..5323e2d2 --- /dev/null +++ b/tools/openssl/test/combined_provider.cpp @@ -0,0 +1,33 @@ +// 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) + +#include +#include +#include + +#include +#include + +#include + +int main() { + if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) { + std::fprintf(stderr, "OpenSSL headers and implementation differ: %s / %s\n", + OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION)); + return 1; + } + boost::asio::io_context context; + boost::asio::ssl::context tls(boost::asio::ssl::context::tls_client); + boost::beast::tcp_stream stream(context); + webcpp::trystero::native::backend backend(context.get_executor()); + rtc::PeerConnection peer(rtc::Configuration{}); + auto channel = peer.createDataChannel("combined-provider"); + peer.close(); + if (!channel || !tls.native_handle()) { + return 2; + } + std::puts("Asio, Beast and Trystero share the pinned OpenSSL provider"); +} diff --git a/tools/openssl/test/tls_client_embedded.cpp b/tools/openssl/test/tls_client_embedded.cpp new file mode 100644 index 00000000..1ecdc994 --- /dev/null +++ b/tools/openssl/test/tls_client_embedded.cpp @@ -0,0 +1,10 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Keep a distinct translation unit so a joint B2 build cannot reuse the +// filesystem-CA client's object for the client that accepts certificate bytes. +#define WEBCPP_TEST_EMBEDDED_CA +#include "tls_client.cpp" diff --git a/tools/release/release.py b/tools/release/release.py index 553c7b3a..5b788fec 100755 --- a/tools/release/release.py +++ b/tools/release/release.py @@ -823,11 +823,40 @@ def repositories(root: Path, names: list[str]) -> list[tuple[str, Path]]: def source_submodules(root: Path) -> dict[str, str]: - """Supported root source submodules and their pinned commits: site and direct dependencies - under third_party/libs. Other gitlinks must be refused, never silently omitted.""" + """Recorded source dependencies, including explicitly pinned required nested sources.""" recorded = blobs(root, 'site', 'third_party/libs/')[1] - return {path: commit for path, commit in recorded.items() if not hidden(path) and - (path == 'site' or PurePosixPath(path).parent == PurePosixPath('third_party/libs'))} + sources = {path: commit for path, commit in recorded.items() if not hidden(path) and + (path == 'site' or PurePosixPath(path).parent == PurePosixPath('third_party/libs'))} + required = nested_source_policy(root, sources, 'libdatachannel', 'required_submodules') + sources.update({f'third_party/libs/libdatachannel/{path}': commit + for path, commit in required.items()}) + return sources + + +def nested_source_policy(root: Path, sources: dict[str, str], library: str, + field: str) -> dict[str, str]: + """Read a reviewed dependency policy only when its enclosing source pin matches.""" + recorded = sources.get(f'third_party/libs/{library}') + if recorded is None: + return {} + relative = f'tools/{library}/pin.json' + try: + pin = json.loads(read(root, relative)) + except json.JSONDecodeError as error: + raise Broken(f'{relative} is not valid JSON: {error}') from error + if not isinstance(pin, dict): + raise Broken(f'{relative} must hold an object') + if pin.get('commit') != recorded: + return {} + dependencies = pin.get(field, {}) + if not isinstance(dependencies, dict) or any( + not isinstance(path, str) or not path or hidden(path) or + PurePosixPath(path).is_absolute() or '..' in PurePosixPath(path).parts or + str(PurePosixPath(path)) != path or not isinstance(commit, str) or + re.fullmatch(r'[0-9a-f]{40}', commit) is None + for path, commit in dependencies.items()): + raise Broken(f'{relative}: {field} must map normalized relative paths to commit hashes') + return dependencies def source_checkout_findings(root: Path, sources: dict[str, str]) -> list[str]: @@ -870,26 +899,8 @@ def link_refusal(path: str, target: bytes) -> str | None: def omitted_openssl_submodules(root: Path, sources: dict[str, str]) -> dict[str, str]: - """The unused upstream gitlinks reviewed for exactly the recorded OpenSSL source pin.""" - recorded = sources.get('third_party/libs/openssl') - if recorded is None: - return {} - relative = 'tools/openssl/pin.json' - try: - pin = json.loads(read(root, relative)) - except json.JSONDecodeError as error: - raise Broken(f'{relative} is not valid JSON: {error}') from error - if not isinstance(pin, dict): - raise Broken(f'{relative} must hold an object') - if pin.get('commit') != recorded: - return {} - omitted = pin.get('omitted_submodules', {}) - if not isinstance(omitted, dict) or any( - not isinstance(path, str) or not isinstance(commit, str) or - re.fullmatch(r'[0-9a-f]{40}', commit) is None - for path, commit in omitted.items()): - raise Broken(f'{relative}: omitted_submodules must map paths to commit hashes') - return omitted + """Unused gitlinks reviewed for exactly the recorded OpenSSL source pin.""" + return nested_source_policy(root, sources, 'openssl', 'omitted_submodules') def repository_refusals(root: Path, names: list[str]) -> list[str]: @@ -900,6 +911,8 @@ def repository_refusals(root: Path, names: list[str]) -> list[str]: refusals = [] sources = source_submodules(root) openssl_omissions = omitted_openssl_submodules(root, sources) + transport_omissions = nested_source_policy( + root, sources, 'libdatachannel', 'omitted_submodules') for base, directory in repositories(root, names): files, submodules = blobs(directory) for path in submodules: @@ -908,6 +921,11 @@ def repository_refusals(root: Path, names: list[str]) -> list[str]: if (not base and path in sources) or base == \ 'third_party/libs/nativejson-benchmark/': continue + if sources.get(base + path) == submodules[path]: + continue + if base == 'third_party/libs/libdatachannel/' and \ + transport_omissions.get(path) == submodules[path]: + continue if base == 'third_party/libs/openssl/' and \ openssl_omissions.get(path) == submodules[path]: continue diff --git a/tools/release/release_test.py b/tools/release/release_test.py index 51d29667..59d4e4b6 100755 --- a/tools/release/release_test.py +++ b/tools/release/release_test.py @@ -28,6 +28,7 @@ import zlib from collections.abc import Callable, Iterator from pathlib import Path +from typing import TypedDict import changelog import release @@ -1370,6 +1371,74 @@ def test_dist_refuses_unreviewed_openssl_nested_dependencies(directory: Path) -> assert f'third_party/libs/openssl/{path} is a submodule' in output, output +class TransportPin(TypedDict): + commit: str + required_submodules: dict[str, str] + omitted_submodules: dict[str, str] + + +def libdatachannel_source_submodule(tree: scratch.Tree) -> tuple[Path, Path, TransportPin]: + """A source-built transport with one required and one unused nested repository.""" + checkout = source_submodule(tree, 'third_party/libs/libdatachannel') + origin = tree.root.parent / 'transport-dependency' + scratch.write(origin / 'LICENSE', 'Nested upstream licence\n') + scratch.write(origin / 'source.c', 'int transport_dependency(void) { return 7; }\n') + scratch.git(origin, 'init', '-q') + scratch.git(origin, 'add', '.') + scratch.git(origin, 'commit', '-q', '-m', 'The required transport dependency') + scratch.git(checkout, 'submodule', 'add', '-q', str(origin), 'deps/libjuice') + revision = scratch.git(origin, 'rev-parse', 'HEAD').strip() + scratch.git(checkout, 'update-index', '--add', '--cacheinfo', + f'160000,{revision},deps/json') + scratch.git(checkout, 'commit', '-q', '-m', 'Pinned transport dependencies') + scratch.git(tree.root, 'add', 'third_party/libs/libdatachannel') + pin: TransportPin = {'commit': scratch.git(checkout, 'rev-parse', 'HEAD').strip(), + 'required_submodules': {'deps/libjuice': revision}, + 'omitted_submodules': {'deps/json': revision}} + tree.commit_file('tools/libdatachannel/pin.json', json.dumps(pin)) + return checkout, checkout / 'deps/libjuice', pin + + +def test_dist_bundles_required_transport_sources(directory: Path) -> None: + tree = scratch.make_tree(directory) + _, nested, _ = libdatachannel_source_submodule(tree) + out = directory / 'out' + completed = dist_cli(tree.root, out) + assert completed.returncode == 0, completed.stdout + completed.stderr + with tarfile.open(out / 'webcpp-0.1.0.tar.gz') as archive: + prefix = 'webcpp-0.1.0/third_party/libs/libdatachannel/deps/' + for name in ('LICENSE', 'source.c'): + assert member_bytes(archive, archive.getmember(prefix + 'libjuice/' + name)) == \ + (nested / name).read_bytes() + assert not any(name.startswith(prefix + 'json/') for name in archive.getnames()) + + +def test_dist_refuses_unverified_transport_dependencies(directory: Path) -> None: + for number, change in enumerate(('missing', 'dirty', 'moved', 'unlisted', 'wrong-pin')): + case = directory / str(number) + case.mkdir() + tree = scratch.make_tree(case) + _, nested, pin = libdatachannel_source_submodule(tree) + if change == 'missing': + shutil.rmtree(nested) + elif change == 'dirty': + scratch.write(nested / 'source.c', 'uncommitted dependency change\n') + elif change == 'moved': + scratch.git(nested, 'commit', '-q', '--allow-empty', '-m', 'Unrecorded change') + else: + if change == 'unlisted': + pin['required_submodules'] = {} + else: + pin['required_submodules'] = {'deps/libjuice': pin['commit']} + tree.commit_file('tools/libdatachannel/pin.json', json.dumps(pin)) + out = case / 'out' + completed = dist_cli(tree.root, out) + assert completed.returncode == 1 and not out.exists(), \ + (change, completed.stdout + completed.stderr) + assert 'libdatachannel/deps/libjuice' in completed.stdout + completed.stderr, \ + (change, completed.stdout + completed.stderr) + + def test_dist_names_source_paths_that_are_not_utf8(directory: Path) -> None: tree = scratch.make_tree(directory) commit = scratch.git(tree.library('alpha'), 'rev-parse', 'HEAD').strip().encode() @@ -1983,6 +2052,8 @@ def test_jamroot_without_config(root: Path) -> None: test_dist_refuses_nested_source_submodules, test_dist_bundles_openssl_without_reviewed_unused_dependencies, test_dist_refuses_unreviewed_openssl_nested_dependencies, + test_dist_bundles_required_transport_sources, + test_dist_refuses_unverified_transport_dependencies, test_dist_names_source_paths_that_are_not_utf8, test_dist_is_reproducible, test_dist_leaves_out_dot_files_and_what_git_does_not_track, diff --git a/tools/test/boost_libraries_test.py b/tools/test/boost_libraries_test.py index 2d15d022..4a3f03c5 100755 --- a/tools/test/boost_libraries_test.py +++ b/tools/test/boost_libraries_test.py @@ -778,6 +778,41 @@ def test_msvc_overlays_win_actual_header_lookup(root: Path) -> None: assert '/external:anglebrackets' not in words, command +def test_boost_cobalt_thread_joins_without_exceptions(root: Path) -> None: + # Omitting thread_promise's exception-disabled hook makes a real coroutine + # fail to compile. Exercise the compiled thread implementation and its executor. + source = r'''#include +#include +#include +#include +#include +#include + +boost::cobalt::thread worker(std::atomic& completed) { + auto executor = co_await boost::cobalt::this_coro::executor; + co_await boost::asio::post(executor, boost::cobalt::use_op); + completed.store(42); +} + +int main() { + std::atomic completed{0}; + auto operation = worker(completed); + operation.join(); + if (completed.load() != 42) return 1; + std::puts("thread coroutine completed and joined"); +} +''' + harness.add_library(root, 'thread_probe', + 'import webcpp ;\nwebcpp.targets native ;\n' + 'webcpp.run thread : thread.cpp : multi ' + '/webcpp//boost_cobalt ;\n', {'thread.cpp': source}) + for exceptions in ('off', 'on'): + result = harness.run_b2(root, '-a', '-j4', '--verbose-test', + f'exception-handling={exceptions}', 'libs/thread_probe/test') + harness.expect(result, True, 'thread coroutine completed and joined') + assert passed(result) == {'thread'}, result.stdout[-4000:] + + def test_boost_cobalt_preserves_exception_setting(root: Path) -> None: # A blanket exception requirement would reject a valid result-based consumer. # Build the real archive and execute eager promises and cancellation in each mode. @@ -855,6 +890,7 @@ def test_boost_context_refuses_unverified_wasm(root: Path) -> None: test_boost_cobalt_names_missing_or_mismatched_sources, test_boost_cobalt_omits_main_and_ssl_from_supplied_sources, test_boost_cobalt_warns_only_for_disabled_exceptions, + test_boost_cobalt_thread_joins_without_exceptions, test_boost_cobalt_preserves_exception_setting, test_asio_windows_allocator_overlay_reaches_sources_and_consumers, test_msvc_overlays_win_actual_header_lookup, diff --git a/tools/test/ca_certificates_b2_test.py b/tools/test/ca_certificates_b2_test.py index 35df665d..a6f0542c 100644 --- a/tools/test/ca_certificates_b2_test.py +++ b/tools/test/ca_certificates_b2_test.py @@ -18,13 +18,13 @@ JAM = '''import webcpp ; webcpp.run roots : roots.cpp : /webcpp/third_party//ca_certificates ; ''' -SOURCE = '''#include +SOURCE = '''#include #include #include int main() { - std::string_view pem = webcpp::detail::ca_certificates::pem; + std::string_view pem = webcpp::asio::detail::ca_certificates::pem; if (!pem.starts_with("-----BEGIN CERTIFICATE-----")) return 1; - std::printf("%zu\\n", webcpp::detail::ca_certificates::count); + std::printf("%zu\\n", webcpp::asio::detail::ca_certificates::count); } ''' diff --git a/tools/test/jamroot_test.py b/tools/test/jamroot_test.py index 70ac7995..e7718fe3 100755 --- a/tools/test/jamroot_test.py +++ b/tools/test/jamroot_test.py @@ -200,7 +200,7 @@ def test_install_copies_headers_to_prefix(root): if path.is_file() and not path.name.startswith('.')) installed = sorted(path.relative_to(prefix / 'include') for path in (prefix / 'include').rglob('*') if path.is_file()) - ca_files = [Path('webcpp_ca_certificates.hpp'), + ca_files = [Path('webcpp/asio/detail/ca_certificates.hpp'), *(Path('webcpp/ca_certificates') / name for name in ('LICENSE-MPL-2.0.txt', 'README.md', 'cacert.pem', 'manifest.json'))] expected = sorted([*files, *(Path('webcpp/demo') / name for name in licences), *ca_files]) diff --git a/tools/test/libdatachannel_test.py b/tools/test/libdatachannel_test.py new file mode 100644 index 00000000..65f96afe --- /dev/null +++ b/tools/test/libdatachannel_test.py @@ -0,0 +1,135 @@ +#!/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) +"""Exercise one static OpenSSL provider through the real native WebRTC build graph.""" +from pathlib import Path +import json +import re +import subprocess +import sys + +import harness + +JAM = '''import webcpp ; +webcpp.run provider : provider.cpp + : /webcpp/third_party//openssl + /webcpp/third_party//libdatachannel multi ; +''' +SOURCE = '''#include +#include +#include +#ifndef OPENSSL_THREADS +#error "WebRTC requires the threaded OpenSSL provider" +#endif +int main() { + if (OPENSSL_VERSION_NUMBER != OpenSSL_version_num()) return 1; + auto* tls = SSL_CTX_new(TLS_method()); + if (!tls) return 2; + rtc::PeerConnection peer(rtc::Configuration{}); + auto channel = peer.createDataChannel("one-provider"); + peer.close(); + SSL_CTX_free(tls); + std::puts("one pinned OpenSSL provider"); + return channel ? 0 : 3; +} +''' + + +def test_one_native_provider_in_a_path_with_spaces(root: Path) -> None: + harness.add_library(root, 'datachannel_user', JAM, {'provider.cpp': SOURCE}) + result = harness.run_b2(root, '-a', '-j4', '-d+2', 'toolset=clang', 'variant=release', + 'libs/datachannel_user/test') + harness.expect(result, True, '**passed**') + # The combined direct/transitive dependency must use one exact archive pair, + # with users before providers even when OpenSSL was named first by the user. + link = next(line for line in result.stdout.splitlines() + if ' -o ' in line and '/libssl.a"' in line) + for library in ('ssl', 'crypto', 'datachannel', 'juice', 'usrsctp', 'srtp2'): + assert len(re.findall('/lib' + library + r'\.a"', link)) == 1, link + assert link.index('/libdatachannel.a') < link.index('/libssl.a'), link + assert link.index('/libssl.a') < link.index('/libcrypto.a'), link + binary = next(path for path in (root / 'bin').rglob('provider') if path.is_file()) + command = ['otool', '-L', str(binary)] if sys.platform == 'darwin' else ['ldd', str(binary)] + dependencies = subprocess.check_output(command, text=True) + assert not re.search(r'lib(?:ssl|crypto|datachannel)[.-]', dependencies), dependencies + records = [json.loads(path.read_text()) + for path in (root / 'bin/third_party').rglob('build.json')] + datachannel = next(record for record in records if record['pin']['version'] == '0.24.6') + openssl = next(record for record in records if 'openssl_sha256' not in record) + assert datachannel['openssl_sha256'] == openssl['sha256'], records + result = harness.run_b2(root, '-j4', 'toolset=clang', 'variant=release', + 'libs/datachannel_user/test') + harness.expect(result, True) + assert 'webcpp-libdatachannel.build ' not in result.stdout, result.stdout + # A free C++ ABI/compiler option changes the dependency's output directory. + changed = harness.run_b2(root, '-n', '-a', '-d+2', 'toolset=clang', 'variant=release', + 'cxxflags=-DWEBCPP_TEST_DATACHANNEL_VARIANT=1', + 'libs/datachannel_user/test') + harness.expect(changed, True) + initial = re.findall(r'config-[a-f0-9]+/libdatachannel\.a', link) + revised = re.findall(r'config-[a-f0-9]+/libdatachannel\.a', changed.stdout) + assert revised and set(initial).isdisjoint(revised), (initial, revised) + + +def test_single_threaded_and_unsupported_consumers_are_refused(root: Path) -> None: + result = harness.run_b2(root, '-n', 'toolset=clang', 'threading=single', + 'third_party//libdatachannel') + harness.expect(result, False, 'native backend uses worker threads', 'threading=multi') + result = harness.run_b2(root, '-n', 'toolset=clang-wasip3', 'threading=multi', + 'third_party//libdatachannel') + harness.expect(result, False, 'requires native Clang/GCC') + + +def test_missing_source_is_lazy_and_never_uses_an_external_install(root: Path) -> None: + harness.third_party_of_its_own(root, 'libdatachannel', checked_out=False) + harness.expect(harness.run_b2(root, '-n', 'declared-targets'), True) + result = harness.run_b2(root, '-n', 'threading=multi', 'third_party//libdatachannel') + harness.expect(result, False, 'libdatachannel sources are missing', + 'git submodule update --init --recursive third_party/libs/libdatachannel') + + +def test_msvc_runtime_and_custom_cpp_flags_reach_both_dependencies(root: Path) -> None: + compiler = root / 'Visual Studio/bin/cl.exe' + compiler.parent.mkdir(parents=True) + compiler.write_text('') + setup = compiler.parent / 'vcvarsall.bat' + setup.write_text('') + harness.configure(root, f'using msvc : 14.3 : "{compiler.as_posix()}"\n' + f' : "{setup.as_posix()}" off ;\n') + (root / 'Jamroot').write_text( + 'import webcpp-openssl ;\nimport webcpp-libdatachannel ;\n' + 'project : build-dir bin ;\n' + f'webcpp-openssl.declare "{root.as_posix()}" : ssl.h configuration.h\n' + ' : tools/openssl/build.py ;\n' + f'webcpp-libdatachannel.declare "{root.as_posix()}" : rtc.hpp\n' + ' : tools/libdatachannel/build.py ;\n' + 'exe consumer : provider.cpp libdatachannel openssl ;\n') + (root / 'provider.cpp').write_text(SOURCE) + for runtime, flag in (('shared', '/MDd'), ('static', '/MTd')): + result = harness.run_b2( + root, '-n', '-a', '-d+2', '-d+6', 'consumer', 'toolset=msvc-14.3', 'target-os=windows', + 'architecture=x86', 'address-model=64', 'threading=multi', 'variant=debug', + 'runtime-link=' + runtime, 'debug-store=database', 'cxxflags=/DWEBCPP_TEST_ABI=17', + env_extra={'BOOST_BUILD_PATH': str(root / 'tools')}) + harness.expect(result, True, 'datachannel.lib', 'libssl.lib', '--cxx "cl"', + '/DWEBCPP_TEST_ABI=17', flag, 'RTC_STATIC', 'iphlpapi.lib', + 'webcpp-datachannel.pdb', 'webcpp-juice.pdb', + 'webcpp-usrsctp.pdb', 'webcpp-srtp2.pdb') + command = next(line for line in result.stdout.splitlines() if '--cxx "cl"' in line) + assert '/DWEBCPP_TEST_ABI=17' in command, command + assert flag in command, command + c_flags, cpp_flags = command.split('--cxx-flags', 1) + assert '/DWEBCPP_TEST_ABI=17' not in c_flags, command + assert '/DWEBCPP_TEST_ABI=17' in cpp_flags, command + + +CASES = [test_one_native_provider_in_a_path_with_spaces, + test_msvc_runtime_and_custom_cpp_flags_reach_both_dependencies, + test_single_threaded_and_unsupported_consumers_are_refused, + test_missing_source_is_lazy_and_never_uses_an_external_install] + +if __name__ == '__main__': + sys.exit(harness.run_cases('libdatachannel_test', CASES, sys.argv[1:])) diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index c07d1c2e..f55ee228 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -8,7 +8,9 @@ from pathlib import Path import sys import io +import hashlib import json +import os import shutil import subprocess import tarfile @@ -39,6 +41,80 @@ ''' +def test_native_upstream_suite_checks_the_consumed_archives(root: Path) -> None: + # Disabling the harness, selecting only one recipe, or publishing different + # archives must fail this consumer-level proof of the opt-in upstream suite. + harness.add_library(root, 'openssl_user', JAM, {'uses_openssl.cpp': SOURCE}) + for threads in ('single', 'multi'): + result = harness.run_b2( + root, '-a', '-j2', 'toolset=clang', 'variant=release', f'threading={threads}', + 'webcpp-openssl-tests=on', 'libs/openssl_user/test', timeout=2400, + env_extra={'TESTS': 'test_this_does_not_exist', 'HARNESS_JOBS': '999'}) + harness.expect(result, True, 'upstream suite passed', '**passed**') + records = list((root / 'bin/third_party').rglob('upstream-tests.json')) + assert len(records) == 2, records + for path in records: + proof = json.loads(path.read_text()) + config = json.loads((path.parent / 'build.json').read_text()) + log = (path.parent / 'upstream-tests.log').read_text() + assert proof['result'] == 'passed', proof + assert proof['selection'] == 'alltests', proof + assert 'no-tests' not in config['configure'], config + assert 'no-apps' not in config['configure'], config + assert 'All tests successful.' in log, log[-3000:] + for recipe in (root / 'third_party/libs/openssl/test/recipes').glob('*.t'): + assert recipe.name in log, recipe.name + assert proof['sha256'] == config['sha256'], proof + for name, digest in proof['sha256'].items(): + assert hashlib.sha256((path.parent / name).read_bytes()).hexdigest() == digest + print(f'OpenSSL upstream {config["threading"]}: {proof["files"]} files, ' + f'{proof["tests"]} tests, consumed archive hashes verified', flush=True) + result = harness.run_b2(root, '-j2', 'toolset=clang', 'variant=release', 'threading=multi', + 'webcpp-openssl-tests=on', 'libs/openssl_user/test') + harness.expect(result, True) + assert 'webcpp-openssl.build ' not in result.stdout, result.stdout + + +def test_upstream_suite_rejects_wasi_by_name(root: Path) -> None: + result = harness.run_b2(root, 'third_party//openssl', 'toolset=clang-wasip3', + 'webcpp-openssl-tests=on') + harness.expect(result, False, 'upstream test harness requires native executables') + + +def test_upstream_failure_prevents_archive_publication(root: Path) -> None: + # Plant a fault in an executable after the real upstream build. The pinned + # source remains unchanged, and the real, unfiltered harness must reject it. + make = shutil.which('make') + assert make + wrappers = root / 'tool wrappers' + wrappers.mkdir() + wrapper = wrappers / 'make' + wrapper.write_text('#!/usr/bin/env python3\n' + 'import os, pathlib, subprocess, sys\n' + f'make = {make!r}\n' + 'if "test" in sys.argv[1:]:\n' + ' subprocess.run([make, "-j2", "build_tests"], check=True)\n' + ' executable = pathlib.Path("test/evp_test")\n' + ' assert executable.is_file()\n' + ' executable.write_text("#!/bin/sh\\n"' + '"echo planted EVP executable failure >&2\\nexit 1\\n")\n' + ' print("planted EVP executable failure", flush=True)\n' + 'os.execv(make, [make, *sys.argv[1:]])\n') + wrapper.chmod(0o755) + result = harness.run_b2( + root, '-a', '-j2', 'third_party//openssl', 'toolset=clang', 'variant=release', + 'threading=single', 'webcpp-openssl-tests=on', timeout=2400, + env_extra={'PATH': str(wrappers) + os.pathsep + os.environ['PATH']}) + harness.expect(result, False, 'command failed') + logs = list((root / 'bin/third_party').rglob('upstream-tests.log')) + assert len(logs) == 1, result.stdout + log = logs[0].read_text() + assert 'planted EVP executable failure' in log, log[-4000:] + assert 'Result: FAIL' in log, log[-4000:] + for name in ('libssl.a', 'libcrypto.a', 'build.json', 'upstream-tests.json'): + assert not (logs[0].parent / name).exists(), name + + def test_native_source_dependency(root: Path) -> None: harness.add_library(root, 'openssl_user', JAM, {'uses_openssl.cpp': SOURCE}) for threads in ('single', 'multi'): @@ -228,7 +304,10 @@ def test_source_archive_tampering_fails_before_configuration(root: Path) -> None (source / 'unexpected.pm').unlink(missing_ok=True) -CASES = [test_native_source_dependency, test_symlinked_compiler_without_c_sibling, +CASES = [test_native_upstream_suite_checks_the_consumed_archives, + test_upstream_suite_rejects_wasi_by_name, + test_upstream_failure_prevents_archive_publication, + test_native_source_dependency, test_symlinked_compiler_without_c_sibling, test_msvc_build_commands_preserve_the_consumers_configuration, test_missing_checkout_is_lazy_and_actionable, test_unsupported_target_is_rejected, test_pin_mismatch_fails_before_compilation, diff --git a/tools/webcpp-ca-certificates.jam b/tools/webcpp-ca-certificates.jam index efa00f98..9ce0d0ab 100644 --- a/tools/webcpp-ca-certificates.jam +++ b/tools/webcpp-ca-certificates.jam @@ -24,7 +24,7 @@ class ca-certificates-target : basic-target rule construct ( name : sources * : properties ) { local action = [ new action $(sources) : webcpp-ca-certificates.generate : $(properties) ] ; - local header = [ new file-target webcpp_ca_certificates.hpp exact : H + local header = [ new file-target webcpp/asio/detail/ca_certificates.hpp exact : H : $(self.project) : $(action) ] ; local directory = [ path.root [ path.make [ $(header).path ] ] [ path.pwd ] ] ; header = [ virtual-target.register $(header) ] ; diff --git a/tools/webcpp-libdatachannel.jam b/tools/webcpp-libdatachannel.jam new file mode 100644 index 00000000..1c6c29cf --- /dev/null +++ b/tools/webcpp-libdatachannel.jam @@ -0,0 +1,203 @@ +# 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) + +import "class" : new ; +import errors ; +import feature ; +import modules ; +import path ; +import project ; +import property-set ; +import targets ; +import toolset ; +import virtual-target ; + +feature.feature webcpp-libdatachannel-openssl : : free incidental ; + +class libdatachannel-target : basic-target +{ + import "class" : new ; + import errors ; + import modules ; + import path ; + import property-set ; + import toolset ; + import unix ; + import virtual-target ; + + rule __init__ ( name : project : sources * : requirements * + : default-build * : usage-requirements * ) + { + basic-target.__init__ $(name) : $(project) : $(sources) : + $(requirements) : $(default-build) : $(usage-requirements) ; + } + + rule construct ( name : source-targets * : properties ) + { + local root = [ modules.peek webcpp-libdatachannel : .root ] ; + if ! [ path.exists [ path.native $(root)/third_party/libs/libdatachannel/CMakeLists.txt ] ] + { + errors.user-error "libdatachannel sources are missing. Run: git submodule update --init --recursive third_party/libs/libdatachannel" ; + } + local os = [ $(properties).get ] ; + local provider ; + local provider-libraries ; + local provider-ssl ; + local provider-crypto ; + for local source in $(source-targets) + { + if [ $(source).name ] in libssl.a libssl.lib + { + provider-ssl = $(source) ; + provider = [ path.root [ path.make [ $(source).path ] ] [ path.pwd ] ] ; + } + if [ $(source).name ] in libcrypto.a libcrypto.lib + { + provider-crypto = $(source) ; + } + if [ $(source).name ] in libssl.a libssl.lib libcrypto.a libcrypto.lib + { + provider-libraries += $(source) ; + } + } + if ! $(provider) + { + errors.user-error "libdatachannel requires the source-built OpenSSL target as a dependency." ; + } + local relevant = [ toolset.relevant webcpp-libdatachannel.build ] ; + properties = [ $(properties).add $(relevant) ] ; + local fingerprint = [ modules.call-in webcpp-libdatachannel : fingerprint $(properties) ] ; + properties = [ $(properties).add-raw $(provider) ] ; + local action = [ new action $(source-targets) : webcpp-libdatachannel.build : $(properties) ] ; + local prefix = lib ; + local extension = a ; + if $(os) = windows { prefix = "" ; extension = lib ; } + local archives ; + local directory ; + for local library in datachannel juice usrsctp srtp2 + { + local archive = [ new file-target $(prefix)$(library).$(extension) exact + : STATIC_LIB : $(self.project) : $(action) ] ; + if ! $(directory) + { + directory = [ path.root [ path.make [ $(archive).path ] ] [ path.pwd ] ] ; + directory = $(directory)/config-$(fingerprint) ; + } + $(archive).set-path $(directory) ; + archives += [ virtual-target.register $(archive) ] ; + } + local headers ; + for local header in [ modules.peek webcpp-libdatachannel : .headers ] + { + local generated = [ new file-target include/rtc/$(header) exact + : H : $(self.project) : $(action) ] ; + $(generated).set-path $(directory) ; + headers += [ virtual-target.register $(generated) ] ; + } + if $(os) = windows && [ $(properties).get ] = "on" + && [ $(properties).get ] = database + { + for local library in datachannel juice usrsctp srtp2 + { + local symbols = [ new file-target webcpp-$(library).pdb exact + : PDB : $(self.project) : $(action) ] ; + $(symbols).set-path $(directory) ; + headers += [ virtual-target.register $(symbols) ] ; + } + } + unix.set-library-order-aux $(provider-ssl) : $(provider-crypto) ; + unix.set-library-order-aux $(archives[1]) : $(archives[2-]) ; + unix.set-library-order-aux $(archives) : $(provider-libraries) ; + # Keep the one OpenSSL target in the final link after its static users. + return [ property-set.create [ $(relevant).raw ] $(directory)/include + $(headers) ] $(archives) $(provider-libraries) ; + } +} + +rule declare ( root : headers * : sources * ) +{ + .root = $(root) ; + .headers = $(headers) ; + targets.create-metatarget libdatachannel-target : [ project.current ] : libdatachannel + : $(sources) openssl : static off off + @webcpp-libdatachannel.configuration + : : RTC_STATIC RTC_ENABLE_WEBSOCKET=0 RTC_ENABLE_MEDIA=1 + linux:-pthread + windows:"ws2_32.lib iphlpapi.lib bcrypt.lib" ; +} + +rule configuration ( properties * ) +{ + local ps = [ property-set.create $(properties) ] ; + local os = [ $(ps).get ] ; + local tool = [ $(ps).get ] ; + if ! ( ( $(tool) in clang gcc && $(os) in darwin linux ) + || ( $(tool) = msvc && $(os) = windows ) ) + { + errors.user-error "Source-built libdatachannel requires native Clang/GCC on macOS/Linux or MSVC on Windows." ; + } + if [ $(ps).get ] != multi + { + errors.user-error "Trystero's native backend uses worker threads. Add multi to the consuming target or pass threading=multi." ; + } +} + +toolset.uses-features webcpp-libdatachannel.build : ; + +rule compiler-settings ( outputs * : ps ) +{ + local compiler = [ $(ps).get ] ; + if $(compiler) = clang + { + local platform = [ $(ps).get ] ; + compiler = clang-$(platform) ; + } + local c-settings = $(outputs[1])-c ; + toolset.set-target-variables $(compiler).compile.c $(c-settings) : $(ps) ; + toolset.set-target-variables $(compiler).compile.c++ $(outputs) : $(ps) ; + if $(compiler) = msvc + { + DRIVER on $(outputs) = [ on $(outputs[1]) return $(.CC[1]) ] ; + C_OPTIONS on $(outputs) = [ on $(c-settings) return $(.CC[2-]) $(OPTIONS) $(CFLAGS) $(USER_CFLAGS) ] ; + CXX_OPTIONS on $(outputs) = [ on $(outputs[1]) return $(.CC[2-]) $(OPTIONS) $(CFLAGS) $(C++FLAGS) $(USER_CFLAGS) $(USER_C++FLAGS) $(USER_COMPILEFLAGS) ] ; + } + else + { + DRIVER on $(outputs) = [ on $(outputs[1]) return $(CONFIG_COMMAND[1]) ] ; + C_OPTIONS on $(outputs) = [ on $(c-settings) return $(OPTIONS) $(USER_OPTIONS) ] ; + CXX_OPTIONS on $(outputs) = [ on $(outputs[1]) return $(OPTIONS) $(USER_OPTIONS) ] ; + } +} + +rule fingerprint ( ps ) +{ + if $(.fingerprint.$(ps)) { return $(.fingerprint.$(ps)) ; } + local settings = libdatachannel-settings-$(ps) ; + compiler-settings $(settings) : $(ps) ; + local values = [ on $(settings) return $(DRIVER) $(C_OPTIONS) $(CXX_OPTIONS) $(DEFINES) $(.SETUP) $(.SETUP-SCRIPT) $(.SETUP-OPTIONS) ] ; + .fingerprint.$(ps) = [ MD5 "$(values:J=|)" ] ; + return $(.fingerprint.$(ps)) ; +} + +rule build ( outputs * : inputs * : properties * ) +{ + local ps = [ property-set.create $(properties) ] ; + compiler-settings $(outputs) : $(ps) ; + if [ $(ps).get ] = msvc + { + modules.call-in msvc : set-setup-command $(outputs) : $(properties) ; + } + SCRIPT on $(outputs) = [ path.native $(.root)/tools/libdatachannel/build.py ] ; + SOURCE on $(outputs) = [ path.native $(.root)/third_party/libs/libdatachannel ] ; + OPENSSL on $(outputs) = [ path.native [ $(ps).get ] ] ; + PLATFORM on $(outputs) = [ $(ps).get ] ; + VARIANT on $(outputs) = [ $(ps).get ] ; +} + +actions build +{ + $(.SETUP) python3 "$(SCRIPT)" "@($(<[1]:W).rsp:E=--source "$(SOURCE)" --output "$(<[1]:DW)" --openssl "$(OPENSSL)" --platform "$(PLATFORM)" --variant "$(VARIANT)" --cxx "$(DRIVER)" -- $(C_OPTIONS) -D$(DEFINES) --cxx-flags $(CXX_OPTIONS) -D$(DEFINES))" +} diff --git a/tools/webcpp-openssl.jam b/tools/webcpp-openssl.jam index 22e5c194..422672e5 100644 --- a/tools/webcpp-openssl.jam +++ b/tools/webcpp-openssl.jam @@ -12,9 +12,13 @@ import project ; import property-set ; import targets ; import toolset ; +import type ; import virtual-target ; import webcpp-wasi ; +feature.feature webcpp-openssl-tests : on : optional propagated ; +type.register WEBCPP_OPENSSL_TESTS ; + class openssl-target : basic-target { import "class" : new ; @@ -42,6 +46,11 @@ class openssl-target : basic-target local os = [ $(properties).get ] ; local tool = [ $(properties).get ] ; local version = [ $(properties).get ] ; + if $(os) = wasi && [ $(properties).get ] = "on" + { + errors.user-error "The OpenSSL upstream test harness requires native executables." + "WASIp3 uses the separately declared TLS integration tests." ; + } if ! ( ( $(tool) in clang gcc && $(os) in darwin linux ) || ( $(tool) = clang && $(os) = wasi && $(version) = wasip3 ) || ( $(tool) = msvc && $(os) = windows ) ) @@ -74,6 +83,13 @@ class openssl-target : basic-target $(generated).set-path $(directory) ; headers += [ virtual-target.register $(generated) ] ; } + if [ $(properties).get ] = "on" + { + local proof = [ new file-target upstream-tests.json exact + : WEBCPP_OPENSSL_TESTS : $(self.project) : $(action) ] ; + $(proof).set-path $(directory) ; + headers += [ virtual-target.register $(proof) ] ; + } if $(os) = windows && [ $(properties).get ] = "on" && [ $(properties).get ] = database { @@ -102,7 +118,7 @@ rule declare ( root : headers * : sources * ) wasi:"-lwasi-emulated-getpid -lwasi-emulated-signal -lwasi-emulated-process-clocks -lwasi-emulated-mman" ; } -toolset.uses-features webcpp-openssl.build : ; +toolset.uses-features webcpp-openssl.build : ; rule configuration ( properties * ) { @@ -168,9 +184,13 @@ rule build ( outputs * : inputs * : properties * ) PLATFORM on $(outputs) = [ $(ps).get ] ; THREADING on $(outputs) = [ $(ps).get ] ; VARIANT on $(outputs) = [ $(ps).get ] ; + if [ $(ps).get ] = "on" + { + TEST on $(outputs) = --test ; + } } actions build { - $(.SETUP) python3 "$(SCRIPT)" "@($(<[1]:W).rsp:E=--source "$(SOURCE)" --output "$(<[1]:DW)" --platform "$(PLATFORM)" --threading "$(THREADING)" --variant "$(VARIANT)" --cc "$(DRIVER)" --ar "$(ARCHIVER)" -- $(C_OPTIONS) -D$(DEFINES))" + $(.SETUP) python3 "$(SCRIPT)" "@($(<[1]:W).rsp:E=--source "$(SOURCE)" --output "$(<[1]:DW)" --platform "$(PLATFORM)" --threading "$(THREADING)" --variant "$(VARIANT)" --cc "$(DRIVER)" --ar "$(ARCHIVER)" $(TEST) -- $(C_OPTIONS) -D$(DEFINES))" } From e80ffabb9cc3223f71f07696d3d6a5e806a24f20 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 08:37:47 -0500 Subject: [PATCH 09/32] Integrate checked WASIp2 pollable backend and validation --- doc/releases/0.1.0.adoc | 4 +- .../plans/2026-11-03-asio-wasip2-pollables.md | 104 +++++ libs/asio | 2 +- libs/beast | 2 +- tools/boost/asio-wasip2/Jamfile | 31 ++ .../boost/asio/detail/wasi_resolver.hpp | 368 ++++++++++++++++++ tools/boost/asio-wasip2/pollable.cpp | 77 ++++ tools/boost/asio-wasip2/run.sh | 11 + tools/boost/asio-wasip2/verify.py | 61 +++ tools/boost/asio-wasip2/verify_test.py | 48 +++ tools/boost/asio-wasip2/wasi-libc/LICENSE | 17 + .../asio-wasip2/wasi-libc/LICENSE-APACHE | 201 ++++++++++ tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT | 23 ++ .../boost/asio-wasip2/wasi-libc/manifest.json | 12 + .../wasi-libc/wasi/descriptor_table.h | 368 ++++++++++++++++++ tools/boost/asio-wasip2/wasi-libc/wasi/poll.h | 79 ++++ tools/boost/asio-wasip3/Jamfile | 5 + tools/boost/asio-wasip3/README.md | 16 +- tools/boost/asio-wasip3/boost-1.92.patch | 250 ++++++++---- tools/boost/asio-wasip3/manifest.json | 34 +- tools/ci/matrix.py | 4 +- tools/ci/matrix_test.py | 8 +- tools/lint/lint.sh | 13 + tools/lint/lint_test.py | 21 + tools/test/asio_wasip3_test.py | 44 ++- tools/webcpp-wasi.jam | 8 +- 26 files changed, 1715 insertions(+), 96 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md create mode 100644 tools/boost/asio-wasip2/Jamfile create mode 100644 tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp create mode 100644 tools/boost/asio-wasip2/pollable.cpp create mode 100755 tools/boost/asio-wasip2/run.sh create mode 100644 tools/boost/asio-wasip2/verify.py create mode 100644 tools/boost/asio-wasip2/verify_test.py create mode 100644 tools/boost/asio-wasip2/wasi-libc/LICENSE create mode 100644 tools/boost/asio-wasip2/wasi-libc/LICENSE-APACHE create mode 100644 tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT create mode 100644 tools/boost/asio-wasip2/wasi-libc/manifest.json create mode 100644 tools/boost/asio-wasip2/wasi-libc/wasi/descriptor_table.h create mode 100644 tools/boost/asio-wasip2/wasi-libc/wasi/poll.h diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index d4fa6c05..e1115556 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -7,13 +7,11 @@ [#webcpp-0-1-0] = webcpp 0.1.0 -// Frozen candidate only; publishing the release and tag is a separate owner action. - [#webcpp-0-1-0-new-libraries] == New Libraries * link:{library-pages}asio/{library-page}[asio]: Boost.Asio and Cobalt with -browser event-loop suspension, WASIp3 networking and optional source-built TLS, +browser event-loop suspension, WASIp2/P3 networking and optional source-built TLS, from R. * link:{library-pages}beast/{library-page}[beast]: HTTP messages and WebSocket applications for native, WASI and browser targets, with socket transports, diff --git a/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md b/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md new file mode 100644 index 00000000..3b42bda9 --- /dev/null +++ b/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md @@ -0,0 +1,104 @@ +# Asio WASIp2 pollables and supplied WebSocket implementation plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking. + +**Goal:** Run Asio timers, TCP, UDP and asynchronous name resolution on WASIp2, report unsupported facilities explicitly, and run both supplied-channel WebSocket examples with exceptions on and off. + +**Architecture:** Preserve Boost.Asio's scheduler and protocol implementations. Reuse wasi-libc's P2 socket/readiness translation where it preserves the contract; connect any additional native P2 pollables through a checked private Boost overlay. Supplied WebSocket channels use the same executor, preserve partial I/O and report cancellation through ordinary completion handlers. + +**Tech Stack:** C++20, Boost 1.92, wasi-sdk 34.0, Wasmtime 50.0.1, B2. + +**Spec:** The owner approved both designs in this conversation on 2026-11-03. This document records that approved scope and the implementation choices below. This supersedes the earlier exclusion of Asio P2 sockets, but does not declare untested Cobalt, TLS or thread variants supported. + +## Global constraints + +- Work in the existing isolated checkout; preserve the preceding closure commits. +- Preserve native, Emscripten and WASIp3 behavior and private overlay hash checks. +- Start with single-threaded P2, exceptions on/off; reject unsupported thread configurations at build time. +- Keep unavailable static APIs distinguishable from runtime capability denial and unsupported socket options. +- Preserve deferred initiation, associated allocator/executor/cancellation, and completion outside initiation. +- Do not rewrite WebSocket framing or silently replace the supplied channel with TCP. +- Generated application files and matrices change only through their generators. +- Local tests first; final remote CI and merge still follow the existing authorized closure process. +- No tags or release publication. + +## Review focus + +- Idle waits, timer deadlines and an operation becoming ready during registration must not spin or lose wakeups. +- Cancelling or destroying a pending DNS/read/write operation must not leave borrowed buffers or invoke handlers twice. +- Unsupported calls must produce deliberate diagnostics or errors, not traps from absent POSIX facilities. +- A slow consumer and full output pipe must not be advertised as bounded cancellation when the host import blocks. +- Exceptions-off, associated allocation and native/P3 regressions need actual compiled consumers. + +### Task 1: P2 Asio core, sockets and deliberate diagnostics + +**Files:** `tools/boost/asio-wasip3/{boost-1.92.patch,manifest.json,Jamfile}`, `libs/asio/{build.jam,test/Jamfile}`, new `libs/asio/test/wasip2` consumers, Asio capability documentation. + +**Interfaces:** Existing `webcpp::asio::io_context`, timers and IP socket types; `/webcpp/asio//asio` gains P2 single-thread support. Existing unsupported optional targets retain clear build errors until validated separately. + +- [x] Add a P2 public-target consumer for timer, TCP/UDP echo, partial transfer, refusal and cancellation; run it against the current target and record the missing-port failure. +- [x] Inspect pinned wasi-libc readiness and reuse its `select`/`poll` to `wasi:io/poll` path. Extend only the necessary private overlay guards and build configuration. +- [x] Add consumer-level negative checks for unsupported thread/API/operation paths, paired with valid controls. +- [x] Run `b2 -a toolset=clang-wasip2` consumers in Wasmtime with real network grants, exceptions on/off, plus native/P3 regression consumers. Expected: correct payloads, callbacks and intentional diagnostics. +- [x] Commit the library and superproject changes with their evidence. + +### Task 2: Pollable-based asynchronous DNS + +**Files:** Asio resolver implementation and checked overlay, P2 resolver consumers and real peer driver. + +**Interfaces:** `async_resolve` retains Asio completion-token semantics, owns host/service inputs and maps WASI DNS errors to values. No resolver worker thread or synchronous DNS call inside initiation. + +- [x] Add a real lookup test with deferred initiation, cancellation and independent ready work. Record the existing unsupported behavior. +- [x] Integrate P2 address-stream pollables with the scheduler, preserving resource lifetime and associated allocation. +- [x] Run successful, invalid-name, cancellation and context-destruction cases in both exception profiles, plus unaffected native/P3 cases. Expected: no inline completion, no duplicate callback, no leaked resources. +- [x] Commit implementation and contract evidence. + +### Task 3: Supplied-channel WebSocket on P2 + +**Files:** `libs/beast/include/webcpp/beast/websocket.hpp`, `libs/beast/build.jam`, supplied-channel adapters and application generator, `libs/beast/test/applications/streams`. + +**Interfaces:** The existing WebSocket engine consumes a supplied byte-stream adapter and the P2 executor. The application retains ownership of its channel; WebSocket close is not invented Unix descriptor ownership. + +- [x] Enable the two P2 application test consumers first and record their actual compile/runtime failure. +- [x] Implement readiness-driven asynchronous partial read/write and cancellation for supplied channels, preserve synchronous operations, and remove unnecessary socket-target coupling. +- [x] Verify actual upgrade, text/binary and fragmented frames, ping/pong, close, truncated input and pending-operation cancellation. Exercise slow consumers with documented host-blocking boundaries. +- [x] Run P2 EH on/off, native and P3 stream lanes from scratch. Expected: four formerly blocked P2 cells have real passing evidence. +- [x] Commit the adapter, applications and evidence. + +### Task 4: Matrices, regression verification and review + +**Files:** Asio/Beast guides and agents, matrix generator, root build/CI registration and proposal records. + +- [x] Update approved P2 scope and per-feature/profile declarations; keep TLS, Cobalt and thread support separate from core support. +- [x] Regenerate the matrix using runtime evidence, not optimistic status replacements. +- [ ] Run all declared Asio/Beast local suites, focused build/tool tests, changed-code lint and documentation generation from scratch. +- [x] Obtain one fresh review, fix important findings with reproductions, and preserve remaining limitations explicitly. +- [ ] Continue exact-candidate CI/merge closure without claiming an older green run validates these changes. + + +## Verification record, 2026-11-03 + +The two approved implementation paths are committed locally. Broader release/CI gates +remain separate and are not inferred from the earlier green superproject commit. + +- Asio commit: `dad1aef`, WASIp2 core/DNS and supplied CLI streams. +- Beast commit: `ab95e84`, supplied-channel WebSocket client/server and matrix. +- Fresh Release default suites plus supplied-stream lanes: native 138, WASIp3 131, + WASIp2 68 passing B2 test targets, including compile/header and runtime targets. + Each run covered exception handling on/off. No failed actions remained. +- Focused clang-tidy: 20 translation-unit configurations passed, covering both EH modes. + Changed-file formatting, text rules and Pyright passed. Asio/Beast documentation rendered. +- Build-profile tests cover public target selection, P2 multi/Cobalt/TLS rejection, + the SDK ABI refusal and the unchanged P3 profile contracts. CI matrix tooling passed. +- One fresh review found idle empty-poll trapping and quota narrowing. Consumer regressions + failed before each fix and passed afterward. Added ready-at-registration and pending-write + cancellation witnesses. The quota fixture models the host ABI; it does not claim every + real host is nonblocking. +- WASIp2 supplied WebSocket cells now pass: client/server, EH on/off. The generated corpus + matrix is 571 passed, 216 blocked, 432 platform-unavailable. P2 raw-socket Beast corpus + integration remains blocked; core TCP support alone is not application evidence. + +Decisions: reuse libc select/poll, pin the private descriptor ABI, retain deferred DNS +initiation and upstream public-result allocation, and keep host-blocking writes explicit. +The ABI bridge must be revalidated on SDK updates. No CPU-thread, guest TLS, Cobalt, +Unix addressing or host WebSocket-upgrade capability is implied for P2. diff --git a/libs/asio b/libs/asio index 69482921..dad1aefb 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 6948292165c436a51b0f254de1c7486e92759979 +Subproject commit dad1aefbe99f8a2cae4e2e3389779106a24cf3dc diff --git a/libs/beast b/libs/beast index 1cffa163..ab95e844 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 1cffa1634811b7bf2f754a7b188bf66015ce22a0 +Subproject commit ab95e844d2eee707eedd3ac708e3a14c9ff8b47d diff --git a/tools/boost/asio-wasip2/Jamfile b/tools/boost/asio-wasip2/Jamfile new file mode 100644 index 00000000..117204aa --- /dev/null +++ b/tools/boost/asio-wasip2/Jamfile @@ -0,0 +1,31 @@ +# 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) +import make ; +import webcpp-wasi ; +project /webcpp/asio-wasip2 ; +path-constant BUNDLE : . ; +path-constant OUTPUT : ../../../bin/boost-asio-wasip2 ; +make verified.stamp : verify.py wasi-libc/manifest.json : @verify + : $(OUTPUT) off ; +always verified.stamp ; +explicit verified.stamp ; +rule verify ( targets * : sources * : properties * ) +{ + SCRIPT on $(targets) = $(BUNDLE)/verify.py ; + SDK on $(targets) = [ webcpp-wasi.sdk $(WEBCPP_ROOT) ] ; +} +actions verify +{ + python3 "$(SCRIPT)" --sdk "$(SDK)" --stamp "$(<)" +} +obj pollable : pollable.cpp + : ../../../libs/asio/include wasi-libc + verified.stamp /webcpp/config//config ; +explicit pollable ; + +# Private resolver extension selected only with the P2 platform overlay. +alias headers : : : : include /webcpp/asio-wasip3//headers ; +explicit headers ; diff --git a/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp b/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp new file mode 100644 index 00000000..dd2081fc --- /dev/null +++ b/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp @@ -0,0 +1,368 @@ +// 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) +#ifndef WEBCPP_ASIO_DETAIL_WASI_RESOLVER_HPP +#define WEBCPP_ASIO_DETAIL_WASI_RESOLVER_HPP +#if defined(__wasip2__) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// This adapter is included only by the checked WASIp2 Boost overlay. +namespace boost { +namespace asio { +BOOST_ASIO_INLINE_NAMESPACE_BEGIN + +namespace detail { + +struct wasi_resolver_state; + +struct wasi_resolver_node { + wasi_resolver_state* owner = nullptr; + wasi_resolver_node* next = nullptr; + void (*cancel)(wasi_resolver_node*) = nullptr; + void detach(); +}; + +struct wasi_resolver_state { + wasi_resolver_node* head = nullptr; + + void cancel_all() { + while (head) { + auto* node = head; + node->detach(); + node->cancel(node); + } + } + + ~wasi_resolver_state() { cancel_all(); } +}; + +inline void wasi_resolver_node::detach() { + if (!owner) + return; + auto** current = &owner->head; + while (*current != this) + current = &(*current)->next; + *current = next; + owner = nullptr; + next = nullptr; +} + +inline void wasi_resolver_construct(std::shared_ptr& impl, execution_context& context) { + impl = std::allocate_shared( + execution_context::allocator(context)); +} + +inline void wasi_resolver_cancel(std::shared_ptr& impl) { + if (impl) + static_cast(impl.get())->cancel_all(); +} + +inline boost::system::error_code wasi_resolver_error(network_error_code_t error) { + switch (error) { + case NETWORK_ERROR_CODE_ACCESS_DENIED: return boost::asio::error::access_denied; + case NETWORK_ERROR_CODE_NOT_SUPPORTED: return boost::asio::error::operation_not_supported; + case NETWORK_ERROR_CODE_INVALID_ARGUMENT: return boost::asio::error::invalid_argument; + case NETWORK_ERROR_CODE_OUT_OF_MEMORY: return boost::asio::error::no_memory; + case NETWORK_ERROR_CODE_TIMEOUT: return boost::asio::error::timed_out; + case NETWORK_ERROR_CODE_NAME_UNRESOLVABLE: return boost::asio::error::host_not_found; + case NETWORK_ERROR_CODE_TEMPORARY_RESOLVER_FAILURE: + return boost::asio::error::host_not_found_try_again; + default: return boost::asio::error::no_recovery; + } +} + +template +class wasi_resolve_op : public reactor_op, public wasi_resolver_node { + using query_type = boost::asio::ip::basic_resolver_query; + using results_type = boost::asio::ip::basic_resolver_results; + using endpoint_type = typename Protocol::endpoint; + using allocator_type = associated_allocator_t; + using char_allocator = + typename std::allocator_traits::template rebind_alloc; + using endpoint_allocator = + typename std::allocator_traits::template rebind_alloc; + using string_type = std::basic_string, char_allocator>; + using slot_type = associated_cancellation_slot_t; + + select_reactor& reactor_; + select_reactor::per_descriptor_data reactor_data_{}; + string_type host_; + string_type service_; + addrinfo_type hints_; + std::vector endpoints_; + Handler handler_; + handler_work work_; + slot_type slot_; + webcpp::asio::detail::wasi_pollable_descriptor descriptor_{}; + int fd_ = -1; + ip_name_lookup_own_resolve_address_stream_t lookup_{}; + poll_own_pollable_t ready_{}; + bool has_lookup_ = false; + bool has_ready_ = false; + bool started_ = false; + bool waiting_ = false; + bool cancelled_ = false; + unsigned short port_ = 0; + bool allow_v4_ = true; + bool allow_v6_ = true; + + struct slot_cancel { + wasi_resolve_op* operation; + + void operator()(cancellation_type_t type) { + if (type != cancellation_type::none) + operation->request_cancel(); + } + }; + + void request_cancel() { + cancelled_ = true; + if (waiting_) + reactor_.cancel_ops(fd_, reactor_data_); + } + + // Only numeric address parsing and the libc service table are used here. + // AI_NUMERICHOST prevents this helper from ever initiating host DNS. + void numeric(const char* host, addrinfo_type hints, + std::vector& output, + boost::system::error_code& ec) { + hints.ai_flags |= AI_NUMERICHOST; + addrinfo_type* addresses = nullptr; + socket_ops::getaddrinfo(host, service_.c_str(), hints, &addresses, ec); + + struct address_owner { + addrinfo_type* value; + + ~address_owner() { + if (value) + socket_ops::freeaddrinfo(value); + } + } owner{addresses}; + + if (ec) + return; + for (auto* entry = addresses; entry; entry = entry->ai_next) { + if (entry->ai_family != AF_INET && entry->ai_family != AF_INET6) + continue; + endpoint_type endpoint; + if (entry->ai_addrlen > endpoint.capacity()) + continue; + std::memcpy(endpoint.data(), entry->ai_addr, entry->ai_addrlen); + endpoint.resize(entry->ai_addrlen); + output.push_back(endpoint); + } + } + + bool begin() { + started_ = true; + if (cancelled_) { + ec_ = boost::asio::error::operation_aborted; + return false; + } + // WASI returns addresses, not canonical names or IPv4 mapping policy. + if (hints_.ai_flags & (AI_CANONNAME | AI_V4MAPPED | AI_ALL)) { + ec_ = boost::asio::error::operation_not_supported; + return false; + } + numeric(host_.empty() ? nullptr : host_.c_str(), hints_, endpoints_, ec_); + if (!ec_ || (hints_.ai_flags & AI_NUMERICHOST)) + return false; + if (ec_ != boost::asio::error::host_not_found && + ec_ != boost::asio::error::host_not_found_try_again) + return false; + + // Validate the service and implement AI_ADDRCONFIG using libc's local + // numeric-family checks, before starting the asynchronous name lookup. + auto local_hints = hints_; + local_hints.ai_family = AF_INET; + boost::system::error_code v4_error, v6_error; + numeric("127.0.0.1", local_hints, endpoints_, v4_error); + allow_v4_ = !v4_error && hints_.ai_family != AF_INET6; + if (!endpoints_.empty()) + port_ = endpoints_.front().port(); + endpoints_.clear(); + local_hints.ai_family = AF_INET6; + numeric("::1", local_hints, endpoints_, v6_error); + allow_v6_ = !v6_error && hints_.ai_family != AF_INET; + if (!endpoints_.empty()) + port_ = endpoints_.front().port(); + endpoints_.clear(); + if (!allow_v4_ && !allow_v6_) { + ec_ = hints_.ai_family == AF_INET6 ? v6_error : v4_error; + if (!ec_) + ec_ = boost::asio::error::host_not_found; + return false; + } + ec_.clear(); + auto network = instance_network_instance_network(); + wasip2_string_t name{reinterpret_cast(host_.data()), host_.size()}; + network_error_code_t error{}; + has_lookup_ = ip_name_lookup_resolve_addresses(network_borrow_network(network), &name, + &lookup_, &error); + network_network_drop_own(network); + if (!has_lookup_) { + ec_ = wasi_resolver_error(error); + return false; + } + ready_ = ip_name_lookup_method_resolve_address_stream_subscribe( + ip_name_lookup_borrow_resolve_address_stream(lookup_)); + has_ready_ = true; + descriptor_.handle = ready_.__handle; + fd_ = webcpp_asio_wasi_pollable_descriptor(&descriptor_); + if (fd_ < 0) { + ec_ = boost::system::error_code(errno, boost::asio::error::get_system_category()); + return false; + } + int const registration = reactor_.register_descriptor(fd_, reactor_data_); + if (registration != 0) { + ec_ = + boost::system::error_code(registration, boost::asio::error::get_system_category()); + return false; + } + waiting_ = true; + reactor_.start_op(select_reactor::read_op, fd_, reactor_data_, this, false, false); + return true; + } + +public: + BOOST_ASIO_DEFINE_HANDLER_PTR(wasi_resolve_op); + + wasi_resolve_op(wasi_resolver_state& state, execution_context& context, query_type const& query, + Handler& handler, IoExecutor const& executor) + : reactor_op({}, &perform_lookup, &complete), + reactor_(boost::asio::use_service(context)), + host_(query.host_name().c_str(), char_allocator(get_associated_allocator(handler))), + service_(query.service_name().c_str(), char_allocator(get_associated_allocator(handler))), + hints_(query.hints()), + endpoints_(endpoint_allocator(get_associated_allocator(handler))), + handler_(static_cast(handler)), + work_(handler_, executor), + slot_(get_associated_cancellation_slot(handler_)) { + reactor_.init_task(); + if (slot_.is_connected()) + slot_.template emplace(this); + owner = &state; + next = state.head; + state.head = this; + cancel = [](wasi_resolver_node* node) { + static_cast(node)->request_cancel(); + }; + } + + ~wasi_resolve_op() { + detach(); + if (slot_.is_connected()) + slot_.clear(); + // No reactor operations refer to the descriptor at completion/shutdown. + if (fd_ >= 0) + ::close(fd_); + if (has_ready_) + poll_pollable_drop_own(ready_); + if (has_lookup_) + ip_name_lookup_resolve_address_stream_drop_own(lookup_); + } + + static status perform_lookup(reactor_op* base) { + auto& self = *static_cast(base); + // Consume a bounded number of addresses per reactor turn. + for (unsigned count = 0; count < 64; ++count) { + ip_name_lookup_option_ip_address_t address{}; + network_error_code_t error{}; + if (!ip_name_lookup_method_resolve_address_stream_resolve_next_address( + ip_name_lookup_borrow_resolve_address_stream(self.lookup_), &address, &error)) { + if (error == NETWORK_ERROR_CODE_WOULD_BLOCK) + return not_done; + self.ec_ = wasi_resolver_error(error); + return done; + } + if (!address.is_some) { + if (self.endpoints_.empty()) + self.ec_ = boost::asio::error::host_not_found; + return done; + } + if (address.val.tag == NETWORK_IP_ADDRESS_IPV4 && self.allow_v4_) { + auto const& a = address.val.val.ipv4; + self.endpoints_.emplace_back(ip::address_v4({a.f0, a.f1, a.f2, a.f3}), self.port_); + } else if (address.val.tag == NETWORK_IP_ADDRESS_IPV6 && self.allow_v6_) { + auto const& a = address.val.val.ipv6; + std::uint16_t const words[] = {a.f0, a.f1, a.f2, a.f3, a.f4, a.f5, a.f6, a.f7}; + ip::address_v6::bytes_type bytes{}; + for (std::size_t i = 0; i != 8; ++i) { + bytes[2 * i] = static_cast(words[i] >> 8); + bytes[2 * i + 1] = static_cast(words[i]); + } + self.endpoints_.emplace_back(ip::address_v6(bytes), self.port_); + } + } + return not_done; + } + + static void complete(void* completion_owner, operation* base, boost::system::error_code const&, + std::size_t) { + auto* self = static_cast(base); + ptr memory = {std::addressof(self->handler_), self, self}; + if (completion_owner && !self->started_ && self->begin()) { + memory.v = memory.p = nullptr; + return; + } + self->waiting_ = false; + if (self->cancelled_) + self->ec_ = boost::asio::error::operation_aborted; + handler_work work( + static_cast&&>(self->work_)); + binder2 handler(self->handler_, self->ec_, + results_type{}); + memory.h = std::addressof(handler.handler_); + if (completion_owner && !self->ec_) { + // Boost's public result container retains its upstream allocator. + handler.arg2_ = + results_type::create(self->endpoints_.begin(), self->endpoints_.end(), + std::string(self->host_.data(), self->host_.size()), + std::string(self->service_.data(), self->service_.size())); + } + memory.reset(); + if (completion_owner) + work.complete(handler, handler.handler_); + } +}; + +template +void wasi_async_resolve(std::shared_ptr& impl, execution_context& context, + typename boost::asio::ip::basic_resolver_query const& query, + Handler& handler, IoExecutor const& executor) { + if (!impl) + wasi_resolver_construct(impl, context); + using op = wasi_resolve_op; + typename op::ptr memory = {std::addressof(handler), op::ptr::allocate(handler), nullptr}; + memory.p = new (memory.v) + op(*static_cast(impl.get()), context, query, handler, executor); + boost::asio::use_service(context).post_immediate_completion(memory.p, false); + memory.v = memory.p = nullptr; +} + +} // namespace detail + +BOOST_ASIO_INLINE_NAMESPACE_END +} // namespace asio +} // namespace boost +#endif // __wasip2__ +#endif // WEBCPP_ASIO_DETAIL_WASI_RESOLVER_HPP diff --git a/tools/boost/asio-wasip2/pollable.cpp b/tools/boost/asio-wasip2/pollable.cpp new file mode 100644 index 00000000..3915319c --- /dev/null +++ b/tools/boost/asio-wasip2/pollable.cpp @@ -0,0 +1,77 @@ +// 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) + +#include +#include +#include +#include +#include +#include + +// These private declarations are pinned to the wasi-libc shipped in SDK 34.0. +// Keep the bridge in one translation unit; no private ABI reaches a user header. +extern "C" { +// The pinned C headers require this exact macro name. +// NOLINTNEXTLINE(readability-identifier-naming) +#define hidden __attribute__((visibility("hidden"))) +#include "wasi-libc/wasi/descriptor_table.h" +#undef hidden +} + +#if !defined(__wasip2__) || __wasi_sdk_major__ != 34 +#error "The WASIp2 pollable bridge requires the pinned wasi-sdk 34.0 ABI" +#endif +static_assert(std::string_view(__wasi_sdk_version__) == "34.0", + "Revalidate the pollable bridge before changing wasi-sdk"); + +namespace { +using storage_type = webcpp::asio::detail::wasi_pollable_descriptor; + +struct descriptor_storage { + descriptor_refcnt_t references; + storage_type* owner; +}; + +static_assert(offsetof(descriptor_storage, references) == 0); +static_assert(sizeof(descriptor_storage) <= sizeof(storage_type::opaque)); +static_assert(alignof(descriptor_storage) <= alignof(storage_type)); + +void release_storage(void* value) { + // The Asio operation owns storage and releases it only after close. + auto* descriptor = static_cast(value); + descriptor->owner->active = false; + descriptor->~descriptor_storage(); +} + +int register_poll(void* value, poll_state_t* state, short events) { + if ((static_cast(events) & ~static_cast(POLLRDNORM)) != 0) { + errno = EOPNOTSUPP; + return -1; + } + return __wasilibc_poll_add( + state, POLLRDNORM, + poll_borrow_pollable_t{static_cast(value)->owner->handle}); +} + +constexpr descriptor_vtable_t operations = []() constexpr noexcept { + descriptor_vtable_t value{}; + value.free = release_storage; + value.poll_register = register_poll; + return value; +}(); +} // namespace + +extern "C" int webcpp_asio_wasi_pollable_descriptor(storage_type* storage) { + if (storage == nullptr || storage->active) { + errno = EINVAL; + return -1; + } + auto* descriptor = + ::new (storage->opaque.data()) descriptor_storage{.references = {0}, .owner = storage}; + storage->active = true; + return descriptor_table_insert( + {.data = &descriptor->references, .vtable = const_cast(&operations)}); +} diff --git a/tools/boost/asio-wasip2/run.sh b/tools/boost/asio-wasip2/run.sh new file mode 100755 index 00000000..840d0fc7 --- /dev/null +++ b/tools/boost/asio-wasip2/run.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env sh +# 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) + +# P2 regression programs use loopback peers and host name lookup. +# Application deployments should grant only the capabilities they need. +exec wasmtime run -S inherit-network=y -S allow-ip-name-lookup=y \ + -W timeout=60s "$@" diff --git a/tools/boost/asio-wasip2/verify.py b/tools/boost/asio-wasip2/verify.py new file mode 100644 index 00000000..ad325278 --- /dev/null +++ b/tools/boost/asio-wasip2/verify.py @@ -0,0 +1,61 @@ +#!/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) +"""Verify the private wasi-libc ABI used by the P2 pollable descriptor bridge.""" +import argparse +import hashlib +import json +from pathlib import Path + + +def verify(sdk: Path, bundle: Path): + manifest = json.loads((bundle / 'wasi-libc/manifest.json').read_text()) + version = (sdk / 'VERSION').read_text().splitlines() + expected = 'wasi-libc: ' + manifest['commit'][:12] + if not version or version[0] != manifest['sdk'] or expected not in version: + raise ValueError('WASIp2 pollables require wasi-sdk ' + manifest['sdk'] + + ' with ' + expected + '; revalidate the bridge before changing SDK') + verify_bundle(bundle) + + +def verify_bundle(bundle: Path): + manifest = json.loads((bundle / 'wasi-libc/manifest.json').read_text()) + expected_files = set(manifest['files']) | {'manifest.json'} + for path in (bundle / 'wasi-libc').rglob('*'): + if path.is_symlink(): + raise ValueError('private wasi-libc snapshot contains a symlink: ' + str(path)) + relative = path.relative_to(bundle / 'wasi-libc').as_posix() + if path.is_file() and relative not in expected_files: + raise ValueError('private wasi-libc snapshot contains an unlisted file: ' + str(path)) + for name, expected_hash in manifest['files'].items(): + path = Path(name) + if path.is_absolute() or '..' in path.parts: + raise ValueError('invalid private ABI manifest path') + actual = hashlib.sha256((bundle / 'wasi-libc' / path).read_bytes()).hexdigest() + if actual != expected_hash: + raise ValueError('private wasi-libc header changed: ' + name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--sdk', type=Path) + parser.add_argument('--bundle', type=Path, default=Path(__file__).resolve().parent) + parser.add_argument('--stamp', type=Path) + args = parser.parse_args() + try: + if args.sdk: + verify(args.sdk, args.bundle) + else: + verify_bundle(args.bundle) + except (OSError, ValueError) as error: + parser.exit(1, str(error) + '\n') + if args.stamp: + args.stamp.parent.mkdir(parents=True, exist_ok=True) + args.stamp.write_text('WASIp2 pollable ABI verified\n') + + +if __name__ == '__main__': + main() diff --git a/tools/boost/asio-wasip2/verify_test.py b/tools/boost/asio-wasip2/verify_test.py new file mode 100644 index 00000000..c1b54c70 --- /dev/null +++ b/tools/boost/asio-wasip2/verify_test.py @@ -0,0 +1,48 @@ +# 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) +import shutil +import tempfile +import unittest +from pathlib import Path +from verify import verify, verify_bundle + +HERE = Path(__file__).resolve().parent + + +class ABI(unittest.TestCase): + def test_unlisted_and_symlinked_files_are_refused(self): + with tempfile.TemporaryDirectory() as temporary: + bundle = Path(temporary) + shutil.copytree(HERE / 'wasi-libc', bundle / 'wasi-libc') + extra = bundle / 'wasi-libc/unlisted.h' + extra.write_text('// Not part of the pinned ABI.\n') + with self.assertRaisesRegex(ValueError, 'unlisted'): + verify_bundle(bundle) + extra.unlink() + extra.symlink_to('wasi/poll.h') + with self.assertRaisesRegex(ValueError, 'symlink'): + verify_bundle(bundle) + + def test_sdk_revision_and_header_integrity(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + sdk, bundle = root / 'sdk', root / 'bundle' + sdk.mkdir() + shutil.copytree(HERE / 'wasi-libc', bundle / 'wasi-libc') + (sdk / 'VERSION').write_text('34.0\nwasi-libc: 2e6fb9d8ee0c\n') + verify(sdk, bundle) + (sdk / 'VERSION').write_text('34.0\nwasi-libc: different\n') + with self.assertRaisesRegex(ValueError, 'revalidate'): + verify(sdk, bundle) + (sdk / 'VERSION').write_text('34.0\nwasi-libc: 2e6fb9d8ee0c\n') + with (bundle / 'wasi-libc/wasi/descriptor_table.h').open('a') as header: + header.write('\n/* incompatible edit */\n') + with self.assertRaisesRegex(ValueError, 'header changed'): + verify(sdk, bundle) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/boost/asio-wasip2/wasi-libc/LICENSE b/tools/boost/asio-wasip2/wasi-libc/LICENSE new file mode 100644 index 00000000..d3e73789 --- /dev/null +++ b/tools/boost/asio-wasip2/wasi-libc/LICENSE @@ -0,0 +1,17 @@ +wasi-libc as a whole is multi-licensed under the +Apache License v2.0 with LLVM Exceptions, the Apache License v2.0, and +the MIT License. See the LICENSE-APACHE-LLVM, LICENSE-APACHE and LICENSE-MIT +files, respectively, for details. + +Portions of this software are derived from third-party works covered by +their own licenses: + +dlmalloc/ - CC0; see the notice in malloc.c for details +emmalloc/ - MIT; see the notice in emmalloc.c for details +libc-bottom-half/cloudlibc/ - BSD-2-Clause; see the LICENSE file for details +libc-top-half/musl/ - MIT; see the COPYRIGHT file for details +fts/musl-fts/ - BSD-3-Clause; see the COPYING file for details + +wasi-libc's changes to these files are multi-licensed under the +Apache License v2.0 with LLVM Exceptions, the Apache License v2.0, +the MIT License, and the original licenses of the third-party works. diff --git a/tools/boost/asio-wasip2/wasi-libc/LICENSE-APACHE b/tools/boost/asio-wasip2/wasi-libc/LICENSE-APACHE new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/tools/boost/asio-wasip2/wasi-libc/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT b/tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/tools/boost/asio-wasip2/wasi-libc/manifest.json b/tools/boost/asio-wasip2/wasi-libc/manifest.json new file mode 100644 index 00000000..732e7eed --- /dev/null +++ b/tools/boost/asio-wasip2/wasi-libc/manifest.json @@ -0,0 +1,12 @@ +{ + "repository": "https://github.com/WebAssembly/wasi-libc", + "commit": "2e6fb9d8ee0cdf9e431fbcabe8af3115de000a13", + "sdk": "34.0", + "files": { + "wasi/descriptor_table.h": "21938b584128a3c17be772f883f3104803cfe2096bcf7e08f6a0e7d509cc2aa3", + "wasi/poll.h": "6417072eda33738773d54747a7901c1583e9ae2d22b206116d8e1e082d6ef14c", + "LICENSE": "2711a8b5a5cdfef0e639f96c1aca12ae23d7d64a02d0507f1bdf14d2b27bbc3a", + "LICENSE-MIT": "23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3", + "LICENSE-APACHE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2" + } +} diff --git a/tools/boost/asio-wasip2/wasi-libc/wasi/descriptor_table.h b/tools/boost/asio-wasip2/wasi-libc/wasi/descriptor_table.h new file mode 100644 index 00000000..b06b8e6d --- /dev/null +++ b/tools/boost/asio-wasip2/wasi-libc/wasi/descriptor_table.h @@ -0,0 +1,368 @@ +#ifndef DESCRIPTOR_TABLE_H +#define DESCRIPTOR_TABLE_H + +#include + +#ifndef __wasip1__ +#include +#include +#include +#include +#include +#include + +#ifdef __wasip3__ + +#include "lock.h" + +/// The stream is complete and no further operations are allowed on it. +#define WASIP3_IO_DONE (1 << 0) +/// An I/O operation, be it a read or write, is in flight. +#define WASIP3_IO_INPROGRESS (1 << 1) +/// The in-flight I/O operation is a zero-length operation. This means that if +/// it's finished we expect that the next operation finishes immediately. +#define WASIP3_IO_ZERO_INPROGRESS (1 << 2) +/// A zero-sized in-flight I/O operation just finished so the next I/O op +/// should finish immediately. If it doesn't it'll turn on the next flag. +#define WASIP3_IO_SHOULD_BE_READY (1 << 3) +/// This stream isn't compatible with zero-length reads/writes signaling +/// readiness, so libc must buffer data internally for reads/writes. +#define WASIP3_IO_MUST_BUFFER (1 << 4) +/// A thread is actively blocked in an I/O operation and no other operation +/// can be performed. +#define WASIP3_IO_BLOCKED (1 << 5) + +/// Helper structure to package up state related to a wasip3 `stream`. +/// +/// This is used by various helpers to coordinate reading/writing/etc on a +/// stream. This simultaneously represents both readers and writers. +typedef struct wasip3_io_state_t { + uint32_t stream; + /// Bitset of `WASIP3_IO_*` flags. + uint32_t flags; + /// Malloc'd buffer used for reads/writes. NULL if not present. + uint8_t *buf; + /// Start of `buf` that has data in-flight or ready. + size_t buf_start; + /// End of `buf` that has data in-flight or ready. + size_t buf_end; + +#ifdef _REENTRANT + /// Pointer to the containing object's lock, which protects all the state + /// above. This is acquired and held through all I/O operations, but dropped + /// while an operation that may indefinitely block is in flight. + volatile int *lock; + /// An internal lock used to hold a queue of threads waiting to do blocking + /// I/O while some other thread is already doing blocking I/O. + DECLARE_STRONG_LOCK(blocking_lock); + /// Number of threads that are waiting on `blocking_lock` to take their turn + /// doing blocking I/O. This count notably disallows a concurrent + /// shutdown/reset/etc of this stream, for example `shutdown` fails while + /// something is blocking and so does `seek`. + size_t blocking_waiters; +#endif +} wasip3_io_state_t; + +static inline void __wasip3_io_state_init(wasip3_io_state_t *state, + uint32_t stream) { + assert(stream != 0); + memset(state, 0, sizeof(*state)); + state->stream = stream; +} + +/// Initializes `state` with the `stream` provided, using `lock` — the +/// containing object's lock — to protect the state's fields. +#ifdef _REENTRANT +#define wasip3_io_state_init(state, stream, lock_ptr) \ + do { \ + __wasip3_io_state_init(state, stream); \ + (state)->lock = &(lock_ptr); \ + } while (0) +#else +#define wasip3_io_state_init(state, stream, lock) \ + __wasip3_io_state_init(state, stream) +#endif + +/// Tests whether `state` has been initialized with a stream yet. +static inline bool wasip3_io_state_present(wasip3_io_state_t *state) { + return state->stream != 0; +} + +/// Closes out the streams/etc internal to `state`. +/// +/// Internally the stream must be a reader-half of a `stream`. +static inline void wasip3_read_state_close(wasip3_io_state_t *state) { + STRONG_ASSERT_EMPTY(state->blocking_lock); + if (state->flags & WASIP3_IO_INPROGRESS) + filesystem_stream_u8_cancel_read(state->stream); + if (state->buf) + free(state->buf); + if (state->stream != 0) + filesystem_stream_u8_drop_readable(state->stream); + memset(state, 0, sizeof(*state)); +} + +/// Closes out the streams/etc internal to `state`. +/// +/// Internally the stream must be a writer-half of a `stream`. +/// +/// Note that unlike `wasip3_read_state_close` this first blocks to flush any +/// buffered-but-unsent data, so this is a blocking operation even when the +/// descriptor is in nonblocking mode. +/// +/// This requires `*state->lock` to be held by the caller, and that lock may be +/// dropped and reacquired while blocking. +#define wasip3_write_state_close __wasilibc_write_state_close +hidden void wasip3_write_state_close(wasip3_io_state_t *state); + +/// Tests whether there is active or pending blocking I/O on this stream which +/// notably should prevent it from being closed. +static inline bool wasip3_io_state_blocked(wasip3_io_state_t *state) { +#ifdef _REENTRANT + return (state->flags & WASIP3_IO_BLOCKED) || state->blocking_waiters > 0; +#else + (void)state; + return false; +#endif +} +#endif + +// Metadata for WASI reads which is used to delegate to `__wasilibc_read(...)` +// to perform the actual read of a stream. +typedef struct wasi_read_t { + // An optional pointer to the internal offset of this stream, updated on + // successful reads. + off_t *offset; + // Whether or not this read will use blocking I/O. + bool blocking; + // The timeout, in nanoseconds, for this operation. + monotonic_clock_duration_t timeout; +#ifdef __wasip2__ + // The `wasi:io/streams.input-stream` that this is reading from. + streams_borrow_input_stream_t input; + // A required pointer to an owned pollable for `input`. This is lazily + // initialized as-necessary. + poll_own_pollable_t *pollable; +#else + wasip3_io_state_t *state; + + // A callback/ptr pair to invoke when EOF is reached to set errno and return + // an error code. + int (*eof)(void *); + void *eof_data; +#endif +} wasi_read_t; + +// Same as `wasip_read_t`, but for writes. +typedef struct wasi_write_t { + off_t *offset; + bool blocking; + monotonic_clock_duration_t timeout; + +#ifdef __wasip2__ + streams_borrow_output_stream_t output; + poll_own_pollable_t *pollable; +#else + wasip3_io_state_t *state; + // A callback/ptr pair to invoke when EOF is reached to set errno and return + // an error code. + int (*eof)(void *); + void *eof_data; +#endif +} wasi_write_t; + +/** + * Operations that are required of all descriptors registered as file + * descriptors. + * + * This structure is used to dynamically dispatch operations various I/O + * objects like files and sockets. Functions pointers below can all be `NULL` + * except for `free`. These are the implementation of the corresponding + * functions in libc. + * + * All functions below communicate errors through the return value. A -1 return + * value indicates that an error happened and that `errno` is set. + */ +typedef struct descriptor_vtable_t { + /// Deallocates the parameter provided, closing all resources as well. + void (*free)(void *); + + // ===================================================================== + // Generic I/O + + /// Looks up metadata to perform a read operation for this stream. This is + /// used to implement the `read` syscall, for example, and is also used with + /// `poll` when waiting for readability. + /// + /// When threading is enabled for WASIp3+ this additionally acquires the + /// internal lock for the object and the caller must unlock the + /// `read->state->lock` object on success. On failure no locks are held when + /// this returns. + int (*get_read_stream)(void *, wasi_read_t *); + /// Same as `get_read_stream`, but for output streams. + int (*get_write_stream)(void *, wasi_write_t *); + + /// Sets the nonblocking flag for this object to the specified value. + int (*set_blocking)(void *, bool); + + /// Implementation of `fstat` the function call, used to learn about file + /// descriptors. + int (*fstat)(void *, struct stat *); + + // ===================================================================== + // File-related APIs + + /// Looks up a `wasi:filesystem/types.descriptor`, if present, from this + /// object. + int (*get_file)(void *, filesystem_borrow_descriptor_t *); + /// Implementation of `lseek`-the-function. + off_t (*seek)(void *, off_t, int); + /// Implementation of `fnctl(fd, F_GETFL)`. + int (*fcntl_getfl)(void *); + /// Implementation of `fnctl(fd, F_SETFL)`. + int (*fcntl_setfl)(void *, int); + /// Implementation of `isatty`-the-function. + int (*isatty)(void *); + + // ===================================================================== + // Sockets-related APIs + + /// Implementation of `accept4`-the-function. + int (*accept4)(void *, struct sockaddr *addr, socklen_t *addrlen, int flags); + /// Implementation of `bind`-the-function. + int (*bind)(void *, const struct sockaddr *addr, socklen_t addrlen); + /// Implementation of `connect`-the-function. + int (*connect)(void *, const struct sockaddr *addr, socklen_t addrlen); + /// Implementation of `getsockname`-the-function. + int (*getsockname)(void *, struct sockaddr *addr, socklen_t *addrlen); + /// Implementation of `getpeername`-the-function. + int (*getpeername)(void *, struct sockaddr *addr, socklen_t *addrlen); + /// Implementation of `listen`-the-function. + int (*listen)(void *, int backlog); + /// Implementation of `recvfrom`-the-function. + ssize_t (*recvfrom)(void *, void *buffer, size_t length, int flags, + struct sockaddr *addr, socklen_t *addrlen); + /// Implementation of `sendto`-the-function. + ssize_t (*sendto)(void *, const void *buffer, size_t length, int flags, + const struct sockaddr *addr, socklen_t addrlen); + /// Implementation of `shutdown`-the-function. + int (*shutdown)(void *, int how); + /// Implementation of `getsockopt`-the-function. + int (*getsockopt)(void *, int level, int optname, void *optval, + socklen_t *optlen); + /// Implementation of `setsockopt`-the-function. + int (*setsockopt)(void *, int level, int optname, const void *optval, + socklen_t optlen); + + // ===================================================================== + // `poll`-related APIs + + /// Invoked when this descriptor is passed as one of the objects to the + /// `poll` function. The `wasi/poll.h` header has functions that can operate + /// on the `state` provided. This should invoke `__wasilibc_poll_add`, for + /// example, for any event in `events` with a pollable derived from this + /// object. + /// + /// If this function is not provided then `poll` will use `get_read_stream` + /// and `get_write_stream`, if present, to handle `POLL{RD,WR}NORM` events. + int (*poll_register)(void *, poll_state_t *state, short events); + +#ifdef __wasip2__ + /// Invoked when `poll` has already run and detected that this object was + /// ready. The `events` provided are the same as those provided to + /// `__wasilibc_poll_add` originally. This function should call + /// `__wasilibc_poll_ready` for example to indicate that the underlying + /// `pollfd` structure has some events ready. + /// + /// If this function is not provided then `events` will automatically + /// be placed into the `revents` field of `pollfd`. + int (*poll_finish)(void *, poll_state_t *state, short events); +#endif // __wasip2__ +} descriptor_vtable_t; + +/// Reference count structure that must be at the beginning of all data passed +/// to `descriptor_table_insert`. +typedef struct { + unsigned cnt; +} descriptor_refcnt_t; + +/// A "fat pointer" which is placed inside of the descriptor table. +typedef struct { + /// Arbitrary descriptor-specific data passed to `vtable` function pointer. + descriptor_refcnt_t *data; + /// Definition of various operations for this descriptor. + descriptor_vtable_t *vtable; +} descriptor_table_entry_t; + +/// Inserts the `entry` provided into the descriptor table, returning the +/// integer file descriptor used to refer to it. +/// +/// Note that `entry` is expected to have a reference count of 0 (freshly +/// initialized), and it'll get initialized within this function. +/// +/// On failure returns -1, sets `errno`, and runs `entry`'s destructor. +hidden int descriptor_table_insert(descriptor_table_entry_t entry); + +/// Operations that `descriptor_table_dup` supports. +enum dup_op_t { + /// `dup` function, no `arg` + DUP_OP_DUP, + /// `dup2` function, `arg` is specified + DUP_OP_DUP2, + /// `dup3` function, `arg` is specified + DUP_OP_DUP3, + /// `F_DUPFD` fcntl, `arg` is specified + DUP_OP_DUPFD, +}; + +/// Performs a `dup`-style operation. +hidden int descriptor_table_dup(int fd, enum dup_op_t op, int arg); + +/// Looks up a descriptor by its file descriptor. +/// +/// On success returns 0 and `entry` is filled in with a strong reference to +/// the new entry. Callers must call `descriptor_table_entry_dec` when they're +/// done with the entry. On failure -1 is returned an `errno` is set. +hidden int descriptor_table_get(int fd, descriptor_table_entry_t *entry); + +/// Removes the specified file descriptor from the table. +/// +/// On success returns 0 and runs the entry's destructor. On failure returns -1 +/// and sets `errno`. +hidden int descriptor_table_remove(int fd); + +/// Removes all file descriptors from the table, running their destructors. +hidden void descriptor_table_clear(); + +/// Increment the reference count of the `entry` provided. +static inline void descriptor_table_entry_inc(descriptor_table_entry_t entry) { + assert(entry.data->cnt > 0); + entry.data->cnt++; +} + +/// Slow-path deallocation routine of `descriptor_table_entry_dec`. +/// +/// Assumes refcount is already 0. +hidden void __wasilibc_descriptor_deallocate(descriptor_table_entry_t entry); + +/// Decrement the reference count of the `entry` provided, running deallocation +/// if the cnt reaches 0. +static inline void descriptor_table_entry_dec(descriptor_table_entry_t entry) { + assert(entry.data->cnt > 0); + entry.data->cnt--; + if (entry.data->cnt == 0) + __wasilibc_descriptor_deallocate(entry); +} + +// Helper function used at program-exit time to assert that there are no +// descriptor leaks when libc is itself built in debug mode. Note that this is +// a noop when compiled with `-DNDEBUG`. +#ifdef NDEBUG +static inline void __wasilibc_assert_no_descriptor_leaks(void) {} +#else +void __wasilibc_assert_no_descriptor_leaks(void); +#endif + +#endif // __wasip1__ + +#endif // DESCRIPTOR_TABLE_H diff --git a/tools/boost/asio-wasip2/wasi-libc/wasi/poll.h b/tools/boost/asio-wasip2/wasi-libc/wasi/poll.h new file mode 100644 index 00000000..39ac8f89 --- /dev/null +++ b/tools/boost/asio-wasip2/wasi-libc/wasi/poll.h @@ -0,0 +1,79 @@ +#ifndef WASI_POLL_H +#define WASI_POLL_H + +#include + +#ifndef __wasip1__ + +#include +#include + +/// Opaque state that the `poll` function manages for itself. +typedef struct poll_state_t poll_state_t; + +/// Indicates that the `pollfd` which `state` refers to is ready with `events`. +/// +/// If called during `poll_register` then `wasi:io/poll.poll` won't be invoked, +/// and otherwise sets the `revents` field after `poll` has run. +void __wasilibc_poll_ready(poll_state_t *state, short events); + +#ifdef __wasip2__ + +/// Adds the `pollable` to the `state` provided. +/// +/// This will add a `pollable` to get passed to `wasi:io/poll.poll`. If that +/// `pollable` becomes ready the `events` specified here will be used to set +/// `revents` in the final `pollfd`. +/// +/// The `state` value internally tracks which `pollfd` is being used. +int __wasilibc_poll_add(poll_state_t *state, short events, + poll_borrow_pollable_t pollable); + +/// Helper function to lazily subscribe to an input stream and call +/// `__wasilibc_poll_add`. +static inline int +__wasilibc_poll_add_input_stream(poll_state_t *state, + streams_borrow_input_stream_t input_stream, + poll_own_pollable_t *pollable) { + if (pollable->__handle == 0) + *pollable = streams_method_input_stream_subscribe(input_stream); + return __wasilibc_poll_add(state, POLLRDNORM, + poll_borrow_pollable(*pollable)); +} + +/// Helper function to lazily subscribe to an output stream and call +/// `__wasilibc_poll_add`. +static inline int +__wasilibc_poll_add_output_stream(poll_state_t *state, + streams_borrow_output_stream_t output_stream, + poll_own_pollable_t *pollable) { + if (pollable->__handle == 0) + *pollable = streams_method_output_stream_subscribe(output_stream); + return __wasilibc_poll_add(state, POLLWRNORM, + poll_borrow_pollable(*pollable)); +} + +#endif // __wasip2__ + +#ifdef __wasip3__ + +/// Callback invoked after `__wasilibc_poll_add` when an event is ready. +/// +/// This additionally serves as a destructor of sorts where if no event arrives +/// before the `poll` is torn down then this is invoked with `state` and +/// `event` as NULL. +typedef void (*poll_ready_t)(void *data, poll_state_t *state, + wasip3_event_t *event); + +/// Adds the `waitable` to the poll `state`. +/// +/// When `waitable` receives an event it'll invoke `ready` with `ready_data`, +/// the poll state, and the event that happened. +int __wasilibc_poll_add(poll_state_t *state, uint32_t waitable, + poll_ready_t ready, void *ready_data); + +#endif // __wasip3__ + +#endif // not(__wasip1__) + +#endif // WASI_POLL_H diff --git a/tools/boost/asio-wasip3/Jamfile b/tools/boost/asio-wasip3/Jamfile index d6e03f0f..9bbe3c98 100644 --- a/tools/boost/asio-wasip3/Jamfile +++ b/tools/boost/asio-wasip3/Jamfile @@ -10,6 +10,7 @@ import make ; import modules ; import path ; import webcpp-wasi ; +import webcpp-target ; project /webcpp/asio-wasip3 ; path-constant BUNDLE : . ; @@ -34,6 +35,10 @@ actions prepare rule configuration ( properties * ) { + if [ webcpp-target.target-of $(properties) ] = wasip2 && multi in $(properties) + { + errors.user-error "webcpp::asio: WASIp2 supports threading=single only; use WASIp3 for the cooperative thread profile." ; + } if single in $(properties) { return BOOST_ASIO_DISABLE_THREADS ; diff --git a/tools/boost/asio-wasip3/README.md b/tools/boost/asio-wasip3/README.md index 592c3cbd..c6884aac 100644 --- a/tools/boost/asio-wasip3/README.md +++ b/tools/boost/asio-wasip3/README.md @@ -1,4 +1,4 @@ -# Boost.Asio WASIp3 compatibility patch +# Boost.Asio WASI compatibility patch This bundle adapts Boost.Asio 1.92.0's platform layer, keeping its scheduler, select reactor, operation objects and associated allocators. The source headers @@ -6,7 +6,7 @@ retain Christopher M. Kohlhoff's copyright and the Boost Software License 1.0. The upstream baseline is the Boost 1.92.0 distribution; `manifest.json` pins each input and patched header by SHA-256. -`/webcpp/asio//asio` selects this bundle only for `clang-wasip3`. `prepare.py` +`/webcpp/asio//asio` selects this bundle for `clang-wasip2` and `clang-wasip3`. `prepare.py` checks the version and every input hash before applying the patch in a temporary directory. It verifies every output hash before replacing private headers under `bin/boost-asio-wasip3/include`. It does not modify the source installation and @@ -16,18 +16,18 @@ private directory and rebuild after changing the set of patched headers. Only patched headers are copied; other headers continue to come from Boost. `/webcpp/asio-wasip3//host-headers` exposes association and completion-token -traits to the single-threaded WASIp2 host HTTP scheduler. The only platform -change selected on WASIp2 is the signal-free wait in `null_event`: WASI uses -`poll` instead of the unavailable POSIX `pause`. This does not enable the Asio -socket reactor on WASIp2. Host operations supply their own executor and never -fall back to `system_executor` or an operating-system thread pool. +traits to the single-threaded WASIp2 host HTTP scheduler without selecting guest +network capabilities. The full Asio P2 target also adds `asio-wasip2`'s compiled +pollable descriptor bridge and asynchronous forward resolver. Its single-thread +reactor needs no pipe interrupter; the P2 multi-thread profile is explicitly refused. +Host operations continue to use their own executor. The changes address missing POSIX signals/interface names, no-thread waiting, thread-safe signal-blocker selection, shutdown error mapping, unavailable socket options, scalar socket I/O, and resolver thread-pool initiation without threads. WASI has no process signals, so the port does not add `MSG_NOSIGNAL`, which the current UDP libc implementation rejects. TCP sequences use partial transfers. -For UDP `send_to`/`async_send_to`, the WASIp3-only service patch gathers the full +For UDP `send_to`/`async_send_to`, the P2/P3 service patch gathers the full buffer sequence before iovec truncation, then sends one contiguous datagram. Multiple nonempty buffers require a copy, allocated through the context for synchronous sends and the handler's associated allocator for asynchronous sends. diff --git a/tools/boost/asio-wasip3/boost-1.92.patch b/tools/boost/asio-wasip3/boost-1.92.patch index 949fb2d2..24445210 100644 --- a/tools/boost/asio-wasip3/boost-1.92.patch +++ b/tools/boost/asio-wasip3/boost-1.92.patch @@ -8,7 +8,7 @@ + for (; iter != end && count_ < max_buffers; ++iter) { Buffer buffer(*iter); -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + if (buffer.size() == 0) + continue; +#endif @@ -22,7 +22,7 @@ static bool all_empty(Iterator begin, Iterator end) { Iterator iter = begin; -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + for (; iter != end; ++iter) +#else std::size_t i = 0; @@ -38,9 +38,9 @@ # define BOOST_ASIO_HAS_BOOST_CONFIG 1 #endif // defined(BOOST_ASIO_STANDALONE) + -+// WASIp3 supplies sockets and cooperative threads, but no process signals, ++// WASIp2/P3 supply sockets (P3 also cooperative threads), but no process signals, +// interface enumeration, Unix domain sockets or serial devices. -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) +# if !defined(_REENTRANT) && !defined(BOOST_ASIO_DISABLE_THREADS) +# define BOOST_ASIO_DISABLE_THREADS 1 +# endif @@ -65,27 +65,36 @@ // Kernel support for MSG_NOSIGNAL. -#if !defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if !defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) && !defined(__wasip3__) ++#if !defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) && !(defined(__wasip2__) || defined(__wasip3__)) # if defined(__linux__) || defined(__NetBSD__) # define BOOST_ASIO_HAS_MSG_NOSIGNAL 1 # elif defined(_POSIX_VERSION) --- a/boost/asio/detail/impl/null_event.ipp +++ b/boost/asio/detail/impl/null_event.ipp -@@ -23,6 +23,9 @@ +@@ -23,6 +23,12 @@ # include #else # include +# if defined(__wasip2__) || defined(__wasip3__) +# include ++# endif ++# if defined(__wasip2__) ++# include +# endif # if defined(__hpux) # include # endif -@@ -45,7 +48,12 @@ +@@ -45,7 +51,18 @@ #elif defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) ::Sleep(INFINITE); #else -+#if defined(__wasip2__) || defined(__wasip3__) ++#if defined(__wasip2__) ++ // P2 rejects an empty poll list. A clock resource permits an idle wait ++ // without repeatedly waking the single-thread scheduler. ++ poll_own_pollable_t idle = ::monotonic_clock_subscribe_instant(UINT64_MAX); ++ ::poll_method_pollable_block(::poll_borrow_pollable(idle)); ++ ::poll_pollable_drop_own(idle); ++#elif defined(__wasip3__) + // Wait through the Component Model rather than a nonexistent POSIX signal. + ::poll(0, 0, -1); +#else @@ -100,7 +109,7 @@ shutdown_(false) { work_scheduler_.work_started(); -+#if !defined(__wasip3__) || defined(BOOST_ASIO_HAS_THREADS) ++#if !(defined(__wasip2__) || defined(__wasip3__)) || defined(BOOST_ASIO_HAS_THREADS) if (num_work_threads_ > 0) start_work_threads(); else @@ -113,7 +122,7 @@ void resolver_thread_pool::start_resolve_op(resolve_op* op) { -+#if !defined(__wasip3__) || defined(BOOST_ASIO_HAS_THREADS) ++#if !(defined(__wasip2__) || defined(__wasip3__)) || defined(BOOST_ASIO_HAS_THREADS) if (scheduler_locking_) { start_work_threads(); @@ -142,7 +151,7 @@ { -#if defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) +#if defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) \ -+ || defined(__wasip3__) ++ || (defined(__wasip2__) || defined(__wasip3__)) (void)(af); (void)(type); (void)(protocol); @@ -151,7 +160,7 @@ } -#if defined(SIOCATMARK) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + ec = boost::asio::error::operation_not_supported; + int value = 0; +#elif defined(SIOCATMARK) @@ -164,7 +173,7 @@ } + +#if !defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) +// WASI currently lacks sendmsg/recvmsg. Stream operations may complete after +// one nonempty buffer. Datagram operations must never split a message. +inline bool wasi_buffer(const msghdr* msg, void*& data, size_t& size, int s) @@ -205,7 +214,7 @@ + size_t size; + if (!wasi_buffer(msg, data, size, s)) + return -1; -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char empty_buffer = 0; + if (!data && !size) + data = &empty_buffer; @@ -224,7 +233,7 @@ + size_t size; + if (!wasi_buffer(msg, data, size, s)) + return -1; -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char empty_buffer = 0; + if (!data && !size) + data = &empty_buffer; @@ -241,7 +250,7 @@ msghdr msg = msghdr(); msg.msg_iov = bufs; msg.msg_iovlen = static_cast(count); -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + signed_size_type result = wasi_recvmsg(s, &msg, flags); +#else signed_size_type result = ::recvmsg(s, &msg, flags); @@ -253,7 +262,7 @@ boost::asio::error::clear(ec); return bytes_transferred; #else // defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char empty_buffer = 0; + if (!data && !size) + data = &empty_buffer; @@ -265,7 +274,7 @@ msg.msg_namelen = static_cast(*addrlen); msg.msg_iov = bufs; msg.msg_iovlen = static_cast(count); -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + signed_size_type result = wasi_recvmsg(s, &msg, flags); +#else signed_size_type result = ::recvmsg(s, &msg, flags); @@ -277,7 +286,7 @@ inline signed_size_type call_recvfrom(SockLenType msghdr::*, socket_type s, void* data, size_t size, int flags, void* addr, std::size_t* addrlen) { -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char empty_buffer = 0; + if (!data && !size) + data = &empty_buffer; @@ -289,7 +298,7 @@ msghdr msg = msghdr(); msg.msg_iov = bufs; msg.msg_iovlen = static_cast(count); -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + signed_size_type result = wasi_recvmsg(s, &msg, in_flags); +#else signed_size_type result = ::recvmsg(s, &msg, in_flags); @@ -301,7 +310,7 @@ #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) flags |= MSG_NOSIGNAL; #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + signed_size_type result = wasi_sendmsg(s, &msg, flags); +#else signed_size_type result = ::sendmsg(s, &msg, flags); @@ -313,7 +322,7 @@ #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) flags |= MSG_NOSIGNAL; #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char empty_buffer = 0; + if (!data && !size) + data = &empty_buffer; @@ -325,7 +334,7 @@ #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) flags |= MSG_NOSIGNAL; #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + signed_size_type result = wasi_sendmsg(s, &msg, flags); +#else signed_size_type result = ::sendmsg(s, &msg, flags); @@ -337,7 +346,7 @@ socket_type s, const void* data, size_t size, int flags, const void* addr, std::size_t addrlen) { -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char empty_buffer = 0; + if (!data && !size) + data = &empty_buffer; @@ -349,7 +358,7 @@ return socket_error_retval; } -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + if (level == SOL_SOCKET && optname < 0) + { + ec = boost::asio::error::operation_not_supported; @@ -374,7 +383,7 @@ return socket_error_retval; } + -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + if (level == SOL_SOCKET && optname < 0) + { + ec = boost::asio::error::operation_not_supported; @@ -388,7 +397,7 @@ if (result != 0 && af == BOOST_ASIO_OS_DEF(AF_INET6) && scope_id != 0) { using namespace std; // For strcat and sprintf. -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + char if_name[22] = "%"; +#else char if_name[(IF_NAMESIZE > 21 ? IF_NAMESIZE : 21) + 1] = "%"; @@ -406,7 +415,7 @@ *scope_id = 0; if (if_name != 0) { -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + // Reject names and malformed numeric scopes instead of silently using 0. + const char* digit = if_name + 1; + unsigned long value = 0; @@ -445,7 +454,7 @@ || defined(BOOST_ASIO_WINDOWS_RUNTIME) \ || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) \ - || defined(__SYMBIAN32__) -+ || defined(__SYMBIAN32__) || defined(__wasip3__) ++ || defined(__SYMBIAN32__) || (defined(__wasip2__) || defined(__wasip3__)) #include @@ -454,7 +463,7 @@ // || defined(BOOST_ASIO_WINDOWS_RUNTIME) // || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) - // || defined(__SYMBIAN32__) -+ // || defined(__SYMBIAN32__) || defined(__wasip3__) ++ // || defined(__SYMBIAN32__) || (defined(__wasip2__) || defined(__wasip3__)) #endif // BOOST_ASIO_DETAIL_NULL_SIGNAL_BLOCKER_HPP --- a/boost/asio/detail/reactive_socket_sendto_op.hpp @@ -463,7 +472,7 @@ #include #include -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) +# include +# include +# include @@ -477,7 +486,7 @@ BOOST_ASIO_INLINE_NAMESPACE_BEGIN namespace detail { + -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) +// wasi-sdk 34's wasi-libc has sendto but no sendmsg. Sending each buffer +// separately would turn one UDP datagram into several messages. Until libc +// supplies sendmsg, gather the complete sequence BEFORE the native iovec @@ -537,7 +546,7 @@ + boost::asio::const_buffer buffer_; + boost::system::error_code error_; +}; -+#endif // defined(__wasip3__) ++#endif // (defined(__wasip2__) || defined(__wasip3__)) template class reactive_socket_sendto_op_base : public reactor_op @@ -545,7 +554,7 @@ buffers_(buffers), destination_(endpoint), flags_(flags) -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + , wasi_datagram_(false), wasi_invalid_(false) +#endif { @@ -555,7 +564,7 @@ ConstBufferSequence> bufs_type; status result; -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + if (o->wasi_datagram_) + { + if (o->wasi_invalid_) @@ -574,7 +583,7 @@ ConstBufferSequence buffers_; Endpoint destination_; socket_base::message_flags flags_; -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) +protected: + boost::asio::const_buffer wasi_buffer_; + bool wasi_datagram_; @@ -587,14 +596,14 @@ : reactive_socket_sendto_op_base( success_ec, socket, buffers, endpoint, flags, &reactive_socket_sendto_op::do_complete), -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + wasi_storage_(buffers, boost::asio::get_associated_allocator(handler), + endpoint.protocol().type() == SOCK_DGRAM), +#endif handler_(static_cast(handler)), work_(handler_, io_ex) { -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + this->wasi_datagram_ = endpoint.protocol().type() == SOCK_DGRAM; + this->wasi_buffer_ = wasi_storage_.buffer(); + this->wasi_invalid_ = !!wasi_storage_.error(); @@ -608,7 +617,7 @@ } private: -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + // Construct before moving the handler, and free before its upcall through + // the existing operation destruction path, including cancellation/shutdown. + wasi_datagram_buffer> wasi_storage_; @@ -622,7 +631,7 @@ const endpoint_type& destination, socket_base::message_flags flags, boost::system::error_code& ec) { -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + if (impl.protocol_.type() == SOCK_DGRAM) + { + if (impl.socket_ == invalid_socket) @@ -652,7 +661,7 @@ #if !defined(BOOST_ASIO_HAS_THREADS) || defined(BOOST_ASIO_WINDOWS) \ || defined(BOOST_ASIO_WINDOWS_RUNTIME) \ - || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) -+ || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) || defined(__wasip3__) ++ || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) || (defined(__wasip2__) || defined(__wasip3__)) # include #elif defined(BOOST_ASIO_HAS_PTHREADS) # include @@ -661,7 +670,7 @@ #if !defined(BOOST_ASIO_HAS_THREADS) || defined(BOOST_ASIO_WINDOWS) \ || defined(BOOST_ASIO_WINDOWS_RUNTIME) \ - || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) -+ || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) || defined(__wasip3__) ++ || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) || (defined(__wasip2__) || defined(__wasip3__)) typedef null_signal_blocker signal_blocker; #elif defined(BOOST_ASIO_HAS_PTHREADS) typedef posix_signal_blocker signal_blocker; @@ -672,7 +681,7 @@ || defined(__FreeBSD__) || defined(__NetBSD__) \ || defined(__OpenBSD__) || defined(__linux__) \ - || defined(__EMSCRIPTEN__) -+ || defined(__EMSCRIPTEN__) || defined(__wasip3__) ++ || defined(__EMSCRIPTEN__) || (defined(__wasip2__) || defined(__wasip3__)) # include # elif !defined(__SYMBIAN32__) # include @@ -681,7 +690,7 @@ # include # include -# include -+# if !defined(__wasip3__) ++# if !(defined(__wasip2__) || defined(__wasip3__)) +# include +# endif # include @@ -690,7 +699,7 @@ # include # endif -# include -+# if !defined(__wasip3__) ++# if !(defined(__wasip2__) || defined(__wasip3__)) +# include +# endif #endif @@ -701,14 +710,14 @@ # define BOOST_ASIO_OS_DEF_FIONREAD FIONREAD # define BOOST_ASIO_OS_DEF_INADDR_ANY INADDR_ANY -# define BOOST_ASIO_OS_DEF_MSG_OOB MSG_OOB -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_MSG_OOB 0x10000000 +# else +# define BOOST_ASIO_DISABLE_MSG_OOB 1 +# endif # define BOOST_ASIO_OS_DEF_MSG_PEEK MSG_PEEK -# define BOOST_ASIO_OS_DEF_MSG_DONTROUTE MSG_DONTROUTE -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_MSG_DONTROUTE 0x20000000 +# else +# define BOOST_ASIO_DISABLE_MSG_DONTROUTE 1 @@ -723,17 +732,17 @@ -# define BOOST_ASIO_OS_DEF_SO_BROADCAST SO_BROADCAST -# define BOOST_ASIO_OS_DEF_SO_DEBUG SO_DEBUG -# define BOOST_ASIO_OS_DEF_SO_DONTROUTE SO_DONTROUTE -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_BROADCAST (-1) +# else +# define BOOST_ASIO_DISABLE_SO_BROADCAST 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_DEBUG (-2) +# else +# define BOOST_ASIO_DISABLE_SO_DEBUG 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_DONTROUTE (-3) +# else +# define BOOST_ASIO_DISABLE_SO_DONTROUTE 1 @@ -741,12 +750,12 @@ # define BOOST_ASIO_OS_DEF_SO_KEEPALIVE SO_KEEPALIVE -# define BOOST_ASIO_OS_DEF_SO_LINGER SO_LINGER -# define BOOST_ASIO_OS_DEF_SO_OOBINLINE SO_OOBINLINE -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_LINGER (-4) +# else +# define BOOST_ASIO_DISABLE_SO_LINGER 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_OOBINLINE (-5) +# else +# define BOOST_ASIO_DISABLE_SO_OOBINLINE 1 @@ -755,12 +764,12 @@ # define BOOST_ASIO_OS_DEF_SO_RCVBUF SO_RCVBUF -# define BOOST_ASIO_OS_DEF_SO_SNDLOWAT SO_SNDLOWAT -# define BOOST_ASIO_OS_DEF_SO_RCVLOWAT SO_RCVLOWAT -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_SNDLOWAT (-6) +# else +# define BOOST_ASIO_DISABLE_SO_SNDLOWAT 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_RCVLOWAT (-7) +# else +# define BOOST_ASIO_DISABLE_SO_RCVLOWAT 1 @@ -772,7 +781,7 @@ BOOST_ASIO_INLINE_VARIABLE const int max_addr_v4_str_len = INET_ADDRSTRLEN; #if defined(INET6_ADDRSTRLEN) BOOST_ASIO_INLINE_VARIABLE const int max_addr_v6_str_len = -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + INET6_ADDRSTRLEN + 1 + 10; // A decimal 32-bit numeric scope identifier. +#else INET6_ADDRSTRLEN + 1 + IF_NAMESIZE; @@ -785,7 +794,7 @@ # define BOOST_ASIO_OS_DEF_FIONREAD FIONREAD # define BOOST_ASIO_OS_DEF_INADDR_ANY INADDR_ANY -# define BOOST_ASIO_OS_DEF_MSG_OOB MSG_OOB -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_MSG_OOB 0x10000000 +# else +# define BOOST_ASIO_DISABLE_MSG_OOB 1 @@ -793,12 +802,12 @@ # define BOOST_ASIO_OS_DEF_MSG_PEEK MSG_PEEK -# define BOOST_ASIO_OS_DEF_MSG_DONTROUTE MSG_DONTROUTE -# define BOOST_ASIO_OS_DEF_MSG_EOR MSG_EOR -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_MSG_DONTROUTE 0x20000000 +# else +# define BOOST_ASIO_DISABLE_MSG_DONTROUTE 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_MSG_EOR 0x40000000 +# else +# define BOOST_ASIO_DISABLE_MSG_EOR 1 @@ -813,17 +822,17 @@ -# define BOOST_ASIO_OS_DEF_SO_BROADCAST SO_BROADCAST -# define BOOST_ASIO_OS_DEF_SO_DEBUG SO_DEBUG -# define BOOST_ASIO_OS_DEF_SO_DONTROUTE SO_DONTROUTE -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_BROADCAST (-1) +# else +# define BOOST_ASIO_DISABLE_SO_BROADCAST 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_DEBUG (-2) +# else +# define BOOST_ASIO_DISABLE_SO_DEBUG 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_DONTROUTE (-3) +# else +# define BOOST_ASIO_DISABLE_SO_DONTROUTE 1 @@ -831,12 +840,12 @@ # define BOOST_ASIO_OS_DEF_SO_KEEPALIVE SO_KEEPALIVE -# define BOOST_ASIO_OS_DEF_SO_LINGER SO_LINGER -# define BOOST_ASIO_OS_DEF_SO_OOBINLINE SO_OOBINLINE -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_LINGER (-4) +# else +# define BOOST_ASIO_DISABLE_SO_LINGER 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_OOBINLINE (-5) +# else +# define BOOST_ASIO_DISABLE_SO_OOBINLINE 1 @@ -845,12 +854,12 @@ # define BOOST_ASIO_OS_DEF_SO_RCVBUF SO_RCVBUF -# define BOOST_ASIO_OS_DEF_SO_SNDLOWAT SO_SNDLOWAT -# define BOOST_ASIO_OS_DEF_SO_RCVLOWAT SO_RCVLOWAT -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_SNDLOWAT (-6) +# else +# define BOOST_ASIO_DISABLE_SO_SNDLOWAT 1 +# endif -+# if defined(__wasip3__) ++# if (defined(__wasip2__) || defined(__wasip3__)) +# define BOOST_ASIO_OS_DEF_SO_RCVLOWAT (-7) +# else +# define BOOST_ASIO_DISABLE_SO_RCVLOWAT 1 @@ -864,7 +873,7 @@ operation_not_supported = BOOST_ASIO_SOCKET_ERROR(EOPNOTSUPP), /// Cannot send after transport endpoint shutdown. -+#if defined(__wasip3__) ++#if (defined(__wasip2__) || defined(__wasip3__)) + // wasi-libc reports EPIPE for a write after shutdown; it has no ESHUTDOWN. + shut_down = BOOST_ASIO_SOCKET_ERROR(EPIPE), +#else @@ -873,3 +882,112 @@ /// Connection timed out. timed_out = BOOST_ASIO_SOCKET_ERROR(ETIMEDOUT), +--- a/boost/asio/detail/impl/select_reactor.ipp ++++ b/boost/asio/detail/impl/select_reactor.ipp +@@ -228,7 +228,9 @@ + // Set up the descriptor sets. + for (int i = 0; i < max_select_ops; ++i) + fd_sets_[i].reset(); ++#if !defined(__wasip2__) + fd_sets_[read_op].set(interrupter_.read_descriptor()); ++#endif + socket_type max_fd = 0; + bool have_work_to_do = !timer_queues_.all_empty(); + for (int i = 0; i < max_select_ops; ++i) +@@ -267,6 +269,7 @@ + fd_sets_[read_op], fd_sets_[write_op], fd_sets_[except_op], tv, ec); + + // Reset the interrupter. ++#if !defined(__wasip2__) + if (retval > 0 && fd_sets_[read_op].is_set(interrupter_.read_descriptor())) + { + if (!interrupter_.reset()) +@@ -281,6 +284,7 @@ + } + --retval; + } ++#endif + + lock.lock(); + +--- a/boost/asio/detail/select_interrupter.hpp ++++ b/boost/asio/detail/select_interrupter.hpp +@@ -19,7 +19,9 @@ + + #if !defined(BOOST_ASIO_WINDOWS_RUNTIME) + +-#if defined(BOOST_ASIO_WINDOWS) \ ++#if defined(__wasip2__) ++// P2 has one application thread and no pipe-based cross-thread wakeup. ++#elif defined(BOOST_ASIO_WINDOWS) \ + || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) + # include + #elif defined(BOOST_ASIO_HAS_EVENTFD) +@@ -33,7 +35,16 @@ + BOOST_ASIO_INLINE_NAMESPACE_BEGIN + namespace detail { + +-#if defined(BOOST_ASIO_WINDOWS) \ ++#if defined(__wasip2__) ++class select_interrupter ++{ ++public: ++ void recreate() {} ++ void interrupt() {} ++ bool reset() { return true; } ++ int read_descriptor() const { return -1; } ++}; ++#elif defined(BOOST_ASIO_WINDOWS) \ + || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) || defined(__SYMBIAN32__) + typedef socket_select_interrupter select_interrupter; + #elif defined(BOOST_ASIO_HAS_EVENTFD) +--- a/boost/asio/detail/resolver_service.hpp ++++ b/boost/asio/detail/resolver_service.hpp +@@ -25,6 +25,10 @@ + #include + #include + #include ++ ++#if defined(__wasip2__) ++# include ++#endif + + #include + +@@ -64,6 +68,18 @@ + { + } + ++#if defined(__wasip2__) ++ void construct(implementation_type& impl) ++ { ++ wasi_resolver_construct(impl, thread_pool_.context()); ++ } ++ ++ void cancel(implementation_type& impl) ++ { ++ wasi_resolver_cancel(impl); ++ } ++#endif ++ + // Resolve a query to a list of entries. + results_type resolve(implementation_type&, const query_type& qry, + boost::system::error_code& ec) +@@ -84,6 +100,9 @@ + void async_resolve(implementation_type& impl, const query_type& qry, + Handler& handler, const IoExecutor& io_ex) + { ++#if defined(__wasip2__) ++ wasi_async_resolve(impl, thread_pool_.context(), qry, handler, io_ex); ++#else + // Allocate and construct an operation to wrap the handler. + typedef resolve_query_op op; + typename op::ptr p = { boost::asio::detail::addressof(handler), +@@ -95,6 +114,7 @@ + + thread_pool_.start_resolve_op(p.p); + p.v = p.p = 0; ++#endif + } + + // Resolve an endpoint to a list of entries. diff --git a/tools/boost/asio-wasip3/manifest.json b/tools/boost/asio-wasip3/manifest.json index ee4d4d75..44bad91b 100644 --- a/tools/boost/asio-wasip3/manifest.json +++ b/tools/boost/asio-wasip3/manifest.json @@ -3,47 +3,59 @@ "files": { "boost/asio/detail/buffer_sequence_adapter.hpp": { "before": "fa90fb4211bd4463269d6a3f36b37cd8702ffc0260b35b27eca8627bfee2ee33", - "after": "16c3e0504b7e0275913e310c66c225294654802cd61d9f45183c006b66b29d99" + "after": "a9e9d5f90228d8360eb99a8c267b3ca902be4bd08de5dff7bcf25443b04fe08c" }, "boost/asio/detail/config.hpp": { "before": "be2ff484edb3f0bc46b6874f8e9595b4802132c4c052ca675d3c7d4359da8352", - "after": "1fab22f6c04b81d0714a60278dfd2be8db8bc868ae81aad1bc9bee5b2d663815" + "after": "a3354e5be669ad04377a1b65dd4ab2706443ea1491d9cc6fa75fef83cb4a1580" }, "boost/asio/detail/impl/null_event.ipp": { "before": "00b0ffc7de583ed07afe02ca249d630414c118ac2d68948cbc1a51d47c583617", - "after": "52999ae8533645b9d897df9cca045bccb132f57001494922443e1f50f2c5ad26" + "after": "f7aa930637aa0d4d466a7f6b078387620f50d28fa9b66059f19c10911e5499fa" }, "boost/asio/detail/impl/resolver_thread_pool.ipp": { "before": "2c1488b04ea5cb139f0a632aa908b9ce7fe01e7c95464af2f9a16541cab31cb8", - "after": "e20a3df71d36846b422099d93c8200a014bd41a05b0af77aa76f5f1979d7d15f" + "after": "d173fc0fc5ab396b24c7d7b56832676c05ba2017a6dca9997338821dd23bb0dc" }, "boost/asio/detail/impl/socket_ops.ipp": { "before": "fd5bae35b76c374174d4cd6613c420225c297ef01acafd0487fff4b8d9298529", - "after": "e7ee8cf75b602b0711ce172cb20c39f398cee2fc604574acbe7993c946f9af3e" + "after": "3f191e38e230f05b5f629325d027b8408b6c28b9116219e5c43aaf399cb2eaaf" }, "boost/asio/detail/null_signal_blocker.hpp": { "before": "125601602bac1118debb090870c96757abf71818dda18299c560555940b550d8", - "after": "1abf63fc17a666ebb355f48e3f3c229f2af57f9faf643c1a3fe2f70c15f8aa0e" + "after": "13b78db25b3ff599d36fb0270109a0c077673f3de0d410d7e4392bd75110ef83" }, "boost/asio/detail/reactive_socket_sendto_op.hpp": { "before": "1f8e02cf41fea19813b97ed8abdb77f64432b2168cd7cfcad86bea36aea1b4df", - "after": "c519375db39820b1b4d06f13c1f6fe6e9cfac9ddbe303b801b8917920069c5c6" + "after": "a64bdbab55fe71a178ded3fe1f81473e52a9adee6fba4509a1720de237a0732a" }, "boost/asio/detail/reactive_socket_service.hpp": { "before": "5f68f1e43559adab6ec869f989a33c1295e0fafbb9ce7f27f4c0f205cfb0bbb2", - "after": "1089880b86ff8a2d2aa2983c486239cb0c520bf90efca6740601f2b85eb97656" + "after": "486d9c8d7962dd9313efaac40dcdf240901e64d1672e58ccd30c499db1f0fe16" }, "boost/asio/detail/signal_blocker.hpp": { "before": "b46eb959862d0b1643f244a743a2366aff3f0acd7638a5c3cfa78dc826dd4df9", - "after": "2deaf6699a7a0d97ef8c4bc666b05b73a37914f2f15c4f42a903669cda8a6092" + "after": "24559dd6af26a5ba8ee466e15ab9efb560602ef2995361824bc2b09eda160daa" }, "boost/asio/detail/socket_types.hpp": { "before": "c83d94ea136034fc3e89018d47b38afed40449250660cc2720cbc89441023551", - "after": "24b76bd98e3fdaf79f5e620be90fddd51f4b9ad82da6a7e018dc49d4c1ac5d2b" + "after": "52b404d0793e36afb0cdf3daf7b4d7713f40beaab9d2f09cab982c9f791985cb" }, "boost/asio/error.hpp": { "before": "a836acf6bb58190eb3ae72d6795affb75d39876633c88c8343c61dfac67b0be2", - "after": "141c916e00a0db9e73aa7993ad89a7365d88d0ae002dd85f6973692fbb45be6c" + "after": "25e5d4ce36c513eed48c925d24cff62df0009469b73c6038c075939669cc2777" + }, + "boost/asio/detail/impl/select_reactor.ipp": { + "before": "4e6df639193d0c93d2a9b3e2ead005824a6a3c921d1382c3ce72e5ce959e6a48", + "after": "f1a671b45aafe10afe156748b1a0c01d05dba9ded02b7baef57bd61d445202b2" + }, + "boost/asio/detail/select_interrupter.hpp": { + "before": "debfbfa6e8915f7123229d2031b4704b1b95edcb4590f4d9a5b25c8cdd4105d5", + "after": "0f41bb2fb2190bbb23ab553c3bc0c52266f4685f2e400fd57f0b4fb987cdedbb" + }, + "boost/asio/detail/resolver_service.hpp": { + "before": "8ec1a1f84c3de50a4bf85e9ae5f2247ceb10cb36970c2bcaa3598587fa3acb50", + "after": "206411e63f5e34f028bd9c7a09a2866c61b1f8d2c3d1f7dba39357ede2afc733" } } } diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index beada8bb..72b82b25 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -321,9 +321,9 @@ def emscripten_lines() -> str: def wasm_lane(target: str) -> Lane: - # WASIp3 programs exercise Asio sockets on loopback; Wasmtime needs explicit network + # WASI programs exercise Asio sockets on loopback; Wasmtime needs explicit network # capabilities even there. Reuse the bounded launcher used by the library's own tests. - launcher = 'tools/boost/asio-wasip3/run.sh' if target == 'wasip3' else 'wasmtime' + launcher = f'tools/boost/asio-{target}/run.sh' return Lane(id=target, name=f'wasm32-{target} (wasi-sdk 34, wasmtime 50.0.1)', os='ubuntu-24.04', target=target, lane=target, toolset=f'clang-{target}', using=WASI_TOOLSET, options=(f'testing.launcher={launcher}',), wasm=True) diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 46e01a40..ccf9c49f 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -94,6 +94,8 @@ def test_plan_of_one_library(root): 'msvc-14.3', 'msvc-14.5'], lanes assert by_id['apple-clang']['detect'] == 'clang++', by_id['apple-clang'] assert by_id['wasip2']['toolset'] == 'clang-wasip2', by_id['wasip2'] + assert by_id['wasip2']['options'] == [ + 'testing.launcher=tools/boost/asio-wasip2/run.sh'], by_id['wasip2'] assert by_id['wasip3']['options'] == [ 'testing.launcher=tools/boost/asio-wasip3/run.sh'], by_id['wasip3'] assert by_id['wasip3']['wasm'] and not by_id['gcc-14']['wasm'], lanes @@ -497,7 +499,8 @@ def test_an_own_lanes_command(root): xml = Path('bin/ci/wasip2.alpha.http.xml') assert matrix.own_lane_command(served[0], config, xml, []) == [ 'b2', f'--user-config={config}', '-a', '--dump-tests', f'--out-xml={xml}', - 'toolset=clang-wasip2', 'testing.launcher=wasmtime', 'libs/alpha/example//http', + 'toolset=clang-wasip2', 'testing.launcher=tools/boost/asio-wasip2/run.sh', + 'libs/alpha/example//http', 'libs/alpha/test//http'] # On emscripten, as the emscripten lane runs: its toolset, and no launcher. driven = matrix.parsed_own_lanes('alpha driver libs/alpha/test/driver emscripten original') @@ -614,7 +617,8 @@ def test_an_own_lane_on_a_target_writes_its_xml_and_the_report_merges_it(root): printed = (f'own lane wasip2.demo.served: b2 ' f'{shlex.quote(f"--user-config={config.resolve()}")} -a --dump-tests ' f'{shlex.quote(f"--out-xml={xml}")} toolset=clang-wasip2 ' - 'testing.launcher=wasmtime --build-dir=bin/own libs/demo/test//served\n') + 'testing.launcher=tools/boost/asio-wasip2/run.sh ' + '--build-dir=bin/own libs/demo/test//served\n') assert result.stdout.startswith(printed), (printed, result.stdout[:2000]) assert output.read_text().splitlines() == ['lane=wasip2.demo.served', f'xml={xml.as_posix()}'], output.read_text() diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index ed75d6b7..b10e813c 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -146,6 +146,17 @@ if [ -d libs/beast/example/upstream ]; then fi fi +# Private libc declarations keep upstream text only after their pinned hashes match. +wasi_abi_verified=false +if [ -d tools/boost/asio-wasip2/wasi-libc ]; then + rule 'WASI ABI declaration integrity' + if python3 tools/boost/asio-wasip2/verify.py; then + wasi_abi_verified=true + else + fail 'the pinned wasi-libc declaration snapshot failed its integrity check' + fi +fi + # Every file of the repositories that is there, relative to the root, sorted, NUL-separated. # The index can name a path a move has not been staged for yet, and a submodule is listed as a # directory; neither is a file. A symbolic link is not read either: its text is a path. @@ -158,6 +169,8 @@ for repository in "${repositories[@]}"; do fi case "${path}" in third_party/libs/*) continue ;; + tools/boost/asio-wasip2/wasi-libc/*) + if [ "${wasi_abi_verified}" = true ]; then continue; fi ;; libs/beast/example/upstream/*) if [ "${beast_corpus_verified}" = true ]; then continue; fi ;; esac diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 61894d33..c7c8ccc6 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -2159,7 +2159,28 @@ def test_beast_corpus_is_verified_before_excluding_upstream_style(root): expect_alone(lint(root), 'em dash', [adapted + ':1:']) +def test_wasi_abi_snapshot_requires_integrity_before_style_exemption(root): + prepare(root) + snapshot = 'tools/boost/asio-wasip2/wasi-libc/descriptor.h' + verifier = 'tools/boost/asio-wasip2/verify.py' + # This test replaces the verifier with a controlled executable. Its unit + # tests import the real implementation, which is absent in this fixture. + (root / 'tools/boost/asio-wasip2/verify_test.py').unlink(missing_ok=True) + write(root, snapshot, '// upstream text ' + EM_DASH + '\n') + write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') + expect_clean(lint(root)) + write(root, verifier, HASH + '\nimport sys\n\nsys.exit(1)\n') + result = lint(root) + assert result.returncode != 0, result.stdout + assert 'WASI ABI declaration integrity' in FAILED.findall(result.stdout), result.stdout + write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') + bridge = 'tools/boost/asio-wasip2/notes.txt' + write(root, bridge, EM_DASH + '\n') + expect_alone(lint(root), 'em dash', [bridge + ':1:']) + + CASES = [ + test_wasi_abi_snapshot_requires_integrity_before_style_exemption, test_compile_database_normalizes_shared_source_paths, test_beast_corpus_is_verified_before_excluding_upstream_style, test_clean_tree_passes, diff --git a/tools/test/asio_wasip3_test.py b/tools/test/asio_wasip3_test.py index e3d3ca41..96059a51 100644 --- a/tools/test/asio_wasip3_test.py +++ b/tools/test/asio_wasip3_test.py @@ -12,6 +12,7 @@ """ from pathlib import Path +import shutil import sys import harness @@ -108,9 +109,50 @@ def test_wasip2_host_traits_without_socket_reactor(root: Path) -> None: harness.expect(result, True, '**passed**') +def test_wasip2_consumer_and_unsupported_profiles(root: Path) -> None: + # Use the public B2 alias in a clean path with spaces, including its ABI guard. + for name in ('config', 'asio'): + source = harness.ROOT / 'libs' / name + target = root / 'libs' / name + shutil.copytree(source / 'include', target / 'include') + shutil.copyfile(source / 'build.jam', target / 'build.jam') + harness.link_wasi_tools(root) + harness.add_library(root, 'p2_user', '''import webcpp ; +webcpp.targets wasip2 ; +webcpp.run consumer : consumer.cpp : /webcpp/asio//asio ; +''', {'consumer.cpp': '''#include +#include +int main() { + webcpp::asio::io_context context; + webcpp::asio::steady_timer timer(context, std::chrono::milliseconds(0)); + bool completed = false; + timer.async_wait([&](boost::system::error_code error) { completed = !error; }); + context.run(); // lint-run: validate the public WASIp2 timer target + return completed ? 0 : 1; +} +'''}) + options = ('toolset=clang-wasip2', + 'testing.launcher=tools/boost/asio-wasip2/run.sh', 'libs/p2_user/test') + for handling in ('on', 'off'): + harness.expect(harness.run_b2(root, '-a', f'exception-handling={handling}', *options), + True, '**passed**') + harness.expect(harness.run_b2(root, 'threading=multi', *options), + False, 'WASIp2 supports threading=single only') + for target, reason in (('cobalt', 'Cobalt requires'), ('tls', 'OpenSSL requires')): + harness.expect(harness.run_b2(root, 'toolset=clang-wasip2', '/webcpp/asio//' + target), + False, reason) + stale = root / 'unknown SDK' + stale.mkdir() + (stale / 'VERSION').write_text('34.0\nwasi-libc: unknown\n') + harness.expect(harness.run_b2(root, f'-sWASI_SDK={stale}', *options), + False, 'revalidate the bridge') + harness.expect(harness.run_b2(root, *options), True) + + CASES = [test_overlay_is_wasi_only_and_precedes_stock_headers, test_cooperative_profile_and_missing_exception_runtime, - test_wasip2_host_traits_without_socket_reactor] + test_wasip2_host_traits_without_socket_reactor, + test_wasip2_consumer_and_unsupported_profiles] if __name__ == '__main__': sys.exit(harness.run_cases('asio_wasip3_test', CASES, sys.argv[1:])) diff --git a/tools/webcpp-wasi.jam b/tools/webcpp-wasi.jam index 31ecb09b..28533908 100644 --- a/tools/webcpp-wasi.jam +++ b/tools/webcpp-wasi.jam @@ -7,7 +7,7 @@ import errors ; import modules ; import path ; -rule cooperative ( root : properties * ) +rule sdk ( root ) { # A user-config modules.poke can overwrite -s in the global module. # Read ARGV first so an explicit command-line SDK always wins. @@ -32,6 +32,12 @@ rule cooperative ( root : properties * ) } sdk ?= $(root)/.local/wasi-sdk ; sdk = [ path.root [ path.make $(sdk) ] [ path.pwd ] ] ; + return $(sdk) ; +} + +rule cooperative ( root : properties * ) +{ + local sdk = [ sdk $(root) ] ; local coop = $(sdk)/share/wasi-sysroot/experimental-coop-threads ; if ! [ path.exists [ path.native $(coop)/lib/wasm32-wasip3/libc.a ] ] { From 15e2f44d2bdff0602b8e761a5a9c89b98c3a5d97 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 08:50:50 -0500 Subject: [PATCH 10/32] Record WASIp2 cross-target regression evidence --- .../plans/2026-11-03-asio-wasip2-pollables.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md b/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md index 3b42bda9..6c3b543b 100644 --- a/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md +++ b/docs/superpowers/plans/2026-11-03-asio-wasip2-pollables.md @@ -102,3 +102,25 @@ Decisions: reuse libc select/poll, pin the private descriptor ABI, retain deferr initiation and upstream public-result allocation, and keep host-blocking writes explicit. The ABI bridge must be revalidated on SDK updates. No CPU-thread, guest TLS, Cobalt, Unix addressing or host WebSocket-upgrade capability is implied for P2. + +### Additional local regression, 2026-11-03 + +A fresh Emscripten Release build passed 271 B2 test targets with no unexpected +failures or skipped dependencies, updating 2,941 build targets. It covered the +Asio/Beast default tests/examples and Asio Asyncify/Cobalt lanes with EH on/off. +This is Node-based Emscripten regression evidence, not a fresh complete real-browser +or remote-CI run. The implementation commits above are unchanged. + +Proposal commit `5a1fcb6` records the scope amendment and exact committed reference +trees (182 Asio files, 774 Beast files), with Git blobs and executable modes verified. +All 23 proposals pass their structural check, all 17 proposal-tool tests pass and +strict OpenSpec validation passes in all 15 roots. Root `b2 check-release` passed +for `e80ffab` after the implementation commits. The later local documentation-only +verification record does not replace the pending exact-candidate remote CI. + +The full compilation-database preparation completed successfully with 1,419 commands. +It includes Asio P2 aggregate commands with and without exceptions and prepares the +checked overlays and generated dependencies used by the lint. This is preparation +and aggregate compilation evidence, not a claim that all 1,419 commands received +clang-tidy in this increment; the focused 20-configuration result above remains its +actual static-analysis scope. From f4162d3a5f2451be9ba7829df3e5a862ec175026 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 10:04:26 -0500 Subject: [PATCH 11/32] Plan remaining Asio implementation and capability guards --- .../2026-11-03-asio-capability-completion.md | 74 +++++++++++++++++++ ...11-03-asio-capability-completion-design.md | 58 +++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-03-asio-capability-completion.md create mode 100644 docs/superpowers/specs/2026-11-03-asio-capability-completion-design.md diff --git a/docs/superpowers/plans/2026-11-03-asio-capability-completion.md b/docs/superpowers/plans/2026-11-03-asio-capability-completion.md new file mode 100644 index 00000000..e2435e0e --- /dev/null +++ b/docs/superpowers/plans/2026-11-03-asio-capability-completion.md @@ -0,0 +1,74 @@ +# Asio Capability Completion Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Complete the WebCPP-owned Asio gaps and diagnose external unsupported combinations at their correct boundary. + +**Architecture:** Reuse Boost and the checked private overlays, source-built OpenSSL and WASI native asynchronous resources. Keep target capability detection in config.hpp; preserve runtime errors for runtime facts. + +**Tech Stack:** C++20, Boost 1.92, wasi-sdk 34.0, Wasmtime 50.0.1, Emscripten 6.0.11, B2, MrDocs/AsciiDoc. + +**Spec:** docs/superpowers/specs/2026-11-03-asio-capability-completion-design.md + +## Global Constraints + +- English files/comments/commits, no em dash or coauthor trailer. +- Preserve allocator/executor/cancellation/deferred initiation and existing APIs. +- No installed Boost edits, no changed SDK or environment policy, no duplicate TLS provider. +- SDK/runtime blockers need reproducible evidence and explicit guards, not optimistic enablement. +- Do not hand-edit generated files; regenerate overlays and hash manifests from pristine inputs. +- Distinct build directories per concurrent task. Parent owns shared config.hpp, docs and final B2 integration. +- No push, merge, tag or remote CI in this increment. Local commands and examples are shown in chat. + +## Review Focus + +- UDP truncation, empty buffers and cancellation preserve one-datagram semantics. +- DNS does not block initiation or starve unrelated timers while the host is pending. +- TLS verifies trust/hostname and cancellation cannot leave borrowed state alive. +- Browser operations run on a valid thread/stack without recursive executor execution. +- A compiler guard rejects unsupported use without rejecting portable includes or supported runtime alternatives. + +### Task 1: Complete WASI datagrams and P3 asynchronous DNS + +**Files:** tools/boost/asio-wasip3 checked overlay/manifest and new private backend files as required; libs/asio/test/wasi_udp_gather_test.cpp, new focused DNS/datagram consumers, their own test subdirectory/Jamfile. Parent integrates root test/Jamfile and config. + +**Interfaces:** Existing Asio UDP and async_resolve APIs. Both P2/P3 scalar and sequence consumers retain ordinary completion tokens. P3 S uses native async lookup without a worker pool. P2 resolver remains unchanged unless shared behavior requires correction. + +- [ ] Write and run public-target RED consumers for connected gather send, scatter receive (sync/async), empty/oversize datagrams, cancellation, and P3 S deferred DNS with timer progress. +- [ ] Implement checked overlay changes with context/associated allocation and release before callbacks. Use native P3 waitable integration where required; never implement async DNS by blocking inside initiation. +- [ ] Verify P2/P3 EH twins, P3 cooperative where applicable, native controls, source hash preparation and meaningful failure cases. +- [ ] Write report with exact commands, RED/GREEN, changes and remaining external dependencies; parent reviews/integrates and commits. + +### Task 2: WASIp2 TLS and Cobalt + +**Files:** tools/openssl source build configuration, tools/boost Cobalt overlays/source integration, third_party/Jamfile, libs/asio/src/cobalt_main.cpp, libs/asio/test P2 TLS/Cobalt consumers. Coordinate modifications to libs/asio/build.jam with parent. Do not edit config.hpp or global docs. + +**Interfaces:** Existing /webcpp/third_party//openssl and /webcpp/asio//cobalt, //tls, //cobalt_ssl gain validated P2 S/EH on/off. CA replacement/embedding contract remains identical. No new OpenSSL copy or system fallback. + +- [ ] Run existing/public P2 consumers to capture deliberate baseline refusal, then register real minimal Cobalt and TLS consumers. +- [ ] Extend verified source recipe and Cobalt source/runner selection to P2. Preserve capability omission of signals, local sockets and thread APIs. +- [ ] Verify Cobalt main status, timer/TCP/UDP/resolver cancellation, real TLS trust and hostname failures, embedded/custom CAs, handshake/transfer/shutdown including cancellation under both EH modes. Retain the known no-EH pending-task move warning. +- [ ] Run native/P3 focused regressions and source build tests. Report exact evidence and changes for parent integration/review/commit. + +### Task 3: Browser worker profile and environment boundary + +**Files:** temporary feasibility consumers followed by tools/emscripten toolset sources and libs/asio browser implementation/tests where feasible. Parent coordinates shared build selection and config.hpp. + +**Interfaces:** An explicit supported threaded browser build must coexist with existing single-thread JSPI/Asyncify. No blanket claim of DOM access from workers; do not silently switch suspension mechanisms. + +- [ ] Reproduce the current public-target rejection and independently compile/run pinned Emscripten pthread consumers with each suspension mechanism in a real browser, with required isolation headers. +- [ ] If supported by the pinned environment, implement the worker executor/wakeup and main-thread handoff, preserving thread affinity, allocator/cancellation and same-context semantics. Add real-browser success/error/shutdown tests. +- [ ] For any external blocker, retain a smallest reproducible compile/runtime witness and precise diagnosis. Do not upgrade the SDK or classify missing WebCPP code as external. +- [ ] Report actual supported matrix, code changes, test commands and guard requirements for parent integration/review/commit. + +### Task 4: Central config guards, documentation and final verification + +**Files:** libs/asio/include/webcpp/asio/config.hpp and feature headers, libs/asio/build.jam/test/Jamfile, targeted tools/build tests, Asio AsciiDoc/MrDocs, root guidelines/agents and proposal scope/status. + +**Interfaces:** Derived WEBCPP_ASIO capability macros with 0/1 values, optional dependency selection separate from platform availability, explicit compile-time requirement diagnostics. Existing generic/browser settings headers remain usable. + +- [ ] Write positive/negative compiler consumers proving capabilities cannot be forged, optional dependencies are required only by their features, unsupported known profiles fail clearly and runtime alternatives remain usable. +- [ ] Implement central detection and header/build guards using final verified Task 1-3 outcomes. Runtime network permissions and blocking host calls remain documented error/behavior boundaries. +- [ ] Update feature tables with evidence and dependency ownership, include compiled examples, reconcile approved proposal and guideline scope without declaring publication complete. +- [ ] Run affected Release suites from scratch, focused tools/lint, MrDocs/rendered checks and proposal validation. Review delegated tasks and the complete candidate, fix important findings with RED/GREEN evidence. +- [ ] Commit scoped library/root/proposal changes and report completed work plus externally blocked cases, with no implicit CI/merge claim. diff --git a/docs/superpowers/specs/2026-11-03-asio-capability-completion-design.md b/docs/superpowers/specs/2026-11-03-asio-capability-completion-design.md new file mode 100644 index 00000000..21b66c8e --- /dev/null +++ b/docs/superpowers/specs/2026-11-03-asio-capability-completion-design.md @@ -0,0 +1,58 @@ +# Asio implementation gaps and capability diagnostics + +The owner requested completing the gaps attributable to WebCPP's implementation, +while documenting and guarding unsupported SDK/environment combinations. This +request follows the explicit inventory in the conversation and authorizes execution +without another approval round. Existing compatibility and allocator contracts stay +in force. The existing isolated worktree is reused. + +## Deliverables + +1. Complete WASI connected UDP gather sends and scatter receives without changing + datagram atomicity, partial/truncated result semantics or allocator ownership. +2. Add WASIp3 single-thread asynchronous forward resolution using the available + native asynchronous interface, preserving deferred initiation, cancellation, + associated executors/allocators and useful progress of unrelated operations. +3. Integrate source-built OpenSSL, embedded/replacement CAs, Cobalt and its SSL + wrapper on WASIp2, using the existing shared provider and checked Boost patches. +4. Establish browser worker-profile feasibility using real compiler/runtime + consumers. Implement the integration where the pinned SDK and engine support + it. A demonstrated toolchain/runtime blocker is documented and guarded, not + hidden with a different program or an SDK upgrade. +5. Centralize compile-time capabilities in Asio config.hpp and apply diagnostics + at unsupported feature headers/build requests. Keep ordinary umbrella headers + and browser transport abstractions usable. Do not confuse compile-time support + with runtime network grants, certificates, reachable peers or a custom transport + selected at runtime. +6. Update the AsciiDoc/Diataxis feature matrix and MrDocs comments. Distinguish + implementation gaps, unavailable external facilities, and unverified behavior. + +## Boundaries + +Do not change the pinned SDK, add runtime/OS APIs, repair upstream Cobalt issue 287, +implement raw browser sockets or a proxy, invent reverse DNS from a forward-only +host API, or claim CPU parallelism from cooperative threads. Those dependencies +remain documented with deliberate diagnostics where compiler-visible. Runtime-only +failures remain error values. Keep native/P3/browser behavior and shared OpenSSL +provenance intact. No push, merge or CI dispatch is part of this implementation +increment; the previously authorized publication closure remains a separate gate. + +## Compiler contract + +Capability macros are derived by config.hpp from the compiler target and verified +build selections. They use the WEBCPP_ASIO_ prefix, have documented 0/1 values, +and cannot be forced to claim support. Availability of a backend and selection of +an optional compiled dependency are distinct. Feature-specific headers must reject +known-invalid use with a named target, missing requirement and supported alternative. +Generic headers must not reject supported alternatives such as a custom browser +transport. Unsupported runtime flags/options are still errors, not global build bans. + +## Verification + +Public B2 consumers must fail before each implementation and pass afterward. +Run native/P2/P3 regressions, browser tests as relevant, EH on/off, negative compile +controls, handler allocation/cancellation/lifetime tests, real TLS trust/hostname and +transfer/shutdown cases. Use bounded local drivers and preserve logs. Builds use +wasi-sdk 34.0, Wasmtime 50.0.1, Boost 1.92 and Emscripten 6.0.11. Never count an +unsupported error as successful feature execution. Each delegated task receives a +fresh review, followed by an integration review of the final candidate. From 0da952fa03821042bd6c793a8cc4f26b72736d4c Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 10:44:03 -0500 Subject: [PATCH 12/32] Complete WASI networking and shared TLS capability integration --- AGENTS.md | 12 +- CODING-GUIDELINES.md | 86 +-- Jamroot | 6 +- doc/releases/0.1.0.adoc | 3 + ...2026-11-03-asio-capability-verification.md | 137 +++++ libs/asio | 2 +- tools/boost/Jamfile | 13 +- .../boost/asio/detail/wasi_resolver.hpp | 21 +- tools/boost/asio-wasip3/Jamfile | 17 + tools/boost/asio-wasip3/README.md | 29 +- tools/boost/asio-wasip3/boost-1.92.patch | 571 +++++++++++++++++- .../boost/asio/detail/wasi_p3_resolver.hpp | 368 +++++++++++ .../boost/asio/detail/wasi_waitable.hpp | 31 + tools/boost/asio-wasip3/manifest.json | 28 +- tools/boost/asio-wasip3/verify.py | 61 ++ tools/boost/asio-wasip3/verify_test.py | 48 ++ tools/boost/asio-wasip3/waitable.cpp | 121 ++++ tools/boost/asio-wasip3/wasi-libc/LICENSE | 17 + .../asio-wasip3/wasi-libc/LICENSE-APACHE | 201 ++++++ tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT | 23 + .../boost/asio-wasip3/wasi-libc/manifest.json | 13 + .../wasi-libc/wasi/descriptor_table.h | 368 +++++++++++ tools/boost/asio-wasip3/wasi-libc/wasi/lock.h | 60 ++ tools/boost/asio-wasip3/wasi-libc/wasi/poll.h | 79 +++ tools/boost/cobalt-ssl/Jamfile | 4 +- tools/boost/cobalt-wasip3/Jamfile | 5 +- tools/lint/lint.sh | 18 +- tools/lint/lint_test.py | 19 +- tools/openssl/build.py | 18 +- tools/openssl/test/cobalt_ssl_cancel.cpp | 17 +- tools/openssl/test/tls.py | 20 +- tools/openssl/wasip3.conf | 6 + tools/test/asio_wasip3_test.py | 5 +- tools/test/openssl_test.py | 34 +- tools/webcpp-openssl.jam | 10 +- 35 files changed, 2348 insertions(+), 123 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-03-asio-capability-verification.md create mode 100644 tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp create mode 100644 tools/boost/asio-wasip3/include/boost/asio/detail/wasi_waitable.hpp create mode 100644 tools/boost/asio-wasip3/verify.py create mode 100644 tools/boost/asio-wasip3/verify_test.py create mode 100644 tools/boost/asio-wasip3/waitable.cpp create mode 100644 tools/boost/asio-wasip3/wasi-libc/LICENSE create mode 100644 tools/boost/asio-wasip3/wasi-libc/LICENSE-APACHE create mode 100644 tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT create mode 100644 tools/boost/asio-wasip3/wasi-libc/manifest.json create mode 100644 tools/boost/asio-wasip3/wasi-libc/wasi/descriptor_table.h create mode 100644 tools/boost/asio-wasip3/wasi-libc/wasi/lock.h create mode 100644 tools/boost/asio-wasip3/wasi-libc/wasi/poll.h diff --git a/AGENTS.md b/AGENTS.md index c8c32529..49dfcd31 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,7 @@ for web developers and for AI developers (`CODING-GUIDELINES.md` chapter 16). | Library | What it is | Targets | State | | --- | --- | --- | --- | -| asio | Boost.Asio and Cobalt with browser event-loop suspension, WASIp3 networking and optional source-built TLS | native, emscripten, wasip3 | a submodule at `libs/asio`; see its feature matrix for variants | +| asio | Boost.Asio and Cobalt with browser event-loop suspension, WASIp2/P3 networking and optional source-built TLS | native, emscripten, wasip2, wasip3 | a submodule at `libs/asio`; see its feature matrix for variants | | beast | HTTP and WebSocket applications using native/WASIp3 sockets, browser WebSocket/fetch, WASI host HTTP or supplied streams | native, emscripten, wasip2, wasip3, by backend | a submodule at `libs/beast`; all 53 upstream applications remain in its compatibility matrix | | config | webcpp's configuration, which every library includes first: the target, exceptions and webcpp's version, as Boost.Config is Boost's; webcpp's own | native, wasip2, wasip3, emscripten | a submodule at `libs/config` | | xactor | a deterministic actor system, webcpp's own | native, wasip2, wasip3 (`xactor_asio` native only) | a submodule at `libs/xactor`; the model for every port | @@ -255,7 +255,7 @@ Jamroot is its build configuration, and `libs/` is its repository. nested dependencies with the consumer's compiler and runtime settings. Native Trystero requires `threading=multi` and exceptions; a single-thread request is refused because this backend uses worker threads; -- for native or WASIp3 guest TLS: Python 3, Perl, Make (nmake on Windows), +- for native or WASIp2/P3 guest TLS: Python 3, Perl, Make (nmake on Windows), the selected compiler and `third_party/libs/openssl`, initialized with `git submodule update --init third_party/libs/openssl`. B2 builds the pinned OpenSSL sources and matching generated headers. Native Trystero's @@ -345,7 +345,7 @@ looks. `src/detail/*.cpp` and `src/io/*.cpp`, excluding `src/main.cpp` and `src/io/ssl.cpp`. It supplies no default `co_main` runner; `/webcpp/asio//cobalt` adds the webcpp runner. Ordinary `main` consumers can use the archive directly. -On WASIp3, `tools/boost/cobalt-wasip3` verifies a Boost 1.92 compatibility patch +On WASIp2/P3, `tools/boost/cobalt-wasip3` verifies a Boost 1.92 compatibility patch and prepares private headers and endpoint/acceptor sources. The archive and consumers use the same Asio overlay and thread profile. Signal, serial-port and seqpacket sources are omitted, along with `thread.cpp` in single-thread @@ -364,14 +364,14 @@ compiles `io/ssl.cpp` with `BOOST_COBALT_SSL_SOURCE=1`, source-built OpenSSL and the checked shared patch in `tools/boost/cobalt-ssl`. It preserves handler associations, fixes handshake state and callback constraints, and exposes a borrowed `native_ssl_handle()` for SNI. `/webcpp/asio//cobalt_ssl` adds the -runner and CA factory. Native and WASIp3 consumers share these SSL corrections; -browser/WASIp2 are refused. Plain Cobalt does not acquire an OpenSSL dependency. +runner and CA factory. Native and WASIp2/P3 consumers share these SSL corrections; +browser OpenSSL is refused. Plain Cobalt does not acquire an OpenSSL dependency. Asio's `tls-integration` own lane drives the real OpenSSL/Cobalt fixtures on native and WASIp3 profiles, including primitive/composed transfer cancellation, truncated shutdown and cancelled shutdown. Its native `openssl-upstream` lane requests `webcpp-openssl-tests=on`: the exact archives pass upstream's full `alltests` suite before the TLS consumer links. The upstream harness cannot run -on WASIp3; its separate TLS/entropy integration tests do not substitute for it. +on WASI; its separate TLS/entropy integration tests do not substitute for it. The `openssl-upstream-msvc-14.3` and `openssl-upstream-msvc-14.5` aliases select their matching Windows runners/toolsets; the default native upstream lane uses Linux. CI uploads upstream logs, proof and build manifests even on diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 89c24db9..2af542ba 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -1165,7 +1165,7 @@ site's own decisions follow in the next sections. Boost.Locale without ICU and Boost.Cobalt, are built by webcpp from Boost's own source archive for their supported targets, as `/webcpp//boost_url` and its kin.** Each archive follows its consumer's target, macros and compiler - configuration; Cobalt is unavailable on WASIp2. Checked Asio/Cobalt overlays + configuration; Cobalt supports the validated P2/P3 WASI profiles. Checked Asio/Cobalt overlays apply only to private copies, with original and patched hashes and an exact Boost-version check (AGENTS.md chapter 1). An installed Boost cannot be relied on for sources (Homebrew's has no `libs/url/src`), and the sources' @@ -6179,15 +6179,16 @@ Asio's first library-main CI and the final joint candidate remain separate gates Throwing APIs stay guarded and raise through `boost::throw_exception`. Source: `genesis/specs/asio/spec.md`, Library: Configuration header (proposals). -- **On Emscripten `/webcpp/asio//asio` gives every translation unit, - `browser-src` included, `BOOST_ASIO_DISABLE_THREADS`, and links embind, - `browser-src`, the variant's link flags and the tag rule.** Without the - define Asio decides it has threads and stops at "Only Windows and POSIX are - supported!"; its inline namespace differs with and without threads, so a - unit that missed it fails at link, never silently. +- **On single-thread Emscripten `/webcpp/asio//asio` gives every translation + unit, `browser-src` included, `BOOST_ASIO_DISABLE_THREADS`; explicit pthread + builds retain Boost's POSIX thread configuration.** Both link embind, + `browser-src`, the variant's link flags and the tag rule. Boost's inline + namespace differs with and without threads, so every compiled dependency + must use the consumer's profile. A silent switch from multi to single is + forbidden. Browser runtime isolation remains a host requirement. Source: `genesis/specs/asio/spec.md`, Build (proposals). -- **The library supports native, Emscripten and WASIp3 through the checked - Boost 1.92 overlay; guest sockets on WASIp2 remain unavailable.** A library +- **The library supports native, Emscripten and WASIp2/P3 through the checked + Boost 1.92 overlay; WASI supports guest TCP/UDP and optional source-built TLS.** A library may declare only the targets its actual APIs support. Beast's portable messages and WASI host HTTP do not require guest sockets. xactor's existing Asio driver stays native until separately adapted; Asio's port does not @@ -6202,6 +6203,15 @@ Asio's first library-main CI and the final joint candidate remain separate gates Source: `genesis/specs/asio/spec.md`, Run, and `genesis/proposal.md` (proposals). +- **Asio capabilities are read-only 0/1 macros in `config.hpp`; optional + dependency selection is separate from target availability.** Explicit + `WEBCPP_ASIO_REQUIRE_*` switches reject compiler-visible unsupported needs; + feature headers diagnose wrong targets. Network grants, trust roots, actual + browser isolation and blocking host imports remain runtime conditions. + The owner approved implementation completion and external-boundary guards on + 2026-11-03. Do not reclassify missing WebCPP code as a platform limitation. + Source: `docs/superpowers/specs/2026-11-03-asio-capability-completion-design.md`. + **The run family and the turn limit.** - **On Emscripten the six members of the run family hide Boost's and compose @@ -6489,12 +6499,12 @@ Asio's first library-main CI and the final joint candidate remain separate gates entry, so Beast's layered client code runs unchanged; a resolver that failed like the sockets would change a line of every Beast client. Source: `genesis/design.md`, D14 (proposals). -- **`` is Boost's `ssl` on native and WASIp3; on +- **`` is Boost's `ssl` on native and WASI; on Emscripten it records TLS settings and a host name in `std::pmr` storage for webcpp::beast's browser streams.** Guest TLS explicitly names - `/webcpp/asio//openssl` on native or WASIp3. Naming that source provider for - Emscripten or WASIp2 fails with an instruction; the browser owns TLS in its - profile, and WASIp2 host HTTP uses the host's independent TLS implementation. + `/webcpp/asio//openssl` on native or WASI. Naming that source provider for + Emscripten fails with an instruction; the browser owns TLS in its profile. + WASI host HTTP continues to use the host's independent TLS implementation. Source: `genesis/design.md`, D15 (proposals); `include/webcpp/asio/ssl.hpp` (asio). @@ -6504,7 +6514,7 @@ Asio's first library-main CI and the final joint candidate remain separate gates (`src/cobalt_main.cpp`, `/webcpp/asio//cobalt`), with Cobalt's steps over a `webcpp::asio::io_context{BOOST_ASIO_CONCURRENCY_HINT_1}`, and `/webcpp//boost_cobalt` excludes `main.cpp` and the optional `io/ssl.cpp`, - with additional unsupported sources omitted for WASIp3 as listed below.** + with additional unsupported sources omitted for WASI as listed below.** `co_main` cannot be replaced from a header: `main` is a hidden friend that calls `run_main`, compiled in Cobalt's `src/main.cpp`, which calls Boost's `run`; compiling against the pinned Boost probes the private members it @@ -6625,28 +6635,29 @@ The closure record distinguishes the baseline CI from validation of later change cooperative component. These grants and limits are test-harness settings; they neither configure production capabilities nor enforce network isolation. Source: `tools/boost/asio-wasip3/README.md` (superproject). -- **UDP `send_to` and `async_send_to` gather several nonempty buffers into one - datagram, in storage from the context's allocator (synchronous) or the - handler's (asynchronous), released before the handler runs; a receive or a - connected send of several nonempty buffers fails with - `operation_not_supported`.** wasi-libc has no `sendmsg`, datagram boundaries - never change to make a buffer sequence compile, and no hidden allocation - emulates scatter/gather. +- **WASI UDP sends gather several nonempty buffers into one datagram, + connected or unconnected; receives scatter one datagram into the destination + sequence.** Temporary storage uses the context allocator synchronously or + the handler's allocator asynchronously and is released before completion. + Truncation, empty datagrams and cancellation preserve datagram boundaries. + The pinned libc lacks `sendmsg`/`recvmsg`; this adaptation belongs to the + checked Boost overlay, not the installed SDK. Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md` (superproject); `AGENTS.md` (asio). - **What WASI lacks is explicit: Asio's `shut_down` error maps to `EPIPE`, interface-name scopes are refused, a missing socket option reports - `operation_not_supported`, and an asynchronous resolve without threads posts - `operation_not_supported`.** WASI has no `ESHUTDOWN`, no interface names - and, in the single profile, no thread for Boost's resolver; the port does - not pretend those entry points exist. + `operation_not_supported`, and reverse/canonical lookup policies remain + unsupported.** Forward asynchronous resolution uses native P2 pollables or + P3 async subtasks/waitables in both supported thread profiles. It never + blocks initiation, starts a hidden worker or scans DNS with periodic timers. + Private libc descriptor APIs require the checked SDK/revision/hash manifest. Source: `doc/capabilities.adoc` (asio). -- **The library's test and example Jamfiles declare `wasip3` beside native and - Emscripten, Cobalt and OpenSSL refuse WASIp2 by name, and +- **The library's applicable test and example Jamfiles declare WASIp2/P3 + beside native and Emscripten; Cobalt and OpenSSL support WASIp2 S, and `doc/capabilities.adoc` with `doc/feature-matrix.adoc` is kept current for every feature, target and variant, telling unavailable from unverified.** The owner approved an AsciiDoc feature matrix that links its evidence. Source: `docs/superpowers/specs/2026-10-15-asio-wasip3.md` (superproject); `AGENTS.md` (asio). -- **`/webcpp/asio//cobalt` builds on WASIp3 from a checked patch of private +- **`/webcpp/asio//cobalt` builds on WASIp2/P3 from a checked patch of private copies of Cobalt's headers and sources (`tools/boost/cobalt-wasip3`): its signal, serial-port and seqpacket sources are left out, `thread.cpp` comes only with threads, and the archive and its consumers share the Asio overlay @@ -6655,9 +6666,9 @@ The closure record distinguishes the baseline CI from validation of later change about headers, threads and exceptions. Source: `docs/superpowers/plans/2026-10-16-cobalt-wasip3.md`, `tools/boost/Jamfile` (superproject). -- **On WASIp3 `run_main` sets the promise's `signal_set` to null and includes +- **On WASIp2/P3 `run_main` sets the promise's `signal_set` to null and includes no POSIX signal service, keeping the executor, the initial post, the status - and Cobalt's internal cancellation.** WASIp3 delivers no process signal; a + and Cobalt's internal cancellation.** WASI delivers no process signal; a host's graceful shutdown needs a protocol of the program's. Source: `src/cobalt_main.cpp`, `AGENTS.md` (asio). - **On WASIp3 the Cobalt status driver expects host exit status 1 for a @@ -6675,21 +6686,22 @@ The closure record distinguishes the baseline CI from validation of later change Source: `docs/superpowers/plans/2026-10-16-openssl-source-build.md`, `tools/webcpp-openssl.jam` (superproject). - **The OpenSSL recipe covers native Clang and GCC on macOS and Linux and - WASIp3, single and cooperative, plus native MSVC using Configure/nmake; - WASIp2 and Emscripten stop the build, and a host OpenSSL is never a fallback.** + WASIp2 single, WASIp3 single/cooperative, and native MSVC using Configure/nmake; + Emscripten stops the build, and a host OpenSSL is never a fallback.** Windows recipes preserve B2 runtime settings. Windows runtime results must be tied to their tested candidate, not inferred from recipe tests or older CI. A silent system fallback could link a second copy. Source: `docs/superpowers/plans/2026-10-16-openssl-source-build.md` (superproject). -- **On WASIp3 OpenSSL uses the external Configure target `webcpp-wasip3` (no +- **On WASIp2/P3 OpenSSL uses the external Configure targets `webcpp-wasip2` + and `webcpp-wasip3` (no assembly, no DSO, no QUIC, `getrandom` seeding) and fails closed when host entropy fails.** wasi-libc's `getentropy` reaches `wasi:random`; the tests show entropy is requested and that its failure stops key generation, not its quality. Source: `tools/openssl/wasip3.conf`, `tools/openssl/build.py` (superproject); `doc/building.adoc` (asio). - **`/webcpp/asio//openssl` forwards `/webcpp/third_party//openssl` with - `WEBCPP_ASIO_HAS_OPENSSL` natively and on WASIp3, Emscripten keeps the + `WEBCPP_ASIO_HAS_OPENSSL` natively and on WASIp2/P3, Emscripten keeps the forced-include refusal, and asio's tests that need OpenSSL fail rather than being left out.** A missing checkout is named (`git submodule update --init third_party/libs/openssl`), never skipped. @@ -6846,8 +6858,10 @@ facilities separately; a successful compile never proves runtime parity. scheduling, resolver, transport or error-handling adaptation explicitly. - Feature and application matrices in the guide keep compilation and execution separate for every target, exception mode and supported threading profile. - Unavailable stackful Wasm coroutines, browser listeners, WASIp2 guest sockets - and cooperative WASIp3 exceptions remain unavailable, never counted as passes. + Unavailable stackful Wasm coroutines, browser listeners and cooperative + WASIp3 exceptions remain unavailable, never counted as passes. WASIp2 guest + socket examples remain application-integration work in Beast; Asio now provides + that backend, so they are not a platform impossibility. - Native upstream programs are the oracle. Browser validation runs in real Chrome with a disposable CA profile, independently of Node. WASI host HTTPS uses a pinned Wasmtime host fixture with normal trust and hostname checks; diff --git a/Jamroot b/Jamroot index 61d333b8..a484271d 100644 --- a/Jamroot +++ b/Jamroot @@ -267,11 +267,11 @@ project /webcpp wasi:static # end::wasi-target[] # b2's emscripten builds wasm32 (browsers do not all run memory64, and - # an address-model=64 request would add -sMEMORY64=1), without pthreads - # (they need cross-origin isolation in a page), and static. + # an address-model=64 request would add -sMEMORY64=1), and static. + # Keep b2's single-thread default, but honor an explicit threading=multi. + # Pthreads require a cross-origin isolated page and a compatible library. # tag::emscripten-target[] emscripten:32 - emscripten:single emscripten:static # end::emscripten-target[] # Every WASI target builds with exceptions, as native does: whether a diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index e1115556..0c8afcd1 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -55,6 +55,9 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Added source-built OpenSSL and Cobalt SSL targets for WASIp2. +* Added explicit browser pthread profiles with main-thread handoff tests. +* Changed lint to verify WASIp3 ABI snapshots before excluding upstream headers. * Fixed embedded CA headers using an unowned namespace and include path. * Added source-built Boost.Context for native stackful coroutine applications. * Added negative link tests and explicit reference-source build discovery. diff --git a/docs/superpowers/plans/2026-11-03-asio-capability-verification.md b/docs/superpowers/plans/2026-11-03-asio-capability-verification.md new file mode 100644 index 00000000..40b450c5 --- /dev/null +++ b/docs/superpowers/plans/2026-11-03-asio-capability-verification.md @@ -0,0 +1,137 @@ +# Asio capability completion: local verification + +Date: 2026-11-03. Scope and requirements are in +`2026-11-03-asio-capability-completion.md` and its linked design. + +## Candidate scope + +- Complete WASI connected UDP gather and scatter receive, including transient send + readiness, truncation, empty datagrams, handler allocation and cancellation. +- Use the P3 native asynchronous name-lookup interface in single-thread and + cooperative profiles. A checked private libc descriptor joins the existing + reactor. Preserve deferred initiation, timer progress and resource lifetime. +- Enable the existing source-built OpenSSL, embedded/replacement CAs and Cobalt SSL + targets on P2. Keep a single provider and the no-exceptions issue 287 notice. +- Enable explicit Emscripten pthread builds, creator-thread context execution and + an allocator-aware main-thread handoff. Keep the default single-thread profile. +- Centralize derived capabilities and opt-in compile-time requirements. Document + runtime permissions separately from compiler-visible constraints. + +No SDK upgrade, upstream Cobalt fix, push, merge, remote CI or release is part of +this increment. The handler budget remains 100. The old remote run 41597577370 +does not validate this candidate. + +## Toolchain and commands + +Local validation used Apple Clang 21, Boost 1.92, wasi-sdk 34.0 with its pinned +wasi-libc revision, Wasmtime 50.0.1, Emscripten 6.0.11 and Chrome 156. The wrapper +`.local/review-b2` unsets CPATH, CPLUS_INCLUDE_PATH and C_INCLUDE_PATH, selects +`.local/user-config.jam`, and uses the local writable Emscripten cache. + +```sh +.local/review-b2 -a -j4 libs/asio/test libs/asio/example \ + toolset=clang variant=release exception-handling=on,off +.local/review-b2 -a -j4 libs/asio/test libs/asio/example \ + libs/asio/test//asyncify toolset=emscripten variant=release \ + exception-handling=on,off +.local/review-b2 -j4 libs/asio/test libs/asio/example \ + toolset=clang-wasip2 variant=release exception-handling=on,off \ + testing.launcher=tools/boost/asio-wasip3/run.sh +.local/review-b2 -j4 libs/asio/test libs/asio/example \ + toolset=clang-wasip3 variant=release exception-handling=on,off \ + testing.launcher=tools/boost/asio-wasip3/run.sh +.local/review-b2 -a libs/asio/doc +.local/review-b2 declared-targets declared-lanes -d0 +``` + +The WASI launcher resolves the pinned Wasmtime from PATH. Initial broad WASI +commands built from scratch but omitted that launcher, so their runtime failures +are invalid test evidence. The corrected commands above executed the freshly built +artifacts successfully. An additional attempted `toolset=wasi` command was rejected +because the configured toolsets are `clang-wasip2` and `clang-wasip3`. + +| Final broad local check | Passed B2 test targets | Result | +| --- | ---: | --- | +| Native Release, exceptions on/off | 105 | Exit 0; examples matched output | +| Emscripten Release, JSPI/Asyncify, exceptions on/off | 233 | Exit 0; Node execution and example output | +| WASIp2 Release, exceptions on/off | 66 | Exit 0; examples matched output | +| WASIp3 Release, exceptions on/off | 117 | Exit 0; examples matched output | + +Counts include compile/diagnostic and runtime targets, not individual assertions. +They do not include every separate own lane and do not claim all-platform CI. + +## Focused evidence + +- P2 TLS/Cobalt: 26 checks across both exception profiles. Real peers cover trust, + hostname, replacement and embedded CAs, transfer, handshake, shutdown errors and + cancellation. The final registered `wasip2-tls` lane passed all 16 driver runs. + Native/P3 TLS controls passed in both exception profiles. +- Entropy: independent processes generated distinct public keys; failed host + entropy prevented random output and key generation. This checks wiring and + fail-closed behavior, not the cryptographic strength of a host's entropy source. +- P3 DNS: real localhost lookups plus a deterministic pending native host-clock + subtask proved deferred start, unrelated timer progress, cancellation and release + before callbacks. Cooperative two-runner cancellation passed 20 repetitions, + totaling 40 cancellations. P3 cooperative C++ exceptions remain unsupported by + the pinned SDK runtime and are diagnosed by the build. +- Browser pthreads: real Chrome passed JSPI and Asyncify, each with exceptions on + and off. Eight final lifecycle/affinity runs cover reentrant destruction, posted + work, cancellation and allocator cleanup. Two EH-on runs cover throwing handler + moves. Single-thread browser, idle and rendering controls passed separately. +- A versioned raw pthread-return probe records the SDK's Asyncify join-result + limitation: the worker computes 42 but join yields zero. It deliberately fails + its value check; it is not counted as a passing library test. +- Capability consumers passed native/P2/P3/browser and browser pthread compilation. + They reject forged derived macros, unavailable feature headers and missing or + explicitly disabled optional TLS selection, while retaining portable includes. +- Overlay preparation, SDK/private-ABI checks, source-build harness and OpenSSL + recipe tests passed. The lint verifier regression passed for P2/P3 valid and + rejected snapshots without hiding WebCPP bridge sources. +- Focused clang-tidy passed task-owned code and 16 parent-owned configurations. + Owned Python checks, text/format rules and Node syntax checks passed. This is not + a claim that the complete repository lint printed `lint: clean`. +- MrDocs and rendered guide link/code checks passed after the final public comment + changes. Desktop/narrow screenshot inspection remains unverified: local Chrome + screenshots were blank and the in-app browser refused file URLs. No bypass was + attempted. +- Proposal checking and 17 tool tests passed. OpenSpec 1.10.0 strict validation + passed in all 15 proposal roots before the final committed snapshot refresh. + +## Review and regression record + +Task reviews approved TLS/Cobalt without findings, and approved WASI and browser +code after the following reproduced defects were fixed: + +1. Connected UDP confused a transient EAGAIN with permanent initialization failure. + Immutable validation state now permits readiness retries. +2. Native DNS result cleanup freed canonical empty-list/string sentinels. Cleanup + now observes lengths, matching the pinned canonical ABI. +3. Cooperative cancellation could free a descriptor still borrowed by another + reactor poll. Cancellation completion waits for that borrow to end. +4. A main-thread callback destroying its context could recursively drain the SDK + queue and use a destroyed service. Allocator-owned shared control now survives + active delivery and discards queued callbacks safely. +5. A throwing handler move leaked operation storage. RAII owns the operation before + the move, and the failure path discards queued work without invoking it. + +Each review fix has a public failing regression before its correction and a scoped +approved re-review. The original UDP feature test had a weaker chronology: its +first run failed on sandbox networking, and the valid pristine-overlay failure +was replayed after implementation. It is not described as strict test-first TDD. + +The final whole-candidate review is recorded separately after candidate commits. + +## Controller decisions + +- The user's request supplies scope approval; no additional permission round was + needed. A mistaken scope interpretation would require local rework. +- Reuse the existing isolated worktree and leave the primary checkout untouched. + A wrong base would require rebasing the local candidate. +- Use disjoint task ownership and parent-owned shared files and commits. An + integration mistake would require local rework, not discarded unrelated edits. +- Do not change SDKs or repair upstream Cobalt issue 287. Use guards only for + compile-visible facts and runtime errors for host permissions. A changed SDK or + runtime requires new validation before broadening the matrix. +- Review frozen task-specific diffs before committing the combined candidate; + perform the final review against committed ranges. A missed integration defect + requires a candidate fix, not a waived test. diff --git a/libs/asio b/libs/asio index dad1aefb..a8d0f17b 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit dad1aefbe99f8a2cae4e2e3389779106a24cf3dc +Subproject commit a8d0f17bac7a0c1e3934a70070e6b22e1d3abfef diff --git a/tools/boost/Jamfile b/tools/boost/Jamfile index e3c7f5eb..4b41172d 100644 --- a/tools/boost/Jamfile +++ b/tools/boost/Jamfile @@ -312,7 +312,7 @@ rule cobalt-configuration ( properties * ) rule cobalt-platform-sources ( properties * ) { - if [ webcpp-target.target-of $(properties) ] = wasip3 + if [ webcpp-target.target-of $(properties) ] in wasip2 wasip3 { local threaded ; if multi in $(properties) @@ -329,9 +329,9 @@ rule cobalt-platform-sources ( properties * ) # Boost.Cobalt, with the macros of its own build: its sources see # BOOST_COBALT_SOURCE=1 and BOOST_COBALT_IO_SOURCE=1; users see # BOOST_COBALT_NO_LIB=1. Emscripten sources and users disable Asio threads -# consistently, without changing native thread support. Exception handling -# follows the consumer: result-based programs may disable it without a blanket -# configuration refusal. This does not guarantee every Cobalt operation works +# consistently on single threads; worker builds retain thread support. Exception +# handling follows the consumer: result-based programs may disable it without +# a blanket configuration refusal. This does not guarantee every operation works # without exceptions: moving a pending task creates an exception_ptr in Boost # 1.92, which libc++ aborts on when built with -fno-exceptions. compiled boost_cobalt : [ cobalt-sources ] @@ -339,14 +339,15 @@ compiled boost_cobalt : [ cobalt-sources ] : BOOST_COBALT_SOURCE=1 BOOST_COBALT_IO_SOURCE=1 /webcpp/cobalt-common//headers windows:/webcpp/asio-windows//headers - emscripten:BOOST_ASIO_DISABLE_THREADS + emscripten,single:BOOST_ASIO_DISABLE_THREADS @cobalt-configuration @cobalt-platform-sources : BOOST_COBALT_NO_LIB=1 /webcpp/cobalt-common//headers windows:/webcpp/asio-windows//headers + clang-wasip2:/webcpp/cobalt-wasip3//headers clang-wasip3:/webcpp/cobalt-wasip3//headers - emscripten:BOOST_ASIO_DISABLE_THREADS ; + emscripten,single:BOOST_ASIO_DISABLE_THREADS ; # Optional TLS wrapper, separate from the archive used by non-TLS consumers. alias boost_cobalt_io_ssl : /webcpp/cobalt-ssl//boost_cobalt_io_ssl ; diff --git a/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp b/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp index dd2081fc..85b3af2a 100644 --- a/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp +++ b/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -172,6 +173,15 @@ class wasi_resolve_op : public reactor_op, public wasi_resolver_node { } } + void append_endpoint(const ip::detail::endpoint& source) { + endpoint_type endpoint; + if (source.size() <= endpoint.capacity()) { + std::memcpy(endpoint.data(), source.data(), source.size()); + endpoint.resize(source.size()); + endpoints_.push_back(endpoint); + } + } + bool begin() { started_ = true; if (cancelled_) { @@ -198,13 +208,15 @@ class wasi_resolve_op : public reactor_op, public wasi_resolver_node { numeric("127.0.0.1", local_hints, endpoints_, v4_error); allow_v4_ = !v4_error && hints_.ai_family != AF_INET6; if (!endpoints_.empty()) - port_ = endpoints_.front().port(); + port_ = socket_ops::network_to_host_short( + reinterpret_cast(endpoints_.front().data())->sin_port); endpoints_.clear(); local_hints.ai_family = AF_INET6; numeric("::1", local_hints, endpoints_, v6_error); allow_v6_ = !v6_error && hints_.ai_family != AF_INET; if (!endpoints_.empty()) - port_ = endpoints_.front().port(); + port_ = socket_ops::network_to_host_short( + reinterpret_cast(endpoints_.front().data())->sin_port); endpoints_.clear(); if (!allow_v4_ && !allow_v6_) { ec_ = hints_.ai_family == AF_INET6 ? v6_error : v4_error; @@ -301,7 +313,8 @@ class wasi_resolve_op : public reactor_op, public wasi_resolver_node { } if (address.val.tag == NETWORK_IP_ADDRESS_IPV4 && self.allow_v4_) { auto const& a = address.val.val.ipv4; - self.endpoints_.emplace_back(ip::address_v4({a.f0, a.f1, a.f2, a.f3}), self.port_); + self.append_endpoint( + ip::detail::endpoint(ip::address_v4({a.f0, a.f1, a.f2, a.f3}), self.port_)); } else if (address.val.tag == NETWORK_IP_ADDRESS_IPV6 && self.allow_v6_) { auto const& a = address.val.val.ipv6; std::uint16_t const words[] = {a.f0, a.f1, a.f2, a.f3, a.f4, a.f5, a.f6, a.f7}; @@ -310,7 +323,7 @@ class wasi_resolve_op : public reactor_op, public wasi_resolver_node { bytes[2 * i] = static_cast(words[i] >> 8); bytes[2 * i + 1] = static_cast(words[i]); } - self.endpoints_.emplace_back(ip::address_v6(bytes), self.port_); + self.append_endpoint(ip::detail::endpoint(ip::address_v6(bytes), self.port_)); } } return not_done; diff --git a/tools/boost/asio-wasip3/Jamfile b/tools/boost/asio-wasip3/Jamfile index 9bbe3c98..64f61f80 100644 --- a/tools/boost/asio-wasip3/Jamfile +++ b/tools/boost/asio-wasip3/Jamfile @@ -47,6 +47,7 @@ rule configuration ( properties * ) } alias headers : : : : prepared.stamp + clang-wasip3:waitable include "-I\"$(OVERLAY)/include\"" @configuration ; explicit headers ; @@ -57,3 +58,19 @@ alias host-headers : : : : prepared.stamp "-I\"$(OVERLAY)/include\"" BOOST_ASIO_DISABLE_THREADS ; explicit host-headers ; + +make verified.stamp : verify.py wasi-libc/manifest.json : @verify + : $(OVERLAY) off ; +always verified.stamp ; +explicit verified.stamp ; +rule verify ( targets * : sources * : properties * ) +{ + SCRIPT on $(targets) = $(BUNDLE)/verify.py ; + SDK on $(targets) = [ webcpp-wasi.sdk $(WEBCPP_ROOT) ] ; +} +actions verify +{ + python3 "$(SCRIPT)" --sdk "$(SDK)" --stamp "$(<)" +} +obj waitable : waitable.cpp : include wasi-libc verified.stamp ; +explicit waitable ; diff --git a/tools/boost/asio-wasip3/README.md b/tools/boost/asio-wasip3/README.md index c6884aac..3562a5f7 100644 --- a/tools/boost/asio-wasip3/README.md +++ b/tools/boost/asio-wasip3/README.md @@ -32,10 +32,36 @@ buffer sequence before iovec truncation, then sends one contiguous datagram. Multiple nonempty buffers require a copy, allocated through the context for synchronous sends and the handler's associated allocator for asynchronous sends. The async operation owns the copy and frees it before invoking the handler. -UDP receive and connected `send`/`async_send` still reject multiple nonempty buffers. +Connected `send`/`async_send` use the same gather path. Datagram `receive`, +`receive_from` and their asynchronous forms receive one contiguous message and +scatter it across the original sequence, before any native iovec truncation. +Scratch storage uses the context allocator synchronously and the associated +handler allocator asynchronously. Truncated datagrams discard their remainder; +zero-capacity receives still consume one message. Single nonempty buffers need +no scratch allocation. Zero-byte operations use a live dummy byte when libc rejects a null pointer, without allocating a temporary buffer. +WASIp3 forward `async_resolve` uses the native asynchronous lowering of +`wasi:sockets/ip-name-lookup@0.3.0`, including in the cooperative thread profile. +A queued operation starts the host lookup after initiation returns. A private +waitable descriptor registers its subtask with libc's poll implementation and +Asio's existing select reactor, so unrelated sockets and timers can progress +without a polling interval or resolver worker. Cancellation removes the reactor +operation and releases the subtask, result and descriptor before the associated +handler runs. Numeric lookup and service parsing never initiate host DNS. +Canonical-name and IPv4-mapping flags remain unsupported by the native host API. +Reverse DNS behavior is unchanged. + +`waitable.cpp` is the only translation unit using private libc declarations. +`wasi-libc/manifest.json` pins their original source revision and hashes; +`verify.py` refuses a different SDK revision or changed snapshot. The canonical +lookup result layout and asynchronous import are private to this backend. SDK +bindings allocate host-returned lists through their canonical ABI allocator; +these are released explicitly, while operation, strings and endpoint scratch +storage use the handler's associated allocator. Boost's public resolver result +container retains its upstream allocator. + The patch makes no changes to wasi-libc. Upstream implementations of `sendmsg`/`recvmsg`, missing socket operations and additional cooperative C++ runtimes would allow some compatibility code to be removed. Do not replace @@ -66,6 +92,7 @@ Run from the superproject root: ```bash python3 tools/boost/asio-wasip3/prepare_test.py +python3 tools/boost/asio-wasip3/verify_test.py python3 tools/boost/asio-wasip3/run_test.py python3 tools/test/asio_wasip3_test.py b2 -a toolset=clang-wasip3 variant=release threading=single \ diff --git a/tools/boost/asio-wasip3/boost-1.92.patch b/tools/boost/asio-wasip3/boost-1.92.patch index 24445210..92b08fdb 100644 --- a/tools/boost/asio-wasip3/boost-1.92.patch +++ b/tools/boost/asio-wasip3/boost-1.92.patch @@ -468,13 +468,14 @@ #endif // BOOST_ASIO_DETAIL_NULL_SIGNAL_BLOCKER_HPP --- a/boost/asio/detail/reactive_socket_sendto_op.hpp +++ b/boost/asio/detail/reactive_socket_sendto_op.hpp -@@ -25,12 +25,81 @@ +@@ -25,12 +25,131 @@ #include #include +#if (defined(__wasip2__) || defined(__wasip3__)) +# include +# include ++# include +# include +# include +#endif @@ -494,7 +495,7 @@ +// Synchronous storage uses the context allocator; asynchronous storage uses +// the handler allocator and lives in the operation until completion/destruction. +// Remove this workaround when the pinned WASI SDK provides verified sendmsg -+// support. It does not add recvmsg or connected send/async_send support. ++// support. +template +class wasi_datagram_buffer : private noncopyable +{ @@ -546,11 +547,60 @@ + boost::asio::const_buffer buffer_; + boost::system::error_code error_; +}; ++// Reserve only the capacity that can hold one legal UDP message. All buffer ++// descriptors are visited before the platform iovec limit is applied. ++template ++class wasi_datagram_receive_buffer : private noncopyable ++{ ++public: ++ typedef typename std::allocator_traits::template ++ rebind_alloc byte_allocator; ++ ++ template ++ wasi_datagram_receive_buffer(const MutableBufferSequence& buffers, ++ const Allocator& allocator, bool enabled) ++ : storage_(byte_allocator(allocator)) ++ { ++ if (!enabled) ++ return; ++ std::size_t total = 0; ++ bool multiple = false; ++ auto end = boost::asio::buffer_sequence_end(buffers); ++ for (auto it = boost::asio::buffer_sequence_begin(buffers); it != end; ++it) ++ { ++ boost::asio::mutable_buffer current(*it); ++ if (current.size()) ++ { ++ multiple = multiple || total != 0; ++ buffer_ = current; ++ total += (std::min)(current.size(), std::size_t(65535) - total); ++ } ++ } ++ if (multiple) ++ { ++ storage_.resize(total); ++ buffer_ = boost::asio::buffer(storage_); ++ } ++ } ++ ++ boost::asio::mutable_buffer buffer() const { return buffer_; } ++ ++ template ++ void scatter(const MutableBufferSequence& buffers, std::size_t size) ++ { ++ if (!storage_.empty()) ++ boost::asio::buffer_copy(buffers, boost::asio::buffer(storage_), size); ++ } ++ ++private: ++ std::vector storage_; ++ boost::asio::mutable_buffer buffer_; ++}; +#endif // (defined(__wasip2__) || defined(__wasip3__)) template class reactive_socket_sendto_op_base : public reactor_op -@@ -46,6 +115,9 @@ +@@ -46,6 +165,9 @@ buffers_(buffers), destination_(endpoint), flags_(flags) @@ -560,7 +610,7 @@ { } -@@ -59,6 +131,18 @@ +@@ -59,6 +181,22 @@ ConstBufferSequence> bufs_type; status result; @@ -568,7 +618,11 @@ + if (o->wasi_datagram_) + { + if (o->wasi_invalid_) ++ { ++ // Enabling nonblocking mode can overwrite the construction-time error. ++ o->ec_ = boost::asio::error::message_size; + return done; ++ } + result = socket_ops::non_blocking_sendto1(o->socket_, + o->wasi_buffer_.data(), o->wasi_buffer_.size(), o->flags_, + o->destination_.data(), o->destination_.size(), @@ -579,7 +633,7 @@ if (bufs_type::is_single_buffer) { result = socket_ops::non_blocking_sendto1(o->socket_, -@@ -87,6 +171,12 @@ +@@ -87,6 +225,12 @@ ConstBufferSequence buffers_; Endpoint destination_; socket_base::message_flags flags_; @@ -592,7 +646,7 @@ }; template ( success_ec, socket, buffers, endpoint, flags, &reactive_socket_sendto_op::do_complete), @@ -613,7 +667,7 @@ } static void do_complete(void* owner, operation* base, -@@ -184,6 +285,11 @@ +@@ -184,6 +339,11 @@ } private: @@ -654,6 +708,36 @@ typedef buffer_sequence_adapter bufs_type; +@@ -356,6 +376,29 @@ + endpoint_type& sender_endpoint, socket_base::message_flags flags, + boost::system::error_code& ec) + { ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (impl.protocol_.type() == SOCK_DGRAM) ++ { ++ if (impl.socket_ == invalid_socket) ++ { ++ ec = boost::asio::error::bad_descriptor; ++ return 0; ++ } ++ wasi_datagram_receive_buffer> storage( ++ buffers, execution_context::allocator(this->context()), true); ++ auto buffer = storage.buffer(); ++ std::size_t addr_len = sender_endpoint.capacity(); ++ size_t size = socket_ops::sync_recvfrom1(impl.socket_, impl.state_, ++ buffer.data(), buffer.size(), flags, ++ sender_endpoint.data(), &addr_len, ec); ++ if (!ec) ++ { ++ sender_endpoint.resize(addr_len); ++ storage.scatter(buffers, size); ++ } ++ return size; ++ } ++#endif + typedef buffer_sequence_adapter bufs_type; + --- a/boost/asio/detail/signal_blocker.hpp +++ b/boost/asio/detail/signal_blocker.hpp @@ -19,7 +19,7 @@ @@ -884,7 +968,44 @@ timed_out = BOOST_ASIO_SOCKET_ERROR(ETIMEDOUT), --- a/boost/asio/detail/impl/select_reactor.ipp +++ b/boost/asio/detail/impl/select_reactor.ipp -@@ -228,7 +228,9 @@ +@@ -103,6 +103,9 @@ + for (int i = 0; i < max_ops; ++i) + op_queue_[i].get_all_operations(ops); + ++#if defined(__wasip3__) ++ ops.push(wasi_cancelled_ops_); ++#endif + timer_queues_.get_all_timers(ops); + + scheduler_.abandon_operations(ops); +@@ -180,6 +183,26 @@ + boost::asio::detail::mutex::scoped_lock lock(mutex_); + cancel_ops_unlocked(descriptor, boost::asio::error::operation_aborted); + } ++ ++#if defined(__wasip3__) ++void select_reactor::cancel_ops_after_poll(socket_type descriptor, ++ select_reactor::per_descriptor_data&) ++{ ++ boost::asio::detail::mutex::scoped_lock lock(mutex_); ++ if (!wasi_polling_) ++ { ++ cancel_ops_unlocked(descriptor, boost::asio::error::operation_aborted); ++ return; ++ } ++ bool need_interrupt = false; ++ for (int i = 0; i < max_ops; ++i) ++ need_interrupt = op_queue_[i].cancel_operations(descriptor, ++ wasi_cancelled_ops_, boost::asio::error::operation_aborted) ++ || need_interrupt; ++ if (need_interrupt) ++ interrupter_.interrupt(); ++} ++#endif + + void select_reactor::cancel_ops_by_key(socket_type descriptor, + select_reactor::per_descriptor_data&, +@@ -228,7 +251,9 @@ // Set up the descriptor sets. for (int i = 0; i < max_select_ops; ++i) fd_sets_[i].reset(); @@ -894,7 +1015,17 @@ socket_type max_fd = 0; bool have_work_to_do = !timer_queues_.all_empty(); for (int i = 0; i < max_select_ops; ++i) -@@ -267,6 +269,7 @@ +@@ -259,6 +284,9 @@ + timeval tv_buf = { 0, 0 }; + timeval* tv = usec ? get_timeout(usec, tv_buf) : &tv_buf; + ++#if defined(__wasip3__) ++ wasi_polling_ = true; ++#endif + lock.unlock(); + + // Block on the select call until descriptors become ready. +@@ -267,6 +295,7 @@ fd_sets_[read_op], fd_sets_[write_op], fd_sets_[except_op], tv, ec); // Reset the interrupter. @@ -902,14 +1033,21 @@ if (retval > 0 && fd_sets_[read_op].is_set(interrupter_.read_descriptor())) { if (!interrupter_.reset()) -@@ -281,6 +284,7 @@ +@@ -281,8 +310,14 @@ } --retval; } +#endif lock.lock(); ++#if defined(__wasip3__) ++ // socket_ops::select has returned and libc released every borrowed waitable. ++ wasi_polling_ = false; ++ ops.push(wasi_cancelled_ops_); ++#endif + // Dispatch all ready operations. + if (retval > 0) --- a/boost/asio/detail/select_interrupter.hpp +++ b/boost/asio/detail/select_interrupter.hpp @@ -19,7 +19,9 @@ @@ -943,22 +1081,26 @@ #elif defined(BOOST_ASIO_HAS_EVENTFD) --- a/boost/asio/detail/resolver_service.hpp +++ b/boost/asio/detail/resolver_service.hpp -@@ -25,6 +25,10 @@ +@@ -25,6 +25,14 @@ #include #include #include + -+#if defined(__wasip2__) -+# include ++#if defined(__wasip2__) || defined(__wasip3__) ++# if defined(__wasip3__) ++# include ++# else ++# include ++# endif +#endif #include -@@ -64,6 +68,18 @@ +@@ -64,6 +72,18 @@ { } -+#if defined(__wasip2__) ++#if defined(__wasip2__) || defined(__wasip3__) + void construct(implementation_type& impl) + { + wasi_resolver_construct(impl, thread_pool_.context()); @@ -973,17 +1115,17 @@ // Resolve a query to a list of entries. results_type resolve(implementation_type&, const query_type& qry, boost::system::error_code& ec) -@@ -84,6 +100,9 @@ +@@ -84,6 +104,9 @@ void async_resolve(implementation_type& impl, const query_type& qry, Handler& handler, const IoExecutor& io_ex) { -+#if defined(__wasip2__) ++#if defined(__wasip2__) || defined(__wasip3__) + wasi_async_resolve(impl, thread_pool_.context(), qry, handler, io_ex); +#else // Allocate and construct an operation to wrap the handler. typedef resolve_query_op op; typename op::ptr p = { boost::asio::detail::addressof(handler), -@@ -95,6 +114,7 @@ +@@ -95,6 +118,7 @@ thread_pool_.start_resolve_op(p.p); p.v = p.p = 0; @@ -991,3 +1133,396 @@ } // Resolve an endpoint to a list of entries. +--- a/boost/asio/detail/reactive_socket_service_base.hpp ++++ b/boost/asio/detail/reactive_socket_service_base.hpp +@@ -16,6 +16,9 @@ + #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + + #include ++#if defined(__wasip2__) || defined(__wasip3__) ++# include ++#endif + + #if !defined(BOOST_ASIO_HAS_IOCP) \ + && !defined(BOOST_ASIO_WINDOWS_RUNTIME) \ +@@ -255,6 +258,24 @@ + const ConstBufferSequence& buffers, + socket_base::message_flags flags, boost::system::error_code& ec) + { ++#if defined(__wasip2__) || defined(__wasip3__) ++ if ((impl.state_ & socket_ops::datagram_oriented) != 0) ++ { ++ if (impl.socket_ == invalid_socket) ++ { ++ ec = boost::asio::error::bad_descriptor; ++ return 0; ++ } ++ wasi_datagram_buffer> storage( ++ buffers, execution_context::allocator(reactor_.context()), true); ++ if ((ec = storage.error())) ++ return 0; ++ auto buffer = storage.buffer(); ++ size_t size = socket_ops::sync_send1(impl.socket_, impl.state_, ++ buffer.data(), buffer.size(), flags, ec); ++ return size; ++ } ++#endif + typedef buffer_sequence_adapter bufs_type; + +@@ -361,6 +382,24 @@ + const MutableBufferSequence& buffers, + socket_base::message_flags flags, boost::system::error_code& ec) + { ++#if defined(__wasip2__) || defined(__wasip3__) ++ if ((impl.state_ & socket_ops::datagram_oriented) != 0) ++ { ++ if (impl.socket_ == invalid_socket) ++ { ++ ec = boost::asio::error::bad_descriptor; ++ return 0; ++ } ++ wasi_datagram_receive_buffer> storage( ++ buffers, execution_context::allocator(reactor_.context()), true); ++ auto buffer = storage.buffer(); ++ size_t size = socket_ops::sync_recv1(impl.socket_, impl.state_, ++ buffer.data(), buffer.size(), flags, ec); ++ if (!ec) ++ storage.scatter(buffers, size); ++ return size; ++ } ++#endif + typedef buffer_sequence_adapter bufs_type; + +--- a/boost/asio/detail/reactive_socket_send_op.hpp ++++ b/boost/asio/detail/reactive_socket_send_op.hpp +@@ -16,6 +16,9 @@ + #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + + #include ++#if defined(__wasip2__) || defined(__wasip3__) ++# include ++#endif + #include + #include + #include +@@ -46,6 +49,9 @@ + state_(state), + buffers_(buffers), + flags_(flags) ++#if defined(__wasip2__) || defined(__wasip3__) ++ , wasi_datagram_(false), wasi_invalid_(false) ++#endif + { + } + +@@ -59,6 +65,21 @@ + ConstBufferSequence> bufs_type; + + status result; ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (o->wasi_datagram_) ++ { ++ if (o->wasi_invalid_) ++ { ++ // Enabling nonblocking mode can overwrite the construction-time error. ++ o->ec_ = boost::asio::error::message_size; ++ return done; ++ } ++ result = socket_ops::non_blocking_send1(o->socket_, ++ o->wasi_buffer_.data(), o->wasi_buffer_.size(), o->flags_, ++ o->ec_, o->bytes_transferred_) ? done : not_done; ++ } ++ else ++#endif + if (bufs_type::is_single_buffer) + { + result = socket_ops::non_blocking_send1(o->socket_, +@@ -95,6 +116,13 @@ + socket_ops::state_type state_; + ConstBufferSequence buffers_; + socket_base::message_flags flags_; ++#if defined(__wasip2__) || defined(__wasip3__) ++protected: ++ boost::asio::const_buffer wasi_buffer_; ++ bool wasi_datagram_; ++ bool wasi_invalid_; ++#endif ++ + }; + + template +@@ -113,9 +141,20 @@ + Handler& handler, const IoExecutor& io_ex) + : reactive_socket_send_op_base(success_ec, socket, + state, buffers, flags, &reactive_socket_send_op::do_complete), ++#if defined(__wasip2__) || defined(__wasip3__) ++ wasi_storage_(buffers, boost::asio::get_associated_allocator(handler), ++ (state & socket_ops::datagram_oriented) != 0), ++#endif + handler_(static_cast(handler)), + work_(handler_, io_ex) + { ++#if defined(__wasip2__) || defined(__wasip3__) ++ this->wasi_datagram_ = (state & socket_ops::datagram_oriented) != 0; ++ this->wasi_buffer_ = wasi_storage_.buffer(); ++ this->wasi_invalid_ = !!wasi_storage_.error(); ++ if (this->wasi_datagram_ && this->wasi_invalid_) ++ this->ec_ = wasi_storage_.error(); ++#endif + } + + static void do_complete(void* owner, operation* base, +@@ -190,6 +229,9 @@ + } + + private: ++#if defined(__wasip2__) || defined(__wasip3__) ++ wasi_datagram_buffer> wasi_storage_; ++#endif + Handler handler_; + handler_work work_; + }; +--- a/boost/asio/detail/reactive_socket_recv_op.hpp ++++ b/boost/asio/detail/reactive_socket_recv_op.hpp +@@ -16,6 +16,9 @@ + #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + + #include ++#if defined(__wasip2__) || defined(__wasip3__) ++# include ++#endif + #include + #include + #include +@@ -46,6 +49,9 @@ + state_(state), + buffers_(buffers), + flags_(flags) ++#if defined(__wasip2__) || defined(__wasip3__) ++ , wasi_datagram_(false) ++#endif + { + } + +@@ -59,6 +65,15 @@ + MutableBufferSequence> bufs_type; + + status result; ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (o->wasi_datagram_) ++ { ++ result = socket_ops::non_blocking_recv1(o->socket_, ++ o->wasi_buffer_.data(), o->wasi_buffer_.size(), o->flags_, false, ++ o->ec_, o->bytes_transferred_) ? done : not_done; ++ } ++ else ++#endif + if (bufs_type::is_single_buffer) + { + result = socket_ops::non_blocking_recv1(o->socket_, +@@ -110,8 +125,16 @@ + private: + socket_type socket_; + socket_ops::state_type state_; ++protected: + MutableBufferSequence buffers_; ++private: + socket_base::message_flags flags_; ++#if defined(__wasip2__) || defined(__wasip3__) ++protected: ++ boost::asio::mutable_buffer wasi_buffer_; ++ bool wasi_datagram_; ++#endif ++ + }; + + template +@@ -130,9 +153,17 @@ + Handler& handler, const IoExecutor& io_ex) + : reactive_socket_recv_op_base(success_ec, socket, + state, buffers, flags, &reactive_socket_recv_op::do_complete), ++#if defined(__wasip2__) || defined(__wasip3__) ++ wasi_storage_(buffers, boost::asio::get_associated_allocator(handler), ++ (state & socket_ops::datagram_oriented) != 0), ++#endif + handler_(static_cast(handler)), + work_(handler_, io_ex) + { ++#if defined(__wasip2__) || defined(__wasip3__) ++ this->wasi_datagram_ = (state & socket_ops::datagram_oriented) != 0; ++ this->wasi_buffer_ = wasi_storage_.buffer(); ++#endif + } + + static void do_complete(void* owner, operation* base, +@@ -162,6 +193,10 @@ + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = boost::asio::detail::addressof(handler.handler_); ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (owner && o->wasi_datagram_ && !o->ec_) ++ o->wasi_storage_.scatter(o->buffers_, o->bytes_transferred_); ++#endif + p.reset(); + + // Make the upcall if required. +@@ -199,6 +234,10 @@ + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = boost::asio::detail::addressof(handler.handler_); ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (o->wasi_datagram_ && !o->ec_) ++ o->wasi_storage_.scatter(o->buffers_, o->bytes_transferred_); ++#endif + p.reset(); + + BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); +@@ -207,6 +246,9 @@ + } + + private: ++#if defined(__wasip2__) || defined(__wasip3__) ++ wasi_datagram_receive_buffer> wasi_storage_; ++#endif + Handler handler_; + handler_work work_; + }; +--- a/boost/asio/detail/reactive_socket_recvfrom_op.hpp ++++ b/boost/asio/detail/reactive_socket_recvfrom_op.hpp +@@ -16,6 +16,9 @@ + #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + + #include ++#if defined(__wasip2__) || defined(__wasip3__) ++# include ++#endif + #include + #include + #include +@@ -47,6 +50,9 @@ + buffers_(buffers), + sender_endpoint_(endpoint), + flags_(flags) ++#if defined(__wasip2__) || defined(__wasip3__) ++ , wasi_datagram_(false) ++#endif + { + } + +@@ -61,6 +67,16 @@ + + std::size_t addr_len = o->sender_endpoint_.capacity(); + status result; ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (o->wasi_datagram_) ++ { ++ result = socket_ops::non_blocking_recvfrom1(o->socket_, ++ o->wasi_buffer_.data(), o->wasi_buffer_.size(), o->flags_, ++ o->sender_endpoint_.data(), &addr_len, ++ o->ec_, o->bytes_transferred_) ? done : not_done; ++ } ++ else ++#endif + if (bufs_type::is_single_buffer) + { + result = socket_ops::non_blocking_recvfrom1( +@@ -90,9 +106,17 @@ + private: + socket_type socket_; + int protocol_type_; ++protected: + MutableBufferSequence buffers_; ++private: + Endpoint& sender_endpoint_; + socket_base::message_flags flags_; ++#if defined(__wasip2__) || defined(__wasip3__) ++protected: ++ boost::asio::mutable_buffer wasi_buffer_; ++ bool wasi_datagram_; ++#endif ++ + }; + + template ( + success_ec, socket, protocol_type, buffers, endpoint, flags, + &reactive_socket_recvfrom_op::do_complete), ++#if defined(__wasip2__) || defined(__wasip3__) ++ wasi_storage_(buffers, boost::asio::get_associated_allocator(handler), ++ protocol_type == SOCK_DGRAM), ++#endif + handler_(static_cast(handler)), + work_(handler_, io_ex) + { ++#if defined(__wasip2__) || defined(__wasip3__) ++ this->wasi_datagram_ = protocol_type == SOCK_DGRAM; ++ this->wasi_buffer_ = wasi_storage_.buffer(); ++#endif + } + + static void do_complete(void* owner, operation* base, +@@ -147,6 +179,10 @@ + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = boost::asio::detail::addressof(handler.handler_); ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (owner && o->wasi_datagram_ && !o->ec_) ++ o->wasi_storage_.scatter(o->buffers_, o->bytes_transferred_); ++#endif + p.reset(); + + // Make the upcall if required. +@@ -185,6 +221,10 @@ + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = boost::asio::detail::addressof(handler.handler_); ++#if defined(__wasip2__) || defined(__wasip3__) ++ if (o->wasi_datagram_ && !o->ec_) ++ o->wasi_storage_.scatter(o->buffers_, o->bytes_transferred_); ++#endif + p.reset(); + + BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); +@@ -193,6 +233,9 @@ + } + + private: ++#if defined(__wasip2__) || defined(__wasip3__) ++ wasi_datagram_receive_buffer> wasi_storage_; ++#endif + Handler handler_; + handler_work work_; + }; +--- a/boost/asio/detail/select_reactor.hpp ++++ b/boost/asio/detail/select_reactor.hpp +@@ -125,6 +125,12 @@ + // operation_aborted error. + BOOST_ASIO_DECL void cancel_ops(socket_type descriptor, per_descriptor_data&); + ++#if defined(__wasip3__) ++ // Keep a borrowed native waitable alive until the current poll releases it. ++ BOOST_ASIO_DECL void cancel_ops_after_poll(socket_type descriptor, ++ per_descriptor_data&); ++#endif ++ + // Cancel all operations associated with the given descriptor and key. The + // handlers associated with the descriptor will be invoked with the + // operation_aborted error. +@@ -230,6 +236,14 @@ + + // The queues of read, write and except operations. + reactor_op_queue op_queue_[max_ops]; ++ ++#if defined(__wasip3__) ++ // Cancellation may be delivered by a different cooperative runner while the ++ // reactor is suspended in libc poll. Do not expose these completions until ++ // that poll has released its descriptor references and waitable membership. ++ bool wasi_polling_ = false; ++ op_queue wasi_cancelled_ops_; ++#endif + + // The file descriptor sets to be passed to the select system call. + fd_set_adapter fd_sets_[max_select_ops]; diff --git a/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp b/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp new file mode 100644 index 00000000..81f187ed --- /dev/null +++ b/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp @@ -0,0 +1,368 @@ +// 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) +#ifndef WEBCPP_ASIO_DETAIL_WASI_P3_RESOLVER_HPP +#define WEBCPP_ASIO_DETAIL_WASI_P3_RESOLVER_HPP +#if defined(__wasip3__) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// This adapter is included only by the checked WASIp3 Boost overlay. +namespace boost { +namespace asio { +BOOST_ASIO_INLINE_NAMESPACE_BEGIN + +namespace detail { + +struct wasi_resolver_state; + +struct wasi_resolver_node { + wasi_resolver_state* owner = nullptr; + wasi_resolver_node* next = nullptr; + void (*cancel)(wasi_resolver_node*) = nullptr; + void detach(); +}; + +struct wasi_resolver_state { + wasi_resolver_node* head = nullptr; + + void cancel_all() { + while (head) { + auto* node = head; + node->detach(); + node->cancel(node); + } + } + + ~wasi_resolver_state() { cancel_all(); } +}; + +inline void wasi_resolver_node::detach() { + if (!owner) + return; + auto** current = &owner->head; + while (*current != this) + current = &(*current)->next; + *current = next; + owner = nullptr; + next = nullptr; +} + +inline void wasi_resolver_construct(std::shared_ptr& impl, execution_context& context) { + impl = std::allocate_shared( + execution_context::allocator(context)); +} + +inline void wasi_resolver_cancel(std::shared_ptr& impl) { + if (impl) + static_cast(impl.get())->cancel_all(); +} + +inline boost::system::error_code wasi_resolver_error(unsigned char error) { + switch (error) { + case IP_NAME_LOOKUP_ERROR_CODE_ACCESS_DENIED: return boost::asio::error::access_denied; + case IP_NAME_LOOKUP_ERROR_CODE_INVALID_ARGUMENT: + return boost::asio::error::invalid_argument; + case IP_NAME_LOOKUP_ERROR_CODE_NAME_UNRESOLVABLE: return boost::asio::error::host_not_found; + case IP_NAME_LOOKUP_ERROR_CODE_TEMPORARY_RESOLVER_FAILURE: + return boost::asio::error::host_not_found_try_again; + default: return boost::asio::error::no_recovery; + } +} + +template +class wasi_resolve_op : public reactor_op, public wasi_resolver_node { + using query_type = boost::asio::ip::basic_resolver_query; + using results_type = boost::asio::ip::basic_resolver_results; + using endpoint_type = typename Protocol::endpoint; + using allocator_type = associated_allocator_t; + using char_allocator = + typename std::allocator_traits::template rebind_alloc; + using endpoint_allocator = + typename std::allocator_traits::template rebind_alloc; + using string_type = std::basic_string, char_allocator>; + using slot_type = associated_cancellation_slot_t; + + select_reactor& reactor_; + select_reactor::per_descriptor_data reactor_data_{}; + string_type host_; + string_type service_; + addrinfo_type hints_; + std::vector endpoints_; + Handler handler_; + handler_work work_; + slot_type slot_; + webcpp_asio_wasip3::waitable_descriptor descriptor_{}; + webcpp_asio_wasip3::lookup_result result_{}; + int fd_ = -1; + bool has_result_ = false; + bool started_ = false; + bool waiting_ = false; + bool cancelled_ = false; + unsigned short port_ = 0; + bool allow_v4_ = true; + bool allow_v6_ = true; + + struct slot_cancel { + wasi_resolve_op* operation; + + void operator()(cancellation_type_t type) { + if (type != cancellation_type::none) + operation->request_cancel(); + } + }; + + void request_cancel() { + cancelled_ = true; + if (waiting_) + reactor_.cancel_ops_after_poll(fd_, reactor_data_); + } + + // Only numeric address parsing and the libc service table are used here. + // AI_NUMERICHOST prevents this helper from ever initiating host DNS. + void numeric(const char* host, addrinfo_type hints, + std::vector& output, + boost::system::error_code& ec) { + hints.ai_flags |= AI_NUMERICHOST; + addrinfo_type* addresses = nullptr; + socket_ops::getaddrinfo(host, service_.c_str(), hints, &addresses, ec); + + struct address_owner { + addrinfo_type* value; + + ~address_owner() { + if (value) + socket_ops::freeaddrinfo(value); + } + } owner{addresses}; + + if (ec) + return; + for (auto* entry = addresses; entry; entry = entry->ai_next) { + if (entry->ai_family != AF_INET && entry->ai_family != AF_INET6) + continue; + endpoint_type endpoint; + if (entry->ai_addrlen > endpoint.capacity()) + continue; + std::memcpy(endpoint.data(), entry->ai_addr, entry->ai_addrlen); + endpoint.resize(entry->ai_addrlen); + output.push_back(endpoint); + } + } + + void append_endpoint(const ip::detail::endpoint& source) { + endpoint_type endpoint; + if (source.size() <= endpoint.capacity()) { + std::memcpy(endpoint.data(), source.data(), source.size()); + endpoint.resize(source.size()); + endpoints_.push_back(endpoint); + } + } + + bool begin() { + started_ = true; + if (cancelled_) { + ec_ = boost::asio::error::operation_aborted; + return false; + } + // WASI returns addresses, not canonical names or IPv4 mapping policy. + if (hints_.ai_flags & (AI_CANONNAME | AI_V4MAPPED | AI_ALL)) { + ec_ = boost::asio::error::operation_not_supported; + return false; + } + numeric(host_.empty() ? nullptr : host_.c_str(), hints_, endpoints_, ec_); + if (!ec_ || (hints_.ai_flags & AI_NUMERICHOST)) + return false; + if (ec_ != boost::asio::error::host_not_found && + ec_ != boost::asio::error::host_not_found_try_again) + return false; + + // Validate the service and implement AI_ADDRCONFIG using libc's local + // numeric-family checks, before starting the asynchronous name lookup. + auto local_hints = hints_; + local_hints.ai_family = AF_INET; + boost::system::error_code v4_error, v6_error; + numeric("127.0.0.1", local_hints, endpoints_, v4_error); + allow_v4_ = !v4_error && hints_.ai_family != AF_INET6; + if (!endpoints_.empty()) + port_ = socket_ops::network_to_host_short( + reinterpret_cast(endpoints_.front().data())->sin_port); + endpoints_.clear(); + local_hints.ai_family = AF_INET6; + numeric("::1", local_hints, endpoints_, v6_error); + allow_v6_ = !v6_error && hints_.ai_family != AF_INET; + if (!endpoints_.empty()) + port_ = socket_ops::network_to_host_short( + reinterpret_cast(endpoints_.front().data())->sin_port); + endpoints_.clear(); + if (!allow_v4_ && !allow_v6_) { + ec_ = hints_.ai_family == AF_INET6 ? v6_error : v4_error; + if (!ec_) + ec_ = boost::asio::error::host_not_found; + return false; + } + ec_.clear(); + auto status = webcpp_asio_wasip3::start(host_.data(), host_.size(), result_); + descriptor_.state = WASIP3_SUBTASK_STATE(status); + descriptor_.handle = WASIP3_SUBTASK_HANDLE(status); + if (descriptor_.state == WASIP3_SUBTASK_RETURNED) { + has_result_ = true; + perform_lookup(this); + return false; + } + fd_ = webcpp_asio_wasip3::open(descriptor_); + if (fd_ < 0) { + ec_ = boost::system::error_code(errno, boost::asio::error::get_system_category()); + return false; + } + int const registration = reactor_.register_descriptor(fd_, reactor_data_); + if (registration != 0) { + ec_ = + boost::system::error_code(registration, boost::asio::error::get_system_category()); + return false; + } + waiting_ = true; + reactor_.start_op(select_reactor::read_op, fd_, reactor_data_, this, false, false); + return true; + } + +public: + BOOST_ASIO_DEFINE_HANDLER_PTR(wasi_resolve_op); + + wasi_resolve_op(wasi_resolver_state& state, execution_context& context, query_type const& query, + Handler& handler, IoExecutor const& executor) + : reactor_op({}, &perform_lookup, &complete), + reactor_(boost::asio::use_service(context)), + host_(query.host_name().c_str(), char_allocator(get_associated_allocator(handler))), + service_(query.service_name().c_str(), char_allocator(get_associated_allocator(handler))), + hints_(query.hints()), + endpoints_(endpoint_allocator(get_associated_allocator(handler))), + handler_(static_cast(handler)), + work_(handler_, executor), + slot_(get_associated_cancellation_slot(handler_)) { + reactor_.init_task(); + if (slot_.is_connected()) + slot_.template emplace(this); + owner = &state; + next = state.head; + state.head = this; + cancel = [](wasi_resolver_node* node) { + static_cast(node)->request_cancel(); + }; + } + + ~wasi_resolve_op() { + detach(); + if (slot_.is_connected()) + slot_.clear(); + // No reactor operations refer to the descriptor at completion/shutdown. + if (fd_ >= 0) + ::close(fd_); + webcpp_asio_wasip3::release(descriptor_); + if (has_result_ || descriptor_.state == WASIP3_SUBTASK_RETURNED) + webcpp_asio_wasip3::free_result(result_); + } + + static status perform_lookup(reactor_op* base) { + auto& self = *static_cast(base); + if (self.descriptor_.state != WASIP3_SUBTASK_RETURNED) + return not_done; + self.has_result_ = true; + const auto* data = self.result_.bytes.data(); + if (data[0] != std::byte{0}) { + self.ec_ = wasi_resolver_error(static_cast(data[sizeof(void*)])); + return done; + } + ip_name_lookup_list_ip_address_t addresses; + std::memcpy(&addresses, data + sizeof(void*), sizeof(addresses)); + for (std::size_t index = 0; index != addresses.len; ++index) { + const auto& address = addresses.ptr[index]; + if (address.tag == SOCKETS_IP_ADDRESS_IPV4 && self.allow_v4_) { + const auto& a = address.val.ipv4; + self.append_endpoint( + ip::detail::endpoint(ip::address_v4({a.f0, a.f1, a.f2, a.f3}), self.port_)); + } else if (address.tag == SOCKETS_IP_ADDRESS_IPV6 && self.allow_v6_) { + const auto& a = address.val.ipv6; + const std::uint16_t words[] = {a.f0, a.f1, a.f2, a.f3, a.f4, a.f5, a.f6, a.f7}; + ip::address_v6::bytes_type bytes{}; + for (std::size_t i = 0; i != 8; ++i) { + bytes[2 * i] = static_cast(words[i] >> 8); + bytes[2 * i + 1] = static_cast(words[i]); + } + self.append_endpoint(ip::detail::endpoint(ip::address_v6(bytes), self.port_)); + } + } + if (self.endpoints_.empty()) + self.ec_ = boost::asio::error::host_not_found; + return done; + } + + static void complete(void* completion_owner, operation* base, boost::system::error_code const&, + std::size_t) { + auto* self = static_cast(base); + ptr memory = {std::addressof(self->handler_), self, self}; + if (completion_owner && !self->started_ && self->begin()) { + memory.v = memory.p = nullptr; + return; + } + self->waiting_ = false; + if (self->cancelled_) + self->ec_ = boost::asio::error::operation_aborted; + handler_work work( + static_cast&&>(self->work_)); + binder2 handler(self->handler_, self->ec_, + results_type{}); + memory.h = std::addressof(handler.handler_); + if (completion_owner && !self->ec_) { + // Boost's public result container retains its upstream allocator. + handler.arg2_ = + results_type::create(self->endpoints_.begin(), self->endpoints_.end(), + std::string(self->host_.data(), self->host_.size()), + std::string(self->service_.data(), self->service_.size())); + } + memory.reset(); + if (completion_owner) + work.complete(handler, handler.handler_); + } +}; + +template +void wasi_async_resolve(std::shared_ptr& impl, execution_context& context, + typename boost::asio::ip::basic_resolver_query const& query, + Handler& handler, IoExecutor const& executor) { + if (!impl) + wasi_resolver_construct(impl, context); + using op = wasi_resolve_op; + typename op::ptr memory = {std::addressof(handler), op::ptr::allocate(handler), nullptr}; + memory.p = new (memory.v) + op(*static_cast(impl.get()), context, query, handler, executor); + boost::asio::use_service(context).post_immediate_completion(memory.p, false); + memory.v = memory.p = nullptr; +} + +} // namespace detail + +BOOST_ASIO_INLINE_NAMESPACE_END +} // namespace asio +} // namespace boost +#endif // __wasip3__ +#endif // WEBCPP_ASIO_DETAIL_WASI_P3_RESOLVER_HPP diff --git a/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_waitable.hpp b/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_waitable.hpp new file mode 100644 index 00000000..10727d8a --- /dev/null +++ b/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_waitable.hpp @@ -0,0 +1,31 @@ +// 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) +#ifndef WEBCPP_ASIO_DETAIL_WASI_WAITABLE_HPP +#define WEBCPP_ASIO_DETAIL_WASI_WAITABLE_HPP +#include +#include +#include +#include + +namespace webcpp_asio_wasip3 { +// Stable storage is owned by the resolver operation until descriptor close. +struct waitable_descriptor { + alignas(std::max_align_t) std::array opaque{}; + wasip3_subtask_t handle = 0; + wasip3_subtask_state_t state = WASIP3_SUBTASK_RETURNED; +}; + +// Pinned canonical result layout for result, error-code>. +struct lookup_result { + alignas(void*) std::array bytes{}; +}; + +int open(waitable_descriptor& storage); +void release(waitable_descriptor& storage); +wasip3_subtask_status_t start(const char* host, std::size_t size, lookup_result& result); +void free_result(lookup_result& result); +} // namespace webcpp_asio_wasip3 +#endif diff --git a/tools/boost/asio-wasip3/manifest.json b/tools/boost/asio-wasip3/manifest.json index 44bad91b..6f088993 100644 --- a/tools/boost/asio-wasip3/manifest.json +++ b/tools/boost/asio-wasip3/manifest.json @@ -27,11 +27,11 @@ }, "boost/asio/detail/reactive_socket_sendto_op.hpp": { "before": "1f8e02cf41fea19813b97ed8abdb77f64432b2168cd7cfcad86bea36aea1b4df", - "after": "a64bdbab55fe71a178ded3fe1f81473e52a9adee6fba4509a1720de237a0732a" + "after": "ff72ed6496b9f6c3ea88213f83433e470ef11db948637aefafecbc11d23c9e4b" }, "boost/asio/detail/reactive_socket_service.hpp": { "before": "5f68f1e43559adab6ec869f989a33c1295e0fafbb9ce7f27f4c0f205cfb0bbb2", - "after": "486d9c8d7962dd9313efaac40dcdf240901e64d1672e58ccd30c499db1f0fe16" + "after": "fb5e204b25a39c993c3cbb7480fc1e305952ea2ab5180418a312894b8e938b57" }, "boost/asio/detail/signal_blocker.hpp": { "before": "b46eb959862d0b1643f244a743a2366aff3f0acd7638a5c3cfa78dc826dd4df9", @@ -47,7 +47,7 @@ }, "boost/asio/detail/impl/select_reactor.ipp": { "before": "4e6df639193d0c93d2a9b3e2ead005824a6a3c921d1382c3ce72e5ce959e6a48", - "after": "f1a671b45aafe10afe156748b1a0c01d05dba9ded02b7baef57bd61d445202b2" + "after": "6587f498614375ba046e799c434871ecb682854f219d2ca0cb0685d457341998" }, "boost/asio/detail/select_interrupter.hpp": { "before": "debfbfa6e8915f7123229d2031b4704b1b95edcb4590f4d9a5b25c8cdd4105d5", @@ -55,7 +55,27 @@ }, "boost/asio/detail/resolver_service.hpp": { "before": "8ec1a1f84c3de50a4bf85e9ae5f2247ceb10cb36970c2bcaa3598587fa3acb50", - "after": "206411e63f5e34f028bd9c7a09a2866c61b1f8d2c3d1f7dba39357ede2afc733" + "after": "d56d25b9795e5da2420f63f1c511520e515f20e76e0afa601c70a56c8f78812d" + }, + "boost/asio/detail/reactive_socket_service_base.hpp": { + "before": "cd6aca62ed4c72088946f85f968f6005d6b72ec7ba4d0d54b244b64963c5668e", + "after": "230282cd2f1dfcf196b6c255e90af7cc069cbf9987bf9c3962bbfb134ccbd3ef" + }, + "boost/asio/detail/reactive_socket_send_op.hpp": { + "before": "32e0b1a85875a4b352a5f32afb1e07a2397b5a20c3de0580a1b0ecfb9681ab45", + "after": "2ac6aae36c0812feb5d2bb7da405419e4f9d2af84adc4c656115f00e39e45f25" + }, + "boost/asio/detail/reactive_socket_recv_op.hpp": { + "before": "ffd1dfeb9997f8991e0daa8f85bf72e4aaa555857e8a99cc99faa5ee76e4b878", + "after": "adcd584194aeff30bcd23dc7248c1068eb0a939f6ef0c980c786f9fe8799cb3d" + }, + "boost/asio/detail/reactive_socket_recvfrom_op.hpp": { + "before": "6f2b4e781fcfbafda3b06e26e7ba57f7fbe207571b524e617d621ee3f7b0b24b", + "after": "668eaeb1f563dc5c9ad69d1c7f4b7888066bbe814cf3cac83a138281daf17acb" + }, + "boost/asio/detail/select_reactor.hpp": { + "before": "c00df2bc8876796f774c090d65d1b61d72f96f37611e7bdf72ea571afccd1fc8", + "after": "e46bdac4c17852f4c3a08340d63c0f6d93234271cf53cc23bdaff182115fc74c" } } } diff --git a/tools/boost/asio-wasip3/verify.py b/tools/boost/asio-wasip3/verify.py new file mode 100644 index 00000000..53540e2e --- /dev/null +++ b/tools/boost/asio-wasip3/verify.py @@ -0,0 +1,61 @@ +#!/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) +"""Verify the private wasi-libc ABI used by the P3 waitable descriptor bridge.""" +import argparse +import hashlib +import json +from pathlib import Path + + +def verify(sdk: Path, bundle: Path): + manifest = json.loads((bundle / 'wasi-libc/manifest.json').read_text()) + version = (sdk / 'VERSION').read_text().splitlines() + expected = 'wasi-libc: ' + manifest['commit'][:12] + if not version or version[0] != manifest['sdk'] or expected not in version: + raise ValueError('WASIp3 waitables require wasi-sdk ' + manifest['sdk'] + + ' with ' + expected + '; revalidate the bridge before changing SDK') + verify_bundle(bundle) + + +def verify_bundle(bundle: Path): + manifest = json.loads((bundle / 'wasi-libc/manifest.json').read_text()) + expected_files = set(manifest['files']) | {'manifest.json'} + for path in (bundle / 'wasi-libc').rglob('*'): + if path.is_symlink(): + raise ValueError('private wasi-libc snapshot contains a symlink: ' + str(path)) + relative = path.relative_to(bundle / 'wasi-libc').as_posix() + if path.is_file() and relative not in expected_files: + raise ValueError('private wasi-libc snapshot contains an unlisted file: ' + str(path)) + for name, expected_hash in manifest['files'].items(): + path = Path(name) + if path.is_absolute() or '..' in path.parts: + raise ValueError('invalid private ABI manifest path') + actual = hashlib.sha256((bundle / 'wasi-libc' / path).read_bytes()).hexdigest() + if actual != expected_hash: + raise ValueError('private wasi-libc header changed: ' + name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--sdk', type=Path) + parser.add_argument('--bundle', type=Path, default=Path(__file__).resolve().parent) + parser.add_argument('--stamp', type=Path) + args = parser.parse_args() + try: + if args.sdk: + verify(args.sdk, args.bundle) + else: + verify_bundle(args.bundle) + except (OSError, ValueError) as error: + parser.exit(1, str(error) + '\n') + if args.stamp: + args.stamp.parent.mkdir(parents=True, exist_ok=True) + args.stamp.write_text('WASIp3 waitable ABI verified\n') + + +if __name__ == '__main__': + main() diff --git a/tools/boost/asio-wasip3/verify_test.py b/tools/boost/asio-wasip3/verify_test.py new file mode 100644 index 00000000..c1b54c70 --- /dev/null +++ b/tools/boost/asio-wasip3/verify_test.py @@ -0,0 +1,48 @@ +# 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) +import shutil +import tempfile +import unittest +from pathlib import Path +from verify import verify, verify_bundle + +HERE = Path(__file__).resolve().parent + + +class ABI(unittest.TestCase): + def test_unlisted_and_symlinked_files_are_refused(self): + with tempfile.TemporaryDirectory() as temporary: + bundle = Path(temporary) + shutil.copytree(HERE / 'wasi-libc', bundle / 'wasi-libc') + extra = bundle / 'wasi-libc/unlisted.h' + extra.write_text('// Not part of the pinned ABI.\n') + with self.assertRaisesRegex(ValueError, 'unlisted'): + verify_bundle(bundle) + extra.unlink() + extra.symlink_to('wasi/poll.h') + with self.assertRaisesRegex(ValueError, 'symlink'): + verify_bundle(bundle) + + def test_sdk_revision_and_header_integrity(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + sdk, bundle = root / 'sdk', root / 'bundle' + sdk.mkdir() + shutil.copytree(HERE / 'wasi-libc', bundle / 'wasi-libc') + (sdk / 'VERSION').write_text('34.0\nwasi-libc: 2e6fb9d8ee0c\n') + verify(sdk, bundle) + (sdk / 'VERSION').write_text('34.0\nwasi-libc: different\n') + with self.assertRaisesRegex(ValueError, 'revalidate'): + verify(sdk, bundle) + (sdk / 'VERSION').write_text('34.0\nwasi-libc: 2e6fb9d8ee0c\n') + with (bundle / 'wasi-libc/wasi/descriptor_table.h').open('a') as header: + header.write('\n/* incompatible edit */\n') + with self.assertRaisesRegex(ValueError, 'header changed'): + verify(sdk, bundle) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/boost/asio-wasip3/waitable.cpp b/tools/boost/asio-wasip3/waitable.cpp new file mode 100644 index 00000000..c2f3592c --- /dev/null +++ b/tools/boost/asio-wasip3/waitable.cpp @@ -0,0 +1,121 @@ +// 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) +#include +#include +#include +#include +#include +#include +extern "C" { +// The pinned libc declarations require this exact macro spelling. +// NOLINTNEXTLINE(readability-identifier-naming) +#define hidden __attribute__((visibility("hidden"))) +#include "wasi-libc/wasi/descriptor_table.h" +#undef hidden +// Native asynchronous lowering of the SDK's existing WIT lookup interface. +__attribute__((__import_module__("wasi:sockets/ip-name-lookup@0.3.0"), + __import_name__("[async-lower]resolve-addresses"))) std::uint32_t +webcpp_asio_wasip3_lookup(const char*, std::size_t, void*); +} +#if !defined(__wasip3__) || __wasi_sdk_major__ != 34 +#error "The WASIp3 waitable bridge requires the pinned wasi-sdk 34.0 ABI" +#endif +static_assert(std::string_view(__wasi_sdk_version__) == "34.0"); + +namespace webcpp_asio_wasip3 { +namespace { +struct descriptor_storage { + descriptor_refcnt_t references; + waitable_descriptor* owner; +}; + +static_assert(offsetof(descriptor_storage, references) == 0); +static_assert(sizeof(void*) == 4); +static_assert(sizeof(lookup_result) == 20); +static_assert(sizeof(descriptor_storage) <= sizeof(waitable_descriptor::opaque)); +static_assert(alignof(descriptor_storage) <= alignof(waitable_descriptor)); + +void destroy(void* value) { + static_cast(value)->~descriptor_storage(); +} + +// poll_ready_t requires a mutable event pointer in the pinned SDK ABI. +// NOLINTNEXTLINE(misc-const-correctness) +void ready(void* value, poll_state_t* state, wasip3_event_t* event) { + if (event == nullptr) { + return; + } + auto& storage = *static_cast(value); + storage.state = static_cast(event->code); + // STARTING -> STARTED is progress, not completion. The reactor will wait + // on the same handle again and keep normal timer/socket progress. + if (storage.state == WASIP3_SUBTASK_RETURNED || + storage.state == WASIP3_SUBTASK_RETURNED_CANCELLED) { + __wasilibc_poll_ready(state, POLLRDNORM); + } +} + +int register_poll(void* value, poll_state_t* state, short events) { + if ((static_cast(events) & ~static_cast(POLLRDNORM)) != 0) { + errno = EOPNOTSUPP; + return -1; + } + auto& storage = *static_cast(value)->owner; + if (storage.state == WASIP3_SUBTASK_RETURNED || + storage.state == WASIP3_SUBTASK_RETURNED_CANCELLED) { + __wasilibc_poll_ready(state, POLLRDNORM); + return 0; + } + return __wasilibc_poll_add(state, storage.handle, ready, &storage); +} + +constexpr descriptor_vtable_t operations = [] { + descriptor_vtable_t value{}; + value.free = destroy; + value.poll_register = register_poll; + return value; +}(); +} // namespace + +int open(waitable_descriptor& storage) { + auto* descriptor = + ::new (storage.opaque.data()) descriptor_storage{.references = {0}, .owner = &storage}; + return descriptor_table_insert( + {.data = &descriptor->references, .vtable = const_cast(&operations)}); +} + +void release(waitable_descriptor& storage) { + if (storage.handle == 0u) { + return; + } + if (storage.state != WASIP3_SUBTASK_RETURNED && + storage.state != WASIP3_SUBTASK_RETURNED_CANCELLED) { + auto const status = wasip3_subtask_cancel(storage.handle); + storage.state = WASIP3_SUBTASK_STATE(status); + } + wasip3_subtask_drop(storage.handle); + storage.handle = 0; +} + +wasip3_subtask_status_t start(const char* host, std::size_t size, lookup_result& result) { + return webcpp_asio_wasip3_lookup(host, size, result.bytes.data()); +} + +void free_result(lookup_result& result) { + const auto* data = result.bytes.data(); + if (data[0] == std::byte{0}) { + ip_name_lookup_list_ip_address_t addresses; + std::memcpy(&addresses, data + sizeof(void*), sizeof(addresses)); + ip_name_lookup_list_ip_address_free(&addresses); + } else if (data[sizeof(void*)] == std::byte{IP_NAME_LOOKUP_ERROR_CODE_OTHER} && + data[2 * sizeof(void*)] != std::byte{0}) { + wasip3_string_t message; + std::memcpy(&message, data + (3 * sizeof(void*)), sizeof(message)); + wasip3_string_free(&message); + } + result.bytes.fill(std::byte{0}); +} +} // namespace webcpp_asio_wasip3 diff --git a/tools/boost/asio-wasip3/wasi-libc/LICENSE b/tools/boost/asio-wasip3/wasi-libc/LICENSE new file mode 100644 index 00000000..d3e73789 --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/LICENSE @@ -0,0 +1,17 @@ +wasi-libc as a whole is multi-licensed under the +Apache License v2.0 with LLVM Exceptions, the Apache License v2.0, and +the MIT License. See the LICENSE-APACHE-LLVM, LICENSE-APACHE and LICENSE-MIT +files, respectively, for details. + +Portions of this software are derived from third-party works covered by +their own licenses: + +dlmalloc/ - CC0; see the notice in malloc.c for details +emmalloc/ - MIT; see the notice in emmalloc.c for details +libc-bottom-half/cloudlibc/ - BSD-2-Clause; see the LICENSE file for details +libc-top-half/musl/ - MIT; see the COPYRIGHT file for details +fts/musl-fts/ - BSD-3-Clause; see the COPYING file for details + +wasi-libc's changes to these files are multi-licensed under the +Apache License v2.0 with LLVM Exceptions, the Apache License v2.0, +the MIT License, and the original licenses of the third-party works. diff --git a/tools/boost/asio-wasip3/wasi-libc/LICENSE-APACHE b/tools/boost/asio-wasip3/wasi-libc/LICENSE-APACHE new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT b/tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/tools/boost/asio-wasip3/wasi-libc/manifest.json b/tools/boost/asio-wasip3/wasi-libc/manifest.json new file mode 100644 index 00000000..718083ae --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/manifest.json @@ -0,0 +1,13 @@ +{ + "repository": "https://github.com/WebAssembly/wasi-libc", + "commit": "2e6fb9d8ee0cdf9e431fbcabe8af3115de000a13", + "sdk": "34.0", + "files": { + "LICENSE": "2711a8b5a5cdfef0e639f96c1aca12ae23d7d64a02d0507f1bdf14d2b27bbc3a", + "LICENSE-APACHE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2", + "LICENSE-MIT": "23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3", + "wasi/descriptor_table.h": "21938b584128a3c17be772f883f3104803cfe2096bcf7e08f6a0e7d509cc2aa3", + "wasi/lock.h": "878c2f7465f95c38606233a8a95e85e187faafafb4732877036d03ab3398823b", + "wasi/poll.h": "6417072eda33738773d54747a7901c1583e9ae2d22b206116d8e1e082d6ef14c" + } +} diff --git a/tools/boost/asio-wasip3/wasi-libc/wasi/descriptor_table.h b/tools/boost/asio-wasip3/wasi-libc/wasi/descriptor_table.h new file mode 100644 index 00000000..b06b8e6d --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/wasi/descriptor_table.h @@ -0,0 +1,368 @@ +#ifndef DESCRIPTOR_TABLE_H +#define DESCRIPTOR_TABLE_H + +#include + +#ifndef __wasip1__ +#include +#include +#include +#include +#include +#include + +#ifdef __wasip3__ + +#include "lock.h" + +/// The stream is complete and no further operations are allowed on it. +#define WASIP3_IO_DONE (1 << 0) +/// An I/O operation, be it a read or write, is in flight. +#define WASIP3_IO_INPROGRESS (1 << 1) +/// The in-flight I/O operation is a zero-length operation. This means that if +/// it's finished we expect that the next operation finishes immediately. +#define WASIP3_IO_ZERO_INPROGRESS (1 << 2) +/// A zero-sized in-flight I/O operation just finished so the next I/O op +/// should finish immediately. If it doesn't it'll turn on the next flag. +#define WASIP3_IO_SHOULD_BE_READY (1 << 3) +/// This stream isn't compatible with zero-length reads/writes signaling +/// readiness, so libc must buffer data internally for reads/writes. +#define WASIP3_IO_MUST_BUFFER (1 << 4) +/// A thread is actively blocked in an I/O operation and no other operation +/// can be performed. +#define WASIP3_IO_BLOCKED (1 << 5) + +/// Helper structure to package up state related to a wasip3 `stream`. +/// +/// This is used by various helpers to coordinate reading/writing/etc on a +/// stream. This simultaneously represents both readers and writers. +typedef struct wasip3_io_state_t { + uint32_t stream; + /// Bitset of `WASIP3_IO_*` flags. + uint32_t flags; + /// Malloc'd buffer used for reads/writes. NULL if not present. + uint8_t *buf; + /// Start of `buf` that has data in-flight or ready. + size_t buf_start; + /// End of `buf` that has data in-flight or ready. + size_t buf_end; + +#ifdef _REENTRANT + /// Pointer to the containing object's lock, which protects all the state + /// above. This is acquired and held through all I/O operations, but dropped + /// while an operation that may indefinitely block is in flight. + volatile int *lock; + /// An internal lock used to hold a queue of threads waiting to do blocking + /// I/O while some other thread is already doing blocking I/O. + DECLARE_STRONG_LOCK(blocking_lock); + /// Number of threads that are waiting on `blocking_lock` to take their turn + /// doing blocking I/O. This count notably disallows a concurrent + /// shutdown/reset/etc of this stream, for example `shutdown` fails while + /// something is blocking and so does `seek`. + size_t blocking_waiters; +#endif +} wasip3_io_state_t; + +static inline void __wasip3_io_state_init(wasip3_io_state_t *state, + uint32_t stream) { + assert(stream != 0); + memset(state, 0, sizeof(*state)); + state->stream = stream; +} + +/// Initializes `state` with the `stream` provided, using `lock` — the +/// containing object's lock — to protect the state's fields. +#ifdef _REENTRANT +#define wasip3_io_state_init(state, stream, lock_ptr) \ + do { \ + __wasip3_io_state_init(state, stream); \ + (state)->lock = &(lock_ptr); \ + } while (0) +#else +#define wasip3_io_state_init(state, stream, lock) \ + __wasip3_io_state_init(state, stream) +#endif + +/// Tests whether `state` has been initialized with a stream yet. +static inline bool wasip3_io_state_present(wasip3_io_state_t *state) { + return state->stream != 0; +} + +/// Closes out the streams/etc internal to `state`. +/// +/// Internally the stream must be a reader-half of a `stream`. +static inline void wasip3_read_state_close(wasip3_io_state_t *state) { + STRONG_ASSERT_EMPTY(state->blocking_lock); + if (state->flags & WASIP3_IO_INPROGRESS) + filesystem_stream_u8_cancel_read(state->stream); + if (state->buf) + free(state->buf); + if (state->stream != 0) + filesystem_stream_u8_drop_readable(state->stream); + memset(state, 0, sizeof(*state)); +} + +/// Closes out the streams/etc internal to `state`. +/// +/// Internally the stream must be a writer-half of a `stream`. +/// +/// Note that unlike `wasip3_read_state_close` this first blocks to flush any +/// buffered-but-unsent data, so this is a blocking operation even when the +/// descriptor is in nonblocking mode. +/// +/// This requires `*state->lock` to be held by the caller, and that lock may be +/// dropped and reacquired while blocking. +#define wasip3_write_state_close __wasilibc_write_state_close +hidden void wasip3_write_state_close(wasip3_io_state_t *state); + +/// Tests whether there is active or pending blocking I/O on this stream which +/// notably should prevent it from being closed. +static inline bool wasip3_io_state_blocked(wasip3_io_state_t *state) { +#ifdef _REENTRANT + return (state->flags & WASIP3_IO_BLOCKED) || state->blocking_waiters > 0; +#else + (void)state; + return false; +#endif +} +#endif + +// Metadata for WASI reads which is used to delegate to `__wasilibc_read(...)` +// to perform the actual read of a stream. +typedef struct wasi_read_t { + // An optional pointer to the internal offset of this stream, updated on + // successful reads. + off_t *offset; + // Whether or not this read will use blocking I/O. + bool blocking; + // The timeout, in nanoseconds, for this operation. + monotonic_clock_duration_t timeout; +#ifdef __wasip2__ + // The `wasi:io/streams.input-stream` that this is reading from. + streams_borrow_input_stream_t input; + // A required pointer to an owned pollable for `input`. This is lazily + // initialized as-necessary. + poll_own_pollable_t *pollable; +#else + wasip3_io_state_t *state; + + // A callback/ptr pair to invoke when EOF is reached to set errno and return + // an error code. + int (*eof)(void *); + void *eof_data; +#endif +} wasi_read_t; + +// Same as `wasip_read_t`, but for writes. +typedef struct wasi_write_t { + off_t *offset; + bool blocking; + monotonic_clock_duration_t timeout; + +#ifdef __wasip2__ + streams_borrow_output_stream_t output; + poll_own_pollable_t *pollable; +#else + wasip3_io_state_t *state; + // A callback/ptr pair to invoke when EOF is reached to set errno and return + // an error code. + int (*eof)(void *); + void *eof_data; +#endif +} wasi_write_t; + +/** + * Operations that are required of all descriptors registered as file + * descriptors. + * + * This structure is used to dynamically dispatch operations various I/O + * objects like files and sockets. Functions pointers below can all be `NULL` + * except for `free`. These are the implementation of the corresponding + * functions in libc. + * + * All functions below communicate errors through the return value. A -1 return + * value indicates that an error happened and that `errno` is set. + */ +typedef struct descriptor_vtable_t { + /// Deallocates the parameter provided, closing all resources as well. + void (*free)(void *); + + // ===================================================================== + // Generic I/O + + /// Looks up metadata to perform a read operation for this stream. This is + /// used to implement the `read` syscall, for example, and is also used with + /// `poll` when waiting for readability. + /// + /// When threading is enabled for WASIp3+ this additionally acquires the + /// internal lock for the object and the caller must unlock the + /// `read->state->lock` object on success. On failure no locks are held when + /// this returns. + int (*get_read_stream)(void *, wasi_read_t *); + /// Same as `get_read_stream`, but for output streams. + int (*get_write_stream)(void *, wasi_write_t *); + + /// Sets the nonblocking flag for this object to the specified value. + int (*set_blocking)(void *, bool); + + /// Implementation of `fstat` the function call, used to learn about file + /// descriptors. + int (*fstat)(void *, struct stat *); + + // ===================================================================== + // File-related APIs + + /// Looks up a `wasi:filesystem/types.descriptor`, if present, from this + /// object. + int (*get_file)(void *, filesystem_borrow_descriptor_t *); + /// Implementation of `lseek`-the-function. + off_t (*seek)(void *, off_t, int); + /// Implementation of `fnctl(fd, F_GETFL)`. + int (*fcntl_getfl)(void *); + /// Implementation of `fnctl(fd, F_SETFL)`. + int (*fcntl_setfl)(void *, int); + /// Implementation of `isatty`-the-function. + int (*isatty)(void *); + + // ===================================================================== + // Sockets-related APIs + + /// Implementation of `accept4`-the-function. + int (*accept4)(void *, struct sockaddr *addr, socklen_t *addrlen, int flags); + /// Implementation of `bind`-the-function. + int (*bind)(void *, const struct sockaddr *addr, socklen_t addrlen); + /// Implementation of `connect`-the-function. + int (*connect)(void *, const struct sockaddr *addr, socklen_t addrlen); + /// Implementation of `getsockname`-the-function. + int (*getsockname)(void *, struct sockaddr *addr, socklen_t *addrlen); + /// Implementation of `getpeername`-the-function. + int (*getpeername)(void *, struct sockaddr *addr, socklen_t *addrlen); + /// Implementation of `listen`-the-function. + int (*listen)(void *, int backlog); + /// Implementation of `recvfrom`-the-function. + ssize_t (*recvfrom)(void *, void *buffer, size_t length, int flags, + struct sockaddr *addr, socklen_t *addrlen); + /// Implementation of `sendto`-the-function. + ssize_t (*sendto)(void *, const void *buffer, size_t length, int flags, + const struct sockaddr *addr, socklen_t addrlen); + /// Implementation of `shutdown`-the-function. + int (*shutdown)(void *, int how); + /// Implementation of `getsockopt`-the-function. + int (*getsockopt)(void *, int level, int optname, void *optval, + socklen_t *optlen); + /// Implementation of `setsockopt`-the-function. + int (*setsockopt)(void *, int level, int optname, const void *optval, + socklen_t optlen); + + // ===================================================================== + // `poll`-related APIs + + /// Invoked when this descriptor is passed as one of the objects to the + /// `poll` function. The `wasi/poll.h` header has functions that can operate + /// on the `state` provided. This should invoke `__wasilibc_poll_add`, for + /// example, for any event in `events` with a pollable derived from this + /// object. + /// + /// If this function is not provided then `poll` will use `get_read_stream` + /// and `get_write_stream`, if present, to handle `POLL{RD,WR}NORM` events. + int (*poll_register)(void *, poll_state_t *state, short events); + +#ifdef __wasip2__ + /// Invoked when `poll` has already run and detected that this object was + /// ready. The `events` provided are the same as those provided to + /// `__wasilibc_poll_add` originally. This function should call + /// `__wasilibc_poll_ready` for example to indicate that the underlying + /// `pollfd` structure has some events ready. + /// + /// If this function is not provided then `events` will automatically + /// be placed into the `revents` field of `pollfd`. + int (*poll_finish)(void *, poll_state_t *state, short events); +#endif // __wasip2__ +} descriptor_vtable_t; + +/// Reference count structure that must be at the beginning of all data passed +/// to `descriptor_table_insert`. +typedef struct { + unsigned cnt; +} descriptor_refcnt_t; + +/// A "fat pointer" which is placed inside of the descriptor table. +typedef struct { + /// Arbitrary descriptor-specific data passed to `vtable` function pointer. + descriptor_refcnt_t *data; + /// Definition of various operations for this descriptor. + descriptor_vtable_t *vtable; +} descriptor_table_entry_t; + +/// Inserts the `entry` provided into the descriptor table, returning the +/// integer file descriptor used to refer to it. +/// +/// Note that `entry` is expected to have a reference count of 0 (freshly +/// initialized), and it'll get initialized within this function. +/// +/// On failure returns -1, sets `errno`, and runs `entry`'s destructor. +hidden int descriptor_table_insert(descriptor_table_entry_t entry); + +/// Operations that `descriptor_table_dup` supports. +enum dup_op_t { + /// `dup` function, no `arg` + DUP_OP_DUP, + /// `dup2` function, `arg` is specified + DUP_OP_DUP2, + /// `dup3` function, `arg` is specified + DUP_OP_DUP3, + /// `F_DUPFD` fcntl, `arg` is specified + DUP_OP_DUPFD, +}; + +/// Performs a `dup`-style operation. +hidden int descriptor_table_dup(int fd, enum dup_op_t op, int arg); + +/// Looks up a descriptor by its file descriptor. +/// +/// On success returns 0 and `entry` is filled in with a strong reference to +/// the new entry. Callers must call `descriptor_table_entry_dec` when they're +/// done with the entry. On failure -1 is returned an `errno` is set. +hidden int descriptor_table_get(int fd, descriptor_table_entry_t *entry); + +/// Removes the specified file descriptor from the table. +/// +/// On success returns 0 and runs the entry's destructor. On failure returns -1 +/// and sets `errno`. +hidden int descriptor_table_remove(int fd); + +/// Removes all file descriptors from the table, running their destructors. +hidden void descriptor_table_clear(); + +/// Increment the reference count of the `entry` provided. +static inline void descriptor_table_entry_inc(descriptor_table_entry_t entry) { + assert(entry.data->cnt > 0); + entry.data->cnt++; +} + +/// Slow-path deallocation routine of `descriptor_table_entry_dec`. +/// +/// Assumes refcount is already 0. +hidden void __wasilibc_descriptor_deallocate(descriptor_table_entry_t entry); + +/// Decrement the reference count of the `entry` provided, running deallocation +/// if the cnt reaches 0. +static inline void descriptor_table_entry_dec(descriptor_table_entry_t entry) { + assert(entry.data->cnt > 0); + entry.data->cnt--; + if (entry.data->cnt == 0) + __wasilibc_descriptor_deallocate(entry); +} + +// Helper function used at program-exit time to assert that there are no +// descriptor leaks when libc is itself built in debug mode. Note that this is +// a noop when compiled with `-DNDEBUG`. +#ifdef NDEBUG +static inline void __wasilibc_assert_no_descriptor_leaks(void) {} +#else +void __wasilibc_assert_no_descriptor_leaks(void); +#endif + +#endif // __wasip1__ + +#endif // DESCRIPTOR_TABLE_H diff --git a/tools/boost/asio-wasip3/wasi-libc/wasi/lock.h b/tools/boost/asio-wasip3/wasi-libc/wasi/lock.h new file mode 100644 index 00000000..0bc89f72 --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/wasi/lock.h @@ -0,0 +1,60 @@ +#ifndef LOCK_H +#define LOCK_H + +#include +#include + +// Defines internal locking primitives. The main elements defined here are: +// - __lock_t: the type of a lock variable +// - __lock_ptr_t: the type of a pointer to a lock variable +// - STRONG_LOCK/STRONG_UNLOCK: functions to acquire/release a lock for a critical section that contains +// potential context switch points, and thus must be executed even in cooperative threading mode. +// - WEAK_LOCK/WEAK_UNLOCK: functions to acquire/release a lock for a critical section that does not contain any context switch points, +// and thus can be no-ops in cooperative threading mode. + + +#ifdef _REENTRANT +hidden void __lock(volatile int *lock); +hidden void __unlock(volatile int *lock); +# define DECLARE_STRONG_LOCK(name, ...) __VA_ARGS__ volatile int name +# define STRONG_LOCK(x) __lock(&x) +# define STRONG_UNLOCK(x) __unlock(&x) +# ifdef __wasi_cooperative_threads__ +# define DECLARE_WEAK_LOCK(name, ...) +# define WEAK_LOCK(x) ((void)0) +# define WEAK_UNLOCK(x) ((void)0) +# else +# define DECLARE_WEAK_LOCK(...) DECLARE_STRONG_LOCK(__VA_ARGS__) +# define WEAK_LOCK(x) STRONG_LOCK(x) +# define WEAK_UNLOCK(x) STRONG_UNLOCK(x) +# endif +#else +# define DECLARE_STRONG_LOCK(name, ...) +# define DECLARE_WEAK_LOCK(name, ...) +# define STRONG_LOCK(x) ((void)0) +# define STRONG_UNLOCK(x) ((void)0) +# define WEAK_LOCK(x) ((void)0) +# define WEAK_UNLOCK(x) ((void)0) +#endif + + +#if defined(NDEBUG) || !defined(_REENTRANT) +# define STRONG_ASSERT_HELD(x) ((void)0) +# define STRONG_ASSERT_EMPTY(x) ((void)0) +# define WEAK_ASSERT_HELD(x) ((void)0) +# define WEAK_ASSERT_EMPTY(x) ((void)0) +#else +hidden void __wasilibc_assert_held_lock(volatile int *lock); +hidden void __wasilibc_assert_empty_lock(volatile int *lock); +# define STRONG_ASSERT_HELD(x) __wasilibc_assert_held_lock(&x) +# define STRONG_ASSERT_EMPTY(x) __wasilibc_assert_empty_lock(&x) +# ifdef __wasi_cooperative_threads__ +# define WEAK_ASSERT_HELD(x) ((void)0) +# define WEAK_ASSERT_EMPTY(x) ((void)0) +# else +# define WEAK_ASSERT_HELD(x) STRONG_ASSERT_HELD(x) +# define WEAK_ASSERT_EMPTY(x) STRONG_ASSERT_EMPTY(x) +# endif +#endif + +#endif diff --git a/tools/boost/asio-wasip3/wasi-libc/wasi/poll.h b/tools/boost/asio-wasip3/wasi-libc/wasi/poll.h new file mode 100644 index 00000000..39ac8f89 --- /dev/null +++ b/tools/boost/asio-wasip3/wasi-libc/wasi/poll.h @@ -0,0 +1,79 @@ +#ifndef WASI_POLL_H +#define WASI_POLL_H + +#include + +#ifndef __wasip1__ + +#include +#include + +/// Opaque state that the `poll` function manages for itself. +typedef struct poll_state_t poll_state_t; + +/// Indicates that the `pollfd` which `state` refers to is ready with `events`. +/// +/// If called during `poll_register` then `wasi:io/poll.poll` won't be invoked, +/// and otherwise sets the `revents` field after `poll` has run. +void __wasilibc_poll_ready(poll_state_t *state, short events); + +#ifdef __wasip2__ + +/// Adds the `pollable` to the `state` provided. +/// +/// This will add a `pollable` to get passed to `wasi:io/poll.poll`. If that +/// `pollable` becomes ready the `events` specified here will be used to set +/// `revents` in the final `pollfd`. +/// +/// The `state` value internally tracks which `pollfd` is being used. +int __wasilibc_poll_add(poll_state_t *state, short events, + poll_borrow_pollable_t pollable); + +/// Helper function to lazily subscribe to an input stream and call +/// `__wasilibc_poll_add`. +static inline int +__wasilibc_poll_add_input_stream(poll_state_t *state, + streams_borrow_input_stream_t input_stream, + poll_own_pollable_t *pollable) { + if (pollable->__handle == 0) + *pollable = streams_method_input_stream_subscribe(input_stream); + return __wasilibc_poll_add(state, POLLRDNORM, + poll_borrow_pollable(*pollable)); +} + +/// Helper function to lazily subscribe to an output stream and call +/// `__wasilibc_poll_add`. +static inline int +__wasilibc_poll_add_output_stream(poll_state_t *state, + streams_borrow_output_stream_t output_stream, + poll_own_pollable_t *pollable) { + if (pollable->__handle == 0) + *pollable = streams_method_output_stream_subscribe(output_stream); + return __wasilibc_poll_add(state, POLLWRNORM, + poll_borrow_pollable(*pollable)); +} + +#endif // __wasip2__ + +#ifdef __wasip3__ + +/// Callback invoked after `__wasilibc_poll_add` when an event is ready. +/// +/// This additionally serves as a destructor of sorts where if no event arrives +/// before the `poll` is torn down then this is invoked with `state` and +/// `event` as NULL. +typedef void (*poll_ready_t)(void *data, poll_state_t *state, + wasip3_event_t *event); + +/// Adds the `waitable` to the poll `state`. +/// +/// When `waitable` receives an event it'll invoke `ready` with `ready_data`, +/// the poll state, and the event that happened. +int __wasilibc_poll_add(poll_state_t *state, uint32_t waitable, + poll_ready_t ready, void *ready_data); + +#endif // __wasip3__ + +#endif // not(__wasip1__) + +#endif // WASI_POLL_H diff --git a/tools/boost/cobalt-ssl/Jamfile b/tools/boost/cobalt-ssl/Jamfile index cb88e3b9..ac6a2f62 100644 --- a/tools/boost/cobalt-ssl/Jamfile +++ b/tools/boost/cobalt-ssl/Jamfile @@ -33,9 +33,9 @@ actions prepare rule supported ( properties * ) { - if ! [ webcpp-target.target-of $(properties) ] in native wasip3 + if ! [ webcpp-target.target-of $(properties) ] in native wasip2 wasip3 { - errors.user-error "Cobalt SSL requires native or WASIp3 with source-built OpenSSL." ; + errors.user-error "Cobalt SSL requires native, WASIp2 or WASIp3 with source-built OpenSSL." ; } } diff --git a/tools/boost/cobalt-wasip3/Jamfile b/tools/boost/cobalt-wasip3/Jamfile index 4297bc5c..077ada4e 100644 --- a/tools/boost/cobalt-wasip3/Jamfile +++ b/tools/boost/cobalt-wasip3/Jamfile @@ -30,7 +30,10 @@ actions prepare alias headers : : : : prepared.stamp "-I\"$(OVERLAY)/include\"" - /webcpp/asio-wasip3//headers ; + clang-wasip2:/webcpp/config//config + clang-wasip2:../../../libs/asio/include + clang-wasip2:/webcpp/asio-wasip2//headers + clang-wasip3:/webcpp/asio-wasip3//headers ; explicit headers ; # These objects are built separately from boost_cobalt. Its free include flags diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index b10e813c..0190028e 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -147,15 +147,21 @@ if [ -d libs/beast/example/upstream ]; then fi # Private libc declarations keep upstream text only after their pinned hashes match. -wasi_abi_verified=false -if [ -d tools/boost/asio-wasip2/wasi-libc ]; then +verify_wasi_abi() { + local profile="$1" + [ -d "tools/boost/asio-${profile}/wasi-libc" ] || return 1 rule 'WASI ABI declaration integrity' - if python3 tools/boost/asio-wasip2/verify.py; then - wasi_abi_verified=true + if python3 "tools/boost/asio-${profile}/verify.py"; then + return 0 else fail 'the pinned wasi-libc declaration snapshot failed its integrity check' + return 1 fi -fi +} +wasi_abi_verified=false +wasi_p3_abi_verified=false +if verify_wasi_abi wasip2; then wasi_abi_verified=true; fi +if verify_wasi_abi wasip3; then wasi_p3_abi_verified=true; fi # Every file of the repositories that is there, relative to the root, sorted, NUL-separated. # The index can name a path a move has not been staged for yet, and a submodule is listed as a @@ -171,6 +177,8 @@ for repository in "${repositories[@]}"; do third_party/libs/*) continue ;; tools/boost/asio-wasip2/wasi-libc/*) if [ "${wasi_abi_verified}" = true ]; then continue; fi ;; + tools/boost/asio-wasip3/wasi-libc/*) + if [ "${wasi_p3_abi_verified}" = true ]; then continue; fi ;; libs/beast/example/upstream/*) if [ "${beast_corpus_verified}" = true ]; then continue; fi ;; esac diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index c7c8ccc6..a3a5fc91 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -2159,13 +2159,13 @@ def test_beast_corpus_is_verified_before_excluding_upstream_style(root): expect_alone(lint(root), 'em dash', [adapted + ':1:']) -def test_wasi_abi_snapshot_requires_integrity_before_style_exemption(root): +def check_wasi_abi_style_exemption(root, profile): prepare(root) - snapshot = 'tools/boost/asio-wasip2/wasi-libc/descriptor.h' - verifier = 'tools/boost/asio-wasip2/verify.py' + snapshot = f'tools/boost/asio-{profile}/wasi-libc/descriptor.h' + verifier = f'tools/boost/asio-{profile}/verify.py' # This test replaces the verifier with a controlled executable. Its unit # tests import the real implementation, which is absent in this fixture. - (root / 'tools/boost/asio-wasip2/verify_test.py').unlink(missing_ok=True) + (root / f'tools/boost/asio-{profile}/verify_test.py').unlink(missing_ok=True) write(root, snapshot, '// upstream text ' + EM_DASH + '\n') write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') expect_clean(lint(root)) @@ -2174,12 +2174,21 @@ def test_wasi_abi_snapshot_requires_integrity_before_style_exemption(root): assert result.returncode != 0, result.stdout assert 'WASI ABI declaration integrity' in FAILED.findall(result.stdout), result.stdout write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') - bridge = 'tools/boost/asio-wasip2/notes.txt' + bridge = f'tools/boost/asio-{profile}/notes.txt' write(root, bridge, EM_DASH + '\n') expect_alone(lint(root), 'em dash', [bridge + ':1:']) +def test_wasi_abi_snapshot_requires_integrity_before_style_exemption(root): + check_wasi_abi_style_exemption(root, 'wasip2') + + +def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): + check_wasi_abi_style_exemption(root, 'wasip3') + + CASES = [ + test_wasip3_abi_snapshot_requires_integrity_before_style_exemption, test_wasi_abi_snapshot_requires_integrity_before_style_exemption, test_compile_database_normalizes_shared_source_paths, test_beast_corpus_is_verified_before_excluding_upstream_style, diff --git a/tools/openssl/build.py b/tools/openssl/build.py index 93b13083..0b7727f0 100644 --- a/tools/openssl/build.py +++ b/tools/openssl/build.py @@ -130,7 +130,7 @@ def main() -> None: args = parser.parse_args(arguments) if args.test and args.platform == 'wasi': raise RuntimeError('the OpenSSL upstream test harness requires native executables; ' - 'WASIp3 uses the separately declared TLS integration tests') + 'WASI uses the separately declared TLS integration tests') source, output = args.source.resolve(), args.output.resolve() output.mkdir(parents=True, exist_ok=True) for name in ('build.json', 'upstream-tests.json'): @@ -180,9 +180,15 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat options += ['--openssldir=/etc/ssl'] if args.platform == 'wasi': options += ['no-tests', 'no-apps'] - if '--target=wasm32-wasip3' not in flags: - raise RuntimeError('WASIp3 OpenSSL requires --target=wasm32-wasip3 ' - 'in the configured C flags') + wasi_targets = [target for target in ('wasip2', 'wasip3') + if f'--target=wasm32-{target}' in flags] + if len(wasi_targets) != 1: + raise RuntimeError('WASI OpenSSL requires exactly one --target=wasm32-wasip2 ' + 'or --target=wasm32-wasip3 in the configured C flags') + wasi_target = wasi_targets[0] + if wasi_target == 'wasip2' and args.threading != 'single': + raise RuntimeError('WASIp2 OpenSSL requires threading=single; ' + 'the pinned SDK has no WASIp2 thread backend') sdk = compiler.parent.parent if args.threading == 'multi': sysroots = [flag.split('=', 1)[1] for flag in flags if flag.startswith('--sysroot=')] @@ -197,7 +203,7 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat ('SIGNAL', 'PROCESS_CLOCKS', 'MMAN', 'GETPID')] options += ['--with-rand-seed=getrandom', 'no-asm', 'no-dso', 'no-ui-console', 'no-afalgeng', 'no-quic', '-DOPENSSL_NO_UNIX_SOCK'] - target = ['--config=' + str(HERE / 'wasip3.conf'), 'webcpp-wasip3'] + target = ['--config=' + str(HERE / 'wasip3.conf'), 'webcpp-' + wasi_target] elif windows: native = windows_target(compiler, flags, scratch, env) target = ['--config=' + str(HERE / 'msvc.conf'), native + '-webcpp'] @@ -247,7 +253,7 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat if args.platform == 'wasi': # Copying also works when symlink creation needs Windows privileges. shutil.copyfile(HERE / 'wasip3.conf', scratch / 'wasip3.conf') - actual_target = ['--config=' + str(scratch / 'wasip3.conf'), 'webcpp-wasip3'] + actual_target = ['--config=' + str(scratch / 'wasip3.conf'), target[-1]] elif windows: shutil.copyfile(HERE / 'msvc.conf', scratch / 'msvc.conf') actual_target = ['--config=' + str(scratch / 'msvc.conf'), target[-1]] diff --git a/tools/openssl/test/cobalt_ssl_cancel.cpp b/tools/openssl/test/cobalt_ssl_cancel.cpp index c4bfbe29..75766d83 100644 --- a/tools/openssl/test/cobalt_ssl_cancel.cpp +++ b/tools/openssl/test/cobalt_ssl_cancel.cpp @@ -157,7 +157,22 @@ cobalt::task cancel_write(tls_pair& pair, bool composed) { require(ready >= 0 && (static_cast(descriptor.revents) & failure_events) == 0); if (ready == 0 && receiving.ready() && (composed || total != 0)) { - break; + // WASIp2 may already have a successful SSL completion queued while + // libc reports no current write permit. Let the reactor progress, + // then require that the same operation is still blocked before + // cancelling it. This timer is an event-loop barrier, not evidence + // of backpressure; the second poll and promise state provide that. + asio::steady_timer barrier(pair.exec, std::chrono::milliseconds(1)); + const auto [barrier_error] = + co_await cobalt::as_tuple(barrier.async_wait(cobalt::use_op)); + require(!barrier_error); + descriptor.revents = 0; + ready = ::poll(&descriptor, 1, 0); + require(ready >= 0 && + (static_cast(descriptor.revents) & failure_events) == 0); + if (ready == 0 && !writing.ready()) { + break; + } } } const bool cancel = !writing.ready(); diff --git a/tools/openssl/test/tls.py b/tools/openssl/test/tls.py index a97a2ade..b0e26c9b 100644 --- a/tools/openssl/test/tls.py +++ b/tools/openssl/test/tls.py @@ -23,6 +23,10 @@ client_args = [arg.removeprefix('--client-arg=') for arg in sys.argv[2:] if arg.startswith('--client-arg=')] WASMTIME = os.environ.get('WASMTIME', 'wasmtime') +wasip2 = '--wasip2' in sys.argv[2:] +launcher = ([str(WASMTIME), 'run', '-W', 'timeout=15s'] if wasip2 else + [str(WASMTIME), 'run', '-S', 'p3', '-W', 'component-model-async=y', + '-W', 'component-model-threading=y', '-W', 'timeout=15s']) if not ssl.HAS_TLSv1_3: raise SystemExit('The Python TLS server requires TLS 1.3; select a newer Python interpreter.') print('Native test server: ' + ssl.OPENSSL_VERSION, flush=True) @@ -69,9 +73,7 @@ (certs / 'server-key.pem').read_text(), (certs / 'ca.pem').read_text(), version, *client_args] if wasm: - command = [str(WASMTIME), 'run', '-S', 'p3', '-S', 'inherit-network=y', - '-S', 'tcp=y', '-W', 'component-model-async=y', - '-W', 'component-model-threading=y', '-W', 'timeout=15s'] + command + command = (launcher + ['-S', 'inherit-network=y', '-S', 'tcp=y']) + command # Fixture keys are ephemeral and stay local; do not print them in the command. print('Run TLS state test: ' + str(program) + ' TLS ' + version, flush=True) try: @@ -91,8 +93,7 @@ invalid = ssl.DER_cert_to_PEM_cert(der + extra) command = [str(program), '0', 'localhost', invalid, 'accept', '1.3'] if wasm: - command = [str(WASMTIME), 'run', '-S', 'p3', '-W', 'component-model-async=y', - '-W', 'component-model-threading=y', '-W', 'timeout=15s'] + command + command = launcher + command run = subprocess.run(command, capture_output=True, text=True, timeout=20) if run.returncode != 1 or not run.stderr.startswith('CA preparation:'): raise RuntimeError('Trailing DER data was not rejected before connecting: ' @@ -157,15 +158,12 @@ def check_sni(tls, name, context): command = [str(program), str(port), hostname, authorities] if wasm: # No filesystem preopen: roots are compiled in or supplied as bytes. - command = [str(WASMTIME), 'run', '-S', 'p3', '-S', 'inherit-network=y', - '-S', 'tcp=y', '-W', 'component-model-async=y', - '-W', 'component-model-threading=y', '-W', 'timeout=15s'] + command + command = (launcher + ['-S', 'inherit-network=y', '-S', 'tcp=y']) + command elif not wasm: command = [str(program), str(port), hostname, str(certs / ca)] else: - command = [str(WASMTIME), 'run', '-S', 'p3', '-S', 'inherit-network=y', '-S', 'tcp=y', - '-W', 'component-model-async=y', '-W', 'component-model-threading=y', - '-W', 'timeout=15s', '--dir', str(certs) + '::/certs', + command = [*launcher, '-S', 'inherit-network=y', '-S', 'tcp=y', + '--dir', str(certs) + '::/certs', str(program), str(port), hostname, '/certs/' + ca] command += ['accept' if case == 'valid' else 'reject', version] command += client_args diff --git a/tools/openssl/wasip3.conf b/tools/openssl/wasip3.conf index d912220d..d07ab85d 100644 --- a/tools/openssl/wasip3.conf +++ b/tools/openssl/wasip3.conf @@ -2,6 +2,12 @@ # Distributed under the Boost Software License, Version 1.0. # External Configure target; upstream OpenSSL sources remain unmodified. my %targets = ( + "webcpp-wasip2" => { + inherit_from => [ "BASE_unix" ], + sys_id => "WASI", + bn_ops => "THIRTY_TWO_BIT", + perlasm_scheme => "void", + }, "webcpp-wasip3" => { inherit_from => [ "BASE_unix" ], sys_id => "WASI", diff --git a/tools/test/asio_wasip3_test.py b/tools/test/asio_wasip3_test.py index 96059a51..f75fd181 100644 --- a/tools/test/asio_wasip3_test.py +++ b/tools/test/asio_wasip3_test.py @@ -138,9 +138,8 @@ def test_wasip2_consumer_and_unsupported_profiles(root: Path) -> None: True, '**passed**') harness.expect(harness.run_b2(root, 'threading=multi', *options), False, 'WASIp2 supports threading=single only') - for target, reason in (('cobalt', 'Cobalt requires'), ('tls', 'OpenSSL requires')): - harness.expect(harness.run_b2(root, 'toolset=clang-wasip2', '/webcpp/asio//' + target), - False, reason) + # TLS/Cobalt now have real P2 runtime consumers in + # libs/asio/test/wasip2_tls_cobalt. Only unsupported profiles are refused. stale = root / 'unknown SDK' stale.mkdir() (stale / 'VERSION').write_text('34.0\nwasi-libc: unknown\n') diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index f55ee228..3489dec8 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -76,9 +76,10 @@ def test_native_upstream_suite_checks_the_consumed_archives(root: Path) -> None: def test_upstream_suite_rejects_wasi_by_name(root: Path) -> None: - result = harness.run_b2(root, 'third_party//openssl', 'toolset=clang-wasip3', - 'webcpp-openssl-tests=on') - harness.expect(result, False, 'upstream test harness requires native executables') + for toolset in ('clang-wasip2', 'clang-wasip3'): + result = harness.run_b2(root, 'third_party//openssl', 'toolset=' + toolset, + 'webcpp-openssl-tests=on') + harness.expect(result, False, 'upstream test harness requires native executables') def test_upstream_failure_prevents_archive_publication(root: Path) -> None: @@ -145,6 +146,25 @@ def test_native_source_dependency(root: Path) -> None: harness.expect(result, True, 'webcpp-openssl.build', '**passed**') +def test_wasip2_source_dependency(root: Path) -> None: + jam = JAM.replace('import webcpp ;', 'import webcpp ;\nwebcpp.targets wasip2 ;') + harness.add_library(root, 'openssl_user', jam, {'uses_openssl.cpp': SOURCE}) + for exceptions in ('on', 'off'): + result = harness.run_b2(root, 'toolset=clang-wasip2', 'variant=release', + 'threading=single', f'exception-handling={exceptions}', + 'testing.launcher=wasmtime run -W timeout=15s', + 'libs/openssl_user/test', timeout=600) + harness.expect(result, True, '**passed**') + for path in (root / 'bin/third_party').rglob('build.json'): + configuration = json.loads(path.read_text()) + assert 'webcpp-wasip2' in configuration['configure'], configuration + assert 'no-threads' in configuration['configure'], configuration + assert '--target=wasm32-wasip2' in configuration['flags'], configuration + result = harness.run_b2(root, 'third_party//openssl', 'toolset=clang-wasip2', + 'threading=multi') + harness.expect(result, False, 'WASIp2', 'threading=single') + + def test_symlinked_compiler_without_c_sibling(root: Path) -> None: compiler = shutil.which('clang++') assert compiler @@ -222,9 +242,8 @@ def test_missing_checkout_is_lazy_and_actionable(root: Path) -> None: def test_unsupported_target_is_rejected(root: Path) -> None: - for toolset in ('clang-wasip2', 'emscripten'): - result = harness.run_b2(root, 'third_party//openssl', 'toolset=' + toolset) - harness.expect(result, False, 'not supported by this recipe') + result = harness.run_b2(root, 'third_party//openssl', 'toolset=emscripten') + harness.expect(result, False, 'not supported by this recipe') def test_source_checkout_with_spaces(root: Path) -> None: @@ -307,7 +326,8 @@ def test_source_archive_tampering_fails_before_configuration(root: Path) -> None CASES = [test_native_upstream_suite_checks_the_consumed_archives, test_upstream_suite_rejects_wasi_by_name, test_upstream_failure_prevents_archive_publication, - test_native_source_dependency, test_symlinked_compiler_without_c_sibling, + test_native_source_dependency, test_wasip2_source_dependency, + test_symlinked_compiler_without_c_sibling, test_msvc_build_commands_preserve_the_consumers_configuration, test_missing_checkout_is_lazy_and_actionable, test_unsupported_target_is_rejected, test_pin_mismatch_fails_before_compilation, diff --git a/tools/webcpp-openssl.jam b/tools/webcpp-openssl.jam index 422672e5..3c7ffbb9 100644 --- a/tools/webcpp-openssl.jam +++ b/tools/webcpp-openssl.jam @@ -49,13 +49,13 @@ class openssl-target : basic-target if $(os) = wasi && [ $(properties).get ] = "on" { errors.user-error "The OpenSSL upstream test harness requires native executables." - "WASIp3 uses the separately declared TLS integration tests." ; + "WASI uses the separately declared TLS integration tests." ; } if ! ( ( $(tool) in clang gcc && $(os) in darwin linux ) - || ( $(tool) = clang && $(os) = wasi && $(version) = wasip3 ) + || ( $(tool) = clang && $(os) = wasi && $(version) in wasip2 wasip3 ) || ( $(tool) = msvc && $(os) = windows ) ) { - errors.user-error "Source-built OpenSSL supports native Clang/GCC on macOS/Linux, MSVC on Windows, and clang-wasip3." + errors.user-error "Source-built OpenSSL supports native Clang/GCC on macOS/Linux, MSVC on Windows, clang-wasip2 and clang-wasip3." "Other targets are not supported by this recipe." ; } # B2's normal directory omits free flags. Add the effective compiler @@ -122,6 +122,10 @@ toolset.uses-features webcpp-openssl.build : wasip2 in $(properties) && multi in $(properties) + { + errors.user-error "WASIp2 OpenSSL requires threading=single; the pinned SDK has no WASIp2 thread backend." ; + } if wasi in $(properties) && multi in $(properties) { return [ webcpp-wasi.cooperative $(.root) : $(properties) ] ; From 008a47b944c8175b2b00df2e410db87bd7b15e21 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 10:58:08 -0500 Subject: [PATCH 13/32] Cover supported Asio profiles in recurring test lanes --- doc/releases/0.1.0.adoc | 1 + libs/asio | 2 +- tools/ci/matrix.py | 12 +++++++-- tools/ci/matrix_test.py | 54 +++++++++++++++++++++++++++++++++++++---- 4 files changed, 61 insertions(+), 8 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 0c8afcd1..17ce46cd 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -55,6 +55,7 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Fixed Chrome provisioning and browser/TLS profile coverage in Asio CI lanes. * Added source-built OpenSSL and Cobalt SSL targets for WASIp2. * Added explicit browser pthread profiles with main-thread handoff tests. * Changed lint to verify WASIp3 ABI snapshots before excluding upstream headers. diff --git a/libs/asio b/libs/asio index a8d0f17b..9455076a 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit a8d0f17bac7a0c1e3934a70070e6b22e1d3abfef +Subproject commit 9455076a56ece86204229c455fe64b7ed5fbf530 diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 72b82b25..1514bd51 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -191,7 +191,9 @@ def container_tag() -> str: # its pinned chrome-headless-shell, as CHROME: trystero's interop, natively and on emscripten, and # document's js, whose examples Playwright runs in Chrome, and the browser and # chat applications whose fixture connects Chrome to native or WASI servers. -CHROME_LANES = {('asio', 'browser'), ('beast', 'browser'), ('beast', 'applications-browser'), +CHROME_LANES = {('asio', 'browser'), ('asio', 'browser-workers'), + ('asio', 'browser-worker-exceptions'), + ('beast', 'browser'), ('beast', 'applications-browser'), ('beast', 'applications-chat'), ('document', 'js'), ('trystero', 'interop')} # MSVC's lanes build 64-bit programs, embed their manifest with the linker and abbreviate b2's @@ -512,8 +514,14 @@ def has_external(library: str | None) -> bool: OWN_LANE_BASES = {None: 'clang-18', 'native': 'clang-18', 'emscripten': 'emscripten', 'wasip2': 'wasip2', 'wasip3': 'wasip3'} -# Suspension variants expand inside B2; these lanes also exercise both policy and EH modes. +# Own lanes select their supported suspension, exception and library policy modes. +# Manifest-based browser lanes already expand suspension variants inside B2. OWN_LANE_OPTIONS = { + ('asio', 'browser-workers', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), + ('asio', 'browser-worker-exceptions', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on'), + ('asio', 'wasip2-tls', 'wasip2'): ('exception-handling=on,off',), ('beast', 'browser', 'emscripten'): ('exception-handling=on,off', 'webcpp-beast-unsupported=error,ignore'), ('beast', 'browser-node', 'emscripten'): diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index ccf9c49f..677da336 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -543,6 +543,40 @@ def test_beast_browser_lanes_cover_policies_and_exception_modes(root): assert all(option not in command for option in options), command +def test_asio_capability_lanes_cover_suspension_and_exception_modes(root): + # These direct-source drivers need the CI request to expand their profiles. + harness.add_library(root, 'asio', + 'import webcpp ;\nwebcpp.targets emscripten wasip2 ;\n' + 'webcpp.original python3 ;\n' + 'webcpp.drive worker : pass.cpp : : driver.py : : emscripten ;\n' + 'webcpp.drive exception : pass.cpp : on\n' + ' : driver.py : : emscripten ;\n' + 'webcpp.drive tls : pass.cpp : : driver.py : : wasip2 ;\n' + 'webcpp.lane browser-workers : worker : emscripten ;\n' + 'webcpp.lane browser-worker-exceptions : exception : emscripten ;\n' + 'webcpp.lane wasip2-tls : tls : wasip2 ;\n', + {'pass.cpp': 'int main() {}\n', 'driver.py': '', + 'package.json': '{}\n', 'package-lock.json': '{}\n'}) + entries = own_lanes(root, '--library', 'asio') + assert {entry['id'] for entry in entries} == { + 'emscripten.asio.browser-workers', 'emscripten.asio.browser-worker-exceptions', + 'wasip2.asio.wasip2-tls'}, entries + expected = { + 'browser-workers': ['toolset=emscripten', 'webcpp-suspend=jspi,asyncify', + 'exception-handling=on,off'], + 'browser-worker-exceptions': ['toolset=emscripten', 'webcpp-suspend=jspi,asyncify', + 'exception-handling=on'], + 'wasip2-tls': ['toolset=clang-wasip2', + 'testing.launcher=tools/boost/asio-wasip2/run.sh', + 'exception-handling=on,off'], + } + for entry in entries: + own = matrix.parsed_own_lane(json.dumps(entry)) + command = matrix.own_lane_command(own, root / 'config.jam', root / 'lane.xml', []) + assert command[5:] == [*expected[own.lane], + f'libs/asio/test//{own.lane}'], command + + def test_openssl_upstream_lanes_use_the_windows_builds(root): # Exercise the public planner and command builder. A native-only lane used # to select Linux even when its purpose was to validate the MSVC recipe. @@ -1174,10 +1208,18 @@ def test_a_container_lane_has_its_image_from_the_cache(_): def test_asio_browser_lane_receives_chrome(root): # The browser driver needs Chrome when the lane is scheduled, on emscripten alone. - own = matrix.OwnLane('asio', 'browser', ('libs/asio/test/browser',), - 'emscripten', 'original') - entry = own_lane_entry_of(own) - assert entry['chrome'] is True, entry + harness.add_library(root, 'asio', + 'import webcpp ;\nwebcpp.targets emscripten ;\n' + 'webcpp.original python3 ;\n' + 'webcpp.drive page : pass.cpp : : driver.py ;\n' + 'webcpp.lane browser : page : emscripten ;\n' + 'webcpp.lane browser-workers : page : emscripten ;\n' + 'webcpp.lane browser-worker-exceptions : page : emscripten ;\n', + {'pass.cpp': 'int main() {}\n', 'driver.py': '', + 'package.json': '{}\n', 'package-lock.json': '{}\n'}) + entries = own_lanes(root, '--library', 'asio') + assert {entry['lane']: entry['chrome'] for entry in entries} == { + 'browser': True, 'browser-workers': True, 'browser-worker-exceptions': True}, entries for lane, platform in (('browser', 'emscripten'), ('applications-browser', 'emscripten'), @@ -1194,7 +1236,8 @@ def test_a_browser_lane_has_the_pinned_chrome(root): # chrome-headless-shell, which gives CHROME; no other own lane does, and no job names the # image's Chrome. assert matrix.CHROME_LANES == { - ('asio', 'browser'), ('beast', 'browser'), ('beast', 'applications-browser'), + ('asio', 'browser'), ('asio', 'browser-workers'), ('asio', 'browser-worker-exceptions'), + ('beast', 'browser'), ('beast', 'applications-browser'), ('beast', 'applications-chat'), ('document', 'js'), ('trystero', 'interop')}, matrix.CHROME_LANES boost_only(root) @@ -1418,6 +1461,7 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): test_own_lanes_on_targets, test_an_own_lanes_command, 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, test_a_wasip3_lane_can_bind_a_loopback_socket, test_a_lane_is_named_by_the_compiler_version, From ad092876333dac2cd310cff58a7bc8fe64636bdf Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 11:00:36 -0500 Subject: [PATCH 14/32] Record completed Asio capability checks and reviews --- .../2026-11-03-asio-capability-completion.md | 44 ++-- ...2026-11-03-asio-capability-verification.md | 32 ++- .../2026-11-03-asio-capability-fix-review.md | 24 +++ .../2026-11-03-asio-capability-review.md | 199 ++++++++++++++++++ 4 files changed, 279 insertions(+), 20 deletions(-) create mode 100644 docs/superpowers/reviews/2026-11-03-asio-capability-fix-review.md create mode 100644 docs/superpowers/reviews/2026-11-03-asio-capability-review.md diff --git a/docs/superpowers/plans/2026-11-03-asio-capability-completion.md b/docs/superpowers/plans/2026-11-03-asio-capability-completion.md index e2435e0e..902c167f 100644 --- a/docs/superpowers/plans/2026-11-03-asio-capability-completion.md +++ b/docs/superpowers/plans/2026-11-03-asio-capability-completion.md @@ -1,6 +1,6 @@ # Asio Capability Completion Implementation Plan -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking. **Goal:** Complete the WebCPP-owned Asio gaps and diagnose external unsupported combinations at their correct boundary. @@ -34,10 +34,10 @@ **Interfaces:** Existing Asio UDP and async_resolve APIs. Both P2/P3 scalar and sequence consumers retain ordinary completion tokens. P3 S uses native async lookup without a worker pool. P2 resolver remains unchanged unless shared behavior requires correction. -- [ ] Write and run public-target RED consumers for connected gather send, scatter receive (sync/async), empty/oversize datagrams, cancellation, and P3 S deferred DNS with timer progress. -- [ ] Implement checked overlay changes with context/associated allocation and release before callbacks. Use native P3 waitable integration where required; never implement async DNS by blocking inside initiation. -- [ ] Verify P2/P3 EH twins, P3 cooperative where applicable, native controls, source hash preparation and meaningful failure cases. -- [ ] Write report with exact commands, RED/GREEN, changes and remaining external dependencies; parent reviews/integrates and commits. +- [x] Write and run public-target RED consumers for connected gather send, scatter receive (sync/async), empty/oversize datagrams, cancellation, and P3 S deferred DNS with timer progress. +- [x] Implement checked overlay changes with context/associated allocation and release before callbacks. Use native P3 waitable integration where required; never implement async DNS by blocking inside initiation. +- [x] Verify P2/P3 EH twins, P3 cooperative where applicable, native controls, source hash preparation and meaningful failure cases. +- [x] Write report with exact commands, RED/GREEN, changes and remaining external dependencies; parent reviews/integrates and commits. ### Task 2: WASIp2 TLS and Cobalt @@ -45,10 +45,10 @@ **Interfaces:** Existing /webcpp/third_party//openssl and /webcpp/asio//cobalt, //tls, //cobalt_ssl gain validated P2 S/EH on/off. CA replacement/embedding contract remains identical. No new OpenSSL copy or system fallback. -- [ ] Run existing/public P2 consumers to capture deliberate baseline refusal, then register real minimal Cobalt and TLS consumers. -- [ ] Extend verified source recipe and Cobalt source/runner selection to P2. Preserve capability omission of signals, local sockets and thread APIs. -- [ ] Verify Cobalt main status, timer/TCP/UDP/resolver cancellation, real TLS trust and hostname failures, embedded/custom CAs, handshake/transfer/shutdown including cancellation under both EH modes. Retain the known no-EH pending-task move warning. -- [ ] Run native/P3 focused regressions and source build tests. Report exact evidence and changes for parent integration/review/commit. +- [x] Run existing/public P2 consumers to capture deliberate baseline refusal, then register real minimal Cobalt and TLS consumers. +- [x] Extend verified source recipe and Cobalt source/runner selection to P2. Preserve capability omission of signals, local sockets and thread APIs. +- [x] Verify Cobalt main status, timer/TCP/UDP/resolver cancellation, real TLS trust and hostname failures, embedded/custom CAs, handshake/transfer/shutdown including cancellation under both EH modes. Retain the known no-EH pending-task move warning. +- [x] Run native/P3 focused regressions and source build tests. Report exact evidence and changes for parent integration/review/commit. ### Task 3: Browser worker profile and environment boundary @@ -56,10 +56,10 @@ **Interfaces:** An explicit supported threaded browser build must coexist with existing single-thread JSPI/Asyncify. No blanket claim of DOM access from workers; do not silently switch suspension mechanisms. -- [ ] Reproduce the current public-target rejection and independently compile/run pinned Emscripten pthread consumers with each suspension mechanism in a real browser, with required isolation headers. -- [ ] If supported by the pinned environment, implement the worker executor/wakeup and main-thread handoff, preserving thread affinity, allocator/cancellation and same-context semantics. Add real-browser success/error/shutdown tests. -- [ ] For any external blocker, retain a smallest reproducible compile/runtime witness and precise diagnosis. Do not upgrade the SDK or classify missing WebCPP code as external. -- [ ] Report actual supported matrix, code changes, test commands and guard requirements for parent integration/review/commit. +- [x] Reproduce the current public-target rejection and independently compile/run pinned Emscripten pthread consumers with each suspension mechanism in a real browser, with required isolation headers. +- [x] If supported by the pinned environment, implement the worker executor/wakeup and main-thread handoff, preserving thread affinity, allocator/cancellation and same-context semantics. Add real-browser success/error/shutdown tests. +- [x] For any external blocker, retain a smallest reproducible compile/runtime witness and precise diagnosis. Do not upgrade the SDK or classify missing WebCPP code as external. +- [x] Report actual supported matrix, code changes, test commands and guard requirements for parent integration/review/commit. ### Task 4: Central config guards, documentation and final verification @@ -67,8 +67,16 @@ **Interfaces:** Derived WEBCPP_ASIO capability macros with 0/1 values, optional dependency selection separate from platform availability, explicit compile-time requirement diagnostics. Existing generic/browser settings headers remain usable. -- [ ] Write positive/negative compiler consumers proving capabilities cannot be forged, optional dependencies are required only by their features, unsupported known profiles fail clearly and runtime alternatives remain usable. -- [ ] Implement central detection and header/build guards using final verified Task 1-3 outcomes. Runtime network permissions and blocking host calls remain documented error/behavior boundaries. -- [ ] Update feature tables with evidence and dependency ownership, include compiled examples, reconcile approved proposal and guideline scope without declaring publication complete. -- [ ] Run affected Release suites from scratch, focused tools/lint, MrDocs/rendered checks and proposal validation. Review delegated tasks and the complete candidate, fix important findings with RED/GREEN evidence. -- [ ] Commit scoped library/root/proposal changes and report completed work plus externally blocked cases, with no implicit CI/merge claim. +- [x] Write positive/negative compiler consumers proving capabilities cannot be forged, optional dependencies are required only by their features, unsupported known profiles fail clearly and runtime alternatives remain usable. +- [x] Implement central detection and header/build guards using final verified Task 1-3 outcomes. Runtime network permissions and blocking host calls remain documented error/behavior boundaries. +- [x] Update feature tables with evidence and dependency ownership, include compiled examples, reconcile approved proposal and guideline scope without declaring publication complete. +- [x] Run affected Release suites from scratch, focused tools/lint, MrDocs/rendered checks and proposal validation. Review delegated tasks and the complete candidate, fix important findings with RED/GREEN evidence. +- [x] Commit scoped library/root/proposal changes and report completed work plus externally blocked cases, with no implicit CI/merge claim. + +## Completion record + +All scoped tasks are committed and locally verified. See +`2026-11-03-asio-capability-verification.md` for commands, results, review fixes +and validation limits. The original UDP feature RED was replayed after its +implementation because the initial run failed on sandbox networking; this is +recorded as a chronology limitation rather than strict test-first TDD. diff --git a/docs/superpowers/plans/2026-11-03-asio-capability-verification.md b/docs/superpowers/plans/2026-11-03-asio-capability-verification.md index 40b450c5..49d14ef1 100644 --- a/docs/superpowers/plans/2026-11-03-asio-capability-verification.md +++ b/docs/superpowers/plans/2026-11-03-asio-capability-verification.md @@ -90,12 +90,15 @@ They do not include every separate own lane and do not claim all-platform CI. - Focused clang-tidy passed task-owned code and 16 parent-owned configurations. Owned Python checks, text/format rules and Node syntax checks passed. This is not a claim that the complete repository lint printed `lint: clean`. +- Complete lint database generation passed with 1,451 commands, including the + explicit browser pthread header units. Database generation is not a full tidy + run. The local `check-release` target also passed. - MrDocs and rendered guide link/code checks passed after the final public comment changes. Desktop/narrow screenshot inspection remains unverified: local Chrome screenshots were blank and the in-app browser refused file URLs. No bypass was attempted. - Proposal checking and 17 tool tests passed. OpenSpec 1.10.0 strict validation - passed in all 15 proposal roots before the final committed snapshot refresh. + passed in all 15 proposal roots after exporting the 206-file candidate snapshot. ## Review and regression record @@ -119,7 +122,32 @@ approved re-review. The original UDP feature test had a weaker chronology: its first run failed on sandbox networking, and the valid pristine-overlay failure was replayed after implementation. It is not described as strict test-first TDD. -The final whole-candidate review is recorded separately after candidate commits. +The final whole-candidate review covered root `15e2f44..0da952f` and Asio +`dad1aef..a8d0f17`. It found no additional backend/lifetime defect, but requested +two important recurring-lane fixes: Chrome provisioning for the new browser lanes +and persisted EH/suspension coverage. It also identified stale P2 TLS guide +commands and a stale single-thread Cobalt DNS refusal statement. These findings +were resolved in one scoped fix wave, root `008a47b` and Asio `9455076`. +The complete matrix suite passed 41/41 cases. Local B2 XML confirmed 34 driver +configurations: four profiles for each of four worker drivers, two EH-on +suspension profiles for the exception fixture and two EH profiles for each of +eight P2 TLS drivers. Documentation generation and focused static checks passed. +An initial matrix test could not bind loopback in the sandbox; the same case and +the complete suite passed with local socket permission, without changing tests. + +The scoped re-review approved every finding with no new breakage and no +out-of-scope observations. Reports are preserved in +`../reviews/2026-11-03-asio-capability-review.md` and +`../reviews/2026-11-03-asio-capability-fix-review.md`. Local raw reports, logs and +review packages are retained in `.local/asio-capability-evidence-2026-11-03.tar.gz`. +The completed branch and worktree are kept for the separately authorized +publication closure; nothing here asserts fresh remote CI or a merge. + +The reviewer explicitly left broader external DNS/IPv6/multicast/native-device +validation, general Cobalt compositions and upstream issue 287, other host OSes +and engines, pixel-level documentation inspection and publication outside the +verdict. These remain the documented validation/external boundaries; none is +silently promoted to tested support by this review. ## Controller decisions diff --git a/docs/superpowers/reviews/2026-11-03-asio-capability-fix-review.md b/docs/superpowers/reviews/2026-11-03-asio-capability-fix-review.md new file mode 100644 index 00000000..e3257016 --- /dev/null +++ b/docs/superpowers/reviews/2026-11-03-asio-capability-fix-review.md @@ -0,0 +1,24 @@ +- **Provision Chrome for both new browser own lanes: ADDRESSED.** `tools/ci/matrix.py:194` includes both worker lanes in `CHROME_LANES`; the existing entry construction at `tools/ci/matrix.py:633` propagates that classification. `tools/ci/matrix_test.py:1209` now tests the public planner's entries for all three Asio browser lanes. The frozen `final-own-lanes-after.json` records `chrome=true` for both new worker lanes. +- **Encode the promised recurring profile coverage: ADDRESSED.** `tools/ci/matrix.py:519` selects JSPI/Asyncify and EH on/off for workers, JSPI/Asyncify with EH on only for the exception fixture, and EH on/off for WASIp2 TLS. `tools/ci/matrix.py:789` includes these options in the existing command path. `tools/ci/matrix_test.py:547` exercises public discovery, JSON parsing and exact generated requests. The recorded B2 XML contains the required 34 configurations across all 13 named drivers, with no EH-off exception fixture. +- **Point the P2 TLS how-to at its explicit test lane: ADDRESSED.** `libs/asio/doc/wasip2.adoc:35` retains the ordinary consumer directory and adds `//wasip2-tls` with the launcher and both EH modes. `libs/asio/doc/building.adoc:432` limits the older driver to native/WASIp3, and `libs/asio/doc/building.adoc:440` separately identifies the WASIp2 lane and links to its complete command. +- **Remove the stale single-thread Cobalt DNS refusal: ADDRESSED.** `libs/asio/doc/feature-matrix.adoc:410` now describes numeric Cobalt resolution and the WASIp3 native asynchronous forward resolver, including localhost, deferred initiation, progress and cancellation evidence. It retains the host-policy qualification and does not equate numeric/localhost results with arbitrary external DNS reachability. + +### New Breakage in the Fix Diff + +- **None.** The same-wave correction at `libs/asio/doc/feature-matrix.adoc:622` confines TLS 1.2/1.3 and buffered-client results to the recorded native/WASIp3 profiles, then states the separate WASIp2 peer/state/cancellation evidence in S with EH on/off. It introduces no P2 buffered-coverage claim. +- **Fixture isolation checked.** The new fixtures at `tools/ci/matrix_test.py:548` and `tools/ci/matrix_test.py:1211` provide the package files required by public browser-lane discovery. `tools/test/harness.py:501` creates and removes a separate scratch superproject for every case, so these local Asio declarations do not leak into other cases. The fixtures test planning and command construction; empty driver/package contents do not replace runtime evidence. + +### Checks + +- Read the scoped re-review template, all four original findings, the frozen final fix report, and both supplied diff packages: root `0da952f..008a47b` and Asio `a8d0f17..9455076`. Inspected the changed lines and their immediate request, lane and fixture integration. No git command, source/index/branch mutation, additional agent, remote action or test rerun was used. +- Read the recorded matrix log and independently counted 41 passing case lines plus `matrix_test: ok`. The new profile regression and both browser provisioning regressions are included. Read the focused loopback log, which also ends in `matrix_test: ok`. +- Parsed the existing three final-fix B2 XML files without rebuilding: each regular worker driver has exactly JSPI/on, JSPI/off, Asyncify/on and Asyncify/off; the exception driver has exactly JSPI/on and Asyncify/on; each WASIp2 TLS driver has exactly EH on and EH off. Total: 34 `.driven` configurations. These are graph checks, not additional runtime claims. +- Read the final documentation build log: doc-check, reference generation, conversion and rendered-check completed with six updated targets. The frozen report also records clean Pyright and applicable lint checks. No unresolved code-reading doubt required repeating the completed suites. + +### Out-of-Scope Observations + +- None. The parent's unstaged evidence-only `verification.md` update is outside these fix ranges and was not reviewed as a source change. + +### Verdict + +- **Fix round: All findings addressed, no new Critical/Important breakage.** The four findings are closed for the supplied frozen ranges. This verdict does not establish fresh remote CI, publication or merge status. diff --git a/docs/superpowers/reviews/2026-11-03-asio-capability-review.md b/docs/superpowers/reviews/2026-11-03-asio-capability-review.md new file mode 100644 index 00000000..1d534f0b --- /dev/null +++ b/docs/superpowers/reviews/2026-11-03-asio-capability-review.md @@ -0,0 +1,199 @@ +# Final whole-candidate review: Asio capability completion + +Date: 2026-11-03. + +## Review boundary + +Reviewed the frozen root range `15e2f44..0da952f`, Asio range +`dad1aef..a8d0f17`, and `final-proposals-review.diff` against the approved +capability-completion design and plan. This is the single final reviewer pass. +No subagents were dispatched. No source, index, HEAD, branch, SDK, installed +Boost tree or generated output was modified. This report is the only written +review artifact. + +The review included the complete candidate's shared capability/header/build +integration, WASI UDP and asynchronous DNS paths, private descriptor ABI and +cancellation lifetime, browser affinity/main-thread queue lifetime, P2 shared +TLS/Cobalt integration, recurring B2 test registration and public documentation. +It also read the progress/verification records and the task review corrections. +The earlier task approvals were considered evidence, not a substitute for +checking their shared boundaries. + +## Strengths + +- `libs/asio/include/webcpp/asio/config.hpp:77` distinguishes derived 0/1 + facilities from optional OpenSSL selection. Requirement switches diagnose + compiler-visible limitations while portable browser includes and runtime + permission errors retain their intended behavior. +- The checked UDP overlay preserves the entire buffer sequence and one-datagram + semantics. Synchronous scratch uses the context allocator, asynchronous scratch + uses the associated allocator, and scatter/copy cleanup precedes callback + delivery. The retry fix separates immutable validation failure from EAGAIN. +- `tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp:181` + defers host lookup until queued execution and joins native waitables to the + reactor instead of blocking initiation or polling DNS on a timer. The + cancellation queue protects borrowed descriptors until the active poll returns. + SDK/version/header checks make the private ABI dependency explicit. +- `libs/asio/include/webcpp/asio/browser/main_thread_context.hpp:85` separates + queued-control lifetime from the context service. It safely discards pending + callbacks during reentrant destruction, retains control during delivery and + owns operation memory before potentially throwing handler moves. The public + allocator-resource lifetime clarification is present. +- P2 TLS reuses the existing pinned source provider, CA contract and checked + Cobalt overlays. Actual peer identity/trust failures, transfer, shutdown, + cancellation and entropy failure evidence are distinguished from build success. +- The evidence record does not disguise the initial invalid WASI launcher run, + UDP RED chronology, raw Asyncify pthread return-value failure, screenshot + limitation or upstream Cobalt issue 287 as successful feature coverage. + +## Issues + +### Critical (Must Fix) + +None found. + +### Important (Should Fix) + +1. **Provision Chrome for both new browser own lanes.** + + Locations: `libs/asio/test/browser/Jamfile:69` and `:84`; + missing integration in `tools/ci/matrix.py:194`. + + The newly registered `browser-workers` and `browser-worker-exceptions` lanes + are absent from `CHROME_LANES`. The actual matrix functions therefore produce + `chrome=False` and `os=ubuntu-24.04` for both. The workflow only installs the + pinned browser and sets `CHROME` when that flag is true + (`.github/workflows/library.yml:336`). On Linux, `findChrome` immediately + rejects an absent `CHROME` (`libs/asio/test/browser/run.mjs:29`). These jobs + cannot execute their real-browser tests when scheduled, despite the successful + local macOS runs. + + Add both lanes to the browser provisioning classification and extend the + focused matrix regression to cover their actual entries. Do not rely on an + incidental runner browser or change the driver to silently skip execution. + +2. **Encode the promised profile coverage in recurring own-lane requests.** + + Locations: `libs/asio/test/browser/Jamfile:46`, `:79`, + `libs/asio/test/wasip2_tls_cobalt/Jamfile:38`; shared request construction at + `tools/ci/matrix.py:516` and `:771`. + + The new browser drivers compile direct sources, not the older browser lane's + two-variant manifests. Their lane declarations and CI requests supply no + suspension/EH expansion. Consequently `browser-workers` schedules only default + JSPI/EH-on, `browser-worker-exceptions` schedules only JSPI/EH-on, and + `wasip2-tls` schedules only EH-on. The manually supplied local matrix flags do + not persist in recurring coverage. Asyncify and the supported no-EH paths, + including the explicitly retained Cobalt limitation boundary, can regress + without these own lanes exercising them. + + Encode JSPI/Asyncify plus EH-on/off for `browser-workers`, both suspension + variants with EH-on for `browser-worker-exceptions`, and EH-on/off for + `wasip2-tls`, either in the established own-lane options mechanism or explicit + B2 target variants. Add focused checks of the generated requests and confirm + that the B2 graph contains the intended configurations. Avoid expanding the + exception-only fixture into an unsupported no-EH execution. + +### Minor (Nice to Have) + +3. **Point the P2 TLS how-to at the lane that runs its advertised tests.** + + Locations: `libs/asio/doc/wasip2.adoc:35` and + `libs/asio/doc/building.adoc:439`. + + The new P2 command names only `libs/asio/test/wasip2_tls_cobalt`, but + `webcpp.lane` marks the TLS/entropy/status drivers explicit + (`tools/webcpp.jam:930`). That directory command runs the ordinary consumers + and skips the advertised real TLS peer checks. The general TLS guide also + says `libs/asio/test/tls//tls-integration` covers P2, although its Jamfile + declares only native/P3 (`libs/asio/test/tls/Jamfile:9`, `:46`). + + Keep the directory for the ordinary Cobalt tests and additionally name + `libs/asio/test/wasip2_tls_cobalt//wasip2-tls` in the P2 command. Describe the + separate P2 lane in the general TLS guide instead of extending the old lane's + claimed scope. The older `tools/openssl/test/run.py --fresh` driver also + remains native/P3; do not imply it supplies the new P2 evidence. + +4. **Remove the stale single-thread Cobalt DNS refusal statement.** + + Location: `libs/asio/doc/feature-matrix.adoc:410`. + + The paragraph still says async resolution without threads returns + `operation_not_supported` and that this negative behavior is tested. The + preceding updated numeric-resolver row and the completed P3 native-async + backend now establish the opposite. This wrongly tells a user the completed + capability is unavailable. + + State the actual numeric/forward asynchronous resolver behavior and its + evidence, retaining the separate qualification that arbitrary external DNS + access depends on host policy and is not established by localhost/numeric + consumers. + +## Checks and evidence + +- Read the implementation changes and immediate shared dependencies, including + allocator/cancellation completion paths, overlay preparation/ABI checks, + optional provider selection, header diagnostics, driver registration, + the lint integrity-gated exemption and changed proposal/public documentation. +- Read `progress.md`, the final local verification document, task reports and + scoped approved task reviews. Their recorded native 105, P2 66, P3 117 and + Emscripten 233 broad B2 checks, own-lane runtime results, real browser runs, + targeted static analysis and rendered-content checks were not rerun. +- Named focused experiment: **recurring lane environment/profile synthesis**. + Imported `tools/ci/matrix.py` with `python3 -B`, constructed the three actual + `OwnLane` records, and called only `own_lane_entry` and `own_lane_command`. + This was read-only, did not dispatch CI, and produced: + + ```text + browser-workers chrome=False os=ubuntu-24.04 + b2 --user-config=candidate-user-config.jam -a --dump-tests --out-xml=candidate.xml toolset=emscripten libs/asio/test/browser//browser-workers + browser-worker-exceptions chrome=False os=ubuntu-24.04 + b2 --user-config=candidate-user-config.jam -a --dump-tests --out-xml=candidate.xml toolset=emscripten libs/asio/test/browser//browser-worker-exceptions + wasip2-tls chrome=False os=ubuntu-24.04 + b2 --user-config=candidate-user-config.jam -a --dump-tests --out-xml=candidate.xml toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh libs/asio/test/wasip2_tls_cobalt//wasip2-tls + ``` + + Inspected `tools/drive/drive.jam:94` to confirm that direct-source driven + tests do not implicitly expand suspension or exception modes. Inspected + `tools/webcpp.jam:930` to confirm explicit own-lane members are excluded from + an ordinary directory build. No repeat feature suite was needed to establish + these integration defects. +- Parent reported that final broad runs, documentation, metadata/check-release, + proposal export verification and proposal checks finished successfully during + this review. Before report freeze, the parent also confirmed completed database + generation with 1,451 compilation commands and all headers materialized. This does not establish correctness of the missing recurring + environment/profile settings found above. + +## Recommendations + +Resolve the four findings in one scoped fix wave. Use focused matrix regressions +and the affected generated B2 graph/driver checks to verify the automation +corrections; re-render/check the corrected guide text. No SDK change, production +backend rewrite, remote CI dispatch or broad suite replay is needed to resolve +these findings. + +## Declined to judge + +- General external DNS reachability, IPv6 traffic, multicast and all native + OS-specific devices: outside the approved implementation increment and + explicitly listed as unverified/future validation in the feature matrix. +- Broader Cobalt coroutine composition and fixing upstream issue 287: excluded + by the binding scope; this review checks preservation of the documented limit. +- Runtime guarantees for other browser engines, Windows/Linux native execution + or other SDK/runtime versions: the supplied local evidence does not establish + those combinations and the candidate does not claim it does. +- Desktop/narrow rendered-page visual perfection: the recorded screenshot + attempts did not yield usable images; rendered content/link checks do not + establish pixel-level review. This remains unverified, not approved visually. +- Publication, fresh remote CI and merge readiness against remote branch state: + explicitly excluded from this increment; no remote action was performed. + +## Assessment + +**Ready to merge? With fixes.** + +The completed runtime implementations and their scoped corrections are coherent +with the approved design; this pass found no additional production backend or +lifetime defect. Two recurring-test integration defects must be corrected, and +the two documentation findings should be reconciled in the same local fix wave. +The verdict is for this frozen candidate and does not close publication gates. From 3b2bf444ddc7c9b59399327fd469576419652d16 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 12:05:51 -0500 Subject: [PATCH 15/32] Fix full lint coverage for configured OpenSSL consumers --- CODING-GUIDELINES.md | 10 +- libs/asio | 2 +- libs/beast | 2 +- tools/boost/cobalt-ssl/ssl.cpp | 3 +- tools/lint/compile_commands.py | 52 ++++++++- tools/lint/lint_test.py | 34 +++++- tools/openssl/test/.clang-tidy | 8 ++ tools/openssl/test/cobalt_ssl_cancel.cpp | 66 +++++++----- tools/openssl/test/combined_provider.cpp | 13 +-- tools/openssl/test/threads.cpp | 18 ++-- tools/openssl/test/tls_client.cpp | 120 ++++++++++++--------- tools/openssl/test/tls_client_embedded.cpp | 2 +- 12 files changed, 228 insertions(+), 102 deletions(-) create mode 100644 tools/openssl/test/.clang-tidy diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 2af542ba..192f6810 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -615,6 +615,12 @@ A source b2 expects not to compile (`webcpp.compile-fail`), and one that must stop with the error it states (`webcpp.compile-diagnostic`), are left out of clang-tidy only; every other rule reads them. +The compilation database prepares generated inputs before analysis. Public +header units prepare their dependencies; programs that select another OpenSSL +configuration prepare that exact configuration through B2 as well, including +their exception-off twins. B2 builds only the requested header artifacts and +their dependencies during this preparation, never the consumer's run target. + **A library's include boundaries.** Every header compiles alone, so only a boundary check sees a part of a library start to depend on another. A library declares its boundaries in `meta/include-boundaries.json`, each a set @@ -6117,7 +6123,7 @@ which includes the change `shared-connection` (trystero `2e2dcd4`, webcpp example needs the public relays or a browser. Source: `doc/differences.adoc` (libs/trystero). -### asio (Boost.Asio and Cobalt on native, Emscripten and WASIp3; implemented for 0.1.0 in preparation) +### asio (Boost.Asio and Cobalt on native, Emscripten and WASIp2/P3; implemented for 0.1.0 in preparation) webcpp::asio is a C++20 wrapper over Boost.Asio: natively it is Boost.Asio itself, and on Emscripten it is Boost's own `io_context`, whose run @@ -8646,7 +8652,7 @@ compatibility departure belongs with its rationale in chapter 15. ### Asio/Beast closure: remaining gates and limits Chapter 15 now records the implemented configuration, allocator and private-header -corrections, native/Emscripten/WASIp3 target contract, default turn limit 100, +corrections, native/Emscripten/WASIp2/P3 target contract, default turn limit 100, Diataxis guide, source-built OpenSSL, checked Boost overlays and recurring thread and TLS lanes. Chapter 4's executor contract and compiled-unit exceptions and chapter 6's SDK-limited exception profiles reflect the existing approvals. diff --git a/libs/asio b/libs/asio index 9455076a..984c7054 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 9455076a56ece86204229c455fe64b7ed5fbf530 +Subproject commit 984c7054c4cecd2d7fb7beeae2ddaa83deaea299 diff --git a/libs/beast b/libs/beast index ab95e844..7d41654d 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit ab95e844d2eee707eedd3ac708e3a14c9ff8b47d +Subproject commit 7d41654d750061ecf4b1bac873cd66af28cf8a09 diff --git a/tools/boost/cobalt-ssl/ssl.cpp b/tools/boost/cobalt-ssl/ssl.cpp index f7441e81..9c1024c9 100644 --- a/tools/boost/cobalt-ssl/ssl.cpp +++ b/tools/boost/cobalt-ssl/ssl.cpp @@ -4,4 +4,5 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -#include +// Compile the checked, patched upstream implementation through its selected include directory. +#include // NOLINT(bugprone-suspicious-include) diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index 3f0188a5..012e6385 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -607,6 +607,47 @@ def prepare_boost_overlays(root: str, target: str, commands: list[list[str]]) -> 'while preparing checked Boost overlays') +def prepare_openssl_headers(root: str, request: list[str], commands: list[list[str]]) -> None: + """Build each program's configured OpenSSL headers without executing its test target.""" + includes: set[Path] = set() + for words in commands: + for index, word in enumerate(words): + if word in ('-I', '-isystem') and index + 1 < len(words): + include = words[index + 1] + elif word.startswith('-I'): + include = word[2:] + else: + continue + directory = Path(root, include).resolve() + if (directory.is_relative_to(Path(root, BUILD_DIR, 'third_party').resolve()) + and directory.name == 'include' + and directory.parent.name.startswith('config-')): + includes.add(directory) + if not includes: + return + # libdatachannel also publishes config-*/include. Identify the provider from + # its actual B2 action, rather than assuming every configured directory is TLS. + headers: set[str] = set() + for line in dry_run(root, request): + built = re.fullmatch(r'webcpp-openssl\.build (.+[/\\])libssl\.(?:a|lib)', line) + if built: + directory = Path(root, built.group(1), 'include') + # B2 aliases explicit outputs by their original spelling, even when + # the build directory is a symlink. Canonicalize only comparisons. + if directory.resolve() in includes: + headers.add(str(directory / 'openssl/configuration.h')) + if not headers: + return + # Keep the original request so B2 constructs the exact consumer variants. + # Explicit output filenames restrict execution to these dependencies, even + # though the request includes run targets. Never execute a dry-run shell line. + command, completed = run_b2(root, ['-d0', 'webcpp-require-external=on', + *request, *sorted(headers)]) + if completed.returncode != 0 or any(not Path(header).is_file() for header in headers): + raise Failure(f'{completed.stdout}{" ".join(command)} exited {completed.returncode} ' + 'while preparing program OpenSSL headers') + + def source_path(root: str, source: str) -> str: """The physical source's path relative to root, independent of its Jamfile's spelling.""" return os.path.relpath(os.path.realpath(os.path.join(root, source)), os.path.realpath(root)) @@ -614,7 +655,7 @@ def source_path(root: str, source: str) -> str: def read(root: str, target: str, commands: list[list[str]], entries: list[dict[str, object]], seen: set[tuple[str, ...]], earlier: set[str], - wasi_clang: str | None) -> tuple[Units, set[str]]: + wasi_clang: str | None, request: list[str]) -> tuple[Units, set[str]]: """Adds to entries each command of commands, compiled for target, that compiles a .cpp file of the source tree that is not in earlier, a source an earlier target compiles, and that is not in seen, as the lint analyses it (analysed); a WebAssembly command of a compiler other than @@ -642,6 +683,7 @@ def read(root: str, target: str, commands: list[list[str]], entries: list[dict[s entries.append({'directory': root, 'file': os.path.join(root, source), 'arguments': analysed(target, source, words, wasi_clang)}) prepare_boost_overlays(root, target, selected) + prepare_openssl_headers(root, request, selected) return units, sources @@ -740,8 +782,8 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni kept: set[str] = set() compiled: set[str] = set() selected: list[list[str]] = [] - for words in compiles(dry_run(root, [*TARGETS[target], WITHOUT_EXCEPTIONS, *PROGRAMS, *lanes, - *handler, *requested])): + request = [*TARGETS[target], WITHOUT_EXCEPTIONS, *PROGRAMS, *lanes, *handler, *requested] + for words in compiles(dry_run(root, request)): source = words[-1] unit = ALONE.match(source) if unit: @@ -764,6 +806,7 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni entries.append({'directory': root, 'file': os.path.join(root, source), 'arguments': analysed(target, source, words, wasi_clang)}) prepare_boost_overlays(root, target, selected) + prepare_openssl_headers(root, request, selected) twinned.programs |= kept - compiled for library, theirs in aggregates.items(): index = next(index for index, aggregate in enumerate(theirs) @@ -818,7 +861,8 @@ def database(root: str, wasi_clang: str | None = None) -> list[dict[str, object] continue units[target], sources = read(root, target, target_run(root, target, declaring, lanes.get(target, [])), - entries, seen, set(first), wasi_clang) + entries, seen, set(first), wasi_clang, + [*TARGETS[target], *PROGRAMS, *lanes.get(target, [])]) for source in sources: first.setdefault(source, target) diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index a3a5fc91..895dc098 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -401,9 +401,9 @@ def test_compile_database_prepares_generated_header_dependencies(root): harness.replace(root / 'libs/demo/build.jam', 'include ;', 'include /webcpp/third_party//ca_certificates ;') append(root, 'libs/demo/include/webcpp/demo.hpp', - '\n#include \n' - 'static_assert(webcpp::detail::ca_certificates::count > 0);\n') - assert not list((root / 'bin').rglob('webcpp_ca_certificates.hpp')) + '\n#include \n' + 'static_assert(webcpp::asio::detail::ca_certificates::count > 0);\n') + assert not list((root / 'bin').rglob('ca_certificates.hpp')) completed = compile_database(root) assert completed.returncode == 0, completed.stdout[-6000:] entries = json.loads((root / 'compile database/compile_commands.json').read_text()) @@ -417,6 +417,33 @@ def test_compile_database_prepares_generated_header_dependencies(root): assert not list((root / 'bin').rglob('*.run')) +def test_compile_database_prepares_program_openssl_variants(root): + # A program-only define selects a different OpenSSL configuration than any + # public header unit. Both exception modes must be analysable on a clean tree. + # A relocated build tree must retain B2's output spelling during preparation. + output = root / 'build outputs' + output.mkdir() + (root / 'bin').symlink_to(output, target_is_directory=True) + harness.add_library(root, 'tls_user', HASH + '\nimport webcpp ;\n' + 'webcpp.targets native ;\n' + 'webcpp.run tls_program : tls_program.cpp\n' + ' : /webcpp/third_party//openssl\n' + ' WEBCPP_TEST_TLS_PROGRAM ;\n', + {'tls_program.cpp': CPP + '\n#include \n' + 'int main() { return SSL_ERROR_NONE; }\n'}) + completed = compile_database(root) + assert completed.returncode == 0, completed.stdout[-6000:] + source = root / 'libs/tls_user/test/tls_program.cpp' + entries = json.loads((root / 'compile database/compile_commands.json').read_text()) + commands = [entry['arguments'] for entry in entries if Path(entry['file']) == source] + assert len(commands) == 2, commands + for command in commands: + said = compile_commands.compiles_aggregate(str(root), command, str(source)) + assert not said, said + # Preparation may build dependencies, but must not execute consumer programs. + assert not list((root / 'bin').rglob('*.run')) + + def test_compile_database_reads_what_only_wasi_builds(root): add_component_demo(root) completed = compile_database(root) @@ -2197,6 +2224,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_a_user_config_the_environment_names_is_read, test_compile_database_lists_what_b2_builds, test_compile_database_prepares_generated_header_dependencies, + test_compile_database_prepares_program_openssl_variants, test_compile_database_reads_what_only_wasi_builds, test_an_aggregate_no_units_options_compile_names_each, test_wasi_sdk_is_told_by_the_compiler_itself, diff --git a/tools/openssl/test/.clang-tidy b/tools/openssl/test/.clang-tidy new file mode 100644 index 00000000..f23c83ed --- /dev/null +++ b/tools/openssl/test/.clang-tidy @@ -0,0 +1,8 @@ +# A probe's main lets an unexpected exception terminate the process and fail +# the test, as the library tests do. Keep exception-escape checks for noexcept +# functions, destructors, moves and swaps. +--- +InheritParentConfig: true +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/tools/openssl/test/cobalt_ssl_cancel.cpp b/tools/openssl/test/cobalt_ssl_cancel.cpp index 75766d83..cfe31e3d 100644 --- a/tools/openssl/test/cobalt_ssl_cancel.cpp +++ b/tools/openssl/test/cobalt_ssl_cancel.cpp @@ -129,6 +129,41 @@ cobalt::task cancel_read(tls_pair& pair, bool composed) { require(static_cast(pair.peer.close())); } +cobalt::task wait_for_blocked_write(tls_pair& pair, + const cobalt::promise& writing, + const cobalt::promise& receiving, + bool can_cancel) { + pollfd descriptor{.fd = pair.client.native_handle(), .events = POLLOUT, .revents = 0}; + int ready = 1; + while (!writing.ready()) { + co_await asio::post(pair.exec, cobalt::use_op); + ready = ::poll(&descriptor, 1, 0); + constexpr unsigned failure_events = static_cast(POLLERR) | + static_cast(POLLHUP) | + static_cast(POLLNVAL); + require(ready >= 0 && (static_cast(descriptor.revents) & failure_events) == 0); + if (ready == 0 && receiving.ready() && can_cancel) { + // WASIp2 may already have a successful SSL completion queued while + // libc reports no current write permit. Let the reactor progress, + // then require that the same operation is still blocked before + // cancelling it. This timer is an event-loop barrier, not evidence + // of backpressure; the second poll and promise state provide that. + asio::steady_timer barrier(pair.exec, std::chrono::milliseconds(1)); + const auto [barrier_error] = + co_await cobalt::as_tuple(barrier.async_wait(cobalt::use_op)); + require(!barrier_error); + descriptor.revents = 0; + ready = ::poll(&descriptor, 1, 0); + require(ready >= 0 && + (static_cast(descriptor.revents) & failure_events) == 0); + if (ready == 0 && !writing.ready()) { + break; + } + } + } + co_return ready; +} + cobalt::task cancel_write(tls_pair& pair, bool composed) { require(static_cast(pair.client.set_send_buffer_size(4096))); require(static_cast(pair.peer.set_receive_buffer_size(4096))); @@ -146,35 +181,8 @@ cobalt::task cancel_write(tls_pair& pair, bool composed) { while (total < data.size()) { // One promise per primitive write: a cancelled promise must not start another await. auto writing = write_transfer(pair.client, io::buffer(data) + total, composed); - pollfd descriptor{.fd = pair.client.native_handle(), .events = POLLOUT, .revents = 0}; - int ready = 1; - while (!writing.ready()) { - co_await asio::post(pair.exec, cobalt::use_op); - ready = ::poll(&descriptor, 1, 0); - constexpr unsigned failure_events = static_cast(POLLERR) | - static_cast(POLLHUP) | - static_cast(POLLNVAL); - require(ready >= 0 && - (static_cast(descriptor.revents) & failure_events) == 0); - if (ready == 0 && receiving.ready() && (composed || total != 0)) { - // WASIp2 may already have a successful SSL completion queued while - // libc reports no current write permit. Let the reactor progress, - // then require that the same operation is still blocked before - // cancelling it. This timer is an event-loop barrier, not evidence - // of backpressure; the second poll and promise state provide that. - asio::steady_timer barrier(pair.exec, std::chrono::milliseconds(1)); - const auto [barrier_error] = - co_await cobalt::as_tuple(barrier.async_wait(cobalt::use_op)); - require(!barrier_error); - descriptor.revents = 0; - ready = ::poll(&descriptor, 1, 0); - require(ready >= 0 && - (static_cast(descriptor.revents) & failure_events) == 0); - if (ready == 0 && !writing.ready()) { - break; - } - } - } + const int ready = + co_await wait_for_blocked_write(pair, writing, receiving, composed || total != 0); const bool cancel = !writing.ready(); if (cancel) { require(ready == 0 && receiving.ready()); diff --git a/tools/openssl/test/combined_provider.cpp b/tools/openssl/test/combined_provider.cpp index 5323e2d2..385c6ded 100644 --- a/tools/openssl/test/combined_provider.cpp +++ b/tools/openssl/test/combined_provider.cpp @@ -15,18 +15,19 @@ int main() { if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) { - std::fprintf(stderr, "OpenSSL headers and implementation differ: %s / %s\n", - OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION)); + static_cast(std::fprintf(stderr, + "OpenSSL headers and implementation differ: %s / %s\n", + OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION))); return 1; } boost::asio::io_context context; boost::asio::ssl::context tls(boost::asio::ssl::context::tls_client); - boost::beast::tcp_stream stream(context); - webcpp::trystero::native::backend backend(context.get_executor()); + const boost::beast::tcp_stream stream(context); + const webcpp::trystero::native::backend backend(context.get_executor()); rtc::PeerConnection peer(rtc::Configuration{}); - auto channel = peer.createDataChannel("combined-provider"); + const auto channel = peer.createDataChannel("combined-provider"); peer.close(); - if (!channel || !tls.native_handle()) { + if (!channel || tls.native_handle() == nullptr) { return 2; } std::puts("Asio, Beast and Trystero share the pinned OpenSSL provider"); diff --git a/tools/openssl/test/threads.cpp b/tools/openssl/test/threads.cpp index 4ed34720..ef24ecfa 100644 --- a/tools/openssl/test/threads.cpp +++ b/tools/openssl/test/threads.cpp @@ -29,12 +29,14 @@ int main() { ready.notify_all(); ready.wait(lock, [&] { return release; }); } - if (!contexts[i]) + if (contexts[i] == nullptr) { return; + } std::array buffer{}; for (int round = 0; round < 16; ++round) { - if (RAND_priv_bytes(buffer.data(), buffer.size()) != 1) + if (RAND_priv_bytes(buffer.data(), buffer.size()) != 1) { return; + } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } EVP_PKEY* key = EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", "prime256v1"); @@ -49,19 +51,23 @@ int main() { // All workers retain their contexts until comparison is complete. for (std::size_t i = 0; i < contexts.size(); ++i) { distinct = distinct && contexts[i] != nullptr; - for (std::size_t j = 0; j < i; ++j) + for (std::size_t j = 0; j < i; ++j) { distinct = distinct && contexts[i] != contexts[j]; + } } release = true; } ready.notify_all(); - for (auto& worker : workers) + for (auto& worker : workers) { worker.join(); - if (!distinct) + } + if (!distinct) { return 1; + } for (std::size_t i = 0; i < workers.size(); ++i) { - if (!passed[i]) + if (!passed[i]) { return 1; + } } std::puts("PASS 4 threads: distinct private DRBG contexts, 64 random requests, 4 EC keys"); } diff --git a/tools/openssl/test/tls_client.cpp b/tools/openssl/test/tls_client.cpp index 55334099..8d003f43 100644 --- a/tools/openssl/test/tls_client.cpp +++ b/tools/openssl/test/tls_client.cpp @@ -17,9 +17,65 @@ #include #endif -int main(int argc, char** argv) { - if (argc != 6) +namespace { + +using tls_stream = webcpp::asio::ssl::stream; + +bool verify_handshake(tls_stream& stream, boost::system::error_code error, bool reject, + int& result) { + if (error) { + if (reject && SSL_get_verify_result(stream.native_handle()) != X509_V_OK) { + static_cast( + std::printf("PASS certificate rejection: %s\n", error.message().c_str())); + result = 0; + } else { + static_cast(std::fprintf(stderr, "handshake: %s\n", error.message().c_str())); + } + return false; + } + if (reject) { + static_cast(std::fprintf(stderr, "FAIL: invalid identity was accepted\n")); + return false; + } + return true; +} + +void exchange(tls_stream& stream, const std::array& request, std::array& response, + int& result) { + boost::asio::async_write( + stream, boost::asio::buffer(request), + [&](boost::system::error_code write_ec, std::size_t bytes) { + if (write_ec || bytes != request.size()) { + return; + } + boost::asio::async_read( + stream, boost::asio::buffer(response), + [&](boost::system::error_code read_ec, std::size_t count) { + if (read_ec || count != response.size() || + std::string_view(response.data(), count) != "pong") { + return; + } + stream.async_shutdown([&](boost::system::error_code shutdown_ec) { + if (shutdown_ec) { + static_cast(std::fprintf(stderr, "shutdown: %s\n", + shutdown_ec.message().c_str())); + return; + } + static_cast(std::printf( + "PASS %s: verified handshake, async ping/pong, clean shutdown\n", + SSL_get_version(stream.native_handle()))); + result = 0; + }); + }); + }); +} + +} // namespace + +int main(int argc, char* const* argv) { + if (argc != 6) { return 2; + } const auto port = static_cast(std::strtoul(argv[1], nullptr, 10)); const char* hostname = argv[2]; const bool reject = std::string_view(argv[4]) == "reject"; @@ -31,81 +87,49 @@ int main(int argc, char** argv) { : webcpp::asio::make_tls_client_context(argv[3]); if (!prepared) { const auto message = prepared.error().message(); - std::fprintf(stderr, "CA preparation: %s\n", message.c_str()); + static_cast(std::fprintf(stderr, "CA preparation: %s\n", message.c_str())); return 1; } auto tls = std::move(*prepared); #else webcpp::asio::ssl::context tls(webcpp::asio::ssl::context::tls_client); boost::system::error_code error; - tls.load_verify_file(argv[3], error); + // Boost's deprecated return duplicates the error output checked below. + // NOLINTNEXTLINE(bugprone-unused-return-value) + static_cast(tls.load_verify_file(argv[3], error)); if (error) { - std::fprintf(stderr, "CA load: %s\n", error.message().c_str()); + static_cast(std::fprintf(stderr, "CA load: %s\n", error.message().c_str())); return 1; } #endif - if (!SSL_CTX_set_min_proto_version(tls.native_handle(), version) || - !SSL_CTX_set_max_proto_version(tls.native_handle(), version)) + if (SSL_CTX_set_min_proto_version(tls.native_handle(), version) != 1 || + SSL_CTX_set_max_proto_version(tls.native_handle(), version) != 1) { return 1; - webcpp::asio::ssl::stream stream(context, tls); + } + tls_stream stream(context, tls); #ifndef WEBCPP_TEST_EMBEDDED_CA stream.set_verify_mode(webcpp::asio::ssl::verify_peer); #endif stream.set_verify_callback(webcpp::asio::ssl::host_name_verification(hostname)); - if (SSL_set_tlsext_host_name(stream.native_handle(), hostname) != 1) + if (SSL_set_tlsext_host_name(stream.native_handle(), hostname) != 1) { return 1; + } const std::array request{'p', 'i', 'n', 'g'}; std::array response{}; int result = 1; stream.next_layer().async_connect( {boost::asio::ip::address_v4::loopback(), port}, [&](boost::system::error_code ec) { if (ec) { - std::fprintf(stderr, "connect: %s\n", ec.message().c_str()); + static_cast(std::fprintf(stderr, "connect: %s\n", ec.message().c_str())); return; } stream.async_handshake( webcpp::asio::ssl::stream_base::client, [&](boost::system::error_code handshake_ec) { - if (handshake_ec) { - if (reject && SSL_get_verify_result(stream.native_handle()) != X509_V_OK) { - std::printf("PASS certificate rejection: %s\n", - handshake_ec.message().c_str()); - result = 0; - } else { - std::fprintf(stderr, "handshake: %s\n", handshake_ec.message().c_str()); - } - return; - } - if (reject) { - std::fprintf(stderr, "FAIL: invalid identity was accepted\n"); + if (!verify_handshake(stream, handshake_ec, reject, result)) { return; } - boost::asio::async_write( - stream, boost::asio::buffer(request), - [&](boost::system::error_code write_ec, std::size_t bytes) { - if (write_ec || bytes != request.size()) - return; - boost::asio::async_read( - stream, boost::asio::buffer(response), - [&](boost::system::error_code read_ec, std::size_t count) { - if (read_ec || count != response.size() || - std::string_view(response.data(), count) != "pong") - return; - stream.async_shutdown( - [&](boost::system::error_code shutdown_ec) { - if (shutdown_ec) { - std::fprintf(stderr, "shutdown: %s\n", - shutdown_ec.message().c_str()); - return; - } - std::printf( - "PASS %s: verified handshake, async ping/pong, " - "clean shutdown\n", - SSL_get_version(stream.native_handle())); - result = 0; - }); - }); - }); + exchange(stream, request, response, result); }); }); context.run(); // lint-run: the probe owns the application event loop diff --git a/tools/openssl/test/tls_client_embedded.cpp b/tools/openssl/test/tls_client_embedded.cpp index 1ecdc994..f08dceba 100644 --- a/tools/openssl/test/tls_client_embedded.cpp +++ b/tools/openssl/test/tls_client_embedded.cpp @@ -7,4 +7,4 @@ // Keep a distinct translation unit so a joint B2 build cannot reuse the // filesystem-CA client's object for the client that accepts certificate bytes. #define WEBCPP_TEST_EMBEDDED_CA -#include "tls_client.cpp" +#include "tls_client.cpp" // NOLINT(bugprone-suspicious-include) From 080230c3a16f4a2d652443dad398e7f14eda4979 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 12:37:03 -0500 Subject: [PATCH 16/32] Keep incremental lint preparation from running consumers --- CODING-GUIDELINES.md | 6 ++- Jamroot | 3 ++ tools/lint/compile_commands.py | 16 +++++-- tools/lint/lint_test.py | 47 ++++++++++++++++--- tools/webcpp-openssl.jam | 85 +++++++++++++++++++++++++++++++++- 5 files changed, 142 insertions(+), 15 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 192f6810..e28ad49c 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -618,8 +618,10 @@ out of clang-tidy only; every other rule reads them. The compilation database prepares generated inputs before analysis. Public header units prepare their dependencies; programs that select another OpenSSL configuration prepare that exact configuration through B2 as well, including -their exception-off twins. B2 builds only the requested header artifacts and -their dependencies during this preparation, never the consumer's run target. +their exception-off twins. A dedicated preparation target resolves each original +request with its own defaults and returns only the requested provider headers. +B2 updates those artifacts and their dependencies even when headers already +exist, without compiling or running the consumers used to discover the variants. **A library's include boundaries.** Every header compiles alone, so only a boundary check sees a part of a library start to depend on another. A diff --git a/Jamroot b/Jamroot index a484271d..27e5b8e3 100644 --- a/Jamroot +++ b/Jamroot @@ -780,6 +780,9 @@ actions dist notfile dist : @dist : : doc off ; +# This target is declared only for the lint's explicit preparation request. +webcpp-openssl.declare-lint-headers ; + explicit boost_version throw_exception boost_json boost_url boost_charconv boost_locale boost_cobalt boost_cobalt_io_ssl node-test emscripten-reference test example doc install $(.install) declared-targets declared-lanes site site-serve check-release whats-new diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index 012e6385..9fa0d79a 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -638,11 +638,17 @@ def prepare_openssl_headers(root: str, request: list[str], commands: list[list[s headers.add(str(directory / 'openssl/configuration.h')) if not headers: return - # Keep the original request so B2 constructs the exact consumer variants. - # Explicit output filenames restrict execution to these dependencies, even - # though the request includes run targets. Never execute a dry-run shell line. - command, completed = run_b2(root, ['-d0', 'webcpp-require-external=on', - *request, *sorted(headers)]) + # Resolve the original consumers inside a dedicated B2 preparation target. + # Its result contains only provider headers, even when those files exist. + # Existing filenames on B2's command line would instead become input files + # and let B2 execute all the consumers. Never execute a dry-run shell line. + properties = ['webcpp-require-external=on', + *(argument for argument in request if '=' in argument)] + original = [f'--webcpp-lint-property={argument}' for argument in properties] + sources = [f'--webcpp-lint-source={argument}' for argument in request if '=' not in argument] + requested = [f'--webcpp-lint-header={header}' for header in sorted(headers)] + command, completed = run_b2(root, ['-d0', *properties, *original, *sources, *requested, + 'lint-openssl-headers']) if completed.returncode != 0 or any(not Path(header).is_file() for header in headers): raise Failure(f'{completed.stdout}{" ".join(command)} exited {completed.returncode} ' 'while preparing program OpenSSL headers') diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 895dc098..2527914c 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -425,23 +425,56 @@ def test_compile_database_prepares_program_openssl_variants(root): output.mkdir() (root / 'bin').symlink_to(output, target_is_directory=True) harness.add_library(root, 'tls_user', HASH + '\nimport webcpp ;\n' - 'webcpp.targets native ;\n' - 'webcpp.run tls_program : tls_program.cpp\n' - ' : /webcpp/third_party//openssl\n' - ' WEBCPP_TEST_TLS_PROGRAM ;\n', - {'tls_program.cpp': CPP + '\n#include \n' - 'int main() { return SSL_ERROR_NONE; }\n'}) + 'webcpp.targets native ;\n', {}) + lane = root / 'libs/tls_user/test/release' + lane.mkdir() + (lane / 'Jamfile').write_text(HASH + '\nimport webcpp ;\n' + 'project : default-build release ;\n' + 'webcpp.targets native ;\n' + 'webcpp.run tls_program : tls_program.cpp\n' + ' : /webcpp/third_party//openssl\n' + ' WEBCPP_TEST_TLS_PROGRAM ;\n' + 'webcpp.lane tls-variant : tls_program : native ;\n') + source = lane / 'tls_program.cpp' + source.write_text(CPP + '\n#include \n' + 'int main() { return SSL_ERROR_NONE; }\n') completed = compile_database(root) assert completed.returncode == 0, completed.stdout[-6000:] - source = root / 'libs/tls_user/test/tls_program.cpp' entries = json.loads((root / 'compile database/compile_commands.json').read_text()) commands = [entry['arguments'] for entry in entries if Path(entry['file']) == source] assert len(commands) == 2, commands for command in commands: + # The preparation target must preserve the own lane's release default, + # rather than propagate its own debug default into the consumer. + assert any('/release/' in word for word in command), command said = compile_commands.compiles_aggregate(str(root), command, str(source)) assert not said, said # Preparation may build dependencies, but must not execute consumer programs. assert not list((root / 'bin').rglob('*.run')) + # Existing generated headers must not turn an incremental analysis into + # an execution of the consumer targets used to discover their variants. + repeated = compile_database(root) + assert repeated.returncode == 0, repeated.stdout[-6000:] + assert not list((root / 'bin').rglob('*.run')) + # A missing header and an existing, stale variant must both be updated. + # Inspect B2's actual actions without rebuilding OpenSSL a third time. + # B2 roots output paths at its actual cwd. Preserve the bin symlink while + # resolving the parent's /var alias on macOS, just as its dry run does. + headers = sorted(root.resolve() / header.relative_to(root) + for header in (root / 'bin/third_party').rglob('configuration.h')) + assert len(headers) == 2, headers + changed = max(header.stat().st_mtime for header in headers) + 1 + os.utime(root / 'tools/openssl/build.py', (changed, changed)) + headers[0].unlink() + pending = harness.run_b2( + root, '-n', '--webcpp-lint-source=libs/tls_user/test/release//tls-variant', + '--webcpp-lint-property=exception-handling=on,off', + *(f'--webcpp-lint-header={header}' for header in headers), 'lint-openssl-headers') + assert pending.returncode == 0, pending.stdout[-6000:] + assert len(re.findall(r'^webcpp-openssl\.build ', pending.stdout, re.MULTILINE)) == 2, ( + pending.stdout[-6000:]) + assert 'testing.capture-output' not in pending.stdout, pending.stdout[-6000:] + assert not re.search(r'^\S+\.compile', pending.stdout, re.MULTILINE), pending.stdout[-6000:] def test_compile_database_reads_what_only_wasi_builds(root): diff --git a/tools/webcpp-openssl.jam b/tools/webcpp-openssl.jam index 3c7ffbb9..5b9b39ab 100644 --- a/tools/webcpp-openssl.jam +++ b/tools/webcpp-openssl.jam @@ -5,8 +5,10 @@ # https://www.boost.org/LICENSE_1_0.txt) import "class" : new ; +import build-request ; import errors ; import feature ; +import modules ; import path ; import project ; import property-set ; @@ -81,7 +83,13 @@ class openssl-target : basic-target local generated = [ new file-target include/openssl/$(header) exact : H : $(self.project) : $(action) ] ; $(generated).set-path $(directory) ; - headers += [ virtual-target.register $(generated) ] ; + generated = [ virtual-target.register $(generated) ] ; + headers += $(generated) ; + if $(header) = configuration.h + { + modules.call-in webcpp-openssl : register-lint-header + $(directory)/include/openssl/$(header) : $(generated) ; + } } if [ $(properties).get ] = "on" { @@ -103,6 +111,81 @@ class openssl-target : basic-target } } +rule register-lint-header ( file : target ) +{ + .lint-header.$(file) = $(target) ; +} + +# Resolve consumers exactly as B2 does, but return only provider artifacts. +# Requesting existing filenames on B2's command line instead would treat them +# as input files and update every consumer in the original request. +class openssl-lint-headers-target : basic-target +{ + import errors ; + import modules ; + import property-set ; + + rule __init__ ( name : project : sources * : requirements * + : default-build * : usage-requirements * ) + { + basic-target.__init__ $(name) : $(project) : $(sources) : + $(requirements) : $(default-build) : $(usage-requirements) ; + } + + rule construct ( name : source-targets * : properties ) + { + # Generate each original top-level request independently. Making them + # sources of this target would propagate its defaults into own lanes. + for local request in [ modules.peek webcpp-openssl : .lint-properties ] + { + for local source in [ modules.peek webcpp-openssl : .lint-sources ] + { + local target = [ $(self.project).find $(source) ] ; + local generated = [ $(target).generate $(request) ] ; + } + } + local selected ; + for local file in [ modules.peek webcpp-openssl : .lint-requested-headers ] + { + local target = [ modules.peek webcpp-openssl : .lint-header.$(file) ] ; + if ! $(target) + { + errors.user-error "No OpenSSL header variant was generated for" $(file) ; + } + selected += $(target) ; + } + return [ property-set.empty ] $(selected) ; + } +} + +rule declare-lint-headers ( ) +{ + local arguments = [ modules.peek : ARGV ] ; + .lint-sources = [ MATCH "^--webcpp-lint-source=(.*)$" : $(arguments) ] ; + for local file in [ MATCH "^--webcpp-lint-header=(.*)$" : $(arguments) ] + { + .lint-requested-headers += [ path.make $(file) ] ; + } + local properties = [ MATCH "^--webcpp-lint-property=(.*)$" : $(arguments) ] ; + if $(properties) + { + local converted = [ build-request.convert-command-line-elements $(properties) ] ; + for local expanded in [ build-request.expand-no-defaults $(converted) ] + { + .lint-properties += [ property-set.create [ feature.split $(expanded) ] ] ; + } + } + else + { + .lint-properties = [ property-set.empty ] ; + } + if $(.lint-sources) && $(.lint-requested-headers) + { + targets.create-metatarget openssl-lint-headers-target : [ project.current ] + : lint-openssl-headers ; + } +} + rule declare ( root : headers * : sources * ) { .root = $(root) ; From d7a6614516facca397a60e8c3192c3328ebcfc46 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 12:40:31 -0500 Subject: [PATCH 17/32] Validate browser startup under delayed readiness --- libs/asio | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/asio b/libs/asio index 984c7054..059f64c4 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 984c7054c4cecd2d7fb7beeae2ddaa83deaea299 +Subproject commit 059f64c4c6aa316e351b10aca1f31ca810b446e6 From 38761bad4a0eb3ff75cb4e420dce8d26aa3fab57 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 12:55:09 -0500 Subject: [PATCH 18/32] Include Config in the Asio Windows overlay fixture --- tools/test/boost_libraries_test.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/test/boost_libraries_test.py b/tools/test/boost_libraries_test.py index 4a3f03c5..0c41fa86 100755 --- a/tools/test/boost_libraries_test.py +++ b/tools/test/boost_libraries_test.py @@ -694,6 +694,11 @@ def test_asio_windows_allocator_overlay_reaches_sources_and_consumers(root: Path (root / 'libs/asio/build.jam').write_text((original / 'build.jam').read_text()) for name in ('include', 'src'): shutil.copytree(original / name, root / 'libs/asio' / name) + # The actual Asio build project requires config even in a dry run. + config = root / 'libs/config' + config.mkdir() + shutil.copyfile(harness.ROOT / 'libs/config/build.jam', config / 'build.jam') + shutil.copytree(harness.ROOT / 'libs/config/include', config / 'include') harness.add_library(root, 'coroutines', COBALT_JAMFILE, {'coroutines.cpp': COBALT_SOURCE}) for request, selected in (((), False), (('target-os=windows',), True)): result = harness.run_b2(root, '-a', '-n', '-d+2', *request, From 6f0604cca1b8ecce46d6a7dbf443be68a98c5346 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 13:08:36 -0500 Subject: [PATCH 19/32] tools/test: Align Cobalt SSL guards with WASIp2 support --- tools/test/cobalt_ssl_test.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/tools/test/cobalt_ssl_test.py b/tools/test/cobalt_ssl_test.py index 4ef6cbac..e6cae175 100644 --- a/tools/test/cobalt_ssl_test.py +++ b/tools/test/cobalt_ssl_test.py @@ -65,14 +65,21 @@ def test_changed_ssl_source_is_refused(root: Path) -> None: def test_ssl_is_optional_and_unsupported_targets_are_refused(root: Path) -> None: + # P2 Cobalt uses Asio's pollable backend and its Config dependency. + for name in ('config', 'asio'): + source = harness.ROOT / 'libs' / name + target = root / 'libs' / name + shutil.copytree(source / 'include', target / 'include') + shutil.copyfile(source / 'build.jam', target / 'build.jam') harness.third_party_of_its_own(root, 'openssl', checked_out=False) harness.expect(harness.run_b2(root, '-n', '/webcpp//boost_cobalt'), True) - harness.expect(harness.run_b2(root, '/webcpp//boost_cobalt_io_ssl'), False, - 'OpenSSL sources are missing') - for target in ('emscripten', 'clang-wasip2'): + for target in ('clang', 'clang-wasip2', 'clang-wasip3'): harness.expect(harness.run_b2(root, 'toolset=' + target, '/webcpp//boost_cobalt_io_ssl'), False, - 'Cobalt SSL requires native or WASIp3') + 'OpenSSL sources are missing') + harness.expect(harness.run_b2(root, 'toolset=emscripten', + '/webcpp//boost_cobalt_io_ssl'), False, + 'Cobalt SSL requires native, WASIp2 or WASIp3 with source-built OpenSSL.') CASES = [test_transitive_openssl_is_unique, test_public_archive_in_a_path_with_spaces, From 31982c6c3b82cdf0c354b60758a5352cdaface18 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 13:32:39 -0500 Subject: [PATCH 20/32] asio: Preserve Windows datagram error semantics in tests --- libs/asio | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/asio b/libs/asio index 059f64c4..70e6f5f2 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 059f64c4c6aa316e351b10aca1f31ca810b446e6 +Subproject commit 70e6f5f2839e1ab0535ffea1e5da5a10a185178a From 52c1120778b28402c9b6fdf77f1def72eae6cbd3 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 13:59:28 -0500 Subject: [PATCH 21/32] tools/drive: Preserve executables and contain Windows processes --- .github/workflows/library.yml | 4 + AGENTS.md | 5 +- CODING-GUIDELINES.md | 13 ++ doc/releases/0.1.0.adoc | 2 + .../plans/2026-11-03-asio-beast-closure.md | 14 +- libs/asio | 2 +- tools/component/process_tree.py | 143 +++++++++++++ tools/component/serve.py | 59 +----- tools/component/serve_test.py | 3 +- tools/drive/drive.jam | 23 +- tools/drive/drive.py | 42 ++-- tools/drive/drive_test.py | 200 ++++++++++++++++-- tools/test/openssl_test.py | 117 ++++++++++ 13 files changed, 525 insertions(+), 102 deletions(-) create mode 100644 tools/component/process_tree.py diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 3df50c07..04a2fefe 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -225,6 +225,10 @@ jobs: - *superproject-for-library - *make-room - *library + - name: Verify Windows driven-test process cleanup + if: runner.os == 'Windows' + timeout-minutes: 5 + run: python tools/drive/drive_test.py - *transport-sources - *boost diff --git a/AGENTS.md b/AGENTS.md index 49dfcd31..a61f1903 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1139,7 +1139,7 @@ webcpp.drive : + : * :