From c41196569b22bd1b0ca80baf4945cd657be15f3f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 7 Nov 2026 09:00:36 -0300 Subject: [PATCH 1/9] network: distribute portable Asio Cobalt and Beast backends --- .clang-format | 5 + .gitmodules | 3 + AGENTS.md | 107 +- CODING-GUIDELINES.md | 92 +- Jamroot | 23 +- doc/releases/0.1.0.adoc | 5 +- .../2026-11-06-portable-network-libraries.md | 165 ++ .../2026-11-06-portable-network-libraries.md | 129 ++ libs/asio | 2 +- libs/beast | 2 +- libs/cobalt | 1 + tools/boost/Jamfile | 100 +- tools/boost/asio-wasip2/Jamfile | 31 - .../boost/asio/detail/wasi_resolver.hpp | 381 ---- tools/boost/asio-wasip2/pollable.cpp | 77 - 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 | 76 - tools/boost/asio-wasip3/README.md | 115 +- tools/boost/asio-wasip3/boost-1.92.patch | 1528 ----------------- .../boost/asio/detail/wasi_p3_resolver.hpp | 368 ---- .../boost/asio/detail/wasi_waitable.hpp | 31 - tools/boost/asio-wasip3/manifest.json | 81 - tools/boost/asio-wasip3/prepare.py | 89 - tools/boost/asio-wasip3/prepare_test.py | 77 - 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/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/Jamfile | 34 - tools/boost/cobalt-common/boost-1.92.patch | 67 - tools/boost/cobalt-common/manifest.json | 17 - tools/boost/cobalt-ssl/Jamfile | 52 - tools/boost/cobalt-ssl/boost-1.92.patch | 187 -- tools/boost/cobalt-ssl/manifest.json | 13 - tools/boost/cobalt-ssl/ssl.cpp | 8 - tools/boost/cobalt-wasip3/Jamfile | 47 - tools/boost/cobalt-wasip3/acceptor.cpp | 10 - tools/boost/cobalt-wasip3/boost-1.92.patch | 225 --- tools/boost/cobalt-wasip3/endpoint.cpp | 10 - tools/boost/cobalt-wasip3/manifest.json | 45 - tools/boost/cobalt-wasip3/prepare.py | 94 - tools/boost/cobalt-wasip3/prepare_test.py | 85 - tools/ci/container/Dockerfile | 2 +- tools/doc/doc_comments.py | 7 +- tools/doc/docinfo.html | 6 + tools/doc/reference.py | 13 +- tools/lint/compile_commands.py | 57 +- tools/lint/lint.sh | 44 +- tools/lint/lint_test.py | 165 +- .../include/webcpp/test/asyncify_watch.hpp | 108 ++ .../include/webcpp/test/browser_values.hpp | 115 ++ .../include/webcpp/test/page_timeout.hpp | 88 + tools/openssl/test/Jamfile | 18 +- tools/openssl/test/cobalt_ssl_cancel.cpp | 319 ---- tools/openssl/test/cobalt_ssl_client.cpp | 170 -- tools/openssl/test/cobalt_ssl_state.cpp | 195 --- tools/openssl/test/cobalt_tls_client.cpp | 94 - tools/openssl/test/driver.py | 15 + tools/shipped_sources.py | 169 ++ tools/shipped_sources_test.py | 206 +++ tools/test/asio_sdk_abi_test.py | 48 + tools/test/asio_wasip3_test.py | 61 +- tools/test/boost_libraries_test.py | 230 +-- tools/test/cobalt_config_test.py | 110 ++ tools/test/cobalt_ownership_test.py | 86 + tools/test/cobalt_ssl_test.py | 45 +- tools/test/cobalt_wasip3_test.py | 45 +- .../test/fixtures/native_network_identity.cpp | 40 + .../test/fixtures/native_network_runtime.cpp | 53 + .../fixtures/portable-network/CMakeLists.txt | 220 +++ tools/test/harness.py | 33 + tools/test/native_network_identity.py | 60 + tools/test/openssl_test.py | 12 +- tools/test/portable_network_distribution.py | 476 +++++ .../portable_network_distribution_test.py | 182 ++ 92 files changed, 2920 insertions(+), 6837 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-06-portable-network-libraries.md create mode 100644 docs/superpowers/specs/2026-11-06-portable-network-libraries.md create mode 160000 libs/cobalt delete mode 100644 tools/boost/asio-wasip2/Jamfile delete mode 100644 tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp delete mode 100644 tools/boost/asio-wasip2/pollable.cpp delete mode 100644 tools/boost/asio-wasip2/verify.py delete mode 100644 tools/boost/asio-wasip2/verify_test.py delete mode 100644 tools/boost/asio-wasip2/wasi-libc/LICENSE delete mode 100644 tools/boost/asio-wasip2/wasi-libc/LICENSE-APACHE delete mode 100644 tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT delete mode 100644 tools/boost/asio-wasip2/wasi-libc/manifest.json delete mode 100644 tools/boost/asio-wasip2/wasi-libc/wasi/descriptor_table.h delete mode 100644 tools/boost/asio-wasip2/wasi-libc/wasi/poll.h delete mode 100644 tools/boost/asio-wasip3/Jamfile delete mode 100644 tools/boost/asio-wasip3/boost-1.92.patch delete mode 100644 tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp delete mode 100644 tools/boost/asio-wasip3/include/boost/asio/detail/wasi_waitable.hpp delete mode 100644 tools/boost/asio-wasip3/manifest.json delete mode 100644 tools/boost/asio-wasip3/prepare.py delete mode 100644 tools/boost/asio-wasip3/prepare_test.py delete mode 100644 tools/boost/asio-wasip3/verify.py delete mode 100644 tools/boost/asio-wasip3/verify_test.py delete mode 100644 tools/boost/asio-wasip3/waitable.cpp delete mode 100644 tools/boost/asio-wasip3/wasi-libc/LICENSE delete mode 100644 tools/boost/asio-wasip3/wasi-libc/LICENSE-APACHE delete mode 100644 tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT delete mode 100644 tools/boost/asio-wasip3/wasi-libc/manifest.json delete mode 100644 tools/boost/asio-wasip3/wasi-libc/wasi/descriptor_table.h delete mode 100644 tools/boost/asio-wasip3/wasi-libc/wasi/lock.h delete mode 100644 tools/boost/asio-wasip3/wasi-libc/wasi/poll.h delete mode 100644 tools/boost/asio-windows/Jamfile delete mode 100644 tools/boost/asio-windows/README.md delete mode 100644 tools/boost/asio-windows/boost-1.92.patch delete mode 100644 tools/boost/asio-windows/manifest.json delete mode 100644 tools/boost/cobalt-common/Jamfile delete mode 100644 tools/boost/cobalt-common/boost-1.92.patch delete mode 100644 tools/boost/cobalt-common/manifest.json delete mode 100644 tools/boost/cobalt-ssl/Jamfile delete mode 100644 tools/boost/cobalt-ssl/boost-1.92.patch delete mode 100644 tools/boost/cobalt-ssl/manifest.json delete mode 100644 tools/boost/cobalt-ssl/ssl.cpp delete mode 100644 tools/boost/cobalt-wasip3/Jamfile delete mode 100644 tools/boost/cobalt-wasip3/acceptor.cpp delete mode 100644 tools/boost/cobalt-wasip3/boost-1.92.patch delete mode 100644 tools/boost/cobalt-wasip3/endpoint.cpp delete mode 100644 tools/boost/cobalt-wasip3/manifest.json delete mode 100644 tools/boost/cobalt-wasip3/prepare.py delete mode 100644 tools/boost/cobalt-wasip3/prepare_test.py create mode 100644 tools/node-test/include/webcpp/test/asyncify_watch.hpp create mode 100644 tools/node-test/include/webcpp/test/browser_values.hpp create mode 100644 tools/node-test/include/webcpp/test/page_timeout.hpp delete mode 100644 tools/openssl/test/cobalt_ssl_cancel.cpp delete mode 100644 tools/openssl/test/cobalt_ssl_client.cpp delete mode 100644 tools/openssl/test/cobalt_ssl_state.cpp delete mode 100644 tools/openssl/test/cobalt_tls_client.cpp create mode 100644 tools/openssl/test/driver.py create mode 100644 tools/shipped_sources.py create mode 100644 tools/shipped_sources_test.py create mode 100644 tools/test/asio_sdk_abi_test.py create mode 100644 tools/test/cobalt_config_test.py create mode 100644 tools/test/cobalt_ownership_test.py create mode 100644 tools/test/fixtures/native_network_identity.cpp create mode 100644 tools/test/fixtures/native_network_runtime.cpp create mode 100644 tools/test/fixtures/portable-network/CMakeLists.txt create mode 100644 tools/test/native_network_identity.py create mode 100644 tools/test/portable_network_distribution.py create mode 100644 tools/test/portable_network_distribution_test.py diff --git a/.clang-format b/.clang-format index a8e68c6c..b47b29cf 100644 --- a/.clang-format +++ b/.clang-format @@ -29,3 +29,8 @@ EmptyLineBeforeAccessModifier: LogicalBlock # by its columns: clang-format neither splits such a line at the column limit # nor joins it with the next. The first alternative is clang-format's default. CommentPragmas: '^ IWYU pragma:|^ *\|' + +# These macros accept a header-name token, not an arithmetic expression. +WhitespaceSensitiveMacros: + - WEBCPP_ASIO_BACKEND_HEADER + - WEBCPP_BEAST_BACKEND_HEADER diff --git a/.gitmodules b/.gitmodules index 23e77683..3762d051 100644 --- a/.gitmodules +++ b/.gitmodules @@ -46,3 +46,6 @@ [submodule "third_party/libs/libdatachannel"] path = third_party/libs/libdatachannel url = https://github.com/paullouisageneau/libdatachannel.git +[submodule "libs/cobalt"] + path = libs/cobalt + url = ../cobalt.git diff --git a/AGENTS.md b/AGENTS.md index 11d6457e..68b76971 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,8 +73,9 @@ 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, WASIp2/P3 networking and optional source-built TLS | native, emscripten, wasip2, wasip3 | a submodule at `libs/asio`; see its feature matrix for variants | +| asio | Boost.Asio 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 | +| cobalt | Boost.Cobalt coroutine applications with shipped Wasm adaptations and optional corrected SSL | native, emscripten, wasip2, wasip3, by capability | a submodule at `libs/cobalt`; see its feature and application matrices for variants | | 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) | @@ -343,55 +344,39 @@ being on the compiler's default include path, naming the `using boost` line to add, and if it lacks the library's sources; a build that needs none never looks. -**Cobalt source target.** `/webcpp//boost_cobalt` builds a static library from -24 of Boost 1.92's 26 Cobalt sources on native/browser targets: `src/*.cpp`, -`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 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 -builds. Cooperative builds include and test the thread coroutine. Installed -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 -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 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 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 -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 shipped sources.** `libs/cobalt/sources.json` declares the core, +runner, optional SSL and additional threaded sources per target. The independent +library owns them. `/webcpp//boost_cobalt` aliases its plain core; +`/webcpp/cobalt//cobalt` supplies exactly one runner for a user-defined `co_main`. +The older Asio Cobalt targets are compatibility aliases. Native core and runner +sources are unchanged Boost 1.92. Wasm implementations are shipped under explicit +WebCPP paths; consumers never run an importer or prepare replacement Boost headers. +Cobalt does not require an external `BOOST_SOURCE` tree. Boost.URL, Charconv, +Locale and Context retain the source requirements above. + +Compile the application, core, runner and optional SSL with matching exception, +thread and Cobalt executor/PMR settings. A custom configuration header is +preincluded in every source. Native sources use Boost's configuration vocabulary; +Wasm maps those settings to its isolated implementation. Its generated B2 source +list and external compiler/CMake recipes consume the same inventory. Asio has +its own runtime inventory and private WASI SDK ABI checks under `libs/asio/src`. +The consumer test creates and extracts a source archive, validates hashes and +compiler dependencies, and rejects accidental checkout inputs. + +`/webcpp/cobalt//io_ssl` selects WebCPP's corrected wrapper for native and WASI, +with the shared source-built OpenSSL/CA provider. This is the owner-approved +exception to native Boost identity. `/webcpp/cobalt//cobalt_ssl` adds the runner. +Plain Cobalt does not link OpenSSL. Browser HTTPS/WSS uses the browser's TLS. +State, transfer cancellation and shutdown drivers live in `libs/cobalt/test/tls`. +Asio's existing integration aliases preserve their callers. Native upstream +OpenSSL tests remain distinct from WebCPP TLS witnesses and from WASI tests. + +**Native upstream limitations.** Native Cobalt retains Boost's composition, +accept, write-at and missing-no-exceptions-promise-hook limitations, documented +by its probes. Those core paths do not receive Wasm corrections. Native Asio +retains Boost's Windows IOCP worker/timer allocation limitation. Historical patch +inputs survive in `libs/asio/upstream/reference/windows-iocp`, without a consumer +build rule. A dry run on this machine is not Windows runtime evidence. **Cobalt without exceptions.** A build that uses `/webcpp//boost_cobalt` with `exception-handling=off` emits a non-fatal configuration warning with @@ -638,6 +623,28 @@ Comment becomes `@see ""`. ## 3. Documentation +### Shipped Boost implementation provenance + +Asio, Cobalt and Beast ship their Wasm implementation explicitly under their own +paths. Native Cobalt core/runner sources remain unchanged upstream snapshots; +the owner approved the separately corrected native SSL wrapper on 2026-11-06. +No consumer build applies a patch or shadows an installed Boost include tree. + +`upstream/generated.json` identifies maintainer-generated implementation and +forwarding files by hash. `tools/shipped_sources.py` verifies every entry before +lint preserves its upstream style or the reference omits inherited declarations. +A missing, changed or escaping path fails this integrity gate. The importer, +correction inputs and hand-written wrappers/adapters remain subject to all owned +source rules. Regeneration uses the pinned input and correction manifests. + +The owned-header aggregate and MrDocs input document WebCPP's additions and +configuration; guides link the matching upstream reference for inherited APIs. +The input list excludes only verified generated outputs. This does not disable +MrDocs warnings or permit a library-specific arbitrary reference filter. Actual +consumer/application tests still compile the imported implementation. Generated +forwarders additionally require distribution/header coverage for their supported +profiles; omitting them from the documentation aggregate is not test evidence. + ### The page Each library has one AsciiDoc page, `doc/<name>.adoc`, with its sections in diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 67ed411e..2c574463 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -1186,11 +1186,12 @@ 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 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' - version must equal the configured Boost's. + configuration. Cobalt's independent library now ships its pinned upstream + native sources and adapted Wasm sources; Asio ships its Wasm backend too. + Maintainer imports record original and resulting hashes, while consumer + builds apply no patches. Other compiled Boost dependencies still require the + matching source archive: an installed Boost cannot be relied on for sources + (Homebrew's has no `libs/url/src`). Source: `organization/openspec/changes/archive/2026-10-07-genesis/design.md` (proposals). - **Boost.JSON's definitions and Boost.Test's header-only framework are @@ -6181,7 +6182,38 @@ 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 WASIp2/P3; implemented for 0.1.0 in preparation) +### asio (Boost.Asio on native, Emscripten and WASIp2/P3; implemented for 0.1.0 in preparation) + + +**Owner-approved architecture update, 2026-11-06.** The coordinated Asio, +Cobalt and Beast migration supersedes the earlier derived-native-context and +consumer overlay choices in the historical design inventory below. Native +upstream-equivalent public types are the actual Boost types. Wasm implementations +are shipped under explicit WebCPP paths, selected by config, and shared by B2 +and independent compiler/CMake consumers. Cobalt owns its compiled sources; +Asio's old Cobalt targets are compatibility aliases. Native Cobalt SSL alone uses +the separately corrected WebCPP type after reproduced state/cancellation defects +and explicit owner approval. The core and runner remain unchanged upstream. + +Distribution closure uses `sources.json` in Asio and Cobalt, with B2 lists +generated from the same inventories. Direct compiler and CMake consumers build +from an extracted, hashed source archive. Compiler dependencies must name only +that archive, explicit dependencies or the selected toolchain's declared paths. +Custom executor/PMR settings apply to every source; incompatible per-translation- +unit flags are not repaired by a general ABI guard. The consumer audit checks +the requested configuration instead. Consumer overlay recipes and the lint's +overlay preparation hook have been removed. Historical patch inputs remain only +for maintainer provenance and upstream comparison. + +Verified maintainer-generated imports preserve upstream provenance and style; +owned adapters and generators remain linted. The shared integrity gate checks +all generated hashes before any documentation or lint classification. Guides +explain WebCPP additions and link the pinned upstream reference. The migration +plan and its local evidence, not the historical inventory below, determine +current closure. Dated application matrices and Release measurements passed locally +on 2026-11-07. Local lint and review are complete; coordinated remote CI and +publication remain separate gates. + 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 @@ -6867,6 +6899,33 @@ 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. +### cobalt (Boost.Cobalt source integration; local candidate for 0.1.0) + +The owner approved independent Cobalt ownership and the coordinated source contract +on 2026-11-06. `libs/cobalt` owns core, runner, optional SSL, tests, examples and +Diataxis/MrDocs documentation. Native coroutine/plain I/O types and core/runner +sources are Boost 1.92. Wasm uses checked-in sources over the same WebCPP Asio +backend as Beast. Consumer builds require no patches or replacement Boost headers. + +The corrected native SSL stream is an explicit owner-approved identity exception, +after real upstream state/cancellation failures. Plain Cobalt never links SSL. +Native upstream defects outside that wrapper remain named negative probes; +corrected Wasm behavior is not reported as native Boost behavior. The issue-287 +no-EH caution remains informational, with versioned runtime evidence. + +Default browser scheduling stays at Asio's 100 handlers. Config distinguishes +application requirements, read-only capabilities and build-wide executor/PMR +policies. A capability cannot grant runtime permissions. Arbitrary cross-unit ABI +mismatches remain caller errors; source consumers must rebuild all support units. +B2 lists and external builds consume the same source inventories. + +The 2026-11-07 report covers 12 original applications in 432 cells, keeping +counterparts, unavailable facilities and upstream defects separate. Shared Release +measurements cover 136 builds and 15,906 runtime observations, with immutable source +snapshots and distinct memory boundaries. The full source-archive, lint, review and +publication gates are recorded in the portable-network migration plan. Local +results do not claim a released library, GitHub repository creation or CI approval. + ### beast (Boost.Beast portability facade) The owner's expanded Beast genesis proposal in @@ -6882,11 +6941,14 @@ 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 +- Native and WASIp2/P3 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. + remain explicit. Native equivalent types are exactly Boost.Beast types. + Wasm protocol sources are shipped explicitly and use Asio's selected backend, + without replacement Boost include directories. WASI stream internals retain + upstream Beast's allocation behavior; browser allocator extensions do not + change the native type or constructor contract. - 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 @@ -6925,9 +6987,11 @@ facilities separately; a successful compile never proves runtime parity. - 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 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. + WASIp3 exceptions remain unavailable in SDK 34, never counted as passes. + The 2026-11-07 application matrix includes WASIp2 guest sockets: across + 53 applications and 35 profiles it records 843 passed, 816 unavailable and + 196 blocked cells. Dated results identify their exact measured source + snapshot; subsequent edits do not silently replace that evidence. - 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; @@ -8713,7 +8777,7 @@ compatibility departure belongs with its rationale in chapter 15. Chapter 15 now records the implemented configuration, allocator and private-header corrections, native/Emscripten/WASIp2/P3 target contract, default turn limit 100, -Diataxis guide, source-built OpenSSL, checked Boost overlays and recurring thread +Diataxis guide, source-built OpenSSL, shipped Wasm backends 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. @@ -8736,7 +8800,7 @@ adopted. Chapter 5 rule 7's existing exact-archive exception stays in force. 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 +- **Upstream corrections 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 diff --git a/Jamroot b/Jamroot index ebcde7f4..384b7ffd 100644 --- a/Jamroot +++ b/Jamroot @@ -419,20 +419,29 @@ rule boost-source-usable ( properties * ) } } +# Independent compiled integrations use the same source/version validation. +alias boost-source-check : : <conditional>@boost-source-usable ; +explicit boost-source-check ; + # Boost's compiled libraries, built from those sources (tools/boost/Jamfile). use-project /webcpp/boost-libraries : tools/boost ; -# Boost.URL, Boost.Charconv, Boost.Locale and Boost.Cobalt, compiled: a library -# that needs one puts <library>/webcpp//boost_url, boost_charconv, boost_locale -# or boost_cobalt in its main target's usage requirements, as one that needs -# 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 boost_context +# Boost.URL, Boost.Charconv, Boost.Locale and Boost.Context, compiled: a library +# that needs one puts its /webcpp//boost_* alias in its usage requirements, +# as one that needs Boost.JSON does with boost_json. Each alias checks sources +# before building. CODING-GUIDELINES.md chapter 10 lists Boost.Locale's targets. +for local name in boost_url boost_charconv boost_locale boost_context { alias $(name) : tools/boost//$(name) : <conditional>@boost-source-usable ; } +# Cobalt owns shipped sources and needs matching Boost headers, not an external +# Boost source checkout. Legacy aliases retain the same dependency contract. +for local name in boost_cobalt boost_cobalt_io_ssl +{ + alias $(name) : tools/boost//$(name) ; +} + # What every test and example of a library links (tools/webcpp.jam): the # header webcpp/test/exit_status.hpp on every target, and on emscripten the # pre-js that fails a test under node whose main did not finish, and stops diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 2b06cc15..8da39b24 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -10,12 +10,15 @@ [#webcpp-0-1-0-new-libraries] == New Libraries -* link:{library-pages}asio/{library-page}[asio]: Boost.Asio and Cobalt with +* link:{library-pages}asio/{library-page}[asio]: Boost.Asio with 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, browser WebSocket and fetch, WASI host HTTP and supplied byte streams, from R. +* link:{library-pages}cobalt/{library-page}[cobalt]: Boost.Cobalt coroutine +applications for native, browser and WASI targets, with explicit source distribution +and optional corrected SSL integration, 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. diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md new file mode 100644 index 00000000..0f732dae --- /dev/null +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -0,0 +1,165 @@ +# Portable Network Libraries Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship Asio, Cobalt and Beast with native Boost identity and explicit, build-system-independent WebAssembly adaptations. + +**Architecture:** Native facades forward to Boost. Wasm implementations are shipped under explicit library-owned paths and selected through config, with one coherent Asio backend for all three libraries. B2 and external consumers compile those same files without applying patches. + +**Tech Stack:** C++20, Boost 1.92, Emscripten 6.0.11, WASI SDK 34, Wasmtime 50.0.1, B2, CMake, Python, AsciiDoc and MrDocs. + +**Spec:** `docs/superpowers/specs/2026-11-06-portable-network-libraries.md`. + +## Global Constraints + +- Work in the existing isolated checkout, preserving the unfinished Cobalt extraction. +- No remote CI, push, merge or publication during local implementation. On + 2026-11-07 the owner authorized remaining-work item 6: coordinated commits, + publication, remote CI and integration after successful verification. +- Native upstream-equivalent types are actual Boost types; extensions are documented separately. The owner explicitly approved a corrected native Cobalt SSL wrapper after its upstream failures were reproduced. +- No consumer-time patches or replacement Boost include-tree precedence. +- Keep one Asio backend and one optional OpenSSL/CA provider per program. +- Preserve the browser scheduling default of 100 and all existing benchmark dimensions. +- Preserve immutable upstream examples; counterpart and runtime identities remain separate. +- All written artifacts use English, BSL/provenance notices and no em dash. + +## Review Focus + +- Header include order must not silently select a different backend (task 2). +- Compiled sources and consumers must agree on EH/thread/backend configuration (task 3). +- Native custom executors and traits must retain Boost identity (tasks 1 and 3). +- An unpacked distribution must not resolve hidden checkout/cache paths (task 5). +- An unavailable host facility must not become a fake successful example (tasks 4 and 6). + +### Task 1: Native facade identity + +**Files:** `tools/test/native_network_identity_test.py`, +`tools/test/fixtures/native_network_identity.cpp`, +`libs/asio/include/webcpp/asio/io_context.hpp`, `libs/asio/test/names_test.cpp`, +`libs/beast/include/webcpp/beast/websocket.hpp`, +`libs/cobalt/include/webcpp/cobalt.hpp` and corresponding configuration/docs. + +**Interfaces:** Consume existing public headers plus installed Boost. Produce a +direct-compiler consumer whose context, timer, sockets, task/promise/generator and +WebSocket types are identical to Boost, with timer and HTTP behavior checked. + +- [x] Write the real consumer and bounded driver; compile without B2/overlays. +- [x] Observe failures for the derived Asio context, missing Cobalt facade and Beast stream identity. +- [x] Add native forwarding, preserving existing Wasm implementations. Scope browser option tests to the browser API. +- [x] Run direct native consumer with both include orders and EH on/off, then relevant B2 regressions. +- [x] Commit explicit files and record that compiled Cobalt/source selection remains task 3. + +### Task 2: Shipped Asio backend + +**Files:** `libs/asio/include/webcpp/asio/config.hpp`, public facade headers, +new `libs/asio/include/webcpp/asio/detail/backend/`, +new `libs/asio/upstream/` synchronization manifest/tool, `libs/asio/src/`, +`libs/asio/build.jam`, `tools/boost/asio-{wasip2,wasip3,windows}/`, +new `libs/asio/test/distribution/` consumers. + +**Interfaces:** Public `<webcpp/asio/...>` includes select native Boost or the +shipped Wasm implementation. Explicit source inventory identifies browser, P2 +pollable and P3 waitable units and SDK contracts. + +- [x] Add failing clean-distribution timer/TCP/UDP/DNS consumers for P2/P3 and browser timer/Promise consumers. +- [x] Import the pinned source and incorporate verified corrections with maintained provenance, namespace/guard isolation and explicit includes. +- [x] Move owned SDK adapters beside the library; keep deterministic SDK/version diagnostics and explicit configuration inputs. +- [x] Make B2 compile the shipped files; remove native Windows hidden patch selection and record the upstream limitation with its regression. +- [x] Run include-order/custom-token/multi-TU cases and existing network/cancel/thread tests; trace dependencies to reject overlay paths. +- [x] Commit the independently validated Asio distribution and its test evidence. + +### Task 3: Native and Wasm Cobalt source selection + +**Files:** `libs/cobalt/include/webcpp/cobalt/`, `libs/cobalt/src/`, +`libs/cobalt/build-support/`, `libs/cobalt/build.jam`, +`libs/cobalt/upstream/`, `libs/cobalt/test/`, old compatibility aliases. + +**Interfaces:** Native public types and compiled core/runner use matching upstream +Boost. Wasm uses shipped Cobalt adaptations over task 2's backend; core, runner and +SSL stay separate targets. + +- [x] Add source/link witnesses rejecting local native corrections and consumer-time patching; add executor/token/custom-main/entry-point runtime cases. +- [x] Import the adapted Wasm implementation and facade headers, retaining licenses and correction provenance. +- [x] Select unmodified native core sources and the native runner; keep known upstream regressions separate from Wasm corrections and issue-287 diagnostics. +- [x] Deliver the explicitly approved corrected native SSL wrapper as a separate type/source and rerun the native TLS state/cancel suite. +- [x] Run all current Cobalt operation/application/browser/TLS tests on their actual applicable profiles, including flags-mismatch and mixed-alias checks. +- [x] Commit coordinated Cobalt ownership/aliases and update the genesis plan/status without promoting historical results. + +### Task 4: Beast backend audit + +**Files:** `libs/beast/include/webcpp/beast/`, `libs/beast/build.jam`, +`libs/beast/test/`, application generators and matrices; shared WASI binding recipes. + +**Interfaces:** Existing message/browser/host/socket/TLS entry points consume the +same selected Asio backend; native types remain upstream identities. + +- [x] Add clean consumer HTTP/WebSocket/socket/browser/host-HTTP checks and native type/trait interoperability cases. +- [x] Adapt only the dependency boundaries that need it, preserving existing browser and host implementations; ship any required protocol-engine adaptation explicitly. +- [x] Run real peer, TLS state/cancel and supplied-stream regressions; reclassify unsupported original applications honestly. +- [x] Commit the reviewed Beast changes with exact profile evidence. + +### Task 5: External build and source archive + +**Files:** Per-library source/dependency inventories, new +`tools/test/portable_network_distribution_test.py` and an out-of-tree CMake consumer, +installation/archive metadata and per-library build-recipe documentation. + +**Interfaces:** One declared source/configuration contract consumed by B2, a direct +compiler invocation and a CMake consumer. No second project release pipeline. + +- [x] Build a source archive fixture without `.git`, `.local`, `bin` or B2 and prove current hidden dependencies fail. +- [x] Export explicit source/flags/dependency inputs and WIT generation requirements. +- [x] Run native and feasible Wasm consumers using explicit toolchain paths, inspect commands/dependencies and verify one runner/TLS provider. +- [x] Commit installation and consumer recipes only after the unpacked fixture passes. + +Local consumer verification completed on 2026-11-06. Evidence is in the matching +SDD ledger under "Remaining-work item 1". Coordinated commits and publication +remain in the later closure phase; this does not close the full migration. + +### Task 6: Examples, benchmarks and documentation + +**Files:** Asio/Cobalt/Beast application inventories, benchmark generators/data, +`doc/*.adoc`, MrDocs configuration, `AGENTS.md`, organization guidance and proposals. + +**Interfaces:** Retain the existing Cobalt genesis tasks as obligations. Fresh +source/runtime hashes bind all new support and measurement claims to this migration. + +- [ ] Run every original application/profile or a named versioned negative probe; keep browser/host counterparts separate. +- [x] Repeat optimized size, compile/startup/performance/yield/memory measurements under the established methodology. +- [x] Apply webcpp-documentation: purpose, differences from Boost, config options/defaults, targets versus suspension modes, matrices and compiled examples. +- [x] Render/check docs and run relevant local build, lint and proposal checks; repair real failures. +- [x] Obtain a fresh whole-candidate review, address findings and record remaining environmental restrictions. Publication/CI remains a separate gate. + +Remaining-work items 2/3 were completed locally on 2026-11-07. The dated library +reports retain the current application matrices, all 136 Release builds, 2,176 +payload checks, 15,906 runtime observations and 442 yield cases. Asio application +coverage is its nine maintained guide programs, not the full Boost.Asio corpus. +The focused measurement review and three strict documentation builds passed; +they do not replace this plan's later whole-candidate closure gates. See the SDD +ledger for exact evidence, boundary diagnostics and retained SDK constraints. + +Remaining-work items 4 and 5 are complete locally on 2026-11-07. Documentation, +tooling/proposal checks and the fresh whole-candidate review passed. The complete +lint covered 831 translation units and 1,528 commands; its two final style findings +were corrected and their exact checks passed again. The original failed run and +successful follow-ups remain separately recorded in `closure-lint-reconciled.json`. +The review has no unresolved findings. See `closure-items-4-5.md` in the SDD ledger. +The coordinated commits now record those reviewed changes. The broad original-application box +also remains open: Asio's dated matrix covers its nine guide programs, not every +original Boost.Asio example. This coverage boundary is explicit in the guides. + + +### Remaining-work item 6: coordinated publication + +On 2026-11-07 the owner authorized coordinated publication and remote CI. Library +commits are Asio `e7cf267b4ab43437a09ce68f40a3994ca63b9054`, Cobalt +`36b9f2475aab1171e0898ab87d5b9630a8e04d71`, and Beast +`6c53f854070a4eebd844f21c29692e938181f8f6`. Cobalt has its public repository and +is registered as a submodule. These commits preserve the checked source and +measurement bytes; Git attributes retain imported/generated whitespace and CSV +line endings. The superproject records all three revisions together. + +Remote CI is pending. The changed container recipe must first produce verified +immutable environment pins. The complete superproject CI validates the combined +candidate before integration; library workflows use the superproject's main and +must be rerun after its integration. No release or proposal archival is implied. diff --git a/docs/superpowers/specs/2026-11-06-portable-network-libraries.md b/docs/superpowers/specs/2026-11-06-portable-network-libraries.md new file mode 100644 index 00000000..4955237a --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-portable-network-libraries.md @@ -0,0 +1,129 @@ +# Portable Asio, Cobalt and Beast distribution + +## Owner direction and scope + +On 2026-11-06 the owner requested Asio first, coordinated Cobalt delivery, and a +Beast audit under the same consumption contract. Native applications must use the +corresponding Boost implementations. WebAssembly selects explicit adaptations +through each library's configuration and target-specific headers. Consumer builds +must not patch an installed Boost or manufacture replacement headers behind B2. +The public entry points are `webcpp::asio`, `webcpp::cobalt` and `webcpp::beast`. + +This supersedes the Cobalt genesis decision that keeping all upstream include paths +and namespaces was more important than portable distribution. The existing genesis +application, browser, benchmark and documentation obligations remain in scope. +Earlier green results identify the previous implementation and must be rerun after +the migration. No remote CI, publication or merge is part of local implementation. + +## Native contract + +The supported upstream-equivalent public types are aliases to the actual Boost +types, not subclasses that merely behave similarly. Identity is checked with +`std::is_same_v`, including Asio contexts, timers, sockets and executors, Cobalt +coroutine types/tokens and Beast HTTP/WebSocket types. Explicit WebCPP additions, +such as trust-policy helpers, remain separately documented extensions. + +Native Cobalt uses the upstream compiled core and upstream entry-point behavior. +It must not silently receive local coroutine or I/O corrections through an include +overlay. Known upstream failures remain independently reproduced and documented; +correcting them upstream is distinct from claiming a patched library is native +Boost. The current Windows IOCP correction requires the same treatment. + +Owner-approved exception on 2026-11-06: retain WebCPP's corrected Cobalt SSL +wrapper on native targets too. The unmodified upstream wrapper reproduced state, +shutdown and post-cancellation write failures. `webcpp::cobalt::io::ssl::stream` +therefore has its own type and implementation, while the core coroutine types, +executor and plain I/O types remain Boost. Its headers and compiled source must +ship explicitly and coexist with the unmodified `boost::cobalt::io::ssl` type. +This exception does not authorize patching installed Boost or changing the native +core/runner. TLS state, transfer, errors and cancellation require fresh native and +WASI runtime evidence. + +The current Asio `io_context_options` and turn-control methods are browser +extensions. Native code uses Boost's constructors and members. Code that needs a +browser-only option uses an explicit target conditional. WASI behavior is specified +independently; preserving its existing wrapper initially does not establish native +identity or final packaging completion. + +## WebAssembly contract + +Targets are Emscripten, WASIp2 and WASIp3. JSPI and Asyncify are Emscripten suspension +variants, not WASI versions. Thread mode, exception mode, compiler/SDK and actual +runtime remain separate matrix dimensions. Config derives target capabilities from +the compiler and backend; a caller cannot forge support by defining a capability. +Compiler and linker requirements still have to agree with header configuration. + +Adapted implementation files are shipped as ordinary, versioned library sources. +Source synchronization may use an audited maintainer generator, but a consumer +must not need to run that generator, Git, or a patch program. Each derived file has +an upstream revision, license, original hash and resulting hash. The initial +upstream baseline remains Boost 1.92.0. + +Wasm implementation includes use explicit library-owned paths. They must not rely +on placing a replacement `boost/asio` or `boost/cobalt` directory before installed +Boost. Internal namespaces and include guards must prevent accidental mixing of +upstream and adapted implementations. Public algorithms continue to use the +appropriate Asio executor, cancellation and completion-token traits. The precise +private source transformation is an implementation decision gated by include-order, +multi-translation-unit and custom-token conformance tests. + +The three libraries must select one consistent Asio backend. A native Beast or +Cobalt template must not accidentally instantiate against an incompatible Wasm +executor family. Preserve the existing browser scheduler, default 100 callbacks, +worker ownership and cleanup. Plain Asio must not depend on Cobalt or optional TLS. +Optional guest TLS continues to use one shared OpenSSL/CA provider. + +## Build-system boundary + +B2 remains the project's primary development, testing, documentation and release +tool. It consumes the same shipped sources that an external build consumes. +Generated WIT bindings, platform source units, compiler/link flags, exports and +optional provider dependencies are explicit build requirements. Generation of WIT +bindings is a normal toolchain step, not permission to rewrite Boost headers. + +Provide a documented consumer recipe and machine-readable source/configuration +inventory. Prove consumption with direct compiler commands and an out-of-tree +CMake consumer. Do not maintain a second release or CI pipeline. Both consumers +must work from an unpacked source distribution with no `.git`, `bin/`, `.local/`, +B2 installation or existing overlay. Dependencies/toolchains may be supplied at +explicit paths; the test must not silently read developer-specific caches. + +Native and Wasm builds of the same source can have different type identities and +ABIs. Native interoperability with Boost must be proved, not extrapolated into +cross-backend binary interoperability. Specialization and customization points +must have a documented, tested migration path. + +## Examples, evidence and documentation + +Retain every original example and its exact identity. Run feasible originals on +native, real browsers and Wasmtime. An environment lacking a facility cannot be +advertised as running the unchanged example. A browser fetch/WebSocket counterpart, +WASI host-HTTP counterpart, or supplied-stream counterpart has a separate identity, +states its semantic differences and remains a real C++ program. + +Preserve and extend the existing Release size, compile-time, startup, throughput, +yield/responsiveness and memory methodology. Record source/artifact hashes, actual +flags, runtimes, sample counts and unavailable measurements. Prior measurements +remain historical until reproduced for the new implementation. + +Each library's Diataxis AsciiDoc guide leads with its purpose: making existing +Boost-style C++ applications easy to compile for WebAssembly. State what is new +relative to Boost, the native forwarding contract, every public configuration +option and its default/scope, build recipes, feature/application matrix and +versioned limitations. MrDocs describes WebCPP additions and public adaptations; +link the corresponding pinned Boost reference instead of duplicating prose +unnecessarily. Examples in documentation come from compiled sources. + +## Acceptance and sequencing + +1. Establish direct native-consumer identity and runtime witnesses first. +2. Package the Asio Wasm backend and its SDK support, without consumer patching. +3. Package Cobalt against that backend and restore upstream native source selection. +4. Audit and adapt Beast against the same dependency contract. +5. Run every feasible declared application/profile, refresh measurements and docs. +6. Verify source-distribution consumption, local checks and an independent review. + +No stage alone completes the three-library migration. Do not remove the old Wasm +build path until its replacement has equivalent user-facing evidence. Native +identity checks do not certify the current Cobalt archive or Windows recipe: those +have their own source-selection gates. diff --git a/libs/asio b/libs/asio index db4f7fc6..e7cf267b 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit db4f7fc6afc516fdef057614cc971cdc39484099 +Subproject commit e7cf267b4ab43437a09ce68f40a3994ca63b9054 diff --git a/libs/beast b/libs/beast index 31af6915..6c53f854 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 31af69150d61776e7699cb89125f79d103e11ac8 +Subproject commit 6c53f854070a4eebd844f21c29692e938181f8f6 diff --git a/libs/cobalt b/libs/cobalt new file mode 160000 index 00000000..36b9f247 --- /dev/null +++ b/libs/cobalt @@ -0,0 +1 @@ +Subproject commit 36b9f2475aab1171e0898ab87d5b9630a8e04d71 diff --git a/tools/boost/Jamfile b/tools/boost/Jamfile index 4b41172d..3a433c1c 100644 --- a/tools/boost/Jamfile +++ b/tools/boost/Jamfile @@ -9,7 +9,8 @@ # program's own features, exception-handling=off among them, reach them. The # sources are the Jamroot's WEBCPP_BOOST_SOURCE, whose version the Jamroot's # alias of each library checks before anything is built: /webcpp//boost_url, -# /webcpp//boost_charconv, /webcpp//boost_locale and /webcpp//boost_cobalt. +# /webcpp//boost_charconv, /webcpp//boost_locale and /webcpp//boost_context. +# Cobalt's legacy names forward to its independent shipped-source library. # They are Boost's code, # not webcpp's, and compile without webcpp's warnings, as Boost's headers are # read as system ones. @@ -21,12 +22,6 @@ 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 ; - project /webcpp/boost-libraries : source-location $(WEBCPP_BOOST_SOURCE) : requirements <warnings>off <warnings-as-errors>off @@ -265,90 +260,7 @@ compiled boost_locale : $(.locale) # Boost.Cobalt without its default co_main runner (main.cpp), which webcpp # supplies separately, and io/ssl.cpp, which needs OpenSSL. -rule cobalt-sources ( ) -{ - local sources ; - for local file in [ glob libs/cobalt/src/*.cpp libs/cobalt/src/detail/*.cpp - libs/cobalt/src/io/*.cpp ] - { - if ! [ MATCH "(^|/)(main|ssl|endpoint|acceptor|thread|signal_set|serial_port|seq_packet_socket)[.]cpp$" : $(file) ] - { - sources += $(file) ; - } - } - return $(sources) ; -} - -# This diagnostic is a configuration warning, not a compiler warning: even -# warnings-as-errors=on must preserve the consumer's choice. Cache the -# base configuration so several consumers of one archive do not repeat it. -# b2 evaluates conditionals before and after applying library requirements; -# ignore link and warning features, which this library fixes independently. -rule cobalt-configuration ( properties * ) -{ - if <exception-handling>off in $(properties) - { - local settings = [ property-set.create $(properties) ] ; - local base = [ $(settings).base ] ; - base = [ set.difference $(base) : <link>shared <link>static - <warnings>all <warnings>extra <warnings>off - <warnings-as-errors>on <warnings-as-errors>off ] ; - local key = $(base:J=|) ; - if ! $(.cobalt-warned.$(key)) - { - .cobalt-warned.$(key) = true ; - ECHO "warning: webcpp: Boost.Cobalt is built with exceptions disabled;" - "moving a pending task can abort at runtime with libc++." - "Use exception-handling=on." - "See https://github.com/boostorg/cobalt/issues/287" ; - } - } -} - -.cobalt-platform-sources = [ glob libs/cobalt/src/thread.cpp - libs/cobalt/src/io/endpoint.cpp libs/cobalt/src/io/acceptor.cpp - libs/cobalt/src/io/signal_set.cpp libs/cobalt/src/io/serial_port.cpp - libs/cobalt/src/io/seq_packet_socket.cpp ] ; - -rule cobalt-platform-sources ( properties * ) -{ - if [ webcpp-target.target-of $(properties) ] in wasip2 wasip3 - { - local threaded ; - if <threading>multi in $(properties) - { - threaded = <source>libs/cobalt/src/thread.cpp ; - } - return <source>/webcpp/cobalt-wasip3//endpoint - <source>/webcpp/cobalt-wasip3//acceptor - <library>/webcpp/cobalt-wasip3//headers $(threaded) ; - } - return <source>$(.cobalt-platform-sources) ; -} - -# 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 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 ] - : libs/cobalt/src holds no .cpp file - : <define>BOOST_COBALT_SOURCE=1 <define>BOOST_COBALT_IO_SOURCE=1 - <library>/webcpp/cobalt-common//headers - <target-os>windows:<library>/webcpp/asio-windows//headers - <toolset>emscripten,<threading>single:<define>BOOST_ASIO_DISABLE_THREADS - <conditional>@cobalt-configuration - <conditional>@cobalt-platform-sources - : <define>BOOST_COBALT_NO_LIB=1 - <library>/webcpp/cobalt-common//headers - <target-os>windows:<library>/webcpp/asio-windows//headers - <toolset>clang-wasip2:<library>/webcpp/cobalt-wasip3//headers - <toolset>clang-wasip3:<library>/webcpp/cobalt-wasip3//headers - <toolset>emscripten,<threading>single:<define>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 ; -explicit boost_cobalt_io_ssl ; +# Cobalt-specific sources and checked corrections belong to libs/cobalt. +alias boost_cobalt : /webcpp/cobalt//core ; +alias boost_cobalt_io_ssl : /webcpp/cobalt//io_ssl ; +explicit boost_cobalt boost_cobalt_io_ssl ; diff --git a/tools/boost/asio-wasip2/Jamfile b/tools/boost/asio-wasip2/Jamfile deleted file mode 100644 index 117204aa..00000000 --- a/tools/boost/asio-wasip2/Jamfile +++ /dev/null @@ -1,31 +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) -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 - : <location>$(OUTPUT) <webcpp-boost-check>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 - : <include>../../../libs/asio/include <include>wasi-libc - <dependency>verified.stamp <library>/webcpp/config//config ; -explicit pollable ; - -# Private resolver extension selected only with the P2 platform overlay. -alias headers : : : : <include>include <library>/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 deleted file mode 100644 index 85b3af2a..00000000 --- a/tools/boost/asio-wasip2/include/boost/asio/detail/wasi_resolver.hpp +++ /dev/null @@ -1,381 +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) -#ifndef WEBCPP_ASIO_DETAIL_WASI_RESOLVER_HPP -#define WEBCPP_ASIO_DETAIL_WASI_RESOLVER_HPP -#if defined(__wasip2__) - -#include <unistd.h> -#include <wasi/wasip2.h> -#include <boost/asio/associated_allocator.hpp> -#include <boost/asio/associated_cancellation_slot.hpp> -#include <boost/asio/detail/bind_handler.hpp> -#include <boost/asio/detail/handler_alloc_helpers.hpp> -#include <boost/asio/detail/handler_work.hpp> -#include <boost/asio/detail/select_reactor.hpp> -#include <boost/asio/detail/socket_ops.hpp> -#include <boost/asio/ip/address.hpp> -#include <boost/asio/ip/basic_resolver_query.hpp> -#include <boost/asio/ip/basic_resolver_results.hpp> -#include <boost/asio/ip/detail/endpoint.hpp> -#include <cstring> -#include <memory> -#include <string> -#include <vector> -#include <webcpp/asio/detail/wasi_pollable_descriptor.hpp> - -// 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<void>& impl, execution_context& context) { - impl = std::allocate_shared<wasi_resolver_state>( - execution_context::allocator<wasi_resolver_state>(context)); -} - -inline void wasi_resolver_cancel(std::shared_ptr<void>& impl) { - if (impl) - static_cast<wasi_resolver_state*>(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 Protocol, class Handler, class IoExecutor> -class wasi_resolve_op : public reactor_op, public wasi_resolver_node { - using query_type = boost::asio::ip::basic_resolver_query<Protocol>; - using results_type = boost::asio::ip::basic_resolver_results<Protocol>; - using endpoint_type = typename Protocol::endpoint; - using allocator_type = associated_allocator_t<Handler>; - using char_allocator = - typename std::allocator_traits<allocator_type>::template rebind_alloc<char>; - using endpoint_allocator = - typename std::allocator_traits<allocator_type>::template rebind_alloc<endpoint_type>; - using string_type = std::basic_string<char, std::char_traits<char>, char_allocator>; - using slot_type = associated_cancellation_slot_t<Handler>; - - select_reactor& reactor_; - select_reactor::per_descriptor_data reactor_data_{}; - string_type host_; - string_type service_; - addrinfo_type hints_; - std::vector<endpoint_type, endpoint_allocator> endpoints_; - Handler handler_; - handler_work<Handler, IoExecutor> 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<endpoint_type, endpoint_allocator>& 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<const sockaddr_in*>(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<const sockaddr_in*>(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 network = instance_network_instance_network(); - wasip2_string_t name{reinterpret_cast<uint8_t*>(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<select_reactor>(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&&>(handler)), - work_(handler_, executor), - slot_(get_associated_cancellation_slot(handler_)) { - reactor_.init_task(); - if (slot_.is_connected()) - slot_.template emplace<slot_cancel>(this); - owner = &state; - next = state.head; - state.head = this; - cancel = [](wasi_resolver_node* node) { - static_cast<wasi_resolve_op*>(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<wasi_resolve_op*>(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.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}; - ip::address_v6::bytes_type bytes{}; - for (std::size_t i = 0; i != 8; ++i) { - bytes[2 * i] = static_cast<unsigned char>(words[i] >> 8); - bytes[2 * i + 1] = static_cast<unsigned char>(words[i]); - } - self.append_endpoint(ip::detail::endpoint(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<wasi_resolve_op*>(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<Handler, IoExecutor> work( - static_cast<handler_work<Handler, IoExecutor>&&>(self->work_)); - binder2<Handler, boost::system::error_code, results_type> 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 <class Protocol, class Handler, class IoExecutor> -void wasi_async_resolve(std::shared_ptr<void>& impl, execution_context& context, - typename boost::asio::ip::basic_resolver_query<Protocol> const& query, - Handler& handler, IoExecutor const& executor) { - if (!impl) - wasi_resolver_construct(impl, context); - using op = wasi_resolve_op<Protocol, Handler, IoExecutor>; - typename op::ptr memory = {std::addressof(handler), op::ptr::allocate(handler), nullptr}; - memory.p = new (memory.v) - op(*static_cast<wasi_resolver_state*>(impl.get()), context, query, handler, executor); - boost::asio::use_service<select_reactor>(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 deleted file mode 100644 index 3915319c..00000000 --- a/tools/boost/asio-wasip2/pollable.cpp +++ /dev/null @@ -1,77 +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) - -#include <wasi/wasip2.h> -#include <cerrno> -#include <cstddef> -#include <new> -#include <string_view> -#include <webcpp/asio/detail/wasi_pollable_descriptor.hpp> - -// 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<descriptor_storage*>(value); - descriptor->owner->active = false; - descriptor->~descriptor_storage(); -} - -int register_poll(void* value, poll_state_t* state, short events) { - if ((static_cast<unsigned>(events) & ~static_cast<unsigned>(POLLRDNORM)) != 0) { - errno = EOPNOTSUPP; - return -1; - } - return __wasilibc_poll_add( - state, POLLRDNORM, - poll_borrow_pollable_t{static_cast<descriptor_storage*>(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<descriptor_vtable_t*>(&operations)}); -} diff --git a/tools/boost/asio-wasip2/verify.py b/tools/boost/asio-wasip2/verify.py deleted file mode 100644 index ad325278..00000000 --- a/tools/boost/asio-wasip2/verify.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) 2026 WebCpp.org -# -# Distributed under the Boost Software License, Version 1.0. (See -# accompanying file LICENSE_1_0.txt or copy at -# https://www.boost.org/LICENSE_1_0.txt) -"""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 deleted file mode 100644 index c1b54c70..00000000 --- a/tools/boost/asio-wasip2/verify_test.py +++ /dev/null @@ -1,48 +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) -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 deleted file mode 100644 index d3e73789..00000000 --- a/tools/boost/asio-wasip2/wasi-libc/LICENSE +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 16fe87b0..00000000 --- a/tools/boost/asio-wasip2/wasi-libc/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - 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 deleted file mode 100644 index 31aa7938..00000000 --- a/tools/boost/asio-wasip2/wasi-libc/LICENSE-MIT +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 732e7eed..00000000 --- a/tools/boost/asio-wasip2/wasi-libc/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "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 deleted file mode 100644 index b06b8e6d..00000000 --- a/tools/boost/asio-wasip2/wasi-libc/wasi/descriptor_table.h +++ /dev/null @@ -1,368 +0,0 @@ -#ifndef DESCRIPTOR_TABLE_H -#define DESCRIPTOR_TABLE_H - -#include <wasi/api.h> - -#ifndef __wasip1__ -#include <assert.h> -#include <netinet/in.h> -#include <stdlib.h> -#include <string.h> -#include <sys/stat.h> -#include <wasi/poll.h> - -#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<u8>`. -/// -/// 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<u8>`. -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<u8>`. -/// -/// 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 deleted file mode 100644 index 39ac8f89..00000000 --- a/tools/boost/asio-wasip2/wasi-libc/wasi/poll.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef WASI_POLL_H -#define WASI_POLL_H - -#include <wasi/version.h> - -#ifndef __wasip1__ - -#include <poll.h> -#include <wasi/api.h> - -/// 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 deleted file mode 100644 index 64f61f80..00000000 --- a/tools/boost/asio-wasip3/Jamfile +++ /dev/null @@ -1,76 +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) - -import errors ; -import feature ; -import make ; -import modules ; -import path ; -import webcpp-wasi ; -import webcpp-target ; - -project /webcpp/asio-wasip3 ; -path-constant BUNDLE : . ; -path-constant OVERLAY : ../../../bin/boost-asio-wasip3 ; - -make prepared.stamp : prepare.py manifest.json boost-1.92.patch : @prepare - : <location>$(OVERLAY) <webcpp-boost-check>off ; -always prepared.stamp ; -explicit prepared.stamp ; - -rule prepare ( targets * : sources * : properties * ) -{ - SCRIPT on $(targets) = $(BUNDLE)/prepare.py ; - HEADERS on $(targets) = $(WEBCPP_BOOST_HEADERS) ; - OUTPUT on $(targets) = $(OVERLAY)/include ; -} - -actions prepare -{ - python3 "$(SCRIPT)" --boost "$(HEADERS)" --output "$(OUTPUT)" --stamp "$(<)" -} - -rule configuration ( properties * ) -{ - if [ webcpp-target.target-of $(properties) ] = wasip2 && <threading>multi in $(properties) - { - errors.user-error "webcpp::asio: WASIp2 supports threading=single only; use WASIp3 for the cooperative thread profile." ; - } - if <threading>single in $(properties) - { - return <define>BOOST_ASIO_DISABLE_THREADS ; - } - return [ webcpp-wasi.cooperative $(WEBCPP_ROOT) : $(properties) ] ; -} - -alias headers : : : : <dependency>prepared.stamp - <toolset>clang-wasip3:<source>waitable <include>include - <cxxflags>"-I\"$(OVERLAY)/include\"" - <conditional>@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 : : : : <dependency>prepared.stamp - <cxxflags>"-I\"$(OVERLAY)/include\"" - <define>BOOST_ASIO_DISABLE_THREADS ; -explicit host-headers ; - -make verified.stamp : verify.py wasi-libc/manifest.json : @verify - : <location>$(OVERLAY) <webcpp-boost-check>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>include <include>wasi-libc <dependency>verified.stamp ; -explicit waitable ; diff --git a/tools/boost/asio-wasip3/README.md b/tools/boost/asio-wasip3/README.md index 3562a5f7..b2e2e9f6 100644 --- a/tools/boost/asio-wasip3/README.md +++ b/tools/boost/asio-wasip3/README.md @@ -1,110 +1,17 @@ -# Boost.Asio WASI compatibility patch +# WASI test launchers -This bundle adapts Boost.Asio 1.92.0's platform layer, keeping its scheduler, -select reactor, operation objects and associated allocators. The source headers -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. +`run.sh` grants the local networking capabilities required by the WASIp3 tests, +enables the component-model async/threading features, and enforces a finite +runtime bound. `../asio-wasip2/run.sh` supplies the corresponding P2 launcher. +These are test launchers, not consumer build adapters or deployment policies. -`/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 -refuses to apply to a different Boost version or a locally modified input. -Stale extra files or symlinks in the private overlay stop preparation; clean that -private directory and rebuild after changing the set of patched headers. -Only patched headers are copied; other headers continue to come from Boost. +The Asio implementation, SDK ABI declarations, verifier and runtime sources ship +under `libs/asio`. Its `sources.json` inventory selects the required sources. +There is no consumer header overlay and no `prepared.stamp` target here. -`/webcpp/asio-wasip3//host-headers` exposes association and completion-token -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. +Run launcher and ABI checks locally with: -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 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. -The async operation owns the copy and frees it before invoking the handler. -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 -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. 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. - -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/verify_test.py +```sh 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 -b2 -a toolset=clang-wasip3 variant=release threading=multi exception-handling=off \ - testing.launcher=tools/boost/asio-wasip3/run.sh \ - libs/asio/test libs/asio/test//wasi_core_threads libs/asio/example +python3 tools/test/asio_sdk_abi_test.py ``` - -For a new Boost baseline, review the upstream changes, regenerate the unified -patch and input/output hashes from clean and modified source headers, and repeat -the single-thread, cooperative-thread and native controls. Never relax the hash -check to apply a patch approximately. The feature and build-profile contract is -in `libs/asio/doc/capabilities.adoc`; build instructions are in `doc/wasip3.adoc` -within that library. No CI is started by the commands above. diff --git a/tools/boost/asio-wasip3/boost-1.92.patch b/tools/boost/asio-wasip3/boost-1.92.patch deleted file mode 100644 index 92b08fdb..00000000 --- a/tools/boost/asio-wasip3/boost-1.92.patch +++ /dev/null @@ -1,1528 +0,0 @@ ---- a/boost/asio/detail/buffer_sequence_adapter.hpp -+++ b/boost/asio/detail/buffer_sequence_adapter.hpp -@@ -179,11 +179,16 @@ - void init(Iterator begin, Iterator end) - { - Iterator iter = begin; -- for (; iter != end && count_ < max_buffers; ++iter, ++count_) -+ for (; iter != end && count_ < max_buffers; ++iter) - { - Buffer buffer(*iter); -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ if (buffer.size() == 0) -+ continue; -+#endif - init_native_buffer(buffers_[count_], buffer); - total_buffer_size_ += buffer.size(); -+ ++count_; - } - } - -@@ -191,8 +196,12 @@ - static bool all_empty(Iterator begin, Iterator end) - { - Iterator iter = begin; -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ for (; iter != end; ++iter) -+#else - std::size_t i = 0; - for (; iter != end && i < max_buffers; ++iter, ++i) -+#endif - if (Buffer(*iter).size() > 0) - return false; - return true; ---- a/boost/asio/detail/config.hpp -+++ b/boost/asio/detail/config.hpp -@@ -31,6 +31,26 @@ - # include <boost/version.hpp> - # define BOOST_ASIO_HAS_BOOST_CONFIG 1 - #endif // defined(BOOST_ASIO_STANDALONE) -+ -+// WASIp2/P3 supply sockets (P3 also cooperative threads), but no process signals, -+// interface enumeration, Unix domain sockets or serial devices. -+#if (defined(__wasip2__) || defined(__wasip3__)) -+# if !defined(_REENTRANT) && !defined(BOOST_ASIO_DISABLE_THREADS) -+# define BOOST_ASIO_DISABLE_THREADS 1 -+# endif -+# if !defined(BOOST_ASIO_DISABLE_SIGNAL) -+# define BOOST_ASIO_DISABLE_SIGNAL 1 -+# endif -+# if !defined(BOOST_ASIO_DISABLE_SIGACTION) -+# define BOOST_ASIO_DISABLE_SIGACTION 1 -+# endif -+# if !defined(BOOST_ASIO_DISABLE_LOCAL_SOCKETS) -+# define BOOST_ASIO_DISABLE_LOCAL_SOCKETS 1 -+# endif -+# if !defined(BOOST_ASIO_DISABLE_SERIAL_PORT) -+# define BOOST_ASIO_DISABLE_SERIAL_PORT 1 -+# endif -+#endif - - // Default to a header-only implementation. The user must specifically request - // separate compilation by defining either BOOST_ASIO_SEPARATE_COMPILATION or -@@ -1531,7 +1551,7 @@ - #endif // !defined(BOOST_ASIO_DEPRECATED_MSG) - - // Kernel support for MSG_NOSIGNAL. --#if !defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#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,12 @@ - # include <boost/asio/detail/socket_types.hpp> - #else - # include <unistd.h> -+# if defined(__wasip2__) || defined(__wasip3__) -+# include <poll.h> -+# endif -+# if defined(__wasip2__) -+# include <wasi/wasip2.h> -+# endif - # if defined(__hpux) - # include <sys/time.h> - # endif -@@ -45,7 +51,18 @@ - #elif defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) - ::Sleep(INFINITE); - #else -+#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 - ::pause(); -+#endif - #endif - } - ---- a/boost/asio/detail/impl/resolver_thread_pool.ipp -+++ b/boost/asio/detail/impl/resolver_thread_pool.ipp -@@ -56,10 +56,12 @@ - shutdown_(false) - { - work_scheduler_.work_started(); -+#if !(defined(__wasip2__) || defined(__wasip3__)) || defined(BOOST_ASIO_HAS_THREADS) - if (num_work_threads_ > 0) - start_work_threads(); - else - num_work_threads_ = 1; -+#endif - } - - resolver_thread_pool::~resolver_thread_pool() -@@ -97,6 +99,7 @@ - - void resolver_thread_pool::start_resolve_op(resolve_op* op) - { -+#if !(defined(__wasip2__) || defined(__wasip3__)) || defined(BOOST_ASIO_HAS_THREADS) - if (scheduler_locking_) - { - start_work_threads(); -@@ -104,6 +107,7 @@ - work_scheduler_.post_immediate_completion(op, false); - } - else -+#endif - { - op->ec_ = boost::asio::error::operation_not_supported; - scheduler_.post_immediate_completion(op, false); ---- a/boost/asio/detail/impl/socket_ops.ipp -+++ b/boost/asio/detail/impl/socket_ops.ipp -@@ -315,7 +315,7 @@ - opt.l_linger = 0; - boost::system::error_code ignored_ec; - socket_ops::setsockopt(s, state, SOL_SOCKET, -- SO_LINGER, &opt, sizeof(opt), ignored_ec); -+ BOOST_ASIO_OS_DEF(SO_LINGER), &opt, sizeof(opt), ignored_ec); - } - - #if defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -@@ -680,7 +680,8 @@ - int socketpair(int af, int type, int protocol, - socket_type sv[2], boost::system::error_code& ec) - { --#if defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -+#if defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) \ -+ || (defined(__wasip2__) || defined(__wasip3__)) - (void)(af); - (void)(type); - (void)(protocol); -@@ -702,7 +703,10 @@ - return false; - } - --#if defined(SIOCATMARK) -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ ec = boost::asio::error::operation_not_supported; -+ int value = 0; -+#elif defined(SIOCATMARK) - ioctl_arg_type value = 0; - # if defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) - int result = ::ioctlsocket(s, SIOCATMARK, &value); -@@ -818,6 +822,78 @@ - { - name = static_cast<T>(const_cast<void*>(addr)); - } -+ -+#if !defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -+#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) -+{ -+ data = 0; -+ size = 0; -+ bool multiple = false; -+ for (size_t i = 0; i < static_cast<size_t>(msg->msg_iovlen); ++i) -+ { -+ if (!msg->msg_iov[i].iov_len) -+ continue; -+ if (size) -+ multiple = true; -+ else -+ { -+ data = msg->msg_iov[i].iov_base; -+ size = msg->msg_iov[i].iov_len; -+ } -+ } -+ if (multiple) -+ { -+ int type = 0; -+ socklen_t length = sizeof(type); -+ if (::getsockopt(s, SOL_SOCKET, SO_TYPE, &type, &length) < 0) -+ return false; -+ if (type != SOCK_STREAM) -+ { -+ errno = EOPNOTSUPP; -+ return false; -+ } -+ } -+ return true; -+} -+ -+inline signed_size_type wasi_recvmsg(int s, msghdr* msg, int flags) -+{ -+ void* data; -+ size_t size; -+ if (!wasi_buffer(msg, data, size, s)) -+ return -1; -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ char empty_buffer = 0; -+ if (!data && !size) -+ data = &empty_buffer; -+#endif -+ socklen_t length = msg->msg_namelen; -+ signed_size_type result = ::recvfrom(s, data, size, flags, -+ static_cast<sockaddr*>(msg->msg_name), msg->msg_name ? &length : 0); -+ msg->msg_namelen = length; -+ msg->msg_flags = 0; -+ return result; -+} -+ -+inline signed_size_type wasi_sendmsg(int s, const msghdr* msg, int flags) -+{ -+ void* data; -+ size_t size; -+ if (!wasi_buffer(msg, data, size, s)) -+ return -1; -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ char empty_buffer = 0; -+ if (!data && !size) -+ data = &empty_buffer; -+#endif -+ return ::sendto(s, data, size, flags, -+ static_cast<const sockaddr*>(msg->msg_name), msg->msg_namelen); -+} -+#endif -+#endif - - signed_size_type recv(socket_type s, buf* bufs, size_t count, - int flags, boost::system::error_code& ec) -@@ -844,7 +920,11 @@ - msghdr msg = msghdr(); - msg.msg_iov = bufs; - msg.msg_iovlen = static_cast<int>(count); -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ signed_size_type result = wasi_recvmsg(s, &msg, flags); -+#else - signed_size_type result = ::recvmsg(s, &msg, flags); -+#endif - get_last_error(ec, result < 0); - return result; - #endif // defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -@@ -874,6 +954,11 @@ - boost::asio::error::clear(ec); - return bytes_transferred; - #else // defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ char empty_buffer = 0; -+ if (!data && !size) -+ data = &empty_buffer; -+#endif - signed_size_type result = ::recv(s, static_cast<char*>(data), size, flags); - get_last_error(ec, result < 0); - return result; -@@ -1113,7 +1198,11 @@ - msg.msg_namelen = static_cast<int>(*addrlen); - msg.msg_iov = bufs; - msg.msg_iovlen = static_cast<int>(count); -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ signed_size_type result = wasi_recvmsg(s, &msg, flags); -+#else - signed_size_type result = ::recvmsg(s, &msg, flags); -+#endif - get_last_error(ec, result < 0); - *addrlen = msg.msg_namelen; - return result; -@@ -1124,6 +1213,11 @@ - 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(__wasip2__) || defined(__wasip3__)) -+ char empty_buffer = 0; -+ if (!data && !size) -+ data = &empty_buffer; -+#endif - SockLenType tmp_addrlen = addrlen ? (SockLenType)*addrlen : 0; - signed_size_type result = ::recvfrom(s, static_cast<char*>(data), size, - flags, static_cast<socket_addr_type*>(addr), addrlen ? &tmp_addrlen : 0); -@@ -1333,7 +1427,11 @@ - msghdr msg = msghdr(); - msg.msg_iov = bufs; - msg.msg_iovlen = static_cast<int>(count); -+#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); -+#endif - get_last_error(ec, result < 0); - if (result >= 0) - out_flags = msg.msg_flags; -@@ -1463,7 +1561,11 @@ - #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) - flags |= MSG_NOSIGNAL; - #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ signed_size_type result = wasi_sendmsg(s, &msg, flags); -+#else - signed_size_type result = ::sendmsg(s, &msg, flags); -+#endif - get_last_error(ec, result < 0); - return result; - #endif // defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -@@ -1494,6 +1596,11 @@ - #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) - flags |= MSG_NOSIGNAL; - #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ char empty_buffer = 0; -+ if (!data && !size) -+ data = &empty_buffer; -+#endif - signed_size_type result = ::send(s, - static_cast<const char*>(data), size, flags); - get_last_error(ec, result < 0); -@@ -1695,7 +1802,11 @@ - #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) - flags |= MSG_NOSIGNAL; - #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL) -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ signed_size_type result = wasi_sendmsg(s, &msg, flags); -+#else - signed_size_type result = ::sendmsg(s, &msg, flags); -+#endif - get_last_error(ec, result < 0); - return result; - #endif // defined(BOOST_ASIO_WINDOWS) || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -@@ -1706,6 +1817,11 @@ - socket_type s, const void* data, size_t size, int flags, - const void* addr, std::size_t addrlen) - { -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ char empty_buffer = 0; -+ if (!data && !size) -+ data = &empty_buffer; -+#endif - return ::sendto(s, static_cast<char*>(const_cast<void*>(data)), size, flags, - static_cast<const socket_addr_type*>(addr), (SockLenType)addrlen); - } -@@ -1943,6 +2059,14 @@ - return socket_error_retval; - } - -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ if (level == SOL_SOCKET && optname < 0) -+ { -+ ec = boost::asio::error::operation_not_supported; -+ return socket_error_retval; -+ } -+#endif -+ - if (level == custom_socket_option_level && optname == always_fail_option) - { - ec = boost::asio::error::invalid_argument; -@@ -1966,7 +2090,7 @@ - return 0; - } - -- if (level == SOL_SOCKET && optname == SO_LINGER) -+ if (level == SOL_SOCKET && optname == BOOST_ASIO_OS_DEF(SO_LINGER)) - state |= user_set_linger; - - #if defined(__BORLANDC__) -@@ -2030,6 +2154,14 @@ - ec = boost::asio::error::bad_descriptor; - return socket_error_retval; - } -+ -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ if (level == SOL_SOCKET && optname < 0) -+ { -+ ec = boost::asio::error::operation_not_supported; -+ return socket_error_retval; -+ } -+#endif - - if (level == custom_socket_option_level && optname == always_fail_option) - { -@@ -2592,6 +2724,9 @@ - if (result != 0 && af == BOOST_ASIO_OS_DEF(AF_INET6) && scope_id != 0) - { - using namespace std; // For strcat and sprintf. -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ char if_name[22] = "%"; -+#else - char if_name[(IF_NAMESIZE > 21 ? IF_NAMESIZE : 21) + 1] = "%"; - const in6_addr_type* ipv6_address = static_cast<const in6_addr_type*>(src); - bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe) -@@ -2600,6 +2735,7 @@ - && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02)); - if ((!is_link_local && !is_multicast_link_local) - || if_indextoname(static_cast<unsigned>(scope_id), if_name + 1) == 0) -+#endif - #if defined(BOOST_ASIO_HAS_SNPRINTF) - snprintf(if_name + 1, sizeof(if_name) - 1, "%lu", scope_id); - #elif defined(BOOST_ASIO_HAS_SECURE_RTL) -@@ -2854,6 +2990,27 @@ - *scope_id = 0; - if (if_name != 0) - { -+#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; -+ if (*digit == 0) -+ { -+ ec = boost::asio::error::invalid_argument; -+ return 0; -+ } -+ for (; *digit; ++digit) -+ { -+ if (*digit < '0' || *digit > '9' -+ || value > (0xFFFFFFFFUL - (*digit - '0')) / 10) -+ { -+ ec = boost::asio::error::invalid_argument; -+ return 0; -+ } -+ value = value * 10 + (*digit - '0'); -+ } -+ *scope_id = value; -+#else - in6_addr_type* ipv6_address = static_cast<in6_addr_type*>(dest); - bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe) - && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80)); -@@ -2863,6 +3020,7 @@ - *scope_id = if_nametoindex(if_name + 1); - if (*scope_id == 0) - *scope_id = atoi(if_name + 1); -+#endif - } - } - return result; ---- a/boost/asio/detail/null_signal_blocker.hpp -+++ b/boost/asio/detail/null_signal_blocker.hpp -@@ -21,7 +21,7 @@ - || defined(BOOST_ASIO_WINDOWS) \ - || defined(BOOST_ASIO_WINDOWS_RUNTIME) \ - || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) \ -- || defined(__SYMBIAN32__) -+ || defined(__SYMBIAN32__) || (defined(__wasip2__) || defined(__wasip3__)) - - #include <boost/asio/detail/noncopyable.hpp> - -@@ -68,6 +68,6 @@ - // || defined(BOOST_ASIO_WINDOWS) - // || defined(BOOST_ASIO_WINDOWS_RUNTIME) - // || defined(BOOST_ASIO_CYGWIN_W32_SOCKETS) -- // || defined(__SYMBIAN32__) -+ // || defined(__SYMBIAN32__) || (defined(__wasip2__) || defined(__wasip3__)) - - #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,131 @@ - #include <boost/asio/detail/reactor_op.hpp> - #include <boost/asio/detail/socket_ops.hpp> - -+#if (defined(__wasip2__) || defined(__wasip3__)) -+# include <boost/asio/associated_allocator.hpp> -+# include <boost/asio/detail/noncopyable.hpp> -+# include <algorithm> -+# include <memory> -+# include <vector> -+#endif -+ - #include <boost/asio/detail/push_options.hpp> - - namespace boost { - namespace asio { - BOOST_ASIO_INLINE_NAMESPACE_BEGIN - namespace detail { -+ -+#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 -+// adapter can truncate it. Only multiple nonempty buffers need a copy. -+// 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. -+template <typename Allocator> -+class wasi_datagram_buffer : private noncopyable -+{ -+public: -+ typedef typename std::allocator_traits<Allocator>::template -+ rebind_alloc<char> byte_allocator; -+ -+ template <typename ConstBufferSequence> -+ wasi_datagram_buffer(const ConstBufferSequence& 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::const_buffer current(*it); -+ // WASI's UDP interface may trap above 64 KiB. Check before adding -+ // lengths or allocating; the host still enforces its smaller IP limit. -+ if (current.size() > 65535 - total) -+ { -+ error_ = boost::asio::error::message_size; -+ return; -+ } -+ if (current.size()) -+ { -+ multiple = multiple || total != 0; -+ buffer_ = current; -+ total += current.size(); -+ } -+ } -+ if (multiple) -+ { -+ storage_.resize(total); -+ boost::asio::buffer_copy(boost::asio::buffer(storage_), buffers); -+ buffer_ = boost::asio::buffer(storage_); -+ } -+ } -+ -+ boost::asio::const_buffer buffer() const { return buffer_; } -+ boost::system::error_code error() const { return error_; } -+ -+private: -+ std::vector<char, byte_allocator> storage_; -+ 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 <typename Allocator> -+class wasi_datagram_receive_buffer : private noncopyable -+{ -+public: -+ typedef typename std::allocator_traits<Allocator>::template -+ rebind_alloc<char> byte_allocator; -+ -+ template <typename MutableBufferSequence> -+ 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 <typename MutableBufferSequence> -+ 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<char, byte_allocator> storage_; -+ boost::asio::mutable_buffer buffer_; -+}; -+#endif // (defined(__wasip2__) || defined(__wasip3__)) - - template <typename ConstBufferSequence, typename Endpoint> - class reactive_socket_sendto_op_base : public reactor_op -@@ -46,6 +165,9 @@ - buffers_(buffers), - destination_(endpoint), - flags_(flags) -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ , wasi_datagram_(false), wasi_invalid_(false) -+#endif - { - } - -@@ -59,6 +181,22 @@ - 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_sendto1(o->socket_, -+ o->wasi_buffer_.data(), o->wasi_buffer_.size(), o->flags_, -+ o->destination_.data(), o->destination_.size(), -+ o->ec_, o->bytes_transferred_) ? done : not_done; -+ } -+ else -+#endif - if (bufs_type::is_single_buffer) - { - result = socket_ops::non_blocking_sendto1(o->socket_, -@@ -87,6 +225,12 @@ - ConstBufferSequence buffers_; - Endpoint destination_; - 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 <typename ConstBufferSequence, typename Endpoint, -@@ -107,9 +251,20 @@ - : reactive_socket_sendto_op_base<ConstBufferSequence, Endpoint>( - success_ec, socket, buffers, endpoint, flags, - &reactive_socket_sendto_op::do_complete), -+#if (defined(__wasip2__) || defined(__wasip3__)) -+ wasi_storage_(buffers, boost::asio::get_associated_allocator(handler), -+ endpoint.protocol().type() == SOCK_DGRAM), -+#endif - handler_(static_cast<Handler&&>(handler)), - work_(handler_, io_ex) - { -+#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(); -+ if (this->wasi_invalid_) -+ this->ec_ = wasi_storage_.error(); -+#endif - } - - static void do_complete(void* owner, operation* base, -@@ -184,6 +339,11 @@ - } - - private: -+#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<associated_allocator_t<Handler>> wasi_storage_; -+#endif - Handler handler_; - handler_work<Handler, IoExecutor> work_; - }; ---- a/boost/asio/detail/reactive_socket_service.hpp -+++ b/boost/asio/detail/reactive_socket_service.hpp -@@ -240,6 +240,26 @@ - const endpoint_type& destination, 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; -+ } -+ // See wasi_datagram_buffer: libc lacks sendmsg, so send one gathered -+ // datagram with context-owned storage, never one datagram per buffer. -+ wasi_datagram_buffer<execution_context::allocator<char>> gathered( -+ buffers, execution_context::allocator<char>(this->context()), true); -+ if ((ec = gathered.error())) -+ return 0; -+ const boost::asio::const_buffer buffer = gathered.buffer(); -+ return socket_ops::sync_sendto1(impl.socket_, impl.state_, -+ buffer.data(), buffer.size(), flags, -+ destination.data(), destination.size(), ec); -+ } -+#endif - typedef buffer_sequence_adapter<boost::asio::const_buffer, - ConstBufferSequence> 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<execution_context::allocator<char>> storage( -+ buffers, execution_context::allocator<char>(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<boost::asio::mutable_buffer, - MutableBufferSequence> bufs_type; - ---- a/boost/asio/detail/signal_blocker.hpp -+++ b/boost/asio/detail/signal_blocker.hpp -@@ -19,7 +19,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(__wasip2__) || defined(__wasip3__)) - # include <boost/asio/detail/null_signal_blocker.hpp> - #elif defined(BOOST_ASIO_HAS_PTHREADS) - # include <boost/asio/detail/posix_signal_blocker.hpp> -@@ -34,7 +34,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(__wasip2__) || defined(__wasip3__)) - typedef null_signal_blocker signal_blocker; - #elif defined(BOOST_ASIO_HAS_PTHREADS) - typedef posix_signal_blocker signal_blocker; ---- a/boost/asio/detail/socket_types.hpp -+++ b/boost/asio/detail/socket_types.hpp -@@ -60,7 +60,7 @@ - # if (defined(__MACH__) && defined(__APPLE__)) \ - || defined(__FreeBSD__) || defined(__NetBSD__) \ - || defined(__OpenBSD__) || defined(__linux__) \ -- || defined(__EMSCRIPTEN__) -+ || defined(__EMSCRIPTEN__) || (defined(__wasip2__) || defined(__wasip3__)) - # include <poll.h> - # elif !defined(__SYMBIAN32__) - # include <sys/poll.h> -@@ -83,13 +83,17 @@ - # endif - # include <arpa/inet.h> - # include <netdb.h> --# include <net/if.h> -+# if !(defined(__wasip2__) || defined(__wasip3__)) -+# include <net/if.h> -+# endif - # include <limits.h> - # if defined(__sun) - # include <sys/filio.h> - # include <sys/sockio.h> - # endif --# include <signal.h> -+# if !(defined(__wasip2__) || defined(__wasip3__)) -+# include <signal.h> -+# endif - #endif - - #include <boost/asio/detail/push_options.hpp> -@@ -236,9 +240,17 @@ - # define BOOST_ASIO_OS_DEF_FIONBIO FIONBIO - # 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(__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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_MSG_DONTROUTE 0x20000000 -+# else -+# define BOOST_ASIO_DISABLE_MSG_DONTROUTE 1 -+# endif - # define BOOST_ASIO_OS_DEF_MSG_EOR 0 // Not supported on Windows. - # define BOOST_ASIO_OS_DEF_MSG_DONTWAIT 0 // Not supported on Windows. - # define BOOST_ASIO_OS_DEF_SHUT_RD SD_RECEIVE -@@ -246,16 +258,44 @@ - # define BOOST_ASIO_OS_DEF_SHUT_RDWR SD_BOTH - # define BOOST_ASIO_OS_DEF_SOMAXCONN SOMAXCONN - # define BOOST_ASIO_OS_DEF_SOL_SOCKET SOL_SOCKET --# 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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_BROADCAST (-1) -+# else -+# define BOOST_ASIO_DISABLE_SO_BROADCAST 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_DEBUG (-2) -+# else -+# define BOOST_ASIO_DISABLE_SO_DEBUG 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_DONTROUTE (-3) -+# else -+# define BOOST_ASIO_DISABLE_SO_DONTROUTE 1 -+# endif - # 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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_LINGER (-4) -+# else -+# define BOOST_ASIO_DISABLE_SO_LINGER 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_OOBINLINE (-5) -+# else -+# define BOOST_ASIO_DISABLE_SO_OOBINLINE 1 -+# endif - # define BOOST_ASIO_OS_DEF_SO_SNDBUF SO_SNDBUF - # 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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_SNDLOWAT (-6) -+# else -+# define BOOST_ASIO_DISABLE_SO_SNDLOWAT 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_RCVLOWAT (-7) -+# else -+# define BOOST_ASIO_DISABLE_SO_RCVLOWAT 1 -+# endif - # define BOOST_ASIO_OS_DEF_SO_REUSEADDR SO_REUSEADDR - # define BOOST_ASIO_OS_DEF_TCP_NODELAY TCP_NODELAY - # define BOOST_ASIO_OS_DEF_IP_MULTICAST_IF IP_MULTICAST_IF -@@ -308,7 +348,11 @@ - 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(__wasip2__) || defined(__wasip3__)) -+ INET6_ADDRSTRLEN + 1 + 10; // A decimal 32-bit numeric scope identifier. -+#else - INET6_ADDRSTRLEN + 1 + IF_NAMESIZE; -+#endif - #else // defined(INET6_ADDRSTRLEN) - BOOST_ASIO_INLINE_VARIABLE const int max_addr_v6_str_len = 256; - #endif // defined(INET6_ADDRSTRLEN) -@@ -357,10 +401,22 @@ - # define BOOST_ASIO_OS_DEF_FIONBIO FIONBIO - # 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(__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 --# define BOOST_ASIO_OS_DEF_MSG_EOR MSG_EOR -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_MSG_DONTROUTE 0x20000000 -+# else -+# define BOOST_ASIO_DISABLE_MSG_DONTROUTE 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_MSG_EOR 0x40000000 -+# else -+# define BOOST_ASIO_DISABLE_MSG_EOR 1 -+# endif - # if defined(__linux__) \ - || defined(__FreeBSD__) \ - || defined(__NetBSD__) \ -@@ -375,16 +431,44 @@ - # define BOOST_ASIO_OS_DEF_SHUT_RDWR SHUT_RDWR - # define BOOST_ASIO_OS_DEF_SOMAXCONN SOMAXCONN - # define BOOST_ASIO_OS_DEF_SOL_SOCKET SOL_SOCKET --# 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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_BROADCAST (-1) -+# else -+# define BOOST_ASIO_DISABLE_SO_BROADCAST 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_DEBUG (-2) -+# else -+# define BOOST_ASIO_DISABLE_SO_DEBUG 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_DONTROUTE (-3) -+# else -+# define BOOST_ASIO_DISABLE_SO_DONTROUTE 1 -+# endif - # 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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_LINGER (-4) -+# else -+# define BOOST_ASIO_DISABLE_SO_LINGER 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_OOBINLINE (-5) -+# else -+# define BOOST_ASIO_DISABLE_SO_OOBINLINE 1 -+# endif - # define BOOST_ASIO_OS_DEF_SO_SNDBUF SO_SNDBUF - # 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(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_SNDLOWAT (-6) -+# else -+# define BOOST_ASIO_DISABLE_SO_SNDLOWAT 1 -+# endif -+# if (defined(__wasip2__) || defined(__wasip3__)) -+# define BOOST_ASIO_OS_DEF_SO_RCVLOWAT (-7) -+# else -+# define BOOST_ASIO_DISABLE_SO_RCVLOWAT 1 -+# endif - # define BOOST_ASIO_OS_DEF_SO_REUSEADDR SO_REUSEADDR - # define BOOST_ASIO_OS_DEF_TCP_NODELAY TCP_NODELAY - # define BOOST_ASIO_OS_DEF_IP_MULTICAST_IF IP_MULTICAST_IF ---- a/boost/asio/error.hpp -+++ b/boost/asio/error.hpp -@@ -173,7 +173,12 @@ - operation_not_supported = BOOST_ASIO_SOCKET_ERROR(EOPNOTSUPP), - - /// Cannot send after transport endpoint shutdown. -+#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 - shut_down = BOOST_ASIO_SOCKET_ERROR(ESHUTDOWN), -+#endif - - /// 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 -@@ -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(); -+#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) -@@ -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. -+#if !defined(__wasip2__) - if (retval > 0 && fd_sets_[read_op].is_set(interrupter_.read_descriptor())) - { - if (!interrupter_.reset()) -@@ -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 @@ - - #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 <boost/asio/detail/socket_select_interrupter.hpp> - #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,14 @@ - #include <boost/asio/detail/resolve_endpoint_op.hpp> - #include <boost/asio/detail/resolve_query_op.hpp> - #include <boost/asio/detail/resolver_service_base.hpp> -+ -+#if defined(__wasip2__) || defined(__wasip3__) -+# if defined(__wasip3__) -+# include <boost/asio/detail/wasi_p3_resolver.hpp> -+# else -+# include <boost/asio/detail/wasi_resolver.hpp> -+# endif -+#endif - - #include <boost/asio/detail/push_options.hpp> - -@@ -64,6 +72,18 @@ - { - } - -+#if defined(__wasip2__) || defined(__wasip3__) -+ 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 +104,9 @@ - void async_resolve(implementation_type& impl, const query_type& qry, - Handler& handler, const IoExecutor& io_ex) - { -+#if defined(__wasip2__) || defined(__wasip3__) -+ wasi_async_resolve<Protocol>(impl, thread_pool_.context(), qry, handler, io_ex); -+#else - // Allocate and construct an operation to wrap the handler. - typedef resolve_query_op<Protocol, Handler, IoExecutor> op; - typename op::ptr p = { boost::asio::detail::addressof(handler), -@@ -95,6 +118,7 @@ - - thread_pool_.start_resolve_op(p.p); - p.v = p.p = 0; -+#endif - } - - // 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 <boost/asio/detail/config.hpp> -+#if defined(__wasip2__) || defined(__wasip3__) -+# include <boost/asio/detail/reactive_socket_sendto_op.hpp> -+#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<execution_context::allocator<char>> storage( -+ buffers, execution_context::allocator<char>(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<boost::asio::const_buffer, - ConstBufferSequence> 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<execution_context::allocator<char>> storage( -+ buffers, execution_context::allocator<char>(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<boost::asio::mutable_buffer, - MutableBufferSequence> 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 <boost/asio/detail/config.hpp> -+#if defined(__wasip2__) || defined(__wasip3__) -+# include <boost/asio/detail/reactive_socket_sendto_op.hpp> -+#endif - #include <boost/asio/detail/bind_handler.hpp> - #include <boost/asio/detail/buffer_sequence_adapter.hpp> - #include <boost/asio/detail/fenced_block.hpp> -@@ -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 <typename ConstBufferSequence, typename Handler, typename IoExecutor> -@@ -113,9 +141,20 @@ - Handler& handler, const IoExecutor& io_ex) - : reactive_socket_send_op_base<ConstBufferSequence>(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&&>(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<associated_allocator_t<Handler>> wasi_storage_; -+#endif - Handler handler_; - handler_work<Handler, IoExecutor> 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 <boost/asio/detail/config.hpp> -+#if defined(__wasip2__) || defined(__wasip3__) -+# include <boost/asio/detail/reactive_socket_sendto_op.hpp> -+#endif - #include <boost/asio/detail/bind_handler.hpp> - #include <boost/asio/detail/buffer_sequence_adapter.hpp> - #include <boost/asio/detail/fenced_block.hpp> -@@ -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 <typename MutableBufferSequence, typename Handler, typename IoExecutor> -@@ -130,9 +153,17 @@ - Handler& handler, const IoExecutor& io_ex) - : reactive_socket_recv_op_base<MutableBufferSequence>(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&&>(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, boost::system::error_code, std::size_t> - 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, boost::system::error_code, std::size_t> - 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<associated_allocator_t<Handler>> wasi_storage_; -+#endif - Handler handler_; - handler_work<Handler, IoExecutor> 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 <boost/asio/detail/config.hpp> -+#if defined(__wasip2__) || defined(__wasip3__) -+# include <boost/asio/detail/reactive_socket_sendto_op.hpp> -+#endif - #include <boost/asio/detail/bind_handler.hpp> - #include <boost/asio/detail/buffer_sequence_adapter.hpp> - #include <boost/asio/detail/fenced_block.hpp> -@@ -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 <typename MutableBufferSequence, typename Endpoint, -@@ -114,9 +138,17 @@ - : reactive_socket_recvfrom_op_base<MutableBufferSequence, Endpoint>( - 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&&>(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, boost::system::error_code, std::size_t> - 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, boost::system::error_code, std::size_t> - 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<associated_allocator_t<Handler>> wasi_storage_; -+#endif - Handler handler_; - handler_work<Handler, IoExecutor> 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<socket_type> 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<operation> 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 deleted file mode 100644 index 81f187ed..00000000 --- a/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_p3_resolver.hpp +++ /dev/null @@ -1,368 +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) -#ifndef WEBCPP_ASIO_DETAIL_WASI_P3_RESOLVER_HPP -#define WEBCPP_ASIO_DETAIL_WASI_P3_RESOLVER_HPP -#if defined(__wasip3__) - -#include <unistd.h> -#include <wasi/wasip3.h> -#include <boost/asio/associated_allocator.hpp> -#include <boost/asio/associated_cancellation_slot.hpp> -#include <boost/asio/detail/bind_handler.hpp> -#include <boost/asio/detail/handler_alloc_helpers.hpp> -#include <boost/asio/detail/handler_work.hpp> -#include <boost/asio/detail/select_reactor.hpp> -#include <boost/asio/detail/socket_ops.hpp> -#include <boost/asio/detail/wasi_waitable.hpp> -#include <boost/asio/ip/address.hpp> -#include <boost/asio/ip/basic_resolver_query.hpp> -#include <boost/asio/ip/basic_resolver_results.hpp> -#include <boost/asio/ip/detail/endpoint.hpp> -#include <cstring> -#include <memory> -#include <string> -#include <vector> - -// 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<void>& impl, execution_context& context) { - impl = std::allocate_shared<wasi_resolver_state>( - execution_context::allocator<wasi_resolver_state>(context)); -} - -inline void wasi_resolver_cancel(std::shared_ptr<void>& impl) { - if (impl) - static_cast<wasi_resolver_state*>(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 Protocol, class Handler, class IoExecutor> -class wasi_resolve_op : public reactor_op, public wasi_resolver_node { - using query_type = boost::asio::ip::basic_resolver_query<Protocol>; - using results_type = boost::asio::ip::basic_resolver_results<Protocol>; - using endpoint_type = typename Protocol::endpoint; - using allocator_type = associated_allocator_t<Handler>; - using char_allocator = - typename std::allocator_traits<allocator_type>::template rebind_alloc<char>; - using endpoint_allocator = - typename std::allocator_traits<allocator_type>::template rebind_alloc<endpoint_type>; - using string_type = std::basic_string<char, std::char_traits<char>, char_allocator>; - using slot_type = associated_cancellation_slot_t<Handler>; - - select_reactor& reactor_; - select_reactor::per_descriptor_data reactor_data_{}; - string_type host_; - string_type service_; - addrinfo_type hints_; - std::vector<endpoint_type, endpoint_allocator> endpoints_; - Handler handler_; - handler_work<Handler, IoExecutor> 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<endpoint_type, endpoint_allocator>& 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<const sockaddr_in*>(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<const sockaddr_in*>(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<select_reactor>(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&&>(handler)), - work_(handler_, executor), - slot_(get_associated_cancellation_slot(handler_)) { - reactor_.init_task(); - if (slot_.is_connected()) - slot_.template emplace<slot_cancel>(this); - owner = &state; - next = state.head; - state.head = this; - cancel = [](wasi_resolver_node* node) { - static_cast<wasi_resolve_op*>(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<wasi_resolve_op*>(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<unsigned char>(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<unsigned char>(words[i] >> 8); - bytes[2 * i + 1] = static_cast<unsigned char>(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<wasi_resolve_op*>(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<Handler, IoExecutor> work( - static_cast<handler_work<Handler, IoExecutor>&&>(self->work_)); - binder2<Handler, boost::system::error_code, results_type> 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 <class Protocol, class Handler, class IoExecutor> -void wasi_async_resolve(std::shared_ptr<void>& impl, execution_context& context, - typename boost::asio::ip::basic_resolver_query<Protocol> const& query, - Handler& handler, IoExecutor const& executor) { - if (!impl) - wasi_resolver_construct(impl, context); - using op = wasi_resolve_op<Protocol, Handler, IoExecutor>; - typename op::ptr memory = {std::addressof(handler), op::ptr::allocate(handler), nullptr}; - memory.p = new (memory.v) - op(*static_cast<wasi_resolver_state*>(impl.get()), context, query, handler, executor); - boost::asio::use_service<select_reactor>(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 deleted file mode 100644 index 10727d8a..00000000 --- a/tools/boost/asio-wasip3/include/boost/asio/detail/wasi_waitable.hpp +++ /dev/null @@ -1,31 +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) -#ifndef WEBCPP_ASIO_DETAIL_WASI_WAITABLE_HPP -#define WEBCPP_ASIO_DETAIL_WASI_WAITABLE_HPP -#include <wasi/wasip3.h> -#include <array> -#include <cstddef> -#include <cstdint> - -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<std::byte, 32> opaque{}; - wasip3_subtask_t handle = 0; - wasip3_subtask_state_t state = WASIP3_SUBTASK_RETURNED; -}; - -// Pinned canonical result layout for result<list<ip-address>, error-code>. -struct lookup_result { - alignas(void*) std::array<std::byte, 5 * sizeof(void*)> 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 deleted file mode 100644 index 6f088993..00000000 --- a/tools/boost/asio-wasip3/manifest.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "boost_version": 109200, - "files": { - "boost/asio/detail/buffer_sequence_adapter.hpp": { - "before": "fa90fb4211bd4463269d6a3f36b37cd8702ffc0260b35b27eca8627bfee2ee33", - "after": "a9e9d5f90228d8360eb99a8c267b3ca902be4bd08de5dff7bcf25443b04fe08c" - }, - "boost/asio/detail/config.hpp": { - "before": "be2ff484edb3f0bc46b6874f8e9595b4802132c4c052ca675d3c7d4359da8352", - "after": "a3354e5be669ad04377a1b65dd4ab2706443ea1491d9cc6fa75fef83cb4a1580" - }, - "boost/asio/detail/impl/null_event.ipp": { - "before": "00b0ffc7de583ed07afe02ca249d630414c118ac2d68948cbc1a51d47c583617", - "after": "f7aa930637aa0d4d466a7f6b078387620f50d28fa9b66059f19c10911e5499fa" - }, - "boost/asio/detail/impl/resolver_thread_pool.ipp": { - "before": "2c1488b04ea5cb139f0a632aa908b9ce7fe01e7c95464af2f9a16541cab31cb8", - "after": "d173fc0fc5ab396b24c7d7b56832676c05ba2017a6dca9997338821dd23bb0dc" - }, - "boost/asio/detail/impl/socket_ops.ipp": { - "before": "fd5bae35b76c374174d4cd6613c420225c297ef01acafd0487fff4b8d9298529", - "after": "3f191e38e230f05b5f629325d027b8408b6c28b9116219e5c43aaf399cb2eaaf" - }, - "boost/asio/detail/null_signal_blocker.hpp": { - "before": "125601602bac1118debb090870c96757abf71818dda18299c560555940b550d8", - "after": "13b78db25b3ff599d36fb0270109a0c077673f3de0d410d7e4392bd75110ef83" - }, - "boost/asio/detail/reactive_socket_sendto_op.hpp": { - "before": "1f8e02cf41fea19813b97ed8abdb77f64432b2168cd7cfcad86bea36aea1b4df", - "after": "ff72ed6496b9f6c3ea88213f83433e470ef11db948637aefafecbc11d23c9e4b" - }, - "boost/asio/detail/reactive_socket_service.hpp": { - "before": "5f68f1e43559adab6ec869f989a33c1295e0fafbb9ce7f27f4c0f205cfb0bbb2", - "after": "fb5e204b25a39c993c3cbb7480fc1e305952ea2ab5180418a312894b8e938b57" - }, - "boost/asio/detail/signal_blocker.hpp": { - "before": "b46eb959862d0b1643f244a743a2366aff3f0acd7638a5c3cfa78dc826dd4df9", - "after": "24559dd6af26a5ba8ee466e15ab9efb560602ef2995361824bc2b09eda160daa" - }, - "boost/asio/detail/socket_types.hpp": { - "before": "c83d94ea136034fc3e89018d47b38afed40449250660cc2720cbc89441023551", - "after": "52b404d0793e36afb0cdf3daf7b4d7713f40beaab9d2f09cab982c9f791985cb" - }, - "boost/asio/error.hpp": { - "before": "a836acf6bb58190eb3ae72d6795affb75d39876633c88c8343c61dfac67b0be2", - "after": "25e5d4ce36c513eed48c925d24cff62df0009469b73c6038c075939669cc2777" - }, - "boost/asio/detail/impl/select_reactor.ipp": { - "before": "4e6df639193d0c93d2a9b3e2ead005824a6a3c921d1382c3ce72e5ce959e6a48", - "after": "6587f498614375ba046e799c434871ecb682854f219d2ca0cb0685d457341998" - }, - "boost/asio/detail/select_interrupter.hpp": { - "before": "debfbfa6e8915f7123229d2031b4704b1b95edcb4590f4d9a5b25c8cdd4105d5", - "after": "0f41bb2fb2190bbb23ab553c3bc0c52266f4685f2e400fd57f0b4fb987cdedbb" - }, - "boost/asio/detail/resolver_service.hpp": { - "before": "8ec1a1f84c3de50a4bf85e9ae5f2247ceb10cb36970c2bcaa3598587fa3acb50", - "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/prepare.py b/tools/boost/asio-wasip3/prepare.py deleted file mode 100644 index 77e121a4..00000000 --- a/tools/boost/asio-wasip3/prepare.py +++ /dev/null @@ -1,89 +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) - -"""Apply a checked Asio patch to private headers, never to installed Boost.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -from pathlib import Path -import re -import subprocess -import tempfile - - -def digest(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def prepare(source: Path, output: Path, bundle: Path) -> None: - source, output, bundle = source.resolve(), output.resolve(), bundle.resolve() - if source == output or source in output.parents or output in source.parents: - raise ValueError('the overlay must be separate from the installed Boost tree') - manifest = json.loads((bundle / 'manifest.json').read_text()) - 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 Asio patch requires Boost 1.92; rebase and verify the patch') - inputs = {} - for name, hashes in manifest['files'].items(): - path = Path(name) - if path.is_absolute() or '..' in path.parts or not name.startswith('boost/asio/'): - 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 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. - for path in output.rglob('*'): - if path.is_symlink(): - raise ValueError('overlay contains a symlink: ' + str(path)) - if path.is_file() and path.relative_to(output).as_posix() not in inputs: - raise ValueError('unexpected overlay file: ' + str(path) - + '; clean the private overlay directory and rebuild') - output.parent.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix='asio-patch-', dir=output.parent) as temporary: - stage = Path(temporary) - for name, data in inputs.items(): - path = stage / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(data) - subprocess.run(['git', 'apply', '--no-index', str(bundle / 'boost-1.92.patch')], - cwd=stage, check=True, capture_output=True, text=True) - for name, hashes in manifest['files'].items(): - if digest((stage / name).read_bytes()) != hashes['after']: - raise ValueError('patched header failed verification: ' + name) - for name in inputs: - destination = output / name - data = (stage / name).read_bytes() - if destination.is_file() and destination.read_bytes() == data: - continue - destination.parent.mkdir(parents=True, exist_ok=True) - os.replace(stage / name, destination) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - 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, arguments.bundle) - except (ValueError, OSError, subprocess.CalledProcessError) as error: - 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 patched headers verified\n') - return 0 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/tools/boost/asio-wasip3/prepare_test.py b/tools/boost/asio-wasip3/prepare_test.py deleted file mode 100644 index 6f576430..00000000 --- a/tools/boost/asio-wasip3/prepare_test.py +++ /dev/null @@ -1,77 +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) - -"""Check that preparing a private Boost overlay is exact and non-destructive.""" -from pathlib import Path -import hashlib -import importlib.machinery -import importlib.util -import json -import subprocess -import sys -import tempfile -import unittest - -HERE = Path(__file__).resolve().parent -spec = importlib.util.spec_from_file_location('prepare', HERE / 'prepare.py') -assert spec is not None and isinstance(spec.loader, importlib.machinery.SourceFileLoader) -prepare = importlib.util.module_from_spec(spec) -spec.loader.exec_module(prepare) - - -class Preparation(unittest.TestCase): - def test_exact_inputs_idempotence_and_mismatch(self): - with tempfile.TemporaryDirectory(prefix='asio wasi patch ') as directory: - root = Path(directory) - source, output, bundle = root / 'boost', root / 'output', root / 'bundle' - header = source / 'boost/asio/example.hpp' - header.parent.mkdir(parents=True) - header.write_text('before\n') - (source / 'boost/version.hpp').write_text('#define BOOST_VERSION 109200\n') - bundle.mkdir() - digest = lambda data: hashlib.sha256(data.encode()).hexdigest() - (bundle / 'manifest.json').write_text(json.dumps({ - 'boost_version': 109200, - 'files': {'boost/asio/example.hpp': { - 'before': digest('before\n'), 'after': digest('after\n')}}})) - (bundle / 'boost-1.92.patch').write_text( - '--- a/boost/asio/example.hpp\n+++ b/boost/asio/example.hpp\n' - '@@ -1 +1 @@\n-before\n+after\n') - prepare.prepare(source, output, bundle) - self.assertEqual(header.read_text(), 'before\n') - result = output / 'boost/asio/example.hpp' - self.assertEqual(result.read_text(), 'after\n') - 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'): - prepare.prepare(source, output, bundle) - self.assertEqual(result.stat().st_mtime_ns, modified) - stale.unlink() - (output / 'linked').symlink_to(source, target_is_directory=True) - with self.assertRaisesRegex(ValueError, 'symlink'): - prepare.prepare(source, output, bundle) - self.assertEqual(header.read_text(), 'before\n') - (output / 'linked').unlink() - header.write_text('different upstream version\n') - with self.assertRaisesRegex(ValueError, 'incompatible Boost header'): - prepare.prepare(source, output, bundle) - self.assertEqual(result.read_text(), 'after\n') - - def test_refuses_the_installed_tree(self): - with tempfile.TemporaryDirectory() as directory: - source = Path(directory) - with self.assertRaisesRegex(ValueError, 'separate'): - prepare.prepare(source, source, HERE) - - -if __name__ == '__main__': - unittest.main() diff --git a/tools/boost/asio-wasip3/verify.py b/tools/boost/asio-wasip3/verify.py deleted file mode 100644 index 53540e2e..00000000 --- a/tools/boost/asio-wasip3/verify.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) 2026 WebCpp.org -# -# Distributed under the Boost Software License, Version 1.0. (See -# accompanying file LICENSE_1_0.txt or copy at -# https://www.boost.org/LICENSE_1_0.txt) -"""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 deleted file mode 100644 index c1b54c70..00000000 --- a/tools/boost/asio-wasip3/verify_test.py +++ /dev/null @@ -1,48 +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) -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 deleted file mode 100644 index c2f3592c..00000000 --- a/tools/boost/asio-wasip3/waitable.cpp +++ /dev/null @@ -1,121 +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) -#include <boost/asio/detail/wasi_waitable.hpp> -#include <cerrno> -#include <cstdlib> -#include <cstring> -#include <new> -#include <string_view> -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<descriptor_storage*>(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<waitable_descriptor*>(value); - storage.state = static_cast<wasip3_subtask_state_t>(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<unsigned>(events) & ~static_cast<unsigned>(POLLRDNORM)) != 0) { - errno = EOPNOTSUPP; - return -1; - } - auto& storage = *static_cast<descriptor_storage*>(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<descriptor_vtable_t*>(&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 deleted file mode 100644 index d3e73789..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/LICENSE +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 16fe87b0..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - 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 deleted file mode 100644 index 31aa7938..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/LICENSE-MIT +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 718083ae..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/manifest.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "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 deleted file mode 100644 index b06b8e6d..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/wasi/descriptor_table.h +++ /dev/null @@ -1,368 +0,0 @@ -#ifndef DESCRIPTOR_TABLE_H -#define DESCRIPTOR_TABLE_H - -#include <wasi/api.h> - -#ifndef __wasip1__ -#include <assert.h> -#include <netinet/in.h> -#include <stdlib.h> -#include <string.h> -#include <sys/stat.h> -#include <wasi/poll.h> - -#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<u8>`. -/// -/// 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<u8>`. -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<u8>`. -/// -/// 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 deleted file mode 100644 index 0bc89f72..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/wasi/lock.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef LOCK_H -#define LOCK_H - -#include <features.h> -#include <wasi/version.h> - -// 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 deleted file mode 100644 index 39ac8f89..00000000 --- a/tools/boost/asio-wasip3/wasi-libc/wasi/poll.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef WASI_POLL_H -#define WASI_POLL_H - -#include <wasi/version.h> - -#ifndef __wasip1__ - -#include <poll.h> -#include <wasi/api.h> - -/// 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-windows/Jamfile b/tools/boost/asio-windows/Jamfile deleted file mode 100644 index 6c800fa4..00000000 --- a/tools/boost/asio-windows/Jamfile +++ /dev/null @@ -1,33 +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) - -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 - : <location>$(OVERLAY) <webcpp-boost-check>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 : : : : <dependency>prepared.stamp - <cxxflags>"-I\"$(OVERLAY)/include\"" ; -explicit headers ; diff --git a/tools/boost/asio-windows/README.md b/tools/boost/asio-windows/README.md deleted file mode 100644 index 00f9f654..00000000 --- a/tools/boost/asio-windows/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# 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 deleted file mode 100644 index 4fe0249d..00000000 --- a/tools/boost/asio-windows/boost-1.92.patch +++ /dev/null @@ -1,22 +0,0 @@ ---- 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<void>(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<void>(this->context()), thread_function, 65536); - } - } - diff --git a/tools/boost/asio-windows/manifest.json b/tools/boost/asio-windows/manifest.json deleted file mode 100644 index 4a18d42d..00000000 --- a/tools/boost/asio-windows/manifest.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "boost_version": 109200, - "files": { - "boost/asio/detail/impl/win_iocp_io_context.ipp": { - "before": "d05a5e4fbb540eb13eb8e3165614177407fbed564e3a3bbbeca0b5b9ae0247f3", - "after": "0d77d743e222e71145abdfc8d968d275b66b9550f8416aa4724561f86085ba19" - } - } -} diff --git a/tools/boost/cobalt-common/Jamfile b/tools/boost/cobalt-common/Jamfile deleted file mode 100644 index 4b86ad53..00000000 --- a/tools/boost/cobalt-common/Jamfile +++ /dev/null @@ -1,34 +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) - -import make ; - -project /webcpp/cobalt-common ; -path-constant BUNDLE : . ; -path-constant OVERLAY : ../../../bin/boost-cobalt-common ; - -make prepared.stamp : ../cobalt-wasip3/prepare.py manifest.json boost-1.92.patch : @prepare - : <location>$(OVERLAY) <webcpp-boost-check>off ; -always prepared.stamp ; -explicit prepared.stamp ; - -rule prepare ( targets * : sources * : properties * ) -{ - SCRIPT on $(targets) = $(BUNDLE)/../cobalt-wasip3/prepare.py ; - BUNDLE on $(targets) = $(BUNDLE) ; - HEADERS on $(targets) = $(WEBCPP_BOOST_HEADERS) ; - SOURCES on $(targets) = $(WEBCPP_BOOST_SOURCE) ; - OUTPUT on $(targets) = $(OVERLAY)/include ; -} - -actions prepare -{ - python3 "$(SCRIPT)" --boost "$(HEADERS)" --sources "$(SOURCES)" --output "$(OUTPUT)" --bundle "$(BUNDLE)" --stamp "$(<)" -} - -alias headers : : : : <dependency>prepared.stamp - <cxxflags>"-I\"$(OVERLAY)/include\"" ; -explicit headers ; diff --git a/tools/boost/cobalt-common/boost-1.92.patch b/tools/boost/cobalt-common/boost-1.92.patch deleted file mode 100644 index 03f21dfb..00000000 --- a/tools/boost/cobalt-common/boost-1.92.patch +++ /dev/null @@ -1,67 +0,0 @@ ---- a/boost/cobalt/composition.hpp -+++ b/boost/cobalt/composition.hpp -@@ -130,7 +130,7 @@ - template<typename ... Ts> - composition_promise(Ts && ... args) : handler(std::move(std::get<sizeof... (Ts) - 1>(std::tie(args...)))) - { -- -+ this->reset_cancellation_source(handler.get_cancellation_slot()); - } - - void unhandled_exception() { throw ; } ---- a/boost/cobalt/detail/main.hpp -+++ b/boost/cobalt/detail/main.hpp -@@ -13,6 +13,7 @@ - #include <boost/cobalt/this_coro.hpp> - - #include <boost/config.hpp> -+#include <exception> - - - 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) - { ---- a/boost/cobalt/detail/thread.hpp -+++ b/boost/cobalt/detail/thread.hpp -@@ -17,6 +17,7 @@ - - #include <boost/asio/cancellation_signal.hpp> - -+#include <exception> - #include <thread> - - 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 deleted file mode 100644 index 32d42332..00000000 --- a/tools/boost/cobalt-common/manifest.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "boost_version": 109200, - "files": { - "boost/cobalt/composition.hpp": { - "before": "4f89225430772cc39a82e37ec1b67069b342fa77423b3f6ad74edc3d8d1a77c5", - "after": "a4d22f4619cad58063473d0e86a31dfbbfd4856b57d59c22e1c18ec0ccfabe1b" - }, - "boost/cobalt/detail/main.hpp": { - "before": "fbdcb0ca58d8a368b8e4ec680dc99bcdd6ce2a2c5375770e278dec1dec91afcb", - "after": "2a55b2e808068c0aaef80ab257f462ab9d61f7d3d59ef0ede23ed6b56046bdf5" - }, - "boost/cobalt/detail/thread.hpp": { - "before": "e8dc12b4145c9903ac7f87dd50d87f4b3d742819ee653cdd84e84d92c3c8c37d", - "after": "670b2c403b2e75d70ade9dd95bfe34834ce49ea2c1f875559071fd6fd4a2812b" - } - } -} diff --git a/tools/boost/cobalt-ssl/Jamfile b/tools/boost/cobalt-ssl/Jamfile deleted file mode 100644 index ac6a2f62..00000000 --- a/tools/boost/cobalt-ssl/Jamfile +++ /dev/null @@ -1,52 +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) - -import errors ; -import make ; -import webcpp-target ; - -project /webcpp/cobalt-ssl ; -path-constant BUNDLE : . ; -path-constant OVERLAY : ../../../bin/boost-cobalt-ssl ; - -make prepared.stamp : ../cobalt-wasip3/prepare.py manifest.json boost-1.92.patch : @prepare - : <location>$(OVERLAY) <webcpp-boost-check>off ; -always prepared.stamp ; -explicit prepared.stamp ; - -rule prepare ( targets * : sources * : properties * ) -{ - SCRIPT on $(targets) = $(BUNDLE)/../cobalt-wasip3/prepare.py ; - BUNDLE on $(targets) = $(BUNDLE) ; - HEADERS on $(targets) = $(WEBCPP_BOOST_HEADERS) ; - SOURCES on $(targets) = $(WEBCPP_BOOST_SOURCE) ; - OUTPUT on $(targets) = $(OVERLAY)/include ; -} - -actions prepare -{ - python3 "$(SCRIPT)" --boost "$(HEADERS)" --sources "$(SOURCES)" --output "$(OUTPUT)" --bundle "$(BUNDLE)" --stamp "$(<)" -} - -rule supported ( properties * ) -{ - if ! [ webcpp-target.target-of $(properties) ] in native wasip2 wasip3 - { - errors.user-error "Cobalt SSL requires native, WASIp2 or WASIp3 with source-built OpenSSL." ; - } -} - -alias headers : : : : <dependency>prepared.stamp - <cxxflags>"-I\"$(OVERLAY)/include\"" ; -explicit headers ; - -lib boost_cobalt_io_ssl : ssl.cpp - : <conditional>@supported <link>static <define>BOOST_COBALT_SSL_SOURCE=1 - <library>headers <library>/webcpp//boost_cobalt - <library>/webcpp/third_party//openssl <warnings>off <warnings-as-errors>off - : : <library>headers <library>/webcpp//boost_cobalt - <library>/webcpp/third_party//openssl ; -explicit boost_cobalt_io_ssl ; diff --git a/tools/boost/cobalt-ssl/boost-1.92.patch b/tools/boost/cobalt-ssl/boost-1.92.patch deleted file mode 100644 index 002a5561..00000000 --- a/tools/boost/cobalt-ssl/boost-1.92.patch +++ /dev/null @@ -1,187 +0,0 @@ ---- a/boost/cobalt/io/ssl.hpp -+++ b/boost/cobalt/io/ssl.hpp -@@ -62,17 +62,20 @@ - - [[nodiscard]] write_op write_some(const_buffer_sequence buffer) override - { -- return {buffer, this, initiate_write_some_}; -+ return {buffer, this, initiate_write_some_, check_write_}; - } - [[nodiscard]] read_op read_some(mutable_buffer_sequence buffer) override - { -- return {buffer, this, initiate_read_some_}; -+ return {buffer, this, initiate_read_some_, check_read_}; - } - - [[nodiscard]] bool secure() const {return upgraded_;} - -+ // The SSL connection, distinct from socket::native_handle()'s descriptor. -+ [[nodiscard]] SSL * native_ssl_handle() { return stream_socket_.native_handle(); } -+ - template<typename VerifyCallback> -- requires requires (const VerifyCallback & cb, context & ctx) {{cb(true, ctx)} -> std::same_as<bool>;} -+ requires requires (VerifyCallback & cb, asio::ssl::verify_context & ctx) {{cb(true, ctx)} -> std::same_as<bool>;} - system::result<void> set_verify_callback(VerifyCallback vc) - { - system::error_code ec; -@@ -93,12 +96,13 @@ - { - void ready(handler<system::error_code> h) final; - void initiate(completion_handler<system::error_code> h) final; -- handshake_op_(handshake_type type, bool upgraded, asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> & stream_socket) -- : type_(type), upgraded_(upgraded), stream_socket_(stream_socket) {} -+ handshake_op_(handshake_type type, bool & upgraded, bool & started, asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> & stream_socket) -+ : type_(type), upgraded_(upgraded), started_(started), stream_socket_(stream_socket) {} - ~handshake_op_() = default; - private: - handshake_type type_; -- bool upgraded_; -+ bool & upgraded_; -+ bool & started_; - asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> &stream_socket_; - }; - -@@ -107,13 +111,14 @@ - { - void ready(handler<system::error_code, std::size_t> h) final; - void initiate(completion_handler<system::error_code, std::size_t> h) final; -- handshake_buffer_op_(handshake_type type, bool upgraded, const_buffer_sequence buffer_, -+ handshake_buffer_op_(handshake_type type, bool & upgraded, bool & started, const_buffer_sequence buffer_, - asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> & stream_socket) -- : type_(type), upgraded_(upgraded), buffer_(buffer_), stream_socket_(stream_socket) {} -+ : type_(type), upgraded_(upgraded), started_(started), buffer_(buffer_), stream_socket_(stream_socket) {} - ~handshake_buffer_op_() = default; - private: - handshake_type type_; -- bool upgraded_; -+ bool & upgraded_; -+ bool & started_; - const_buffer_sequence buffer_; - asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> &stream_socket_; - }; -@@ -123,18 +128,18 @@ - { - void ready(handler<system::error_code> h) final; - void initiate(completion_handler<system::error_code> h) final; -- shutdown_op_(bool upgraded, asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> & stream_socket) -+ shutdown_op_(bool & upgraded, asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> & stream_socket) - : upgraded_(upgraded), stream_socket_(stream_socket) {} - ~shutdown_op_() = default; - private: -- bool upgraded_; -+ bool & upgraded_; - asio::ssl::stream<asio::basic_stream_socket<protocol_type, executor>> &stream_socket_; - }; - public: -- [[nodiscard]] auto handshake(handshake_type type) { return handshake_op_{type, upgraded_, stream_socket_}; } -+ [[nodiscard]] auto handshake(handshake_type type) { return handshake_op_{type, upgraded_, started_, stream_socket_}; } - [[nodiscard]] auto handshake(handshake_type type, const_buffer_sequence buffer) - { -- return handshake_buffer_op_{type, upgraded_, buffer, stream_socket_}; -+ return handshake_buffer_op_{type, upgraded_, started_, buffer, stream_socket_}; - } - [[nodiscard]] auto shutdown() { return shutdown_op_{upgraded_, stream_socket_}; } - private: -@@ -145,6 +150,11 @@ - BOOST_COBALT_SSL_DECL static void initiate_write_some_(void *, const_buffer_sequence, cobalt::completion_handler<system::error_code, std::size_t>); - - -+ static void check_read_(void *, mutable_buffer_sequence, cobalt::handler<system::error_code, std::size_t>); -+ static void check_write_(void *, const_buffer_sequence, cobalt::handler<system::error_code, std::size_t>); -+ -+ // Plain TCP is allowed only before the first TLS attempt (STARTTLS). -+ bool started_ = false; - bool upgraded_ = false; - }; - ---- a/libs/cobalt/src/io/ssl.cpp -+++ b/libs/cobalt/src/io/ssl.cpp -@@ -10,6 +10,43 @@ - - namespace boost::cobalt::io::ssl - { -+namespace -+{ -+// Inherit all associated properties, including cancellation, allocator and the -+// immediate executor. Update state before the base handler resumes the coroutine. -+template<bool SecureOnSuccess, typename... Args> -+struct state_handler : completion_handler<system::error_code, Args...> -+{ -+ using base = completion_handler<system::error_code, Args...>; -+ bool & secure_; -+ -+ state_handler(base handler, bool & secure) -+ : base(std::move(handler)), secure_(secure) {} -+ -+ void operator()(system::error_code ec, Args... args) -+ { -+ secure_ = SecureOnSuccess && !ec; -+ base::operator()(ec, std::move(args)...); -+ } -+}; -+} -+ -+void stream::check_read_(void * self, mutable_buffer_sequence, -+ cobalt::handler<system::error_code, std::size_t> handler) -+{ -+ const auto & stream = *static_cast<ssl::stream *>(self); -+ if (stream.started_ && !stream.upgraded_) -+ handler(asio::error::not_connected, 0); -+} -+ -+void stream::check_write_(void * self, const_buffer_sequence, -+ cobalt::handler<system::error_code, std::size_t> handler) -+{ -+ const auto & stream = *static_cast<ssl::stream *>(self); -+ if (stream.started_ && !stream.upgraded_) -+ handler(asio::error::not_connected, 0); -+} -+ - - stream::stream(context & ctx, const cobalt::executor & exec) - : stream_impl{.stream_socket_={exec, ctx}}, socket(stream_socket_.lowest_layer()) -@@ -80,7 +117,7 @@ - - void stream::handshake_op_::ready(handler<system::error_code> handler) - { -- if (upgraded_) -+ if (started_) - { - constexpr static boost::source_location loc{BOOST_CURRENT_LOCATION}; - handler(system::error_code{asio::error::already_started}); -@@ -89,12 +126,13 @@ - - void stream::handshake_op_::initiate(completion_handler<system::error_code> handler) - { -- stream_socket_.async_handshake(type_, std::move(handler)); -+ started_ = true; -+ stream_socket_.async_handshake(type_, state_handler<true>{std::move(handler), upgraded_}); - } - - void stream::handshake_buffer_op_::ready(handler<system::error_code, std::size_t> handler) - { -- if (upgraded_) -+ if (started_) - { - constexpr static boost::source_location loc{BOOST_CURRENT_LOCATION}; - handler(system::error_code{asio::error::already_started}, 0ull); -@@ -103,7 +141,9 @@ - - void stream::handshake_buffer_op_::initiate(completion_handler<system::error_code, std::size_t> handler) - { -- stream_socket_.async_handshake(type_, buffer_, std::move(handler)); -+ started_ = true; -+ stream_socket_.async_handshake(type_, buffer_, -+ state_handler<true, std::size_t>{std::move(handler), upgraded_}); - } - - void stream::shutdown_op_::ready(handler<system::error_code> handler) -@@ -117,7 +157,7 @@ - - void stream::shutdown_op_::initiate(completion_handler<system::error_code> handler) - { -- stream_socket_.async_shutdown(std::move(handler)); -+ stream_socket_.async_shutdown(state_handler<false>{std::move(handler), upgraded_}); - } - - diff --git a/tools/boost/cobalt-ssl/manifest.json b/tools/boost/cobalt-ssl/manifest.json deleted file mode 100644 index 575e0530..00000000 --- a/tools/boost/cobalt-ssl/manifest.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "boost_version": 109200, - "files": { - "boost/cobalt/io/ssl.hpp": { - "before": "777102926b05287e6dc33077b0784f8435a4bf661adf4db0f5616f7af506ce87", - "after": "9c26d54001d4de8f2092cfe6d0f277b9dabfb0bcca1db7cb59f018ae0b44bb38" - }, - "libs/cobalt/src/io/ssl.cpp": { - "before": "8ba89c9f5cb2c492f67d05b00c59b80b71090b8af03d9dd13956cccc6f329f72", - "after": "eac41d38066f6e027c428a49a55791031d3bfb76bdffd9dbedacf0564410e620" - } - } -} diff --git a/tools/boost/cobalt-ssl/ssl.cpp b/tools/boost/cobalt-ssl/ssl.cpp deleted file mode 100644 index 9c1024c9..00000000 --- a/tools/boost/cobalt-ssl/ssl.cpp +++ /dev/null @@ -1,8 +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) - -// Compile the checked, patched upstream implementation through its selected include directory. -#include <libs/cobalt/src/io/ssl.cpp> // NOLINT(bugprone-suspicious-include) diff --git a/tools/boost/cobalt-wasip3/Jamfile b/tools/boost/cobalt-wasip3/Jamfile deleted file mode 100644 index 077ada4e..00000000 --- a/tools/boost/cobalt-wasip3/Jamfile +++ /dev/null @@ -1,47 +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) - -import make ; - -project /webcpp/cobalt-wasip3 ; -path-constant BUNDLE : . ; -path-constant OVERLAY : ../../../bin/boost-cobalt-wasip3 ; - -make prepared.stamp : prepare.py manifest.json boost-1.92.patch : @prepare - : <location>$(OVERLAY) <webcpp-boost-check>off ; -always prepared.stamp ; -explicit prepared.stamp ; - -rule prepare ( targets * : sources * : properties * ) -{ - SCRIPT on $(targets) = $(BUNDLE)/prepare.py ; - HEADERS on $(targets) = $(WEBCPP_BOOST_HEADERS) ; - SOURCES on $(targets) = $(WEBCPP_BOOST_SOURCE) ; - OUTPUT on $(targets) = $(OVERLAY)/include ; -} - -actions prepare -{ - python3 "$(SCRIPT)" --boost "$(HEADERS)" --sources "$(SOURCES)" --output "$(OUTPUT)" --stamp "$(<)" -} - -alias headers : : : : <dependency>prepared.stamp - <cxxflags>"-I\"$(OVERLAY)/include\"" - <toolset>clang-wasip2:<library>/webcpp/config//config - <toolset>clang-wasip2:<include>../../../libs/asio/include - <toolset>clang-wasip2:<library>/webcpp/asio-wasip2//headers - <toolset>clang-wasip3:<library>/webcpp/asio-wasip3//headers ; -explicit headers ; - -# These objects are built separately from boost_cobalt. Its free include flags -# and source markers do not reach them, so they explicitly share both. -obj endpoint : endpoint.cpp : <library>headers <library>/webcpp/cobalt-common//headers - <define>BOOST_COBALT_SOURCE=1 <define>BOOST_COBALT_IO_SOURCE=1 - <warnings>off <warnings-as-errors>off ; -obj acceptor : acceptor.cpp : <library>headers <library>/webcpp/cobalt-common//headers - <define>BOOST_COBALT_SOURCE=1 <define>BOOST_COBALT_IO_SOURCE=1 - <warnings>off <warnings-as-errors>off ; -explicit endpoint acceptor ; diff --git a/tools/boost/cobalt-wasip3/acceptor.cpp b/tools/boost/cobalt-wasip3/acceptor.cpp deleted file mode 100644 index 78ba21a1..00000000 --- a/tools/boost/cobalt-wasip3/acceptor.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// 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 <libs/cobalt/src/io/acceptor.cpp> diff --git a/tools/boost/cobalt-wasip3/boost-1.92.patch b/tools/boost/cobalt-wasip3/boost-1.92.patch deleted file mode 100644 index 73517bdf..00000000 --- a/tools/boost/cobalt-wasip3/boost-1.92.patch +++ /dev/null @@ -1,225 +0,0 @@ ---- a/boost/cobalt/io/acceptor.hpp -+++ b/boost/cobalt/io/acceptor.hpp -@@ -54,6 +54,7 @@ - stream_socket sock_{acceptor_.get_executor()}; - }; - -+#if defined(SOCK_SEQPACKET) - struct BOOST_COBALT_IO_DECL accept_seq_packet_op final : op<system::error_code, seq_packet_socket> - { - void initiate(completion_handler<system::error_code, seq_packet_socket> h) override; -@@ -66,6 +67,8 @@ - seq_packet_socket sock_{acceptor_.get_executor()}; - }; - -+ -+#endif - - struct BOOST_COBALT_IO_DECL wait_op final : op<system::error_code> - { -@@ -94,12 +97,15 @@ - return accept_stream_op{acceptor_}; - } - -+#if defined(SOCK_SEQPACKET) - template<protocol_type::family_t F, protocol_type::protocol_t P> - [[nodiscard]] accept_seq_packet_op accept(static_protocol<F, local_seqpacket.type(), P> stream_proto) - { - return accept_seq_packet_op{acceptor_}; - } - -+ -+#endif - - [[nodiscard]] wait_op wait(wait_type wt = wait_type::wait_read) - { ---- a/boost/cobalt/io/datagram_socket.hpp -+++ b/boost/cobalt/io/datagram_socket.hpp -@@ -46,6 +46,7 @@ - }; - - -+#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) - inline system::result<std::pair<datagram_socket, datagram_socket>> make_pair(decltype(local_datagram) protocol) - { - std::pair<datagram_socket, datagram_socket> res; -@@ -55,6 +56,8 @@ - else - return c.error(); - } -+#endif -+ - - } - ---- a/boost/cobalt/io/endpoint.hpp -+++ b/boost/cobalt/io/endpoint.hpp -@@ -118,10 +118,13 @@ - constexpr static_protocol<BOOST_ASIO_OS_DEF(AF_INET), BOOST_ASIO_OS_DEF(SOCK_DGRAM), BOOST_ASIO_OS_DEF(IPPROTO_UDP)> udp_v4{}; - constexpr static_protocol<BOOST_ASIO_OS_DEF(AF_INET6), BOOST_ASIO_OS_DEF(SOCK_DGRAM), BOOST_ASIO_OS_DEF(IPPROTO_ICMP)> udp_v6{}; - constexpr static_protocol<BOOST_ASIO_OS_DEF(AF_UNSPEC), BOOST_ASIO_OS_DEF(SOCK_DGRAM), BOOST_ASIO_OS_DEF(IPPROTO_ICMP)> icmp {}; -+#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) - constexpr static_protocol<AF_UNIX, BOOST_ASIO_OS_DEF(SOCK_STREAM)> local_stream {}; - constexpr static_protocol<AF_UNIX, BOOST_ASIO_OS_DEF(SOCK_DGRAM)> local_datagram {}; - constexpr static_protocol<AF_UNIX, BOOST_ASIO_OS_DEF(SOCK_SEQPACKET)> local_seqpacket{}; - constexpr static_protocol<AF_UNIX> local_protocol {}; -+ -+#endif - - #if defined(IPPROTO_SCTP) - constexpr static_protocol<BOOST_ASIO_OS_DEF(AF_UNSPEC), BOOST_ASIO_OS_DEF(SOCK_SEQPACKET), IPPROTO_SCTP> sctp {}; -@@ -256,6 +259,7 @@ - return *e; - } - -+#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) - struct local_endpoint - { - std::string_view path() const { return unix_.sun_path;} -@@ -275,6 +279,8 @@ - const local_endpoint* tag_invoke(get_endpoint_tag<AF_UNIX>, - protocol_type actual, - const endpoint::addr_type * addr); -+ -+#endif - - struct ip_address_v4 - { ---- a/boost/cobalt/io/seq_packet_socket.hpp -+++ b/boost/cobalt/io/seq_packet_socket.hpp -@@ -7,6 +7,9 @@ - - #ifndef BOOST_COBALT_IOSEQ_PACKET_SOCKET_HPP - #define BOOST_COBALT_IOSEQ_PACKET_SOCKET_HPP -+ -+#include <boost/asio/detail/config.hpp> -+#if defined(SOCK_SEQPACKET) - - #include <boost/cobalt/io/detail/config.hpp> - #include <boost/cobalt/io/endpoint.hpp> -@@ -91,4 +94,6 @@ - - } - -+#endif -+ - #endif //BOOST_COBALT_IOSEQ_PACKET_SOCKET_HPP ---- a/boost/cobalt/io/serial_port.hpp -+++ b/boost/cobalt/io/serial_port.hpp -@@ -7,6 +7,9 @@ - - #ifndef BOOST_COBALT_IO_SERIAL_PORT_HPP - #define BOOST_COBALT_IO_SERIAL_PORT_HPP -+ -+#include <boost/asio/detail/config.hpp> -+#if defined(BOOST_ASIO_HAS_SERIAL_PORT) - - #include <boost/cobalt/io/detail/config.hpp> - #include <boost/cobalt/op.hpp> -@@ -81,4 +84,6 @@ - - } - -+#endif -+ - #endif //BOOST_COBALT_IO_SERIAL_PORT_HPP ---- a/boost/cobalt/io/signal_set.hpp -+++ b/boost/cobalt/io/signal_set.hpp -@@ -7,6 +7,9 @@ - - #ifndef BOOST_COBALT_IO_SIGNAL_SET_HPP - #define BOOST_COBALT_IO_SIGNAL_SET_HPP -+ -+#include <boost/asio/detail/config.hpp> -+#if defined(BOOST_ASIO_HAS_SIGNAL) - - #include <boost/cobalt/io/detail/config.hpp> - #include <boost/cobalt/op.hpp> -@@ -48,4 +51,6 @@ - - } - -+#endif -+ - #endif //BOOST_COBALT_IO_SIGNAL_SET_HPP ---- a/boost/cobalt/io/stream_socket.hpp -+++ b/boost/cobalt/io/stream_socket.hpp -@@ -49,6 +49,7 @@ - }; - - -+#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) - inline system::result<std::pair<stream_socket, stream_socket>> make_pair(decltype(local_stream) protocol) - { - std::pair<stream_socket, stream_socket> res; -@@ -58,6 +59,8 @@ - else - return c.error(); - } -+#endif -+ - - } - ---- a/boost/cobalt/thread.hpp -+++ b/boost/cobalt/thread.hpp -@@ -7,6 +7,9 @@ - - #ifndef BOOST_COBALT_THREAD_HPP - #define BOOST_COBALT_THREAD_HPP -+ -+#include <boost/asio/detail/config.hpp> -+#if defined(BOOST_ASIO_HAS_THREADS) - - #include <boost/cobalt/detail/thread.hpp> - #include <boost/cobalt/detail/exception.hpp> -@@ -121,4 +124,6 @@ - - } - -+#endif -+ - #endif //BOOST_COBALT_THREAD_HPP ---- a/libs/cobalt/src/io/acceptor.cpp -+++ b/libs/cobalt/src/io/acceptor.cpp -@@ -43,11 +43,14 @@ - co_return {ec, std::move(sock_)}; - } - -+#if defined(SOCK_SEQPACKET) - void acceptor::accept_seq_packet_op::initiate(completion_handler<system::error_code, seq_packet_socket>) - { - auto [ec] = co_await acceptor_.async_accept(sock_.socket_); - co_return {ec, std::move(sock_)}; - } -+ -+#endif - - void acceptor::wait_op::initiate(completion_handler<system::error_code> handler) - { ---- a/libs/cobalt/src/io/endpoint.cpp -+++ b/libs/cobalt/src/io/endpoint.cpp -@@ -25,11 +25,14 @@ - { - - static_assert(std::is_standard_layout_v<endpoint>); -+#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) - static_assert(std::is_standard_layout_v<local_endpoint>); -+#endif - static_assert(std::is_standard_layout_v<ip_address>); - static_assert(std::is_standard_layout_v<ip_address_v4>); - static_assert(std::is_standard_layout_v<ip_address_v6>); - -+#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) - std::size_t tag_invoke(make_endpoint_tag<AF_UNIX>, - asio::detail::socket_addr_type* base, - std::string_view sv) -@@ -52,6 +55,8 @@ - return nullptr; - return reinterpret_cast<const local_endpoint*>(addr); - } -+ -+#endif - - boost::static_string<15> ip_address_v4::addr_str() const - { diff --git a/tools/boost/cobalt-wasip3/endpoint.cpp b/tools/boost/cobalt-wasip3/endpoint.cpp deleted file mode 100644 index 71638bb9..00000000 --- a/tools/boost/cobalt-wasip3/endpoint.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// 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 <libs/cobalt/src/io/endpoint.cpp> diff --git a/tools/boost/cobalt-wasip3/manifest.json b/tools/boost/cobalt-wasip3/manifest.json deleted file mode 100644 index 9b9b2d9d..00000000 --- a/tools/boost/cobalt-wasip3/manifest.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "boost_version": 109200, - "files": { - "boost/cobalt/io/acceptor.hpp": { - "before": "d4288bd7bfd6953c15fdfac09a8caff56c7e78fceebe2c5b9f232daff8736c18", - "after": "33c3aa0fa45184a555353153c08f4950b81209221791ec43759ab783fc7ba6fd" - }, - "boost/cobalt/io/datagram_socket.hpp": { - "before": "d7779550e83648e7c4e5c2224ada99b2a7d9766adf6411107570eca173865e83", - "after": "b60aa660ce9d181967c4369f73a5c8d069d9ee189082d19f033f7cce80c3d0db" - }, - "boost/cobalt/io/endpoint.hpp": { - "before": "ab852f4996a2c1078bf79198daec50a5fd5acbefa000a3ab3065b58ce334e595", - "after": "5b915d39de36a0291eb1e8fc82f21342f9a6cb3cd64150f0a82f63cc334c219e" - }, - "boost/cobalt/io/seq_packet_socket.hpp": { - "before": "75dc97e20b798fc6b6cd159c780d3eb44834fa3b7438e13f3715b3b98ec333ff", - "after": "a3bae77026e2d17ea92a303e0139a7bdcd906118a2907508a17d31039cd203d7" - }, - "boost/cobalt/io/serial_port.hpp": { - "before": "9a4afa14aef6bb441a2ecb8d83db127a9d555db272f0fcd05688b35b46667d2f", - "after": "1019ac492135056919651ce2fc729e9918f7e2fd263a9cf8a88c7da821ed7012" - }, - "boost/cobalt/io/signal_set.hpp": { - "before": "e0ca22360d314b483ed6f867eb660a77f4fc931f697094859b702dc245d736d7", - "after": "f291fac6c423d9922d9f1c60d57dfec3c97c2652053ff76f3fb8fd90df6ce311" - }, - "boost/cobalt/io/stream_socket.hpp": { - "before": "01f6ecedbbf17de0754dd6c8d812fe93fa854c9c45af2eaf4ff7c89ce589058c", - "after": "ec45ab77be736f2dbde0bda5924d78acdef80b712305abf59a346cc79a1535e4" - }, - "boost/cobalt/thread.hpp": { - "before": "8c4c9882e0e6eb4dd7418f94a7db0bd8eb676b1563afc708886abba9d954df39", - "after": "75ce0daf18d95198901180811457e765b29dec0a616cc0d34e9477184fdd520a" - }, - "libs/cobalt/src/io/acceptor.cpp": { - "before": "d52e42c21036881779f2064cb99a584e33d1cc062402bc45dce56aa6cfcc57d4", - "after": "352b56a65b37f1dbdefd18be99df851a850387c76c5286262d8439e29d271bf0" - }, - "libs/cobalt/src/io/endpoint.cpp": { - "before": "00b80c29337991bb81863cd9f666bf6c6ce2b1001a0b0e296f053734da5af51b", - "after": "ba0dabaf0b557cebf02223b78b1610e0bedef0b5ce372d006b783d9bc9f6d8cf" - } - } -} diff --git a/tools/boost/cobalt-wasip3/prepare.py b/tools/boost/cobalt-wasip3/prepare.py deleted file mode 100644 index ed5ed7ad..00000000 --- a/tools/boost/cobalt-wasip3/prepare.py +++ /dev/null @@ -1,94 +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) - -"""Apply the checked Cobalt port to private headers, never to installed Boost.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -from pathlib import Path -import re -import subprocess -import tempfile - - -def digest(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def prepare(source: Path, sources: Path, output: Path, bundle: Path) -> None: - source, sources = source.resolve(), sources.resolve() - output, bundle = output.resolve(), bundle.resolve() - if any(root == output or root in output.parents or output in root.parents - for root in (source, sources)): - raise ValueError('the overlay must be separate from the installed Boost tree') - manifest = json.loads((bundle / 'manifest.json').read_text()) - 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 Cobalt patch requires Boost 1.92; rebase and verify the patch') - inputs = {} - for name, hashes in manifest['files'].items(): - path = Path(name) - if (path.is_absolute() or '..' in path.parts - or not name.startswith(('boost/cobalt/', 'libs/cobalt/src/'))): - raise ValueError('invalid patch manifest path: ' + name) - root = source if name.startswith('boost/') else sources - data = (root / path).read_bytes() - if digest(data) != hashes['before']: - raise ValueError('incompatible Boost header: ' + name + '; rebase the Cobalt 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. - for path in output.rglob('*'): - if path.is_symlink(): - raise ValueError('overlay contains a symlink: ' + str(path)) - if path.is_file() and path.relative_to(output).as_posix() not in inputs: - raise ValueError('unexpected overlay file: ' + str(path) - + '; clean the private overlay directory and rebuild') - output.parent.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix='cobalt-patch-', dir=output.parent) as temporary: - stage = Path(temporary) - for name, data in inputs.items(): - path = stage / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(data) - subprocess.run(['git', 'apply', '--no-index', str(bundle / 'boost-1.92.patch')], - cwd=stage, check=True, capture_output=True, text=True) - for name, hashes in manifest['files'].items(): - if digest((stage / name).read_bytes()) != hashes['after']: - raise ValueError('patched header failed verification: ' + name) - for name in inputs: - destination = output / name - data = (stage / name).read_bytes() - if destination.is_file() and destination.read_bytes() == data: - continue - destination.parent.mkdir(parents=True, exist_ok=True) - os.replace(stage / name, destination) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--boost', type=Path, required=True) - parser.add_argument('--sources', 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.sources, arguments.output, arguments.bundle) - except (ValueError, OSError, subprocess.CalledProcessError) as error: - parser.exit(1, f'Cobalt preparation failed: {error}\n') - if arguments.stamp: - arguments.stamp.parent.mkdir(parents=True, exist_ok=True) - arguments.stamp.write_text('Boost.Cobalt patched headers and sources verified\n') - return 0 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/tools/boost/cobalt-wasip3/prepare_test.py b/tools/boost/cobalt-wasip3/prepare_test.py deleted file mode 100644 index d54ede97..00000000 --- a/tools/boost/cobalt-wasip3/prepare_test.py +++ /dev/null @@ -1,85 +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) - -"""Check that patched headers and sources are verified before being published.""" -from pathlib import Path -import hashlib -import importlib.machinery -import importlib.util -import json -import subprocess -import sys -import tempfile -import unittest - -HERE = Path(__file__).resolve().parent -spec = importlib.util.spec_from_file_location('prepare', HERE / 'prepare.py') -assert spec is not None and isinstance(spec.loader, importlib.machinery.SourceFileLoader) -prepare = importlib.util.module_from_spec(spec) -spec.loader.exec_module(prepare) - - -class Preparation(unittest.TestCase): - def test_checked_headers_and_sources(self): - with tempfile.TemporaryDirectory(prefix='cobalt patch ') as directory: - root = Path(directory) - headers, sources = root / 'headers', root / 'sources' - output, bundle = root / 'output', root / 'bundle' - names = {'boost/cobalt/io/endpoint.hpp': headers, - 'libs/cobalt/src/io/endpoint.cpp': sources} - manifest = {'boost_version': 109200, 'files': {}} - patch = '' - for name, parent in names.items(): - original = parent / name - original.parent.mkdir(parents=True, exist_ok=True) - original.write_text('before\n') - manifest['files'][name] = { - 'before': hashlib.sha256(b'before\n').hexdigest(), - 'after': hashlib.sha256(b'after\n').hexdigest()} - patch += f'--- a/{name}\n+++ b/{name}\n@@ -1 +1 @@\n-before\n+after\n' - (headers / 'boost/version.hpp').write_text('#define BOOST_VERSION 109200\n') - bundle.mkdir() - (bundle / 'manifest.json').write_text(json.dumps(manifest)) - (bundle / 'boost-1.92.patch').write_text(patch) - prepare.prepare(headers, sources, output, bundle) - timestamps = {} - for name, parent in names.items(): - self.assertEqual((parent / name).read_text(), 'before\n') - self.assertEqual((output / name).read_text(), 'after\n') - timestamps[name] = (output / name).stat().st_mtime_ns - prepare.prepare(headers, sources, output, bundle) - for name in names: - self.assertEqual((output / name).stat().st_mtime_ns, timestamps[name]) - # A caller may select another checked Cobalt patch without copying the engine. - subprocess.run([sys.executable, str(HERE / 'prepare.py'), '--boost', str(headers), - '--sources', str(sources), '--output', str(output), - '--bundle', str(bundle)], check=True, capture_output=True) - # Either input tree changing must invalidate the complete overlay. - for name, parent in names.items(): - (parent / name).write_text('different\n') - with self.assertRaisesRegex(ValueError, 'incompatible Boost'): - prepare.prepare(headers, sources, output, bundle) - self.assertEqual((output / name).read_text(), 'after\n') - (parent / name).write_text('before\n') - stale = output / 'stale.hpp' - stale.write_text('obsolete\n') - with self.assertRaisesRegex(ValueError, 'unexpected overlay'): - prepare.prepare(headers, sources, output, bundle) - stale.unlink() - stale.symlink_to(headers, target_is_directory=True) - with self.assertRaisesRegex(ValueError, 'symlink'): - prepare.prepare(headers, sources, output, bundle) - stale.unlink() - for original in (headers, sources): - with self.assertRaisesRegex(ValueError, 'separate'): - prepare.prepare(headers, sources, original, bundle) - (headers / 'boost/version.hpp').write_text('#define BOOST_VERSION 109300\n') - with self.assertRaisesRegex(ValueError, 'requires Boost 1.92'): - prepare.prepare(headers, sources, output, bundle) - - -if __name__ == '__main__': - unittest.main() diff --git a/tools/ci/container/Dockerfile b/tools/ci/container/Dockerfile index 84bf8c6b..d216f54b 100644 --- a/tools/ci/container/Dockerfile +++ b/tools/ci/container/Dockerfile @@ -7,7 +7,7 @@ # 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 and Python, which runs -# the examples. Git applies checked overlays; Make and Perl build pinned OpenSSL, and CMake +# the examples. Git checks maintainer imports; 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. diff --git a/tools/doc/doc_comments.py b/tools/doc/doc_comments.py index 9eff3310..e73b73d0 100755 --- a/tools/doc/doc_comments.py +++ b/tools/doc/doc_comments.py @@ -59,6 +59,9 @@ from pathlib import Path from typing import Any +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import shipped_sources + Node = dict[str, Any] COMPILER_PATHS = ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH') @@ -235,6 +238,7 @@ class Checker: def __init__(self, objects: list[Node], include: Path) -> None: self.locations = Locations(objects) self.include = include.resolve() + self.imported = shipped_sources.verified(self.include.parent) self.symbols: dict[tuple[str, ...], Symbol] = {} # The name of each class, by the id of its declarations, for the members defined out # of it. @@ -249,7 +253,8 @@ def ours(self, file: str | None) -> bool: if file is None: return False try: - return Path(file).resolve().is_relative_to(self.include) + path = Path(file).resolve() + return path.is_relative_to(self.include) and path not in self.imported except OSError: return False diff --git a/tools/doc/docinfo.html b/tools/doc/docinfo.html index 581e7425..2383ab7c 100644 --- a/tools/doc/docinfo.html +++ b/tools/doc/docinfo.html @@ -35,6 +35,12 @@ word-wrap: normal; overflow-x: auto; } +/* Inline exported plots have fixed point dimensions. Fit the available column + without changing their viewBox, aspect ratio or underlying measurement data. */ +.imageblock > .content > svg { + max-width: 100%; + height: auto; +} /* Where the table of contents stands at the left of the content, from 768px, Asciidoctor leaves the content 15px of room at its right, against the table's 240px, 320px from 1280px. The content gets a gutter there taken from the table's width, whose entries keep their lines: the diff --git a/tools/doc/reference.py b/tools/doc/reference.py index ee8a6d4d..9a3e8d80 100755 --- a/tools/doc/reference.py +++ b/tools/doc/reference.py @@ -461,11 +461,16 @@ def reference(options: argparse.Namespace) -> int: output = Path(os.path.abspath(options.output)) work = output.parent work.mkdir(parents=True, exist_ok=True) - if not compile_commands.public_headers(str(root), library): + headers = compile_commands.public_headers(str(root), library) + if library == 'config': + # This public header lives outside config's headers-alone family. + # Its dedicated version test already compiles it independently. + headers.append('webcpp/version.hpp') + if not headers: raise Broken(f'{include} holds neither webcpp/{library}.hpp nor a header under ' f'webcpp/{library}/') aggregate = work / 'aggregate.cpp' - compile_commands.write_aggregate(str(root), library, str(aggregate)) + compile_commands.write_aggregate(str(root), library, str(aggregate), headers) # The library's own headers are read as the library's; every other include directory, as # Boost's, is a system one. @@ -500,7 +505,9 @@ def reference(options: argparse.Namespace) -> int: 'MACROS': macro_prefix(library), 'SOURCE_ROOT': quoted(source_root), 'DATABASE': quoted(database), - 'INPUT': quoted(include), + # Shipped imports retain their upstream reference. Only owned facades + # define WebCPP's additional reference, after hash verification. + 'INPUT': '\n - '.join(quoted(include / header) for header in headers), 'OUTPUT': quoted(written), }, override if override.is_file() else None)) diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index 87af3241..491fba49 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -99,8 +99,7 @@ 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. 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 +program commands consume shipped Asio/Cobalt sources without header overlays. No preparation executes a test program. Program-only OpenSSL and libdatachannel variants prepare their verified provider headers too, without compiling archives or publishing build proof. @@ -127,6 +126,9 @@ import sys from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import shipped_sources + # The b2 request whose compile lines the database holds: every library's programs. PROGRAMS = ['test', 'example'] @@ -139,13 +141,6 @@ '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', '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, # 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. @@ -453,7 +448,9 @@ def public_headers(root: str, library: str) -> list[str]: include = Path(root, 'libs', library, 'include') headers = [include / 'webcpp' / f'{library}.hpp'] headers += (include / 'webcpp' / library).rglob('*.hpp') - return sorted(header.relative_to(include).as_posix() for header in headers if header.is_file()) + imported = shipped_sources.verified(include.parent) + return sorted(header.relative_to(include).as_posix() for header in headers + if header.is_file() and header.resolve() not in imported) def alone_name(header: str) -> str: @@ -586,28 +583,6 @@ 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 prepare_provider_headers(root: str, request: list[str], commands: list[list[str]], lines: list[str]) -> None: """Build each program's configured provider headers without executing its test target.""" @@ -665,6 +640,18 @@ def source_path(root: str, source: str) -> str: return os.path.relpath(os.path.realpath(os.path.join(root, source)), os.path.realpath(root)) +def imported_source(root: str, source: str) -> bool: + """Apply the same verified-source boundary to ordinary and exception-off commands.""" + parts = Path(source).parts + if len(parts) <= 2 or parts[0] != 'libs': + return False + try: + imported = shipped_sources.lint_sources(Path(root, 'libs', parts[1])) + except (ValueError, OSError, KeyError, TypeError) as error: + raise Failure(str(error)) from error + return Path(root, source).resolve() in imported + + def read(root: str, target: str, lines: list[str], entries: list[dict[str, object]], seen: set[tuple[str, ...]], earlier: set[str], wasi_clang: str | None, request: list[str]) -> tuple[Units, set[str]]: @@ -685,6 +672,8 @@ def read(root: str, target: str, lines: list[str], entries: list[dict[str, objec if source.startswith(f'{BUILD_DIR}/') or not of_the_tree(root, source): continue source = source_path(root, source) + if imported_source(root, source): + continue words = [*words[:-1], source] sources.add(source) key = tuple(without_output(words)) @@ -694,7 +683,6 @@ def read(root: str, target: str, lines: list[str], entries: list[dict[str, objec 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) prepare_provider_headers(root, request, selected, lines) return units, sources @@ -804,6 +792,8 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni if source.startswith(f'{BUILD_DIR}/') or not of_the_tree(root, source): continue source = source_path(root, source) + if imported_source(root, source): + continue words = [*words[:-1], source] if first.setdefault(source, target) != target: continue @@ -818,7 +808,6 @@ def twins(root: str, target: str, chosen: dict[str, list[Aggregate]], units: Uni 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) prepare_provider_headers(root, request, selected, lines) twinned.programs |= kept - compiled for library, theirs in aggregates.items(): diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index 0190028e..b4614a96 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -146,12 +146,20 @@ if [ -d libs/beast/example/upstream ]; then fi fi +# Exempt exact imports only after their inventory and generator checks pass. +# Hand-written wrappers, functional adaptations and correction inputs remain linted. +rule 'shipped source integrity' +if ! python3 tools/shipped_sources.py . --list > "${work_directory}/imported"; then + fail 'the shipped implementation failed its integrity check' + : > "${work_directory}/imported" +fi + # Private libc declarations keep upstream text only after their pinned hashes match. verify_wasi_abi() { local profile="$1" - [ -d "tools/boost/asio-${profile}/wasi-libc" ] || return 1 + [ -d "libs/asio/src/${profile}/wasi-libc" ] || return 1 rule 'WASI ABI declaration integrity' - if python3 "tools/boost/asio-${profile}/verify.py"; then + if python3 "libs/asio/src/${profile}/verify.py"; then return 0 else fail 'the pinned wasi-libc declaration snapshot failed its integrity check' @@ -175,9 +183,9 @@ for repository in "${repositories[@]}"; do fi case "${path}" in third_party/libs/*) continue ;; - tools/boost/asio-wasip2/wasi-libc/*) + libs/asio/src/wasip2/wasi-libc/*) if [ "${wasi_abi_verified}" = true ]; then continue; fi ;; - tools/boost/asio-wasip3/wasi-libc/*) + libs/asio/src/wasip3/wasi-libc/*) if [ "${wasi_p3_abi_verified}" = true ]; then continue; fi ;; libs/beast/example/upstream/*) if [ "${beast_corpus_verified}" = true ]; then continue; fi ;; @@ -188,6 +196,28 @@ for repository in "${repositories[@]}"; do done done | sort -z -u > "${work_directory}/files" +python3 - "${work_directory}/files" "${work_directory}/imported" <<'PYTHON' +from pathlib import Path +import sys +files, imported = map(Path, sys.argv[1:]) +excluded = set(imported.read_bytes().split(b'\0')) - {b''} +files.write_bytes(b''.join(path + b'\0' for path in files.read_bytes().split(b'\0') + if path and path not in excluded)) +PYTHON + +# Only a fully verified subtree can use a directory filter; owned neighbors +# force exact-file matching and remain subject to all checks. +tidy_exclude="$(python3 - "${work_directory}/imported" <<'PYTHON' +from pathlib import Path +import sys +sys.path.insert(0, 'tools') +from shipped_sources import header_filter +paths = [path.decode() for path in Path(sys.argv[1]).read_bytes().split(b'\0') if path] +headers = [path for path in paths if Path(path).suffix in ('.h', '.hpp', '.ipp', '.cpp')] +print(header_filter(headers, Path.cwd())) +PYTHON +)" + # The files whose path matches the extended regular expression given, NUL-separated. files_matching() { while IFS= read -r -d '' file; do @@ -279,7 +309,9 @@ PYTHON # shellcheck disable=SC2329 tidy_one() { local index="$1" kind="$2" file="$3" - local arguments=(-p "${work_directory}/database") + local arguments=(-p "${work_directory}/database" + '--header-filter=(^|/)(include/webcpp|libs/[^/]+/(test|example|js))/' + "--exclude-header-filter=${tidy_exclude}") if [ "${kind}" = host ]; then arguments+=("--extra-arg=--target=${host_target}") if [ -n "${host_sysroot}" ]; then @@ -292,7 +324,7 @@ PYTHON printf '%s\n' "${status}" > "${work_directory}/${index}.status" } export -f tidy_one - export clang_tidy host_target host_sysroot work_directory + export clang_tidy host_target host_sysroot work_directory tidy_exclude # This shard's slice: the files whose position in the sorted list is K modulo N. # Interleaving keeps the slices alike, since neighbours are alike (the examples of one diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 6e4a3a4a..b2fdc307 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -239,6 +239,96 @@ def at(root: Path, path: str, text: str) -> str: return f'{path}:{lines[0]}:' +def test_import_exemption_is_verified_and_file_specific(root): + prepare(root) + import hashlib + + imported = 'libs/demo/include/webcpp/demo/imported.hpp' + # The exact pinned text has deliberately foreign formatting and no WebCPP + # notice. No adjacent file should inherit that exemption. + write(root, imported, '// Preserved upstream text\ninline int original( ){return 1;}\n') + manifest = 'libs/demo/upstream/generated.json' + write(root, manifest, json.dumps({ + 'include/webcpp/demo/imported.hpp': + hashlib.sha256((root / imported).read_bytes()).hexdigest()})) + expect_clean(lint(root)) + neighbor = 'libs/demo/include/webcpp/demo/neighbor.hpp' + write(root, neighbor, CPP + '\n// Owned neighboring header.\n') + append(root, neighbor, '// ' + EM_DASH + '\n') + expect_alone(lint(root), 'em dash', [neighbor]) + (root / neighbor).unlink() + append(root, imported, '// unreviewed change\n') + result = lint(root) + assert result.returncode == 1, result.stdout[-6000:] + assert 'lint: failed: shipped source integrity' in result.stdout, result.stdout[-6000:] + assert 'shipped source differs from maintainer output' in result.stdout + + +def test_imported_translation_unit_keeps_owned_source_diagnostics(root): + prepare(root) + import hashlib + + imported = 'libs/demo/src/original.cpp' + owned = 'libs/demo/src/owned.cpp' + write(root, imported, 'int original( ){return 1;}\n') + clean = CPP + ('\nint main() {\n const int* const value = nullptr;\n' + ' return value == nullptr ? 0 : 1;\n}\n') + write(root, owned, clean) + write(root, 'libs/demo/upstream/generated.json', json.dumps({ + 'src/original.cpp': hashlib.sha256((root / imported).read_bytes()).hexdigest()})) + append(root, 'libs/demo/test/Jamfile', + '\nwebcpp.compile original : ../src/original.cpp ;\n' + 'webcpp.compile owned : ../src/owned.cpp ;\n') + expect_clean(lint(root)) + (root / owned).write_text(clean.replace('value = nullptr', 'value = 0')) + expect_alone(lint(root), 'clang-tidy', [owned, 'modernize-use-nullptr'], spared=(imported,)) + append(root, imported, '// changed after import\n') + result = lint(root) + assert 'lint: failed: shipped source integrity' in result.stdout, result.stdout[-6000:] + + +def test_imported_inline_source_exemption_does_not_hide_owned_headers(root): + prepare(root) + import hashlib + + imported = 'libs/demo/include/webcpp/demo/upstream.ipp' + owned = 'libs/demo/include/webcpp/demo/owned.ipp' + write(root, imported, 'inline int original_inline(int value) {\n' + 'if (value) return 1; return 0; }\n') + append(root, 'libs/demo/include/webcpp/demo.hpp', + '\n#include <webcpp/demo/owned.ipp>\n#include <webcpp/demo/upstream.ipp>\n') + write(root, 'libs/demo/upstream/generated.json', json.dumps({ + 'include/webcpp/demo/upstream.ipp': + hashlib.sha256((root / imported).read_bytes()).hexdigest()})) + # The import retains implicit bool conversion and unbraced statements. + (root / owned).write_text(CPP + '\n[[nodiscard]] inline int owned_inline() { return 2; }\n') + expect_clean(lint(root)) + (root / owned).write_text(CPP + '\ninline int owned_inline(int value) {\n' + 'if (value) return 1; return 0; }\n') + expect_alone(lint(root), 'clang-tidy', [owned], spared=(imported,)) + + +def test_import_subtree_keeps_owned_inc_diagnostics(root): + prepare(root) + import hashlib + + imported = 'libs/demo/include/webcpp/demo/detail/imported/backend.ipp' + owned = 'libs/demo/include/webcpp/demo/detail/imported/owned.inc' + write(root, imported, 'inline int original_inline(int value) {\n' + 'if (value) return 1; return 0; }\n') + write(root, 'libs/demo/upstream/generated.json', json.dumps({ + 'include/webcpp/demo/detail/imported/backend.ipp': + hashlib.sha256((root / imported).read_bytes()).hexdigest()})) + append(root, 'libs/demo/include/webcpp/demo.hpp', + '\n#include <webcpp/demo/detail/imported/backend.ipp>\n' + '#include <webcpp/demo/detail/imported/owned.inc>\n') + (root / owned).write_text( + CPP + '\n[[nodiscard]] inline int* owned_pointer() { return nullptr; }\n') + expect_clean(lint(root)) + harness.replace(root / owned, 'return nullptr;', 'return 0;') + expect_alone(lint(root), 'clang-tidy', [owned, 'modernize-use-nullptr'], spared=(imported,)) + + def test_clean_tree_passes(root): prepare(root) result = lint(root) @@ -965,10 +1055,8 @@ 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. +def test_clang_tidy_uses_shipped_cobalt_sources_on_a_clean_tree(root): + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') prepare(root) append(root, 'libs/demo/test/Jamfile', 'webcpp.run cobalt : cobalt.cpp : <library>/webcpp//boost_cobalt : wasip3 ;\n') @@ -976,24 +1064,20 @@ def test_clang_tidy_prepares_cobalt_wrappers_on_a_clean_tree(root): '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) + harness.link_wasi_tools(root) + request = ['toolset=clang-wasip3', 'libs/demo/test//cobalt'] + completed = harness.run_b2(root, '-n', '-a', *request) + harness.expect(completed, True) + entries = [] + compile_commands.read(str(root), 'wasip3', completed.stdout.splitlines(), entries, + set(), set(), wasi_sdk_tool('clang++'), request) + assert any('/libs/asio/src/wasip3/waitable.cpp' in entry['file'] for entry in entries) + # Imported source is verified separately; the database keeps hand-written + # bridges and the user program. It must never manufacture an include tree. + assert not any('/libs/cobalt/src/wasm/' in entry['file'] for entry in entries) + assert not any('boost-cobalt-' in ' '.join(entry['arguments']) or + 'boost-asio-' in ' '.join(entry['arguments']) for entry in entries) + assert not (root / 'bin/boost-cobalt-wasip3').exists() # Preparing lint inputs must not execute the deliberately failing program. assert not list((root / 'bin/libs/demo/test').rglob('cobalt.run')) @@ -2322,13 +2406,31 @@ def test_beast_corpus_is_verified_before_excluding_upstream_style(root): expect_alone(lint(root), 'em dash', [adapted + ':1:']) +def test_cobalt_corpus_is_verified_before_excluding_upstream_style(root): + prepare(root) + corpus = 'libs/cobalt/test/applications/upstream/original.cpp' + verifier = 'libs/cobalt/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/cobalt/example/notes.txt' + write(root, adapted, EM_DASH + '\n') + expect_alone(lint(root), 'em dash', [adapted + ':1:']) + + def check_wasi_abi_style_exemption(root, profile): prepare(root) - 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 / f'tools/boost/asio-{profile}/verify_test.py').unlink(missing_ok=True) + snapshot = f'libs/asio/src/{profile}/wasi-libc/descriptor.h' + verifier = f'libs/asio/src/{profile}/verify.py' + # The real verifiers have independent integrity regression coverage. write(root, snapshot, '// upstream text ' + EM_DASH + '\n') write(root, verifier, HASH + '\nimport sys\n\nsys.exit(0)\n') expect_clean(lint(root)) @@ -2337,7 +2439,7 @@ def check_wasi_abi_style_exemption(root, profile): 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 = f'tools/boost/asio-{profile}/notes.txt' + bridge = f'libs/asio/src/{profile}/notes.txt' write(root, bridge, EM_DASH + '\n') expect_alone(lint(root), 'em dash', [bridge + ':1:']) @@ -2351,10 +2453,15 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): CASES = [ + test_imported_translation_unit_keeps_owned_source_diagnostics, + test_import_exemption_is_verified_and_file_specific, + test_imported_inline_source_exemption_does_not_hide_owned_headers, + test_import_subtree_keeps_owned_inc_diagnostics, 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, + test_cobalt_corpus_is_verified_before_excluding_upstream_style, test_clean_tree_passes, test_no_library_passes, test_a_user_config_the_environment_names_is_read, @@ -2378,7 +2485,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_clang_tidy_reads_a_program_of_javascript_exceptions, test_a_dependency_s_warnings_are_not_ours, test_a_compiled_boost_library_s_sources_are_not_analysed, - test_clang_tidy_prepares_cobalt_wrappers_on_a_clean_tree, + test_clang_tidy_uses_shipped_cobalt_sources_on_a_clean_tree, test_clang_tidy_refuses_a_throw_on_each_target_without_exceptions, test_a_native_header_that_needs_no_exceptions_has_its_twin, test_a_library_webcpp_does_not_build_missing_is_named, diff --git a/tools/node-test/include/webcpp/test/asyncify_watch.hpp b/tools/node-test/include/webcpp/test/asyncify_watch.hpp new file mode 100644 index 00000000..192d246c --- /dev/null +++ b/tools/node-test/include/webcpp/test/asyncify_watch.hpp @@ -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) + +#ifndef WEBCPP_TEST_ASIO_ASYNCIFY_WATCH_HPP +#define WEBCPP_TEST_ASIO_ASYNCIFY_WATCH_HPP + +#include <emscripten/em_asm.h> +#include <emscripten/em_js.h> +#include <boost/core/lightweight_test.hpp> + +#include <cstddef> +#include <iostream> +#include <string_view> + +EM_JS_DEPS(webcpp_test_asio_asyncify_stack, "$Asyncify,$doPollAsync"); + +// Watches every unwind from here on: when one stops, the bytes it wrote are its data's position +// less the stack's start, which is its limit less Asyncify's stack size. It reads Emscripten's +// private runtime, which may change: a reading that finds no unwind, or no byte written, fails. +// Count blocking polls too: an expired C++ timer can finish in poll_one, measuring only the +// initial nonblocking poll's shorter path while still reporting an unwind. +// clang-format off +EM_JS(void, test_watch_unwinds, (), { + const watch = {deepest : 0, unwinds : 0, waits : 0}; + globalThis.webcppAsyncifyWatch = watch; + const poll = doPollAsync; + doPollAsync = function(fds, nfds, timeout) { + if (timeout !== 0) { + ++watch.waits; + } + return poll(fds, nfds, timeout); + }; + const stop = Asyncify.maybeStopUnwind; + Asyncify.maybeStopUnwind = function() { + const data = Asyncify.currData; + if (data && Asyncify.state === Asyncify.State.Unwinding && !Asyncify.exportCallStack.length) { + const start = HEAPU32[(data + 4) >> 2] - Asyncify.StackSize; + watch.deepest = Math.max(watch.deepest, HEAPU32[data >> 2] - start); + ++watch.unwinds; + } + return stop.call(Asyncify); + }; +}); +// clang-format on + +namespace webcpp::test { + +/** The unwinds seen since the last reset, and the stack Asyncify saves each in. */ +struct unwinds { + static void reset() { + EM_ASM({ + globalThis.webcppAsyncifyWatch.deepest = 0; + globalThis.webcppAsyncifyWatch.unwinds = 0; + globalThis.webcppAsyncifyWatch.waits = 0; + }); + } + + /** The bytes the deepest unwind since the last reset wrote. */ + static std::size_t deepest() { + return static_cast<std::size_t>( + EM_ASM_INT({ return globalThis.webcppAsyncifyWatch.deepest; })); + } + + static std::size_t count() { + return static_cast<std::size_t>( + EM_ASM_INT({ return globalThis.webcppAsyncifyWatch.unwinds; })); + } + + /** Polls that can wait, excluding the initial nonblocking reactor poll. */ + static std::size_t waits() { + return static_cast<std::size_t>( + EM_ASM_INT({ return globalThis.webcppAsyncifyWatch.waits; })); + } + + /** ASYNCIFY_STACK_SIZE, as the program was linked with it. */ + static std::size_t stack_size() { + return static_cast<std::size_t>(EM_ASM_INT({ return Asyncify.StackSize; })); + } +}; + +/** + Measures the unwinds of one path, which call makes on a fresh io_context, and checks that the + deepest leaves half of the stack. + + @param path What call does, as printed. + @param call Runs the io_context through the path. + @param waits Whether the path must reach a blocking reactor poll. +*/ +template <class Call> +void measure(std::string_view path, Call call, bool waits = true) { + unwinds::reset(); + call(); + const std::size_t deepest = unwinds::deepest(); + std::cout << path << ": " << deepest << " bytes of " << unwinds::stack_size() << '\n'; + if (waits) { + BOOST_TEST_GE(unwinds::waits(), 1U); + } + BOOST_TEST_GE(unwinds::count(), 1U); + BOOST_TEST_GT(deepest, 0U); + BOOST_TEST_LE(2 * deepest, unwinds::stack_size()); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_ASIO_ASYNCIFY_WATCH_HPP diff --git a/tools/node-test/include/webcpp/test/browser_values.hpp b/tools/node-test/include/webcpp/test/browser_values.hpp new file mode 100644 index 00000000..f2b6ff86 --- /dev/null +++ b/tools/node-test/include/webcpp/test/browser_values.hpp @@ -0,0 +1,115 @@ +// 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 JavaScript values asio's browser tests use, made and observed in JavaScript. It defines +// EM_JS functions, so that one source file of a program includes it, never two. + +#ifndef WEBCPP_TEST_ASIO_BROWSER_VALUES_HPP +#define WEBCPP_TEST_ASIO_BROWSER_VALUES_HPP + +#include <emscripten/em_js.h> +#include <emscripten/val.h> + +// Emscripten's ExitStatus, which exit() throws, and the count of live Emval handles. +EM_JS_DEPS(webcpp_test_asio, "$ExitStatus,$count_emval_handles"); + +// clang-format off +EM_JS(emscripten::EM_VAL, test_event_target, (), { + return Emval.toHandle(new EventTarget()); +}); + +EM_JS(void, test_dispatch_after, (emscripten::EM_VAL target, int milliseconds, int detail), { + const object = Emval.toValue(target); + setTimeout(() => object.dispatchEvent(new CustomEvent('message', {detail})), milliseconds); +}); + +// A parameter's name is the JavaScript function's too: never a reserved word such as +// `function`, which links and then stops the program at load with a SyntaxError (measured with +// Emscripten 6.0.11). em_js_test proves every EM_JS here loads. +EM_JS(void, test_call_after, (emscripten::EM_VAL callback, int milliseconds, int value), { + const call = Emval.toValue(callback); + setTimeout(() => call(value), milliseconds); +}); + +// Calls callback times times from JavaScript, with 0, 1 and on: a C++ caller's epilogue would +// put WebAssembly's stack pointer back after each call, and hide one that a call left moved. +EM_JS(void, test_call_times, (emscripten::EM_VAL callback, int times), { + const call = Emval.toValue(callback); + for (let i = 0; i < times; ++i) { + call(i); + } +}); + +EM_JS(emscripten::EM_VAL, test_throwing_function, (), { + return Emval.toHandle(() => { + throw new Error('from JavaScript'); + }); +}); + +// A function that throws what Emscripten's runtime throws: 1, a trap's WebAssembly.RuntimeError, +// as abort() throws too; 2, 'unwind'; 3, the ExitStatus that exit() throws. +EM_JS(emscripten::EM_VAL, test_throwing_runtime, (int kind), { + return Emval.toHandle(() => { + if (kind === 1) { + throw new WebAssembly.RuntimeError('a trap'); + } + throw kind === 2 ? 'unwind' : new ExitStatus(0); + }); +}); + +// Calls callback with 0: 0 when nothing escaped it, 1 when a WebAssembly.RuntimeError did, 2 when +// something else did. +EM_JS(int, test_call_caught, (emscripten::EM_VAL callback), { + try { + Emval.toValue(callback)(0); + return 0; + } catch (error) { + return error instanceof WebAssembly.RuntimeError ? 1 : 2; + } +}); + +EM_JS(int, test_emval_handles, (), { + return count_emval_handles(); +}); + +EM_JS(emscripten::EM_VAL, test_promise_after, (int milliseconds, int value, bool reject), { + return Emval.toHandle(new Promise((resolve, fail) => + setTimeout(() => (reject ? fail(value) : resolve(value)), milliseconds))); +}); + +EM_JS(int, test_reported, (), { + return globalThis.webcppTestReported ?? 0; +}); + +EM_JS(void, test_count_reports, (), { + globalThis.webcppTestReported = 0; + globalThis.reportError = () => { ++globalThis.webcppTestReported; }; +}); +EM_JS(emscripten::EM_VAL, test_never_settles, (), { + return Emval.toHandle(new Promise(() => {})); +}); +// Tracks the exact listener functions registered on this test target. +EM_JS(int, test_listener_count, (emscripten::EM_VAL handle), { + const target = Emval.toValue(handle); + if (!target.webcppListeners) { + const listeners = new Set(); + target.webcppListeners = listeners; + const add = target.addEventListener.bind(target); + const remove = target.removeEventListener.bind(target); + target.addEventListener = (type, listener, options) => { + listeners.add(listener); + add(type, listener, options); + }; + target.removeEventListener = (type, listener, options) => { + listeners.delete(listener); + remove(type, listener, options); + }; + } + return target.webcppListeners.size; +}); +// clang-format on + +#endif // WEBCPP_TEST_ASIO_BROWSER_VALUES_HPP diff --git a/tools/node-test/include/webcpp/test/page_timeout.hpp b/tools/node-test/include/webcpp/test/page_timeout.hpp new file mode 100644 index 00000000..e95065cd --- /dev/null +++ b/tools/node-test/include/webcpp/test/page_timeout.hpp @@ -0,0 +1,88 @@ +// 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_TEST_ASIO_PAGE_TIMEOUT_HPP +#define WEBCPP_TEST_ASIO_PAGE_TIMEOUT_HPP + +#ifdef __EMSCRIPTEN__ +#include <emscripten/em_asm.h> +#endif + +namespace webcpp::test { + +#ifdef __EMSCRIPTEN__ +/** + A JavaScript setTimeout(0), armed at construction, whose running only JavaScript records, so + that a timeout that runs after its case ended touches nothing. + + Tip: when it runs is the host's: node delays a setTimeout(0) by 1 ms, a browser clamps a nested + one to 4 ms and throttles a background tab's to 1 s or more. A test asserts where it runs, at a + yield, never after how many handlers. +*/ +class page_timeout { +public: + page_timeout() + : id_(EM_ASM_INT({ + const state = {ran : false}; + globalThis.webcppTimeouts = globalThis.webcppTimeouts || []; + const id = globalThis.webcppTimeouts.push(state) - 1; + setTimeout(function() { state.ran = true; }, 0); + return id; + })) {} + + /** Whether the timeout has run. */ + [[nodiscard]] bool ran() const { + return EM_ASM_INT({ return globalThis.webcppTimeouts[$0].ran ? 1 : 0; }, id_) != 0; + } + +private: + int id_; +}; +#endif + +/** + Counts the run family's yields from its construction: every MessagePort message the page + posts, which only the yield posts in these tests. + + Tip: deterministic where a setTimeout(0) is not, since a handler that reads a new count runs + after the yield's message was delivered: the yield resumes only in its onmessage. A test that + posts MessagePort messages of its own cannot use it. Natively there is no page, and the count + stays 0. +*/ +class yield_counter { +public: + yield_counter() : start_(posted()) {} + + /** The yields since construction. */ + [[nodiscard]] int count() const { return posted() - start_; } + +private: + // Every MessagePort message posted so far, counted from the first call. + static int posted() { +#ifdef __EMSCRIPTEN__ + return EM_ASM_INT({ + if (!globalThis.webcppYieldsCounted) { + globalThis.webcppYieldsCounted = true; + globalThis.webcppYields = 0; + const post = MessagePort.prototype.postMessage; + MessagePort.prototype.postMessage = function() { + ++globalThis.webcppYields; + return post.apply(this, arguments); + }; + } + return globalThis.webcppYields; + }); +#else + return 0; +#endif + } + + int start_; +}; + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_ASIO_PAGE_TIMEOUT_HPP diff --git a/tools/openssl/test/Jamfile b/tools/openssl/test/Jamfile index f4c13340..7b3b66aa 100644 --- a/tools/openssl/test/Jamfile +++ b/tools/openssl/test/Jamfile @@ -15,22 +15,14 @@ exe tls_client_embedded : tls_client_embedded.cpp /webcpp/asio//tls : <exception-handling>off:<source>/webcpp//throw_exception ; explicit tls_client_embedded ; -exe cobalt_tls_client : cobalt_tls_client.cpp /webcpp/asio//cobalt /webcpp/asio//tls - : <exception-handling>off:<source>/webcpp//throw_exception ; +# Compatibility names resolve to the Cobalt-owned clients. +alias cobalt_tls_client : ../../../libs/cobalt/test/tls//cobalt_tls_client-program ; explicit cobalt_tls_client ; - -exe cobalt_ssl_client : cobalt_ssl_client.cpp /webcpp/asio//cobalt_ssl - : <exception-handling>off:<source>/webcpp//throw_exception ; +alias cobalt_ssl_client : ../../../libs/cobalt/test/tls//cobalt_ssl_client-program ; explicit cobalt_ssl_client ; - -exe cobalt_ssl_state : cobalt_ssl_state.cpp /webcpp/asio//cobalt_ssl - : <include>../../node-test/include - <exception-handling>off:<source>/webcpp//throw_exception ; +alias cobalt_ssl_state : ../../../libs/cobalt/test/tls//cobalt_ssl_state-program ; explicit cobalt_ssl_state ; - -exe cobalt_ssl_cancel : cobalt_ssl_cancel.cpp /webcpp/asio//cobalt_ssl - : <include>../../node-test/include - <exception-handling>off:<source>/webcpp//throw_exception ; +alias cobalt_ssl_cancel : ../../../libs/cobalt/test/tls//cobalt_ssl_cancel-program ; explicit cobalt_ssl_cancel ; # The native WebRTC backend needs worker threads and exceptions. diff --git a/tools/openssl/test/cobalt_ssl_cancel.cpp b/tools/openssl/test/cobalt_ssl_cancel.cpp deleted file mode 100644 index cfe31e3d..00000000 --- a/tools/openssl/test/cobalt_ssl_cancel.cpp +++ /dev/null @@ -1,319 +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) - -#include <webcpp/test/exit_status.hpp> - -#include <boost/asio/post.hpp> -#include <boost/asio/steady_timer.hpp> -#include <boost/cobalt/io/acceptor.hpp> -#include <boost/cobalt/io/read.hpp> -#include <boost/cobalt/io/ssl.hpp> -#include <boost/cobalt/io/write.hpp> -#include <boost/cobalt/main.hpp> -#include <boost/cobalt/op.hpp> -#include <boost/cobalt/promise.hpp> -#include <boost/cobalt/task.hpp> -#include <boost/core/lightweight_test.hpp> - -#include <poll.h> -#include <array> -#include <chrono> -#include <cstdio> -#include <cstdlib> -#include <source_location> -#include <string_view> -#include <tuple> -#include <vector> - -namespace cobalt = boost::cobalt; -namespace io = cobalt::io; -namespace asio = boost::asio; - -namespace { - -using transfer_result = std::tuple<boost::system::error_code, std::size_t>; - -void require(bool condition, std::source_location location = std::source_location::current()) { - if (!BOOST_TEST(condition)) { - static_cast<void>(std::fprintf(stderr, "Precondition failed at %s:%u\n", - location.file_name(), location.line())); - std::abort(); - } -} - -cobalt::promise<void> accept(io::acceptor& listener, io::socket& peer) { - const auto [error] = co_await cobalt::as_tuple(listener.accept(peer)); - require(!error); -} - -cobalt::promise<void> handshake(io::ssl::stream& stream) { - const auto [error] = - co_await cobalt::as_tuple(stream.handshake(asio::ssl::stream_base::server)); - require(!error && stream.secure()); -} - -struct tls_pair { - io::ssl::stream client; - io::ssl::stream peer; - cobalt::executor exec; - - tls_pair(io::ssl::context& client_context, io::ssl::context& server_context, - cobalt::executor executor) - : client(client_context, executor), - peer(server_context, executor), - exec(std::move(executor)) {} - - cobalt::task<void> connect() { - io::acceptor listener({io::tcp_v4, "127.0.0.1", 0}, exec); - auto accepted = accept(listener, peer); - const auto [error] = co_await cobalt::as_tuple(client.connect(listener.local_endpoint())); - require(!error); - co_await accepted; - auto server_handshake = handshake(peer); - const auto [handshake_error] = - co_await cobalt::as_tuple(client.handshake(asio::ssl::stream_base::client)); - require(!handshake_error && client.secure()); - co_await server_handshake; - } -}; - -cobalt::promise<transfer_result> read_transfer(io::ssl::stream& stream, io::mutable_buffer buffer, - bool composed) { - if (composed) { - co_return co_await cobalt::as_tuple(io::read(stream, buffer)); - } - co_return co_await cobalt::as_tuple(stream.read_some(buffer)); -} - -cobalt::promise<transfer_result> write_transfer(io::ssl::stream& stream, io::const_buffer buffer, - bool composed) { - if (composed) { - co_return co_await cobalt::as_tuple(io::write(stream, buffer)); - } - co_return co_await cobalt::as_tuple(stream.write_some(buffer)); -} - -cobalt::promise<boost::system::error_code> shutdown(io::ssl::stream& stream) { - const auto [error] = co_await cobalt::as_tuple(stream.shutdown()); - co_return error; -} - -cobalt::task<void> cancel_read(tls_pair& pair, bool composed) { - std::array<char, 8> data{}; - auto reading = read_transfer(pair.client, io::buffer(data), composed); - if (composed) { - const auto [error, size] = - co_await cobalt::as_tuple(io::write(pair.peer, io::buffer(std::string_view("ping")))); - require(!error && size == 4); - // Observe delivered bytes, not a guessed delay, before cancelling the remainder. - while (data[3] != 'g') { - co_await asio::post(pair.exec, cobalt::use_op); - } - require(std::string_view(data.data(), 4) == "ping"); - } else { - co_await asio::post(pair.exec, cobalt::use_op); - } - require(!reading.ready()); - std::puts("Cancelling pending TLS read"); - static_cast<void>(std::fflush(stdout)); - reading.cancel(); - const auto [error, size] = co_await reading; - BOOST_TEST(error == asio::error::operation_aborted); - BOOST_TEST_EQ(size, composed ? 4U : 0U); - BOOST_TEST(pair.client.secure()); - // Terminal cancellation ends this connection's use; it does not undo TLS negotiation. - require(static_cast<bool>(pair.client.close())); - require(static_cast<bool>(pair.peer.close())); -} - -cobalt::task<int> wait_for_blocked_write(tls_pair& pair, - const cobalt::promise<transfer_result>& writing, - const cobalt::promise<transfer_result>& 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<unsigned>(POLLERR) | - static_cast<unsigned>(POLLHUP) | - static_cast<unsigned>(POLLNVAL); - require(ready >= 0 && (static_cast<unsigned>(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<unsigned>(descriptor.revents) & failure_events) == 0); - if (ready == 0 && !writing.ready()) { - break; - } - } - } - co_return ready; -} - -cobalt::task<bool> cancel_write(tls_pair& pair, bool composed) { - require(static_cast<bool>(pair.client.set_send_buffer_size(4096))); - require(static_cast<bool>(pair.peer.set_receive_buffer_size(4096))); - const auto send_capacity = pair.client.get_send_buffer_size(); - const auto receive_capacity = pair.peer.get_receive_buffer_size(); - require(send_capacity && receive_capacity); - require(*send_capacity > 0 && *receive_capacity > 0); - std::vector<char> data(std::size_t{16} * 1024U * 1024U, 'x'); - require(static_cast<std::size_t>(*send_capacity) + static_cast<std::size_t>(*receive_capacity) < - data.size() / 2); - std::array<char, 1> received{}; - auto receiving = read_transfer(pair.peer, io::buffer(received), false); - std::size_t total = 0; - bool interrupted = false; - 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); - 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()); - writing.cancel(); - } - const auto [error, written] = co_await writing; - BOOST_TEST_LE(written, data.size() - total); - total += written; - if (error) { - BOOST_TEST(error == asio::error::operation_aborted); - require(cancel); - interrupted = error == asio::error::operation_aborted; - break; - } - require(written != 0); - if (cancel) { - // TCP backpressure cannot rule out an already-queued successful SSL completion. - // Do not manufacture an error or reuse a terminally cancelled connection. - std::puts("Cancellation raced a successful TLS write; retry with a fresh connection"); - break; - } - } - const auto [read_error, read_size] = co_await receiving; - require(!read_error && read_size == 1 && received[0] == 'x'); - BOOST_TEST_LT(total, data.size()); - BOOST_TEST(pair.client.secure()); - static_cast<void>(std::printf("TLS %s write: %zu plaintext bytes, interrupted=%d\n", - composed ? "composed" : "primitive", total, - static_cast<int>(interrupted))); - require(static_cast<bool>(pair.client.close())); - require(static_cast<bool>(pair.peer.close())); - co_return interrupted; -} - -cobalt::task<void> closed_state(io::ssl::stream& stream) { - if (!BOOST_TEST(!stream.secure())) { - co_return; - } - std::array<char, 1> data{}; - const auto [read_error, read_size] = - co_await cobalt::as_tuple(stream.read_some(io::buffer(data))); - BOOST_TEST(read_error == asio::error::not_connected); - BOOST_TEST_EQ(read_size, 0U); - const auto [write_error, write_size] = - co_await cobalt::as_tuple(stream.write_some(io::buffer(data))); - BOOST_TEST(write_error == asio::error::not_connected); - BOOST_TEST_EQ(write_size, 0U); - const auto [repeat_error] = co_await cobalt::as_tuple(stream.shutdown()); - BOOST_TEST(repeat_error == asio::error::no_protocol_option); -} - -cobalt::task<void> interrupted_shutdown(tls_pair& pair, bool cancel) { - auto closing = shutdown(pair.client); - std::array<char, 1> data{}; - const auto [peer_error, size] = - co_await cobalt::as_tuple(pair.peer.read_some(io::buffer(data))); - require(peer_error == asio::error::eof && size == 0); - const auto flags = static_cast<unsigned>(SSL_get_shutdown(pair.peer.native_ssl_handle())); - require((flags & SSL_RECEIVED_SHUTDOWN) != 0 && (flags & SSL_SENT_SHUTDOWN) == 0); - require(!closing.ready()); - if (cancel) { - closing.cancel(); - } else { - // Close TCP without replying with close_notify: this must not become clean TLS EOF. - require(static_cast<bool>(pair.peer.close())); - } - const auto error = co_await closing; - if (cancel) { - BOOST_TEST(error == asio::error::operation_aborted); - } else { - BOOST_TEST(error == asio::ssl::error::stream_truncated); - } - co_await closed_state(pair.client); -} - -cobalt::task<bool> run_case(tls_pair& pair, std::string_view name) { - if (name == "read_some" || name == "read") { - co_await cancel_read(pair, name == "read"); - } else if (name == "write_some" || name == "write") { - co_return co_await cancel_write(pair, name == "write"); - } else { - co_await interrupted_shutdown(pair, name == "shutdown_cancel"); - } - co_return true; -} - -} // namespace - -cobalt::main co_main(int argc, char** argv) { - if (argc != 5 && argc != 6) { - co_return 1; - } - // NOLINTNEXTLINE(readability-static-accessed-through-instance) - const auto exec = co_await cobalt::this_coro::executor; - asio::steady_timer watchdog(exec, std::chrono::seconds(10)); - watchdog.async_wait([](boost::system::error_code error) { - if (!error) { - static_cast<void>(std::fputs("FAIL TLS cancellation watchdog\n", stderr)); - std::abort(); - } - }); - io::ssl::context client(asio::ssl::context::tls_client); - io::ssl::context server(asio::ssl::context::tls_server); - client.add_certificate_authority(asio::buffer(std::string_view(argv[3]))); - client.set_verify_mode(asio::ssl::verify_peer); - server.use_certificate_chain(asio::buffer(std::string_view(argv[1]))); - server.use_private_key(asio::buffer(std::string_view(argv[2])), asio::ssl::context::pem); - const int version = std::string_view(argv[4]) == "1.2" ? TLS1_2_VERSION : TLS1_3_VERSION; - require(SSL_CTX_set_min_proto_version(client.native_handle(), version) == 1); - require(SSL_CTX_set_max_proto_version(client.native_handle(), version) == 1); - require(SSL_CTX_set_min_proto_version(server.native_handle(), version) == 1); - require(SSL_CTX_set_max_proto_version(server.native_handle(), version) == 1); - bool selected = false; - for (const auto* name : - {"read_some", "write_some", "read", "write", "shutdown_error", "shutdown_cancel"}) { - if (argc == 6 && std::string_view(name) != argv[5]) { - continue; - } - selected = true; - static_cast<void>(std::printf("BEGIN TLS %s\n", name)); - static_cast<void>(std::fflush(stdout)); - bool verified = false; - for (int attempt = 0; !verified && attempt < 8; ++attempt) { - tls_pair pair(client, server, exec); - co_await pair.connect(); - verified = co_await run_case(pair, name); - } - require(verified); - static_cast<void>(std::printf("Completed TLS %s\n", name)); - } - BOOST_TEST(selected); - watchdog.cancel(); - co_return webcpp::test::exit_status(boost::report_errors()); -} diff --git a/tools/openssl/test/cobalt_ssl_client.cpp b/tools/openssl/test/cobalt_ssl_client.cpp deleted file mode 100644 index 9b746b06..00000000 --- a/tools/openssl/test/cobalt_ssl_client.cpp +++ /dev/null @@ -1,170 +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) - -#include <webcpp/asio/tls_client_context.hpp> - -#include <boost/cobalt/io/read.hpp> -#include <boost/cobalt/io/ssl.hpp> -#include <boost/cobalt/io/write.hpp> -#include <boost/cobalt/main.hpp> -#include <boost/cobalt/op.hpp> -#include <boost/cobalt/result.hpp> -#include <boost/cobalt/task.hpp> -#include <boost/cobalt/this_coro.hpp> - -#include <array> -#include <charconv> -#include <cstdio> -#include <string_view> - -namespace cobalt = boost::cobalt; -namespace asio = boost::asio; - -namespace { - -cobalt::task<boost::system::error_code> perform_handshake(cobalt::io::ssl::stream& stream, - bool buffered) { - const auto [before_shutdown] = co_await cobalt::as_tuple(stream.shutdown()); - if (before_shutdown != asio::error::no_protocol_option) { - { - co_return asio::error::invalid_argument; - } - } - if (buffered) { - const auto [error, consumed] = co_await cobalt::as_tuple( - stream.handshake(asio::ssl::stream_base::client, cobalt::io::const_buffer{})); - if (consumed != 0) { - { - co_return asio::error::invalid_argument; - } - } - co_return error; - } - const auto [error] = - co_await cobalt::as_tuple(stream.handshake(asio::ssl::stream_base::client)); - co_return error; -} - -cobalt::task<bool> rejected_io(cobalt::io::ssl::stream& stream) { - if (stream.secure()) { - co_return false; - } - const auto [write_error, sent] = co_await cobalt::as_tuple( - stream.write_some(cobalt::io::buffer(std::string_view("must not escape")))); - if (write_error != asio::error::not_connected || sent != 0) { - co_return false; - } - std::array<char, 1> bytes{}; - const auto [read_error, received] = - co_await cobalt::as_tuple(stream.read_some(cobalt::io::buffer(bytes))); - if (read_error != asio::error::not_connected || received != 0) { - co_return false; - } - std::puts("PASS Cobalt SSL certificate rejection and blocked application I/O"); - co_return true; -} - -cobalt::task<bool> exchange(cobalt::io::ssl::stream& stream) { - const auto [repeat_error] = - co_await cobalt::as_tuple(stream.handshake(asio::ssl::stream_base::client)); - if (repeat_error != asio::error::already_started) { - co_return false; - } - constexpr std::string_view request = "ping"; - const auto [write_error, sent] = - co_await cobalt::as_tuple(cobalt::io::write(stream, cobalt::io::buffer(request))); - if (write_error || sent != request.size()) { - { - co_return false; - } - } - std::array<char, 4> response{}; - const auto [read_error, received] = - co_await cobalt::as_tuple(cobalt::io::read(stream, cobalt::io::buffer(response))); - if (read_error || received != response.size() || - std::string_view(response.data(), received) != "pong") { - co_return false; - } - const auto [shutdown_error] = co_await cobalt::as_tuple(stream.shutdown()); - if (shutdown_error || stream.secure()) { - { - co_return false; - } - } - std::puts("PASS Cobalt SSL verified TLS, encrypted ping/pong and clean shutdown"); - co_return true; -} - -} // namespace - -cobalt::main co_main(int argc, char** argv) { - if (argc != 6 && argc != 7) { - { - co_return 1; - } - } - unsigned short port = 0; - const std::string_view port_text(argv[1]); - const auto parsed = - std::from_chars(port_text.data(), port_text.data() + port_text.size(), port); - if (parsed.ec != std::errc{} || parsed.ptr != port_text.data() + port_text.size()) { - { - co_return 1; - } - } - auto prepared = std::string_view(argv[3]) == "@default" - ? webcpp::asio::make_tls_client_context() - : webcpp::asio::make_tls_client_context(argv[3]); - if (!prepared) { - const auto message = prepared.error().message(); - static_cast<void>(std::fprintf(stderr, "CA preparation: %s\n", message.c_str())); - co_return 1; - } - auto& context = *prepared; - const int version = std::string_view(argv[5]) == "1.2" ? TLS1_2_VERSION : TLS1_3_VERSION; - if (!SSL_CTX_set_min_proto_version(context.native_handle(), version) || - !SSL_CTX_set_max_proto_version(context.native_handle(), version)) { - co_return 1; - } - // NOLINTNEXTLINE(readability-static-accessed-through-instance) - const auto exec = co_await cobalt::this_coro::executor; - cobalt::io::ssl::stream stream(context, exec); - if (stream.secure()) { - co_return 1; - } - if (!stream.set_verify_callback(asio::ssl::host_name_verification(argv[2]))) { - co_return 1; - } - if (SSL_set_tlsext_host_name(stream.native_ssl_handle(), argv[2]) != 1) { - { - co_return 1; - } - } - const auto [connect_error] = - co_await cobalt::as_tuple(stream.connect({cobalt::io::tcp_v4, "127.0.0.1", port})); - if (connect_error) { - { - co_return 1; - } - } - const auto error = - co_await perform_handshake(stream, argc == 7 && std::string_view(argv[6]) == "buffered"); - const bool reject = std::string_view(argv[4]) == "reject"; - if (error) { - if (reject && SSL_get_verify_result(stream.native_ssl_handle()) != X509_V_OK) { - { - co_return (co_await rejected_io(stream)) ? 0 : 1; - } - } - co_return 1; - } - if (reject || !stream.secure()) { - { - co_return 1; - } - } - co_return (co_await exchange(stream)) ? 0 : 1; -} diff --git a/tools/openssl/test/cobalt_ssl_state.cpp b/tools/openssl/test/cobalt_ssl_state.cpp deleted file mode 100644 index 6f89f52b..00000000 --- a/tools/openssl/test/cobalt_ssl_state.cpp +++ /dev/null @@ -1,195 +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) - -#include <webcpp/test/exit_status.hpp> - -#include <boost/asio/post.hpp> -#include <boost/asio/steady_timer.hpp> -#include <boost/cobalt/io/acceptor.hpp> -#include <boost/cobalt/io/read.hpp> -#include <boost/cobalt/io/ssl.hpp> -#include <boost/cobalt/io/write.hpp> -#include <boost/cobalt/main.hpp> -#include <boost/cobalt/promise.hpp> -#include <boost/cobalt/task.hpp> -#include <boost/core/lightweight_test.hpp> - -#include <array> -#include <chrono> -#include <cstdio> -#include <cstdlib> -#include <string_view> - -namespace cobalt = boost::cobalt; -namespace io = cobalt::io; -namespace asio = boost::asio; - -namespace { - -cobalt::promise<void> serve(io::acceptor& listener, io::ssl::context& context, - const cobalt::executor& exec) { - io::stream_socket socket(exec); - const auto [accepted] = co_await cobalt::as_tuple(listener.accept(socket)); - if (!BOOST_TEST(!accepted)) { - co_return; - } - std::array<char, 5> start{}; - const auto [read_start, start_size] = - co_await cobalt::as_tuple(io::read(socket, io::buffer(start))); - BOOST_TEST(!read_start); - BOOST_TEST_EQ(start_size, start.size()); - BOOST_TEST(std::string_view(start.data(), start.size()) == "start"); - const auto [write_ready, ready_size] = - co_await cobalt::as_tuple(io::write(socket, io::buffer(std::string_view("ready")))); - BOOST_TEST(!write_ready); - BOOST_TEST_EQ(ready_size, 5U); - - // Read actual ClientHello bytes before transferring the socket into TLS. - std::array<char, 16384> hello{}; - const auto [read_hello, hello_size] = - co_await cobalt::as_tuple(socket.read_some(io::buffer(hello))); - if (!BOOST_TEST(!read_hello && hello_size != 0)) { - co_return; - } - io::ssl::stream stream(context, std::move(socket)); - auto shutdown = stream.shutdown(); - auto duplicate = stream.handshake(asio::ssl::stream_base::server); - const auto [handshake_error, consumed] = co_await cobalt::as_tuple( - stream.handshake(asio::ssl::stream_base::server, io::buffer(hello.data(), hello_size))); - if (!BOOST_TEST(!handshake_error && stream.secure())) { - co_return; - } - BOOST_TEST_EQ(consumed, hello_size); - // Operations created before the handshake must observe the current state. - const auto [duplicate_error] = co_await cobalt::as_tuple(duplicate); - BOOST_TEST(duplicate_error == asio::error::already_started); - std::array<char, 4> request{}; - const auto [read_error, received] = - co_await cobalt::as_tuple(io::read(stream, io::buffer(request))); - BOOST_TEST(!read_error); - BOOST_TEST_EQ(received, 4U); - BOOST_TEST(std::string_view(request.data(), request.size()) == "ping"); - const auto [write_error, written] = - co_await cobalt::as_tuple(io::write(stream, io::buffer(std::string_view("pong")))); - BOOST_TEST(!write_error); - BOOST_TEST_EQ(written, 4U); - const auto [shutdown_error] = co_await cobalt::as_tuple(shutdown); - BOOST_TEST(!shutdown_error); - BOOST_TEST(!stream.secure()); -} - -cobalt::task<void> starttls(io::ssl::context& client_context, io::ssl::context& server_context, - const cobalt::executor& exec) { - io::acceptor listener({io::tcp_v4, "127.0.0.1", 0}, exec); - auto server = serve(listener, server_context, exec); - io::ssl::stream stream(client_context, exec); - const auto [connected] = co_await cobalt::as_tuple(stream.connect(listener.local_endpoint())); - BOOST_TEST(!connected); - const auto [write_start, start_size] = - co_await cobalt::as_tuple(io::write(stream, io::buffer(std::string_view("start")))); - BOOST_TEST(!write_start); - BOOST_TEST_EQ(start_size, 5U); - std::array<char, 5> ready{}; - const auto [read_ready, ready_size] = - co_await cobalt::as_tuple(io::read(stream, io::buffer(ready))); - BOOST_TEST(!read_ready); - BOOST_TEST_EQ(ready_size, 5U); - BOOST_TEST(std::string_view(ready.data(), ready.size()) == "ready"); - const auto [handshake_error] = - co_await cobalt::as_tuple(stream.handshake(asio::ssl::stream_base::client)); - BOOST_TEST(!handshake_error); - BOOST_TEST(stream.secure()); - const auto [write_error, written] = - co_await cobalt::as_tuple(io::write(stream, io::buffer(std::string_view("ping")))); - BOOST_TEST(!write_error); - BOOST_TEST_EQ(written, 4U); - std::array<char, 4> response{}; - const auto [read_error, received] = - co_await cobalt::as_tuple(io::read(stream, io::buffer(response))); - BOOST_TEST(!read_error); - BOOST_TEST_EQ(received, 4U); - BOOST_TEST(std::string_view(response.data(), response.size()) == "pong"); - const auto [shutdown_error] = co_await cobalt::as_tuple(stream.shutdown()); - BOOST_TEST(!shutdown_error); - BOOST_TEST(!stream.secure()); - const auto [closed_error, closed_size] = - co_await cobalt::as_tuple(stream.write_some(io::buffer(response))); - BOOST_TEST(closed_error == asio::error::not_connected); - BOOST_TEST_EQ(closed_size, 0U); - co_await server; -} - -cobalt::promise<boost::system::error_code> handshake(io::ssl::stream& stream) { - const auto [error] = - co_await cobalt::as_tuple(stream.handshake(asio::ssl::stream_base::client)); - co_return error; -} - -cobalt::promise<void> accept(io::acceptor& listener, io::stream_socket& peer) { - const auto [error] = co_await cobalt::as_tuple(listener.accept(peer)); - BOOST_TEST(!error); -} - -cobalt::task<void> cancel_handshake(io::ssl::context& context, const cobalt::executor& exec) { - io::acceptor listener({io::tcp_v4, "127.0.0.1", 0}, exec); - io::stream_socket peer(exec); - auto accepted = accept(listener, peer); - io::ssl::stream stream(context, exec); - const auto [connected] = co_await cobalt::as_tuple(stream.connect(listener.local_endpoint())); - BOOST_TEST(!connected); - co_await accepted; - auto operation = handshake(stream); - // The peer reads ClientHello but deliberately never starts TLS. - std::array<char, 4096> hello{}; - const auto [hello_error, hello_size] = - co_await cobalt::as_tuple(peer.read_some(io::buffer(hello))); - BOOST_TEST(!hello_error); - BOOST_TEST_GT(hello_size, 0U); - BOOST_TEST(!operation.ready()); - asio::post(exec, [&operation] { operation.cancel(); }); - const auto error = co_await operation; - BOOST_TEST(error == asio::error::operation_aborted); - BOOST_TEST(!stream.secure()); - const auto [write_error, size] = co_await cobalt::as_tuple( - stream.write_some(io::buffer(std::string_view("must not escape")))); - BOOST_TEST(write_error == asio::error::not_connected); - BOOST_TEST_EQ(size, 0U); - const auto [retry] = - co_await cobalt::as_tuple(stream.handshake(asio::ssl::stream_base::client)); - BOOST_TEST(retry == asio::error::already_started); -} - -} // namespace - -cobalt::main co_main(int argc, char** argv) { - if (argc != 5) { - co_return 1; - } - // NOLINTNEXTLINE(readability-static-accessed-through-instance) - const auto exec = co_await cobalt::this_coro::executor; - asio::steady_timer watchdog(exec, std::chrono::seconds(10)); - watchdog.async_wait([](boost::system::error_code error) { - if (!error) { - std::abort(); - } - }); - io::ssl::context client(asio::ssl::context::tls_client); - io::ssl::context server(asio::ssl::context::tls_server); - client.add_certificate_authority(asio::buffer(std::string_view(argv[3]))); - client.set_verify_mode(asio::ssl::verify_peer); - server.use_certificate_chain(asio::buffer(std::string_view(argv[1]))); - server.use_private_key(asio::buffer(std::string_view(argv[2])), asio::ssl::context::pem); - const int version = std::string_view(argv[4]) == "1.2" ? TLS1_2_VERSION : TLS1_3_VERSION; - BOOST_TEST_EQ(SSL_CTX_set_min_proto_version(client.native_handle(), version), 1); - BOOST_TEST_EQ(SSL_CTX_set_max_proto_version(client.native_handle(), version), 1); - BOOST_TEST_EQ(SSL_CTX_set_min_proto_version(server.native_handle(), version), 1); - BOOST_TEST_EQ(SSL_CTX_set_max_proto_version(server.native_handle(), version), 1); - co_await starttls(client, server, exec); - co_await cancel_handshake(client, exec); - watchdog.cancel(); - std::puts("Cobalt SSL: STARTTLS, buffered ClientHello, state and cancellation checked"); - co_return webcpp::test::exit_status(boost::report_errors()); -} diff --git a/tools/openssl/test/cobalt_tls_client.cpp b/tools/openssl/test/cobalt_tls_client.cpp deleted file mode 100644 index b039e1d8..00000000 --- a/tools/openssl/test/cobalt_tls_client.cpp +++ /dev/null @@ -1,94 +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) - -#include <webcpp/asio/tls_client_context.hpp> - -#include <boost/asio/ip/tcp.hpp> -#include <boost/asio/read.hpp> -#include <boost/asio/write.hpp> -#include <boost/cobalt/main.hpp> -#include <boost/cobalt/op.hpp> -#include <boost/cobalt/result.hpp> -#include <boost/cobalt/this_coro.hpp> - -#include <array> -#include <charconv> -#include <cstdio> -#include <string_view> - -namespace cobalt = boost::cobalt; -namespace asio = boost::asio; - -cobalt::main co_main(int argc, char** argv) { - if (argc != 6) { - co_return 1; - } - unsigned short port = 0; - const std::string_view port_text(argv[1]); - const auto parsed = - std::from_chars(port_text.data(), port_text.data() + port_text.size(), port); - if (parsed.ec != std::errc{} || parsed.ptr != port_text.data() + port_text.size()) { - co_return 1; - } - auto prepared = std::string_view(argv[3]) == "@default" - ? webcpp::asio::make_tls_client_context() - : webcpp::asio::make_tls_client_context(argv[3]); - if (!prepared) { - const auto message = prepared.error().message(); - static_cast<void>(std::fprintf(stderr, "CA preparation: %s\n", message.c_str())); - co_return 1; - } - auto& context = *prepared; - const int version = std::string_view(argv[5]) == "1.2" ? TLS1_2_VERSION : TLS1_3_VERSION; - if (!SSL_CTX_set_min_proto_version(context.native_handle(), version) || - !SSL_CTX_set_max_proto_version(context.native_handle(), version)) { - co_return 1; - } - // NOLINTNEXTLINE(readability-static-accessed-through-instance) - const auto exec = co_await cobalt::this_coro::executor; - asio::ssl::stream<asio::ip::tcp::socket> stream(exec, context); - stream.set_verify_callback(asio::ssl::host_name_verification(argv[2])); - if (SSL_set_tlsext_host_name(stream.native_handle(), argv[2]) != 1) { - co_return 1; - } - const auto [connect_error] = co_await cobalt::as_tuple(stream.next_layer().async_connect( - {asio::ip::address_v4::loopback(), port}, cobalt::use_op)); - if (connect_error) { - co_return 1; - } - const auto [handshake_error] = co_await cobalt::as_tuple( - stream.async_handshake(asio::ssl::stream_base::client, cobalt::use_op)); - const bool reject = std::string_view(argv[4]) == "reject"; - if (handshake_error) { - if (reject && SSL_get_verify_result(stream.native_handle()) != X509_V_OK) { - std::puts("PASS Cobalt certificate rejection"); - co_return 0; - } - co_return 1; - } - if (reject) { - co_return 1; - } - constexpr std::string_view request = "ping"; - const auto [write_error, sent] = - co_await cobalt::as_tuple(asio::async_write(stream, asio::buffer(request), cobalt::use_op)); - if (write_error || sent != request.size()) { - co_return 1; - } - std::array<char, 4> response{}; - const auto [read_error, received] = - co_await cobalt::as_tuple(asio::async_read(stream, asio::buffer(response), cobalt::use_op)); - if (read_error || received != response.size() || - std::string_view(response.data(), received) != "pong") { - co_return 1; - } - const auto [shutdown_error] = co_await cobalt::as_tuple(stream.async_shutdown(cobalt::use_op)); - if (shutdown_error) { - co_return 1; - } - std::puts("PASS Cobalt verified TLS, ping/pong and clean shutdown"); - co_return 0; -} diff --git a/tools/openssl/test/driver.py b/tools/openssl/test/driver.py new file mode 100644 index 00000000..531bbe85 --- /dev/null +++ b/tools/openssl/test/driver.py @@ -0,0 +1,15 @@ +# 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) + + +"""Run the shared TLS peer with B2's executable argument placed last.""" +from pathlib import Path +import subprocess +import sys + +script = Path(__file__).with_name('tls.py') +subprocess.run([sys.executable, str(script), sys.argv[-1], *sys.argv[1:-1]], + check=True, timeout=170) diff --git a/tools/shipped_sources.py b/tools/shipped_sources.py new file mode 100644 index 00000000..634278f3 --- /dev/null +++ b/tools/shipped_sources.py @@ -0,0 +1,169 @@ +#!/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 shipped imports before treating their original style as third-party text.""" +from __future__ import annotations + +import argparse +import functools +import hashlib +import json +import os +import re +import subprocess +import sys +from pathlib import Path + + +def checked_file(base: Path, name: str) -> Path: + """Resolve one inventory entry without following a source symlink.""" + relative = Path(name) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError(f"unsafe shipped-source path: {name}") + path = base + for part in relative.parts: + path = path / part + if path.is_symlink(): + raise ValueError(f"unsafe shipped-source path: {name}") + if not path.resolve().is_relative_to(base.resolve()): + raise ValueError(f"shipped-source path escapes library: {name}") + if not path.is_file(): + raise ValueError(f"missing shipped-source file: {path}") + return path.resolve() + + +@functools.lru_cache(maxsize=None) +def verified(library: Path) -> frozenset[Path]: + """Return verified generated paths; an absent manifest grants no exemption.""" + library = library.resolve() + manifest = library / "upstream/generated.json" + if not manifest.is_file(): + return frozenset() + entries = json.loads(manifest.read_text()) + if not isinstance(entries, dict) or not entries: + raise ValueError(f"empty or invalid shipped-source manifest: {manifest}") + result = set() + for name, expected in entries.items(): + path = checked_file(library, name) + if hashlib.sha256(path.read_bytes()).hexdigest() != expected: + raise ValueError(f"shipped source differs from maintainer output: {path}") + result.add(path) + return frozenset(result) + + +def check_generator(script: Path, *arguments: str) -> None: + """Check maintainer output without writing files or granting directory exemptions.""" + try: + result = subprocess.run( + [sys.executable, str(script), *arguments], capture_output=True, text=True, + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, timeout=60, check=False) + except subprocess.TimeoutExpired as error: + raise ValueError(f"shipped-source check timed out: {script}") from error + if result.returncode != 0: + raise ValueError(f"shipped-source check failed: {script}\n" + + (result.stdout + result.stderr).strip()) + + +@functools.lru_cache(maxsize=None) +def lint_sources(library: Path) -> frozenset[Path]: + """Return exact imported lint inputs; public header discovery uses verified alone. + + Cobalt's original corpus and mechanical namespace migration retain upstream + style. Functional network/Python adaptations and adjacent owned files do not. + """ + library = library.resolve() + paths = set(verified(library)) + applications = library / "test/applications" + manifest = applications / "manifest.json" + if library.name != "cobalt" or not manifest.is_file(): + return frozenset(paths) + check_generator(applications / "inventory.py") + inventory = json.loads(manifest.read_text()) + originals = inventory["applications"] + inventory["benchmarks"] + for entry in originals + inventory["supporting_files"]: + paths.add(checked_file(applications, "upstream/" + entry["path"])) + if (applications / "migrated").is_dir(): + check_generator(applications / "prepare.py", "--check") + for entry in originals: + paths.add(checked_file(applications, "migrated/" + entry["path"])) + extraction = applications / "spsc/extract.py" + if extraction.is_file(): + check_generator(extraction, "--check") + paths.add(checked_file(applications, "spsc/original_queue.hpp")) + return frozenset(paths) + + +def header_filter(paths: list[str], root: Path | None = None) -> str: + """Match exact verified files with a compact POSIX extended regex. + + Sharing literal prefixes avoids repeated directory alternatives. With a + checkout root, a subtree is compacted only when every C++ file in it belongs + to the verified set. Adding an owned neighbor restores exact-file matching. + """ + def alternatives(values: list[str]) -> str: + if len(values) == 1: + return re.escape(values[0]) + prefix = os.path.commonprefix(values) + if prefix: + return re.escape(prefix) + alternatives([v[len(prefix):] for v in values]) + groups: dict[str, list[str]] = {} + for value in values: + groups.setdefault(value[:1], []).append(value[1:]) + choices = [re.escape(key) + alternatives(tails) for key, tails in groups.items()] + return "(" + "|".join(choices) + ")" + + remaining = set(paths) + directories: list[str] = [] + if root is not None: + # Choose only complete import subtrees. A name outside + # the manifest is not an import, even when placed beside imported code. + cpp_suffixes = {".h", ".hpp", ".ipp", ".cpp"} + parents = {Path(name).parent.as_posix() for name in remaining} + candidates = {parent.as_posix() for name in parents + for parent in (Path(name), *Path(name).parents) + if parent.as_posix() not in (".", "libs")} + for name in sorted(candidates, key=lambda value: (value.count("/"), value)): + prefix = name + "/" + imported = {path for path in remaining if path.startswith(prefix)} + if not imported: + continue + entries = list((root / name).rglob("*")) + if any(path.is_symlink() for path in entries): + continue + actual = {path.relative_to(root).as_posix() for path in entries + if path.is_file() and path.suffix in cpp_suffixes} + if actual == imported: + directories.append(re.escape(prefix) + r".*\.(h|hpp|ipp|cpp)") + remaining.difference_update(imported) + choices = directories + ([alternatives(sorted(remaining))] if remaining else []) + return "(^|/)(" + "|".join(choices) + ")$" if choices else "^$" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("--list", action="store_true", + help="Print exact verified imported lint files, NUL-separated") + args = parser.parse_args() + root = args.root.resolve() + try: + paths = set() + for library in sorted((root / "libs").iterdir()): + if library.is_dir(): + paths.update(lint_sources(library)) + for path in sorted(paths): + if args.list: + print(path.relative_to(root).as_posix(), end="\0") + if not args.list: + print(f"Verified {len(paths)} imported lint inputs") + except (ValueError, OSError, KeyError, TypeError) as error: + parser.exit(1, str(error) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/shipped_sources_test.py b/tools/shipped_sources_test.py new file mode 100644 index 00000000..4ff08ee7 --- /dev/null +++ b/tools/shipped_sources_test.py @@ -0,0 +1,206 @@ +#!/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) + +"""Imported text retains its provenance without exempting hand-written wrappers.""" +import hashlib +import json +import re +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +import shipped_sources + +sys.path.insert(0, str(Path(__file__).parent / "lint")) +import compile_commands + + +class ShippedSourcesTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="verified import ") + self.root = Path(self.temporary.name) + self.library = self.root / "libs/demo" + self.imported = self.library / "include/webcpp/demo/detail/backend.hpp" + self.imported.parent.mkdir(parents=True) + self.imported.write_text("// upstream implementation\n") + self.owned = self.library / "include/webcpp/demo/config.hpp" + self.owned.write_text("// documented WebCPP configuration\n") + (self.library / "upstream").mkdir() + self.manifest = self.library / "upstream/generated.json" + self.manifest.write_text(json.dumps({ + self.imported.relative_to(self.library).as_posix(): + hashlib.sha256(self.imported.read_bytes()).hexdigest()})) + + def tearDown(self): + shipped_sources.verified.cache_clear() + self.temporary.cleanup() + + def test_public_aggregate_keeps_owned_headers(self): + self.assertEqual(compile_commands.public_headers(str(self.root), "demo"), + ["webcpp/demo/config.hpp"]) + + def test_tampered_import_fails_before_exemption(self): + self.imported.write_text("// different implementation\n") + with self.assertRaisesRegex(ValueError, "differs"): + compile_commands.public_headers(str(self.root), "demo") + + def test_header_filter_matches_only_exact_paths(self): + paths = [f"libs/demo/include/webcpp/demo/backend/dir{i}/file{j}.ipp" + for i in range(8) for j in range(40)] + paths += ["libs/demo/include/webcpp/demo/a.hpp", "libs/demo/include/webcpp/demo/a+.hpp"] + pattern = shipped_sources.header_filter(paths) + matcher = re.compile(pattern) + self.assertLess(len(pattern), sum(map(len, paths)) // 2) + for path in paths: + self.assertIsNotNone(matcher.search(path)) + self.assertIsNotNone(matcher.search("/tmp/tree/" + path)) + self.assertIsNone(matcher.search(path + ".other")) + self.assertIsNone(matcher.search("x" + path)) + self.assertIsNone(matcher.search("libs/demo/include/webcpp/demo/backend/owned.ipp")) + self.assertIsNone(re.search(shipped_sources.header_filter([]), "anything.hpp")) + + def test_complete_import_subtree_is_compact_but_owned_neighbors_stay_visible(self): + paths = [self.imported.relative_to(self.root).as_posix()] + compact = shipped_sources.header_filter(paths, self.root) + self.assertIn(".*", compact) + self.assertIsNotNone(re.search(compact, paths[0])) + neighbor = self.imported.with_name("owned.ipp") + neighbor.write_text("// maintained WebCPP source\n") + exact = shipped_sources.header_filter(paths, self.root) + self.assertNotIn(".*", exact) + self.assertIsNotNone(re.search(exact, paths[0])) + self.assertIsNone(re.search(exact, neighbor.relative_to(self.root).as_posix())) + self.assertIsNone(re.search(exact, self.owned.relative_to(self.root).as_posix())) + + def test_compact_filter_does_not_exempt_other_header_extensions(self): + paths = [self.imported.relative_to(self.root).as_posix()] + for extension in (".inc", ".inl", ".hxx", ".tpp", ""): + neighbor = self.imported.with_name("owned" + extension) + neighbor.write_text("// maintained header\n") + pattern = shipped_sources.header_filter(paths, self.root) + self.assertIsNone(re.search(pattern, neighbor.relative_to(self.root).as_posix())) + self.assertIsNotNone(re.search(pattern, paths[0])) + + def test_symlink_neighbor_prevents_subtree_compaction(self): + (self.imported.parent / "linked").symlink_to(self.owned.parent, + target_is_directory=True) + paths = [self.imported.relative_to(self.root).as_posix()] + pattern = shipped_sources.header_filter(paths, self.root) + self.assertNotIn(".*", pattern) + self.assertIsNotNone(re.search(pattern, paths[0])) + + def test_no_manifest_exempts_nothing(self): + self.manifest.unlink() + self.assertEqual(len(compile_commands.public_headers(str(self.root), "demo")), 2) + + def test_manifest_cannot_escape_its_library(self): + self.manifest.write_text(json.dumps({"../foreign.hpp": ""})) + with self.assertRaisesRegex(ValueError, "unsafe"): + shipped_sources.verified(self.library) + + def test_symlink_is_not_imported_source(self): + self.imported.unlink() + self.imported.symlink_to(self.owned) + with self.assertRaisesRegex(ValueError, "unsafe"): + shipped_sources.verified(self.library) + + +class CobaltLintSourcesTest(unittest.TestCase): + """Only checked upstream text and mechanical outputs leave lint's owned set.""" + + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="cobalt lint sources ") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.checkout = Path(__file__).resolve().parents[1] + self.applications = self.root / "libs/cobalt/test/applications" + original = self.checkout / "libs/cobalt/test/applications" + self.applications.mkdir(parents=True) + for name in ("upstream", "migrated"): + shutil.copytree(original / name, self.applications / name) + for name in ("manifest.json", "inventory.py", "prepare.py"): + shutil.copyfile(original / name, self.applications / name) + (self.applications / "spsc").mkdir() + for name in ("extract.py", "original_queue.hpp"): + shutil.copyfile(original / "spsc" / name, self.applications / "spsc" / name) + shutil.copyfile(self.checkout / ".clang-format", self.root / ".clang-format") + formatter = self.root / ".local/wasi-sdk/bin/clang-format" + formatter.parent.mkdir(parents=True) + formatter.symlink_to(self.checkout / ".local/wasi-sdk/bin/clang-format") + + def classify(self): + return subprocess.run( + [sys.executable, str(self.checkout / "tools/shipped_sources.py"), + str(self.root), "--list"], capture_output=True, text=True, check=False) + + def test_exact_corpus_paths_include_non_cpp_but_not_owned_neighbors(self): + neighbors = [self.applications / "migrated/example/owned.hpp", + self.applications / "network/port/http.cpp", + self.applications / "python/binding.cpp", + self.applications / "spsc/owned.hpp"] + for path in neighbors: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("// maintained implementation\n") + result = self.classify() + self.assertEqual(result.returncode, 0, result.stderr) + paths = set(result.stdout.split("\0")) + for suffix in ("upstream/example/http.cpp", "upstream/example/python.py", + "upstream/example/Jamfile", "migrated/example/http.cpp", + "spsc/original_queue.hpp"): + self.assertIn("libs/cobalt/test/applications/" + suffix, paths) + for path in neighbors: + self.assertNotIn(path.relative_to(self.root).as_posix(), paths) + + def test_changed_original_is_rejected_before_classification(self): + source = self.applications / "upstream/example/http.cpp" + source.write_text(source.read_text() + "// changed upstream body\n") + result = self.classify() + self.assertNotEqual(result.returncode, 0) + self.assertIn("source hash mismatch", result.stderr) + self.assertEqual(result.stdout, "") + + def test_changed_migration_and_updated_hash_still_fail_generator_check(self): + source = self.applications / "migrated/example/http.cpp" + source.write_text(source.read_text() + "// changed generated body\n") + mapping = self.applications / "migrated/mapping.json" + entries = json.loads(mapping.read_text()) + for entry in entries["files"]: + if entry["source"] == "example/http.cpp": + entry["migrated_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest() + mapping.write_text(json.dumps(entries)) + result = self.classify() + self.assertNotEqual(result.returncode, 0) + self.assertIn("stale namespace migration", result.stderr) + self.assertEqual(result.stdout, "") + + def test_changed_extraction_is_rejected_without_rewriting_it(self): + source = self.applications / "spsc/original_queue.hpp" + changed = source.read_text() + "// changed queue body\n" + source.write_text(changed) + result = self.classify() + self.assertNotEqual(result.returncode, 0) + self.assertIn("stale", result.stderr) + self.assertEqual(source.read_text(), changed) + self.assertEqual(result.stdout, "") + + def test_corpus_symlink_does_not_exempt_an_owned_file(self): + source = self.applications / "upstream/example/http.cpp" + owned = self.root / "owned.cpp" + owned.write_bytes(source.read_bytes()) + source.unlink() + source.symlink_to(owned) + result = self.classify() + self.assertNotEqual(result.returncode, 0) + self.assertIn("unsafe", result.stderr) + self.assertEqual(result.stdout, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test/asio_sdk_abi_test.py b/tools/test/asio_sdk_abi_test.py new file mode 100644 index 00000000..dba8982d --- /dev/null +++ b/tools/test/asio_sdk_abi_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) + +"""Verify the ABI declarations shipped with Asio, without any former build overlay.""" +from pathlib import Path +import runpy +import shutil +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class ABI(unittest.TestCase): + def test_pinned_declarations_and_sdk(self): + for profile in ('wasip2', 'wasip3'): + with self.subTest(profile=profile), tempfile.TemporaryDirectory() as temporary: + original = ROOT / 'libs/asio/src' / profile + api = runpy.run_path(str(original / 'verify.py')) + root = Path(temporary) + bundle, sdk = root / 'bundle', root / 'sdk' + shutil.copytree(original / 'wasi-libc', bundle / 'wasi-libc') + sdk.mkdir() + (sdk / 'VERSION').write_text('34.0\nwasi-libc: 2e6fb9d8ee0c\n') + api['verify'](sdk, bundle) + extra = bundle / 'wasi-libc/extra.h' + extra.write_text('// Unlisted ABI declaration.\n') + with self.assertRaisesRegex(ValueError, 'unlisted'): + api['verify_bundle'](bundle) + extra.unlink() + extra.symlink_to('wasi/poll.h') + with self.assertRaisesRegex(ValueError, 'symlink'): + api['verify_bundle'](bundle) + extra.unlink() + (sdk / 'VERSION').write_text('34.0\nwasi-libc: different\n') + with self.assertRaisesRegex(ValueError, 'revalidate'): + api['verify'](sdk, bundle) + header = bundle / 'wasi-libc/wasi/descriptor_table.h' + header.write_text(header.read_text() + '\n/* changed ABI */\n') + with self.assertRaisesRegex(ValueError, 'header changed'): + api['verify_bundle'](bundle) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test/asio_wasip3_test.py b/tools/test/asio_wasip3_test.py index f75fd181..3bd42d6a 100644 --- a/tools/test/asio_wasip3_test.py +++ b/tools/test/asio_wasip3_test.py @@ -5,71 +5,72 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Verify private WASIp3 headers and profile selection in a checkout with spaces. +"""Verify shipped WASI headers and profile selection in a checkout with spaces. These build tests need wasi-sdk but do not execute a WASI runtime. The library's wasi_core and wasi_contract programs provide runtime coverage separately. """ from pathlib import Path -import shutil import sys import harness JAM = ''' -use-project /webcpp/asio-wasip3 : ../../../tools/boost/asio-wasip3 ; webcpp.compile wasi_configuration : wasi_configuration.cpp - : <toolset>clang-wasip3:<library>/webcpp/asio-wasip3//headers ; + : <library>/webcpp/asio//asio ; ''' -SOURCE = '''#include <boost/asio/io_context.hpp> -#include <boost/asio/steady_timer.hpp> -#include <boost/asio/ip/tcp.hpp> -#include <boost/asio/ip/udp.hpp> -#if defined(__wasip3__) && !defined(_REENTRANT) && defined(BOOST_ASIO_HAS_THREADS) +SOURCE = '''#include <webcpp/asio/io_context.hpp> +#include <webcpp/asio/steady_timer.hpp> +#include <webcpp/asio/ip/tcp.hpp> +#include <webcpp/asio/ip/udp.hpp> +#if defined(__wasip3__) && !defined(_REENTRANT) && WEBCPP_ASIO_HAS_THREADS #error "single profile must disable Asio threads" #endif -#if defined(__wasip3__) && defined(_REENTRANT) && !defined(BOOST_ASIO_HAS_THREADS) +#if defined(__wasip3__) && defined(_REENTRANT) && !WEBCPP_ASIO_HAS_THREADS #error "cooperative profile must enable Asio threads" #endif void instantiate() { - boost::asio::io_context context; - boost::asio::steady_timer timer(context); - boost::asio::ip::tcp::socket tcp(context); - boost::asio::ip::udp::socket udp(context); + webcpp::asio::io_context context; + webcpp::asio::steady_timer timer(context); + webcpp::asio::ip::tcp::socket tcp(context); + webcpp::asio::ip::udp::socket udp(context); } ''' TARGET = 'libs/demo/test//wasi_configuration' -HOST_SOURCE = '''#include <boost/asio/associated_executor.hpp> -#include <boost/asio/associated_allocator.hpp> -#include <boost/asio/associated_cancellation_slot.hpp> -#include <boost/asio/async_result.hpp> -#include <boost/asio/bind_allocator.hpp> -#include <boost/asio/execution.hpp> +HOST_SOURCE = '''#include <webcpp/asio/associated_executor.hpp> +#include <webcpp/asio/associated_allocator.hpp> +#include <webcpp/asio/associated_cancellation_slot.hpp> +#include <webcpp/asio/async_result.hpp> +#include <webcpp/asio/bind_allocator.hpp> +#include <webcpp/asio/execution.hpp> void host_traits() {} ''' def fixture(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio') + harness.link_wasi_tools(root) directory = root / 'libs/demo/test' jam = directory / 'Jamfile' jam.write_text(jam.read_text() + JAM) (directory / 'wasi_configuration.cpp').write_text(SOURCE) -def test_overlay_is_wasi_only_and_precedes_stock_headers(root: Path) -> None: +def test_public_consumer_uses_shipped_headers_without_overlays(root: Path) -> None: fixture(root) - result = harness.run_b2(root, '-a', TARGET) + result = harness.run_b2(root, '-a', '-d+2', TARGET) harness.expect(result, True, '**passed**') overlay = root / 'bin/boost-asio-wasip3/include/boost/asio/detail/config.hpp' assert not overlay.exists(), result.stdout for handling in ('on', 'off'): - result = harness.run_b2(root, '-a', 'toolset=clang-wasip3', 'threading=single', + result = harness.run_b2(root, '-a', '-d+2', 'toolset=clang-wasip3', 'threading=single', f'exception-handling={handling}', TARGET) harness.expect(result, True, '**passed**') - assert '__wasip3__' in overlay.read_text() + assert not overlay.exists(), result.stdout + assert 'boost-asio-wasip3/include' not in result.stdout, result.stdout[-4000:] def test_cooperative_profile_and_missing_exception_runtime(root: Path) -> None: @@ -98,7 +99,7 @@ def test_wasip2_host_traits_without_socket_reactor(root: Path) -> None: jam = directory / 'Jamfile' jam.write_text(jam.read_text() + ''' webcpp.compile host_traits : host_traits.cpp - : <toolset>clang-wasip2:<library>/webcpp/asio-wasip3//host-headers ; + : <library>/webcpp/asio//asio ; ''') (directory / 'host_traits.cpp').write_text(HOST_SOURCE) for toolset in ('clang', 'clang-wasip2'): @@ -111,11 +112,7 @@ def test_wasip2_host_traits_without_socket_reactor(root: Path) -> None: 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.copy_integration_libraries(root, 'config', 'asio') harness.link_wasi_tools(root) harness.add_library(root, 'p2_user', '''import webcpp ; webcpp.targets wasip2 ; @@ -139,7 +136,7 @@ def test_wasip2_consumer_and_unsupported_profiles(root: Path) -> None: harness.expect(harness.run_b2(root, 'threading=multi', *options), False, 'WASIp2 supports threading=single only') # TLS/Cobalt now have real P2 runtime consumers in - # libs/asio/test/wasip2_tls_cobalt. Only unsupported profiles are refused. + # libs/cobalt/test/wasip2. Only unsupported profiles are refused. stale = root / 'unknown SDK' stale.mkdir() (stale / 'VERSION').write_text('34.0\nwasi-libc: unknown\n') @@ -148,7 +145,7 @@ def test_wasip2_consumer_and_unsupported_profiles(root: Path) -> None: harness.expect(harness.run_b2(root, *options), True) -CASES = [test_overlay_is_wasi_only_and_precedes_stock_headers, +CASES = [test_public_consumer_uses_shipped_headers_without_overlays, test_cooperative_profile_and_missing_exception_runtime, test_wasip2_host_traits_without_socket_reactor, test_wasip2_consumer_and_unsupported_profiles] diff --git a/tools/test/boost_libraries_test.py b/tools/test/boost_libraries_test.py index 0c41fa86..1817f9e1 100755 --- a/tools/test/boost_libraries_test.py +++ b/tools/test/boost_libraries_test.py @@ -21,6 +21,7 @@ from __future__ import annotations +import json import re import shlex import shutil @@ -536,78 +537,88 @@ def test_boost_locale_is_refused_without_exceptions(root: Path) -> None: COBALT_JAMFILE = ('import webcpp ;\n' 'webcpp.targets native emscripten ;\n' - 'webcpp.run coroutines : coroutines.cpp : <library>/webcpp//boost_cobalt ;\n') + 'webcpp.run coroutines : coroutines.cpp : <library>/webcpp//boost_cobalt ' + '<toolset>clang,<exception-handling>off:' + '<cxxflags>-Wno-error=coroutine-missing-unhandled-exception ;\n') -COBALT_SOURCE = r'''#if defined(__EMSCRIPTEN__) && !defined(BOOST_ASIO_DISABLE_THREADS) +COBALT_SOURCE = r'''#include <webcpp/cobalt/config.hpp> +#if defined(__EMSCRIPTEN__) && WEBCPP_ASIO_HAS_THREADS #error Cobalt must configure Asio for the browser in its usage requirements #endif -#if !defined(__EMSCRIPTEN__) && defined(BOOST_ASIO_DISABLE_THREADS) +#if !defined(__EMSCRIPTEN__) && !WEBCPP_ASIO_HAS_THREADS #error Native consumers must retain their normal thread configuration #endif -#if defined(BOOST_COBALT_SOURCE) || defined(BOOST_COBALT_IO_SOURCE) +#if defined(BOOST_COBALT_SOURCE) || defined(BOOST_COBALT_IO_SOURCE) || \ + defined(WEBCPP_COBALT_BACKEND_SOURCE) || defined(WEBCPP_COBALT_BACKEND_IO_SOURCE) #error Source-only macros must not leak into consumers #endif -#include <boost/asio/io_context.hpp> -#include <boost/asio/post.hpp> -#include <boost/asio/steady_timer.hpp> -#include <boost/cobalt/composition.hpp> -#include <boost/cobalt/io/steady_timer.hpp> -#include <boost/cobalt/op.hpp> -#include <boost/cobalt/result.hpp> -#include <boost/cobalt/promise.hpp> -#include <boost/cobalt/this_thread.hpp> +#include <webcpp/asio/io_context.hpp> +#include <webcpp/asio/post.hpp> +#include <webcpp/asio/steady_timer.hpp> +#include <webcpp/cobalt/composition.hpp> +#include <webcpp/cobalt/io/steady_timer.hpp> +#include <webcpp/cobalt/op.hpp> +#include <webcpp/cobalt/result.hpp> +#include <webcpp/cobalt/promise.hpp> +#include <webcpp/cobalt/this_thread.hpp> #include <webcpp/test/exit_status.hpp> #include <chrono> #include <cstdio> -boost::cobalt::promise<int> answer() { +webcpp::cobalt::promise<int> answer() { co_return 42; } -struct composed_wait : boost::cobalt::op<boost::system::error_code> { - boost::asio::steady_timer& timer; - explicit composed_wait(boost::asio::steady_timer& timer) : timer(timer) {} - void initiate(boost::cobalt::completion_handler<boost::system::error_code>) override { - co_return co_await timer.async_wait(boost::asio::deferred); +struct composed_wait : webcpp::cobalt::op<boost::system::error_code> { + webcpp::asio::steady_timer& timer; + explicit composed_wait(webcpp::asio::steady_timer& timer) : timer(timer) {} + void initiate(webcpp::cobalt::completion_handler<boost::system::error_code>) override { + co_return co_await timer.async_wait(webcpp::asio::deferred); } }; -boost::cobalt::promise<boost::system::error_code> wait_composed(boost::asio::steady_timer& timer) { +webcpp::cobalt::promise<boost::system::error_code> +wait_composed(webcpp::asio::steady_timer& timer) { composed_wait operation(timer); - auto [error] = co_await boost::cobalt::as_tuple(operation); + auto [error] = co_await webcpp::cobalt::as_tuple(operation); co_return error; } -boost::cobalt::promise<int> exercise(boost::asio::io_context& ctx) { +webcpp::cobalt::promise<int> exercise(webcpp::asio::io_context& ctx) { // Eager promises provide a result without moving a pending task. auto child = answer(); - auto result = co_await boost::cobalt::as_result(child); + auto result = co_await webcpp::cobalt::as_result(child); if (!result || *result != 42) co_return 1; - boost::cobalt::io::steady_timer cobalt_timer(std::chrono::milliseconds(1), + webcpp::cobalt::io::steady_timer cobalt_timer(std::chrono::milliseconds(1), ctx.get_executor()); - auto [timer_error] = co_await boost::cobalt::as_tuple(cobalt_timer.wait()); + auto [timer_error] = co_await webcpp::cobalt::as_tuple(cobalt_timer.wait()); if (timer_error) co_return 3; - boost::asio::steady_timer timer(ctx, std::chrono::hours(1)); - boost::asio::post(ctx, [&timer] { timer.cancel(); }); - auto [error] = co_await boost::cobalt::as_tuple( - timer.async_wait(boost::cobalt::use_op)); - if (error != boost::asio::error::operation_aborted) + webcpp::asio::steady_timer timer(ctx, std::chrono::hours(1)); + webcpp::asio::post(ctx, [&timer] { timer.cancel(); }); + auto [error] = co_await webcpp::cobalt::as_tuple( + timer.async_wait(webcpp::cobalt::use_op)); + if (error != webcpp::asio::error::operation_aborted) co_return 2; +#ifdef WEBCPP_TARGET_NATIVE + // Native composition cancellation is a separately reproduced upstream limitation. + co_return 42; +#else timer.expires_after(std::chrono::hours(1)); auto pending = wait_composed(timer); - boost::asio::post(ctx, [&pending] { pending.cancel(); }); + webcpp::asio::post(ctx, [&pending] { pending.cancel(); }); auto composed_error = co_await pending; - co_return composed_error == boost::asio::error::operation_aborted ? 42 : 4; + co_return composed_error == webcpp::asio::error::operation_aborted ? 42 : 4; +#endif } int main() { webcpp::test::bound(std::chrono::seconds(10)); - boost::asio::io_context ctx; - boost::cobalt::this_thread::set_executor(ctx.get_executor()); + webcpp::asio::io_context ctx; + webcpp::cobalt::this_thread::set_executor(ctx.get_executor()); auto operation = exercise(ctx); ctx.run(); bool const ok = operation.ready() && operation.get() == 42; @@ -617,41 +628,39 @@ def test_boost_locale_is_refused_without_exceptions(root: Path) -> None: ''' -def test_boost_cobalt_names_missing_or_mismatched_sources(root: Path) -> None: +def test_cobalt_consumes_shipped_sources_without_external_boost_source(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') harness.without_boost_source(root) target = '/webcpp//boost_cobalt' - harness.expect(harness.run_b2(root, '-a', target), False, - "Boost's sources", '-sBOOST_SOURCE=<dir>', '.local/boost-source') - harness.expect(harness.run_b2(root, '-a', 'libs/demo/test//pass'), True) - empty = fake_sources(root / 'no cobalt sources', 109200, with_url=False) - harness.expect(harness.run_b2(root, '-a', f'-sBOOST_SOURCE={empty}', target), False, - 'libs/cobalt/src holds no .cpp file', target) - old = with_sources_of(fake_sources(root / 'old sources', 109100), 'cobalt') - harness.expect(harness.run_b2(root, '-a', f'-sBOOST_SOURCE={old}', target), False, - "holds Boost 1.91.0's sources", 'is 1.92.0') - - -def test_boost_cobalt_omits_main_and_ssl_from_supplied_sources(root: Path) -> None: - # Poison the excluded sources: compiling either would break the application boundary. - sources = fake_sources(root / 'cobalt sources', 109200, with_url=False) - for name in ('channel.cpp', 'detail/util.cpp', 'io/sleep.cpp', 'main.cpp', 'io/ssl.cpp'): - source = sources / 'libs/cobalt/src' / name - source.parent.mkdir(parents=True, exist_ok=True) - text = '#error This source must not be compiled by boost_cobalt\n' - if name not in ('main.cpp', 'io/ssl.cpp'): - text = ('#if !defined(BOOST_COBALT_SOURCE) || !defined(BOOST_COBALT_IO_SOURCE)\n' - '#error Both source macros are required\n#endif\n') - text += 'int fixture_' + name.replace('/', '_').replace('.', '_') + ' = 0;\n' - source.write_text(text) - result = harness.run_b2(root, '-a', '-j4', '-d+2', f'-sBOOST_SOURCE={sources}', - '/webcpp//boost_cobalt') + harness.expect(harness.run_b2(root, '-a', '-j4', target), True) + assert len(list((root / 'bin').rglob('libnative-core.a'))) == 1 + # An unrelated source-tree option does not replace the shipped Cobalt inventory. + for supplied in (root / 'missing source', fake_sources(root / 'old source', 109100)): + result = harness.run_b2(root, '-a', '-n', '-d+2', f'-sBOOST_SOURCE={supplied}', target) + harness.expect(result, True) + assert 'src/native/channel.cpp' in result.stdout, result.stdout[-4000:] + assert str(supplied / 'libs/cobalt/src') not in result.stdout, result.stdout[-4000:] + + +def test_cobalt_core_omits_shipped_runner_and_ssl(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + # Poison excluded fixture sources. Linking plain core must not compile a + # runner or SSL, including when those files exist in the distribution. + for name in ('native/main.cpp', 'native/io/ssl.cpp', 'native_ssl.cpp', + 'native_ssl_transfer.cpp', 'wasm/main.cpp', 'wasm/io/ssl.cpp'): + (root / 'libs/cobalt/src' / name).write_text('#error Core compiled an optional source\n') + result = harness.run_b2(root, '-a', '-j4', '-d+2', '/webcpp//boost_cobalt') harness.expect(result, True) - compiled = set(re.findall(r'libs/cobalt/src/([a-z/_]+[.]cpp)"', result.stdout)) - assert compiled == {'channel.cpp', 'detail/util.cpp', 'io/sleep.cpp'}, compiled - assert len(list((root / 'bin').rglob('libboost_cobalt.a'))) == 1 + compiled = {name for line in result.stdout.splitlines() if ' -c ' in line + for name in re.findall(r'"libs/cobalt/(src/[^" ]+[.]cpp)"', line)} + inventory = json.loads((root / 'libs/cobalt/sources.json').read_text()) + assert compiled == set(inventory['profiles']['native']['core']), compiled + assert len(list((root / 'bin').rglob('libnative-core.a'))) == 1 + assert not list((root / 'bin').rglob('libssl.a')) def test_boost_cobalt_warns_only_for_disabled_exceptions(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') # Missing, unconditional or repeated warnings would hide or misrepresent the risk. # Dry runs exercise dependency configuration without recompiling the archive. harness.add_library(root, 'coroutines', COBALT_JAMFILE, {'coroutines.cpp': COBALT_SOURCE}) @@ -665,7 +674,7 @@ def test_boost_cobalt_warns_only_for_disabled_exceptions(root: Path) -> None: assert result.stdout.count(issue) == expected, result.stdout if expected: assert 'warning:' in result.stdout, result.stdout - assert 'pending task' in result.stdout, result.stdout + assert 'pending coroutine' in result.stdout, result.stdout assert 'libc++' in result.stdout, result.stdout assert 'exception-handling=on' in result.stdout, result.stdout unrelated = harness.run_b2(root, '-a', '-n', 'exception-handling=off', 'libs/demo/test//pass') @@ -674,7 +683,7 @@ def test_boost_cobalt_warns_only_for_disabled_exceptions(root: Path) -> None: variants = harness.run_b2(root, '-a', '-n', 'exception-handling=off', 'variant=debug,release', *targets) harness.expect(variants, True) - assert variants.stdout.count(issue) == 2, variants.stdout + assert variants.stdout.count(issue) == 1, variants.stdout # A consumer may require exceptions even in an otherwise exception-free build. forced = COBALT_JAMFILE.replace('<library>/webcpp//boost_cobalt', '<library>/webcpp//boost_cobalt <exception-handling>on') @@ -684,35 +693,28 @@ 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', +def test_native_sources_and_consumers_do_not_select_windows_overlays(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.add_library(root, 'asio_user', 'import webcpp ;\nwebcpp.targets native ;\n' 'webcpp.run context : context.cpp : <library>/webcpp/asio//asio ;\n', {'context.cpp': '#include <webcpp/asio.hpp>\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) - # 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)): + for request in ((), ('target-os=windows',)): result = harness.run_b2(root, '-a', '-n', '-d+2', *request, - 'libs/asio/test//context', 'libs/coroutines/test') + 'libs/asio_user/test', '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 + assert 'boost-asio-windows/include' not in command, command + assert 'boost-cobalt-common/include' not in command, command -def test_msvc_overlays_win_actual_header_lookup(root: Path) -> None: +def test_msvc_commands_preserve_native_header_identity(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') # 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}) @@ -751,41 +753,37 @@ def test_msvc_overlays_win_actual_header_lookup(root: Path) -> None: 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() + assert str(headers) in includes, includes + assert not any('boost-asio-windows' in path or 'boost-cobalt-common' in path + for path in includes), includes + # Reuse the emitted include directories with a native compiler: the + # no-exceptions main promise must retain the original missing hook. flags = ' '.join(f'-I\\"{path}\\"' for path in includes) - source = ('#include <boost/cobalt/main.hpp>\n' - 'static_assert(requires(boost::cobalt::detail::main_promise& promise) {\n' - ' promise.unhandled_exception();\n' - '});\n') + source = ('#include <webcpp/cobalt/main.hpp>\n' + 'template<class Promise> concept has_hook = requires(Promise& promise) {\n' + ' promise.unhandled_exception();\n};\n' + 'static_assert(!has_hook<boost::cobalt::detail::main_promise>);\n') harness.add_library(root, 'selected', 'import webcpp ;\nwebcpp.targets native ;\n' 'webcpp.compile promise : promise.cpp : <exception-handling>off ' f'<cxxflags>"{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 not any('boost-asio-windows' in word or 'boost-cobalt-common' in word + for word in words), command assert '/external:W0' in words, command 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. + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + # Native Boost retains the missing no-EH hook. Keep that known Clang + # diagnostic visible while checking thread execution and joining separately. source = r'''#include <boost/asio/post.hpp> #include <boost/cobalt/op.hpp> #include <boost/cobalt/this_coro.hpp> @@ -810,7 +808,10 @@ def test_boost_cobalt_thread_joins_without_exceptions(root: Path) -> None: harness.add_library(root, 'thread_probe', 'import webcpp ;\nwebcpp.targets native ;\n' 'webcpp.run thread : thread.cpp : <threading>multi ' - '<library>/webcpp//boost_cobalt ;\n', {'thread.cpp': source}) + '<library>/webcpp//boost_cobalt ' + '<toolset>clang,<exception-handling>off:' + '<cxxflags>-Wno-error=coroutine-missing-unhandled-exception ;\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') @@ -819,12 +820,13 @@ def test_boost_cobalt_thread_joins_without_exceptions(root: Path) -> None: def test_boost_cobalt_preserves_exception_setting(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') # A blanket exception requirement would reject a valid result-based consumer. # Build the real archive and execute eager promises and cancellation in each mode. harness.link_emsdk(root) harness.add_library(root, 'coroutines', COBALT_JAMFILE, {'coroutines.cpp': COBALT_SOURCE}) wasm = EMSCRIPTEN - count = 0 + counts = {'libnative-core.a': 0, 'libwasm-core.a': 0} for request in ((), wasm, (*wasm, 'webcpp-suspend=asyncify')): for exceptions in ('off', 'on'): result = harness.run_b2(root, '-a', '-j4', '-d+2', '--verbose-test', *request, @@ -837,18 +839,22 @@ def test_boost_cobalt_preserves_exception_setting(root: Path) -> None: if ' -c ' in line and ('coroutines.cpp' in line or '/cobalt/src/' in line)] assert any('coroutines.cpp' in line for line in compiles), result.stdout[-4000:] library_compiles = [line for line in compiles if '/cobalt/src/' in line] - assert len(library_compiles) == 24, library_compiles + profile = 'emscripten' if request else 'native' + inventory = json.loads((root / 'libs/cobalt/sources.json').read_text()) + expected = inventory['profiles'][profile]['core'] + assert len(library_compiles) == len(expected), library_compiles assert not any('/main.cpp' in line or '/io/ssl.cpp' in line for line in library_compiles), library_compiles for line in library_compiles: - assert '-DBOOST_COBALT_SOURCE=1' in line, line - assert '-DBOOST_COBALT_IO_SOURCE=1' in line, line - assert all(('-DBOOST_ASIO_DISABLE_THREADS' in line) == bool(request) - for line in compiles), compiles + prefix = 'WEBCPP_COBALT_BACKEND' if request else 'BOOST_COBALT' + assert f'-D{prefix}_SOURCE=1' in line, line + assert f'-D{prefix}_IO_SOURCE=1' in line, line + assert all('boost-cobalt-common/include' not in line for line in compiles) assert all(('-fno-exceptions' in line) == (exceptions == 'off') for line in compiles), (request, exceptions, compiles) - count += 1 - assert len(list((root / 'bin').rglob('libboost_cobalt.a'))) == count + archive = 'libwasm-core.a' if request else 'libnative-core.a' + counts[archive] += 1 + assert len(list((root / 'bin').rglob(archive))) == counts[archive] print(f'cobalt {request or ("native",)} exceptions={exceptions}: passed', flush=True) @@ -892,13 +898,13 @@ def test_boost_context_refuses_unverified_wasm(root: Path) -> None: 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_cobalt_consumes_shipped_sources_without_external_boost_source, + test_cobalt_core_omits_shipped_runner_and_ssl, 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, + test_native_sources_and_consumers_do_not_select_windows_overlays, + test_msvc_commands_preserve_native_header_identity, 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/cobalt_config_test.py b/tools/test/cobalt_config_test.py new file mode 100644 index 00000000..1ca748e6 --- /dev/null +++ b/tools/test/cobalt_config_test.py @@ -0,0 +1,110 @@ +#!/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) + +"""Require specific diagnostics from Cobalt's public configuration contract.""" +from pathlib import Path +import sys + +import harness + +CAPABILITIES = ('SOCKET_BACKEND', 'OPENSSL_BACKEND', 'BROWSER_BRIDGE', 'THREADS', + 'BROWSER_WORKERS', 'LOCAL_SOCKETS', 'SIGNALS', 'SERIAL_PORT', + 'HOST_DNS', 'REVERSE_DNS', 'PIPE_CREATION', 'POSIX_STDIO', 'POLLABLE_STDIO') + + +def fixture(root: Path, requirements: str = '') -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.add_library(root, 'consumer', f'''import webcpp ; +webcpp.targets native wasip2 wasip3 emscripten ; +webcpp.compile config : config.cpp : <library>/webcpp/cobalt//core {requirements} ; +''', {'config.cpp': '#include <webcpp/cobalt/config.hpp>\n'}) + + +def test_capabilities_cannot_be_overridden(root: Path) -> None: + fixture(root) + for capability in CAPABILITIES: + result = harness.run_b2(root, '-a', + f'define=WEBCPP_COBALT_HAS_{capability}=1', 'libs/consumer/test') + harness.expect(result, False, 'webcpp::cobalt: capability macros are derived') + + +def test_browser_requirements_name_the_missing_feature(root: Path) -> None: + fixture(root) + harness.link_emsdk(root) + for requirement, diagnostic in ( + ('SOCKET_BACKEND', 'webcpp::cobalt: raw TCP/UDP'), + ('OPENSSL', 'webcpp::cobalt: guest OpenSSL'), + ('THREADS', 'webcpp::cobalt: threads are disabled'), + ('LOCAL_SOCKETS', 'webcpp::cobalt: local sockets'), + ('SIGNALS', 'webcpp::cobalt: process signals'), + ('SERIAL_PORT', 'webcpp::cobalt: serial ports'), + ('REVERSE_DNS', 'webcpp::cobalt: reverse DNS')): + result = harness.run_b2(root, '-a', 'toolset=emscripten', + f'define=WEBCPP_COBALT_REQUIRE_{requirement}=1', 'libs/consumer/test') + harness.expect(result, False, diagnostic) + + +def test_descriptor_requirements_name_sdk_limits(root: Path) -> None: + fixture(root) + harness.link_wasi_tools(root) + for toolset, requirement, diagnostic in ( + ('clang-wasip2', 'PIPE_CREATION', 'wasi-libc does not create pipes on WASIp2'), + ('clang-wasip2', 'POSIX_STDIO', 'stdio descriptors have no nonblocking mode'), + ('clang-wasip3', 'POSIX_STDIO', 'stdio descriptors have no nonblocking mode'), + ('clang-wasip3', 'POLLABLE_STDIO', 'pollable stdio adapter requires WASIp2')): + result = harness.run_b2(root, '-a', f'toolset={toolset}', + f'define=WEBCPP_COBALT_REQUIRE_{requirement}=1', 'libs/consumer/test') + harness.expect(result, False, diagnostic) + + +def test_optional_ssl_is_explicit(root: Path) -> None: + fixture(root) + result = harness.run_b2(root, 'define=WEBCPP_COBALT_REQUIRE_OPENSSL=1', + 'libs/consumer/test') + harness.expect(result, False, 'requires /webcpp/cobalt//io_ssl or //cobalt_ssl') + + +def test_browser_ssl_header_names_its_transport_limit(root: Path) -> None: + fixture(root) + harness.link_emsdk(root) + (root / 'libs/consumer/test/config.cpp').write_text( + '#include <webcpp/cobalt/io/ssl.hpp>\n') + result = harness.run_b2(root, 'toolset=emscripten', 'libs/consumer/test') + harness.expect(result, False, 'webcpp::cobalt: guest SSL requires native/WASI OpenSSL') + + +def test_browser_socket_headers_name_the_transport_limit(root: Path) -> None: + fixture(root) + harness.link_emsdk(root) + for header in ('io.hpp', 'io/acceptor.hpp', 'io/socket.hpp', + 'io/stream_socket.hpp', 'io/datagram_socket.hpp'): + (root / 'libs/consumer/test/config.cpp').write_text( + '#include <webcpp/cobalt/' + header + '>\n') + result = harness.run_b2(root, '-a', 'toolset=emscripten', 'libs/consumer/test') + harness.expect(result, False, 'webcpp::cobalt: raw TCP/UDP requires native/WASI') + + +def test_unsupported_wasi_profiles_are_named(root: Path) -> None: + fixture(root) + harness.link_wasi_tools(root) + for toolset, diagnostic in ( + ('clang-wasip2', 'WASIp2 supports threading=single only'), + ('clang-wasip3', 'no cooperative WASIp3 C++ exception runtime')): + result = harness.run_b2(root, '-n', f'toolset={toolset}', 'threading=multi', + 'exception-handling=on', 'libs/consumer/test') + harness.expect(result, False, diagnostic) + + +CASES = [test_capabilities_cannot_be_overridden, + test_browser_requirements_name_the_missing_feature, + test_descriptor_requirements_name_sdk_limits, test_optional_ssl_is_explicit, + test_unsupported_wasi_profiles_are_named, + test_browser_ssl_header_names_its_transport_limit, + test_browser_socket_headers_name_the_transport_limit] + +if __name__ == '__main__': + sys.exit(harness.run_cases('cobalt_config_test', CASES, sys.argv[1:])) diff --git a/tools/test/cobalt_ownership_test.py b/tools/test/cobalt_ownership_test.py new file mode 100644 index 00000000..e1bc5ec1 --- /dev/null +++ b/tools/test/cobalt_ownership_test.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) + +"""Exercise the public dependency graph from isolated consumer checkouts.""" +from pathlib import Path +import sys + +import harness + + +def test_asio_builds_without_cobalt_or_openssl(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio') + harness.third_party_of_its_own(root, 'openssl', checked_out=False) + assert not (root / 'libs/cobalt').exists() + harness.add_library(root, 'consumer', '''import webcpp ; +webcpp.targets native ; +webcpp.run timer : timer.cpp : <library>/webcpp/asio//asio ; +''', {'timer.cpp': '''#include <webcpp/asio.hpp> +#include <chrono> +int main() { + webcpp::asio::io_context context; + webcpp::asio::steady_timer timer(context, std::chrono::milliseconds(1)); + bool completed = false; + timer.async_wait([&](boost::system::error_code error) { completed = !error; }); + context.run(); + return completed ? 0 : 1; +} +'''}) + result = harness.run_b2(root, '-j4', '-d+2', 'libs/consumer/test') + harness.expect(result, True, '**passed**') + compiled = [line for line in result.stdout.splitlines() if ' -c ' in line] + assert compiled, result.stdout + assert all('cobalt' not in line and 'openssl' not in line for line in compiled), compiled + assert not list((root / 'bin').rglob('libnative-core.a')) + assert not list((root / 'bin').rglob('libwasm-core.a')) + assert not list((root / 'bin').rglob('libssl.a')) + + +def test_legacy_and_canonical_runner_have_one_definition(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.add_library(root, 'consumer', '''import webcpp ; +webcpp.targets native ; +webcpp.run main : main.cpp : <library>/webcpp/asio//cobalt + <library>/webcpp/cobalt//cobalt <library>/webcpp//boost_cobalt ; +''', {'main.cpp': '''#include <webcpp/cobalt.hpp> +webcpp::cobalt::main co_main(int, char**) { co_return 0; } +'''}) + result = harness.run_b2(root, '-j4', '-d+2', 'libs/consumer/test') + harness.expect(result, True, '**passed**') + assert len(list((root / 'bin').rglob('libnative-core.a'))) == 1 + assert len(list((root / 'bin').rglob('libnative-runner.a'))) == 1 + assert not list((root / 'bin').rglob('libwasm-core.a')) + compiled = [line for line in result.stdout.splitlines() if ' -c ' in line] + assert sum('src/native/main.cpp' in line for line in compiled) == 1, compiled + assert all('boost-cobalt-' not in line for line in compiled), compiled + assert not list((root / 'bin').rglob('libssl.a')) + + +def test_native_archive_rejects_mismatched_headers(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + original = harness.boost_include() + shadow = root / 'different-boost/boost' + shadow.mkdir(parents=True) + for entry in (original / 'boost').iterdir(): + if entry.name != 'version.hpp': + (shadow / entry.name).symlink_to(entry, target_is_directory=entry.is_dir()) + version = (original / 'boost/version.hpp').read_text() + (shadow / 'version.hpp').write_text(version.replace('109200', '109300')) + config = harness.user_config(root) + harness.configure(root, harness.USING_BOOST.sub( + f'using boost : 1.93 : <include>"{shadow.parent}" ' + f'<library>"{original.parent / "lib"}" ;', config.read_text())) + result = harness.run_b2(root, '-j4', 'libs/cobalt/src//native-core') + harness.expect(result, False, 'webcpp::cobalt requires Boost 1.92.0 headers') + + +CASES = [test_asio_builds_without_cobalt_or_openssl, + test_legacy_and_canonical_runner_have_one_definition, + test_native_archive_rejects_mismatched_headers] + +if __name__ == '__main__': + sys.exit(harness.run_cases('cobalt_ownership_test', CASES, sys.argv[1:])) diff --git a/tools/test/cobalt_ssl_test.py b/tools/test/cobalt_ssl_test.py index e6cae175..749ff7c9 100644 --- a/tools/test/cobalt_ssl_test.py +++ b/tools/test/cobalt_ssl_test.py @@ -5,23 +5,24 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Check optional Cobalt SSL dependencies and private patches through B2.""" +"""Check optional shipped Cobalt SSL dependencies and maintainer provenance.""" from pathlib import Path import re import shutil +import subprocess import sys import harness -SOURCE = '''#include <boost/cobalt/io/ssl.hpp> -#include <boost/asio/io_context.hpp> -#include <boost/asio/ssl/host_name_verification.hpp> +SOURCE = '''#include <webcpp/cobalt/io/ssl.hpp> +#include <webcpp/asio/io_context.hpp> +#include <webcpp/asio/ssl/host_name_verification.hpp> int main() { - boost::asio::io_context context; - boost::cobalt::io::ssl::context tls(boost::asio::ssl::context::tls_client); - boost::cobalt::io::ssl::stream stream(tls, context.get_executor()); + webcpp::asio::io_context context; + webcpp::cobalt::io::ssl::context tls(webcpp::asio::ssl::context::tls_client); + webcpp::cobalt::io::ssl::stream stream(tls, context.get_executor()); auto verified = stream.set_verify_callback( - boost::asio::ssl::host_name_verification("localhost")); + webcpp::asio::ssl::host_name_verification("localhost")); return verified && stream.native_ssl_handle() && !stream.secure() ? 0 : 1; } ''' @@ -34,6 +35,8 @@ def test_transitive_openssl_is_unique(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.link_wasi_tools(root) harness.add_library(root, 'cobalt_ssl', JAM, {'cobalt_ssl.cpp': SOURCE}) result = harness.run_b2(root, '-n', '-a', '-d+2', 'variant=release', 'libs/cobalt_ssl/test') @@ -43,6 +46,8 @@ def test_transitive_openssl_is_unique(root: Path) -> None: def test_public_archive_in_a_path_with_spaces(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.link_wasi_tools(root) harness.add_library(root, 'cobalt_ssl', JAM, {'cobalt_ssl.cpp': SOURCE}) for target in ('clang', 'clang-wasip3'): result = harness.run_b2(root, '-j6', 'variant=release', 'toolset=' + target, @@ -52,25 +57,24 @@ def test_public_archive_in_a_path_with_spaces(root: Path) -> None: harness.expect(result, True, '**passed**') -def test_changed_ssl_source_is_refused(root: Path) -> None: +def test_changed_ssl_maintainer_input_is_refused(root: Path) -> None: source = root / 'modified Boost source' shutil.copytree(harness.boost_source() / 'libs/cobalt/src', source / 'libs/cobalt/src') (source / 'boost').mkdir() shutil.copyfile(harness.boost_source() / 'boost/version.hpp', source / 'boost/version.hpp') ssl_source = source / 'libs/cobalt/src/io/ssl.cpp' ssl_source.write_text(ssl_source.read_text() + '\n// Different upstream input.\n') - result = harness.run_b2(root, '-j6', f'-sBOOST_SOURCE={source}', - '/webcpp//boost_cobalt_io_ssl') - harness.expect(result, False, 'incompatible Boost header: libs/cobalt/src/io/ssl.cpp') + result = subprocess.run( + [sys.executable, str(harness.ROOT / 'libs/cobalt/upstream/sync.py'), + '--boost-include', str(harness.boost_include()), '--boost-source', str(source), '--check'], + text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60) + harness.expect(result, False, + 'upstream file differs from pinned Cobalt 1.92: libs/cobalt/src/io/ssl.cpp') 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.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.link_wasi_tools(root) harness.third_party_of_its_own(root, 'openssl', checked_out=False) harness.expect(harness.run_b2(root, '-n', '/webcpp//boost_cobalt'), True) for target in ('clang', 'clang-wasip2', 'clang-wasip3'): @@ -79,11 +83,12 @@ def test_ssl_is_optional_and_unsupported_targets_are_refused(root: Path) -> None '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.') + 'Cobalt SSL requires native or WASI OpenSSL; ' + 'browser TLS is managed by HTTPS/WSS.') CASES = [test_transitive_openssl_is_unique, test_public_archive_in_a_path_with_spaces, - test_changed_ssl_source_is_refused, + test_changed_ssl_maintainer_input_is_refused, test_ssl_is_optional_and_unsupported_targets_are_refused] if __name__ == '__main__': diff --git a/tools/test/cobalt_wasip3_test.py b/tools/test/cobalt_wasip3_test.py index ea59e7d0..d43e618b 100644 --- a/tools/test/cobalt_wasip3_test.py +++ b/tools/test/cobalt_wasip3_test.py @@ -5,20 +5,21 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Build an ordinary Cobalt consumer in a path with spaces; reject stale patches.""" +"""Build shipped Cobalt in a path with spaces; verify maintainer input provenance.""" from pathlib import Path import shutil +import subprocess import sys import harness -SOURCE = '''#include <boost/cobalt.hpp> -#include <boost/cobalt/io.hpp> -#include <boost/asio/io_context.hpp> +SOURCE = '''#include <webcpp/cobalt.hpp> +#include <webcpp/cobalt/io.hpp> +#include <webcpp/asio/io_context.hpp> int main() { - boost::asio::io_context ctx; - boost::cobalt::io::datagram_socket socket( - {boost::cobalt::io::udp_v4, "127.0.0.1", 0}, ctx.get_executor()); + webcpp::asio::io_context ctx; + webcpp::cobalt::io::datagram_socket socket( + {webcpp::cobalt::io::udp_v4, "127.0.0.1", 0}, ctx.get_executor()); return socket.close().has_error() ? 1 : 0; } ''' @@ -28,30 +29,38 @@ ''' -def test_archive_and_consumer_share_private_headers(root: Path) -> None: - harness.add_library(root, 'cobalt', JAM, {'cobalt.cpp': SOURCE}) +def test_archive_and_consumer_share_shipped_headers(root: Path) -> None: + harness.copy_integration_libraries(root, 'config', 'asio', 'cobalt') + harness.link_wasi_tools(root) + harness.add_library(root, 'cobalt_consumer', JAM, {'cobalt.cpp': SOURCE}) launcher = 'testing.launcher=tools/boost/asio-wasip3/run.sh' for handling in ('on', 'off'): - result = harness.run_b2(root, '-a', '-j4', 'toolset=clang-wasip3', launcher, - f'exception-handling={handling}', 'libs/cobalt/test') + result = harness.run_b2(root, '-a', '-j4', '-d+2', 'toolset=clang-wasip3', launcher, + f'exception-handling={handling}', 'libs/cobalt_consumer/test') harness.expect(result, True, '**passed**') - # The prepared headers must not affect native consumers. - harness.expect(harness.run_b2(root, '-a', '-j4', 'libs/cobalt/test'), True, '**passed**') + assert 'boost-cobalt-' not in result.stdout, result.stdout[-4000:] + assert 'boost-asio-wasip3/include' not in result.stdout, result.stdout[-4000:] + # Native selects its upstream identity implementation from the same facade. + harness.expect(harness.run_b2(root, '-a', '-j4', 'libs/cobalt_consumer/test'), + True, '**passed**') -def test_modified_upstream_source_is_refused(root: Path) -> None: +def test_modified_maintainer_input_is_refused(root: Path) -> None: source = root / 'modified Boost source' shutil.copytree(harness.boost_source() / 'libs/cobalt/src', source / 'libs/cobalt/src') (source / 'boost').mkdir() shutil.copyfile(harness.boost_source() / 'boost/version.hpp', source / 'boost/version.hpp') endpoint = source / 'libs/cobalt/src/io/endpoint.cpp' endpoint.write_text(endpoint.read_text() + '\n// Different upstream input.\n') - result = harness.run_b2(root, '-j4', 'toolset=clang-wasip3', f'-sBOOST_SOURCE={source}', - '/webcpp//boost_cobalt') - harness.expect(result, False, 'incompatible Boost header: libs/cobalt/src/io/endpoint.cpp') + result = subprocess.run( + [sys.executable, str(harness.ROOT / 'libs/cobalt/upstream/sync.py'), + '--boost-include', str(harness.boost_include()), '--boost-source', str(source), '--check'], + text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60) + harness.expect(result, False, + 'upstream file differs from pinned Cobalt 1.92: libs/cobalt/src/io/endpoint.cpp') -CASES = [test_archive_and_consumer_share_private_headers, test_modified_upstream_source_is_refused] +CASES = [test_archive_and_consumer_share_shipped_headers, test_modified_maintainer_input_is_refused] if __name__ == '__main__': sys.exit(harness.run_cases('cobalt_wasip3_test', CASES, sys.argv[1:])) diff --git a/tools/test/fixtures/native_network_identity.cpp b/tools/test/fixtures/native_network_identity.cpp new file mode 100644 index 00000000..53a59c47 --- /dev/null +++ b/tools/test/fixtures/native_network_identity.cpp @@ -0,0 +1,40 @@ +// 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) + +#ifdef WEBCPP_TEST_BOOST_FIRST +#include <boost/asio.hpp> +#include <boost/beast.hpp> +#include <boost/cobalt.hpp> +#endif + +#include <webcpp/asio.hpp> +#include <webcpp/beast.hpp> +#include <webcpp/beast/tcp_stream.hpp> +#include <webcpp/beast/websocket.hpp> +#include <webcpp/cobalt.hpp> + +#include <boost/asio.hpp> +#include <boost/beast.hpp> +#include <boost/cobalt.hpp> +#include <type_traits> + +static_assert(std::is_same_v<webcpp::asio::io_context, boost::asio::io_context>); +static_assert(std::is_same_v<webcpp::asio::steady_timer, boost::asio::steady_timer>); +static_assert(std::is_same_v<webcpp::asio::ip::tcp::socket, boost::asio::ip::tcp::socket>); +static_assert(std::is_same_v<webcpp::asio::ip::udp::socket, boost::asio::ip::udp::socket>); +static_assert(std::is_same_v<webcpp::asio::io_context::executor_type, + boost::asio::io_context::executor_type>); +static_assert(std::is_same_v<webcpp::cobalt::task<int>, boost::cobalt::task<int>>); +static_assert(std::is_same_v<webcpp::cobalt::promise<int>, boost::cobalt::promise<int>>); +static_assert(std::is_same_v<webcpp::cobalt::generator<int>, boost::cobalt::generator<int>>); +static_assert(std::is_same_v<decltype(webcpp::cobalt::use_op), decltype(boost::cobalt::use_op)>); +static_assert(std::is_same_v<webcpp::beast::tcp_stream, boost::beast::tcp_stream>); +static_assert(std::is_same_v<webcpp::beast::http::request<webcpp::beast::http::string_body>, + boost::beast::http::request<boost::beast::http::string_body>>); +static_assert(std::is_same_v<webcpp::beast::websocket::stream<webcpp::beast::tcp_stream>, + boost::beast::websocket::stream<boost::beast::tcp_stream>>); + +// This is a compile-only consumer. It must not accidentally link Cobalt's runner. diff --git a/tools/test/fixtures/native_network_runtime.cpp b/tools/test/fixtures/native_network_runtime.cpp new file mode 100644 index 00000000..3bb6a5f0 --- /dev/null +++ b/tools/test/fixtures/native_network_runtime.cpp @@ -0,0 +1,53 @@ +// 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 <webcpp/asio.hpp> +#include <webcpp/beast.hpp> + +#include <boost/asio/buffer.hpp> +#include <boost/asio/post.hpp> +#include <chrono> +#include <cstdio> +#include <string_view> + +namespace { + +bool accepts_upstream_request( + const boost::beast::http::request<boost::beast::http::string_body>& request) { + return request.method() == boost::beast::http::verb::get && request.target() == "/probe"; +} + +} // namespace + +int main() { + webcpp::asio::io_context context; + webcpp::asio::steady_timer timer(context, std::chrono::seconds(10)); + int completions = 0; + bool cancelled = false; + timer.async_wait([&](boost::system::error_code error) { + ++completions; + cancelled = error == boost::asio::error::operation_aborted; + }); + boost::asio::post(context, [&] { + if (timer.cancel() != 1) { + context.stop(); + } + }); + context.run(); // lint-run: the consumer drives timer cancellation on the native context + if (!cancelled || completions != 1) { + return 1; + } + + constexpr std::string_view wire = "GET /probe HTTP/1.1\r\nHost: example.invalid\r\n\r\n"; + webcpp::beast::http::request_parser<webcpp::beast::http::string_body> parser; + boost::system::error_code error; + const auto consumed = parser.put(boost::asio::buffer(wire), error); + if (error || consumed != wire.size() || !parser.is_done() || + !accepts_upstream_request(parser.get())) { + return 2; + } + std::puts("native consumer: Boost timer cancellation and HTTP interoperability passed"); +} diff --git a/tools/test/fixtures/portable-network/CMakeLists.txt b/tools/test/fixtures/portable-network/CMakeLists.txt new file mode 100644 index 00000000..e18def60 --- /dev/null +++ b/tools/test/fixtures/portable-network/CMakeLists.txt @@ -0,0 +1,220 @@ +# Copyright (c) 2026 WebCpp.org +# Distributed under the Boost Software License, Version 1.0. +cmake_minimum_required(VERSION 3.20) +project(webcpp_portable_network_consumer LANGUAGES CXX) + +# This consumer reads only an unpacked source tree, explicit Boost headers and +# the chosen compiler/SDK. It does not invoke B2 or modify any installed library. +set(WEBCPP_SOURCE_ROOT "" CACHE PATH "Unpacked WebCPP source root") +set(BOOST_INCLUDE_DIR "" CACHE PATH "Boost 1.92 headers") +set(WEBCPP_TARGET "native" CACHE STRING "native, wasip2, wasip3 or emscripten") +set(WEBCPP_SUSPEND "jspi" CACHE STRING "Emscripten suspension: jspi or asyncify") +set(WEBCPP_WASI_SDK "" CACHE PATH "Explicit WASI SDK directory") +set(WEBCPP_OPENSSL_PREFIX "" CACHE PATH "Explicit matching static OpenSSL provider") +set(WEBCPP_CA_INCLUDE "" CACHE PATH "Explicit embedded CA header include root") +set(WEBCPP_COBALT_EXECUTOR "any" CACHE STRING "Cobalt executor: any, io_context or custom") +set(WEBCPP_COBALT_PMR "std" CACHE STRING "Cobalt memory policy: std, none or custom") +option(WEBCPP_EXCEPTIONS "Enable C++ exceptions" ON) +option(WEBCPP_THREADS "Enable compiler pthread/cooperative ABI" OFF) +if(NOT WEBCPP_SOURCE_ROOT OR NOT BOOST_INCLUDE_DIR) + message(FATAL_ERROR "Set WEBCPP_SOURCE_ROOT and BOOST_INCLUDE_DIR explicitly") +endif() +file(STRINGS "${BOOST_INCLUDE_DIR}/boost/version.hpp" boost_version REGEX "^#define BOOST_VERSION ") +if(NOT boost_version STREQUAL "#define BOOST_VERSION 109200") + message(FATAL_ERROR "The shipped Cobalt sources require matching Boost 1.92 headers") +endif() + +add_library(consumer_configuration INTERFACE) +target_compile_features(consumer_configuration INTERFACE cxx_std_20) +target_compile_options(consumer_configuration INTERFACE -O2) +target_include_directories(consumer_configuration SYSTEM INTERFACE "${BOOST_INCLUDE_DIR}") +foreach(library config asio cobalt beast) + target_include_directories(consumer_configuration INTERFACE "${WEBCPP_SOURCE_ROOT}/libs/${library}/include") +endforeach() +target_compile_definitions(consumer_configuration INTERFACE BOOST_COBALT_NO_LIB=1) +if(WEBCPP_COBALT_EXECUTOR STREQUAL "io_context") + target_compile_definitions(consumer_configuration INTERFACE BOOST_COBALT_USE_IO_CONTEXT=1) +elseif(WEBCPP_COBALT_EXECUTOR STREQUAL "custom") + target_compile_definitions(consumer_configuration INTERFACE BOOST_COBALT_CUSTOM_EXECUTOR=1) +elseif(NOT WEBCPP_COBALT_EXECUTOR STREQUAL "any") + message(FATAL_ERROR "Unknown WEBCPP_COBALT_EXECUTOR") +endif() +if(WEBCPP_COBALT_PMR STREQUAL "none") + target_compile_definitions(consumer_configuration INTERFACE BOOST_COBALT_NO_PMR=1) +elseif(WEBCPP_COBALT_PMR STREQUAL "custom") + target_compile_definitions(consumer_configuration INTERFACE BOOST_COBALT_USE_CUSTOM_PMR=1) +elseif(NOT WEBCPP_COBALT_PMR STREQUAL "std") + message(FATAL_ERROR "Unknown WEBCPP_COBALT_PMR") +endif() +if(WEBCPP_COBALT_EXECUTOR STREQUAL "custom" OR WEBCPP_COBALT_PMR STREQUAL "custom") + target_compile_options(consumer_configuration INTERFACE + -include "${WEBCPP_SOURCE_ROOT}/consumers/consumer_config.hpp") +endif() +set(runtime_sources) +file(READ "${WEBCPP_SOURCE_ROOT}/libs/asio/sources.json" asio_contract) +foreach(kind runtime private_include) + string(JSON count LENGTH "${asio_contract}" profiles "${WEBCPP_TARGET}" "${kind}") + if(count GREATER 0) + math(EXPR last "${count} - 1") + foreach(index RANGE 0 ${last}) + string(JSON relative GET "${asio_contract}" profiles "${WEBCPP_TARGET}" "${kind}" ${index}) + set(path "${WEBCPP_SOURCE_ROOT}/libs/asio/${relative}") + if(kind STREQUAL "runtime") + list(APPEND runtime_sources "${path}") + else() + target_include_directories(consumer_configuration INTERFACE "${path}") + endif() + endforeach() + endif() +endforeach() +if(WEBCPP_TARGET MATCHES "^wasi") + if(NOT WEBCPP_WASI_SDK) + message(FATAL_ERROR "WASI requires WEBCPP_WASI_SDK") + endif() + target_compile_options(consumer_configuration INTERFACE "--target=wasm32-${WEBCPP_TARGET}") + target_link_options(consumer_configuration INTERFACE "--target=wasm32-${WEBCPP_TARGET}") + set(runtime_dir "${WEBCPP_SOURCE_ROOT}/libs/asio/src/${WEBCPP_TARGET}") + find_package(Python3 REQUIRED COMPONENTS Interpreter) + execute_process(COMMAND "${Python3_EXECUTABLE}" "${runtime_dir}/verify.py" --sdk "${WEBCPP_WASI_SDK}" + COMMAND_ERROR_IS_FATAL ANY) + if(WEBCPP_THREADS) + if(NOT WEBCPP_TARGET STREQUAL "wasip3" OR WEBCPP_EXCEPTIONS) + message(FATAL_ERROR "SDK 34 supplies cooperative threads for WASIp3 without exceptions only") + endif() + set(cooperative_sysroot "${WEBCPP_WASI_SDK}/share/wasi-sysroot/experimental-coop-threads") + target_compile_options(consumer_configuration INTERFACE "--sysroot=${cooperative_sysroot}" -pthread) + target_link_options(consumer_configuration INTERFACE "--sysroot=${cooperative_sysroot}" -pthread) + target_include_directories(consumer_configuration SYSTEM INTERFACE "${WEBCPP_WASI_SDK}/share/wasi-sysroot/include/c++/v1") + endif() + if(WEBCPP_EXCEPTIONS) + target_compile_options(consumer_configuration INTERFACE -fwasm-exceptions -mllvm -wasm-use-legacy-eh=false) + target_link_options(consumer_configuration INTERFACE -fwasm-exceptions) + target_link_libraries(consumer_configuration INTERFACE unwind) + endif() +elseif(WEBCPP_TARGET STREQUAL "emscripten") + if(WEBCPP_THREADS) + message(FATAL_ERROR "This consumer runs in Node; use the browser worker harness for pthread profiles") + endif() + target_link_options(consumer_configuration INTERFACE -lembind -sEXIT_RUNTIME=1 -sENVIRONMENT=node + -Wl,--export=emscripten_stack_get_current -Wl,--export=_emscripten_stack_restore) + if(WEBCPP_SUSPEND STREQUAL "jspi") + target_link_options(consumer_configuration INTERFACE -sJSPI) + if(WEBCPP_EXCEPTIONS) + target_compile_options(consumer_configuration INTERFACE -fwasm-exceptions) + target_link_options(consumer_configuration INTERFACE -fwasm-exceptions) + endif() + elseif(WEBCPP_SUSPEND STREQUAL "asyncify") + target_link_options(consumer_configuration INTERFACE -sASYNCIFY -sASYNCIFY_STACK_SIZE=8192) + if(WEBCPP_EXCEPTIONS) + target_compile_options(consumer_configuration INTERFACE -fexceptions) + target_link_options(consumer_configuration INTERFACE -fexceptions) + endif() + else() + message(FATAL_ERROR "Unknown WEBCPP_SUSPEND") + endif() +elseif(NOT WEBCPP_TARGET STREQUAL "native") + message(FATAL_ERROR "Unknown WEBCPP_TARGET") +elseif(WEBCPP_THREADS) + target_compile_options(consumer_configuration INTERFACE -pthread) + target_link_options(consumer_configuration INTERFACE -pthread) +endif() +if(NOT WEBCPP_EXCEPTIONS) + target_compile_options(consumer_configuration INTERFACE -fno-exceptions) + target_link_options(consumer_configuration INTERFACE -fno-exceptions) + list(APPEND runtime_sources "${WEBCPP_SOURCE_ROOT}/consumers/throw_exception.cpp") +endif() + +add_library(asio_runtime INTERFACE) +if(runtime_sources) + # Emscripten's EM_JS metadata is not an ordinary unresolved C++ symbol. + # Keep the bridge object in the final link, as a direct compiler invocation does. + add_library(asio_runtime_objects OBJECT ${runtime_sources}) + target_link_libraries(asio_runtime_objects PUBLIC consumer_configuration) + target_link_libraries(asio_runtime INTERFACE asio_runtime_objects $<TARGET_OBJECTS:asio_runtime_objects>) +endif() +target_link_libraries(asio_runtime INTERFACE consumer_configuration) +add_executable(customizations "${WEBCPP_SOURCE_ROOT}/consumers/customizations.cpp" + "${WEBCPP_SOURCE_ROOT}/consumers/peer.cpp") +target_link_libraries(customizations PRIVATE asio_runtime) +if(WEBCPP_TARGET MATCHES "^wasi") + set_target_properties(customizations PROPERTIES SUFFIX ".wasm") +elseif(WEBCPP_TARGET STREQUAL "emscripten") + set_target_properties(customizations PROPERTIES SUFFIX ".js") +endif() + +file(READ "${WEBCPP_SOURCE_ROOT}/libs/cobalt/sources.json" cobalt_contract) +function(cobalt_sources output kind) + string(JSON count LENGTH "${cobalt_contract}" profiles "${WEBCPP_TARGET}" "${kind}") + set(selected) + if(count GREATER 0) + math(EXPR last "${count} - 1") + foreach(index RANGE 0 ${last}) + string(JSON source GET "${cobalt_contract}" profiles "${WEBCPP_TARGET}" "${kind}" ${index}) + list(APPEND selected "${WEBCPP_SOURCE_ROOT}/libs/cobalt/${source}") + endforeach() + endif() + set(${output} "${selected}" PARENT_SCOPE) +endfunction() +cobalt_sources(core_sources core) +if(WEBCPP_THREADS) + cobalt_sources(thread_sources multi_add) + list(APPEND core_sources ${thread_sources}) +endif() +cobalt_sources(runner_sources runner) +add_library(cobalt_core STATIC ${core_sources}) +target_link_libraries(cobalt_core PUBLIC asio_runtime) +if(WEBCPP_TARGET STREQUAL "native") + target_compile_definitions(cobalt_core PRIVATE BOOST_COBALT_SOURCE=1 BOOST_COBALT_IO_SOURCE=1) +else() + target_compile_definitions(cobalt_core PRIVATE WEBCPP_COBALT_BACKEND_SOURCE=1 WEBCPP_COBALT_BACKEND_IO_SOURCE=1) +endif() +add_library(cobalt_runner STATIC ${runner_sources}) +target_link_libraries(cobalt_runner PUBLIC cobalt_core) +add_executable(timers "${WEBCPP_SOURCE_ROOT}/consumers/timers.cpp" + "${WEBCPP_SOURCE_ROOT}/consumers/configuration.cpp") +target_link_libraries(timers PRIVATE cobalt_runner) +if(WEBCPP_THREADS) + add_executable(threads "${WEBCPP_SOURCE_ROOT}/consumers/threads.cpp") + target_link_libraries(threads PRIVATE cobalt_core) + if(WEBCPP_TARGET MATCHES "^wasi") + set_target_properties(threads PROPERTIES SUFFIX ".wasm") + endif() +endif() +if(WEBCPP_OPENSSL_PREFIX) + if(WEBCPP_TARGET STREQUAL "emscripten" OR NOT WEBCPP_CA_INCLUDE) + message(FATAL_ERROR "Guest TLS requires native/WASI and an explicit CA include root") + endif() + cobalt_sources(ssl_sources ssl) + add_library(cobalt_ssl STATIC ${ssl_sources}) + target_link_libraries(cobalt_ssl PUBLIC cobalt_core + "${WEBCPP_OPENSSL_PREFIX}/libssl.a" "${WEBCPP_OPENSSL_PREFIX}/libcrypto.a") + target_include_directories(cobalt_ssl PUBLIC "${WEBCPP_OPENSSL_PREFIX}/include" "${WEBCPP_CA_INCLUDE}") + target_compile_definitions(cobalt_ssl PUBLIC WEBCPP_ASIO_HAS_OPENSSL=1 WEBCPP_COBALT_LINK_SSL=1) + if(WEBCPP_TARGET MATCHES "^wasi") + # These are the explicit libc support libraries of WebCPP's OpenSSL provider. + target_link_libraries(cobalt_ssl PUBLIC wasi-emulated-getpid wasi-emulated-signal + wasi-emulated-process-clocks wasi-emulated-mman) + endif() + foreach(program ssl_client ssl_state ssl_cancel) + add_executable(${program} "${WEBCPP_SOURCE_ROOT}/consumers/${program}.cpp" + "${WEBCPP_SOURCE_ROOT}/consumers/configuration.cpp") + target_include_directories(${program} PRIVATE "${WEBCPP_SOURCE_ROOT}/consumers/include") + target_link_libraries(${program} PRIVATE cobalt_runner cobalt_ssl) + if(WEBCPP_TARGET MATCHES "^wasi") + set_target_properties(${program} PROPERTIES SUFFIX ".wasm") + endif() + endforeach() +endif() +if(WEBCPP_TARGET STREQUAL "emscripten") + add_executable(browser "${WEBCPP_SOURCE_ROOT}/consumers/browser.cpp") + target_link_libraries(browser PRIVATE asio_runtime) + set_target_properties(timers browser PROPERTIES SUFFIX ".js") +else() + foreach(program network beast) + add_executable(${program} "${WEBCPP_SOURCE_ROOT}/consumers/${program}.cpp") + target_link_libraries(${program} PRIVATE asio_runtime) + endforeach() + if(WEBCPP_TARGET MATCHES "^wasi") + set_target_properties(timers network beast PROPERTIES SUFFIX ".wasm") + endif() +endif() diff --git a/tools/test/harness.py b/tools/test/harness.py index 1c4ed894..7ae9501b 100644 --- a/tools/test/harness.py +++ b/tools/test/harness.py @@ -314,6 +314,30 @@ def scratch_superproject(*fixtures: str) -> Path: return root +def copy_integration_libraries(root: Path, *names: str) -> None: + """Copy named real build integrations, without their tests or generated products. + + Most build-tool tests use only artificial libraries. Cases that exercise a + cross-library dependency opt into its actual recipe, headers and sources. + This keeps unrelated fixtures independent of the checked-out collection. + """ + for name in names: + source = ROOT / 'libs' / name + destination = root / 'libs' / name + destination.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / 'build.jam', destination / 'build.jam') + for entry in ('include', 'src', 'test/applications/upstream'): + if (source / entry).is_dir(): + shutil.copytree(source / entry, destination / entry, + ignore=built, dirs_exist_ok=True) + # Shipped imports are sources, not disposable build output. Preserve the + # exact manifest and source inventory so integrity/lint sees the same tree. + for entry in ('sources.json', 'upstream/generated.json'): + if (source / entry).is_file(): + (destination / entry).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / entry, destination / entry) + + def link_wasi_tools(root: Path) -> None: """Gives the scratch superproject root, in its .local, the wit-bindgen, the WASI WIT and the wasi-sdk that a copy leaves out: links to $WIT_BINDGEN_ROOT, the directory that holds @@ -420,6 +444,15 @@ def without_emscripten(root: Path) -> None: re.MULTILINE) +def boost_include() -> Path: + """Return the explicit Boost header directory configured for these fixtures.""" + text = user_config(ROOT).read_text() + include = re.search(r'using\s+boost\b[^;]*<include>(?:"([^"]+)"|([^;\s]+))', text) + if not include: + raise RuntimeError('configure using boost with an explicit <include> directory') + return Path(include.group(1) or include.group(2)).resolve() + + def boost_source() -> Path: """The tree of Boost's sources this checkout builds with: the one its user-config.jam names, else its .local/boost-source.""" diff --git a/tools/test/native_network_identity.py b/tools/test/native_network_identity.py new file mode 100644 index 00000000..1f3b0ee2 --- /dev/null +++ b/tools/test/native_network_identity.py @@ -0,0 +1,60 @@ +#!/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) + +"""Compile real native consumers without B2, generated overlays or a Cobalt archive.""" + +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import shlex +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +FIXTURES = Path(__file__).resolve().parent / 'fixtures' + + +def run(command: list[str], environment: dict[str, str]) -> None: + """Show and execute a bounded consumer command with its actual output.""" + print(shlex.join(command), flush=True) + subprocess.run(command, env=environment, check=True, timeout=60) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--boost-include', type=Path, required=True) + arguments = parser.parse_args() + environment = dict(os.environ) + for name in ('CPATH', 'CPLUS_INCLUDE_PATH', 'C_INCLUDE_PATH'): + environment.pop(name, None) + command = [str(arguments.compiler), '-std=c++20', '-O2', '-pthread', + '-Wall', '-Wextra', '-Werror', '-DBOOST_COBALT_NO_LIB=1', + '-isystem', str(arguments.boost_include)] + for library in ('config', 'asio', 'beast', 'cobalt'): + command += ['-I', str(ROOT / 'libs' / library / 'include')] + with tempfile.TemporaryDirectory(prefix='webcpp native consumer ') as temporary: + output = Path(temporary) + for exceptions in ('on', 'off'): + flags = [] if exceptions == 'on' else ['-fno-exceptions'] + for upstream_first in (False, True): + order = ['-DWEBCPP_TEST_BOOST_FIRST=1'] if upstream_first else [] + run(command + flags + order + ['-c', + str(FIXTURES / 'native_network_identity.cpp'), '-o', + str(output / f'identity-{exceptions}-{upstream_first}.o')], environment) + executable = output / f'runtime-{exceptions}' + run(command + flags + [str(FIXTURES / 'native_network_runtime.cpp'), + str(ROOT / 'tools/throw_exception.cpp'), '-o', str(executable)], environment) + run([str(executable)], environment) + print('native identity: 4 compilations and 2 runtime consumers passed', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index 04aa2da0..c2b41d3e 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -238,6 +238,10 @@ def test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles(root: Path) -> Non config_library.mkdir() shutil.copyfile(harness.ROOT / 'libs/config/build.jam', config_library / 'build.jam') shutil.copytree(harness.ROOT / 'libs/config/include', config_library / 'include') + harness.copy_integration_libraries(root, 'cobalt') + shutil.copytree(harness.ROOT / 'libs/cobalt/test/tls', root / 'libs/cobalt/test/tls') + for name in ('package.json', 'package-lock.json'): + shutil.copyfile(harness.ROOT / 'libs/cobalt/test' / name, root / 'libs/cobalt/test' / name) config = harness.user_config(root).read_text() for version in ('14.3', '14.5'): config += f'\nusing msvc : {version} : "{sys.executable}"' \ @@ -287,8 +291,10 @@ def test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles(root: Path) -> Non lines = [line.replace('\\', '/') for line in result.stdout.splitlines()] drivers = [line.strip() for line in lines if '/tools/drive/drive.py"' in line] for source in sources: + folder = ('libs/cobalt/test/tls' if source.startswith('cobalt_') + else 'tools/openssl/test') compiles = [line for line in lines - if ' -c ' in line and f'/test/{source}"' in line] + if ' -c ' in line and f'{folder}/{source}"' in line] for runtime in ('/MT', '/MD'): if variant == 'debug': runtime += 'd' @@ -307,7 +313,9 @@ def test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles(root: Path) -> Non links = [line for line in lines if ' link ' in line and f'"{object_path}"' in line] assert len(links) == 1, (object_path, links) - executable = object_path.removesuffix('.obj') + '.exe' + output = re.search(r'/out:"([^"]+)"', links[0], re.IGNORECASE) + assert output, links[0] + executable = output.group(1) assert any(line.endswith(f'"{executable}"') for line in drivers), drivers print(f'MSVC {version} {lane}: distinct S/M providers and fixture links verified') diff --git a/tools/test/portable_network_distribution.py b/tools/test/portable_network_distribution.py new file mode 100644 index 00000000..549c783e --- /dev/null +++ b/tools/test/portable_network_distribution.py @@ -0,0 +1,476 @@ +#!/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 and run actual consumers from an unpacked, B2-free source snapshot.""" +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import sys +import tarfile +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def run(command: list[str], environment: dict[str, str], expected: str = "", + directory: Path | None = None) -> None: + print(shlex.join(command), flush=True) + result = subprocess.run(command, env=environment, cwd=directory, check=True, timeout=240, + text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + if result.stdout: + print(result.stdout, end="", flush=True) + if expected and expected not in result.stdout: + raise RuntimeError("consumer exited without its completion witness: " + expected) + + +def compiler_search_paths(command: list[str], environment: dict[str, str]) -> list[Path]: + """Ask the selected compiler/target for its declared system-header roots.""" + result = subprocess.run(command + ["-E", "-x", "c++", "-v", "-"], input="", text=True, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + env=environment, check=True, timeout=60) + paths = [] + reading = False + for line in result.stderr.splitlines(): + if '-cc1' in line: + words = shlex.split(line) + for flag in ("-isysroot", "-resource-dir"): + if flag in words: + paths.append(Path(words[words.index(flag) + 1]).resolve()) + if line == "#include <...> search starts here:": + reading = True + elif line == "End of search list.": + reading = False + elif reading: + paths.append(Path(line.strip().removesuffix(" (framework directory)")).resolve()) + if not paths: + raise RuntimeError("compiler did not report its system include paths") + return paths + + +def dependency_audit(stage: Path, build: Path, commands: list[dict], + boost: Path, expected_cobalt: set[str], policy: list[str], + compiler_roots: list[Path]) -> dict: + """Inspect compiler depfiles and commands, including system headers and all source units.""" + dependencies: set[Path] = set() + depfiles = list(build.rglob("*.d")) + if not depfiles: + raise RuntimeError("no compiler dependency files were produced") + for depfile in depfiles: + body = depfile.read_text().replace("\\\n", "") + _, separator, body = body.partition(": ") + if not separator: + raise RuntimeError("invalid compiler dependency file: " + str(depfile)) + for name in shlex.split(body): + path = Path(name) + dependencies.add((path if path.is_absolute() else build / path).resolve()) + stage = stage.resolve() + boost = boost.resolve() + for path in dependencies: + if path.is_relative_to(ROOT.resolve()) and not path.is_relative_to(stage): + raise RuntimeError("compiler used a checkout dependency: " + str(path)) + if not path.is_file(): + raise RuntimeError("compiler dependency is missing: " + str(path)) + if not path.is_relative_to(stage) and not path.is_relative_to(boost) and not any( + path.is_relative_to(root) for root in compiler_roots): + raise RuntimeError("compiler used an undeclared dependency: " + str(path)) + if path.is_relative_to(stage) and "/boost/" in str(path): + raise RuntimeError("source package contains a replacement Boost header: " + str(path)) + cobalt: set[str] = set() + for entry in commands: + source = Path(entry["file"]).resolve() + if not source.is_relative_to(stage): + raise RuntimeError("compiler used a source outside the archive: " + str(source)) + if source not in dependencies: + raise RuntimeError("source has no compiler dependency evidence: " + str(source)) + arguments = entry.get("arguments") or shlex.split(entry["command"]) + if source.is_relative_to(stage / "libs/cobalt/src"): + cobalt.add(source.relative_to(stage / "libs/cobalt").as_posix()) + for flag in policy: + if flag not in arguments: + raise RuntimeError("Cobalt source has a different configuration: " + + str(source) + ": missing " + flag) + if cobalt != expected_cobalt: + raise RuntimeError("compiled Cobalt inventory mismatch: " + + repr(cobalt.symmetric_difference(expected_cobalt))) + groups = {"archive": [], "boost": [], "toolchain": []} + for path in sorted(dependencies): + group = "archive" if path.is_relative_to(stage) else ( + "boost" if path.is_relative_to(boost) else "toolchain") + groups[group].append(str(path)) + if not groups["archive"] or not groups["boost"]: + raise RuntimeError("incomplete compiler dependency evidence") + print(f"Dependency audit: {len(commands)} compilations, {len(dependencies)} files, " + f"{len(cobalt)} declared Cobalt sources; no checkout or replacement Boost headers.", + flush=True) + return {"commands": commands, "dependencies": groups, "cobalt_sources": sorted(cobalt), + "compiler_include_roots": [str(path) for path in compiler_roots]} + + +def copy_sources(destination: Path) -> None: + for library in ("config", "asio", "cobalt", "beast"): + source = ROOT / "libs" / library + target = destination / "libs" / library + shutil.copytree(source / "include", target / "include", symlinks=True) + if library in ("asio", "cobalt"): + # Source files and pinned ABI declarations, but no build scripts or caches. + shutil.copytree(source / "src", target / "src", symlinks=True, + ignore=shutil.ignore_patterns("Jamfile", "*.jam", "__pycache__")) + if library in ("asio", "cobalt"): + shutil.copyfile(source / "sources.json", target / "sources.json") + shutil.copyfile(source / "LICENSE_1_0.txt", target / "LICENSE_1_0.txt") + if library in ("asio", "cobalt", "beast"): + # Audit records and maintainer inputs travel with the derived source. + # Consumers inspect them; they never need to execute the importer. + shutil.copytree(source / "upstream", target / "upstream", symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + fixtures = destination / "consumers" + fixtures.mkdir() + for library, name in (("asio", "network.cpp"), ("asio", "browser.cpp"), + ("asio", "customizations.cpp"), ("asio", "customizations.hpp"), + ("asio", "peer.cpp"), + ("cobalt", "timers.cpp"), ("cobalt", "configuration.cpp"), + ("cobalt", "consumer_config.hpp"), ("cobalt", "threads.cpp")): + shutil.copyfile(ROOT / "libs" / library / "test/distribution" / name, fixtures / name) + shutil.copyfile(ROOT / "libs/beast/test/socket_test.cpp", fixtures / "beast.cpp") + shutil.copyfile(ROOT / "tools/throw_exception.cpp", fixtures / "throw_exception.cpp") + shutil.copyfile(ROOT / "tools/test/fixtures/portable-network/CMakeLists.txt", + destination / "CMakeLists.txt") + tests = fixtures / "include/webcpp/test" + tests.mkdir(parents=True) + shutil.copyfile(ROOT / "tools/node-test/include/webcpp/test/exit_status.hpp", + tests / "exit_status.hpp") + for name in ("client", "state", "cancel"): + shutil.copyfile(ROOT / f"libs/cobalt/test/tls/cobalt_ssl_{name}.cpp", + fixtures / f"ssl_{name}.cpp") + shutil.copyfile(ROOT / "tools/openssl/test/tls.py", fixtures / "tls.py") + for path in destination.rglob("*"): + if path.is_symlink(): + raise RuntimeError("source snapshot contains a symlink: " + str(path)) + if path.name in (".git", ".local", "bin", "Jamfile", "Jamroot"): + raise RuntimeError("source snapshot leaked a checkout/build dependency: " + str(path)) + + +def snapshot(destination: Path) -> None: + """Pack real source bytes, delete staging, then extract and verify the archive.""" + staging = destination.parent / "source staging" + copy_sources(staging) + hashes = {path.relative_to(staging).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(staging.rglob("*")) if path.is_file()} + (staging / "archive-manifest.json").write_text( + json.dumps({"schema": 1, "sha256": hashes}, indent=2) + "\n") + archive = destination.parent / "webcpp-network.tar.gz" + with archive.open("wb") as output, gzip.GzipFile( + fileobj=output, filename="", mode="wb", mtime=0) as zipped: + with tarfile.open(fileobj=zipped, mode="w") as packed: + for path in sorted(staging.rglob("*")): + if not path.is_file(): + continue + if path.is_symlink(): + raise RuntimeError("source archive cannot contain symlinks: " + str(path)) + info = packed.gettarinfo(str(path), arcname=path.relative_to(staging).as_posix()) + info.uid = info.gid = info.mtime = 0 + info.uname = info.gname = "" + info.mode = 0o644 + with path.open("rb") as content: + packed.addfile(info, content) + shutil.rmtree(staging) + with tarfile.open(archive) as packed: + # Extract only our regular files, also on supported Python versions that + # predate tarfile's extraction filters. No links or external paths. + for member in packed: + path = Path(member.name) + if not member.isfile() or path.is_absolute() or ".." in path.parts: + raise RuntimeError("invalid source archive entry: " + member.name) + content = packed.extractfile(member) + if content is None: + raise RuntimeError("missing source archive entry: " + member.name) + target = destination / path + target.parent.mkdir(parents=True, exist_ok=True) + with content, target.open("wb") as output: + shutil.copyfileobj(content, output) + for name, digest in hashes.items(): + if hashlib.sha256((destination / name).read_bytes()).hexdigest() != digest: + raise RuntimeError("source archive hash mismatch: " + name) + print(f"Extracted source archive: {len(hashes)} files; SHA256=" + + hashlib.sha256(archive.read_bytes()).hexdigest(), flush=True) + + +def tls_dependencies(stage: Path, prefix: Path, authorities: Path) -> None: + """Copy explicitly supplied, already built dependencies into the clean snapshot.""" + dependency = stage / "dependencies/openssl" + shutil.copytree(prefix / "include", dependency / "include") + for name in ("libssl.a", "libcrypto.a"): + shutil.copyfile(prefix / name, dependency / name) + ca = stage / "dependencies/include/webcpp/asio/detail/ca_certificates.hpp" + ca.parent.mkdir(parents=True) + shutil.copyfile(authorities, ca) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--compiler", type=Path, required=True) + parser.add_argument("--boost-include", type=Path, required=True) + parser.add_argument("--target", choices=("native", "wasip2", "wasip3", "emscripten"), + required=True) + parser.add_argument("--exceptions", choices=("on", "off"), default="on") + parser.add_argument("--threads", choices=("single", "multi"), default="single") + parser.add_argument("--suspend", choices=("jspi", "asyncify"), default="jspi") + parser.add_argument("--cobalt-executor", choices=("any", "io_context", "custom"), default="any") + parser.add_argument("--cobalt-pmr", choices=("std", "none", "custom"), default="std") + parser.add_argument("--runtime", type=Path) + parser.add_argument("--wasi-sdk", type=Path) + parser.add_argument("--build-system", choices=("direct", "cmake"), default="direct") + parser.add_argument("--cmake", default="cmake") + parser.add_argument("--archiver", type=Path) + parser.add_argument("--ranlib", type=Path) + parser.add_argument("--evidence-dir", type=Path, + help="Keep the tested source archive and compiler dependency receipt") + parser.add_argument("--openssl-prefix", type=Path, + help="Explicit matching provider with include/, libssl.a and libcrypto.a") + parser.add_argument("--ca-header", type=Path, help="Explicit generated embedded CA header") + args = parser.parse_args() + if bool(args.openssl_prefix) != bool(args.ca_header): + parser.error("TLS requires both --openssl-prefix and --ca-header") + if args.openssl_prefix and args.target == "emscripten": + parser.error("Guest OpenSSL is not a browser transport") + environment = dict(os.environ) + for name in ("CPATH", "CPLUS_INCLUDE_PATH", "C_INCLUDE_PATH", "CXXFLAGS", "CPPFLAGS", + "CFLAGS", "LDFLAGS", "CMAKE_PREFIX_PATH", "CMAKE_TOOLCHAIN_FILE"): + environment.pop(name, None) + try: + with tempfile.TemporaryDirectory(prefix="webcpp unpacked consumer ") as temporary: + stage = Path(temporary) / "unpacked" + snapshot(stage) + # Installed developer tools must not accidentally rescue this consumer. + unavailable = Path(temporary) / "unavailable-build-tools" + unavailable.mkdir() + for name in ("b2", "bjam", "git", "patch"): + tool = unavailable / name + tool.write_text("#!/bin/sh\n" + f"echo 'Source consumer cannot use {name}' >&2\nexit 127\n") + tool.chmod(0o755) + environment["PATH"] = str(unavailable) + os.pathsep + environment.get("PATH", "") + print("Consumer PATH: B2, Git and patch unavailable (guarded).", flush=True) + if args.openssl_prefix: + tls_dependencies(stage, args.openssl_prefix.resolve(), args.ca_header.resolve()) + # Preserve clang++'s basename: resolving its symlink to clang selects + # the C driver and drops the C++ standard-library link automatically. + command = [str(args.compiler.absolute()), "-std=c++20", "-O2", + "-DBOOST_COBALT_NO_LIB=1"] + command += ["-isystem", str(args.boost_include.resolve())] + policy: list[str] = [] + if args.cobalt_executor == "io_context": + policy += ["-DBOOST_COBALT_USE_IO_CONTEXT=1"] + if args.cobalt_pmr == "none": + policy += ["-DBOOST_COBALT_NO_PMR=1"] + if args.cobalt_executor == "custom": + policy += ["-DBOOST_COBALT_CUSTOM_EXECUTOR=1"] + if args.cobalt_pmr == "custom": + policy += ["-DBOOST_COBALT_USE_CUSTOM_PMR=1"] + command += policy + if args.cobalt_executor == "custom" or args.cobalt_pmr == "custom": + command += ["-include", str(stage / "consumers/consumer_config.hpp")] + for library in ("config", "asio", "cobalt", "beast"): + command += ["-I", str(stage / "libs" / library / "include")] + asio = stage / "libs/asio" + asio_profile = json.loads((asio / "sources.json").read_text())["profiles"][args.target] + runtime_sources = [str(asio / source) for source in asio_profile["runtime"]] + for include in asio_profile["private_include"]: + command += ["-I", str(asio / include)] + links: list[str] = [] + if args.target.startswith("wasi"): + if not args.wasi_sdk or not args.runtime: + parser.error("WASI requires --wasi-sdk and --runtime") + sdk = args.wasi_sdk.resolve() + command += ["--target=wasm32-" + args.target] + private = stage / "libs/asio/src" / args.target + run(["python3", str(private / "verify.py"), "--sdk", str(sdk)], environment) + if args.threads == "multi": + if args.target != "wasip3" or args.exceptions != "off": + parser.error("SDK 34 supports cooperative P3 threads " + "only without exceptions") + sysroot = sdk / "share/wasi-sysroot/experimental-coop-threads" + command += ["--sysroot=" + str(sysroot), "-pthread", "-isystem", + str(sdk / "share/wasi-sysroot/include/c++/v1")] + if args.exceptions == "on": + command += ["-fwasm-exceptions", "-mllvm", "-wasm-use-legacy-eh=false"] + links += ["-lunwind"] + elif args.target == "emscripten": + if not args.runtime: + parser.error("Emscripten requires --runtime (Node)") + if args.threads == "multi": + parser.error("The external consumer worker profile needs a browser harness") + links += ["-lembind", "-sEXIT_RUNTIME=1", "-sENVIRONMENT=node", + "-Wl,--export=emscripten_stack_get_current", + "-Wl,--export=_emscripten_stack_restore"] + if args.suspend == "jspi": + links += ["-sJSPI"] + if args.exceptions == "on": + command += ["-fwasm-exceptions"] + else: + links += ["-sASYNCIFY", "-sASYNCIFY_STACK_SIZE=8192"] + if args.exceptions == "on": + command += ["-fexceptions"] + elif args.threads == "multi": + command += ["-pthread"] + if args.exceptions == "off": + command += ["-fno-exceptions"] + runtime_sources += [str(stage / "consumers/throw_exception.cpp")] + compiler_roots = compiler_search_paths(command, environment) + suffix = ".js" if args.target == "emscripten" else ( + ".wasm" if args.target.startswith("wasi") else "") + programs = ([("browser", "distribution browser Promise/timer/HTTP: passed")] + if args.target == "emscripten" else + [("network", "8 completions, 0 failures"), + ("beast", "No errors detected.")]) + programs += [("timers", "distribution Cobalt/Asio timers: passed")] + programs += [("customizations", "public token/trait specializations and multiple TUs")] + if args.threads == "multi": + programs += [("threads", "distribution Cobalt thread coroutine and join: passed")] + if args.openssl_prefix: + programs += [("ssl_client", ""), ("ssl_state", ""), ("ssl_cancel", "")] + build = stage + commands: list[dict] = [] + contract = json.loads((stage / "libs/cobalt/sources.json").read_text())["profiles"][ + args.target] + expected_cobalt = set(contract["core"] + contract["runner"]) + if args.threads == "multi": + expected_cobalt.update(contract["multi_add"]) + if args.openssl_prefix: + expected_cobalt.update(contract["ssl"]) + if args.build_system == "cmake": + build = stage / "build" + configure = [args.cmake, "-S", str(stage), "-B", str(build), + "-DCMAKE_CXX_COMPILER=" + str(args.compiler.absolute()), + "-DCMAKE_BUILD_TYPE=Release", "-DWEBCPP_SOURCE_ROOT=" + str(stage), + "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", + "-DBOOST_INCLUDE_DIR=" + str(args.boost_include.resolve()), + "-DWEBCPP_TARGET=" + args.target, "-DWEBCPP_SUSPEND=" + args.suspend, + "-DWEBCPP_COBALT_EXECUTOR=" + args.cobalt_executor, + "-DWEBCPP_COBALT_PMR=" + args.cobalt_pmr, + "-DWEBCPP_EXCEPTIONS=" + ("ON" if args.exceptions == "on" else "OFF"), + "-DWEBCPP_THREADS=" + ("ON" if args.threads == "multi" else "OFF")] + if args.openssl_prefix: + configure += ["-DWEBCPP_OPENSSL_PREFIX=" + str(stage / "dependencies/openssl"), + "-DWEBCPP_CA_INCLUDE=" + str(stage / "dependencies/include")] + if args.target != "native": + configure += ["-DCMAKE_SYSTEM_NAME=Generic", + "-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY"] + if args.wasi_sdk: + configure += ["-DWEBCPP_WASI_SDK=" + str(args.wasi_sdk.resolve())] + configure += ["-DCMAKE_AR=" + str(args.wasi_sdk.absolute() / "bin/llvm-ar"), + "-DCMAKE_RANLIB=" + str( + args.wasi_sdk.absolute() / "bin/llvm-ranlib")] + if args.target == "emscripten" and (not args.archiver or not args.ranlib): + parser.error("CMake Emscripten requires explicit --archiver emar " + "and --ranlib emranlib") + for variable, path in (("CMAKE_AR", args.archiver), ("CMAKE_RANLIB", args.ranlib)): + if path: + configure += ["-D" + variable + "=" + str(path.absolute())] + run(configure, environment, directory=stage) + run([args.cmake, "--build", str(build), "--parallel", "4"], environment, + directory=stage) + commands = json.loads((build / "compile_commands.json").read_text()) + objects: dict[str, Path] = {} + for name, witness in programs: + executable = build / (name + suffix) + sources = [str(stage / "consumers" / (name + ".cpp"))] + runtime_sources + extra_flags: list[str] = [] + extra_links: list[str] = [] + if name == "customizations": + sources += [str(stage / "consumers/peer.cpp")] + if name in ("timers", "threads") or name.startswith("ssl_"): + sources += [str(stage / "consumers/configuration.cpp")] + library = stage / "libs/cobalt" + profiles = json.loads((library / "sources.json").read_text())["profiles"] + contract = profiles[args.target] + selected = contract["core"] + (contract["runner"] if name != "threads" else []) + if args.threads == "multi": + selected += contract["multi_add"] + if name.startswith("ssl_"): + selected += contract["ssl"] + provider = stage / "dependencies/openssl" + extra_flags = ["-DWEBCPP_ASIO_HAS_OPENSSL=1", "-DWEBCPP_COBALT_LINK_SSL=1", + "-I", str(provider / "include"), + "-I", str(stage / "dependencies/include"), + "-I", str(stage / "consumers/include")] + extra_links = [str(provider / "libssl.a"), str(provider / "libcrypto.a")] + if args.target.startswith("wasi"): + extra_links += ["-lwasi-emulated-getpid", "-lwasi-emulated-signal", + "-lwasi-emulated-process-clocks", + "-lwasi-emulated-mman"] + sources += [str(library / path) for path in selected] + if args.build_system == "direct": + linked_objects = [] + for source in sources: + key = hashlib.sha256(json.dumps(command + extra_flags + [source]).encode() + ).hexdigest()[:20] + if key not in objects: + obj = build / "objects" / (key + ".o") + obj.parent.mkdir(exist_ok=True) + invocation = command + extra_flags + ["-MD", "-MF", str(obj) + ".d", + "-c", source, "-o", str(obj)] + run(invocation, environment, directory=stage) + commands.append({"directory": str(stage), "file": source, + "arguments": invocation}) + objects[key] = obj + linked_objects.append(str(objects[key])) + run(command + extra_flags + linked_objects + extra_links + links + + ["-o", str(executable)], environment, directory=stage) + if name.startswith("ssl_"): + tls_environment = dict(environment) + if args.runtime: + tls_environment["WASMTIME"] = str(args.runtime.resolve()) + invocation = [sys.executable, str(stage / "consumers/tls.py"), str(executable)] + invocation += (["--embedded", "--require-sni"] if name == "ssl_client" + else ["--state-test"]) + if args.target == "wasip2": + invocation += ["--wasip2"] + run(invocation, tls_environment, "PASS", directory=stage) + print(f"PASS {name}: target={args.target} EH={args.exceptions} " + f"threads={args.threads}", flush=True) + continue + invocation = [str(executable)] + if args.target.startswith("wasi"): + invocation = [str(args.runtime.resolve()), "run"] + if args.target == "wasip3": + invocation += ["-S", "p3", "-W", "component-model-async=y"] + if args.threads == "multi": + invocation += ["-W", "component-model-threading=y"] + invocation += ["-S", "inherit-network=y", "-S", "tcp=y", "-S", "udp=y", + "-S", "allow-ip-name-lookup=y", str(executable)] + elif args.target == "emscripten": + invocation = [str(args.runtime.resolve()), str(executable)] + run(invocation, environment, witness, directory=stage) + print(f"PASS {name}: target={args.target} EH={args.exceptions} " + f"threads={args.threads}", flush=True) + receipt = dependency_audit(stage, build, commands, args.boost_include, + expected_cobalt, policy, compiler_roots) + if args.evidence_dir: + args.evidence_dir.mkdir(parents=True, exist_ok=True) + shutil.copyfile(stage.parent / "webcpp-network.tar.gz", + args.evidence_dir / "webcpp-network.tar.gz") + (args.evidence_dir / "compiler-receipt.json").write_text( + json.dumps(receipt, indent=2) + "\n") + except subprocess.CalledProcessError as error: + if error.stdout: + print(error.stdout, end="", flush=True) + return error.returncode or 1 + print("Unpacked source consumer passed without B2, Git, patches or checkout include paths.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/test/portable_network_distribution_test.py b/tools/test/portable_network_distribution_test.py new file mode 100644 index 00000000..6de7b6b5 --- /dev/null +++ b/tools/test/portable_network_distribution_test.py @@ -0,0 +1,182 @@ +#!/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 the B2-free consumer through the standard tools-test entry point.""" +from pathlib import Path +import hashlib +import json +import shutil +import subprocess +import sys +import tarfile + +import harness +import portable_network_distribution as distribution + + +def native_inputs() -> list[str]: + """Read explicit Boost setup; the consumer itself does not discover dependencies.""" + compiler = shutil.which('clang++') + if not compiler: + raise RuntimeError('the native distribution test requires clang++ on PATH') + return ['--compiler', compiler, '--boost-include', str(harness.boost_include())] + + +def run_consumer(driver: str, *options: str) -> None: + command = [sys.executable, str(harness.ROOT / 'tools/test' / driver), + *native_inputs(), *options] + result = subprocess.run(command, cwd=harness.ROOT, env=harness.b2_environment(), + text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=300) + assert result.returncode == 0, result.stdout[-12000:] + if driver == 'portable_network_distribution.py': + assert 'Dependency audit:' in result.stdout, 'missing actual compiler dependency evidence' + print(result.stdout[-3000:], end='') + + +def test_native_identity_and_interoperability(root: Path) -> None: + run_consumer('native_network_identity.py') + + +def test_unpacked_native_cmake_consumer(root: Path) -> None: + run_consumer('portable_network_distribution.py', '--target', 'native', + '--build-system', 'cmake') + + +def test_unpacked_custom_configuration(root: Path) -> None: + run_consumer('portable_network_distribution.py', '--target', 'native', + '--build-system', 'cmake', '--cobalt-executor', 'custom', + '--cobalt-pmr', 'custom') + + +def test_source_archive_roundtrip(root: Path) -> None: + stage = root / 'unpacked source with spaces' + stage.mkdir() + distribution.snapshot(stage) + archive = stage.parent / 'webcpp-network.tar.gz' + assert archive.is_file(), 'the consumer must extract an actual source archive' + with tarfile.open(archive) as packed: + names = packed.getnames() + assert 'libs/cobalt/sources.json' in names + assert 'libs/asio/sources.json' in names + for library in ('asio', 'cobalt', 'beast'): + prefix = f'libs/{library}/upstream/' + for record in ('pin.json', 'generated.json', 'sync.py', 'README.md'): + assert prefix + record in names, f'missing source provenance: {prefix}{record}' + original = distribution.ROOT / 'libs' / library / 'upstream' + for path in original.rglob('*'): + if path.is_file() and '__pycache__' not in path.parts: + archived = stage / prefix / path.relative_to(original) + assert archived.read_bytes() == path.read_bytes(), str(archived) + assert 'libs/asio/src/wasip2/pollable.cpp' in names + assert 'libs/asio/src/wasip3/waitable.cpp' in names + assert all(not member.issym() and not member.islnk() for member in packed) + manifest = json.loads((stage / 'archive-manifest.json').read_text()) + for name, digest in manifest['sha256'].items(): + assert hashlib.sha256((stage / name).read_bytes()).hexdigest() == digest, name + assert set(manifest['sha256']) == set(names) - {'archive-manifest.json'} + assert not (stage.parent / 'source staging').exists(), 'remove inputs before extracting' + + +def test_audit_rejects_hidden_headers_and_mismatched_configuration(root: Path) -> None: + stage = root / 'unpacked' + distribution.snapshot(stage) + compiler = shutil.which('clang++') + assert compiler + command = [compiler, '-std=c++20', '-isystem', str(harness.boost_include())] + for library in ('config', 'asio', 'cobalt', 'beast'): + command += ['-I', str(stage / 'libs' / library / 'include')] + compiler_roots = distribution.compiler_search_paths(command, harness.b2_environment()) + source = stage / 'libs/cobalt/src/native/this_thread.cpp' + depfile = stage / 'control.d' + invocation = command + ['-MD', '-MF', str(depfile), '-c', str(source), + '-o', str(stage / 'control.o')] + subprocess.run(invocation, env=harness.b2_environment(), check=True, capture_output=True) + entries = [{'file': str(source), 'arguments': invocation}] + try: + distribution.dependency_audit(stage, stage, entries, harness.boost_include(), + {'src/native/this_thread.cpp'}, + ['-DBOOST_COBALT_CUSTOM_EXECUTOR=1'], compiler_roots) + except RuntimeError as error: + assert 'different configuration' in str(error), str(error) + else: + raise AssertionError('the audit accepted a core compiled with the wrong configuration') + + source = stage / 'hidden.cpp' + source.write_text('#include "' + str(harness.ROOT / 'libs/config/include/webcpp/config.hpp') + + '"\n') + invocation = command + ['-MD', '-MF', str(depfile), '-c', str(source), + '-o', str(stage / 'control.o')] + subprocess.run(invocation, env=harness.b2_environment(), check=True, capture_output=True) + try: + distribution.dependency_audit(stage, stage, [{'file': str(source), + 'arguments': invocation}], harness.boost_include(), set(), [], + compiler_roots) + except RuntimeError as error: + assert 'checkout dependency' in str(error), str(error) + else: + raise AssertionError('the audit accepted a header outside the source archive') + + +def test_conflicting_cobalt_policies_are_rejected_without_b2(root: Path) -> None: + stage = root / 'unpacked' + distribution.snapshot(stage) + compiler = shutil.which('clang++') + assert compiler + source = stage / 'conflict.cpp' + source.write_text('#include <webcpp/cobalt/config.hpp>\n') + command = [compiler, '-std=c++20', '-fsyntax-only', '-isystem', str(harness.boost_include())] + for library in ('config', 'asio', 'cobalt'): + command += ['-I', str(stage / 'libs' / library / 'include')] + for flags, diagnostic in ( + (['-DBOOST_COBALT_USE_IO_CONTEXT=1', '-DBOOST_COBALT_CUSTOM_EXECUTOR=1'], + 'select either the io_context executor or a custom executor'), + (['-DBOOST_COBALT_NO_PMR=1', '-DBOOST_COBALT_USE_STD_PMR=1'], + 'select exactly one PMR policy'), + ): + result = subprocess.run(command + flags + [str(source)], env=harness.b2_environment(), + text=True, capture_output=True) + assert result.returncode != 0 and diagnostic in result.stderr, result.stderr + + +def test_mismatched_boost_headers_are_rejected_without_b2(root: Path) -> None: + stage = root / 'unpacked' + distribution.snapshot(stage) + compiler = shutil.which('clang++') + assert compiler + shadow = root / 'different Boost/include/boost' + shadow.mkdir(parents=True) + source = stage / 'version.cpp' + source.write_text('#include <webcpp/cobalt/task.hpp>\n') + command = [compiler, '-std=c++20', '-fsyntax-only', '-I', str(shadow.parent), + '-isystem', str(harness.boost_include())] + for library in ('config', 'asio', 'cobalt'): + command += ['-I', str(stage / 'libs' / library / 'include')] + version = (harness.boost_include() / 'boost/version.hpp').read_text() + contract = json.loads((stage / 'libs/cobalt/sources.json').read_text()) + assert 'src/native_version.cpp' in contract['profiles']['native']['core'] + for number in (109100, 109200, 109300): + (shadow / 'version.hpp').write_text(version.replace('109200', str(number))) + for unit in (source, stage / 'libs/cobalt/src/native_version.cpp'): + result = subprocess.run(command + [str(unit)], env=harness.b2_environment(), + text=True, capture_output=True, timeout=30) + if number == 109200: + assert result.returncode == 0, result.stderr + else: + assert result.returncode != 0, 'mismatched Boost headers were accepted' + diagnostic = 'webcpp::cobalt requires Boost 1.92.0 headers' + assert diagnostic in result.stderr, result.stderr + + +CASES = [test_source_archive_roundtrip, test_native_identity_and_interoperability, + test_unpacked_native_cmake_consumer, test_unpacked_custom_configuration, + test_audit_rejects_hidden_headers_and_mismatched_configuration, + test_conflicting_cobalt_policies_are_rejected_without_b2, + test_mismatched_boost_headers_are_rejected_without_b2] + +if __name__ == '__main__': + sys.exit(harness.run_cases('portable_network_distribution_test', CASES, sys.argv[1:])) From 93ec6f69be4b73bdb2aaf1e13bd0dea281178c1c Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 09:01:08 -0300 Subject: [PATCH 2/9] doc: keep the unpublished release in preparation --- doc/releases/0.1.0.adoc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 8da39b24..7052f1e6 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -7,6 +7,9 @@ [#webcpp-0-1-0] = webcpp 0.1.0 +In preparation: no tag names this version yet, and its libraries' entries +are their changelogs' "Unreleased" sections. + [#webcpp-0-1-0-new-libraries] == New Libraries From 83c1675ac2672bb212ce379d12e1fc7201fe69ec Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 09:01:44 -0300 Subject: [PATCH 3/9] Revert "doc: keep the unpublished release in preparation" This reverts commit 93ec6f69be4b73bdb2aaf1e13bd0dea281178c1c. --- doc/releases/0.1.0.adoc | 3 --- 1 file changed, 3 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 7052f1e6..8da39b24 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -7,9 +7,6 @@ [#webcpp-0-1-0] = webcpp 0.1.0 -In preparation: no tag names this version yet, and its libraries' entries -are their changelogs' "Unreleased" sections. - [#webcpp-0-1-0-new-libraries] == New Libraries From e4d3cee3b3c7f63817ff956fa7b103fcb9befed8 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 09:04:10 -0300 Subject: [PATCH 4/9] ci: pin verified environments for the portable network integration --- .../2026-11-06-portable-network-libraries.md | 14 ++++++++-- tools/ci/environments.json | 26 +++++++++---------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md index 0f732dae..07fbb633 100644 --- a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -159,7 +159,17 @@ is registered as a submodule. These commits preserve the checked source and measurement bytes; Git attributes retain imported/generated whitespace and CSV line endings. The superproject records all three revisions together. -Remote CI is pending. The changed container recipe must first produce verified -immutable environment pins. The complete superproject CI validates the combined +The changed container recipe produced verified immutable environment pins in +GitHub run 42370588658. All six publishers, six anonymous consumers and the +manifest assembly passed. The generated manifest is promoted unchanged. Full +remote test CI is pending. The complete superproject CI validates the combined candidate before integration; library workflows use the superproject's main and must be rerun after its integration. No release or proposal archival is implied. + + +The source-release check is a separate unresolved gate: the existing 0.1.0 +notes and the older libraries are frozen, while the three changed libraries +retain Unreleased entries. No release tag or GitHub release exists. The attempted +in-preparation marker conflicted with those historical frozen sections and was +reverted without rewriting them. Reconcile this state in the separately authorized +release procedure; remote integration CI does not certify a release archive. diff --git a/tools/ci/environments.json b/tools/ci/environments.json index 805572f0..f9789639 100644 --- a/tools/ci/environments.json +++ b/tools/ci/environments.json @@ -5,48 +5,48 @@ "archives": [ "9d96e42f303046fb0b221aa9071eabccc40b9683e0b7af2b02a929d15476ca6a" ], - "image": "ghcr.io/webcpporg/ci-environment@sha256:bfc8d2a63423a662cc21dc7377bf1b794cff883aa52446372eab8ccdddbe8b4d", + "image": "ghcr.io/webcpporg/ci-environment@sha256:47ffcbe9dff61287e7482efb908e13ba91ac5973efbc964ff228b98a4f633fc1", "recipe": "1caf5163552b9ba131f4687f9321cf90a157ce02e411d8d3284faf3a63547bbf", - "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + "source": "c41196569b22bd1b0ca80baf4945cd657be15f3f" }, "native-linux-x64": { "archives": [], - "image": "ghcr.io/webcpporg/ci-environment@sha256:d97a1596cfd6b7b0c69b9285bfbe95d90b2324fed34b0108ff102e44ad90888e", - "recipe": "12e35220e73d085db6e4e6aa4fe840a58a885018600e5cb9cc976f41c5996ec3", - "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + "image": "ghcr.io/webcpporg/ci-environment@sha256:c1e7a56dcb3c74bb7431e105e6432d345131ed3fd5d3fbac7c19531e6d5692a4", + "recipe": "34fb00b6fe5aebb73082f45019a5ed6a13a2e8fec9f4900d6a278d1a00c236ac", + "source": "c41196569b22bd1b0ca80baf4945cd657be15f3f" }, "wasi-sdk-linux-x64": { "archives": [ "b761e3a0721dbae9c09a0059e5fdb2bf917d1b4a8a7b430fb3b5aafb0984b2c4" ], - "image": "ghcr.io/webcpporg/ci-environment@sha256:b753ad1d3c1e5a437e65f55e967287211554db9b6ab5e02c0b471829b60c1f89", + "image": "ghcr.io/webcpporg/ci-environment@sha256:fed7836d1847c252bb0a346f1e69aa33f5f3391a17c89aee0b48ec003cec2d91", "recipe": "605940eca683fa1f9da9d842779fcdd2825582e0315fc9f0da78196231a67b1e", - "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + "source": "c41196569b22bd1b0ca80baf4945cd657be15f3f" }, "wasi-wit-linux-x64": { "archives": [ "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487", "f1d5749fdf69bb9400562eba50f8f25f5cd800ef4b74300038b6f99ae7409674" ], - "image": "ghcr.io/webcpporg/ci-environment@sha256:3823662eca2283c12601a4189e7adbe6c307ff011fc4f299e10b2e95cda10af0", + "image": "ghcr.io/webcpporg/ci-environment@sha256:f05fc9fe2786aed49df98ece6508b57a965ddde00b056aaf1ab2104b17513076", "recipe": "a154f6fe1adb7268d5c4f0c6a5e244166d3925fd74d3d125691709067a84209a", - "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + "source": "c41196569b22bd1b0ca80baf4945cd657be15f3f" }, "wasmtime-linux-x64": { "archives": [ "685466455dd42a14774a86c36c8f2e45cbb9bd6d92a850139315df60a75498a5" ], - "image": "ghcr.io/webcpporg/ci-environment@sha256:82c0aea55102da94e9931c6dc95448095f0627ab14a8c78aad10ae2236db8686", + "image": "ghcr.io/webcpporg/ci-environment@sha256:3879086896abc7f0228e174011dedcbe207c4dc0822e1c10034c386f9af7668e", "recipe": "3e46afc7303c53c2161bcc97ff2714fd6a0426aa61dac6cb85f4f56b33bb0101", - "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + "source": "c41196569b22bd1b0ca80baf4945cd657be15f3f" }, "wit-bindgen-linux-x64": { "archives": [ "3e81cc6523729f7532b4aa7968648a04abf0c711b7d1677150e9121f4e6458fe" ], - "image": "ghcr.io/webcpporg/ci-environment@sha256:9e4b762d83ae9bf098e28ef8a34a2e9f3f5ab473a7b997f91cc2f20114012aff", + "image": "ghcr.io/webcpporg/ci-environment@sha256:f6780e906a25d7c6d0de510201bef592761775b2b520e685985a69fd2d78b4b6", "recipe": "436fd39c29f16fc56d136cad6ca2f829f984cf536a0abc83f53d8cf23049ad93", - "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + "source": "c41196569b22bd1b0ca80baf4945cd657be15f3f" } }, "schema": 1 From 349f5b386bc317cbfcdf79febc03baad6304b07c Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 09:28:50 -0300 Subject: [PATCH 5/9] ci: recognize linker dependencies and preserve corpus lint coverage --- doc/releases/0.1.0.adoc | 1 + .../2026-11-06-portable-network-libraries.md | 13 +++ tools/lint/lint_test.py | 8 +- tools/test/portable_network_distribution.py | 30 +++++-- .../portable_network_distribution_test.py | 82 ++++++++++++++++++- 5 files changed, 123 insertions(+), 11 deletions(-) diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 8da39b24..3f46f3e4 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -58,6 +58,7 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Fixed clean CMake consumer audits rejecting system libraries and phony dependency rules. * Changed CI to consume verified prepared environments without rebuilding images in PR jobs. * Added verified archive caches and isolated container availability from unrelated CI lanes. * Fixed parallel builds truncating OpenSSL headers while compilers read them. diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md index 07fbb633..4648fb25 100644 --- a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -173,3 +173,16 @@ retain Unreleased entries. No release tag or GitHub release exists. The attempte in-preparation marker conflicted with those historical frozen sections and was reverted without rewriting them. Reconcile this state in the separately authorized release procedure; remote integration CI does not certify a release archive. + +The first full remote run, 42370852663, exposed three tooling regressions. The +Linux CMake consumer built and ran, but dependency auditing rejected libm because +only header search roots were queried. The audit now also queries the selected +compiler's library paths, with a regression that still rejects an undeclared +library. Linker phony rules were also misread as dependency filenames; a real +compiler regression using `-MP` reproduces this and confirms that dependencies +in subsequent rules are still checked. The existing Cobalt lint fixture lacked the exact-file +inventory required +by the new classification gate; it now supplies that inventory and verifies that +an unlisted neighboring file remains linted. All three failures were reproduced before +correction. These findings supersede the corresponding local reconciliation claims; +the original reports and failed CI logs remain preserved. diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index b2fdc307..883a40fb 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -2413,15 +2413,19 @@ def test_cobalt_corpus_is_verified_before_excluding_upstream_style(root): # 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') + # The shipped-source gate excludes inventory entries, not whole directories. + write(root, 'libs/cobalt/test/applications/manifest.json', json.dumps({ + 'applications': [{'path': 'original.cpp'}], 'benchmarks': [], 'supporting_files': [] + }) + '\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 + assert 'shipped source 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/cobalt/example/notes.txt' + adapted = 'libs/cobalt/test/applications/upstream/notes.txt' write(root, adapted, EM_DASH + '\n') expect_alone(lint(root), 'em dash', [adapted + ':1:']) diff --git a/tools/test/portable_network_distribution.py b/tools/test/portable_network_distribution.py index 549c783e..4e829427 100644 --- a/tools/test/portable_network_distribution.py +++ b/tools/test/portable_network_distribution.py @@ -14,6 +14,7 @@ import json import os from pathlib import Path +import re import shlex import shutil import subprocess @@ -36,7 +37,7 @@ def run(command: list[str], environment: dict[str, str], expected: str = "", def compiler_search_paths(command: list[str], environment: dict[str, str]) -> list[Path]: - """Ask the selected compiler/target for its declared system-header roots.""" + """Ask the selected compiler/target for its header and library search roots.""" result = subprocess.run(command + ["-E", "-x", "c++", "-v", "-"], input="", text=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=environment, check=True, timeout=60) @@ -56,6 +57,15 @@ def compiler_search_paths(command: list[str], environment: dict[str, str]) -> li paths.append(Path(line.strip().removesuffix(" (framework directory)")).resolve()) if not paths: raise RuntimeError("compiler did not report its system include paths") + result = subprocess.run(command + ["-print-search-dirs"], text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=environment, check=True, timeout=60) + for line in result.stdout.splitlines(): + if line.startswith("libraries: ="): + # CMake's linker depfiles also record system libraries, such as libm. + # Trust only the selected driver's declared paths, not a host prefix. + paths += [Path(path).resolve() for path in + line.removeprefix("libraries: =").split(os.pathsep) if path] return paths @@ -69,12 +79,16 @@ def dependency_audit(stage: Path, build: Path, commands: list[dict], raise RuntimeError("no compiler dependency files were produced") for depfile in depfiles: body = depfile.read_text().replace("\\\n", "") - _, separator, body = body.partition(": ") - if not separator: - raise RuntimeError("invalid compiler dependency file: " + str(depfile)) - for name in shlex.split(body): - path = Path(name) - dependencies.add((path if path.is_absolute() else build / path).resolve()) + for rule in body.splitlines(): + if not rule.strip(): + continue + parts = re.split(r"(?<!\\):(?:\s|$)", rule, maxsplit=1) + if len(parts) != 2: + raise RuntimeError("invalid compiler dependency file: " + str(depfile)) + # Linkers and -MP emit additional rules, including empty phony targets. + for name in shlex.split(parts[1]): + path = Path(name) + dependencies.add((path if path.is_absolute() else build / path).resolve()) stage = stage.resolve() boost = boost.resolve() for path in dependencies: @@ -115,7 +129,7 @@ def dependency_audit(stage: Path, build: Path, commands: list[dict], f"{len(cobalt)} declared Cobalt sources; no checkout or replacement Boost headers.", flush=True) return {"commands": commands, "dependencies": groups, "cobalt_sources": sorted(cobalt), - "compiler_include_roots": [str(path) for path in compiler_roots]} + "compiler_search_roots": [str(path) for path in compiler_roots]} def copy_sources(destination: Path) -> None: diff --git a/tools/test/portable_network_distribution_test.py b/tools/test/portable_network_distribution_test.py index 6de7b6b5..0921acf3 100644 --- a/tools/test/portable_network_distribution_test.py +++ b/tools/test/portable_network_distribution_test.py @@ -9,10 +9,13 @@ from pathlib import Path import hashlib import json +import os +import shlex import shutil import subprocess import sys import tarfile +from unittest.mock import patch import harness import portable_network_distribution as distribution @@ -53,6 +56,49 @@ def test_unpacked_custom_configuration(root: Path) -> None: '--cobalt-pmr', 'custom') +def test_audit_recognizes_compiler_library_search_paths(root: Path) -> None: + stage = root / 'unpacked' + boost = root / 'boost/include' + headers = root / 'toolchain/include' + libraries = root / 'toolchain/lib' + foreign = root / 'undeclared' + for directory in (stage, boost, headers, libraries, foreign): + directory.mkdir(parents=True) + source = stage / 'main.cpp' + header = boost / 'version.hpp' + library = libraries / 'libm.so' + hidden = foreign / 'libhidden.so' + for path in (source, header, library, hidden): + path.write_text('') + dependencies = [source, header, library] + depfile = stage / 'link.d' + + def write_dependencies() -> None: + depfile.write_text('program: ' + ' '.join(shlex.quote(str(path)) + for path in dependencies) + '\n') + + write_dependencies() + include_output = '#include <...> search starts here:\n ' + str(headers) + ( + '\nEnd of search list.\n') + search_output = 'libraries: =' + str(libraries) + os.pathsep + str(headers) + '\n' + replies = [subprocess.CompletedProcess([], 0, stderr=include_output), + subprocess.CompletedProcess([], 0, stdout=search_output)] + with patch.object(distribution.subprocess, 'run', side_effect=replies): + roots = distribution.compiler_search_paths(['clang++'], {}) + commands = [{'file': str(source), 'arguments': ['clang++', str(source)]}] + receipt = distribution.dependency_audit(stage, stage, commands, boost, set(), [], roots) + assert str(library.resolve()) in receipt['dependencies']['toolchain'] + + dependencies.append(hidden) + write_dependencies() + try: + distribution.dependency_audit(stage, stage, commands, boost, set(), [], roots) + except RuntimeError as error: + assert 'undeclared dependency' in str(error) and str(hidden) in str(error), str(error) + else: + raise AssertionError('the audit accepted an undeclared library') + + def test_source_archive_roundtrip(root: Path) -> None: stage = root / 'unpacked source with spaces' stage.mkdir() @@ -82,6 +128,38 @@ def test_source_archive_roundtrip(root: Path) -> None: assert not (stage.parent / 'source staging').exists(), 'remove inputs before extracting' +def test_audit_reads_multiple_dependency_rules(root: Path) -> None: + stage = root / 'unpacked' + boost = root / 'boost/include' + stage.mkdir() + boost.mkdir(parents=True) + source = stage / 'main.cpp' + header = boost / 'header with spaces.hpp' + header.write_text('') + source.write_text('#include "header with spaces.hpp"\n') + compiler = shutil.which('clang++') + assert compiler + depfile = stage / 'main.d' + command = [compiler, '-I', str(boost)] + compiler_roots = distribution.compiler_search_paths(command, harness.b2_environment()) + invocation = command + ['-MD', '-MP', '-MF', str(depfile), '-c', str(source), + '-o', str(stage / 'main.o')] + subprocess.run(invocation, env=harness.b2_environment(), check=True, capture_output=True) + entries = [{'file': str(source), 'arguments': invocation}] + receipt = distribution.dependency_audit(stage, stage, entries, boost, set(), [], compiler_roots) + assert str(header.resolve()) in receipt['dependencies']['boost'] + + # A second nonempty rule must still be audited, not discarded with phony rules. + with depfile.open('a') as output: + output.write('other: missing.hpp\n') + try: + distribution.dependency_audit(stage, stage, entries, boost, set(), [], compiler_roots) + except RuntimeError as error: + assert 'dependency is missing' in str(error) and 'missing.hpp' in str(error), str(error) + else: + raise AssertionError('the audit skipped a dependency in a subsequent rule') + + def test_audit_rejects_hidden_headers_and_mismatched_configuration(root: Path) -> None: stage = root / 'unpacked' distribution.snapshot(stage) @@ -176,7 +254,9 @@ def test_mismatched_boost_headers_are_rejected_without_b2(root: Path) -> None: test_unpacked_native_cmake_consumer, test_unpacked_custom_configuration, test_audit_rejects_hidden_headers_and_mismatched_configuration, test_conflicting_cobalt_policies_are_rejected_without_b2, - test_mismatched_boost_headers_are_rejected_without_b2] + test_mismatched_boost_headers_are_rejected_without_b2, + test_audit_recognizes_compiler_library_search_paths, + test_audit_reads_multiple_dependency_rules] if __name__ == '__main__': sys.exit(harness.run_cases('portable_network_distribution_test', CASES, sys.argv[1:])) From 861809f9d5deb6ecf6f5f617b653b8f7dd502799 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 11:28:27 -0300 Subject: [PATCH 6/9] Validate portable libraries across compiler and browser profiles --- .github/workflows/library.yml | 8 +- AGENTS.md | 10 +- CODING-GUIDELINES.md | 274 ++++++++++-------- .../2026-11-06-portable-network-libraries.md | 65 +++++ libs/asio | 2 +- libs/cobalt | 2 +- tools/ci/actions/gcc/action.yml | 26 ++ tools/ci/actions/gcc/coroutine_probe.cpp | 46 +++ tools/ci/actions/gcc/install.py | 105 +++++++ tools/ci/gcc_test.py | 124 ++++++++ tools/ci/matrix.py | 20 +- tools/ci/matrix_test.py | 46 ++- tools/openssl/test/tls_client.cpp | 20 +- tools/test/openssl_test.py | 23 +- 14 files changed, 626 insertions(+), 145 deletions(-) create mode 100644 tools/ci/actions/gcc/action.yml create mode 100644 tools/ci/actions/gcc/coroutine_probe.cpp create mode 100644 tools/ci/actions/gcc/install.py create mode 100644 tools/ci/gcc_test.py diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 089c2562..b41a8b6f 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -207,6 +207,12 @@ jobs: - *transport-sources - *boost + # Ubuntu 26.04's GCC 15.2 crashes on standard coroutine await_suspend + # default arguments (GCC PR121643). Keep the unchanged Cobalt tests and + # install the corrected compiler independently of the runner image. + - if: matrix.id == 'gcc-15' + uses: ./tools/ci/actions/gcc + # What a WASI lane installs, which the own-lanes job installs too, by these anchors, for an # own lane on wasip2 or wasip3: a step a WASI lane needs is one of them. wit-bindgen and the # WIT are installed for every library's WASI lane, whether or not it builds a component: it @@ -315,7 +321,7 @@ jobs: - if: matrix.chrome uses: ./tools/ci/actions/chrome with: - product: ${{ matrix.library == 'beast' && 'chrome' || 'chrome-headless-shell' }} + product: ${{ (matrix.library == 'beast' || matrix.library == 'cobalt') && 'chrome' || 'chrome-headless-shell' }} - name: Build the native Beast interoperability peer if: matrix.library == 'beast' && (matrix.lane == 'browser' || matrix.lane == 'browser-node') diff --git a/AGENTS.md b/AGENTS.md index 68b76971..e6efa1e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -222,6 +222,10 @@ Jamroot is its build configuration, and `libs/<name>` is its repository. the same version (below); - b2 (B2 5.5.3 measured); - a C++20 compiler; +- the GCC 15 CI lane uses pinned GCC 15.3, since the Ubuntu runner's GCC 15.2 + has coroutine default-argument regression PR121643. Its action extracts the + official Linux-X64 image's relocatable toolchain, verifies a compile/run probe + after installation and cache restoration, and selects its matching runtime; - Python 3.9 or newer; - for WebAssembly: wasi-sdk 34 and wasmtime 50.0.1; - for WebAssembly components, such as wasi's: wit-bindgen 0.62.0, which @@ -1804,9 +1808,9 @@ 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 + Beast and Cobalt browser lanes select `product: chrome` at the same pinned + version, installed into `.local/chrome`. Their 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 checked immutable image above. Registry access diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 2c574463..8df15ea5 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -6194,6 +6194,11 @@ and independent compiler/CMake consumers. Cobalt owns its compiled sources; Asio's old Cobalt targets are compatibility aliases. Native Cobalt SSL alone uses the separately corrected WebCPP type after reproduced state/cancellation defects and explicit owner approval. The core and runner remain unchanged upstream. +On 2026-11-07 the owner reaffirmed that defects found in original Boost behavior +are documented and retained, with negative witnesses; this does not authorize +native fixes or compatibility shims, including for MSVC's no-exceptions +`co_main`. The previously approved native SSL exception remains in force, as do +the separately shipped Wasm adaptations and their correction provenance. Distribution closure uses `sources.json` in Asio and Cobalt, with B2 lists generated from the same inventories. Direct compiler and CMake consumers build @@ -6216,10 +6221,10 @@ publication remain separate gates. 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 +Boost.Asio itself, and on Emscripten its context derives from the shipped +Asio backend. Its run family suspends into the browser's event loop and yields +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 with the owner's authorization in superproject `2ba5116`. The published library @@ -6242,22 +6247,21 @@ Asio's first library-main CI and the final joint candidate remain separate gates **Interface and names.** -- **`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 - Boost.** A program sets its options the same way everywhere, code written - against either type interoperates, and Cobalt and Beast are templates over - Boost's executor. A fork of Asio's scheduler was rejected as a maintenance - burden incompatible with every library on Asio. - Source: `genesis/design.md`, D1 (proposals). -- **The library is header-only but for two translation units the build - compiles for a program, `src/browser_src.cpp` (the JavaScript of the yield, - the bridge and the promises, and the export the bridge delivers through) and - `src/cobalt_main.cpp`, each linked once by a target.** The JavaScript - functions and the export exist exactly once, and a second definition fails - at link. - Source: `genesis/specs/asio/spec.md`, Library and Build (proposals). +- **Native public types are aliases of Boost.Asio; Wasm public types select + the shipped `webcpp::asio_backend` implementation.** On Emscripten the + public context derives from that backend context and adds bounded turns. + Portable applications use `webcpp::asio` headers and names for contexts, + timers, `post`, `co_spawn`, completion tokens and executor bindings. Wasm + objects do not interoperate with separately instantiated Boost.Asio types. + The three portable libraries share the same selected implementation. + Source: owner approval, 2026-11-06, and + `docs/superpowers/specs/2026-11-06-portable-network-libraries.md`. +- **Each target links its explicit runtime source once:** + `src/browser_src.cpp` supplies the browser bridge and JavaScript imports; + `src/wasip2/pollable.cpp` and `src/wasip3/waitable.cpp` supply their WASI + bridges. Cobalt owns its separately compiled core and runner. B2 and + external builds consume these shipped sources without modifying Boost. + Source: `doc/distribution.adoc` (asio) and the portable-library contract. - **The convenience header `<webcpp/asio.hpp>` leaves out `<webcpp/asio/ssl.hpp>`.** Natively that header brings OpenSSL, which a user of the rest should not pay for. @@ -6275,16 +6279,17 @@ 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 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 +- **On single-thread Emscripten the shipped backend disables threads in every + translation unit, `browser-src` included; explicit pthread builds retain + its POSIX thread configuration.** Both link embind, + `browser-src`, the variant's link flags and the tag rule. The backend'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 WASIp2/P3 through the checked - Boost 1.92 overlay; WASI supports guest TCP/UDP and optional source-built TLS.** A library +- **The library uses Boost.Asio's native types and a checked, shipped backend + derived from Boost 1.92 on Emscripten and WASIp2/P3; 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 @@ -6310,15 +6315,16 @@ Asio's first library-main CI and the final joint candidate remain separate gates **The run family and the turn limit.** -- **On Emscripten the six members of the run family hide Boost's and compose +- **On Emscripten the six members of the run family hide the backend's and compose `poll_one` and `run_one`: a turn of ready handlers, a return if stopped or - expired, a yield if the turn reached the limit, else one `run_one` that - suspends in the reactor's `select`; natively they are Boost's through - `using` declarations.** Boost's `run` is not virtual and cannot be told to + expired, a yield if the turn reached the limit, else one `run_one` whose + handler consumes the same turn budget.** The latter suspends in the reactor's + `select`; natively the context and its operations are Boost's unchanged + types. Boost's `run` is not virtual and cannot be told to yield: measured, a self-posting handler ran 300,000 times under it before a `setTimeout(0)` ran, because a zero-timeout `select` suspends only to a - microtask. Code that calls `run` through a `boost::asio::io_context&` gets - Boost's run without the limit, as documented. + microtask. Code that calls `run` through a `webcpp::asio_backend::io_context&` + gets the inherited backend run without the limit, as documented. Source: `genesis/design.md`, D2 (proposals). - **The yield is the `EM_ASYNC_JS` import `webcpp_asio_yield`, which awaits a promise that a `MessageChannel` message resolves.** A macrotask lets the @@ -6351,12 +6357,14 @@ Asio's first library-main CI and the final joint candidate remain separate gates one program. Source: `include/webcpp/asio/config.hpp`, `doc/run.adoc` (asio); `genesis/reference/STATUS.md` (proposals). -- **The limit counts handlers and is no time budget: up to - `k + 1 + max_handlers_per_turn` handlers can run between two yields, and a - long handler is never preempted.** Step 4's one handler belongs to no turn, - so a short turn of `k` handlers followed by a wait that ends at once runs it - with no macrotask between. - Source: `genesis/design.md`, Risks (proposals); `doc/run.adoc` (asio). +- **The limit counts every handler completed by `poll_one` or `run_one` in + the same turn, and is no time budget.** At most `max_handlers_per_turn` + handlers run between explicit cooperative yields. Only that yield resets + the budget: a wait can suspend only to microtasks, so resetting after each + wait can starve browser events and worker proxy messages. A blocking wait + may give the host an earlier opportunity to run, and a long handler is never + interrupted. Stop, expiry and exhaustion of work still return before a yield. + Source: `doc/run.adoc`, `test/turn_limit_test.cpp` (asio). - **The browser lane stops the work for the owner's decision when a turn's 95th percentile exceeds 8 ms in any of three runs, and its driver fails when no animation callback occurs.** The criterion leaves roughly half of a 60 Hz @@ -6366,8 +6374,10 @@ Asio's first library-main CI and the final joint candidate remain separate gates Source: `genesis/design.md`, D3, and `genesis/reference/STATUS.md` (proposals); `doc/yield-cost.adoc` (asio). - **The turn limit's tests count the run family's yields - (`webcpp::test::yield_counter`, every `MessagePort.postMessage`) and assert - where a `setTimeout(0)` runs, never after how many handlers.** When a + (`webcpp::test::yield_counter`, every `MessagePort.postMessage`) for both + self-posting handlers and timer-completion chains.** They pin the handler + budget between explicit yields, but assert only where a `setTimeout(0)` + runs, never after how many handlers that particular timer must run. When a `setTimeout(0)` runs is the host's: node delays it by 1 ms, a browser clamps a nested one to 4 ms and throttles a background tab's to 1 s or more. Source: `genesis/specs/asio/spec.md`, Testing (proposals). @@ -6517,19 +6527,27 @@ Asio's first library-main CI and the final joint candidate remain separate gates claims no safety. Source: `genesis/reference/STATUS.md` (proposals); `AGENTS.md`, chapter 1 (superproject branch). -- **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). +- **The shipped Wasm Cobalt promises supply `unhandled_exception` for main + and thread when exceptions are disabled; native promises remain Boost's.** + The Wasm hooks use `std::terminate` for the unreachable exception path, + retaining strict diagnostics and worker/join tests. Boost 1.92 omits those + hooks natively: MSVC rejects no-exceptions `co_main`, and a compile-failure + witness is paired with an exceptions-enabled control and a missing-member + witness. Other no-exceptions consumers remain enabled without a general + safety guarantee. + Source: `doc/differences.adoc`, `test/upstream_limits/main_no_exceptions.cpp` + (cobalt); the historical `tools/boost/cobalt-common/boost-1.92.patch` + records correction provenance only. **Allocation.** - **The io_context passes the user's allocator to Boost's constructor, an operation allocates through its handler's associated allocator, and the - bridge's map through the context's.** Run-time objects route their - allocations through the user's allocator; an allocator given to the context - is not associated with handlers, which bind it with `bind_allocator`. + bridge's map through the context's.** Native Boost retains the IOCP thread + allocation limitation described below; passing a context allocator does not + establish zero global allocation on every platform. An allocator given to + the context is not associated with handlers, which bind it with + `bind_allocator`. Source: `genesis/specs/asio/spec.md`, Allocation (proposals); `doc/allocation.adoc` (asio). - **The counting test counts every `operator new`, the C library's allocation @@ -6546,9 +6564,9 @@ Asio's first library-main CI and the final joint candidate remain separate gates **Timers, promises and events.** -- **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. +- **Timers use the selected Asio backend 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 @@ -6595,9 +6613,10 @@ 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). -- **`<webcpp/asio/ssl.hpp>` 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/ssl.hpp>` selects Boost's `ssl` natively and the shipped + Asio backend's SSL types on 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 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. @@ -6606,16 +6625,17 @@ Asio's first library-main CI and the final joint candidate remain separate gates **Boost.Cobalt.** -- **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` excludes `main.cpp` and the optional `io/ssl.cpp`, - 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 - reads, and Cobalt's own `co_main`, without the limit, is the fallback. - Source: `genesis/design.md`, D11 (proposals). +- **Cobalt owns separate native and Wasm core and runner sources, selected + by `/webcpp/cobalt//cobalt`; the old Asio and root names are compatibility + aliases.** Native `src/native/main.cpp` retains upstream behavior. Wasm + `src/wasm/main.cpp` supplies `main_promise::run_main` and `final_suspend` + over `webcpp::asio::io_context{WEBCPP_ASIO_BACKEND_CONCURRENCY_HINT_1}`, + which adds bounded turns on Emscripten. `co_main` calls the separately + compiled runner, so its settings must agree with the application. The core + excludes the runner and optional SSL implementation; `sources.json` records + all target-specific source selections. + Source: `sources.json`, `src/Jamfile`, `doc/building.adoc` (cobalt); + `genesis/design.md`, D11 (proposals), records the original runner design. - **Under Asyncify `run_main` ends the program with `std::exit` once the context and the signal set are destroyed, and `EXIT_RUNTIME` stays 0.** A `main` that suspended loses its return value under Asyncify, so the @@ -6623,9 +6643,10 @@ Asio's first library-main CI and the final joint candidate remain separate gates not promised. Source: `genesis/design.md`, D11, and `genesis/reference/STATUS.md`, task 16 (proposals). -- **`src/cobalt_main.cpp` keeps the copyright notice of Boost.Cobalt's - `main.cpp`, beside webcpp's.** It adapts that file; the task's review found - the attribution missing. +- **Cobalt's shipped `src/wasm/main.cpp` keeps the copyright notice of + Boost.Cobalt's `main.cpp`, beside webcpp's.** The earlier adaptation at + Asio's `src/cobalt_main.cpp` acquired that attribution during its original + review; the generated source preserves it after the move. Source: `genesis/reference/STATUS.md`, task 16 (proposals). **Documentation and release.** @@ -6654,10 +6675,12 @@ 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 Wasm context retains concurrency-hint constructors with and without an + allocator, including Cobalt's `io_context{1}` use. Native constructors are + Boost's unchanged constructors. +- Plain `/webcpp/cobalt//core` omits SSL; the explicit + `/webcpp/cobalt//io_ssl` supplies the corrected native or WASI wrapper. + The old `/webcpp//boost_cobalt` and `boost_cobalt_io_ssl` names are aliases. - 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. @@ -6702,16 +6725,15 @@ 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 - `bin/boost-asio-wasip3/include` for that toolset alone, keeping Boost's - scheduler and select reactor.** Boost.Asio assumes POSIX signals, `::pause` - and `ESHUTDOWN`; patching a private copy leaves the installed Boost - 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). -- **On WASIp3 the io_context uses Boost's own run family, with no turn limit, +- **Asio runs on WASIp3 (`clang-wasip3`) through its shipped backend, derived + from Boost 1.92's scheduler and select reactor with explicit platform + adaptations.** The installed Boost tree remains untouched. Maintainer import + generation checks the pinned inputs and records the generated hashes; + consumers compile the shipped headers and runtime sources directly. The + earlier private-header patching workflow is historical provenance only. + Source: `upstream/README.md`, `sources.json`, `doc/distribution.adoc` (asio); + `docs/superpowers/specs/2026-10-15-asio-wasip3.md` records the original port. +- **On WASIp3 the io_context uses the backend's 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). @@ -6738,8 +6760,8 @@ The closure record distinguishes the baseline CI from validation of later change 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. + The pinned libc lacks `sendmsg`/`recvmsg`; the shipped Asio backend contains + this adaptation without changing 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 @@ -6755,25 +6777,25 @@ The closure record distinguishes the baseline CI from validation of later change 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 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 - and the thread profile.** Unsupported local sockets, signals and serial - 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). +- **`/webcpp/cobalt//cobalt` builds on WASIp2/P3 from its shipped Wasm headers + and sources: signal, serial-port and seqpacket sources are left out, + `src/wasm/thread.cpp` comes only with threads, and the archive and its + consumers share the selected Asio backend and thread profile.** The old + `/webcpp/asio//cobalt` name is a compatibility alias. Unsupported local + sockets, signals and serial ports must not break the IP APIs, and an archive + and its program must agree about headers, threads and exceptions. + Source: `sources.json`, `src/Jamfile` (cobalt); + `docs/superpowers/plans/2026-10-16-cobalt-wasip3.md` records the original port. - **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.** 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). + Source: `src/wasm/main.cpp`, `AGENTS.md` (cobalt). - **On WASIp3 the Cobalt status driver expects host exit status 1 for a 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). + Source: `test/cobalt_status_driver.mjs` (cobalt). - **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`, @@ -6842,31 +6864,38 @@ The closure record distinguishes the baseline CI from validation of later change a future explicit process-wide crypto policy is separate work. Source: `docs/superpowers/plans/2026-10-16-ca-certificates.md` (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 - `/webcpp/asio//cobalt`, natively and on WASIp3; plain Cobalt takes no - OpenSSL.** Against a real TLS server, Boost 1.92's wrapper finished a - 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). +- **`/webcpp/cobalt//io_ssl` compiles the corrected, shipped SSL sources + independently of the plain core, and `/webcpp/cobalt//cobalt_ssl` adds the + runner and the shared `/webcpp/asio//tls` provider on native and WASIp2/P3.** + Native SSL uses `src/native_ssl.cpp` and `src/native_ssl_transfer.cpp`; + WASI uses `src/wasm/io/ssl.cpp`. Native SSL is the owner's explicit exception + to Boost type identity; plain native coroutine and I/O types, core and runner + remain upstream. The old root and Asio SSL target names are compatibility + aliases, and plain Cobalt takes no OpenSSL. Against a real TLS server, + Boost 1.92's wrapper finished a handshake with `secure` false and then + wrote plaintext, and its verification callback's constraint named + `ssl::context` for `ssl::verify_context`; the corrected wrapper fixes both + and adds the borrowed `native_ssl_handle()` for SNI. + Source: `sources.json`, `doc/differences.adoc` (cobalt); + `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` records the original correction. - **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). -- **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. The overlay also supplies the +- **The shipped Wasm Cobalt composition promise connects its cancellation + source to the handler's slot; native composition retains Boost's behavior.** + Reproduced: a composed read's cancellation hung, because Boost 1.92's + composition promise did not attach to the received handler's slot. + The corrected Wasm sources also supply 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). + worker/join tests and the native upstream-limitation probes keep those + contracts distinct. Native SSL uses its separately corrected transfer path + without changing the upstream native composition or coroutine types. + Source: `doc/differences.adoc`, `src/native_ssl_transfer.cpp` (cobalt); + `docs/superpowers/plans/2026-10-16-cobalt-ssl-cancellation.md` records the + correction's historical overlay implementation. - **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 @@ -6882,9 +6911,15 @@ The closure record distinguishes the baseline CI from validation of later change the toolchain, the entropy and the features itself. 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. +Native Windows uses unmodified Boost.Asio, including IOCP worker and timer-thread +state that does not forward the context allocator. The earlier +`tools/boost/asio-windows` allocator overlay is historical provenance, not a +consumer build path. The Windows allocation scenario is a negative witness: +it requires observable global allocation, preserves the timer and posted-handler +checks, and prints `UPSTREAM-LIMITATION`. It establishes neither zero global +allocation nor an arbitrary allowance. A future upstream fix must fail this +witness and be reclassified. Other supported targets retain checks for zero +global allocation in the measured scenario, with its documented runtime boundaries. The `tls-integration` own lane drives real TLS, embedded trust, Cobalt state and cancellation fixtures on native and WASIp3 profiles. The native @@ -6919,6 +6954,15 @@ policies. A capability cannot grant runtime permissions. Arbitrary cross-unit AB mismatches remain caller errors; source consumers must rebuild all support units. B2 lists and external builds consume the same source inventories. +GCC 15.2's default-argument `await_suspend` regression (GCC PR121643) prevents +unmodified native Cobalt `race` applications from compiling. The GCC 15 CI lane +therefore provisions GCC 15.3 from a pinned official image and validates an +independent compile/run coroutine probe, including after cache restoration. +It does not change the native core or omit those tests. GCC 14's separate known +coroutine-allocation false positive (boostorg/cobalt#7) is scoped to the affected +test functions; the two immutable original application probes retain the warning +as nonfatal for GCC 14 alone. Consumers inherit no warning-suppression flags. + The 2026-11-07 report covers 12 original applications in 432 cells, keeping counterparts, unavailable facilities and upstream defects separate. Shared Release measurements cover 136 builds and 15,906 runtime observations, with immutable source diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md index 4648fb25..cf0b4e42 100644 --- a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -186,3 +186,68 @@ by the new classification gate; it now supplies that inventory and verifies that an unlisted neighboring file remains linted. All three failures were reproduced before correction. These findings supersede the corresponding local reconciliation claims; the original reports and failed CI logs remain preserved. + + +The second remote candidate, 349f5b3 (run 42372677128), exposed additional +portability and lane-registration failures. Its green B2 job statuses do not +certify tests: the XML report is the verdict. Corrections under verification: + +- Preserve the shipped Asio system executor's inherited fatal `noexcept` + initialization boundary explicitly; native Boost types remain unchanged. +- Keep GCC 14 coroutine-allocation false positives confined to the affected + test consumers. Use pinned GCC 15.3 for the GCC 15 lane to avoid compiler + PR121643 without changing Cobalt's coroutine code. The exact relocated + toolchain passed its compile/run probe and five ASan/UBSan Cobalt programs + in Ubuntu 26.04.1. +- Register ICMP header checks only on native; give browser/P2 timer tests their + actual Beast test dependency; exercise the unbounded backend control through + its base type. JSPI/Asyncify with EH on/off and P2 EH on/off passed locally. +- Provision Chrome for Asio's concurrency-hint and all Cobalt browser lanes, + with explicit suspension/EH expansion for direct programs and manifest-based + expansion for network counterparts. The planner regression fails without it. +- Migrate the shared OpenSSL test clients to public WebCPP Asio headers. + Move the Cobalt TLS profile matrix into Cobalt's own lane, preserving its + native S/M and supported P3 combinations and the MSVC CRT/provider checks. +- Keep SDK/upstream limitations visible rather than patching native Boost: + pinned Emscripten PIPEFS returns EAGAIN after writer closure instead of EOF; + native IOCP retains its global thread-state allocation; MSVC rejects the + upstream no-EH main promise without `unhandled_exception`. Negative witnesses + are distinct from feature support. Windows runtime results remain a remote + verification gate for the corrected candidate. + +The completed run contains 131 lane artifacts. Its reconstructed report records +47 failed test cells and refuses the two cross-library TLS lanes; green B2 job +statuses did not override that verdict. The site could not download the report +artifact after that refusal. Every reported cause has a focused local correction +or an explicit upstream/SDK limitation witness. This is not a green remote verdict. + +The browser investigation reproduced a separate starvation defect: successive +timer waits discarded the handler budget and could resume only through JavaScript +microtasks, preventing a worker proxy request from being serviced. The corrected +composition counts both polled and waited handlers until an explicit yield. A +nine-timer regression with limit four failed with zero yields and now requires +two. The unchanged Cobalt worker test, including its one-millisecond observer, +passed in real Chrome for JSPI/Asyncify with EH on/off. Fresh Asio Emscripten and +Asyncify suites passed, including stack witnesses, documentation and focused lint. + +The finite echo counterpart now uses the existing primitive `accept(socket&)` +overload, preserving native Boost while allowing cancellation. Its reset driver +waits for an echoed byte before sending RST, so the test proves that a session +was accepted. Native S/M with EH on/off and WASIp2/P3 supported profiles passed. +The immutable SPSC queue's negative control stays native; the corrected queue's +forced-interleaving tests passed on native, Emscripten's four variants and WASIp3. + +On 2026-11-07 the owner explicitly directed that newly identified original Boost +defects remain documented rather than patched. Native composed accept and MSVC's +no-EH main-promise limitation retain their negative witnesses. The previously +approved native SSL exception remains separate. Documentation now distinguishes +the shipped source layout from historical overlays and states the exact turn +budget and native allocation boundaries. Independent correction reviews found no +remaining code findings; real Windows results still require the next remote run. + +Fresh local evidence, failed controls and independent reviews are retained under +`.superpowers/sdd/2026-11-06-portable-network-libraries/publication/`. A concurrent +local TLS build once exposed an incomplete Wasm file before execution; the same +entropy/thread driver and a subsequent fresh focused build passed. No test +expectation was changed for that build-output collision. No merge has been +performed for this candidate. diff --git a/libs/asio b/libs/asio index e7cf267b..ed7c6c5f 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit e7cf267b4ab43437a09ce68f40a3994ca63b9054 +Subproject commit ed7c6c5f75d242fefb69e2b06510755a21b3be05 diff --git a/libs/cobalt b/libs/cobalt index 36b9f247..01bd516e 160000 --- a/libs/cobalt +++ b/libs/cobalt @@ -1 +1 @@ -Subproject commit 36b9f2475aab1171e0898ab87d5b9630a8e04d71 +Subproject commit 01bd516efb01eb81f42245d1e3ac157a83c1a954 diff --git a/tools/ci/actions/gcc/action.yml b/tools/ci/actions/gcc/action.yml new file mode 100644 index 00000000..e5718eca --- /dev/null +++ b/tools/ci/actions/gcc/action.yml @@ -0,0 +1,26 @@ +# 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: GCC 15.3 +description: Install the pinned official GCC toolchain and verify coroutine support. +runs: + using: composite + steps: + - name: Restore the pinned GCC toolchain + id: cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .local/gcc-15.3.0 + key: gcc-15.3.0-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('tools/ci/actions/gcc/**') }} + - name: Install and verify GCC 15.3 + shell: bash + run: python3 tools/ci/actions/gcc/install.py + - name: Cache the verified GCC toolchain + if: steps.cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .local/gcc-15.3.0 + key: ${{ steps.cache.outputs.cache-primary-key }} diff --git a/tools/ci/actions/gcc/coroutine_probe.cpp b/tools/ci/actions/gcc/coroutine_probe.cpp new file mode 100644 index 00000000..6703fafe --- /dev/null +++ b/tools/ci/actions/gcc/coroutine_probe.cpp @@ -0,0 +1,46 @@ +// 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) + +// GCC PR121643: await_suspend with an additional default argument crashed GCC +// 15.2. Compile and run this after installation and every toolchain cache restore. +#include <coroutine> + +struct task { + struct promise_type { + task get_return_object() { return {}; } + + std::suspend_never initial_suspend() noexcept { return {}; } + + std::suspend_never final_suspend() noexcept { return {}; } + + void return_void() {} + + void unhandled_exception() { __builtin_trap(); } + }; +}; + +struct operation { + int& result; + + bool await_ready() const { return false; } + + bool await_suspend(std::coroutine_handle<>, const int& value = 42) { + result = value; + return false; + } + + void await_resume() const {} +}; + +task exercise(int& result) { + co_await operation{result}; +} + +int main() { + int result = 0; + exercise(result); + return result == 42 ? 0 : 1; +} diff --git a/tools/ci/actions/gcc/install.py b/tools/ci/actions/gcc/install.py new file mode 100644 index 00000000..8df908c7 --- /dev/null +++ b/tools/ci/actions/gcc/install.py @@ -0,0 +1,105 @@ +#!/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) + +"""Install the corrected GCC 15 toolchain without changing host packages. + +The official image is fixed at its Linux-X64 manifest digest. Only /usr/local +is extracted; GCC is relocatable. Ubuntu 26.04 provides its glibc dependencies. +The runtime library path follows the compiler, including after a cache restore. +""" +from __future__ import annotations + +import os +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[4] +IMAGE = 'gcc@sha256:3a49295e08ff62055af03114fd1162403c7613f91b18b10da72b352ed9ea375b' +VERSION = '15.3.0' + + +class Failure(Exception): + """An unsupported host, untrusted directory or unusable compiler.""" + + +def run(command: list[str], *, env: dict[str, str] | None = None) -> str: + result = subprocess.run(command, env=env, text=True, capture_output=True, + check=False, timeout=600) + if result.returncode: + raise Failure(f'{command[0]} failed:\n{result.stdout}{result.stderr}') + return result.stdout + + +def runtime(prefix: Path) -> dict[str, str]: + previous = os.environ.get('LD_LIBRARY_PATH', '') + search = str(prefix / 'lib64') + (':' + previous if previous else '') + return {**os.environ, 'LD_LIBRARY_PATH': search} + + +def verify(prefix: Path) -> None: + """Reject a stale compiler or the PR121643 await_suspend regression.""" + env = runtime(prefix) + compiler = str(prefix / 'bin/g++-15') + version = run([compiler, '-dumpfullversion'], env=env).strip() + if version != VERSION: + raise Failure(f'expected GCC {VERSION}, found {version}') + with tempfile.TemporaryDirectory(prefix='webcpp-gcc-probe-') as temporary: + executable = str(Path(temporary) / 'probe') + run([compiler, '-std=c++20', '-O0', '-Wall', '-Wextra', '-Werror', + str(Path(__file__).with_name('coroutine_probe.cpp')), '-o', executable], env=env) + run([executable], env=env) + + +def prepare(prefix: Path) -> None: + """Install atomically, preserving an existing directory that is not ours.""" + marker = prefix / '.webcpp-image' + if prefix.is_symlink(): + raise Failure(f'refusing a symlink compiler prefix: {prefix}') + if prefix.exists(): + if not marker.is_file() or marker.read_text().strip() != IMAGE: + raise Failure(f'refusing an unrecognized compiler directory: {prefix}') + verify(prefix) + return + prefix.parent.mkdir(parents=True, exist_ok=True) + run(['docker', 'pull', '--platform', 'linux/amd64', IMAGE]) + container = run(['docker', 'create', '--platform', 'linux/amd64', IMAGE, '/bin/true']).strip() + if re.fullmatch(r'[0-9a-f]{12,64}', container) is None: + raise Failure('docker create did not return a container ID') + try: + with tempfile.TemporaryDirectory(dir=prefix.parent, prefix='.gcc-stage-') as temporary: + stage = Path(temporary) / 'compiler' + stage.mkdir() + run(['docker', 'cp', f'{container}:/usr/local/.', str(stage)]) + for name in ('gcc', 'g++'): + (stage / 'bin' / (name + '-15')).symlink_to(name) + verify(stage) + (stage / '.webcpp-image').write_text(IMAGE + '\n') + stage.rename(prefix) + finally: + run(['docker', 'rm', '-f', container]) + verify(prefix) + + +def install() -> None: + if (os.environ.get('RUNNER_OS'), os.environ.get('RUNNER_ARCH')) != ('Linux', 'X64'): + raise Failure('the pinned GCC toolchain requires Linux-X64') + prefix = ROOT / '.local/gcc-15.3.0' + prepare(prefix) + with Path(os.environ['GITHUB_PATH']).open('a') as output: + output.write(str(prefix / 'bin') + '\n') + with Path(os.environ['GITHUB_ENV']).open('a') as output: + output.write('LD_LIBRARY_PATH=' + runtime(prefix)['LD_LIBRARY_PATH'] + '\n') + print(f'GCC {VERSION}: coroutine compile/run probe passed; {prefix}') + + +if __name__ == '__main__': + try: + install() + except (Failure, OSError, KeyError, subprocess.TimeoutExpired) as error: + raise SystemExit(str(error)) from error diff --git a/tools/ci/gcc_test.py b/tools/ci/gcc_test.py new file mode 100644 index 00000000..79f91067 --- /dev/null +++ b/tools/ci/gcc_test.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""The GCC installer rejects unsupported hosts and verifies restored toolchains.""" +from __future__ import annotations + +from importlib.machinery import SourceFileLoader +import importlib.util +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import call, patch + +SCRIPT = Path(__file__).parent / 'actions/gcc/install.py' +SPEC = importlib.util.spec_from_file_location('gcc_install', SCRIPT) +assert SPEC and isinstance(SPEC.loader, SourceFileLoader) +installer = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(installer) + + +class GccInstallTest(unittest.TestCase): + def test_wrong_host_never_runs_docker(self): + with patch.dict(os.environ, {'RUNNER_OS': 'macOS', 'RUNNER_ARCH': 'ARM64'}): + with patch.object(installer, 'run') as run: + with self.assertRaisesRegex(installer.Failure, 'Linux-X64'): + installer.install() + run.assert_not_called() + + def test_version_mismatch_is_rejected_before_probe(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + with patch.object(installer, 'run', return_value='15.2.0\n') as run: + with self.assertRaisesRegex(installer.Failure, '15.3.0'): + installer.verify(root) + self.assertEqual(run.call_count, 1) + + def test_verified_toolchain_compiles_and_runs_coroutine_probe(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + with patch.object(installer, 'run', side_effect=['15.3.0\n', '', '']) as run: + installer.verify(root) + calls = run.call_args_list + self.assertEqual(len(calls), 3) + compile_args = calls[1].args[0] + self.assertEqual(compile_args[0], str(root / 'bin/g++-15')) + self.assertIn('-Werror', compile_args) + self.assertIn(str(SCRIPT.with_name('coroutine_probe.cpp')), compile_args) + self.assertEqual(calls[2].args[0], [compile_args[-1]]) + environment = calls[2].kwargs['env'] + self.assertTrue(environment['LD_LIBRARY_PATH'].startswith(str(root / 'lib64'))) + + def test_probe_failure_is_not_treated_as_supported(self): + with tempfile.TemporaryDirectory() as temporary: + with patch.object(installer, 'run', side_effect=['15.3.0\n', installer.Failure('ICE')]): + with self.assertRaisesRegex(installer.Failure, 'ICE'): + installer.verify(Path(temporary)) + + def test_fresh_install_uses_only_pinned_image_and_removes_container(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) / 'gcc' + seen = [] + def run(command, **_kwargs): + seen.append(command) + if command[:2] == ['docker', 'create']: + return '0123456789abcdef\n' + if command[:2] == ['docker', 'cp']: + destination = Path(command[-1]) + (destination / 'bin').mkdir() + (destination / 'bin/gcc').write_text('compiler') + (destination / 'bin/g++').write_text('compiler') + return '' + with patch.object(installer, 'run', side_effect=run), patch.object(installer, 'verify'): + installer.prepare(root) + self.assertTrue((root / 'bin/g++-15').is_symlink()) + self.assertEqual((root / '.webcpp-image').read_text().strip(), installer.IMAGE) + self.assertIn(['docker', 'pull', '--platform', 'linux/amd64', installer.IMAGE], seen) + self.assertIn(['docker', 'rm', '-f', '0123456789abcdef'], seen) + self.assertIn('@sha256:', installer.IMAGE) + + def test_failed_probe_leaves_no_install_and_cleans_container(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) / 'gcc' + def run(command, **_kwargs): + if command[:2] == ['docker', 'create']: + return '0123456789abcdef\n' + if command[:2] == ['docker', 'cp']: + (Path(command[-1]) / 'bin').mkdir() + return '' + with patch.object(installer, 'run', side_effect=run) as invoke: + with patch.object(installer, 'verify', side_effect=installer.Failure('broken')): + with self.assertRaisesRegex(installer.Failure, 'broken'): + installer.prepare(root) + self.assertFalse(root.exists()) + self.assertIn(call(['docker', 'rm', '-f', '0123456789abcdef']), + invoke.call_args_list) + + def test_unknown_existing_directory_is_preserved(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + marker = root / 'user-file' + marker.write_text('keep') + with patch.object(installer, 'run') as run: + with self.assertRaises(installer.Failure): + installer.prepare(root) + run.assert_not_called() + self.assertEqual(marker.read_text(), 'keep') + + def test_matching_cache_is_verified_without_docker(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / '.webcpp-image').write_text(installer.IMAGE + '\n') + with patch.object(installer, 'run') as run, patch.object(installer, 'verify') as verify: + installer.prepare(root) + run.assert_not_called() + verify.assert_called_once_with(root) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 320e6b5b..5e1f9a68 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -175,9 +175,13 @@ # 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'), ('asio', 'browser-workers'), - ('asio', 'browser-worker-exceptions'), + ('asio', 'browser-worker-exceptions'), ('asio', 'browser-concurrency-hint'), ('beast', 'browser'), ('beast', 'applications-browser'), - ('beast', 'applications-chat'), ('document', 'js'), ('trystero', 'interop')} + ('beast', 'applications-chat'), + ('cobalt', 'browser-workers'), ('cobalt', 'browser-runtime-probes'), + ('cobalt', 'browser-pages'), ('cobalt', 'browser-worker-pages'), + ('cobalt', 'browser-network-counterparts'), + ('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 @@ -500,6 +504,18 @@ def has_external(library: str | None) -> bool: # Own lanes select their supported suspension, exception and library policy modes. # Manifest-based browser lanes already expand suspension variants inside B2. OWN_LANE_OPTIONS = { + ('cobalt', 'browser-workers', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), + ('cobalt', 'browser-runtime-probes', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), + ('cobalt', 'browser-pages', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), + ('cobalt', 'browser-worker-pages', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), + ('cobalt', 'browser-network-counterparts', 'emscripten'): + ('exception-handling=on,off',), + ('asio', 'browser-concurrency-hint', 'emscripten'): + ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), ('asio', 'browser-workers', 'emscripten'): ('webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'), ('asio', 'browser-worker-exceptions', 'emscripten'): diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 2921492e..e65beaac 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -553,14 +553,17 @@ def test_asio_capability_lanes_cover_suspension_and_exception_modes(root): '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 browser-concurrency-hint : worker : 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 + 'emscripten.asio.browser-concurrency-hint', 'wasip2.asio.wasip2-tls'}, entries expected = { + 'browser-concurrency-hint': ['toolset=emscripten', 'webcpp-suspend=jspi,asyncify', + 'exception-handling=on,off'], 'browser-workers': ['toolset=emscripten', 'webcpp-suspend=jspi,asyncify', 'exception-handling=on,off'], 'browser-worker-exceptions': ['toolset=emscripten', 'webcpp-suspend=jspi,asyncify', @@ -1204,12 +1207,14 @@ def test_asio_browser_lane_receives_chrome(root): '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', + 'webcpp.lane browser-worker-exceptions : page : emscripten ;\n' + 'webcpp.lane browser-concurrency-hint : 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 + 'browser': True, 'browser-workers': True, 'browser-worker-exceptions': True, + 'browser-concurrency-hint': True}, entries for lane, platform in (('browser', 'emscripten'), ('applications-browser', 'emscripten'), @@ -1220,6 +1225,30 @@ def test_asio_browser_lane_receives_chrome(root): assert own_lane_entry_of(beast)['chrome'] is True, (lane, platform) +def test_cobalt_browser_lanes_receive_chrome_and_all_profiles(root): + lanes = ('browser-workers', 'browser-runtime-probes', 'browser-pages', + 'browser-worker-pages', 'browser-network-counterparts') + harness.add_library(root, 'cobalt', + 'import webcpp ;\nwebcpp.targets emscripten ;\n' + 'webcpp.original node ;\n' + 'webcpp.drive page : pass.cpp : : driver.mjs ;\n' + + ''.join(f'webcpp.lane {lane} : page : emscripten ;\n' for lane in lanes), + {'pass.cpp': 'int main() {}\n', 'driver.mjs': '', + 'package.json': '{}\n', 'package-lock.json': '{}\n'}) + entries = own_lanes(root, '--library', 'cobalt') + assert {entry['lane'] for entry in entries} == set(lanes), entries + for entry in entries: + assert entry['chrome'] is True, entry + own = matrix.parsed_own_lane(json.dumps(entry)) + command = matrix.own_lane_command(own, root / 'config.jam', root / 'lane.xml', []) + assert 'exception-handling=on,off' in command, command + if own.lane != 'browser-network-counterparts': + assert 'webcpp-suspend=jspi,asyncify' in command, command + else: + # The network lane expands suspension through its variants manifest. + assert 'webcpp-suspend=jspi,asyncify' not in command, command + + 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 # (CHROME_LANES), says chrome, on every target it runs on, and its job installs the pinned @@ -1227,8 +1256,12 @@ def test_a_browser_lane_has_the_pinned_chrome(root): # image's Chrome. assert matrix.CHROME_LANES == { ('asio', 'browser'), ('asio', 'browser-workers'), ('asio', 'browser-worker-exceptions'), + ('asio', 'browser-concurrency-hint'), ('beast', 'browser'), ('beast', 'applications-browser'), - ('beast', 'applications-chat'), ('document', 'js'), + ('beast', 'applications-chat'), + ('cobalt', 'browser-workers'), ('cobalt', 'browser-runtime-probes'), + ('cobalt', 'browser-pages'), ('cobalt', 'browser-worker-pages'), + ('cobalt', 'browser-network-counterparts'), ('document', 'js'), ('trystero', 'interop')}, matrix.CHROME_LANES boost_only(root) external_library(root) @@ -1239,7 +1272,9 @@ 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 + product = ("(matrix.library == 'beast' || matrix.library == 'cobalt') " + "&& 'chrome' || 'chrome-headless-shell'") + assert product 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. @@ -1478,6 +1513,7 @@ def test_an_unavailable_container_image_fails_without_a_build(root): test_the_jobs_install_the_external_dependencies, test_container_availability_does_not_block_other_lanes, test_asio_browser_lane_receives_chrome, + test_cobalt_browser_lanes_receive_chrome_and_all_profiles, 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, diff --git a/tools/openssl/test/tls_client.cpp b/tools/openssl/test/tls_client.cpp index 8d003f43..f7ced171 100644 --- a/tools/openssl/test/tls_client.cpp +++ b/tools/openssl/test/tls_client.cpp @@ -5,21 +5,23 @@ // https://www.boost.org/LICENSE_1_0.txt) #include <openssl/ssl.h> #include <array> -#include <boost/asio/ip/tcp.hpp> -#include <boost/asio/read.hpp> -#include <boost/asio/write.hpp> #include <cstdio> #include <cstdlib> #include <string_view> +#include <webcpp/asio/buffer.hpp> #include <webcpp/asio/io_context.hpp> +#include <webcpp/asio/ip/address_v4.hpp> +#include <webcpp/asio/ip/tcp.hpp> +#include <webcpp/asio/read.hpp> #include <webcpp/asio/ssl.hpp> +#include <webcpp/asio/write.hpp> #ifdef WEBCPP_TEST_EMBEDDED_CA #include <webcpp/asio/tls_client_context.hpp> #endif namespace { -using tls_stream = webcpp::asio::ssl::stream<boost::asio::ip::tcp::socket>; +using tls_stream = webcpp::asio::ssl::stream<webcpp::asio::ip::tcp::socket>; bool verify_handshake(tls_stream& stream, boost::system::error_code error, bool reject, int& result) { @@ -42,14 +44,14 @@ bool verify_handshake(tls_stream& stream, boost::system::error_code error, bool void exchange(tls_stream& stream, const std::array<char, 4>& request, std::array<char, 4>& response, int& result) { - boost::asio::async_write( - stream, boost::asio::buffer(request), + webcpp::asio::async_write( + stream, webcpp::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), + webcpp::asio::async_read( + stream, webcpp::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") { @@ -118,7 +120,7 @@ int main(int argc, char* const* argv) { std::array<char, 4> response{}; int result = 1; stream.next_layer().async_connect( - {boost::asio::ip::address_v4::loopback(), port}, [&](boost::system::error_code ec) { + {webcpp::asio::ip::address_v4::loopback(), port}, [&](boost::system::error_code ec) { if (ec) { static_cast<void>(std::fprintf(stderr, "connect: %s\n", ec.message().c_str())); return; diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index c2b41d3e..90576766 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -252,12 +252,18 @@ def test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles(root: Path) -> Non jamroot.write_text(jamroot.read_text().replace('<conditional>@boost-check', '<webcpp-boost-check>off')) for version in ('14.3', '14.5'): - for lane, variant in ((f'openssl-upstream-msvc-{version}', 'release'), - ('tls-integration', 'debug')): + lanes = ( + ('asio', f'openssl-upstream-msvc-{version}', 'release', ['tls_client.cpp']), + ('asio', 'tls-integration', 'debug', + ['tls_client.cpp', 'tls_client_embedded.cpp']), + ('cobalt', 'tls-integration', 'debug', + ['cobalt_ssl_client.cpp', 'cobalt_ssl_state.cpp', 'cobalt_ssl_cancel.cpp']), + ) + for library, lane, variant, sources in lanes: result = harness.run_b2( root, '-a', '-n', '-d+2', f'toolset=msvc-{version}', 'target-os=windows', 'architecture=x86', 'address-model=64', - f'libs/asio/test/tls//{lane}') + f'libs/{library}/test/tls//{lane}') harness.expect(result, True, 'webcpp-openssl.build') commands = [line for line in result.stdout.splitlines() if '--source "' in line and '--threading "' in line] @@ -284,11 +290,11 @@ def test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles(root: Path) -> Non 'multi': {'headers', 'archives'}}, (version, lane, stages) assert set(profiles) == {'single', 'multi'}, (version, lane, profiles) assert profiles['single'].isdisjoint(profiles['multi']), profiles - sources = ['tls_client.cpp'] - if lane == 'tls-integration': - sources += ['tls_client_embedded.cpp', 'cobalt_ssl_client.cpp', - 'cobalt_ssl_state.cpp', 'cobalt_ssl_cancel.cpp'] lines = [line.replace('\\', '/') for line in result.stdout.splitlines()] + foreign = ('libs/cobalt/test/tls/cobalt_ssl_' if library == 'asio' + else 'tools/openssl/test/tls_client') + assert not any(' -c ' in line and foreign in line for line in lines), \ + (library, lane, foreign) drivers = [line.strip() for line in lines if '/tools/drive/drive.py"' in line] for source in sources: folder = ('libs/cobalt/test/tls' if source.startswith('cobalt_') @@ -317,7 +323,8 @@ def test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles(root: Path) -> Non assert output, links[0] executable = output.group(1) assert any(line.endswith(f'"{executable}"') for line in drivers), drivers - print(f'MSVC {version} {lane}: distinct S/M providers and fixture links verified') + print(f'MSVC {version} {library}/{lane}: ' + 'distinct S/M providers and fixture links verified') def test_wasip3_prebuilt_component_keeps_its_main(root: Path) -> None: From 8cbca683b8a2ca9e7867b05df3d0adde1e91f903 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 12:47:12 -0300 Subject: [PATCH 7/9] cobalt: record verified SSL and upstream limitation boundaries --- CODING-GUIDELINES.md | 6 +++- .../2026-11-06-portable-network-libraries.md | 34 +++++++++++++++++++ libs/cobalt | 2 +- 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 8df15ea5..1b5dac35 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -6943,7 +6943,11 @@ sources are Boost 1.92. Wasm uses checked-in sources over the same WebCPP Asio backend as Beast. Consumer builds require no patches or replacement Boost headers. The corrected native SSL stream is an explicit owner-approved identity exception, -after real upstream state/cancellation failures. Plain Cobalt never links SSL. +after real upstream state/cancellation failures. Document the wrapper as fixing +those defects, including plaintext fallback after a failed or cancelled handshake, +with its regression evidence and supported target boundaries. The owner reaffirmed +this exception on 2026-11-07 and directed that other newly identified original +Boost defects be documented without local corrections. Plain Cobalt never links SSL. Native upstream defects outside that wrapper remain named negative probes; corrected Wasm behavior is not reported as native Boost behavior. The issue-287 no-EH caution remains informational, with versioned runtime evidence. diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md index cf0b4e42..40076603 100644 --- a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -251,3 +251,37 @@ local TLS build once exposed an incomplete Wasm file before execution; the same entropy/thread driver and a subsequent fresh focused build passed. No test expectation was changed for that build-output collision. No merge has been performed for this candidate. + +The third remote candidate, 861809f (run 42381776828), completed all eight +lint shards and tool-test shards successfully. Its report accepted all 133 XML +lanes and recorded three failed cells: the immutable ticker's MSVC C4457 warning +on 14.3 and 14.5, and a lost value in the native SPSC sequence counterpart. +The ticker adjustment is limited to that original compile probe; its bytes and +other warning policies remain unchanged. A deterministic witness reproduced the +queue's stale-notification data loss in both the original and the counterpart. +The existing wakeup correction does not fix that separate upstream defect. +Per the owner's 2026-11-07 direction, preserve that behavior, document the +limitation and withdraw the counterpart's reliable-transfer claim rather than +patching the original or accepting a probabilistic passing run. +The final site assembly also rejected Cobalt's 63-character rendered title, +which exceeds its 60-character limit. The shortened title has 51 characters; +the actual site build reproduced the rejection, then passed all 37 pages, +12 libraries, links and HTML checks with the regenerated final guide. + +The owner also reaffirmed the native SSL exception and requested explicit +fixed-defect documentation. The guide now records the corrected handshake/state, +plaintext-fallback, shutdown, composed-transfer cancellation and move behavior, +with the concrete-type and target constraints. OpenSSL and native Cobalt's +core/plain I/O remain unchanged. The new candidate still requires full remote +verification before integration; these records do not mark it green. + +Follow-up local verification passed nine deterministic queue limitation profiles +(native original/counterpart with EH on/off, Emscripten JSPI/Asyncify with EH +on/off, and cooperative WASIp3 with EH off), with three recurring matrix-policy +regressions. Real Chrome verified the unavailable SPSC UI and the remaining +portable programs in all four suspension/EH profiles. Focused clang-tidy, +Pyright, formatting, import integrity and text rules passed. The historical +source and measurement bytes remain unchanged. MSVC dry runs retained `/W4` +and `/WX`, applying `/wd4457` only to the original ticker probe. The full Cobalt +reference/guide build and independent review passed. Actual MSVC confirmation +of the new diagnostic scope and the complete remote CI remain the merge gate. diff --git a/libs/cobalt b/libs/cobalt index 01bd516e..8b06912a 160000 --- a/libs/cobalt +++ b/libs/cobalt @@ -1 +1 @@ -Subproject commit 01bd516efb01eb81f42245d1e3ac157a83c1a954 +Subproject commit 8b06912a29a292a119a398cb224056093bd1ce55 From f677c12263ae3d142bb5d9ec647ab0e0557e01f6 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 13:59:15 -0300 Subject: [PATCH 8/9] cobalt: validate the MSVC ticker object format requirement --- .../plans/2026-11-06-portable-network-libraries.md | 12 ++++++++++++ libs/cobalt | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md index 40076603..85196e6d 100644 --- a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -285,3 +285,15 @@ source and measurement bytes remain unchanged. MSVC dry runs retained `/W4` and `/WX`, applying `/wd4457` only to the original ticker probe. The full Cobalt reference/guide build and independent review passed. Actual MSVC confirmation of the new diagnostic scope and the complete remote CI remain the merge gate. + +Candidate 8cbca68 (run 42388065736) passed all eight lint shards, all eight tool +test shards, documentation and the final site assembly. Its 133 XML lanes contain +131 passing lanes and two failures: both MSVC versions compile past C4457 but +reject the immutable ticker with C1128 because its Debug object exceeds the +default COFF section limit. Only that compile probe now selects `/bigobj`. +Real B2 dry runs for 14.3/14.5 confirm the option stays confined to that command, +with `/W4` and `/WX` retained and 63 other compiler commands unaffected in each +profile. The original source hash, fresh guide/reference build, text checks and +independent review passed. The SPSC limitation probes and unavailable browser UI +passed remotely. The next complete remote run must confirm actual MSVC compilation +with the expanded object format; this recorded failure does not authorize a merge. diff --git a/libs/cobalt b/libs/cobalt index 8b06912a..fe8dd6d0 160000 --- a/libs/cobalt +++ b/libs/cobalt @@ -1 +1 @@ -Subproject commit 8b06912a29a292a119a398cb224056093bd1ce55 +Subproject commit fe8dd6d04da605a2e945ad8eda7abde1a0bfa2f4 From f9d47292dd08fc5ea23020a4640964d95ad12c3e Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sat, 7 Nov 2026 15:14:18 -0300 Subject: [PATCH 9/9] cobalt: record deterministic worker lifecycle validation --- .../2026-11-06-portable-network-libraries.md | 22 +++++++++++++++++++ libs/cobalt | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md index 85196e6d..8d2c384e 100644 --- a/docs/superpowers/plans/2026-11-06-portable-network-libraries.md +++ b/docs/superpowers/plans/2026-11-06-portable-network-libraries.md @@ -297,3 +297,25 @@ profile. The original source hash, fresh guide/reference build, text checks and independent review passed. The SPSC limitation probes and unavailable browser UI passed remotely. The next complete remote run must confirm actual MSVC compilation with the expanded object format; this recorded failure does not authorize a merge. + +Candidate f677c12 (run 42394021516) confirmed successful original ticker +compilation on both MSVC versions. All eight lint shards and tool-test shards +passed. The XML audit found a separate intermittent browser worker lifecycle +timeout in three suspension/EH profiles, despite the B2 job's zero exit status. +The same timeout reproduced locally in real Chrome before any change. + +The lifecycle test's one-millisecond readiness observer generated hundreds of +thousands of zero-timeout polls and competed with worker setup. Under identical +controlled Chrome CPU throttling, the observer failed six of twelve executions; +a posted readiness notification passed twelve of twelve. The notification +changes a timer's expiry on the creator's executor, retaining an early signal. +Separate controls cover arrival before the wait. The five-second deadline and +all cancellation, completion and executor-affinity checks remain unchanged. +This is a test synchronization correction, not a change to Boost, SDK timer +polling or a general browser worker-latency guarantee. + +Fresh native single/multi-thread profiles with EH on/off, cooperative WASIp3 +with EH off, the strict Cobalt reference/guide build and independent review +passed. The exact combined candidate still requires a new full remote verdict +before integration. Evidence remains in the ignored publication directory; +neither historical measurement archives nor the original sources are rewritten. diff --git a/libs/cobalt b/libs/cobalt index fe8dd6d0..c029fd05 160000 --- a/libs/cobalt +++ b/libs/cobalt @@ -1 +1 @@ -Subproject commit fe8dd6d04da605a2e945ad8eda7abde1a0bfa2f4 +Subproject commit c029fd0543567d6c68a9898284a75d8c15ee232d