From 3c72eea579690c131cae36528ea8b0d8793cb628 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 2 Nov 2026 23:00:08 -0500 Subject: [PATCH 01/12] docs: align WASI runtime guidance and site title [skip ci] --- AGENTS.md | 3 ++- doc/asio.adoc | 2 +- doc/building.adoc | 2 +- doc/capabilities.adoc | 4 ++-- doc/cobalt.adoc | 2 +- doc/feature-matrix.adoc | 4 +++- doc/wasip3.adoc | 6 +++--- 7 files changed, 13 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 37a5727..3a2aa4d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,7 +175,8 @@ patch and its hash manifest explicitly when changing Boost versions. `threading=single` disables Asio threads and accepts exceptions on/off. `threading=multi` selects wasi-sdk's experimental cooperative sysroot with `-pthread`; SDK 34.0 provides only its no-exceptions C++ runtime. Use Wasmtime -49.0.3 for the recorded local tests; 47.0.3 cannot load the cooperative binary. +50.0.1, the project-wide runtime; earlier tests found that 47.0.3 cannot load +the cooperative binary. Cooperative threads do not promise CPU parallelism. Preserve datagram boundaries: WASIp3 `send_to` and `async_send_to` concatenate diff --git a/doc/asio.adoc b/doc/asio.adoc index e94c374..a3f0b7c 100644 --- a/doc/asio.adoc +++ b/doc/asio.adoc @@ -4,7 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -= asio: Boost.Asio in the browser's event loop for {cpp} += asio: Boost.Asio and Cobalt for {cpp} and WebAssembly :toc: left :toclevels: 1 :idprefix: diff --git a/doc/building.adoc b/doc/building.adoc index b10f66d..54d5d59 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -344,7 +344,7 @@ The reproducible local test driver is `python3 tools/openssl/test/run.py --fresh from the superproject. It needs Python with TLS 1.3 and an OpenSSL 3 command-line program only to create short-lived server fixtures. The client links the source-built library. `WASMTIME` selects the runtime executable; the recorded -WASIp3 checks use wasi-sdk 34.0 and Wasmtime 49.0.3. See +WASIp3 checks use wasi-sdk 34.0 and Wasmtime 50.0.1. See <> for the target/variant matrix. The library's targets implement that distinction: diff --git a/doc/capabilities.adoc b/doc/capabilities.adoc index 6ae6b6a..2005162 100644 --- a/doc/capabilities.adoc +++ b/doc/capabilities.adoc @@ -30,9 +30,9 @@ distinguishes public support, isolated probes and unverified combinations. | Emscripten / Asyncify | Disabled in this integration | On or off | Existing browser integration; JavaScript exceptions when enabled. | WASIp3 / `threading=single` | Disabled | On or off -| Minimal port; both configurations tested with wasi-sdk 34.0 and Wasmtime 49.0.3. +| Minimal port; both configurations tested with wasi-sdk 34.0 and Wasmtime 50.0.1. | WASIp3 / `threading=multi` | Experimental cooperative threads | Off -| Minimal port; tested with wasi-sdk 34.0's cooperative sysroot and Wasmtime 49.0.3. +| Minimal port; tested with wasi-sdk 34.0's cooperative sysroot and Wasmtime 50.0.1. | WASIp3 / `threading=multi` | Experimental cooperative threads | On | Unavailable with the tested SDK: its cooperative sysroot has no {cpp} exception runtime. | WASIp2 | Neither profile provided | Not applicable diff --git a/doc/cobalt.adoc b/doc/cobalt.adoc index 6eee2dd..09a0b10 100644 --- a/doc/cobalt.adoc +++ b/doc/cobalt.adoc @@ -157,7 +157,7 @@ b2 toolset=clang-wasip3 variant=release tools/openssl/test//cobalt_ssl_cancel ---- Use each executable path printed by B2's link action. For WASI, put Wasmtime -49.0.3 on `PATH` or set `WASMTIME` to it. The harness needs Python with TLS 1.3 +50.0.1 on `PATH` or set `WASMTIME` to it. The harness needs Python with TLS 1.3 and an OpenSSL CLI to generate temporary local certificates; the tested {cpp} program still links WebCPP's source-built OpenSSL. diff --git a/doc/feature-matrix.adoc b/doc/feature-matrix.adoc index b3c7d9c..2eb0bf7 100644 --- a/doc/feature-matrix.adoc +++ b/doc/feature-matrix.adoc @@ -8,7 +8,9 @@ === Feature matrix by library and build profile This is a snapshot of the WebCPP integration reviewed on 2026-10-16, using -Boost 1.92.0, Emscripten 6.0.11, wasi-sdk 34.0 and Wasmtime 49.0.3. It is not a +Boost 1.92.0, Emscripten 6.0.11 and wasi-sdk 34.0. The project now selects +Wasmtime 50.0.1 for its regression suites; the original isolated probes used +Wasmtime 49.0.3. It is not a list of everything those upstream projects might support in other builds. The Asio target is `/webcpp/asio//asio`; the Cobalt integration is `/webcpp/asio//cobalt`, using Boost.Cobalt's names. Do not infer that an Asio diff --git a/doc/wasip3.adoc b/doc/wasip3.adoc index 87b3406..b632d57 100644 --- a/doc/wasip3.adoc +++ b/doc/wasip3.adoc @@ -13,7 +13,7 @@ choosing a profile; it records the restrictions that still differ from native. === Prerequisites -Use Boost 1.92.0, wasi-sdk 34.0 and Wasmtime 49.0.3 for the configuration verified +Use Boost 1.92.0, wasi-sdk 34.0 and Wasmtime 50.0.1 for the configuration verified here. The port pins the exact input headers: a newer or modified Boost requires rebasing the patch and rerunning the tests. It is not accepted silently. WASIp3 and cooperative threads require runtime support; the previously installed @@ -154,7 +154,7 @@ wrappers, refused TCP connections, TCP/UDP cancellation, EOF and result-based resolver behavior. The `libs/asio/test//cobalt_wasip3` lane checks successful and unsuccessful -command completion with an exact-status driver. Put Wasmtime 49.0.3 on `PATH`, +command completion with an exact-status driver. Put Wasmtime 50.0.1 on `PATH`, or set `WASMTIME` to its executable for that driver. The SDK maps nonzero coroutine returns to host status 1. @@ -178,4 +178,4 @@ local test commands are described in <>. The underlying platform contracts are documented by https://github.com/WebAssembly/wasi-sdk/blob/main/CoopThreading.md[wasi-sdk's cooperative-thread guide] and the -https://github.com/bytecodealliance/wasmtime/releases/tag/v49.0.3[Wasmtime release used here]. +https://github.com/bytecodealliance/wasmtime/releases/tag/v50.0.1[Wasmtime release used here]. From e551f9cf14abb66e79e5fe04960c704762b19a44 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 00:51:18 -0500 Subject: [PATCH 02/12] asio: support allocator-owned browser registrations and portable Cobalt builds [skip ci] --- AGENTS.md | 16 ++++-- build.jam | 11 ++-- doc/allocation.adoc | 5 +- doc/cobalt.adoc | 7 +-- doc/wasip3.adoc | 12 +++-- include/webcpp/asio/browser/bridge.hpp | 73 +++++++++++++++++++++++++- include/webcpp/asio/ssl.hpp | 6 +-- src/cobalt_main.cpp | 6 +-- test/cobalt_accept_cancel_test.cpp | 11 ++++ test/cobalt_io_test.cpp | 11 ++++ test/run_family_test.cpp | 6 ++- 11 files changed, 139 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3a2aa4d..914c4ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,9 +127,10 @@ Task 16 supplies `/webcpp/asio//cobalt`: Cobalt's ordinary `co_main` runs on webcpp's context. The adapter replaces both `main_promise::run_main` and `final_suspend` from Boost 1.92's main.cpp. Do not link the original runner beside it. The source target's issue 287 warning still applies without exceptions. -Clang additionally diagnoses Boost's missing unhandled_exception member in that -mode; the integration suppresses only that diagnostic for exception-free -Clang/Emscripten consumers, without changing exception handling. +The checked Cobalt common overlay supplies the required unhandled_exception +promise member when exceptions are disabled. Its unreachable exception path +calls std::terminate, without enabling exception handling or suppressing a +compiler diagnostic. The Cobalt stack probe measures real Asyncify unwinds from the runner through the yield, a Cobalt timer wait and an Asio timer wait. The timer waits cannot @@ -234,3 +235,12 @@ Run `tools/ca_certificates/run.py --fresh` locally for the native/WASIp3 matrix. Its WASIp3 clients have no certificate filesystem grants. Preserve that witness. Embedded updates require rebuilding and redeploying. Do not silently download roots during builds or runtime, or present a PEM export as Firefox's full policy. + +## Windows context-owned thread allocations + +The checked Boost 1.92 overlay in tools/boost/asio-windows forwards the context +allocator into both IOCP-owned thread constructors, including the lazily started +timer thread. It is selected only for target-os=windows and reaches compiled +Cobalt sources as well as consumers. Keep its original and patched byte hashes +pinned. Do not replace the allocation regression with a warm-up or an allowance +for extra global allocations. diff --git a/build.jam b/build.jam index 5463f38..cef21d8 100644 --- a/build.jam +++ b/build.jam @@ -17,6 +17,7 @@ import webcpp ; import webcpp-target ; use-project /webcpp/asio-wasip3 : ../../tools/boost/asio-wasip3 ; +use-project /webcpp/asio-windows : ../../tools/boost/asio-windows ; # The stack Asyncify saves a suspension in, in bytes: 8192 unless a program # asks for more with , propagated so that asio's usage @@ -84,6 +85,7 @@ explicit browser-src ; # not otherwise need them; JavaScript calls both through stackSave/Restore. # tag::asio[] alias asio : : : : include /boost//headers + windows:/webcpp/asio-windows//headers clang-wasip3:/webcpp/asio-wasip3//headers emscripten:BOOST_ASIO_DISABLE_THREADS emscripten:-lembind @@ -110,12 +112,9 @@ rule cobalt-platform ( properties * ) lib cobalt-main : src/cobalt_main.cpp : static asio /webcpp//boost_cobalt ; explicit cobalt-main ; -# Boost omits main_promise::unhandled_exception without exceptions. Clang -# diagnoses the entry coroutine anyway; suppress only that diagnostic, and -# only in the explicitly exception-free Cobalt consumer configuration. -alias cobalt : : @cobalt-platform : : asio cobalt-main /webcpp//boost_cobalt - clang,off:-Wno-coroutine-missing-unhandled-exception - emscripten,off:-Wno-coroutine-missing-unhandled-exception ; +# The checked common Cobalt patch supplies the promise member required even +# when a compiler builds the coroutine without exception handling. +alias cobalt : : @cobalt-platform : : asio cobalt-main /webcpp//boost_cobalt ; # end::cobalt[] # tag::openssl[] diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 2a56464..69c417f 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -10,7 +10,10 @@ The application supplies an allocator to the `io_context` through its `std::allocator_arg` constructor. Boost.Asio uses it for the context's services and their I/O state. On Emscripten the bridge's registration map -uses the context's allocator too. +uses the context's allocator too. On Windows, a checked Boost 1.92 overlay +forwards that allocator into IOCP's internal worker and timer thread state. +This includes the first timer operation, without warming up its thread or +allowing an extra global allocation. An asynchronous operation uses its completion handler's associated allocator. Giving an allocator to the context does not associate it with diff --git a/doc/cobalt.adoc b/doc/cobalt.adoc index 09a0b10..9e76620 100644 --- a/doc/cobalt.adoc +++ b/doc/cobalt.adoc @@ -70,9 +70,10 @@ Cobalt library or compile Boost's `src/main.cpp`. Exception handling follows the application. A build without exceptions prints the warning linked to https://github.com/boostorg/cobalt/issues/287[Cobalt issue 287]. -Clang's diagnostic about a missing `unhandled_exception` is suppressed only -for this exception-free target: Boost removes that member in this mode. -Other compiler warnings and their warnings-as-errors policy are unchanged. +The checked Boost 1.92 header overlay supplies the coroutine promise's +required `unhandled_exception` member when exceptions are disabled. It calls +`std::terminate` if reached; it does not enable exception propagation. +Compiler warnings and their warnings-as-errors policy are unchanged. Result adapters do not repair upstream operations that construct exception objects internally. This integration does not establish universal support for Cobalt without exceptions. diff --git a/doc/wasip3.adoc b/doc/wasip3.adoc index b632d57..0f86190 100644 --- a/doc/wasip3.adoc +++ b/doc/wasip3.adoc @@ -69,11 +69,15 @@ and the matching SDK's common libc{plus}{plus} headers. This is an experimental not a promise of CPU parallelism. In the tested SDK, requesting exceptions in this profile fails at configuration with a message naming the missing runtime. -The test launcher is for local verification: it enables WASIp3 asynchronous +The test launcher is for local and CI verification: it enables WASIp3 asynchronous components and cooperative-thread support, grants host network and name-lookup -access for the loopback tests, and bounds execution to 15 seconds. Enabling a -runtime feature does not create threads in a single-thread binary. Production -applications should choose their own timeout and network capabilities. +access for the loopback tests, and bounds each guest's execution to 600 seconds. +The global lane also runs large finite document and Unicode workloads. Set +`WEBCPP_WASIP3_TEST_TIMEOUT` to a positive integer number of seconds to choose +another bound, for example `WEBCPP_WASIP3_TEST_TIMEOUT=15` for focused loopback +tests. Invalid or zero bounds fail before launch. Enabling a runtime feature +does not create threads in a single-thread binary. Production applications +should choose their own timeout and network capabilities. === Reproduce the local verification diff --git a/include/webcpp/asio/browser/bridge.hpp b/include/webcpp/asio/browser/bridge.hpp index 5d8a937..800f754 100644 --- a/include/webcpp/asio/browser/bridge.hpp +++ b/include/webcpp/asio/browser/bridge.hpp @@ -13,6 +13,7 @@ #include #include // lint-world: a service of the io_context +#include #include #include @@ -59,6 +60,31 @@ class registration { registration& operator=(const registration&) = default; }; +/** + A registration whose lookup node lives in its owner's allocation. + + The bridge indexes it without allocating memory. Remove it before destruction, + exactly as for registration; it may not be registered in two bridges at once. +*/ +class intrusive_registration : public registration, + public boost::intrusive::avl_set_base_hook< + boost::intrusive::link_mode> { + friend class bridge; + std::uint64_t bridge_key_ = 0; + +protected: + /** Constructs an unregistered node. */ + intrusive_registration() = default; + /** Destroys an already removed node. */ + ~intrusive_registration() = default; + +public: + /** A registered node cannot be copied. */ + intrusive_registration(const intrusive_registration&) = delete; + /** A registered node cannot be assigned. */ + intrusive_registration& operator=(const intrusive_registration&) = delete; +}; + /** The io_context's bridge: the JavaScript functions through which browser events reach it, each delivering to one registration by a key that is never reused. @@ -114,6 +140,17 @@ class bridge : public boost::asio::execution_context::service { return key; } + /** + Registers an owner-allocated node without allocating lookup storage. + @param r Unregistered node that remains alive until removal or shutdown. + @return Its unique key, from the same sequence as ordinary registrations. + */ + [[nodiscard]] std::uint64_t add(intrusive_registration& r) { + r.bridge_key_ = next_++; + intrusive_.insert(r); + return r.bridge_key_; + } + /** A JavaScript function that delivers its argument to the registration key. @@ -132,7 +169,13 @@ class bridge : public boost::asio::execution_context::service { @param key A key add returned; one already removed is ignored. */ - void remove(std::uint64_t key) noexcept { registrations_.erase(key); } + void remove(std::uint64_t key) noexcept { + registrations_.erase(key); + const auto found = intrusive_.find(key, node_less{}); + if (found != intrusive_.end()) { + intrusive_.erase(found); + } + } /** Whether the bridge is delivering an event, which the run family refuses to run inside. @@ -155,6 +198,10 @@ class bridge : public boost::asio::execution_context::service { void deliver(std::uint64_t key, const emscripten::val& event) { const auto found = registrations_.find(key); if (found == registrations_.end()) { + const auto node = intrusive_.find(key, node_less{}); + if (node != intrusive_.end() && node->deliver(event)) { + remove(key); + } return; } // A registration that is done may have freed itself, and one added meanwhile may have @@ -168,6 +215,24 @@ class bridge : public boost::asio::execution_context::service { std::uint64_t, registration*, boost::hash, std::equal_to<>, boost::asio::execution_context::allocator>>; + struct node_less { + bool operator()(const intrusive_registration& a, const intrusive_registration& b) const { + return a.bridge_key_ < b.bridge_key_; + } + + bool operator()(std::uint64_t a, const intrusive_registration& b) const { + return a < b.bridge_key_; + } + + bool operator()(const intrusive_registration& a, std::uint64_t b) const { + return a.bridge_key_ < b; + } + }; + + using nodes = + boost::intrusive::avl_set, + boost::intrusive::constant_time_size>; + /** Stops the functions and shuts down every registration still held, without calling it. */ void shutdown() override { token_.set("alive", false); @@ -175,9 +240,15 @@ class bridge : public boost::asio::execution_context::service { for (auto& [key, r] : pending) { r->shutdown(); } + while (!intrusive_.empty()) { + auto& r = *intrusive_.begin(); + intrusive_.erase(intrusive_.begin()); + r.shutdown(); + } } map registrations_; + nodes intrusive_; // {alive, depth}: whether the bridge exists, which every function of the bridge reads first, // and how many of its deliveries are in progress, which its functions put back however a // delivery ends and delivering() reads. diff --git a/include/webcpp/asio/ssl.hpp b/include/webcpp/asio/ssl.hpp index 6d03c68..d8ebedc 100644 --- a/include/webcpp/asio/ssl.hpp +++ b/include/webcpp/asio/ssl.hpp @@ -238,7 +238,7 @@ class context : public context_base { @param ec Receives success. */ template - void set_verify_callback(VerifyCallback callback, boost::system::error_code& ec) { + void set_verify_callback(const VerifyCallback& callback, boost::system::error_code& ec) { if constexpr (std::is_same_v, host_name_verification>) { host_ = callback.host(); callback_ = verify_callback_kind::host_name_verification; @@ -255,9 +255,9 @@ class context : public context_base { @param callback The verification request. */ template - void set_verify_callback(VerifyCallback callback) { + void set_verify_callback(const VerifyCallback& callback) { boost::system::error_code ec; - set_verify_callback(std::move(callback), ec); + set_verify_callback(callback, ec); } #endif /** diff --git a/src/cobalt_main.cpp b/src/cobalt_main.cpp index 9590114..d9e47e7 100644 --- a/src/cobalt_main.cpp +++ b/src/cobalt_main.cpp @@ -66,11 +66,11 @@ int main_promise::run_main(::boost::cobalt::main mn) { asio::basic_signal_set& signals; asio::cancellation_signal& cancellation; - void operator()(system::error_code ec, int signal) const { - if (signal == SIGINT) { + void operator()(system::error_code ec, int signal_number) const { + if (signal_number == SIGINT) { cancellation.emit(asio::cancellation_type::total); } - if (signal == SIGTERM) { + if (signal_number == SIGTERM) { cancellation.emit(asio::cancellation_type::terminal); } if (!ec) { diff --git a/test/cobalt_accept_cancel_test.cpp b/test/cobalt_accept_cancel_test.cpp index 45587bd..6fe770f 100644 --- a/test/cobalt_accept_cancel_test.cpp +++ b/test/cobalt_accept_cancel_test.cpp @@ -25,12 +25,23 @@ namespace io = cobalt::io; namespace { +// GCC 14 misidentifies Cobalt's placement coroutine allocation and sized delete. +// Both use the resource stored before the frame; GCC 15 accepts these functions. +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 14 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmismatched-new-delete" +#endif + cobalt::promise accept_stream(io::acceptor& listener) { const auto [error, socket] = co_await cobalt::as_tuple(listener.accept()); BOOST_TEST(error == boost::asio::error::operation_aborted); BOOST_TEST(!socket.is_open()); } +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 14 +#pragma GCC diagnostic pop +#endif + } // namespace cobalt::main co_main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { diff --git a/test/cobalt_io_test.cpp b/test/cobalt_io_test.cpp index a3ce143..157ec6c 100644 --- a/test/cobalt_io_test.cpp +++ b/test/cobalt_io_test.cpp @@ -24,6 +24,13 @@ namespace io = cobalt::io; namespace { +// GCC 14 misidentifies Cobalt's placement coroutine allocation and sized delete. +// Both use the resource stored before the frame; GCC 15 accepts these functions. +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 14 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmismatched-new-delete" +#endif + cobalt::promise accept_client(io::acceptor& listener, io::stream_socket& peer) { const auto [error] = co_await cobalt::as_tuple(listener.accept(peer)); BOOST_TEST(!error); @@ -48,6 +55,10 @@ cobalt::task refused_connection(const cobalt::executor& exec) { boost::asio::error::make_error_code(boost::asio::error::connection_refused)); } +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 14 +#pragma GCC diagnostic pop +#endif + } // namespace cobalt::main co_main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { diff --git a/test/run_family_test.cpp b/test/run_family_test.cpp index a4b2424..162b51c 100644 --- a/test/run_family_test.cpp +++ b/test/run_family_test.cpp @@ -108,9 +108,13 @@ void stop_and_restart() { ++ran; io.stop(); }); - boost::asio::post(io, [&ran] { ++ran; }); BOOST_TEST_EQ(io.run(), 1U); // lint-run: the test's event loop BOOST_TEST(io.stopped()); + // IOCP may dispatch earlier queued completions before its stop packet. + // Post after the stopped run to test restart without assuming that ordering. + boost::asio::post(io, [&ran] { ++ran; }); + BOOST_TEST_EQ(io.run(), 0U); // lint-run: a stopped context must not dispatch the new work + BOOST_TEST_EQ(ran, 1); io.restart(); BOOST_TEST_EQ(io.run(), 1U); // lint-run: the test's event loop BOOST_TEST_EQ(ran, 2); From 9ed4ba8597467a1d4348cf974a0a99ee161b70e4 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 02:31:55 -0500 Subject: [PATCH 03/12] fix: protect TLS context bounds from Windows max macro [skip ci] --- include/webcpp/asio/tls_client_context.hpp | 4 +++- test/tls_client_context_test.cpp | 14 +++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/include/webcpp/asio/tls_client_context.hpp b/include/webcpp/asio/tls_client_context.hpp index b0a2c0e..5aa0234 100644 --- a/include/webcpp/asio/tls_client_context.hpp +++ b/include/webcpp/asio/tls_client_context.hpp @@ -112,7 +112,9 @@ inline boost::system::result make_tls_client_context(std::string_v return make_error_code(tls_context_error::invalid_ca_bundle); } const auto length = finish + end.size(); - if (length > static_cast(std::numeric_limits::max())) { + // Parentheses prevent the Windows max macro from expanding this function name. + // NOLINTNEXTLINE(readability-redundant-parentheses) + if (length > static_cast((std::numeric_limits::max)())) { return make_error_code(tls_context_error::invalid_ca_bundle); } const std::unique_ptr input( diff --git a/test/tls_client_context_test.cpp b/test/tls_client_context_test.cpp index f93909b..0eb44ee 100644 --- a/test/tls_client_context_test.cpp +++ b/test/tls_client_context_test.cpp @@ -5,11 +5,23 @@ // https://www.boost.org/LICENSE_1_0.txt) #include #include +#include +#include #include #include -#include +#include #include +// Windows callers can define this before including the public TLS factory. +#ifdef max +#undef max +#endif +// The lowercase name reproduces the Windows SDK macro. +// NOLINTNEXTLINE(readability-identifier-naming) +#define max(left, right) ((left) > (right) ? (left) : (right)) +#include +#undef max + int main() { auto defaults = webcpp::asio::make_tls_client_context(); BOOST_TEST(defaults.has_value()); From 6948292165c436a51b0f254de1c7486e92759979 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 03:59:29 -0500 Subject: [PATCH 04/12] asio: complete allocator, TLS and release preparation checks [skip ci] --- AGENTS.md | 24 +- build.jam | 2 + doc/allocation.adoc | 17 +- doc/asio.adoc | 6 +- doc/building.adoc | 46 +++- doc/capabilities.adoc | 4 +- doc/changelog.adoc | 33 +++ doc/feature-matrix.adoc | 14 +- doc/guarantees.adoc | 3 +- doc/sockets.adoc | 2 +- doc/testing.adoc | 28 ++- include/webcpp/asio.hpp | 2 +- include/webcpp/asio/basic_datagram_socket.hpp | 2 +- include/webcpp/asio/basic_socket_acceptor.hpp | 2 +- include/webcpp/asio/basic_stream_socket.hpp | 2 +- include/webcpp/asio/browser/async_await.hpp | 3 +- .../webcpp/asio/browser/async_wait_event.hpp | 3 +- include/webcpp/asio/browser/error.hpp | 3 +- include/webcpp/asio/config.hpp | 9 +- include/webcpp/asio/io_context.hpp | 6 +- include/webcpp/asio/ip/basic_resolver.hpp | 25 +- include/webcpp/asio/ip/tcp.hpp | 2 +- include/webcpp/asio/ip/udp.hpp | 2 +- include/webcpp/asio/ssl.hpp | 2 +- include/webcpp/asio/tls_client_context.hpp | 21 +- src/cobalt_main.cpp | 4 +- test/Jamfile | 41 +++- test/allocation_test.cpp | 221 +++++++++++++++++- test/config_test.cpp | 16 +- test/tls/Jamfile | 59 +++++ test/tls/driver.py | 34 +++ test/tls/package-lock.json | 13 ++ test/tls/package.json | 6 + test/tls_client_context_test.cpp | 4 +- test/tls_error_peer.cpp | 12 + test/tls_error_peer.hpp | 21 ++ test/tls_error_shared_test.cpp | 29 +++ 37 files changed, 635 insertions(+), 88 deletions(-) create mode 100644 doc/changelog.adoc create mode 100644 test/tls/Jamfile create mode 100644 test/tls/driver.py create mode 100644 test/tls/package-lock.json create mode 100644 test/tls/package.json create mode 100644 test/tls_error_peer.cpp create mode 100644 test/tls_error_peer.hpp create mode 100644 test/tls_error_shared_test.cpp diff --git a/AGENTS.md b/AGENTS.md index 914c4ef..eb898af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -164,7 +164,7 @@ cancellation machinery. Automatic SIGINT/SIGTERM cancellation is unavailable; host-driven graceful shutdown requires a separate application protocol. The runner-only compile test is supplemented by public-target runtime tests: `cobalt_wasi`, `cobalt_network_wasi`, `cobalt_io`, the `cobalt_wasip3` status -lane and explicit `cobalt_thread` in the cooperative profile. +lane and the recurring `threads` lane in the cooperative profile. ## WASIp3 port @@ -244,3 +244,25 @@ timer thread. It is selected only for target-os=windows and reaches compiled Cobalt sources as well as consumers. Keep its original and patched byte hashes pinned. Do not replace the allocation regression with a warm-up or an allowance for extra global allocations. + +## Joint Asio and Beast closure + +Preserve deferred initiation and owning resolver input lifetimes. Resolver host +and service storage uses the initiating token's associated allocator; an allocator +bound only when a deferred operation is launched cannot retroactively own that +captured storage. Keep the positive controls for unbound handlers and runtime +allocation attribution; never replace them with a permitted allocation count. + +The owner clarified on 2026-11-03 that Asio and Beast are intended foundations +for a later Trystero migration. Never ban their combination to avoid a dependency +conflict. All native consumers, including libdatachannel, use the same pinned +source-built OpenSSL provider. Trystero's current native backend requires threads. + +The `tls-integration` own lane runs real native and WASIp3 TLS peers, state and +cancellation checks. The native `openssl-upstream` lane additionally requests +`webcpp-openssl-tests=on` to test the exact source-built archives before use. +OpenSSL's native Perl harness is not evidence for its WASI configuration. + +Use the repository's `webcpp-documentation` skill for Diataxis organization, +AsciiDoc and generated MrDocs reference. The maintained `doc/changelog.adoc` +is the final appendix; never edit generated reference or matrix files by hand. diff --git a/build.jam b/build.jam index cef21d8..11034eb 100644 --- a/build.jam +++ b/build.jam @@ -62,6 +62,7 @@ rule asyncify-stack ( properties * ) # (include/webcpp/asio/browser/src.hpp), linked into every program on # emscripten by asio's usage requirements below. obj browser-src : src/browser_src.cpp : include /boost//headers + /webcpp/config//config emscripten:BOOST_ASIO_DISABLE_THREADS ; explicit browser-src ; @@ -85,6 +86,7 @@ explicit browser-src ; # not otherwise need them; JavaScript calls both through stackSave/Restore. # tag::asio[] alias asio : : : : include /boost//headers + /webcpp/config//config windows:/webcpp/asio-windows//headers clang-wasip3:/webcpp/asio-wasip3//headers emscripten:BOOST_ASIO_DISABLE_THREADS diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 69c417f..33aaf24 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -40,9 +40,17 @@ operation's associated allocator: * Asyncify allocates its unwind data when a call suspends. * Boost.Asio's `basic_resolver_results` allocates its result entries with `new`. The measured operation scenario above does not resolve a name. - Forward asynchronous resolution also owns copies of the input names so a - deferred operation does not borrow temporary string storage. These result - and input strings use the standard allocator, not the handler allocator. + Forward asynchronous resolution owns copies of its input names through the + initiating token's associated allocator, preserving temporary input lifetimes. + Bind the allocator when creating a deferred operation; binding one only when + later launching it cannot retroactively change its already-owned input storage. +* WASI libc allocates pipe descriptors and message storage for Asio's wakeup pipe. + The test attributes only calls creating that pipe and writes to its tracked + writer descriptors, removes descriptors on close, and exercises a real pipe + as a positive control. Ordinary user writes and allocations remain counted. +* OpenSSL owns context, trust-store and cryptographic allocations. Its memory + hooks are process-global and must be set before any OpenSSL allocation; an + Asio context cannot install a per-operation allocator for other OpenSSL users. The allocation test replaces Emscripten's `select` in the test executable with a version whose poll array is on the stack. It marks only the call to @@ -64,6 +72,9 @@ runtime initialization, not the process's cold-start memory usage. `allocation_native` runs natively, with `allocation_native_release` also checking an optimized build; `allocation` joins the Node-based WebAssembly tests with JSPI and Asyncify, each with and without exceptions. +`allocation_wasip3` checks the single-thread profile with exceptions on/off; +`allocation_wasip3_threads` checks the supported cooperative profile without +exceptions through the `threads` lane. A counting allocator services context construction, a timer, ten posts and on Emscripten the bridge's two event deliveries. The measurement includes object destruction. It requires allocations through the supplied allocator diff --git a/doc/asio.adoc b/doc/asio.adoc index a3f0b7c..b410908 100644 --- a/doc/asio.adoc +++ b/doc/asio.adoc @@ -21,8 +21,8 @@ lacks there, the configuration Asio needs to build, what wakes `run` from a browser event, and a limit on the handlers one turn runs, so that the page keeps rendering. -WASIp3 additionally provides timers and plain TCP/UDP, with single-thread and -experimental cooperative-thread profiles. See <> for their +WASIp3 additionally provides timers, TCP/UDP and optional source-built TLS, with +single-thread and experimental cooperative-thread profiles. See <> for their limits and the features available in each target variant. [#asio-reading] @@ -79,3 +79,5 @@ include::testing.adoc[] == Reference include::{reference}[leveloffset=+1] + +include::changelog.adoc[] diff --git a/doc/building.adoc b/doc/building.adoc index 54d5d59..83ab310 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -7,16 +7,21 @@ [#asio-building] == Building -asio is header-only, and is developed inside the webcpp superproject, as a -Boost library is developed inside Boost. A b2 program uses it through one -target, `/webcpp/asio//asio`, on every target: +asio is developed inside the webcpp superproject, as a Boost library is +developed inside Boost. Its headers share Boost's executor model; the browser +bridge and optional Cobalt entry point have compiled support units. A b2 +program uses `/webcpp/asio//asio` on native, Emscripten and WASIp3: [listing] ---- exe app : app.cpp /webcpp/asio//asio ; ---- -The target adds asio's headers and Boost's, and on emscripten everything +The target adds asio's headers, Boost's and the webcpp configuration dependency. +`` includes `` first; +`WEBCPP_NO_EXCEPTIONS` disables asio's throwing APIs even when the compiler +supports exceptions. An explicit `WEBCPP_ASIO_NO_EXCEPTIONS` remains supported. +On emscripten the target also supplies everything else a program needs there: the define Asio needs to build, embind, the JavaScript functions asio calls, compiled once in `src/browser_src.cpp`, the link flags of the program's suspension variant, and the variant in the @@ -289,8 +294,10 @@ Flags retain normal B2 scope: dependency-specific `cflags` belong on the OpenSSL target, not only on its consumer. Independent concurrent B2 processes should use separate `--build-dir` directories. `threading=single` builds OpenSSL with `no-threads`; `threading=multi` enables -its pthread implementation. Source-built native TLS currently requires -Clang/GCC on macOS/Linux. Windows/MSVC needs an additional nmake recipe. +its platform threading implementation. Native recipes support Clang/GCC on +macOS/Linux and MSVC on Windows. MSVC uses upstream Configure and nmake, +static archives and the B2 runtime/debug settings; the initial Windows recipe +uses portable C without requiring NASM. For a program built both natively and for the browser, use the condition below. It also selects OpenSSL for WASIp3; browser builds retain the settings adapter: @@ -318,9 +325,14 @@ Correct configuration errors as follows: The built-in default and base providers are linked statically. Loading provider modules is disabled; this configuration is not a FIPS build. WASIp3 also disables assembly, dynamic loading, QUIC, Unix-domain sockets and the OpenSSL thread pool. -Native builds retain upstream assembly optimizations. The recipe uses function -and data sections plus platform dead stripping. Do not link another copy of -OpenSSL into the same program, including through another native dependency. +Native Clang/GCC builds retain upstream assembly optimizations; the initial +MSVC recipe uses portable C. The recipe uses function and data sections plus +platform dead stripping. A program has one OpenSSL provider. Native Trystero's +`/webcpp/trystero//native` target builds pinned static libdatachannel and its +required nested sources against this same provider, so it can coexist with +Asio and Beast. Such a program selects `threading=multi` and exceptions for +Trystero's worker-thread backend. Libsecp256k1 remains externally provisioned; +`OPENSSL_ROOT` and `LIBDATACHANNEL_ROOT` do not select alternate providers. The configured certificate directory is `/etc/ssl`. A source-built library does not install a system trust store or import the macOS keychain. Use the embedded @@ -347,6 +359,17 @@ source-built library. `WASMTIME` selects the runtime executable; the recorded WASIp3 checks use wasi-sdk 34.0 and Wasmtime 50.0.1. See <> for the target/variant matrix. +The recurring own lane `b2 libs/asio/test/tls//tls-integration` drives those +TLS, embedded-CA, state, cancellation and entropy fixtures on native and WASIp3 +profiles. `b2 libs/asio/test/tls//openssl-upstream` is native only: it requests +`webcpp-openssl-tests=on`, builds and runs upstream's full `alltests` suite, +then links a TLS consumer against those exact archives. The +`openssl-upstream-msvc-14.3` and `openssl-upstream-msvc-14.5` aliases exercise +that suite with the corresponding Windows CI toolsets. Ordinary consumers do +not run that suite. The upstream harness is unavailable on WASIp3; the separate +integration tests give narrower evidence and do not claim upstream-suite parity. +A lane declaration is not evidence that the current candidate passed CI. + The library's targets implement that distinction: [listing] @@ -429,8 +452,9 @@ and repeat it. Run only one updater per output directory. ==== Using installed headers -`b2 install --prefix=DIR` includes the generated `webcpp_ca_certificates.hpp` -at `DIR/include/`, alongside the installed library headers. The matching PEM +`b2 install --prefix=DIR` includes the generated +`webcpp/asio/detail/ca_certificates.hpp` under `DIR/include/`. Its private +namespace is `webcpp::asio::detail::ca_certificates`. The matching PEM source, manifest and MPL notices are under `DIR/include/webcpp/ca_certificates/`. The CA package is generated locally without compiling OpenSSL. A consumer of the installed TLS header must still configure Boost, define diff --git a/doc/capabilities.adoc b/doc/capabilities.adoc index 2005162..ddd8b9e 100644 --- a/doc/capabilities.adoc +++ b/doc/capabilities.adoc @@ -63,8 +63,8 @@ WASIp2 supports none of these features through this library's declared targets. | Steady/system timers, expiry changes and cancellation | Supported | Supported | Supported | Supported | Context and associated-handler allocators -| Boost contract | Supported | Boost contract; dedicated allocation counters unverified -| Boost contract; dedicated allocation counters unverified +| Boost contract | Supported | Context/timer/post counters tested +| Context/timer/post counters tested; named libc pipe allocations separate | Multiple threads posting or running a context | Boost contract | Unavailable | Unavailable | Tested: wakeup and two runners | {cpp}20 Boost.Asio `awaitable` / `co_spawn` diff --git a/doc/changelog.adoc b/doc/changelog.adoc new file mode 100644 index 0000000..f124963 --- /dev/null +++ b/doc/changelog.adoc @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[appendix] +[#asio-changelog] +== Changelog + +Changes prepared for the first WebCPP release. + +[#asio-changelog-unreleased] +=== Unreleased + +// tag::unreleased[] +// end::unreleased[] + +[#asio-changelog-0-1-0] +=== webcpp 0.1.0 + +// tag::0.1.0[] +* Added Boost.Asio contexts and timers with browser event-loop suspension. +* Added configurable browser turns, defaulting to 100 ready handlers. +* Added Promise and DOM-event operations with cancellation and allocator support. +* Added browser socket adapters, retained resolver names and TLS settings. +* Added WASIp3 TCP, UDP, timers and experimental cooperative threads. +* Added Cobalt integration with browser scheduling and WASIp3 networking. +* Added optional source-built OpenSSL and replaceable embedded CA certificates. +* Fixed Cobalt TLS state/cancellation and TLS error equality across shared libraries. +* Fixed global configuration propagation and allocator routing for resolver inputs. +* Added Diataxis guides, compiled examples and MrDocs API reference. +// end::0.1.0[] diff --git a/doc/feature-matrix.adoc b/doc/feature-matrix.adoc index 2eb0bf7..641c770 100644 --- a/doc/feature-matrix.adoc +++ b/doc/feature-matrix.adoc @@ -7,7 +7,8 @@ [#asio-feature-matrix] === Feature matrix by library and build profile -This is a snapshot of the WebCPP integration reviewed on 2026-10-16, using +This records the WebCPP integration of 2026-10-16 with the allocation and +thread-lane follow-up verified on 2026-11-03, using Boost 1.92.0, Emscripten 6.0.11 and wasi-sdk 34.0. The project now selects Wasmtime 50.0.1 for its regression suites; the original isolated probes used Wasmtime 49.0.3. It is not a @@ -174,7 +175,7 @@ runtime, including rows that do not otherwise need exceptions. | Strands | A | A | X | A | Thread pools | X | X | X | U | Asio `awaitable`, `co_spawn`, result-based timer wait | T | T | X | T -| Context/handler allocators with dedicated allocation counters | U | U | X | U +| Context/timer/post allocators with dedicated allocation counters | T | T | X | T | Allocation routing in UDP gather operations | T | T | X | T | IPv4 TCP connect/accept, read/write, EOF and cancellation | T | T | X | T | TCP composed read/write with multiple buffers | T | T | X | T @@ -203,8 +204,10 @@ host policy or destination. UDP gather concatenates into one datagram and uses the caller-associated allocator; this does not add scatter receive or connected multi-buffer send. -The other allocation-counter row remains U because the UDP test is narrower -than a complete allocation audit. Socket-option limits are in +The separate context/timer/post counters now cover all three supported WASIp3 +profiles; narrowly attributed libc wakeup-pipe allocations remain outside the +Asio allocator contract. These scenarios are not a complete audit of every +operation. Socket-option limits are in <>. TLS support does not automatically validate a Cobalt TLS completion token or `boost::cobalt::io::ssl::stream`. @@ -441,9 +444,6 @@ exception propagation or concurrent coroutine composition. | Exercise native scatter receive/connected multi-buffer UDP, resolver variants, IPv6 traffic, multicast and supported socket options. For WASIp3, record host network/DNS grants and test both permitted and denied operations. -| WASIp3 general allocation routing -| Run dedicated context/handler allocation counters for timers and posting -in S/EH on, S/EH off and M/EH off. UDP gather counters cover only that operation. | Cobalt coroutine families | Add lifecycle, result/error, cancellation and cleanup cases for tasks, promises, generators, channels, wait groups and composition; measure PMR diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index d8e114e..5a9c0eb 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -42,7 +42,8 @@ these guarantees describe their behaviour together. . [[asio-invariant-7]]With exceptions enabled, a handler's {cpp} exception propagates out of the run family as it does in Boost.Asio, natively and under both suspension variants. JavaScript errors have different rules. - See <> and <>; checked by `exceptions`. + See <> and <>; + checked by `exceptions`. . [[asio-invariant-8]]Boost's timers and Beast's timeouts complete through the reactor on both targets. Timer cancellation retains Boost's semantics, including cancellation of an individual wait through its associated slot. diff --git a/doc/sockets.adoc b/doc/sockets.adoc index 47a3d28..a0c435f 100644 --- a/doc/sockets.adoc +++ b/doc/sockets.adoc @@ -101,7 +101,7 @@ options, additional roots and client-credential requests. It does not read files, parse certificates, implement TLS or execute verification callbacks. A browser stream adapter must check this record against its capabilities before use; recording a request successfully does not mean the browser honors it. -The future webcpp::beast integration consumes these settings. +The webcpp::beast browser integration consumes these settings. A `host_name_verification` request owns its input string. The context copies that name into its own `std::pmr::string`, using the resource given to its diff --git a/doc/testing.adoc b/doc/testing.adoc index 3f31db9..023f589 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -39,7 +39,8 @@ include it does not make fails, naming it. first, defines `WEBCPP_ASIO_NO_EXCEPTIONS` when the build has no exceptions, and a program may define it itself to turn asio's exceptions off in a build that has them, as Boost.Asio's `BOOST_ASIO_NO_EXCEPTIONS` does. The tests -`config` and `config_developer_defined` check both ways it is defined. +`config`, `config_developer_defined` and `config_all_off` check compiler, +library-specific and global WebCPP settings. [#asio-testing-lanes] === The lanes @@ -405,3 +406,28 @@ small differences are not evidence that a flag makes application code faster. | `-Oz -flto` | on | 3.34 (3.21 to 3.39) | 10.93 (10.46 to 11.06) | 2.94 (2.90 to 3.11) | 14.75 (14.21 to 14.96) | `-Oz -flto` | off | 3.17 (3.09 to 3.19) | 10.27 (10.10 to 10.34) | 2.80 (2.74 to 2.99) | 11.25 (11.07 to 11.86) |=== + +threads:: +The `threads` lane runs Cobalt worker/post/join, multiple Asio context runners +and the WASIp3 allocator witness. The cooperative SDK profile uses exceptions +off and remains distinct from simultaneous native CPU execution. ++ +[source,bash] +---- +b2 -a libs/asio/test//threads +b2 -a toolset=clang-wasip3 libs/asio/test//threads +---- + +tls-integration:: +Real peers exercise trusted/rejected certificates, SNI, embedded/replacement +roots, Cobalt TLS state, encrypted transfer cancellation, and shutdown errors +and cancellation. Native single/multi profiles run with exceptions on/off; +WASIp3 runs single with exceptions on/off and cooperative with exceptions off. +The WASIp3 entropy control verifies that host randomness failure prevents +random output and key generation. It does not measure entropy quality. ++ +[source,bash] +---- +b2 -a libs/asio/test/tls//tls-integration +b2 -a toolset=clang-wasip3 libs/asio/test/tls//tls-integration +---- diff --git a/include/webcpp/asio.hpp b/include/webcpp/asio.hpp index 0bc0eb1..f54b941 100644 --- a/include/webcpp/asio.hpp +++ b/include/webcpp/asio.hpp @@ -24,7 +24,7 @@ #include // lint-world: Boost's timers are asio's #include // lint-world: Boost's timers are asio's -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN #include #include #include diff --git a/include/webcpp/asio/basic_datagram_socket.hpp b/include/webcpp/asio/basic_datagram_socket.hpp index 7232d47..c42c247 100644 --- a/include/webcpp/asio/basic_datagram_socket.hpp +++ b/include/webcpp/asio/basic_datagram_socket.hpp @@ -7,7 +7,7 @@ #ifndef WEBCPP_ASIO_BASIC_DATAGRAM_SOCKET_HPP #define WEBCPP_ASIO_BASIC_DATAGRAM_SOCKET_HPP #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include // lint-world: native sockets keep Boost semantics namespace webcpp::asio { diff --git a/include/webcpp/asio/basic_socket_acceptor.hpp b/include/webcpp/asio/basic_socket_acceptor.hpp index f9500f8..1e6c4c6 100644 --- a/include/webcpp/asio/basic_socket_acceptor.hpp +++ b/include/webcpp/asio/basic_socket_acceptor.hpp @@ -7,7 +7,7 @@ #ifndef WEBCPP_ASIO_BASIC_SOCKET_ACCEPTOR_HPP #define WEBCPP_ASIO_BASIC_SOCKET_ACCEPTOR_HPP #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include // lint-world: native sockets keep Boost semantics namespace webcpp::asio { diff --git a/include/webcpp/asio/basic_stream_socket.hpp b/include/webcpp/asio/basic_stream_socket.hpp index b6579d6..4bdd2fd 100644 --- a/include/webcpp/asio/basic_stream_socket.hpp +++ b/include/webcpp/asio/basic_stream_socket.hpp @@ -7,7 +7,7 @@ #ifndef WEBCPP_ASIO_BASIC_STREAM_SOCKET_HPP #define WEBCPP_ASIO_BASIC_STREAM_SOCKET_HPP #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include // lint-world: native sockets keep Boost semantics namespace webcpp::asio { diff --git a/include/webcpp/asio/browser/async_await.hpp b/include/webcpp/asio/browser/async_await.hpp index 506b8e5..6e5fbc2 100644 --- a/include/webcpp/asio/browser/async_await.hpp +++ b/include/webcpp/asio/browser/async_await.hpp @@ -7,6 +7,8 @@ #ifndef WEBCPP_ASIO_BROWSER_ASYNC_AWAIT_HPP #define WEBCPP_ASIO_BROWSER_ASYNC_AWAIT_HPP +#include + #include // lint-world: the operation's executor #include // lint-world: preserve handler associations when posting values #include // lint-world: operation storage belongs to its handler @@ -23,7 +25,6 @@ #include #include #include -#include namespace webcpp::asio::browser { namespace detail { diff --git a/include/webcpp/asio/browser/async_wait_event.hpp b/include/webcpp/asio/browser/async_wait_event.hpp index 2cb9847..6c58c71 100644 --- a/include/webcpp/asio/browser/async_wait_event.hpp +++ b/include/webcpp/asio/browser/async_wait_event.hpp @@ -7,6 +7,8 @@ #ifndef WEBCPP_ASIO_BROWSER_ASYNC_WAIT_EVENT_HPP #define WEBCPP_ASIO_BROWSER_ASYNC_WAIT_EVENT_HPP +#include + #include // lint-world: the operation's executor #include // lint-world: preserve handler associations when posting values #include // lint-world: operation storage belongs to its handler @@ -23,7 +25,6 @@ #include #include #include -#include namespace webcpp::asio::browser { namespace detail { diff --git a/include/webcpp/asio/browser/error.hpp b/include/webcpp/asio/browser/error.hpp index 8bb1544..5b9356d 100644 --- a/include/webcpp/asio/browser/error.hpp +++ b/include/webcpp/asio/browser/error.hpp @@ -7,10 +7,11 @@ #ifndef WEBCPP_ASIO_BROWSER_ERROR_HPP #define WEBCPP_ASIO_BROWSER_ERROR_HPP +#include + #include #include #include -#include namespace webcpp::asio::browser::error { /** Errors reported by browser operations; values are never reused. */ diff --git a/include/webcpp/asio/config.hpp b/include/webcpp/asio/config.hpp index 73d3339..bb12c89 100644 --- a/include/webcpp/asio/config.hpp +++ b/include/webcpp/asio/config.hpp @@ -13,7 +13,7 @@ #ifndef WEBCPP_ASIO_CONFIG_HPP #define WEBCPP_ASIO_CONFIG_HPP -#include +#include #ifndef WEBCPP_ASIO_DEFAULT_MAX_HANDLERS_PER_TURN /** @@ -40,8 +40,9 @@ #ifdef __MRDOCS__ /** Defined when asio is built without exceptions: automatically when the - compiler has none (`BOOST_NO_EXCEPTIONS`), or by the developer to disable them - in a build that has them. + collection has none (`WEBCPP_HAS_EXCEPTIONS` is not defined), or by the + developer to disable them in this library alone. `WEBCPP_NO_EXCEPTIONS` + disables them throughout the collection. asio raises an exception only where Boost.Asio's own interface throws: the throwing overloads of its sockets, resolver and `ssl::context` (an @@ -61,7 +62,7 @@ "asyncify-stack-size is below 8192 bytes, the least that asio's measured suspensions need, half of it left to the program: ask for 8192 or more" #endif -#if defined(BOOST_NO_EXCEPTIONS) && !defined(WEBCPP_ASIO_NO_EXCEPTIONS) +#if !defined(WEBCPP_HAS_EXCEPTIONS) && !defined(WEBCPP_ASIO_NO_EXCEPTIONS) #define WEBCPP_ASIO_NO_EXCEPTIONS #endif diff --git a/include/webcpp/asio/io_context.hpp b/include/webcpp/asio/io_context.hpp index 0a4bbef..95e18e2 100644 --- a/include/webcpp/asio/io_context.hpp +++ b/include/webcpp/asio/io_context.hpp @@ -10,7 +10,7 @@ #include #include // lint-world: the program's event loop, asio's purpose -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN #include #include #include @@ -109,7 +109,7 @@ class io_context : public boost::asio::io_context { options_.max_handlers_per_turn = n == 0 ? 1 : n; } -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN // run and run_one hide Boost's, which are not virtual: run to compose them with the turn // limit, and run_one so that the whole run family is this class's; hence the exemption from // bugprone-derived-method-shadowing-base-method. @@ -308,7 +308,7 @@ class io_context : public boost::asio::io_context { } io_context_options options_; -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN // Never armed: its construction makes the reactor, which the scheduler then waits on, so a // run with work and no timer of the program's own suspends in select, which a post wakes, // rather than in ::pause(), which nothing wakes (measured with Emscripten 6.0.11; diff --git a/include/webcpp/asio/ip/basic_resolver.hpp b/include/webcpp/asio/ip/basic_resolver.hpp index 4aa8bca..95e9cae 100644 --- a/include/webcpp/asio/ip/basic_resolver.hpp +++ b/include/webcpp/asio/ip/basic_resolver.hpp @@ -9,7 +9,7 @@ #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include // lint-world: native resolver semantics namespace webcpp::asio::ip { @@ -22,16 +22,18 @@ template using basic_resolver = boost::asio::ip::basic_resolver; } // namespace webcpp::asio::ip #else -#include // lint-world: preserve handler associations -#include // lint-world: completion token initiation -#include // lint-world: resolver error values -#include // lint-world: an unspecified address without DNS +#include // lint-world: preserve handler associations +#include // lint-world: input storage uses the token allocator +#include // lint-world: completion token initiation +#include // lint-world: resolver error values +#include // lint-world: an unspecified address without DNS #include // lint-world: Boost resolver result entries #include // lint-world: Boost resolver flags #include #include #include #include +#include #include #include #include @@ -214,6 +216,10 @@ class basic_resolver : public boost::asio::ip::resolver_base { /** Posts a forward result with service parsing flags. + + Copies the inputs with the token's associated allocator before returning. + Deferred tokens retain those copies and compute the result only when initiated. + Bind an allocator to the deferred token to select its input storage allocator. @tparam ResolveToken The completion token type. @param host The original host, copied before returning. @param service The original service, copied before returning. @@ -224,15 +230,20 @@ class basic_resolver : public boost::asio::ip::resolver_base { template auto async_resolve(std::string_view host, std::string_view service, flags resolve_flags, ResolveToken&& token) { + using input_allocator = + std::allocator_traits>>:: + template rebind_alloc; + using input_string = std::basic_string, input_allocator>; + const input_allocator allocator(boost::asio::get_associated_allocator(token)); return boost::asio::async_initiate( - [this](auto handler, const std::string& name, const std::string& port, flags mode) { + [this](auto handler, const input_string& name, const input_string& port, flags mode) { boost::system::error_code ec; auto result = resolve(name, port, mode, ec); webcpp::asio::detail::post_completion( executor_, boost::asio::append(std::move(handler), ec, std::move(result))); }, - token, std::string(host), std::string(service), resolve_flags); + token, input_string(host, allocator), input_string(service, allocator), resolve_flags); } /** diff --git a/include/webcpp/asio/ip/tcp.hpp b/include/webcpp/asio/ip/tcp.hpp index 6792122..6a41b95 100644 --- a/include/webcpp/asio/ip/tcp.hpp +++ b/include/webcpp/asio/ip/tcp.hpp @@ -9,7 +9,7 @@ #include #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include // lint-world: native protocol alias namespace webcpp::asio::ip { diff --git a/include/webcpp/asio/ip/udp.hpp b/include/webcpp/asio/ip/udp.hpp index ee2e357..fc4976b 100644 --- a/include/webcpp/asio/ip/udp.hpp +++ b/include/webcpp/asio/ip/udp.hpp @@ -9,7 +9,7 @@ #include #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include // lint-world: native protocol alias namespace webcpp::asio::ip { diff --git a/include/webcpp/asio/ssl.hpp b/include/webcpp/asio/ssl.hpp index d8ebedc..3d2690b 100644 --- a/include/webcpp/asio/ssl.hpp +++ b/include/webcpp/asio/ssl.hpp @@ -9,7 +9,7 @@ #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #ifndef WEBCPP_ASIO_HAS_OPENSSL #error \ "webcpp::asio: needs OpenSSL on native and WASIp3 targets, and it is not linked. In the program's Jamfile, add /webcpp/asio//openssl beside /webcpp/asio//asio, as in: exe app : app.cpp /webcpp/asio//asio /webcpp/asio//openssl ; b2 builds the pinned OpenSSL sources (git submodule update --init third_party/libs/openssl). (without b2: define WEBCPP_ASIO_HAS_OPENSSL=1 and link libssl and libcrypto)" diff --git a/include/webcpp/asio/tls_client_context.hpp b/include/webcpp/asio/tls_client_context.hpp index 5aa0234..0c27aec 100644 --- a/include/webcpp/asio/tls_client_context.hpp +++ b/include/webcpp/asio/tls_client_context.hpp @@ -7,18 +7,19 @@ #ifndef WEBCPP_ASIO_TLS_CLIENT_CONTEXT_HPP #define WEBCPP_ASIO_TLS_CLIENT_CONTEXT_HPP +#include + #include #include #include -#include #include -#ifndef __EMSCRIPTEN__ +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include #include #include #include -#include +#include #endif namespace webcpp::asio { @@ -36,6 +37,10 @@ namespace detail { /** The stable category for TLS context preparation failures. */ class tls_context_category final : public boost::system::error_category { public: + /** Keeps error identity across hidden shared-library boundaries. */ + constexpr tls_context_category() noexcept + : boost::system::error_category(0x6173696f2e746c73ULL) {} + /** Returns the category name. */ const char* name() const noexcept override { return "webcpp.asio.tls"; } @@ -56,6 +61,10 @@ class tls_context_category final : public boost::system::error_category { /** Converts a TLS context preparation error to its stable error code. + + Category equality is stable across native shared-library boundaries, including + hidden visibility. The library defining a returned category must remain loaded + while a caller uses the error code or its category's virtual functions. @param value The context preparation error. @return The corresponding code in the webcpp.asio.tls category. */ @@ -79,7 +88,7 @@ inline boost::system::error_code make_error_code(tls_context_error value) noexce @see "How-to: configure trusted certificate authorities", in the guide. */ inline boost::system::result make_tls_client_context(std::string_view ca_pem) { -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN (void)ca_pem; return make_error_code(tls_context_error::unsupported_target); #else @@ -158,10 +167,10 @@ inline boost::system::result make_tls_client_context(std::string_v @see "How-to: configure trusted certificate authorities", in the guide. */ inline boost::system::result make_tls_client_context() { -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN return make_error_code(tls_context_error::unsupported_target); #else - return make_tls_client_context(webcpp::detail::ca_certificates::pem); + return make_tls_client_context(webcpp::asio::detail::ca_certificates::pem); #endif } } // namespace webcpp::asio diff --git a/src/cobalt_main.cpp b/src/cobalt_main.cpp index d9e47e7..f5981d9 100644 --- a/src/cobalt_main.cpp +++ b/src/cobalt_main.cpp @@ -21,7 +21,7 @@ #include #endif -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN #include #endif @@ -84,7 +84,7 @@ int main_promise::run_main(::boost::cobalt::main mn) { asio::post(ctx.get_executor(), [coroutine] { coroutine.resume(); }); ctx.run(); // lint-run: Cobalt's application event loop } -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN // Destroy the context before exiting; a suspended Asyncify main loses a returned status. if (emscripten_has_asyncify() == 1) { std::exit(result); diff --git a/test/Jamfile b/test/Jamfile index 4e8e058..8694369 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -14,6 +14,13 @@ webcpp.original node : browser ; webcpp.run tls_client_context : tls_client_context_test.cpp : /webcpp/asio//tls : native wasip3 ; +# Hidden category singletons in the executable and shared object compare equal. +lib tls_error_peer : tls_error_peer.cpp + : shared hidden WEBCPP_TEST_ERROR_EXPORT + /webcpp/asio//tls ; +explicit tls_error_peer ; +webcpp.run tls_error_shared : tls_error_shared_test.cpp + : tls_error_peer /webcpp/asio//tls hidden : native ; webcpp.headers-alone asio : ../include : asio/tls_client_context.hpp : /webcpp/asio//tls : native wasip3 ; webcpp.run tls_client_context_browser : tls_client_context_browser_test.cpp : : emscripten ; @@ -38,15 +45,18 @@ webcpp.run cobalt_io : cobalt_io_test.cpp : /webcpp/asio//cobalt : nati webcpp.run cobalt_accept_cancel : cobalt_accept_cancel_test.cpp : /webcpp/asio//cobalt : native wasip3 ; webcpp.run cobalt_wasi : cobalt_test.cpp : /webcpp/asio//cobalt : wasip3 ; +# The SDK supports cooperative WASIp3 threads only with exceptions disabled. webcpp.run cobalt_thread : cobalt_thread_test.cpp - : /webcpp/asio//cobalt multi : native wasip3 ; + : /webcpp/asio//cobalt multi + clang-wasip3:off : native wasip3 ; explicit cobalt_thread ; # Compile the real runner independently of Cobalt's compiled I/O sources. # This must not require wasi-libc's process-signal emulation. webcpp.compile cobalt_main_wasip3 : ../src/cobalt_main.cpp : BOOST_COBALT_NO_LIB=1 : wasip3 ; webcpp.run wasi_core_threads : wasi_core_test.cpp - : multi WEBCPP_TEST_WASI_THREADS : native wasip3 ; + : multi WEBCPP_TEST_WASI_THREADS + clang-wasip3:off : native wasip3 ; explicit wasi_core_threads ; webcpp.headers-alone asio : ../include : asio.hpp asio/basic_datagram_socket.hpp asio/basic_socket_acceptor.hpp @@ -56,10 +66,10 @@ webcpp.headers-alone asio : ../include : asio.hpp asio/basic_datagram_socket.hpp # alone. webcpp.headers-alone asio : ../include : asio/browser/*.hpp asio/detail/*.hpp : : emscripten ; -# config.hpp defines WEBCPP_ASIO_NO_EXCEPTIONS exactly when the build has no -# exceptions, and keeps it when a developer defines it in a build that has -# them. +# config.hpp follows the collection exception setting and preserves a +# developer definition that disables this library alone. webcpp.compile config : config_test.cpp ; +webcpp.compile config_all_off : config_test.cpp : WEBCPP_NO_EXCEPTIONS ; webcpp.compile config_developer_defined : config_test.cpp : WEBCPP_ASIO_NO_EXCEPTIONS WEBCPP_TEST_ASIO_DEVELOPER_DEFINED ; @@ -148,6 +158,16 @@ webcpp.run timers_wasip3 : timers_test.cpp : : wasip3 ; # test alone, including release; application and size builds stay unchanged. local allocation-native-requirements = clang:-fno-builtin gcc:-fno-builtin ; +local allocation-wasi-requirements = -fno-builtin + -Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=aligned_alloc,--wrap=posix_memalign,--wrap=pipe,--wrap=write,--wrap=close ; +webcpp.run allocation_wasip3 : allocation_test.cpp + : $(allocation-wasi-requirements) : wasip3 ; +webcpp.run allocation_threads : allocation_test.cpp + : multi $(allocation-native-requirements) + clang-wasip3:off + clang-wasip3:-Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=aligned_alloc,--wrap=posix_memalign,--wrap=pipe,--wrap=write,--wrap=close + : native wasip3 ; +webcpp.lane threads : cobalt_thread wasi_core_threads allocation_threads : native wasip3 ; webcpp.run allocation_native : allocation_test.cpp : $(allocation-native-requirements) : native ; webcpp.run allocation_native_release : allocation_test.cpp @@ -155,8 +175,10 @@ webcpp.run allocation_native_release : allocation_test.cpp # Throws and catches across a suspension need exceptions, whatever the build # asks: WebAssembly's under jspi, JavaScript's under asyncify (the feature's -# composition), and natively for the twin. -webcpp.run exceptions : exceptions_test.cpp : on : native emscripten ; +# composition), and natively for the twin. WASIp3 uses its single-threaded +# runtime here because the cooperative SDK has no exception runtime. +webcpp.run exceptions : exceptions_test.cpp + : on clang-wasip3:single : native emscripten wasip3 ; webcpp.run exceptions_asyncify : exceptions_test.cpp : on asyncify : emscripten ; .asyncify += exceptions_asyncify ; @@ -291,7 +313,10 @@ webcpp.compile-fail openssl_named_on_emscripten : openssl_named_test.cpp : /webcpp/asio//openssl : emscripten ; webcpp.headers-alone asio : ../include : asio/ssl.hpp - : /webcpp/asio//openssl-tests : native emscripten ; + : /webcpp/asio//openssl-tests : native emscripten wasip3 ; webcpp.compile-fail openssl_named_c_on_emscripten : openssl_named_c_test.c : /webcpp/asio//openssl : emscripten ; + +# The TLS lane drives real loopback peers with the shared certificate fixtures. +build-project tls ; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index eb26384..69fccef 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -29,6 +30,7 @@ #include #include #include +#include #include #ifdef _MSC_VER #include @@ -46,6 +48,9 @@ #include #include #include +#elif defined(__wasi__) +#include +#include #elif defined(__APPLE__) #include #endif @@ -65,7 +70,7 @@ bool counting = false; // counts nothing: that allocation is operator new's, counted once. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool inside_operator_new = false; -// Runtime allocation attribution, set only by the Asyncify JavaScript wrapper. +// Runtime allocation attribution, set only around measured platform runtime calls. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) std::uint8_t inside_runtime = 0; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) @@ -73,8 +78,9 @@ std::size_t runtime_allocations = 0; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) std::size_t aligned_allocations = 0; -#ifdef _MSC_VER -/** Whether the calling thread is the one the test counts on: MSVC counts every thread. */ +#if defined(_MSC_VER) || (defined(__wasi__) && !defined(_REENTRANT)) +/** Whether the calling thread is the one the test counts on: single-threaded WASI and MSVC count + * every thread. */ bool on_counted_thread() noexcept { return true; } @@ -113,7 +119,8 @@ void count_this_thread() noexcept { // The C library's allocations, seen where a program can see them: glibc's // functions are replaced and forward to glibc's own (__libc_*), Emscripten's // dlmalloc defines its functions weak and keeps emscripten_builtin_*, and -// macOS reports every allocation to malloc_logger. MSVC's are not counted, nor +// macOS reports every allocation to malloc_logger, and WASI uses linker wrappers. +// MSVC's are not counted, nor // any under AddressSanitizer. #ifdef WEBCPP_TEST_ASIO_ADDRESS_SANITIZER // Nothing of the C library is counted. @@ -265,6 +272,103 @@ extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* excep } #endif +#elif defined(__wasi__) +#define WEBCPP_TEST_ASIO_COUNTS_C_ALLOCATIONS 1 + +// WASI libc owns its allocator symbols. Linker wrapping observes callers without +// replacing libc's implementation or recursively counting its internal calls. +// The linker requires the __real_ and __wrap_ symbol prefixes. +// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" { +void* __real_malloc(std::size_t size); +void* __real_calloc(std::size_t count, std::size_t size); +void* __real_realloc(void* pointer, std::size_t size); +void* __real_aligned_alloc(std::size_t alignment, std::size_t size); +int __real_posix_memalign(void** pointer, std::size_t alignment, std::size_t size); +int __real_pipe(int* descriptors); +ssize_t __real_write(int descriptor, const void* bytes, std::size_t size); +int __real_close(int descriptor); +} +// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +#define WEBCPP_TEST_C_MEMALIGN __real_aligned_alloc + +namespace { +// Descriptor ownership lets the wrapper distinguish pipe buffers from other writes. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +fd_set wasi_pipe_writers{}; + +void* observe_wasi_allocation(void* pointer, bool aligned = false) { + if (on_counted_thread() && counting && !inside_operator_new) { + if (inside_runtime != 0) { + ++runtime_allocations; + } else if (aligned) { + ++aligned_allocations; + } else { + ++c_allocations; + } + } + return pointer; +} +} // namespace + +// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" { +// wasi-libc owns the pipe descriptors and the messages written to their queue. +// These calls cannot invoke the application's Asio completion handlers. +int __wrap_pipe(int* descriptors) { + const auto previous = std::exchange(inside_runtime, 1); + const int result = __real_pipe(descriptors); + inside_runtime = previous; + if (result == 0 && descriptors[1] < FD_SETSIZE) { + FD_SET(descriptors[1], &wasi_pipe_writers); + } + return result; +} + +ssize_t __wrap_write(int descriptor, const void* bytes, std::size_t size) { + const auto previous = inside_runtime; + if (descriptor >= 0 && descriptor < FD_SETSIZE && FD_ISSET(descriptor, &wasi_pipe_writers)) { + inside_runtime = 1; + } + const auto result = __real_write(descriptor, bytes, size); + inside_runtime = previous; + return result; +} + +int __wrap_close(int descriptor) { + const int result = __real_close(descriptor); + if (result == 0 && descriptor >= 0 && descriptor < FD_SETSIZE) { + FD_CLR(descriptor, &wasi_pipe_writers); + } + return result; +} + +void* __wrap_malloc(std::size_t size) { + return observe_wasi_allocation(__real_malloc(size)); +} + +void* __wrap_calloc(std::size_t count, std::size_t size) { + return observe_wasi_allocation(__real_calloc(count, size)); +} + +void* __wrap_realloc(void* pointer, std::size_t size) { + return observe_wasi_allocation(__real_realloc(pointer, size)); +} + +void* __wrap_aligned_alloc(std::size_t alignment, std::size_t size) { + return observe_wasi_allocation(__real_aligned_alloc(alignment, size), true); +} + +int __wrap_posix_memalign(void** pointer, std::size_t alignment, std::size_t size) { + const int status = __real_posix_memalign(pointer, alignment, size); + if (status == 0) { + (void)observe_wasi_allocation(*pointer, true); + } + return status; +} +} +// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) + #elif defined(__APPLE__) #define WEBCPP_TEST_ASIO_COUNTS_C_ALLOCATIONS 1 @@ -469,7 +573,7 @@ class counted_resource final : public std::pmr::memory_resource { release(pointer); } - bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { return this == &other; } @@ -479,8 +583,8 @@ class counted_resource final : public std::pmr::memory_resource { void tls_host_storage_uses_the_resource() { namespace ssl = webcpp::asio::ssl; // The request object owns its input independently of the context's recorded copy. - // Construct it before measuring the context, then transfer it without another copy. - ssl::host_name_verification verification( + // Construct it before measuring the copy into the context's supplied resource. + const ssl::host_name_verification verification( "a-long-host-name-that-exceeds-small-string-storage.example.com"); std::size_t given = 0; counted_resource resource(given); @@ -489,7 +593,7 @@ void tls_host_storage_uses_the_resource() { const allocation_window window; ssl::context context(ssl::context::tlsv12_client, &resource); boost::system::error_code ec; - context.set_verify_callback(std::move(verification), ec); + context.set_verify_callback(verification, ec); recorded = !ec && context.verification_host() == "a-long-host-name-that-exceeds-small-string-storage.example.com"; } @@ -501,6 +605,70 @@ void tls_host_storage_uses_the_resource() { BOOST_TEST_EQ(aligned_allocations, 0U); } +/** Long resolver inputs belong to the allocator bound before initiation. */ +void resolver_inputs_use_the_associated_allocator() { + using resolver = webcpp::asio::ip::tcp::resolver; + std::size_t given = 0; + std::size_t completions = 0; + bool correct = false; + webcpp::asio::io_context io(std::allocator_arg, counted(&given)); + resolver names(io); + { + const allocation_window window; + names.async_resolve( + "a-host-name-longer-than-small-string-storage.example.com", + "an-unsupported-service-longer-than-small-string-storage", + boost::asio::bind_allocator( + counted(&given), + [&](boost::system::error_code ec, const resolver::results_type& results) { + correct = ec == boost::asio::error::service_not_found && results.empty(); + ++completions; + })); + names.cancel(); + io.run(); // lint-run: observes the real posted resolver completion + } + report("resolver invalid inputs", given); + BOOST_TEST(correct); + BOOST_TEST_EQ(completions, 1U); + BOOST_TEST_GT(given, 0U); + BOOST_TEST_EQ(operator_new_calls, 0U); + BOOST_TEST_EQ(c_allocations, 0U); + BOOST_TEST_EQ(aligned_allocations, 0U); + + std::string host = "a-host-name-longer-than-small-string-storage.example.com"; + std::string service = "00000000000000000000000000000000000443"; + const auto before = given; + auto deferred = [&] { + const allocation_window window; + return names.async_resolve( + host, service, + boost::asio::bind_allocator(counted(&given), boost::asio::deferred)); + }(); + report("resolver deferred captures", given - before); + // No result entry exists yet: Boost's result storage would allocate globally. + BOOST_TEST_GT(given, before); + BOOST_TEST_EQ(operator_new_calls, 0U); + BOOST_TEST_EQ(c_allocations, 0U); + BOOST_TEST_EQ(aligned_allocations, 0U); + host.assign("changed"); + service.assign("invalid"); + correct = false; + std::move(deferred)([&](boost::system::error_code ec, const resolver::results_type& results) { + correct = !ec && results.size() == 1 && + results.begin()->host_name() == + "a-host-name-longer-than-small-string-storage.example.com" && + results.begin()->service_name() == "00000000000000000000000000000000000443" && + results.begin()->endpoint().port() == 443; + ++completions; + }); + names.cancel(); + BOOST_TEST_EQ(completions, 1U); + io.restart(); + io.run(); // lint-run: a deferred resolution keeps its copied inputs until initiation + BOOST_TEST(correct); + BOOST_TEST_EQ(completions, 2U); +} + /** Each delivered event posts through its associated allocator, never runs inline. */ class counted_registration final : public webcpp::asio::browser::registration { public: @@ -573,14 +741,14 @@ void the_user_s_allocator_takes_everything() { })); target.call("dispatchEvent", emscripten::val::global("Event").new_(emscripten::val("message"))); - for (bool rejected : {false, true}) { + for (const bool rejected : {false, true}) { auto promise = emscripten::val::global("Promise").call( rejected ? "reject" : "resolve", 42); webcpp::asio::browser::async_await( io.get_executor(), promise, boost::asio::bind_allocator( counted(&given), - [&, rejected](boost::system::error_code ec, emscripten::val value) { + [&, rejected](boost::system::error_code ec, const emscripten::val& value) { ++promised; values_correct = values_correct && value.as() == 42 && @@ -612,7 +780,7 @@ void the_user_s_allocator_takes_everything() { // end::supplied-allocator[] -/** A real suspension proves runtime attribution without depending on a timer's deadline. */ +/** Real platform operations prove runtime attribution independently of the Asio context. */ void the_counters_separate_runtime_allocations(bool asyncify) { #if defined(__EMSCRIPTEN__) && defined(WEBCPP_TEST_ASIO_COUNTS_C_ALLOCATIONS) { @@ -628,6 +796,36 @@ void the_counters_separate_runtime_allocations(bool asyncify) { } else { BOOST_TEST_EQ(runtime_allocations, 0U); } +#elif defined(__wasi__) && defined(WEBCPP_TEST_ASIO_COUNTS_C_ALLOCATIONS) + (void)asyncify; + std::array descriptors{}; + int status = 0; + { + const allocation_window window; + status = ::pipe(descriptors.data()); + } + report("WASI libc pipe storage"); + BOOST_TEST_EQ(status, 0); + BOOST_TEST_GT(runtime_allocations, 0U); + BOOST_TEST_EQ(operator_new_calls + c_allocations + aligned_allocations, 0U); + BOOST_TEST_EQ(inside_runtime, 0U); + if (status == 0) { + ssize_t written = 0; + { + const allocation_window window; + written = ::write(descriptors[1], "x", 1); + } + report("WASI libc pipe message"); + BOOST_TEST_EQ(written, 1); + BOOST_TEST_GT(runtime_allocations, 0U); + BOOST_TEST_EQ(operator_new_calls + c_allocations + aligned_allocations, 0U); + BOOST_TEST_EQ(inside_runtime, 0U); + char received = 0; + BOOST_TEST_EQ(::read(descriptors[0], &received, 1), 1); + BOOST_TEST_EQ(received, 'x'); + ::close(descriptors[0]); + ::close(descriptors[1]); + } #else (void)asyncify; #endif @@ -860,6 +1058,7 @@ int main() { the_user_s_allocator_takes_everything(); #ifdef __EMSCRIPTEN__ tls_host_storage_uses_the_resource(); + resolver_inputs_use_the_associated_allocator(); #endif the_counters_see_an_unbound_handler(); #if defined(WEBCPP_TEST_ASIO_COUNTS_C_ALLOCATIONS) && defined(__APPLE__) && !defined(__EMSCRIPTEN__) diff --git a/test/config_test.cpp b/test/config_test.cpp index fc3c62a..9432c25 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -5,10 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // defines WEBCPP_ASIO_NO_EXCEPTIONS exactly when the -// build has no exceptions, and keeps the developer's own definition in a build -// that has them. test/Jamfile builds this file twice: as the build asks, and -// with the macro defined as a developer defines it, on the command line, which -// WEBCPP_TEST_ASIO_DEVELOPER_DEFINED tells this file. +// collection has no exceptions, and keeps the developer's own definition in a build +// that has them. test/Jamfile builds this file as the build asks, with all webcpp exceptions +// disabled, and with the library macro defined by the developer. #include @@ -22,6 +21,11 @@ #ifndef WEBCPP_ASIO_NO_EXCEPTIONS #error "config.hpp drops WEBCPP_ASIO_NO_EXCEPTIONS, which the developer defined" #endif -#elif defined(BOOST_NO_EXCEPTIONS) != defined(WEBCPP_ASIO_NO_EXCEPTIONS) -#error "WEBCPP_ASIO_NO_EXCEPTIONS is not defined exactly when the build has no exceptions" +#elif defined(WEBCPP_HAS_EXCEPTIONS) == defined(WEBCPP_ASIO_NO_EXCEPTIONS) +#error "WEBCPP_ASIO_NO_EXCEPTIONS must follow the collection exception configuration" +#endif + +#if !defined(WEBCPP_TARGET_NATIVE) && !defined(WEBCPP_TARGET_EMSCRIPTEN) && \ + !defined(WEBCPP_TARGET_WASIP3) +#error "Asio must expose the collection target configuration" #endif diff --git a/test/tls/Jamfile b/test/tls/Jamfile new file mode 100644 index 0000000..67d9da6 --- /dev/null +++ b/test/tls/Jamfile @@ -0,0 +1,59 @@ +# 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 webcpp ; +webcpp.targets native wasip3 ; +webcpp.original python3 ; + +# These are the real OpenSSL/Cobalt fixtures, now part of recurring CI rather +# than executables requiring a manual request. Both thread profiles are kept. +local tests ; +for local threading in single multi +{ + for local exceptions in "on" "off" + { + local targets = native wasip3 ; + if $(threading) = multi && $(exceptions) = "on" { targets = native ; } + for local mode in client embedded cobalt state cancel + { + local source ; + switch $(mode) + { + case client : source = tls_client ; + case embedded : source = tls_client_embedded ; + case cobalt : source = cobalt_ssl_client ; + case state : source = cobalt_ssl_state ; + case cancel : source = cobalt_ssl_cancel ; + } + local name = $(mode)-$(threading)-$(exceptions) ; + webcpp.drive $(name) : ../../../../tools/openssl/test//$(source) + : $(threading) $(exceptions) + 180 + : driver.py : $(mode) : $(targets) ; + tests += $(name) ; + } + } +} +webcpp.drive entropy : ../../../../tools/openssl/test//entropy + : off single 60 + : driver.py : entropy : wasip3 ; +webcpp.drive entropy-threads : ../../../../tools/openssl/test//threads + : off multi 60 + : driver.py : threads : native wasip3 ; +webcpp.lane tls-integration : $(tests) entropy entropy-threads : native wasip3 ; + +# Test the exact native archives before this real TLS consumer links them. +# The opt-in feature isolates the upstream suite from ordinary consumer builds. +for local threading in single multi +{ + webcpp.drive upstream-$(threading) : ../../../../tools/openssl/test//tls_client + : release $(threading) on + on 180 + : driver.py : client : native ; +} +webcpp.lane openssl-upstream : upstream-single upstream-multi : native ; +webcpp.lane openssl-upstream-msvc-14.3 : upstream-single upstream-multi : native ; +webcpp.lane openssl-upstream-msvc-14.5 : upstream-single upstream-multi : native ; diff --git a/test/tls/driver.py b/test/tls/driver.py new file mode 100644 index 0000000..5319e79 --- /dev/null +++ b/test/tls/driver.py @@ -0,0 +1,34 @@ +# 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 real-peer TLS fixtures from the Asio recurring test lane.""" + +from pathlib import Path +import subprocess +import sys + + +def main() -> None: + mode, executable = sys.argv[1:] + program = str(Path(executable).resolve()) + root = Path(__file__).resolve().parents[4] + if mode in ('entropy', 'threads'): + command = ([str(root / 'tools/boost/asio-wasip3/run.sh'), program] + if program.endswith('.wasm') else [program]) + subprocess.run(command, check=True, timeout=30) + if mode == 'entropy': + subprocess.run([*command, 'fail-entropy'], check=True, timeout=30) + return + options = {'client': ['--require-sni'], 'embedded': ['--embedded'], + 'cobalt': ['--embedded', '--require-sni'], 'state': ['--state-test'], + 'cancel': ['--state-test']} + fixture = root / 'tools/openssl/test/tls.py' + subprocess.run([sys.executable, str(fixture), program, *options[mode]], + check=True, timeout=150) + + +if __name__ == '__main__': + main() diff --git a/test/tls/package-lock.json b/test/tls/package-lock.json new file mode 100644 index 0000000..488c3f0 --- /dev/null +++ b/test/tls/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "webcpp-asio-tls-fixture", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webcpp-asio-tls-fixture", + "version": "0.0.0", + "license": "BSL-1.0" + } + } +} diff --git a/test/tls/package.json b/test/tls/package.json new file mode 100644 index 0000000..38ef57f --- /dev/null +++ b/test/tls/package.json @@ -0,0 +1,6 @@ +{ + "name": "webcpp-asio-tls-fixture", + "version": "0.0.0", + "private": true, + "license": "BSL-1.0" +} diff --git a/test/tls_client_context_test.cpp b/test/tls_client_context_test.cpp index 0eb44ee..6f3682f 100644 --- a/test/tls_client_context_test.cpp +++ b/test/tls_client_context_test.cpp @@ -34,10 +34,10 @@ int main() { const auto* roots = X509_STORE_get0_objects(SSL_CTX_get_cert_store(handle)); BOOST_TEST_GT(sk_X509_OBJECT_num(roots), 1); BOOST_TEST_EQ(static_cast(sk_X509_OBJECT_num(roots)), - webcpp::detail::ca_certificates::count); + webcpp::asio::detail::ca_certificates::count); // Supplying one authority must replace, not append to, public trust. - const std::string_view pem = webcpp::detail::ca_certificates::pem; + const std::string_view pem = webcpp::asio::detail::ca_certificates::pem; constexpr std::string_view end = "-----END CERTIFICATE-----"; const auto first = pem.substr(0, pem.find(end) + end.size()); auto replacement = webcpp::asio::make_tls_client_context(first); diff --git a/test/tls_error_peer.cpp b/test/tls_error_peer.cpp new file mode 100644 index 0000000..3ce18c1 --- /dev/null +++ b/test/tls_error_peer.cpp @@ -0,0 +1,12 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include "tls_error_peer.hpp" +#include + +boost::system::error_code webcpp::test::tls_error_from_library(int value) { + return webcpp::asio::make_error_code(static_cast(value)); +} diff --git a/test/tls_error_peer.hpp b/test/tls_error_peer.hpp new file mode 100644 index 0000000..343ed67 --- /dev/null +++ b/test/tls_error_peer.hpp @@ -0,0 +1,21 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TEST_TLS_ERROR_PEER_HPP +#define WEBCPP_TEST_TLS_ERROR_PEER_HPP + +#include +#include + +namespace webcpp::test { +#ifdef WEBCPP_TEST_ERROR_EXPORT +BOOST_SYMBOL_EXPORT +#else +BOOST_SYMBOL_IMPORT +#endif +boost::system::error_code tls_error_from_library(int value); +} // namespace webcpp::test +#endif diff --git a/test/tls_error_shared_test.cpp b/test/tls_error_shared_test.cpp new file mode 100644 index 0000000..3ab5a14 --- /dev/null +++ b/test/tls_error_shared_test.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include "tls_error_peer.hpp" + +int main() { + using webcpp::asio::tls_context_error; + for (const auto value : { + tls_context_error::invalid_ca_bundle, + tls_context_error::initialization_failed, + tls_context_error::unsupported_target, + }) { + const auto local = webcpp::asio::make_error_code(value); + const auto imported = webcpp::test::tls_error_from_library(static_cast(value)); + BOOST_TEST_NE(&local.category(), &imported.category()); + BOOST_TEST_EQ(local.value(), imported.value()); + BOOST_TEST_CSTR_EQ(local.category().name(), imported.category().name()); + BOOST_TEST(local == imported); + BOOST_TEST(local.default_error_condition() == imported.default_error_condition()); + BOOST_TEST(local != boost::system::errc::make_error_code( + boost::system::errc::operation_not_permitted)); + } + return boost::report_errors(); +} From dad1aefbe99f8a2cae4e2e3389779106a24cf3dc Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 08:37:08 -0500 Subject: [PATCH 05/12] Add WASIp2 pollable networking and supplied streams --- AGENTS.md | 16 + build.jam | 6 +- doc/Jamfile | 2 +- doc/asio.adoc | 4 + doc/capabilities.adoc | 8 +- doc/feature-matrix.adoc | 34 +- doc/wasip2.adoc | 121 +++++ .../asio/detail/wasi_pollable_descriptor.hpp | 32 ++ include/webcpp/asio/wasi/stdio_stream.hpp | 445 ++++++++++++++++++ test/Jamfile | 5 +- test/wasi_contract_test.cpp | 14 +- test/wasi_core_test.cpp | 2 +- test/wasip2/Jamfile | 33 ++ test/wasip2/counting_allocator.hpp | 43 ++ test/wasip2/idle_driver.py | 34 ++ test/wasip2/idle_test.cpp | 25 + test/wasip2/package-lock.json | 13 + test/wasip2/package.json | 7 + test/wasip2/pollable_test.cpp | 55 +++ test/wasip2/resolver_test.cpp | 155 ++++++ test/wasip2/stdio_driver.py | 30 ++ test/wasip2/stdio_test.cpp | 116 +++++ test/wasip2/write_permit_test.cpp | 95 ++++ 23 files changed, 1280 insertions(+), 15 deletions(-) create mode 100644 doc/wasip2.adoc create mode 100644 include/webcpp/asio/detail/wasi_pollable_descriptor.hpp create mode 100644 include/webcpp/asio/wasi/stdio_stream.hpp create mode 100644 test/wasip2/Jamfile create mode 100644 test/wasip2/counting_allocator.hpp create mode 100644 test/wasip2/idle_driver.py create mode 100644 test/wasip2/idle_test.cpp create mode 100644 test/wasip2/package-lock.json create mode 100644 test/wasip2/package.json create mode 100644 test/wasip2/pollable_test.cpp create mode 100644 test/wasip2/resolver_test.cpp create mode 100644 test/wasip2/stdio_driver.py create mode 100644 test/wasip2/stdio_test.cpp create mode 100644 test/wasip2/write_permit_test.cpp diff --git a/AGENTS.md b/AGENTS.md index eb898af..3629d2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,6 +166,22 @@ The runner-only compile test is supplemented by public-target runtime tests: `cobalt_wasi`, `cobalt_network_wasi`, `cobalt_io`, the `cobalt_wasip3` status lane and the recurring `threads` lane in the cooperative profile. +## WASIp2 port + +The owner approved P2 Asio core and supplied-stream WebSocket on 2026-11-03. +`/webcpp/asio//asio` supports `threading=single`, EH on/off, through the shared +checked Boost overlay. Never infer P2 TLS/Cobalt/thread support from core support. +The P2 reactor reuses libc select/poll and omits the unavailable pipe interrupter. +`tools/boost/asio-wasip2` owns the checked SDK 34.0 private descriptor-table bridge +and the asynchronous DNS extension. Revalidate its libc ABI before changing SDKs. +Preserve deferred initiation, handler associations, operation cancellation and +resource cleanup. DNS must not start a worker or block inside async initiation. +The P2 CLI stream requests output flush before switching protocol direction; +keep the real large-frame regression. Cancellation cannot preempt blocking host +imports. Run `libs/asio/test/wasip2` and its `supplied-stream` lane in both exception +profiles, plus native/P3 regressions. Keep the feature matrix and AsciiDoc guide +consistent with actual runtime evidence. + ## WASIp3 port `/webcpp/asio//asio` applies the superproject's checked Boost 1.92 patch from diff --git a/build.jam b/build.jam index 11034eb..6e913e2 100644 --- a/build.jam +++ b/build.jam @@ -17,6 +17,7 @@ import webcpp ; import webcpp-target ; use-project /webcpp/asio-wasip3 : ../../tools/boost/asio-wasip3 ; +use-project /webcpp/asio-wasip2 : ../../tools/boost/asio-wasip2 ; use-project /webcpp/asio-windows : ../../tools/boost/asio-windows ; # The stack Asyncify saves a suspension in, in bytes: 8192 unless a program @@ -88,6 +89,8 @@ explicit browser-src ; alias asio : : : : include /boost//headers /webcpp/config//config windows:/webcpp/asio-windows//headers + clang-wasip2:/webcpp/asio-wasip2//headers + clang-wasip2:/webcpp/asio-wasip2//pollable clang-wasip3:/webcpp/asio-wasip3//headers emscripten:BOOST_ASIO_DISABLE_THREADS emscripten:-lembind @@ -100,7 +103,8 @@ alias asio : : : : include /boost//headers emscripten:@webcpp%suspend-tag ; # end::asio[] -# WASIp3 uses the checked Cobalt/Asio overlays; WASIp2 has no async port. +# WASIp3 uses the checked Cobalt/Asio overlays. +# The Cobalt integration is not validated on WASIp2. rule cobalt-platform ( properties * ) { if [ webcpp-target.target-of $(properties) ] = wasip2 diff --git a/doc/Jamfile b/doc/Jamfile index 7012e68..b930f51 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -14,4 +14,4 @@ webcpp.doc asio : asio.adoc ; # (/webcpp//emscripten-reference), with the define of build.jam that a # requirement conditioned on the emscripten toolset does not give it. webcpp.reference asio : /webcpp//emscripten-reference - BOOST_ASIO_DISABLE_THREADS ; + BOOST_ASIO_DISABLE_THREADS WEBCPP_ASIO_REFERENCE ; diff --git a/doc/asio.adoc b/doc/asio.adoc index b410908..e78c897 100644 --- a/doc/asio.adoc +++ b/doc/asio.adoc @@ -21,6 +21,8 @@ lacks there, the configuration Asio needs to build, what wakes `run` from a browser event, and a limit on the handlers one turn runs, so that the page keeps rendering. +WASIp2 provides single-threaded timers, TCP/UDP, pollable-driven forward DNS and +supplied CLI streams. See <> for its explicit limitations. WASIp3 additionally provides timers, TCP/UDP and optional source-built TLS, with single-thread and experimental cooperative-thread profiles. See <> for their limits and the features available in each target variant. @@ -53,6 +55,8 @@ include::capabilities.adoc[] include::building.adoc[] +include::wasip2.adoc[] + include::wasip3.adoc[] include::run.adoc[] diff --git a/doc/capabilities.adoc b/doc/capabilities.adoc index ddd8b9e..33ffd34 100644 --- a/doc/capabilities.adoc +++ b/doc/capabilities.adoc @@ -35,8 +35,10 @@ distinguishes public support, isolated probes and unverified combinations. | Minimal port; tested with wasi-sdk 34.0's cooperative sysroot and Wasmtime 50.0.1. | WASIp3 / `threading=multi` | Experimental cooperative threads | On | Unavailable with the tested SDK: its cooperative sysroot has no {cpp} exception runtime. -| WASIp2 | Neither profile provided | Not applicable -| This library does not declare WASIp2 support. +| WASIp2 / `threading=single` | Disabled | On or off +| Core, timers, TCP/UDP, forward DNS and CLI streams tested; see <>. +| WASIp2 / `threading=multi` | Unavailable | On or off +| Rejected by the build; no cross-thread reactor wakeup is provided. |=== `variant=debug` and `variant=release` select build optimization, not different @@ -53,7 +55,7 @@ include::feature-matrix.adoc[] In the following tables, *browser* covers both JSPI and Asyncify. Their API capabilities are the same; their suspension and exception implementations differ. -WASIp2 supports none of these features through this library's declared targets. +The separate <> table records the P2 profile. [cols="3,2,2,2,2",options="header"] |=== diff --git a/doc/feature-matrix.adoc b/doc/feature-matrix.adoc index 641c770..404a351 100644 --- a/doc/feature-matrix.adoc +++ b/doc/feature-matrix.adoc @@ -66,7 +66,8 @@ it does not conceal a requirement for exceptions. | WASIp3 | M, cooperative | on | X | X | SDK 34.0 lacks the cooperative {cpp} EH runtime. | WASIp3 | M, cooperative | off | T | L | Public Cobalt target, including its thread coroutine; SDK cooperative runtime and Cobalt issue 287 apply. -| WASIp2 | S or M | on/off | X | X | Neither library target declares WASIp2 support. +| WASIp2 | S | on/off | T | B | Core, socket, forward DNS and supplied-stream consumers. +| WASIp2 | M | on/off | B | B | The current reactor profile supports one application thread. |=== *Native S is not a promise of no threads.* The native build does not set @@ -161,6 +162,37 @@ yield gives the host an opportunity to run; it does not guarantee a timer deadline or a rendered frame. EH on uses Wasm exceptions with JSPI and the configured JavaScript exception mechanism with Asyncify. +[#asio-feature-wasip2] +==== Asio on WASIp2 + +Both columns use `threading=single`, SDK 34.0 and Wasmtime 50.0.1. +Multiple threads are rejected before compilation. T is limited to the stated +consumer contracts, not every Boost.Asio overload. + +[cols="4,1,1",options="header"] +|=== +| Feature | EH on | EH off +| Run/poll family, timers and timer cancellation | T | T +| TCP connect/accept, partial transfer and shutdown | T | T +| UDP scalar, empty datagrams and gathered send_to | T | T +| Pending socket cancellation | T | T +| Async forward DNS, deferred initiation and associated executor | T | T +| Resolver-wide and per-operation cancellation | T | T +| Numeric synchronous resolution | T | T +| Canonical name, mapped-address policy and async reverse DNS | X | X +| Asio timer coroutine | T | T +| CLI stream pending read cancellation, allocator and executor | T | T +| CLI stream WebSocket client/server, text/binary and close | T | T +| UDP multiple-buffer receive and connected multiple-buffer send | X | X +| POSIX signals, local sockets and serial ports | X | X +| Cobalt runner/wrappers and guest OpenSSL | B | B +| Parallel threads, thread pools and cross-thread post | X | X +|=== + +See <> for resolver flag/allocation limits and +<> for the host-import blocking boundary. Pollable-based +waiting does not make an independently blocking host import preemptible. + [#asio-feature-wasip3] ==== Asio: WASIp3 diff --git a/doc/wasip2.adoc b/doc/wasip2.adoc new file mode 100644 index 0000000..dfcda3f --- /dev/null +++ b/doc/wasip2.adoc @@ -0,0 +1,121 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#asio-wasip2] +== Build for WASIp2 + +Use `/webcpp/asio//asio` with `toolset=clang-wasip2` and `threading=single`. +This profile uses Boost 1.92, wasi-sdk 34.0 and Wasmtime 50.0.1. Both exception +modes are supported for the core, timers, TCP/UDP and asynchronous forward DNS. +It does not enable Cobalt, guest TLS or multiple application threads. + +Configure the compiler using the project's wasi-sdk user-configuration example. +Then run the local consumers from the superproject root: + +[source,bash] +---- +b2 -a toolset=clang-wasip2 variant=release threading=single \ + exception-handling=on,off testing.launcher=tools/boost/asio-wasip2/run.sh \ + libs/asio/test/wasip2 +b2 -a toolset=clang-wasip2 variant=release exception-handling=on,off \ + libs/asio/test/wasip2//supplied-stream libs/asio/test/wasip2//scheduler-idle +---- + +The first command exercises timers, the run/poll family, TCP and UDP exchanges, +coroutines, forward name resolution and pollable readiness. The supplied-stream +lane keeps standard input open without sending data; its timer must still cancel +a pending read. Each consumer reports a passing result. The network launcher +explicitly grants socket access and IP name lookup; production hosts should grant +only the application's required capabilities. + +The idle driver uses an external watchdog and a Wasmtime fuel budget. A context +with a live work guard must remain asleep, including before a reactor is created. +The write-permit consumers exercise a real output with a controlled 64-bit quota +and cancellation against a deliberately non-ready native pollable. Those fixtures +test the adapter's boundary handling; they do not measure every host implementation. + +[#asio-wasip2-readiness] +=== How readiness reaches the executor + +WASIp2 provides TCP, UDP, name-resolution streams, monotonic clocks and resources +that expose readiness through `wasi:io/poll`. The port retains Boost.Asio's select +reactor. wasi-libc gathers socket pollables and timer deadlines into one host wait. +No worker thread, fixed-interval DNS scan or browser turn budget is introduced. +The P2 single-thread profile omits Asio's pipe-based cross-thread interrupter: +this libc has no P2 pipe implementation, and the profile cannot receive work from +another application thread. +An idle scheduler without a reactor waits on a maximum-instant monotonic-clock +pollable. It does not submit an empty poll list, which WASIp2 rejects, or spin. + +A DNS address stream is not a POSIX descriptor. A small compiled bridge registers +its borrowed pollable with wasi-libc's descriptor table so the same reactor can +wait for sockets, DNS and timers together. That registration API is private to +wasi-libc. The build verifies SDK 34.0, libc revision `2e6fb9d8ee0c` and the exact +copied declaration hashes. Changing the SDK requires revalidating this bridge; +the build must not silently use an unknown ABI. The upstream installation is +never modified. + +[#asio-wasip2-dns] +=== Resolver contract + +`async_resolve` starts the native lookup through the executor. A deferred token +does not start DNS until initiated. The handler never runs inside initiation, +uses its associated executor, and receives an error value on failure. Resolver +cancellation and per-operation cancellation work before and after registration. +Destroying a resolver cancels pending lookups; destroying its context abandons +handlers and releases the owned resources. + +Numeric host parsing and the libc service-name table require no host DNS wait. +The host supplies forward lookup addresses; host capabilities govern access. +`canonical_name`, `v4_mapped` and `all_matching` are explicitly unsupported by this +adapter and complete with `operation_not_supported`. Asynchronous reverse lookup +also remains unsupported. `address_configured` uses libc's numeric family checks. +Loopback tests establish local resolution, not access to every external DNS server. + +Operation storage and copied input/endpoint scratch storage use the associated +handler allocator. Resolver ownership uses the context allocator. The public +Boost result container, libc address parsing and descriptor-table storage retain +their upstream allocation behavior; this is not a zero-global-allocation promise. + +[#asio-wasip2-streams] +=== Use a supplied CLI byte stream + +`webcpp::asio::wasi::stdio_stream` implements partial synchronous and asynchronous +reads/writes over WASIp2 CLI resources. Its asynchronous waits use the same reactor, +preserve completion-token associations and support cancellation. Only one read +and one write may be pending per stream. Keep buffer storage alive until completion. +The stream owns resource handles but does not close libc's descriptors 0 and 1. +Cancellation aborts pending operations; subsequent operations remain usable. +Closing or destroying the stream cancels pending operations and prevents new I/O. + +The Beast supplied-channel client and server run real WebSocket upgrade, text, +fragmented binary transfer, ping/pong and close over this adapter, in both exception +modes. They need no TCP socket grant. These channels do not provide Unix socket +names, descriptor passing, peer credentials or `wasi:http` WebSocket upgrades. + +Writes request a WASI flush before the protocol switches to reading. Readiness +cannot preempt an import that the host itself implements with blocking I/O. In +particular, Wasmtime CLI stdout can block when its OS pipe fills. A paused consumer +must resume draining before the component can observe cancellation. A strict +cancellation deadline requires a host/channel whose write imports remain nonblocking. + +[#asio-wasip2-errors] +=== Unsupported operations and build profiles + +`threading=multi`, `/webcpp/asio//cobalt`, `//openssl`, `//tls` and `//cobalt_ssl` +are rejected by this P2 build integration. This does not claim that those features +are impossible in a future port. POSIX signals, Unix-domain sockets, serial ports +and CPU-parallel threads are not provided by this profile. + +Unsupported socket operations retain error-code overloads. Tested examples include +`linger`, `at_mark` and UDP receive into multiple nonempty buffers, which return +`operation_not_supported`. A rejected receive does not consume its datagram. +UDP `send_to` can gather multiple buffers into one datagram; connected UDP +`send` does not support multiple nonempty buffers. TCP retains partial I/O semantics. +Numeric IPv6 scope identifiers work; named interfaces are rejected with +`invalid_argument`. Host permission denial is a runtime error, distinct from an +unsupported build profile. Prefer error-code/completion-handler paths for recovery, +especially when exception handling is disabled. diff --git a/include/webcpp/asio/detail/wasi_pollable_descriptor.hpp b/include/webcpp/asio/detail/wasi_pollable_descriptor.hpp new file mode 100644 index 0000000..d6da3ae --- /dev/null +++ b/include/webcpp/asio/detail/wasi_pollable_descriptor.hpp @@ -0,0 +1,32 @@ +// 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_POLLABLE_DESCRIPTOR_HPP +#define WEBCPP_ASIO_DETAIL_WASI_POLLABLE_DESCRIPTOR_HPP +#include +#include +#include +#include + +namespace webcpp::asio::detail { +/** Stable storage borrowed by the pinned wasi-libc descriptor table. + Close the descriptor before destroying this storage or its pollable. */ +struct wasi_pollable_descriptor { + /** Opaque storage for the pinned libc descriptor, owned by this object. */ + alignas(std::max_align_t) std::array opaque{}; + /** Whether libc currently borrows this object. */ + bool active = false; + /** Borrowed native WASIp2 pollable handle. */ + std::int32_t handle = 0; +}; +} // namespace webcpp::asio::detail + +/** Registers borrowed storage as a read-readiness-only descriptor. + @param storage Stable descriptor state, alive until close returns. + @return The descriptor, or -1 with errno set. */ +extern "C" int webcpp_asio_wasi_pollable_descriptor( + webcpp::asio::detail::wasi_pollable_descriptor* storage); +#endif diff --git a/include/webcpp/asio/wasi/stdio_stream.hpp b/include/webcpp/asio/wasi/stdio_stream.hpp new file mode 100644 index 0000000..34a2a35 --- /dev/null +++ b/include/webcpp/asio/wasi/stdio_stream.hpp @@ -0,0 +1,445 @@ +// 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_WASI_STDIO_STREAM_HPP +#define WEBCPP_ASIO_WASI_STDIO_STREAM_HPP + +#include +#if defined(__MRDOCS__) || defined(WEBCPP_ASIO_REFERENCE) +#include +#include +#include + +namespace webcpp::asio::wasi { +/** A WASIp2 CLI AsyncReadStream and AsyncWriteStream driven by pollables. + + Owns resource handles, without closing libc's stdin/stdout descriptors. + Only one read and one write may be outstanding at once. Operations retain + buffers until completion and preserve allocator, executor and cancellation + associations. Host imports may still block according to the host's behavior. + @see "Build for WASIp2", in the guide. */ +class stdio_stream { +public: + /** The executor used for readiness. */ + using executor_type = boost::asio::io_context::executor_type; + /** This stream is its own lowest layer. */ + using lowest_layer_type = stdio_stream; + /** Acquires CLI resources using the executor's context allocator. + @param executor Drives asynchronous readiness. */ + explicit stdio_stream(executor_type const& executor); + /** Cancels pending operations and releases resources after their completion. */ + ~stdio_stream(); + /** Forbids copied resource ownership. */ + stdio_stream(stdio_stream const&) = delete; + /** Forbids copied resource ownership. */ + stdio_stream& operator=(stdio_stream const&) = delete; + /** Transfers resource ownership. */ + stdio_stream(stdio_stream&&); + /** Forbids replacing a stream that may have pending operations. */ + stdio_stream& operator=(stdio_stream&&) = delete; + /** Returns the readiness executor. + @return The executor. */ + [[nodiscard]] executor_type get_executor() const noexcept; + /** Returns this stream. + @return This stream. */ + lowest_layer_type& lowest_layer() noexcept; + /** Cancels outstanding operations; subsequent operations remain usable. */ + void cancel(); + /** Cancels outstanding operations and disables subsequent operations. */ + void close(); + /** Reads a partial sequence asynchronously. + @tparam Buffers Mutable buffer sequence. + @tparam Token Completion token for void(error_code, size_t). + @param buffers Destination storage, alive until completion. + @param token Receives the error and byte count. + @return The completion token's result. */ + template + auto async_read_some(Buffers const& buffers, Token&& token); + /** Writes a partial sequence asynchronously. + @tparam Buffers Const buffer sequence. + @tparam Token Completion token for void(error_code, size_t). + @param buffers Source storage, alive until completion. + @param token Receives the error and byte count. + @return The completion token's result. */ + template + auto async_write_some(Buffers const& buffers, Token&& token); + /** Reads synchronously. + @tparam Buffers Mutable buffer sequence. + @param buffers Destination bytes. + @param error Receives failure. + @return Bytes read. */ + template + std::size_t read_some(Buffers const& buffers, boost::system::error_code& error); + /** Writes synchronously. + @tparam Buffers Const buffer sequence. + @param buffers Source bytes. + @param error Receives failure. + @return Bytes written. */ + template + std::size_t write_some(Buffers const& buffers, boost::system::error_code& error); + /** Reads synchronously and throws on failure. + @tparam Buffers Mutable buffer sequence. + @param buffers Destination bytes. + @return Bytes read. */ + template + std::size_t read_some(Buffers const& buffers); + /** Writes synchronously and throws on failure. + @tparam Buffers Const buffer sequence. + @param buffers Source bytes. + @return Bytes written. */ + template + std::size_t write_some(Buffers const& buffers); +}; + +/** Cancels the channel for Beast timeouts. + @param stream Channel to close. */ +void beast_close_socket(stdio_stream& stream); +} // namespace webcpp::asio::wasi +#elif !defined(__wasip2__) +#error "webcpp::asio::wasi::stdio_stream currently requires WASIp2" +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::asio::wasi { +/** A byte stream over WASIp2 CLI input and output. + + Asynchronous operations wait on native pollables through Asio. They preserve + associated executors, allocators and cancellation. The stream acquires its own + resource handles; it never closes libc's stdin/stdout descriptors. Keep buffers + alive until completion. Only one read and one write may be outstanding at once. + A host implementation may still block inside an otherwise nonblocking import. +*/ +class stdio_stream { +public: + /** Executor that drives stream readiness. */ + using executor_type = boost::asio::io_context::executor_type; + /** This stream has no additional transport layer. */ + using lowest_layer_type = stdio_stream; + +private: + struct state { + executor_type executor; + boost::asio::posix::stream_descriptor input_wait; + boost::asio::posix::stream_descriptor output_wait; + detail::wasi_pollable_descriptor input_storage{}; + detail::wasi_pollable_descriptor output_storage{}; + streams_own_input_stream_t input = stdin_get_stdin(); + streams_own_output_stream_t output = stdout_get_stdout(); + poll_own_pollable_t input_ready = + streams_method_input_stream_subscribe(streams_borrow_input_stream(input)); + poll_own_pollable_t output_ready = + streams_method_output_stream_subscribe(streams_borrow_output_stream(output)); + boost::system::error_code initialization_error; + std::uint64_t generation = 0; + bool closed = false; + + explicit state(const executor_type& value) + : executor(value), input_wait(value), output_wait(value) { + auto const assign = [&](auto& storage, auto& descriptor, auto ready) { + storage.handle = ready.__handle; + int const fd = webcpp_asio_wasi_pollable_descriptor(&storage); + if (fd < 0) { + initialization_error.assign(errno, boost::system::system_category()); + } else { + boost::system::error_code error; + descriptor.assign(fd, error); + if (error) { + ::close(fd); + initialization_error = error; + } + } + }; + assign(input_storage, input_wait, input_ready); + assign(output_storage, output_wait, output_ready); + } + + ~state() { + boost::system::error_code ignored; + // The descriptor is closed even when close reports an error. + // NOLINTNEXTLINE(bugprone-unused-return-value) + static_cast(input_wait.close(ignored)); + // The descriptor is closed even when close reports an error. + // NOLINTNEXTLINE(bugprone-unused-return-value) + static_cast(output_wait.close(ignored)); + poll_pollable_drop_own(input_ready); + poll_pollable_drop_own(output_ready); + streams_input_stream_drop_own(input); + streams_output_stream_drop_own(output); + } + + void cancel() { + ++generation; + boost::system::error_code ignored; + // Only an unassigned descriptor can fail; generation still cancels the operation. + // NOLINTNEXTLINE(bugprone-unused-return-value) + static_cast(input_wait.cancel(ignored)); + // Only an unassigned descriptor can fail; generation still cancels the operation. + // NOLINTNEXTLINE(bugprone-unused-return-value) + static_cast(output_wait.cancel(ignored)); + } + + std::size_t read(boost::asio::mutable_buffer buffer, + boost::system::error_code& error) const { + wasip2_list_u8_t bytes{}; + streams_stream_error_t failure{}; + if (!streams_method_input_stream_read(streams_borrow_input_stream(input), + std::min(buffer.size(), 65536), + &bytes, &failure)) { + if (failure.tag == STREAMS_STREAM_ERROR_CLOSED) { + error = boost::asio::error::eof; + } else { + error = boost::asio::error::fault; + } + streams_stream_error_free(&failure); + return 0; + } + auto const count = bytes.len; + if (count != 0u) { + std::memcpy(buffer.data(), bytes.ptr, count); + } + wasip2_list_u8_free(&bytes); + error = (count != 0u) ? boost::system::error_code{} : boost::asio::error::would_block; + return count; + } + + std::size_t write(boost::asio::const_buffer buffer, boost::system::error_code& error) { + std::uint64_t capacity = 0; + streams_stream_error_t failure{}; + if (!streams_method_output_stream_check_write(streams_borrow_output_stream(output), + &capacity, &failure)) { + streams_stream_error_free(&failure); + error = boost::asio::error::broken_pipe; + return 0; + } + if (capacity == 0) { + error = boost::asio::error::would_block; + return 0; + } + auto const count = std::min( + buffer.size(), static_cast(std::min(capacity, 4096))); + wasip2_list_u8_t bytes{ + .ptr = reinterpret_cast(const_cast(buffer.data())), + .len = count, + }; + if (!streams_method_output_stream_write(streams_borrow_output_stream(output), &bytes, + &failure)) { + streams_stream_error_free(&failure); + error = boost::asio::error::broken_pipe; + return 0; + } + // Request delivery before the protocol switches from writing to reading. + // A subsequent check-write/pollable wait observes flush completion. + if (!streams_method_output_stream_flush(streams_borrow_output_stream(output), + &failure)) { + streams_stream_error_free(&failure); + error = boost::asio::error::broken_pipe; + return count; + } + error.clear(); + return count; + } + }; + + std::shared_ptr state_; + + template + struct transfer_operation { + std::shared_ptr shared; + Buffer first; + std::uint64_t generation = 0; + + // Initiation only posts. Resumption has a separate signature so the + // composed operation cannot complete recursively inside initiation. + template + void operator()(Self& self) { + generation = shared->generation; + self.reset_cancellation_state(boost::asio::enable_total_cancellation()); + boost::asio::post(shared->executor, + boost::asio::append(std::move(self), boost::system::error_code{})); + } + + template + void operator()(Self& self, boost::system::error_code error) { + if (self.cancelled() != boost::asio::cancellation_type::none || shared->closed || + generation != shared->generation) { + error = boost::asio::error::operation_aborted; + } + if (!error) { + error = shared->initialization_error; + } + if (error || first.size() == 0) { + self.complete(error, 0); + return; + } + std::size_t count = 0; + if constexpr (Writing) { + count = shared->write(first, error); + } else { + count = shared->read(first, error); + } + if (error != boost::asio::error::would_block) { + self.complete(error, count); + return; + } + auto& descriptor = Writing ? shared->output_wait : shared->input_wait; + descriptor.async_wait(boost::asio::posix::stream_descriptor::wait_read, + std::move(self)); + } + }; + + template + auto async_some(Buffers const& buffers, Token&& token) { + using buffer_type = + std::conditional_t; + buffer_type first; + for (auto it = boost::asio::buffer_sequence_begin(buffers), + end = boost::asio::buffer_sequence_end(buffers); + it != end; ++it) { + if (boost::asio::buffer_size(*it) != 0) { + first = buffer_type(*it); + break; + } + } + return boost::asio::async_compose( + transfer_operation{.shared = state_, .first = first}, token, + state_->executor); + } + + template + std::size_t sync_some(Buffers const& buffers, boost::system::error_code& error) { + if (state_->closed) { + error = boost::asio::error::operation_aborted; + return 0; + } + if (state_->initialization_error) { + error = state_->initialization_error; + return 0; + } + for (auto it = boost::asio::buffer_sequence_begin(buffers), + end = boost::asio::buffer_sequence_end(buffers); + it != end; ++it) { + if (boost::asio::buffer_size(*it) == 0) { + continue; + } + for (;;) { + std::size_t count = 0; + if constexpr (Writing) { + count = state_->write(boost::asio::const_buffer(*it), error); + } else { + count = state_->read(boost::asio::mutable_buffer(*it), error); + } + if (error != boost::asio::error::would_block) { + return count; + } + poll_method_pollable_block( + poll_borrow_pollable(Writing ? state_->output_ready : state_->input_ready)); + } + } + error.clear(); + return 0; + } + +public: + /** Acquires independent CLI resource handles using the executor's context allocator. */ + explicit stdio_stream(const executor_type& executor) + : state_(std::allocate_shared( + boost::asio::execution_context::allocator(executor.context()), executor)) {} + + /** Cancels pending operations without closing the application's descriptors. */ + ~stdio_stream() { + if (state_) { + state_->closed = true; + state_->cancel(); + } + } + + stdio_stream(stdio_stream const&) = delete; + stdio_stream& operator=(stdio_stream const&) = delete; + stdio_stream(stdio_stream&&) = default; + stdio_stream& operator=(stdio_stream&&) = delete; + + /** Returns the executor. */ + [[nodiscard]] executor_type get_executor() const noexcept { return state_->executor; } + + /** Returns this stream, which is its own lowest layer. */ + lowest_layer_type& lowest_layer() noexcept { return *this; } + + /** Cancels outstanding operations. Subsequent operations remain usable. */ + void cancel() { state_->cancel(); } + + /** Cancels and disables subsequent operations. */ + void close() { + state_->closed = true; + state_->cancel(); + } + + /** Reads a partial buffer sequence asynchronously. */ + template + auto async_read_some(Buffers const& buffers, Token&& token) { + return async_some(buffers, std::forward(token)); + } + + /** Writes a partial buffer sequence asynchronously. */ + template + auto async_write_some(Buffers const& buffers, Token&& token) { + return async_some(buffers, std::forward(token)); + } + + /** Reads synchronously, reporting failures through error. */ + template + std::size_t read_some(Buffers const& buffers, boost::system::error_code& error) { + return sync_some(buffers, error); + } + + /** Writes synchronously, reporting failures through error. */ + template + std::size_t write_some(Buffers const& buffers, boost::system::error_code& error) { + return sync_some(buffers, error); + } + + /** Reads synchronously, throwing on failure when exceptions are enabled. */ + template + std::size_t read_some(Buffers const& buffers) { + boost::system::error_code error; + auto count = read_some(buffers, error); + if (error) { + boost::throw_exception(boost::system::system_error(error)); + } + return count; + } + + /** Writes synchronously, throwing on failure when exceptions are enabled. */ + template + std::size_t write_some(Buffers const& buffers) { + boost::system::error_code error; + auto count = write_some(buffers, error); + if (error) { + boost::throw_exception(boost::system::system_error(error)); + } + return count; + } +}; + +/** Allows Beast timeouts to cancel the supplied channel without socket shutdown. */ +inline void beast_close_socket(stdio_stream& stream) { + stream.close(); +} +} // namespace webcpp::asio::wasi +#endif +#endif diff --git a/test/Jamfile b/test/Jamfile index 8694369..e2b1217 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -64,7 +64,8 @@ webcpp.headers-alone asio : ../include : asio.hpp asio/basic_datagram_socket.hpp asio/io_context.hpp asio/steady_timer.hpp asio/system_timer.hpp asio/ip/*.hpp ; # The browser's headers name Emscripten's own, and compile on emscripten # alone. -webcpp.headers-alone asio : ../include : asio/browser/*.hpp asio/detail/*.hpp : : emscripten ; +webcpp.headers-alone asio : ../include : asio/browser/*.hpp asio/detail/browser_*.hpp + asio/detail/post_completion.hpp asio/detail/flag_scope.hpp : : emscripten ; # config.hpp follows the collection exception setting and preserves a # developer definition that disables this library alone. @@ -320,3 +321,5 @@ webcpp.compile-fail openssl_named_c_on_emscripten : openssl_named_c_test.c # The TLS lane drives real loopback peers with the shared certificate fixtures. build-project tls ; + +build-project wasip2 ; diff --git a/test/wasi_contract_test.cpp b/test/wasi_contract_test.cpp index 4304637..c61769d 100644 --- a/test/wasi_contract_test.cpp +++ b/test/wasi_contract_test.cpp @@ -57,7 +57,7 @@ int main() { const auto sent = sender.send_to(pieces, receiver.local_endpoint(), 0, error); BOOST_TEST_EQ(error, boost::system::error_code{}); BOOST_TEST_EQ(sent, 2U); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) // A refused vectored receive must not consume even the first byte. const std::array outputs{ asio::buffer(data.data(), 1), @@ -78,7 +78,7 @@ int main() { BOOST_TEST_EQ(error, boost::system::error_code{}); BOOST_TEST_EQ(data[0], 'z'); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) // Empty buffers must not hide payload beyond Asio's native iovec limit. std::array distant{}; distant.front() = asio::buffer("a", 1); @@ -111,7 +111,7 @@ int main() { sender.connect(receiver.local_endpoint()); BOOST_TEST_EQ(sender.send(asio::const_buffer{}, 0, error), 0U); BOOST_TEST_EQ(error, boost::system::error_code{}); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) BOOST_TEST_EQ(receiver.receive_from(asio::mutable_buffer{}, peer, 0, error), 0U); #else // macOS may return from a zero-capacity receive before consuming a packet. @@ -119,19 +119,19 @@ int main() { #endif BOOST_TEST_EQ(error, boost::system::error_code{}); const std::array empty_inputs{}; -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) const std::array empty_outputs{}; #endif BOOST_TEST_EQ(sender.send(empty_inputs, 0, error), 0U); BOOST_TEST_EQ(error, boost::system::error_code{}); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) BOOST_TEST_EQ(receiver.receive_from(empty_outputs, peer, 0, error), 0U); #else BOOST_TEST_EQ(receiver.receive_from(asio::buffer(data), peer, 0, error), 0U); #endif BOOST_TEST_EQ(error, boost::system::error_code{}); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) receiver.non_blocking(true); BOOST_TEST_EQ(receiver.receive_from(asio::buffer(data), peer, 0, error), 0U); BOOST_TEST(error == asio::error::would_block || error == asio::error::try_again); @@ -153,7 +153,7 @@ int main() { context.run(); // lint-run: complete cancellation through the executor BOOST_TEST_EQ(cancelled, 1); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) tcp::socket socket(context, tcp::v4()); BOOST_TEST_EQ(socket.set_option(asio::socket_base::linger(true, 1), error), asio::error::operation_not_supported); diff --git a/test/wasi_core_test.cpp b/test/wasi_core_test.cpp index c01106f..0bc9e7b 100644 --- a/test/wasi_core_test.cpp +++ b/test/wasi_core_test.cpp @@ -113,7 +113,7 @@ void test_tcp() { context.run(); // lint-run: drive both peers without an external server BOOST_TEST_EQ(exchanged, 2); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) // A long empty prefix must not turn a stream operation into a no-op. context.restart(); std::array late_input{}; diff --git a/test/wasip2/Jamfile b/test/wasip2/Jamfile new file mode 100644 index 0000000..d60779d --- /dev/null +++ b/test/wasip2/Jamfile @@ -0,0 +1,33 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/asio//asio ; +import webcpp ; +webcpp.targets wasip2 ; + +# Exercise the same public timer, stream and datagram contracts as WASIp3. +webcpp.run core : ../wasi_core_test.cpp : : wasip2 ; +webcpp.run contract : ../wasi_contract_test.cpp : : wasip2 ; +webcpp.run udp_gather : ../wasi_udp_gather_test.cpp : : wasip2 ; +webcpp.run coroutine : ../wasi_coroutine_test.cpp : : wasip2 ; +webcpp.run pollable : pollable_test.cpp : : wasip2 ; +webcpp.run resolver : resolver_test.cpp : : wasip2 ; +webcpp.run run_family : ../run_family_test.cpp : : wasip2 ; +webcpp.run timers : ../timers_test.cpp : : wasip2 ; +webcpp.run write_permit : write_permit_test.cpp + : -Wl,--wrap=streams_method_output_stream_check_write : wasip2 ; +webcpp.run pending_write : write_permit_test.cpp + : WEBCPP_TEST_PENDING_WRITE + -Wl,--wrap=streams_method_output_stream_check_write + -Wl,--wrap=streams_method_output_stream_subscribe : wasip2 ; +webcpp.original python3 : . ; +webcpp.drive stdio : stdio_test.cpp : /webcpp//node-test : stdio_driver.py : : wasip2 ; +webcpp.lane supplied-stream : stdio : wasip2 ; +webcpp.drive idle : idle_test.cpp : /webcpp//node-test : idle_driver.py : : wasip2 ; +webcpp.lane scheduler-idle : idle : wasip2 ; + +webcpp.headers-alone asio : ../../include : asio/wasi/*.hpp + asio/detail/wasi_pollable_descriptor.hpp : : wasip2 ; diff --git a/test/wasip2/counting_allocator.hpp b/test/wasip2/counting_allocator.hpp new file mode 100644 index 0000000..d8bec95 --- /dev/null +++ b/test/wasip2/counting_allocator.hpp @@ -0,0 +1,43 @@ +// 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_TEST_P2_COUNTING_ALLOCATOR_HPP +#define WEBCPP_ASIO_TEST_P2_COUNTING_ALLOCATOR_HPP +#include + +struct counts { + unsigned allocations = 0; + unsigned live = 0; +}; + +template +struct allocator { + using value_type = T; + counts* counter; + + explicit allocator(counts& value) : counter(&value) {} + + template + explicit allocator(allocator const& other) : counter(other.counter) {} + + T* allocate(std::size_t size) { + ++counter->allocations; + ++counter->live; + return std::allocator{}.allocate(size); + } + + void deallocate(T* ptr, std::size_t size) { + --counter->live; + std::allocator{}.deallocate(ptr, size); + } + + template + bool operator==(allocator const& other) const { + return counter == other.counter; + } +}; + +#endif diff --git a/test/wasip2/idle_driver.py b/test/wasip2/idle_driver.py new file mode 100644 index 0000000..e8a33ea --- /dev/null +++ b/test/wasip2/idle_driver.py @@ -0,0 +1,34 @@ +#!/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) +"""An external watchdog verifies idle waits without relying on a guest timer.""" +import os +import select +import subprocess +import sys + +for arguments in ([], ['reactor']): + command = [os.environ.get('WASMTIME', 'wasmtime'), 'run', '-W', 'fuel=10000000', + sys.argv[-1], *arguments] + with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as guest: + assert guest.stdout is not None + try: + assert select.select([guest.stdout], [], [], 10)[0], 'guest did not start' + line = guest.stdout.readline() + if line != b'ready\n': + _, errors = guest.communicate(timeout=5) + raise AssertionError(('guest startup', line, errors)) + try: + output, errors = guest.communicate(timeout=0.3) + except subprocess.TimeoutExpired: + pass + else: + raise AssertionError(('idle run exited', guest.returncode, output, errors)) + finally: + if guest.poll() is None: + guest.kill() + guest.wait() +print('Guard-only and reactor idle waits stayed blocked without exhausting fuel') diff --git a/test/wasip2/idle_test.cpp b/test/wasip2/idle_test.cpp new file mode 100644 index 0000000..5982cf1 --- /dev/null +++ b/test/wasip2/idle_test.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#include +#include +#include +#include +#include + +int main(int argc, char** /*argv*/) { + webcpp::asio::io_context context; + auto const guard = boost::asio::make_work_guard(context); + std::optional timer; + if (argc > 1) { + timer.emplace(context, std::chrono::milliseconds(0)); + timer->async_wait([](boost::system::error_code) {}); + } + if (std::puts("ready") < 0 || std::fflush(stdout) != 0) { + return 2; + } + context.run(); // lint-run: a live guard must wait indefinitely without trapping or spinning + return 3; +} diff --git a/test/wasip2/package-lock.json b/test/wasip2/package-lock.json new file mode 100644 index 0000000..61e5951 --- /dev/null +++ b/test/wasip2/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "webcpp-asio-wasip2-tests", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webcpp-asio-wasip2-tests", + "version": "0.0.0", + "license": "BSL-1.0" + } + } +} diff --git a/test/wasip2/package.json b/test/wasip2/package.json new file mode 100644 index 0000000..0588552 --- /dev/null +++ b/test/wasip2/package.json @@ -0,0 +1,7 @@ +{ + "name": "webcpp-asio-wasip2-tests", + "version": "0.0.0", + "private": true, + "license": "BSL-1.0", + "description": "Local Python driver for WASIp2 supplied stream tests; no npm dependencies." +} diff --git a/test/wasip2/pollable_test.cpp b/test/wasip2/pollable_test.cpp new file mode 100644 index 0000000..1b08729 --- /dev/null +++ b/test/wasip2/pollable_test.cpp @@ -0,0 +1,55 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +void check_readiness(std::uint64_t delay) { + webcpp::asio::io_context context; + auto const ready = monotonic_clock_subscribe_duration(delay); + webcpp::asio::detail::wasi_pollable_descriptor storage{}; + storage.handle = ready.__handle; + auto const fd = webcpp_asio_wasi_pollable_descriptor(&storage); + BOOST_TEST(fd >= 0); + if (fd < 0) { + poll_pollable_drop_own(ready); + return; + } + boost::asio::posix::stream_descriptor descriptor(context, fd); + webcpp::asio::steady_timer timer(context, std::chrono::milliseconds(1)); + int callbacks = 0; + bool timer_fired = false; + timer.async_wait([&](boost::system::error_code error) { + BOOST_TEST(!error); + timer_fired = true; + }); + descriptor.async_wait(boost::asio::posix::stream_descriptor::wait_read, + [&](boost::system::error_code error) { + BOOST_TEST(!error); + ++callbacks; + }); + BOOST_TEST_EQ(callbacks, 0); + context.run(); // lint-run: wait for a native pollable alongside an Asio timer + BOOST_TEST_EQ(callbacks, 1); + BOOST_TEST(timer_fired); + descriptor.close(); + BOOST_TEST(!storage.active); + poll_pollable_drop_own(ready); +} +} // namespace + +int main() { + check_readiness(0); // Ready before registration must not lose a wakeup. + check_readiness(20000000); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/wasip2/resolver_test.cpp b/test/wasip2/resolver_test.cpp new file mode 100644 index 0000000..0f39374 --- /dev/null +++ b/test/wasip2/resolver_test.cpp @@ -0,0 +1,155 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "counting_allocator.hpp" + +namespace { +void initiation_and_cancellation() { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + webcpp::asio::io_context context; + webcpp::asio::io_context completions; + tcp::resolver resolver(context); + int completed = 0; + auto lazy = resolver.async_resolve("localhost", "80", asio::deferred); + BOOST_TEST_EQ(context.poll(), 0U); + context.restart(); + std::move(lazy)(asio::bind_executor( + completions.get_executor(), + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST(!ec); + BOOST_TEST(!result.empty()); + for (auto const& entry : result) { + BOOST_TEST_EQ(entry.endpoint().port(), 80); + } + ++completed; + })); + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: the lookup must not invoke another executor's handler + BOOST_TEST_EQ(completed, 0); + completions.run(); // lint-run: deliver on the associated executor + BOOST_TEST_EQ(completed, 1); + + context.restart(); + resolver.async_resolve( + "localhost", "80", + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST_EQ(ec, asio::error::operation_aborted); + BOOST_TEST(result.empty()); + ++completed; + }); + resolver.cancel(); + context.run(); // lint-run: cancellation before the lookup starts + BOOST_TEST_EQ(completed, 2); + + context.restart(); + asio::cancellation_signal cancel; + resolver.async_resolve( + "localhost", "80", + asio::bind_cancellation_slot(cancel.slot(), [&](boost::system::error_code ec, + const tcp::resolver::results_type& result) { + BOOST_TEST_EQ(ec, asio::error::operation_aborted); + BOOST_TEST(result.empty()); + ++completed; + })); + cancel.emit(asio::cancellation_type::all); + context.run(); // lint-run: per-operation cancellation + BOOST_TEST_EQ(completed, 3); + + context.restart(); + resolver.async_resolve( + "127.0.0.1", "443", tcp::resolver::numeric_host, + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST(!ec); + BOOST_TEST_EQ(result.size(), 1U); + if (!result.empty()) { + BOOST_TEST_EQ(result.begin()->endpoint().port(), 443); + } + ++completed; + }); + context.run(); // lint-run: numeric addresses never require DNS + BOOST_TEST_EQ(completed, 4); +} + +void resources_and_errors() { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + webcpp::asio::io_context context; + tcp::resolver resolver(context); + int completed = 0; + resolver.async_resolve( + "localhost", "80", + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST_EQ(ec, asio::error::operation_aborted); + BOOST_TEST(result.empty()); + ++completed; + }); + BOOST_TEST_EQ(context.poll_one(), 1U); // Start the native lookup, leave its completion queued. + resolver.cancel(); + context.run(); // lint-run: cancel after registration with the pollable reactor + BOOST_TEST_EQ(completed, 1); + + context.restart(); + resolver.async_resolve( + "localhost", "80", tcp::resolver::canonical_name, + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST_EQ(ec, asio::error::operation_not_supported); + BOOST_TEST(result.empty()); + ++completed; + }); + context.run(); // lint-run: unsupported flags fail deliberately and asynchronously + BOOST_TEST_EQ(completed, 2); + context.restart(); + counts allocations; + resolver.async_resolve( + "localhost", "80", + asio::bind_allocator( + allocator(allocations), + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST(!ec); + BOOST_TEST(!result.empty()); + BOOST_TEST(allocations.allocations >= + 2); // Operation and endpoint scratch storage. + BOOST_TEST_EQ(allocations.live, 0U); // Scratch storage is freed before the upcall. + ++completed; + })); + context.run(); // lint-run: verify associated allocation and deallocation before completion + BOOST_TEST_EQ(completed, 3); + + context.restart(); + resolver.async_resolve( + "invalid host name", "80", + [&](boost::system::error_code ec, const tcp::resolver::results_type& result) { + BOOST_TEST(ec == asio::error::invalid_argument || ec == asio::error::host_not_found); + BOOST_TEST(result.empty()); + ++completed; + }); + context.run(); // lint-run: malformed names report a value without an initiation-time failure + BOOST_TEST_EQ(completed, 4); + { + webcpp::asio::io_context abandoned; + tcp::resolver pending(abandoned); + pending.async_resolve("localhost", "80", + [&](auto, const auto&) { BOOST_ERROR("abandoned callback"); }); + BOOST_TEST_EQ(abandoned.poll_one(), 1U); + } +} + +} // namespace + +int main() { + initiation_and_cancellation(); + resources_and_errors(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/wasip2/stdio_driver.py b/test/wasip2/stdio_driver.py new file mode 100644 index 0000000..9a88544 --- /dev/null +++ b/test/wasip2/stdio_driver.py @@ -0,0 +1,30 @@ +#!/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) +"""Keep the guest's input open and empty while it checks readiness cancellation.""" +import os +import subprocess +import sys +import tempfile + +command = [os.environ.get('WASMTIME', 'wasmtime'), 'run', '-W', 'timeout=15s', sys.argv[-1]] +with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as diagnostics: + with subprocess.Popen(command, + stdin=subprocess.PIPE, stdout=output, stderr=diagnostics) as guest: + try: + status = guest.wait(timeout=20) + finally: + if guest.poll() is None: + guest.kill() + guest.wait() + diagnostics.seek(0) + text = diagnostics.read().decode() + assert status == 0, (status, text) + output.seek(0) + assert output.read() == b'' + print(text, end='') +print('WASIp2 supplied stream: timer cancellation, slot, destruction, ' + 'allocator and executor passed') diff --git a/test/wasip2/stdio_test.cpp b/test/wasip2/stdio_test.cpp new file mode 100644 index 0000000..00e400c --- /dev/null +++ b/test/wasip2/stdio_test.cpp @@ -0,0 +1,116 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "counting_allocator.hpp" + +int main() { + namespace asio = boost::asio; + using stream_type = webcpp::asio::wasi::stdio_stream; + webcpp::asio::io_context context; + stream_type stream(context.get_executor()); + std::array data{}; + counts counter; + int completed = 0; + webcpp::asio::steady_timer timer(context, std::chrono::milliseconds(5)); + timer.async_wait([&](auto error) { + BOOST_TEST(!error); + stream.cancel(); + }); + stream.async_read_some( + asio::buffer(data), + asio::bind_allocator(allocator(counter), + [&](boost::system::error_code error, std::size_t count) { + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST_EQ(count, 0U); + BOOST_TEST(counter.allocations > 0); + BOOST_TEST_EQ(counter.live, 0U); + ++completed; + })); + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: timer must progress while the host keeps input open and empty + BOOST_TEST_EQ(completed, 1); + + context.restart(); + asio::cancellation_signal signal; + stream.async_read_some( + asio::buffer(data), + asio::bind_cancellation_slot(signal.slot(), + [&](boost::system::error_code error, std::size_t count) { + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST_EQ(count, 0U); + ++completed; + })); + signal.emit(asio::cancellation_type::all); + context.run(); // lint-run: cancellation before initial posted work + BOOST_TEST_EQ(completed, 2); + + context.restart(); + { + stream_type temporary(context.get_executor()); + temporary.async_read_some(asio::buffer(data), + [&](boost::system::error_code error, std::size_t count) { + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST_EQ(count, 0U); + ++completed; + }); + BOOST_TEST_EQ(context.poll_one(), 1U); + } + context.run(); // lint-run: destroying the stream cancels its outstanding read safely + BOOST_TEST_EQ(completed, 3); + + context.restart(); + webcpp::asio::io_context target; + stream.async_read_some( + asio::mutable_buffer{}, + asio::bind_executor(target.get_executor(), + [&](boost::system::error_code error, std::size_t count) { + BOOST_TEST(!error); + BOOST_TEST_EQ(count, 0U); + ++completed; + })); + context.poll(); // Both contexts are single-threaded: poll one, then drive the other. + BOOST_TEST_EQ(completed, 3); + target.run(); // lint-run: deliver the zero-length read without consuming input + BOOST_TEST_EQ(completed, 4); + context.restart(); + auto deferred_read = stream.async_read_some(asio::buffer(data), asio::deferred); + stream.cancel(); // No read was initiated yet; this must not cancel the deferred operation. + bool cancelled_by_timer = false; + timer.expires_after(std::chrono::milliseconds(5)); + timer.async_wait([&](auto error) { + BOOST_TEST(!error); + cancelled_by_timer = true; + stream.cancel(); + }); + std::move(deferred_read)([&](boost::system::error_code error, std::size_t count) { + BOOST_TEST(cancelled_by_timer); + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST_EQ(count, 0U); + ++completed; + }); + context.run(); // lint-run: cancellation is scoped to initiated operations + BOOST_TEST_EQ(completed, 5); + { + webcpp::asio::io_context abandoned; + stream_type pending(abandoned.get_executor()); + pending.async_read_some(asio::buffer(data), + [&](auto, auto) { BOOST_ERROR("abandoned callback"); }); + BOOST_TEST_EQ(abandoned.poll_one(), 1U); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/wasip2/write_permit_test.cpp b/test/wasip2/write_permit_test.cpp new file mode 100644 index 0000000..37f70cd --- /dev/null +++ b/test/wasip2/write_permit_test.cpp @@ -0,0 +1,95 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WEBCPP_TEST_PENDING_WRITE +namespace { +std::optional& tested_stream() { + static std::optional handle; + return handle; +} +} // namespace + +extern "C" streams_own_pollable_t real_subscribe(streams_borrow_output_stream_t stream) asm( + "__real_streams_method_output_stream_subscribe"); +#endif + +// Linker wrappers model valid host quotas at the WASI C boundary. The large +// quota case still writes real bytes to Wasmtime stdout. The pending case +// supplies a native clock pollable that will not become ready during the test. +extern "C" bool real_check_write( + streams_borrow_output_stream_t stream, uint64_t* capacity, + streams_stream_error_t* error) asm("__real_streams_method_output_stream_check_write"); +extern "C" bool wrapped_check_write( + streams_borrow_output_stream_t stream, uint64_t* capacity, + streams_stream_error_t* error) asm("__wrap_streams_method_output_stream_check_write"); + +extern "C" bool wrapped_check_write(streams_borrow_output_stream_t stream, uint64_t* capacity, + streams_stream_error_t* error) { +#ifdef WEBCPP_TEST_PENDING_WRITE + if (tested_stream() == stream.__handle) { + *capacity = 0; + return true; + } + return real_check_write(stream, capacity, error); +#else + if (!real_check_write(stream, capacity, error)) { + return false; + } + if (*capacity != 0) { + *capacity = uint64_t{1} << 32u; + } + return true; +#endif +} + +#ifdef WEBCPP_TEST_PENDING_WRITE +extern "C" streams_own_pollable_t wrapped_subscribe(streams_borrow_output_stream_t stream) asm( + "__wrap_streams_method_output_stream_subscribe"); + +extern "C" streams_own_pollable_t wrapped_subscribe(streams_borrow_output_stream_t stream) { + if (!tested_stream()) { + tested_stream() = stream.__handle; + return monotonic_clock_subscribe_instant(std::numeric_limits::max()); + } + return real_subscribe(stream); +} +#endif + +int main() { + webcpp::asio::io_context context; + webcpp::asio::wasi::stdio_stream stream(context.get_executor()); + webcpp::asio::steady_timer timer(context); + int calls = 0; +#ifdef WEBCPP_TEST_PENDING_WRITE + timer.expires_after(std::chrono::milliseconds(5)); + timer.async_wait([&](boost::system::error_code error) { + BOOST_TEST(!error); + stream.cancel(); + }); +#endif + stream.async_write_some(boost::asio::buffer("ping", 4), + [&](boost::system::error_code error, std::size_t transferred) { +#ifdef WEBCPP_TEST_PENDING_WRITE + BOOST_TEST_EQ(error, boost::asio::error::operation_aborted); + BOOST_TEST_EQ(transferred, 0U); +#else + BOOST_TEST(!error); + BOOST_TEST_EQ(transferred, 4U); +#endif + ++calls; + }); + context.run(); // lint-run: exercise host quota conversion and pending-write cancellation + BOOST_TEST_EQ(calls, 1); + return webcpp::test::exit_status(boost::report_errors()); +} From a8d0f17bac7a0c1e3934a70070e6b22e1d3abfef Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 10:44:00 -0500 Subject: [PATCH 06/12] Complete WASI and browser capabilities with explicit guards --- AGENTS.md | 36 +- build.jam | 46 +-- doc/asio.adoc | 9 +- doc/building.adoc | 115 +++++- doc/capabilities.adoc | 107 ++++-- doc/changelog.adoc | 8 +- doc/cobalt.adoc | 17 +- doc/feature-matrix.adoc | 153 ++++++-- doc/wasip2.adoc | 35 +- doc/wasip3.adoc | 5 +- example/Jamfile | 7 +- example/asio_capabilities.cpp | 29 ++ example/asio_capabilities.expected | 1 + include/webcpp/asio.hpp | 3 + include/webcpp/asio/browser/async_await.hpp | 6 + .../webcpp/asio/browser/async_wait_event.hpp | 6 + include/webcpp/asio/browser/bridge.hpp | 6 + .../asio/browser/main_thread_context.hpp | 360 ++++++++++++++++++ include/webcpp/asio/browser/src.hpp | 37 ++ include/webcpp/asio/browser/transport.hpp | 6 + include/webcpp/asio/config.hpp | 137 ++++++- include/webcpp/asio/io_context.hpp | 32 +- include/webcpp/asio/ssl.hpp | 8 +- include/webcpp/asio/wasi/stdio_stream.hpp | 5 +- src/cobalt_main.cpp | 8 +- src/openssl_on_webassembly.hpp | 4 +- test/Jamfile | 9 +- test/browser/Jamfile | 42 ++ test/browser/main_profile_program.cpp | 41 ++ test/browser/move_failure_program.cpp | 135 +++++++ test/browser/probes/pthread_return.cpp | 63 +++ test/browser/run.mjs | 36 +- test/browser/worker_page.html | 47 +++ test/browser/worker_program.cpp | 214 +++++++++++ test/capabilities/Jamfile | 49 +++ test/capabilities/capabilities_test.cpp | 44 +++ test/capabilities/diagnostics_test.cpp | 25 ++ test/capabilities/portable_browser_test.cpp | 16 + test/capabilities/requirements_test.cpp | 6 + test/capability_wasi/Jamfile | 24 ++ test/capability_wasi/datagrams_test.cpp | 288 ++++++++++++++ .../resolver_empty_result_test.cpp | 65 ++++ .../resolver_progress_test.cpp | 173 +++++++++ .../capability_wasi/resolver_runners_test.cpp | 97 +++++ test/capability_wasi/send_retry_test.cpp | 90 +++++ test/cobalt_io_test.cpp | 4 - test/config_test.cpp | 2 +- test/openssl_on_webassembly_test.cpp | 4 +- test/ssl_without_openssl_test.cpp | 4 +- test/wasi_contract_test.cpp | 22 +- test/wasi_udp_gather_test.cpp | 8 +- test/wasip2_tls_cobalt/Jamfile | 39 ++ test/wasip2_tls_cobalt/cobalt_cancel.cpp | 70 ++++ test/wasip2_tls_cobalt/entropy_driver.py | 24 ++ test/wasip2_tls_cobalt/status_driver.py | 18 + test/wasip2_tls_cobalt/tls_driver.py | 14 + 56 files changed, 2652 insertions(+), 207 deletions(-) create mode 100644 example/asio_capabilities.cpp create mode 100644 example/asio_capabilities.expected create mode 100644 include/webcpp/asio/browser/main_thread_context.hpp create mode 100644 test/browser/main_profile_program.cpp create mode 100644 test/browser/move_failure_program.cpp create mode 100644 test/browser/probes/pthread_return.cpp create mode 100644 test/browser/worker_page.html create mode 100644 test/browser/worker_program.cpp create mode 100644 test/capabilities/Jamfile create mode 100644 test/capabilities/capabilities_test.cpp create mode 100644 test/capabilities/diagnostics_test.cpp create mode 100644 test/capabilities/portable_browser_test.cpp create mode 100644 test/capabilities/requirements_test.cpp create mode 100644 test/capability_wasi/Jamfile create mode 100644 test/capability_wasi/datagrams_test.cpp create mode 100644 test/capability_wasi/resolver_empty_result_test.cpp create mode 100644 test/capability_wasi/resolver_progress_test.cpp create mode 100644 test/capability_wasi/resolver_runners_test.cpp create mode 100644 test/capability_wasi/send_retry_test.cpp create mode 100644 test/wasip2_tls_cobalt/Jamfile create mode 100644 test/wasip2_tls_cobalt/cobalt_cancel.cpp create mode 100644 test/wasip2_tls_cobalt/entropy_driver.py create mode 100644 test/wasip2_tls_cobalt/status_driver.py create mode 100644 test/wasip2_tls_cobalt/tls_driver.py diff --git a/AGENTS.md b/AGENTS.md index 3629d2e..55cb3e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,7 +170,10 @@ lane and the recurring `threads` lane in the cooperative profile. The owner approved P2 Asio core and supplied-stream WebSocket on 2026-11-03. `/webcpp/asio//asio` supports `threading=single`, EH on/off, through the shared -checked Boost overlay. Never infer P2 TLS/Cobalt/thread support from core support. +checked Boost overlay. P2 now also supplies the source-built OpenSSL/CA targets, +Cobalt and its SSL wrapper; preserve their dedicated EH-on/off peer and +cancellation tests in `test/wasip2_tls_cobalt`. P2 threading remains unavailable +in the pinned SDK. Never infer new feature support from core support alone. The P2 reactor reuses libc select/poll and omits the unavailable pipe interrupter. `tools/boost/asio-wasip2` owns the checked SDK 34.0 private descriptor-table bridge and the asynchronous DNS extension. Revalidate its libc ABI before changing SDKs. @@ -200,11 +203,15 @@ Preserve datagram boundaries: WASIp3 `send_to` and `async_send_to` concatenate multiple nonempty UDP buffers into one datagram until wasi-libc provides `sendmsg`. Gather before Asio's native iovec limit, use the context allocator for synchronous storage and the handler's associated allocator for asynchronous -storage, and release operation storage before invoking the handler. Multiple -nonempty receive buffers and connected `send`/`async_send` remain unsupported. -The scalar/empty-buffer path must work without heap scratch buffers. TCP -partial transfers remain valid. Single-thread async DNS posts an unsupported -result; it must not try to construct a null thread or abort initiation. +storage, and release operation storage before invoking the handler. Connected +`send`/`async_send` use the same gather path; multi-buffer receives scatter one +received datagram, retaining truncation semantics. The scalar/empty-buffer path +must work without heap scratch buffers. TCP partial transfers remain valid. +Both P3 thread profiles use native asynchronous DNS and the checked private +waitable-descriptor bridge. Never block initiation or use a polling timer for +lookup progress. Validate the SDK/libc ABI snapshot before using the bridge. +Keep deferred initiation, cancellation, associated executors and allocator +release-before-callback witnesses in `test/capability_wasi`. Keep `doc/capabilities.adoc` current for every feature/target/variant change. `/webcpp/asio//cobalt` supports WASIp3 through the superproject's checked @@ -282,3 +289,20 @@ OpenSSL's native Perl harness is not evidence for its WASI configuration. Use the repository's `webcpp-documentation` skill for Diataxis organization, AsciiDoc and generated MrDocs reference. The maintained `doc/changelog.adoc` is the final appendix; never edit generated reference or matrix files by hand. + +## Capability completion and browser workers (2026-11-03) + +`config.hpp` owns read-only numeric `WEBCPP_ASIO_HAS_*` capabilities. Optional +`WEBCPP_ASIO_REQUIRE_*` switches assert compile-visible requirements without +banning portable headers. Selected `WEBCPP_ASIO_HAS_OPENSSL=1` remains distinct +from platform `HAS_OPENSSL_BACKEND`. Runtime network grants, TLS identities, +page isolation and blocking host imports are not compile-time facts. + +Emscripten explicitly supports S and M with JSPI/Asyncify and both EH choices. +Only S disables Asio threads. The M poll wrapper preserves suspension on the +actual main thread; do not silently enable PROXY_TO_PTHREAD. Run a browser +context only on its creator thread, post between threads, and keep DOM values +on main. `browser::main_thread_context` callbacks are nonsuspending. Its context +must outlive executor calls. See the public worker guide and the real-browser +`browser-workers` lane. The versioned raw pthread-return probe documents the +pinned Asyncify SDK limitation; it is not a passing feature test. diff --git a/build.jam b/build.jam index 6e913e2..e965ea7 100644 --- a/build.jam +++ b/build.jam @@ -12,7 +12,6 @@ project /webcpp/asio ; import feature ; import numbers ; -import errors ; import webcpp ; import webcpp-target ; @@ -64,14 +63,13 @@ rule asyncify-stack ( properties * ) # emscripten by asio's usage requirements below. obj browser-src : src/browser_src.cpp : include /boost//headers /webcpp/config//config - emscripten:BOOST_ASIO_DISABLE_THREADS ; + emscripten,single:BOOST_ASIO_DISABLE_THREADS ; explicit browser-src ; -# On emscripten Asio needs BOOST_ASIO_DISABLE_THREADS: without it, -# stops at "Only Windows and POSIX are -# supported!" (, line 27 in Boost -# 1.92). Its inline namespace differs with and without threads, so a -# translation unit that missed the define fails at link. The browser's +# Single-thread Emscripten needs BOOST_ASIO_DISABLE_THREADS. A pthread build +# supplies the POSIX thread implementation instead. Boost's inline namespace +# differs with and without threads, so every translation unit must agree. +# The browser's # values reach C++ through embind: -lembind, a free feature, which a usage # requirement keeps. # @@ -92,10 +90,11 @@ alias asio : : : : include /boost//headers clang-wasip2:/webcpp/asio-wasip2//headers clang-wasip2:/webcpp/asio-wasip2//pollable clang-wasip3:/webcpp/asio-wasip3//headers - emscripten:BOOST_ASIO_DISABLE_THREADS + emscripten,single:BOOST_ASIO_DISABLE_THREADS emscripten:-lembind emscripten:-Wl,--export=emscripten_stack_get_current emscripten:-Wl,--export=_emscripten_stack_restore + emscripten,multi:-Wl,--wrap=__syscall_poll emscripten:browser-src emscripten,jspi:-sJSPI emscripten,asyncify:-sASYNCIFY @@ -103,16 +102,7 @@ alias asio : : : : include /boost//headers emscripten:@webcpp%suspend-tag ; # end::asio[] -# WASIp3 uses the checked Cobalt/Asio overlays. -# The Cobalt integration is not validated on WASIp2. -rule cobalt-platform ( properties * ) -{ - if [ webcpp-target.target-of $(properties) ] = wasip2 - { - errors.user-error "webcpp::asio: Cobalt requires native, Emscripten or WASIp3." ; - } -} - +# WASIp2 and WASIp3 use the same checked Cobalt capability overlays. # Cobalt's entry point, with webcpp's bounded application event loop. # tag::cobalt[] lib cobalt-main : src/cobalt_main.cpp @@ -120,41 +110,31 @@ lib cobalt-main : src/cobalt_main.cpp explicit cobalt-main ; # The checked common Cobalt patch supplies the promise member required even # when a compiler builds the coroutine without exception handling. -alias cobalt : : @cobalt-platform : : asio cobalt-main /webcpp//boost_cobalt ; +alias cobalt : : : : asio cobalt-main /webcpp//boost_cobalt ; # end::cobalt[] # tag::openssl[] -rule openssl-required ( properties * ) -{ - if [ webcpp-target.target-of $(properties) ] = wasip2 - { - errors.user-error "webcpp::asio: OpenSSL requires native or WASIp3; WASIp2 is not supported." ; - } -} - rule openssl-linked ( properties * ) { - if [ webcpp-target.target-of $(properties) ] in native wasip3 + if [ webcpp-target.target-of $(properties) ] in native wasip2 wasip3 { return /webcpp/third_party//openssl WEBCPP_ASIO_HAS_OPENSSL=1 ; } } -# Refused on WebAssembly: every source of a program built for emscripten +# Refused on Emscripten: every source of a program built for emscripten # that names it stops at the forced include, whose message says what to # write. Quoted, as the Jamroot quotes Boost's directory, for a path that # holds a space. path-constant WEBCPP_ASIO_ROOT : . ; -alias openssl : : @openssl-required - : : @openssl-linked +alias openssl : : : : @openssl-linked emscripten:"-include \"$(WEBCPP_ASIO_ROOT)/src/openssl_on_webassembly.hpp\"" emscripten:"-include \"$(WEBCPP_ASIO_ROOT)/src/openssl_on_webassembly.hpp\"" ; # end::openssl[] # Browser tests exercise the settings adapter without linking OpenSSL. -alias openssl-tests : : @openssl-required - : : @openssl-linked ; +alias openssl-tests : : : : @openssl-linked ; explicit openssl-tests ; # An explicit portable trust policy, separate from the raw OpenSSL context. diff --git a/doc/asio.adoc b/doc/asio.adoc index e78c897..0f713b9 100644 --- a/doc/asio.adoc +++ b/doc/asio.adoc @@ -21,10 +21,11 @@ lacks there, the configuration Asio needs to build, what wakes `run` from a browser event, and a limit on the handlers one turn runs, so that the page keeps rendering. -WASIp2 provides single-threaded timers, TCP/UDP, pollable-driven forward DNS and -supplied CLI streams. See <> for its explicit limitations. -WASIp3 additionally provides timers, TCP/UDP and optional source-built TLS, with -single-thread and experimental cooperative-thread profiles. See <> for their +WASIp2 provides single-threaded timers, TCP/UDP, pollable-driven forward DNS, +supplied CLI streams, Cobalt and optional source-built TLS. +See <> for its explicit limitations. +WASIp3 provides timers, TCP/UDP, waitable-driven forward DNS, Cobalt and the same +optional TLS provider, with single-thread and experimental cooperative-thread profiles. See <> for their limits and the features available in each target variant. [#asio-reading] diff --git a/doc/building.adoc b/doc/building.adoc index 83ab310..2dca0b6 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -10,7 +10,7 @@ asio is developed inside the webcpp superproject, as a Boost library is developed inside Boost. Its headers share Boost's executor model; the browser bridge and optional Cobalt entry point have compiled support units. A b2 -program uses `/webcpp/asio//asio` on native, Emscripten and WASIp3: +program uses `/webcpp/asio//asio` on native, Emscripten and WASIp2/P3: [listing] ---- @@ -32,13 +32,11 @@ program's name: include::{library-root}/build.jam[tag=asio] ---- -Asio needs `BOOST_ASIO_DISABLE_THREADS` on emscripten: without it, Asio -decides it has threads under any compiler that defines `+__GNUC__+` outside -Linux, Emscripten's among them, and `` stops at -"Only Windows and POSIX are supported!". The page has no threads, and the -target defines it for every program that uses it on emscripten. Asio's -inline namespace differs with and without threads, so a translation unit -that missed the define fails at link, never silently. +The Emscripten S profile sets `BOOST_ASIO_DISABLE_THREADS`. Explicit +`threading=multi` enables pthreads consistently in the application, browser +support unit and optional Cobalt archive. Asio's inline namespace differs with +and without threads, so all translation units and compiled dependencies must +use matching settings. The bridge's JavaScript uses `stackSave` and `stackRestore`. On Emscripten 6.0.11, their native dependencies must survive the native link before @@ -47,6 +45,85 @@ The bridge's JavaScript uses `stackSave` and `stackRestore`. On Emscripten including in optimized JSPI builds. A build outside b2 must keep the same link flags shown above. +[#asio-building-workers] +=== Browser workers and main-thread callbacks + +Select `threading=multi` together with either suspension variant and exception +setting. The public target supplies `-pthread` through the toolset and the +threaded main-poll adapter. It does not move `main` to a worker automatically. +The M-only `-Wl,--wrap=__syscall_poll` adapter uses the pinned SDK's async poll +on the actual browser main thread; worker waits retain the SDK proxy route. +This private SDK boundary must be rechecked when Emscripten is upgraded. + +A browser `io_context` must run on the thread that constructed it. Other +threads may `post` ordinary {cpp} work to its executor. One context does not +support simultaneous runners; keep separate contexts per worker. Running it +from a different thread triggers a checked-build assertion and returns zero +when assertions are disabled, before accessing thread-local JavaScript values. + +`browser::main_thread_context` supplies an Asio executor for DOM callbacks. +Construct and destroy that context on the actual browser main thread; copy its +executor to workers and use `boost::asio::post` or `bind_executor`. Obtain +JavaScript objects inside the main callback and send ordinary {cpp} data back to +the worker. Do not move `emscripten::val` handles between threads. The context +must outlive calls using its executors, and destruction must not overlap such +calls. If a callback destroys its context, an external allocator resource must +outlive the callback because queue control survives until it returns. Queued +handlers are discarded during shutdown. Handler storage follows +its associated allocator; the SDK owns its separate queue/notification storage. + +A main-executor callback runs on an ordinary browser callback stack. It must +not call a JSPI/Asyncify suspending import or drive the context's run family. +Normal {cpp} coroutine suspension that returns to its caller is a different +mechanism. If moving or invoking a handler throws, queued handlers are discarded +and further queued submissions are discarded. Inline main-thread `dispatch` +retains its ordinary direct-call behavior. The exception propagates to the +browser callback boundary; recovery after that failure is not promised. Cancellation still belongs to the originating operation; posting +a callable does not add a new cancellation protocol. + +The host needs a secure context, workers and shared memory. Serve the page with +`Cross-Origin-Opener-Policy: same-origin` and +`Cross-Origin-Embedder-Policy: require-corp`, and check `crossOriginIsolated`. +These deployment requirements cannot be diagnosed in `config.hpp`. +Applications choose their worker-pool size and must retain the runtime while +work is pending. Never block the browser main thread waiting for a live worker. + +The local lane covers JSPI/Asyncify with EH on/off in an isolated Chrome page: + +[source,bash] +---- +b2 libs/asio/test/browser//browser-workers toolset=emscripten \ + threading=multi webcpp-suspend=jspi exception-handling=on +---- + +Repeat with `webcpp-suspend=asyncify` and `exception-handling=off` for the +other profiles. The driver tests actual main/worker wakeup, DOM handoff, +cancellation, allocator routing, queued shutdown and Cobalt thread completion. +The exact coverage appears in <>. + +==== Pinned Asyncify pthread return-value limit + +A dependency-only witness is versioned in +`test/browser/probes/pthread_return.cpp`. It suspends a pthread entry, returns +pointer value 42, and joins without blocking the browser main thread. With +Emscripten 6.0.11, JSPI preserves 42; Asyncify returns zero and the witness +fails. This does not involve Asio. Void-return worker paths with explicit {cpp} +result storage are tested successfully in both variants. This runtime path is +not identifiable from a target define, so no broad compile-time ban is imposed. + +To reproduce from the superproject root using the configured SDK: + +[source,bash] +---- +em++ libs/asio/test/browser/probes/pthread_return.cpp \ + -pthread -sPTHREAD_POOL_SIZE=1 -sJSPI -o worker_return-jspi.js +node libs/asio/test/browser/run.mjs --mode workers worker_return-jspi.js +---- + +Replace `-sJSPI` with `-sASYNCIFY -sASYNCIFY_STACK_SIZE=8192` and change the +output name for the failing control. The failure is retained as evidence of an +SDK limitation, not counted as a passing application test. + [#asio-building-variants] === The two suspension variants @@ -266,7 +343,7 @@ a pass, in each variant: a `main` that never finishes, and a `main` that suspended and then returns 1 without the helper. [#asio-tls] -=== TLS: build OpenSSL from source on native and WASIp3 +=== TLS: build OpenSSL from source on native and WASI For a program including ``, add `/webcpp/asio//openssl` beside `/webcpp/asio//asio` in its target sources: @@ -300,7 +377,7 @@ static archives and the B2 runtime/debug settings; the initial Windows recipe uses portable C without requiring NASM. For a program built both natively and for the browser, use the condition below. -It also selects OpenSSL for WASIp3; browser builds retain the settings adapter: +It also selects OpenSSL for WASIp2/P3; browser builds retain the settings adapter: [listing] ---- @@ -317,13 +394,13 @@ Correct configuration errors as follows: libssl, libcrypto and platform dependencies yourself. * If the source checkout is missing, initialize the submodule with the command above. Tests requiring OpenSSL fail rather than silently skipping TLS. -* If the target is named for the browser or WASIp2, select native or WASIp3. +* If the target is named for the browser, select native or WASIp2/P3. The browser settings record does not implement TLS inside the Wasm module. * With WASIp3 `threading=multi`, use `exception-handling=off` with wasi-sdk 34.0: its cooperative sysroot does not contain the {cpp} exception runtime. The built-in default and base providers are linked statically. Loading provider -modules is disabled; this configuration is not a FIPS build. WASIp3 also disables +modules is disabled; this configuration is not a FIPS build. Both WASI profiles disable assembly, dynamic loading, QUIC, Unix-domain sockets and the OpenSSL thread pool. Native Clang/GCC builds retain upstream assembly optimizations; the initial MSVC recipe uses portable C. The recipe uses function and data sections plus @@ -342,7 +419,7 @@ context. WASI applications using a file must preopen its directory. Embedded authorities need no certificate filesystem access. Both require the needed TCP network capability; linking the library grants no runtime permission. -WASIp3 seeding explicitly selects OpenSSL's `getrandom` configuration, whose +WASI seeding explicitly selects OpenSSL's `getrandom` configuration, whose WASI implementation calls `getentropy`, then wasi-libc's secure `wasi:random/random.get-random-bytes` host import. With Wasmtime's default host configuration, the generator is seeded from the operating system. The host @@ -356,17 +433,17 @@ The reproducible local test driver is `python3 tools/openssl/test/run.py --fresh from the superproject. It needs Python with TLS 1.3 and an OpenSSL 3 command-line program only to create short-lived server fixtures. The client links the source-built library. `WASMTIME` selects the runtime executable; the recorded -WASIp3 checks use wasi-sdk 34.0 and Wasmtime 50.0.1. See +WASIp2/P3 checks use wasi-sdk 34.0 and Wasmtime 50.0.1. See <> for the target/variant matrix. The recurring own lane `b2 libs/asio/test/tls//tls-integration` drives those -TLS, embedded-CA, state, cancellation and entropy fixtures on native and WASIp3 +TLS, embedded-CA, state, cancellation and entropy fixtures on native and WASIp2/P3 profiles. `b2 libs/asio/test/tls//openssl-upstream` is native only: it requests `webcpp-openssl-tests=on`, builds and runs upstream's full `alltests` suite, then links a TLS consumer against those exact archives. The `openssl-upstream-msvc-14.3` and `openssl-upstream-msvc-14.5` aliases exercise that suite with the corresponding Windows CI toolsets. Ordinary consumers do -not run that suite. The upstream harness is unavailable on WASIp3; the separate +not run that suite. The upstream harness is unavailable on WASI; the separate integration tests give narrower evidence and do not claim upstream-suite parity. A lane declaration is not evidence that the current candidate passed CI. @@ -380,11 +457,11 @@ include::{library-root}/build.jam[tag=openssl,indent=0] [#asio-ca-certificates] === How-to: configure trusted certificate authorities -For a native or WASIp3 client with portable trust defaults, include +For a native or WASI client with portable trust defaults, include `` and link `/webcpp/asio//tls`. The target includes Asio, source-built OpenSSL and `/webcpp/third_party//ca_certificates`. No certificate file, environment setting, -system trust store or network download is read by the factory. WASIp3 needs no +system trust store or network download is read by the factory. WASI needs no certificate directory preopen; a network connection still needs host permission. This program prepares the context and checks errors without exceptions. With no @@ -472,7 +549,7 @@ integration and automatic runtime updates are separate features. Local tests cover real TLS 1.2/1.3 connections, wrong hostnames, an unrelated CA, and rejection of a private test CA by the default public bundle. They also check complete replacement and invalid input. The matrix covers native macOS -single/multi with exceptions on/off, WASIp3 single with exceptions on/off, and +single/multi with exceptions on/off, WASIp2/P3 single with exceptions on/off, and WASIp3 cooperative threads with exceptions off under SDK 34. The WASIp3 client runs without certificate filesystem grants. Tests use a fresh local test CA; they do not depend on a public website's availability. diff --git a/doc/capabilities.adoc b/doc/capabilities.adoc index 33ffd34..a6963e6 100644 --- a/doc/capabilities.adoc +++ b/doc/capabilities.adoc @@ -25,10 +25,10 @@ distinguishes public support, isolated probes and unverified combinations. | Target and variant | Threads | Exceptions | Status | Native | OS threads, subject to Boost configuration | On or off | Existing integration; native controls run on macOS arm64. -| Emscripten / JSPI | Disabled in this integration | On or off -| Existing browser integration; Wasm exceptions when enabled. -| Emscripten / Asyncify | Disabled in this integration | On or off -| Existing browser integration; JavaScript exceptions when enabled. +| Emscripten / JSPI | Single or pthread workers | On or off +| Wasm exceptions when enabled; M requires isolation and creator-thread affinity. +| Emscripten / Asyncify | Single or pthread workers | On or off +| JavaScript exceptions when enabled; M has the raw pthread return-value limit below. | WASIp3 / `threading=single` | Disabled | On or off | Minimal port; both configurations tested with wasi-sdk 34.0 and Wasmtime 50.0.1. | WASIp3 / `threading=multi` | Experimental cooperative threads | Off @@ -36,9 +36,9 @@ distinguishes public support, isolated probes and unverified combinations. | WASIp3 / `threading=multi` | Experimental cooperative threads | On | Unavailable with the tested SDK: its cooperative sysroot has no {cpp} exception runtime. | WASIp2 / `threading=single` | Disabled | On or off -| Core, timers, TCP/UDP, forward DNS and CLI streams tested; see <>. +| Core, timers, TCP/UDP, forward DNS, CLI streams, Cobalt and TLS; see <>. | WASIp2 / `threading=multi` | Unavailable | On or off -| Rejected by the build; no cross-thread reactor wakeup is provided. +| Rejected: the pinned SDK has no supported P2 pthread runtime/profile. |=== `variant=debug` and `variant=release` select build optimization, not different @@ -50,6 +50,62 @@ operations; this does not provide simultaneous CPU execution on multiple cores. include::feature-matrix.adoc[] +[#asio-capability-guards] +=== Require a capability at compile time + +`` defines the following read-only macros as `0` or `1`. +Use `#if`, not `#ifdef`, to inspect them. Do not define these capabilities on +the command line: the header rejects attempts to override them. + +[cols="3,5",options="header"] +|=== +| Macro suffix after `WEBCPP_ASIO_` | Meaning of `1` +| `HAS_SOCKET_BACKEND` | Native/WASI TCP and UDP backend, subject to runtime grants and options. +| `HAS_OPENSSL_BACKEND` | This target supports the optional source-built OpenSSL provider. +| `HAS_HOST_DNS` | Forward lookup through the native/WASI host, subject to host DNS policy. +| `HAS_REVERSE_DNS` | Native reverse lookup; the WASI interface is forward-only. +| `HAS_THREADS` | Boost.Asio thread support is enabled in this build, including cooperative threads. +| `HAS_BROWSER_BRIDGE` | Emscripten JavaScript events and Promises can reach the executor. +| `HAS_BROWSER_WORKERS` | Emscripten pthread build with Asio thread support. +| `HAS_WASI_STDIO` | The WASIp2 pollable CLI stream adapter is available. +| `HAS_LOCAL_SOCKETS`, `HAS_SIGNALS`, `HAS_SERIAL_PORT` +| Native target with the corresponding Boost.Asio facility enabled. +|=== + +`WEBCPP_ASIO_HAS_OPENSSL=1` is different: it declares that the optional compiled +dependency was selected. `/webcpp/asio//openssl` and `//tls` supply it together +with the matching provider. Outside B2, the application must also supply the +matching OpenSSL headers and libraries. Merely defining it cannot satisfy the +linker. `ssl.hpp` rejects native/WASI use without that dependency; Emscripten +keeps its portable TLS settings record. + +Define a `WEBCPP_ASIO_REQUIRE_*` switch to a nonzero integer before the first +WebCPP include, or on the compiler command line, to require `SOCKET_BACKEND`, +`OPENSSL`, `THREADS`, `LOCAL_SOCKETS`, `SIGNALS`, `SERIAL_PORT` or `REVERSE_DNS`. +An absent switch or a value of zero imposes no requirement. The default permits +portable applications to select runtime alternatives, including browser transports. +Apply configuration consistently to every translation unit. + +This compiled example requires a real socket backend and still handles a +runtime refusal from the host: + +[source,cpp] +---- +include::{examples}/asio_capabilities.cpp[tag=program,indent=0] +---- + +[listing] +---- +include::{examples}/asio_capabilities.expected[] +---- + +The browser-specific headers diagnose a non-Emscripten target before including +Emscripten headers. `wasi/stdio_stream.hpp` diagnoses targets without the P2 CLI +adapter. B2 rejects unsupported SDK/thread/EH combinations and checks the private +WASI descriptor ABI. A compiler cannot determine network grants, available peers, +trust roots, a page's isolation headers or whether a host import will block. +Those conditions retain runtime errors or the documented host behavior. + [#asio-capabilities-core] === Execution and integration features @@ -68,7 +124,8 @@ The separate <> table records the P2 profile. | Boost contract | Supported | Context/timer/post counters tested | Context/timer/post counters tested; named libc pipe allocations separate | Multiple threads posting or running a context -| Boost contract | Unavailable | Unavailable | Tested: wakeup and two runners +| Boost contract | Cross-thread post in M; one creator-thread runner per context +| Unavailable | Tested: wakeup and two runners | {cpp}20 Boost.Asio `awaitable` / `co_spawn` | Timer coroutine tested | Timer coroutine tested under Node and Chrome | Timer coroutine tested | Timer coroutine tested @@ -111,11 +168,11 @@ coroutine cancellation is a separate mechanism. See <>. | TCP composed read/write with buffer sequences | Supported | Requires custom transport | Supported; partial transfers | Supported; partial transfers | UDP send/receive, including empty datagrams -| Supported | Requires custom transport | Supported with one nonempty buffer | Supported with one nonempty buffer +| Supported | Requires custom transport | Supported | Supported | UDP `send_to` / `async_send_to` with multiple nonempty buffers | Boost contract | Transport dependent | Supported; concatenated copy | Supported; concatenated copy | UDP receive or connected `send` / `async_send` with multiple nonempty buffers -| Boost contract | Transport dependent | `operation_not_supported` | `operation_not_supported` +| Boost contract | Transport dependent | Supported; gather/scatter copy | Supported; gather/scatter copy | Asynchronous cancellation and TCP EOF | Supported | Transport dependent | Tested | Tested | IPv4 loopback TCP/UDP @@ -129,8 +186,8 @@ coroutine cancellation is a separate mechanism. See <>. | Synchronous resolver | Supported | Retains names; no DNS lookup | wasi-libc resolver | wasi-libc resolver | Asynchronous resolver -| Boost thread pool | Retains names; no DNS lookup | Posts `operation_not_supported` -| Tested with localhost through Boost's thread pool +| Boost thread pool | Retains names; no DNS lookup | Native async host lookup +| Native async host lookup | `available()` / `FIONREAD`, peek, out-of-band marks | OS dependent | Transport dependent | Unavailable in tested libc | Unavailable in tested libc | Socket options @@ -152,10 +209,10 @@ coroutine cancellation is a separate mechanism. See <>. |=== OpenSSL local coverage includes native macOS arm64 single/multi with exceptions -on/off using Clang, WASIp3 single with exceptions on/off, and WASIp3 cooperative +on/off using Clang, WASIp2 and WASIp3 single with exceptions on/off, and WASIp3 cooperative with exceptions off. A GCC 15 native multi-threaded build with exceptions also passed the TLS tests. Linux Clang/GCC mappings are implemented but not runtime-tested -on this macOS host. The native MSVC recipe is unavailable. The source library +on this macOS host. The native MSVC recipe is implemented; this local macOS matrix does not establish Windows runtime coverage. The source library uses OS threads natively and cooperative threads on WASIp3; it does not make cooperative execution CPU-parallel. TLS tests cover verified handshakes, asynchronous application data, clean shutdown and rejected peer identities. @@ -184,14 +241,20 @@ network operations. The browser resolver does not perform DNS; see The gather path rejects payloads above 65,535 bytes with `message_size` before allocating or reading their data; the host may enforce a smaller IP limit. Allocation failure follows the supplied allocator's failure behavior. -* UDP receive and connected `send` / `async_send` still accept at most one - nonempty buffer. More are rejected before consuming or sending a datagram. - Empty buffers do not split a datagram. Empty datagrams are delivered. +* Connected `send` / `async_send` use the same single-datagram gather path. + Multi-buffer receives read one datagram into temporary storage and scatter the + received bytes across the destination sequence. A short destination truncates + the datagram; its remainder is not delivered as another packet. Empty buffers + do not split a datagram. Empty datagrams are delivered. Scratch allocation + follows the synchronous context or asynchronous handler allocator, as for sends. * Synchronous resolution uses wasi-libc. Actual hostname lookup requires host - permission; numeric resolution does not need DNS. The single-thread profile - cannot run Boost's resolver thread pool, so async initiation posts the - unsupported-operation result to the executor. It does not start a hidden thread - or throw during initiation for this condition. + permission; numeric resolution does not need DNS. Both thread profiles use + the native asynchronous forward-lookup import and a waitable-backed descriptor + for `async_resolve`. Initiation is deferred through the executor and other timers + progress while the lookup is pending. Resolver-wide and per-operation + cancellation preserve the normal completion channel. No hidden thread or + periodic DNS polling is introduced. Canonical names, mapped-address policies + and asynchronous reverse lookup are explicitly unsupported. * Interface-name scopes such as `%eth0` are rejected. Decimal IPv6 scopes in the range 0 through 4294967295 are accepted. * Missing socket options, including linger, broadcast, debug, don't-route, @@ -204,8 +267,8 @@ network operations. The browser resolver does not perform DNS; see With exceptions disabled, invoking a throwing overload on an error can still reach Boost's fatal exception handler. Prefer explicit error-code/result paths. * Cobalt uses the same platform restrictions through its public B2 target. - Its async resolver reports `operation_not_supported` without threads; the - cooperative profile uses the resolver worker pool. TLS through Asio/OpenSSL + Its async resolver uses the same native lookup in both thread profiles. + TLS through Asio/OpenSSL with Cobalt tokens uses application-selected trust roots and host network capabilities; embedded roots require no certificate filesystem preopen. See <> and <>. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index f124963..6ffdb1c 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,13 +21,13 @@ Changes prepared for the first WebCPP release. // tag::0.1.0[] * Added Boost.Asio contexts and timers with browser event-loop suspension. -* Added configurable browser turns, defaulting to 100 ready handlers. +* Added browser workers, main-thread handoff and turns defaulting to 100 handlers. * Added Promise and DOM-event operations with cancellation and allocator support. * Added browser socket adapters, retained resolver names and TLS settings. -* Added WASIp3 TCP, UDP, timers and experimental cooperative threads. -* Added Cobalt integration with browser scheduling and WASIp3 networking. +* Added WASIp2/P3 networking, UDP gather/scatter and asynchronous forward DNS. +* Added Cobalt, CLI streams, WASI TLS and P3 cooperative-thread integration. * Added optional source-built OpenSSL and replaceable embedded CA certificates. * Fixed Cobalt TLS state/cancellation and TLS error equality across shared libraries. -* Fixed global configuration propagation and allocator routing for resolver inputs. +* Added capability guards and fixed configuration propagation and resolver allocation. * Added Diataxis guides, compiled examples and MrDocs API reference. // end::0.1.0[] diff --git a/doc/cobalt.adoc b/doc/cobalt.adoc index 9e76620..0fadf26 100644 --- a/doc/cobalt.adoc +++ b/doc/cobalt.adoc @@ -15,7 +15,7 @@ The default turn contains at most 100 handlers, configurable with interrupted, and a yield offers the browser an opportunity to run rather than promising a timer deadline or a rendered frame. -The Cobalt target supports WASIp3 with the single-thread and cooperative +The Cobalt target supports WASIp2 single-thread and WASIp3 single-thread/cooperative profiles in <>. Its checked private Boost overlay removes unavailable local-socket, serial-port and process-signal dependencies from IP networking. The same thread and exception settings reach the application and @@ -85,9 +85,10 @@ Include `` and add `/webcpp/asio//cobalt_ssl` to the program's requirements. This optional target combines the Cobalt runner, the compiled SSL wrapper, source-built OpenSSL and embedded CAs. It supports native Clang/GCC on macOS/Linux and the -three available WASIp3 profiles in <>. The local -native validation uses macOS; it does not establish Linux runtime coverage. -Browser, WASIp2 and the unavailable cooperative/EH-on runtime are refused. +WASIp2 single-thread profile with EH on/off, and the three available WASIp3 +profiles in <>. The local native validation uses +macOS; it does not establish Linux runtime coverage. Browser OpenSSL and the +unavailable WASIp3 cooperative/EH-on runtime are refused. [listing] ---- @@ -190,7 +191,7 @@ For shutdown, the peer first observes `close_notify` but does not send its own. Closing its TCP socket produces `stream_truncated`; cancelling the pending shutdown produces `operation_aborted`. Both paths clear `secure()`, block further application I/O, and make a second shutdown return `no_protocol_option`. -These checks run with TLS 1.2 and 1.3 in the supported native/WASIp3 profiles. +These checks run with TLS 1.2 and 1.3 in the supported native/WASIp2/WASIp3 profiles. Select one case with `--client-arg=read_some`, `write_some`, `read`, `write`, `shutdown_error` or `shutdown_cancel` when diagnosing a failure. @@ -230,13 +231,13 @@ Boost change may require updating this adapter. Linking Cobalt's original runner instead is a fallback with its original behavior, without webcpp's turn limit; the two runners must not be linked together. -On WASIp3, the runner omits the POSIX signal headers, registration and cleanup, +On WASIp2/P3, the runner omits the POSIX signal headers, registration and cleanup, and initializes the promise's `signal_set` pointer to null. This removes its dependency on `SIGINT` and `SIGTERM`; it does not remove Asio's internal `cancellation_signal` or Cobalt's coroutine cancellation machinery. Native and Emscripten builds keep the existing process-signal integration. -A WASIp3 host cannot request graceful shutdown through this automatic signal +A WASI host cannot request graceful shutdown through this automatic signal bridge. An application needs an explicit host/component shutdown protocol that requests cancellation on its executor and lets pending operations finish their cleanup. Calling `io_context::stop()` alone does not do that, and forcibly @@ -257,7 +258,7 @@ that a timer followed by `co_return 7` exits with exactly 7. With Emscripten's default `EXIT_RUNTIME=0`, a debug Asyncify build may print its runtime-retained notice after `std::exit`; the integration does not force runtime shutdown. -The WASIp3 runner returns the coroutine's result to wasi-libc. In wasi-sdk 34.0, +The WASI runner returns the coroutine's result to wasi-libc. In wasi-sdk 34.0, the command startup code reduces that integer to success or failure before returning through `wasi:cli/run`. In the local runner probe, `co_return 7` therefore produces host exit status 1, while `co_return 0` produces 0. This diff --git a/doc/feature-matrix.adoc b/doc/feature-matrix.adoc index 404a351..1afe5b7 100644 --- a/doc/feature-matrix.adoc +++ b/doc/feature-matrix.adoc @@ -7,8 +7,8 @@ [#asio-feature-matrix] === Feature matrix by library and build profile -This records the WebCPP integration of 2026-10-16 with the allocation and -thread-lane follow-up verified on 2026-11-03, using +This records the WebCPP integration and capability-completion work verified +on 2026-11-03, using Boost 1.92.0, Emscripten 6.0.11 and wasi-sdk 34.0. The project now selects Wasmtime 50.0.1 for its regression suites; the original isolated probes used Wasmtime 49.0.3. It is not a @@ -57,17 +57,20 @@ it does not conceal a requirement for exceptions. | A separate profile with Asio's thread support disabled has not been validated. | Browser / JSPI | S | on | T | T | Requires a JSPI-capable engine. | Browser / JSPI | S | off | T | L | Cobalt issue 287; use result-based paths. -| Browser / JSPI | M | on/off | X | X | This integration forces single-threaded builds. +| Browser / JSPI | M | on | T | T | Isolated page and creator-thread affinity. +| Browser / JSPI | M | off | T | L | Same profile; Cobalt issue 287 applies. | Browser / Asyncify | S | on | T | T | Uses the configured Asyncify stack. | Browser / Asyncify | S | off | T | L | Cobalt issue 287; use result-based paths. -| Browser / Asyncify | M | on/off | X | X | This integration forces single-threaded builds. +| Browser / Asyncify | M | on | T | T | Isolated page and creator-thread affinity. +| Browser / Asyncify | M | off | T | L | Same profile; Cobalt issue 287 applies. | WASIp3 | S | on | T | T | Public Cobalt target; Asio threads disabled. | WASIp3 | S | off | T | L | Same tested target; pending-task moves retain issue 287. | WASIp3 | M, cooperative | on | X | X | SDK 34.0 lacks the cooperative {cpp} EH runtime. | WASIp3 | M, cooperative | off | T | L | Public Cobalt target, including its thread coroutine; SDK cooperative runtime and Cobalt issue 287 apply. -| WASIp2 | S | on/off | T | B | Core, socket, forward DNS and supplied-stream consumers. -| WASIp2 | M | on/off | B | B | The current reactor profile supports one application thread. +| WASIp2 | S | on | T | T | Core, DNS, CLI streams, Cobalt and TLS consumers. +| WASIp2 | S | off | T | L | Same consumers; Cobalt issue 287 applies. +| WASIp2 | M | on/off | X | X | Pinned SDK has no supported P2 pthread runtime/profile. |=== *Native S is not a promise of no threads.* The native build does not set @@ -76,8 +79,8 @@ asynchronous name resolution. Explicitly disabling Asio threads is a different configuration and must be applied consistently to the application and compiled dependencies. It does not disable unrelated libraries' threads. -Browser S does set `BOOST_ASIO_DISABLE_THREADS`, and the superproject fixes -Emscripten's `threading=single`. WASIp3 S also disables Asio threads. WASIp3 M +Browser S sets `BOOST_ASIO_DISABLE_THREADS`; explicit M enables pthreads in +the application and compiled dependencies. WASIp3 S also disables Asio threads. WASIp3 M uses cooperative threads, not simultaneous CPU execution on multiple cores. The missing cooperative EH runtime is a limitation of the SDK distribution tested here, not proof that threads and exceptions are fundamentally incompatible. @@ -105,7 +108,7 @@ threads. The strict thread-disabled profile remains U for all features here. | IPv4 TCP connect/accept, read/write, EOF and cancellation | T | T | T | T | IPv4 UDP single-buffer datagrams | T | T | T | T | UDP multi-buffer `send_to` / `async_send_to` | T | T | T | T -| UDP multi-buffer receive and connected send | A | A | A | A +| UDP multi-buffer receive and connected send | T | T | A | A | Synchronous and asynchronous DNS | A | A | A | A | IPv6 traffic, multicast and socket options | A | A | A | A | TLS through Asio/OpenSSL | T | T | T | T @@ -123,7 +126,8 @@ qualification in <>. [#asio-feature-browser] ==== Asio: browser / Emscripten -All columns are S. Both M profiles are X for every row, with either EH setting. +The first table covers S. The M table below records narrower real-browser +worker coverage; S results are not automatically evidence for M. T includes the project's local Emscripten tests under Node; it does not mean every case was independently exercised in every browser engine. The coroutine timer row also passed in HeadlessChrome 153.0.8010.12 in all @@ -143,7 +147,7 @@ four columns, linked for the browser without Node's raw-filesystem option. | OS DNS lookup through that resolver | X | X | X | X | Asio `awaitable`, `co_spawn`, result-based timer wait | T | T | T | T | Strands on the single executor | A | A | A | A -| Worker-thread execution / multiple context runners | X | X | X | X +| Worker-thread execution | X | X | X | X | TLS settings for a transport | T | T | T | T | Linked OpenSSL through the native/WASI TLS target | X | X | X | X | Supplied WebSocket, HTTP or Fetch stream adapter | X | X | X | X @@ -162,6 +166,34 @@ yield gives the host an opportunity to run; it does not guarantee a timer deadline or a rendered frame. EH on uses Wasm exceptions with JSPI and the configured JavaScript exception mechanism with Asyncify. +[#asio-feature-browser-workers] +===== Browser pthread profiles + +These columns use `threading=multi` and real HeadlessChrome 156.0.8078.4 with +isolation headers. Run each context on its constructing thread; post between +threads. See <> for lifetime and hosting requirements. + +[cols="4,1,1,1,1",options="header"] +|=== +| Feature | JSPI / EH on | JSPI / EH off | Asyncify / EH on | Asyncify / EH off +| Main-context wait woken by a browser event | T | T | T | T +| Worker timer, cross-thread wakeup and main DOM handoff | T | T | T | T +| Timer cancellation delivered through the main executor | T | T | T | T +| Context/handler allocators and queued-handler shutdown | T | T | T | T +| Reentrant context destruction with queued work | T | T | T | T +| Cleanup when moving a handler throws | T | N/A | T | N/A +| Reject running a context from a different thread | T | T | T | T +| Multiple simultaneous runners of one browser context | X | X | X | X +| Complete S scheduling, transport and Promise suite under M | U | U | U | U +| Raw pthread return value after an async suspension | T | T | X | X +|=== + +The last row is a dependency-only witness. A suspended pthread returning pointer +value 42 joins with zero under the pinned Asyncify SDK. The versioned probe fails +that assertion; void-return workers with explicit result storage pass in both +variants. This runtime path cannot be identified by a target macro. It is not a +blanket prohibition of pthreads with Asyncify. + [#asio-feature-wasip2] ==== Asio on WASIp2 @@ -183,9 +215,10 @@ consumer contracts, not every Boost.Asio overload. | Asio timer coroutine | T | T | CLI stream pending read cancellation, allocator and executor | T | T | CLI stream WebSocket client/server, text/binary and close | T | T -| UDP multiple-buffer receive and connected multiple-buffer send | X | X +| UDP multiple-buffer receive and connected multiple-buffer send | T | T | POSIX signals, local sockets and serial ports | X | X -| Cobalt runner/wrappers and guest OpenSSL | B | B +| Asio/OpenSSL TLS, roots and peer verification | T | T +| Cobalt runner/wrappers and SSL integration | T | L | Parallel threads, thread pools and cross-thread post | X | X |=== @@ -213,9 +246,9 @@ runtime, including rows that do not otherwise need exceptions. | TCP composed read/write with multiple buffers | T | T | X | T | IPv4 UDP, including empty datagrams | T | T | X | T | UDP multi-buffer `send_to` / `async_send_to` | T | T | X | T -| UDP multi-buffer receive or connected send | X | X | X | X +| UDP multi-buffer receive or connected send | T | T | X | T | Synchronous resolver: numeric addresses and localhost | T | T | X | T -| Asynchronous resolver | X | X | X | T +| Asynchronous forward resolver | T | T | X | T | Arbitrary external DNS and network reachability | U | U | X | U | IPv6 numeric scope parsing and formatting | T | T | X | T | IPv6 connections and multicast interoperability | U | U | X | U @@ -228,14 +261,14 @@ runtime, including rows that do not otherwise need exceptions. | Browser Promise/DOM bridge and browser turn limit | N/A | N/A | X | N/A |=== -The async resolver's X in S means completion with `operation_not_supported`, -not a hidden worker or an initiation-time abort. Its T in M covers localhost -through Boost's thread pool. External name resolution and network access -depend on host capabilities; local loopback evidence does not validate every -host policy or destination. +Both profiles use native asynchronous forward lookup with a waitable-backed +reactor descriptor. Deferred initiation, real localhost lookup, timer progress, +cancellation and allocator routing are tested. The cooperative lane also checks +two-runner cancellation after the host waitable joins the active wait set. +External DNS and network access still depend on host capabilities. -UDP gather concatenates into one datagram and uses the caller-associated -allocator; this does not add scatter receive or connected multi-buffer send. +UDP gather/scatter preserves one datagram and uses the caller-associated +allocator, including connected sends, truncation, empty buffers and cancellation. The separate context/timer/post counters now cover all three supported WASIp3 profiles; narrowly attributed libc wakeup-pipe allocations remain outside the Asio allocator contract. These scenarios are not a complete audit of every @@ -286,7 +319,7 @@ TCP/UDP cancellation and numeric resolution. [#asio-feature-cobalt-browser] ==== Cobalt: browser / Emscripten -All columns are S. Threaded browser profiles are X throughout. +The following columns cover S. M has separate evidence below. [cols="4,1,1,1,1",options="header"] |=== @@ -315,6 +348,39 @@ timer and Promise tests do not establish every Cobalt composition or I/O API. Asyncify tests also measure suspension-stack usage; application call depth still needs an appropriate configured stack, as explained in <>. +M passes the public Cobalt thread posting/completion/join test in all four +suspension/EH combinations. Broader composition, cancellation and Promise paths +under M remain unverified. The completed-thread join still emits the SDK's main +thread blocking warning; Asyncify also emits its documented successful exit notice. +The driver matches only these exact notices. This does not authorize waiting +synchronously on a live worker from the browser main thread. + +[#asio-feature-cobalt-wasip2] +==== Cobalt: WASIp2 + +Both columns use `threading=single`, the public `//cobalt` or optional +`//cobalt_ssl` target, SDK 34.0 and Wasmtime 50.0.1. + +[cols="4,1,1",options="header"] +|=== +| Feature | EH on | EH off +| Runner, bounded posting, timers and exact exit status | T | T +| Asio TCP/UDP with `use_op` and Cobalt IP wrappers | T | T +| Pending accept/read/resolver cancellation | T | T +| Asio/OpenSSL and Cobalt SSL verified TLS | T | T +| Cobalt SSL transfer/shutdown errors and cancellation | T | T +| Entropy-backed key generation and failure handling | T | T +| Moving a pending task safely without exception support | N/A | X +| Thread coroutine, local sockets, serial ports and POSIX signals | X | X +| Broader coroutine families and filesystem I/O | U | U +|=== + +The focused suite has 13 checks per EH profile. Entropy tests observe calls to +host `getentropy`, distinct generated keys and failure handling; they do not +measure the host RNG's entropy strength. TLS uses the shared source-built +OpenSSL and embedded/replacement CA provider. Host networking grants and trust +policy remain application/runtime requirements. + [#asio-feature-cobalt-wasip3] ==== Cobalt: WASIp3 @@ -330,7 +396,7 @@ EH-off tests do not remove the pending-task move restriction in issue 287. | Return success/failure through the WASI command entry point | T | T | X | T | Await Asio IPv4 TCP/UDP, cancellation and EOF with `use_op` | T | T | X | T | Cobalt `io` IPv4 TCP/UDP wrappers, cancellation and EOF | T | T | X | T -| Cobalt async resolver: numeric address | X | X | X | T +| Cobalt async resolver: numeric address | T | T | X | T | Task result and eager promise completion | T | T | X | T | Generators, channels and composition | U | U | X | U | Cobalt thread coroutine completion and join | X | X | X | T @@ -415,23 +481,23 @@ and runtime validation, not just adding `-fexceptions` to an application. | `threading=single` does not define `BOOST_ASIO_DISABLE_THREADS` natively | Native S can still use internal threads. Explicit thread disabling needs consistent library/application settings and its own validation. -| Browser M profiles -| WebCPP's Emscripten integration fixes `threading=single` and disables Asio threads -| Worker execution is not supplied by this integration. Browser support for -workers or shared memory alone does not enable this build profile. +| Browser M hosting and affinity +| Pthreads need isolated shared memory; JavaScript values have thread affinity +| Use the creator thread to run each context and the main executor for DOM work. +Configure COOP/COEP when hosting; compiler macros cannot verify deployment. | Browser sockets and TLS | The default transport returns `operation_not_supported`; only a transport interface and TLS settings are supplied | Supply and validate an adapter. These APIs do not expose raw browser TCP/UDP or provide an OpenSSL stream. See <>. -| WASIp3 async resolver without threads -| Boost's async resolver uses a worker pool, unavailable in S -| S posts `operation_not_supported`. Synchronous resolution remains available; -the M localhost test does not prove arbitrary external DNS reachability. +| WASI reverse DNS and canonical/mapped-name policies +| The host lookup interface supplies forward address results +| Unsupported async policies report `operation_not_supported`. Host DNS permission +remains a runtime fact; numeric and forward lookup paths are available. | WASIp3 UDP buffer sequences | The tested wasi-libc lacks the vectored socket calls used by stock Asio -| `send_to` and `async_send_to` gather into one datagram. Receive and connected -send still reject multiple nonempty buffers. See <>. +| The port supplies gather sends and scatter receives, including connected sends, +with temporary allocator-aware storage. See <>. | WASIp3 socket options and IPv6 scopes | The port exposes only the tested libc interfaces | Missing options return `operation_not_supported`; interface-name scopes are @@ -450,7 +516,8 @@ still need their own success, error and cancellation tests. | Cobalt `io::ssl::stream` | Available through an optional target with a checked Boost 1.92 patch | `/webcpp/asio//cobalt_ssl` adds the wrapper, state/callback corrections and -`native_ssl_handle()` extension. Browser and WASIp2 remain unsupported. See +`native_ssl_handle()` extension. Native, P2 S and supported P3 profiles are +available; browser TLS remains host-owned. See <> for trust configuration and the STARTTLS contract. |=== @@ -473,8 +540,8 @@ do not validate Windows or Linux platform-specific APIs. profile. The Cobalt thread completion/join test does not cover cancellation, exception propagation or concurrent coroutine composition. | Network coverage beyond current loopback cases -| Exercise native scatter receive/connected multi-buffer UDP, resolver variants, -IPv6 traffic, multicast and supported socket options. For WASIp3, record host +| Extend resolver variants, IPv6 traffic, multicast and supported socket options. +Native scatter/connected UDP now has focused S controls. For WASIp3, record host network/DNS grants and test both permitted and denied operations. | Cobalt coroutine families | Add lifecycle, result/error, cancellation and cleanup cases for tasks, @@ -495,8 +562,8 @@ available, and runner cancellation on an actual process signal. WASIp3 file/pipe probes need linking, granted host resources and runtime checks. | Browser engines and unavailable profiles | Record real-browser runs for each supported engine; Node evidence alone -does not cover them. Browser M and WASIp3 M/EH on first need an implemented -build/runtime profile, then the corresponding feature tests. +does not cover them. Browser M has the focused Chrome coverage above, not the +complete S suite. WASIp3 M/EH on needs a matching SDK runtime before validation. |=== [#asio-feature-evidence] @@ -517,6 +584,14 @@ these tests, not a blanket certification of an upstream library. | Native M run/poll and allocation coverage | `run_family_native`, `allocation_native` and `wasi_udp_gather`, Release with `threading=multi` and both EH settings +| WASI datagram sequences and DNS +| `capability_wasi` plus `wasi-dns-threads`: retries, canonical cleanup, +timer progress, cancellation and two-runner ownership +| Browser M contexts and main-thread handoff +| `test/browser//browser-workers`, both suspensions and EH settings; +`test/browser/probes/pthread_return.cpp` is the separate SDK counterexample +| P2 Cobalt/TLS +| `test/wasip2_tls_cobalt` and its `wasip2-tls` lane in both EH profiles | Browser scheduling, timers, Promise/event bridge and transports | `reactor`, `run_family`, `turn_limit`, `timers`, `allocation`, `promise`, `event`, `sockets`, `transport`, `resolver`, and their declared suspension/EH variants diff --git a/doc/wasip2.adoc b/doc/wasip2.adoc index dfcda3f..e613d72 100644 --- a/doc/wasip2.adoc +++ b/doc/wasip2.adoc @@ -9,8 +9,9 @@ Use `/webcpp/asio//asio` with `toolset=clang-wasip2` and `threading=single`. This profile uses Boost 1.92, wasi-sdk 34.0 and Wasmtime 50.0.1. Both exception -modes are supported for the core, timers, TCP/UDP and asynchronous forward DNS. -It does not enable Cobalt, guest TLS or multiple application threads. +modes are supported for the core, timers, TCP/UDP, asynchronous forward DNS, +Cobalt and source-built OpenSSL. Multiple application threads remain unavailable +with the pinned SDK profile. Configure the compiler using the project's wasi-sdk user-configuration example. Then run the local consumers from the superproject root: @@ -19,11 +20,22 @@ Then run the local consumers from the superproject root: ---- b2 -a toolset=clang-wasip2 variant=release threading=single \ exception-handling=on,off testing.launcher=tools/boost/asio-wasip2/run.sh \ - libs/asio/test/wasip2 + libs/asio/test/wasip2 libs/asio/test/capability_wasi b2 -a toolset=clang-wasip2 variant=release exception-handling=on,off \ libs/asio/test/wasip2//supplied-stream libs/asio/test/wasip2//scheduler-idle ---- +Add `/webcpp/asio//cobalt` for Cobalt, `//tls` for OpenSSL with embedded or +replacement trust roots, or `//cobalt_ssl` for Cobalt's SSL wrapper. These targets +share the same source-built provider as native and WASIp3 programs. Run their +real peer, trust, transfer/shutdown and cancellation consumers with: + +[source,bash] +---- +b2 -a toolset=clang-wasip2 variant=release exception-handling=on,off \ + testing.launcher=tools/boost/asio-wasip2/run.sh libs/asio/test/wasip2_tls_cobalt +---- + The first command exercises timers, the run/poll family, TCP and UDP exchanges, coroutines, forward name resolution and pollable readiness. The supplied-stream lane keeps standard input open without sending data; its timer must still cancel @@ -105,16 +117,17 @@ cancellation deadline requires a host/channel whose write imports remain nonbloc [#asio-wasip2-errors] === Unsupported operations and build profiles -`threading=multi`, `/webcpp/asio//cobalt`, `//openssl`, `//tls` and `//cobalt_ssl` -are rejected by this P2 build integration. This does not claim that those features -are impossible in a future port. POSIX signals, Unix-domain sockets, serial ports -and CPU-parallel threads are not provided by this profile. +`threading=multi` is rejected: SDK 34.0 has no supported P2 pthread runtime +profile. POSIX signals, Unix-domain sockets and serial ports are absent from the +host interfaces used here. Use the capability guards in <> +for compiler-visible requirements. Cobalt's known no-EH pending-task move issue +remains an upstream limitation, as on native and P3; see <>. Unsupported socket operations retain error-code overloads. Tested examples include -`linger`, `at_mark` and UDP receive into multiple nonempty buffers, which return -`operation_not_supported`. A rejected receive does not consume its datagram. -UDP `send_to` can gather multiple buffers into one datagram; connected UDP -`send` does not support multiple nonempty buffers. TCP retains partial I/O semantics. +`linger` and `at_mark`, which return `operation_not_supported`. +UDP `send_to` and connected `send` gather multiple buffers into one datagram; +receive scatters one datagram across the destination buffers. Asynchronous forms +retain handler allocation and cancellation. TCP retains partial I/O semantics. Numeric IPv6 scope identifiers work; named interfaces are rejected with `invalid_argument`. Host permission denial is a runtime error, distinct from an unsupported build profile. Prefer error-code/completion-handler paths for recovery, diff --git a/doc/wasip3.adoc b/doc/wasip3.adoc index 0f86190..dbefa87 100644 --- a/doc/wasip3.adoc +++ b/doc/wasip3.adoc @@ -111,11 +111,12 @@ python3 tools/test/cobalt_wasip3_test.py ports, tests timer and socket cancellation, scatter/gather TCP, and TCP EOF. `wasi_core_threads` adds a cross-thread post into a reactor with a pending timer and two runners sharing a context. `wasi_contract` checks empty datagrams, -unsupported vectored UDP receive without consuming data, IPv6 numeric scopes, socket +vectored UDP receive with datagram truncation, IPv6 numeric scopes, socket option errors and resolver behavior. `wasi_coroutine` waits for a timer using Boost.Asio's `co_spawn` and `awaitable` with result-based error handling. The existing run-family and timer tests also run on WASIp3. -`wasi_udp_gather` checks synchronous and asynchronous multi-buffer `send_to`, +`wasi_udp_gather` and `capability_wasi/datagrams` check synchronous and asynchronous +multi-buffer sends and receives, including complete sequences beyond 64 buffers, allocation routing, empty datagrams, oversized input and release of storage before completion. diff --git a/example/Jamfile b/example/Jamfile index f7163a0..3950c92 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -8,7 +8,7 @@ project : requirements /webcpp/asio//asio ; import webcpp ; -webcpp.targets native emscripten wasip3 ; +webcpp.targets native emscripten wasip2 wasip3 ; webcpp.example asio_quick_start.cpp ; webcpp.example asio_turn_limit.cpp : : native emscripten ; @@ -17,8 +17,9 @@ webcpp.example asio_promise.cpp : : emscripten ; webcpp.example asio_event.cpp : : emscripten ; webcpp.example asio_sockets.cpp : : emscripten ; webcpp.example asio_resolver.cpp : : emscripten ; -webcpp.example asio_cobalt.cpp : /webcpp/asio//cobalt : native emscripten wasip3 ; -webcpp.example asio_tls_client.cpp : /webcpp/asio//tls : native wasip3 ; +webcpp.example asio_cobalt.cpp : /webcpp/asio//cobalt : native emscripten wasip2 wasip3 ; +webcpp.example asio_tls_client.cpp : /webcpp/asio//tls : native wasip2 wasip3 ; +webcpp.example asio_capabilities.cpp : : native wasip2 wasip3 ; # A page needs the completion helper header, but not the Node harness. webcpp.variants page-asio_quick_start : asio_quick_start.cpp diff --git a/example/asio_capabilities.cpp b/example/asio_capabilities.cpp new file mode 100644 index 0000000..af88c75 --- /dev/null +++ b/example/asio_capabilities.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// tag::program[] +// State requirements before the first WebCPP include, or use a compiler define. +#define WEBCPP_ASIO_REQUIRE_SOCKET_BACKEND 1 +#include +#include +#include +#include + +int main() { + webcpp::asio::io_context context; + webcpp::asio::ip::tcp::socket socket(context); + boost::system::error_code error; + if (socket.open(webcpp::asio::ip::tcp::v4(), error)) { + // A compiled backend does not imply that the host granted socket access. + const auto message = error.message(); + (void)std::fprintf(stderr, "socket open: %s\n", message.c_str()); + return webcpp::test::exit_status(1); + } + std::puts("TCP socket opened"); + return webcpp::test::exit_status(0); +} + +// end::program[] diff --git a/example/asio_capabilities.expected b/example/asio_capabilities.expected new file mode 100644 index 0000000..72a9404 --- /dev/null +++ b/example/asio_capabilities.expected @@ -0,0 +1 @@ +TCP socket opened diff --git a/include/webcpp/asio.hpp b/include/webcpp/asio.hpp index f54b941..97e5818 100644 --- a/include/webcpp/asio.hpp +++ b/include/webcpp/asio.hpp @@ -29,6 +29,9 @@ #include #include #include +#if WEBCPP_ASIO_HAS_BROWSER_WORKERS +#include +#endif #endif #endif // WEBCPP_ASIO_HPP diff --git a/include/webcpp/asio/browser/async_await.hpp b/include/webcpp/asio/browser/async_await.hpp index 6e5fbc2..4f4ac8a 100644 --- a/include/webcpp/asio/browser/async_await.hpp +++ b/include/webcpp/asio/browser/async_await.hpp @@ -9,6 +9,11 @@ #include +#if !WEBCPP_ASIO_HAS_BROWSER_BRIDGE +#error \ + "webcpp::asio::browser::async_await requires the Emscripten browser bridge; use native/WASI Asio operations on this target" +#else + #include // lint-world: the operation's executor #include // lint-world: preserve handler associations when posting values #include // lint-world: operation storage belongs to its handler @@ -166,4 +171,5 @@ auto async_await(const Executor& executor, emscripten::val promise, CompletionTo } } // namespace webcpp::asio::browser +#endif // WEBCPP_ASIO_HAS_BROWSER_BRIDGE #endif // WEBCPP_ASIO_BROWSER_ASYNC_AWAIT_HPP diff --git a/include/webcpp/asio/browser/async_wait_event.hpp b/include/webcpp/asio/browser/async_wait_event.hpp index 6c58c71..b6ee3ae 100644 --- a/include/webcpp/asio/browser/async_wait_event.hpp +++ b/include/webcpp/asio/browser/async_wait_event.hpp @@ -9,6 +9,11 @@ #include +#if !WEBCPP_ASIO_HAS_BROWSER_BRIDGE +#error \ + "webcpp::asio::browser::async_wait_event requires the Emscripten browser bridge; use native/WASI Asio operations on this target" +#else + #include // lint-world: the operation's executor #include // lint-world: preserve handler associations when posting values #include // lint-world: operation storage belongs to its handler @@ -178,4 +183,5 @@ auto async_wait_event(const Executor& executor, emscripten::val target, std::str } } // namespace webcpp::asio::browser +#endif // WEBCPP_ASIO_HAS_BROWSER_BRIDGE #endif // WEBCPP_ASIO_BROWSER_ASYNC_WAIT_EVENT_HPP diff --git a/include/webcpp/asio/browser/bridge.hpp b/include/webcpp/asio/browser/bridge.hpp index 800f754..c150b38 100644 --- a/include/webcpp/asio/browser/bridge.hpp +++ b/include/webcpp/asio/browser/bridge.hpp @@ -9,6 +9,11 @@ #include +#if !WEBCPP_ASIO_HAS_BROWSER_BRIDGE +#error \ + "webcpp::asio::browser::bridge requires the Emscripten browser bridge; use native/WASI Asio completion operations on this target" +#else + #include #include @@ -258,4 +263,5 @@ class bridge : public boost::asio::execution_context::service { } // namespace webcpp::asio::browser +#endif // WEBCPP_ASIO_HAS_BROWSER_BRIDGE #endif // WEBCPP_ASIO_BROWSER_BRIDGE_HPP diff --git a/include/webcpp/asio/browser/main_thread_context.hpp b/include/webcpp/asio/browser/main_thread_context.hpp new file mode 100644 index 0000000..b3e929f --- /dev/null +++ b/include/webcpp/asio/browser/main_thread_context.hpp @@ -0,0 +1,360 @@ +// 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_BROWSER_MAIN_THREAD_CONTEXT_HPP +#define WEBCPP_ASIO_BROWSER_MAIN_THREAD_CONTEXT_HPP + +#include + +#if !WEBCPP_ASIO_HAS_BROWSER_WORKERS && !defined(WEBCPP_ASIO_REFERENCE) +#error \ + "webcpp::asio::browser::main_thread_context requires Emscripten pthreads; select threading=multi" +#else + +#include +#include +#include +#include // lint-world: owns the main-thread executor service +#include +#include +#include + +#include +#include +#include +#include + +namespace webcpp::asio::browser { + +/** + An execution context that posts C++ handlers onto the browser's main runtime thread. + + Construct and destroy it on the main browser thread. Its executors may be copied to + workers and used with post, dispatch, defer and bind_executor. Handlers execute in + ordinary browser callbacks and must not suspend WebAssembly's stack or call an + io_context run family. + JavaScript values remain on their owning thread: obtain DOM values inside the main + handler, and exchange ordinary C++ data with worker contexts through their executors. + + Destruction discards queued handlers without invoking them. As with an Asio context, + the context must outlive every call that uses its executors. The Emscripten runtime + must remain alive until pending work finishes. The SDK owns proxy-queue notification + storage; handler storage uses the allocator supplied to the executor. + If moving or invoking a callable throws, remaining queued callables and further + queued submissions are discarded. The exception propagates to the browser's + callback boundary; this context does not promise queue recovery after such a failure. +*/ +class main_thread_context : public boost::asio::execution_context { + struct operation : boost::intrusive::list_base_hook<> { + void (*finish)(operation*, bool); + + explicit operation(void (*function)(operation*, bool)) : finish(function) {} + }; + + template + struct handler_operation final : operation { + // This is storage ownership, not a uses_allocator construction protocol. + using storage_allocator = + std::allocator_traits::template rebind_alloc; + + handler_operation(Function handler, const storage_allocator& storage) + : operation(&complete), function(std::move(handler)), allocator(storage) {} + + static void complete(operation* base, bool invoke) { + auto* self = static_cast(base); + const auto release = [](handler_operation* value) { + auto allocator = value->allocator; + std::allocator_traits::destroy(allocator, value); + std::allocator_traits::deallocate(allocator, value, 1); + }; + std::unique_ptr owned(self, release); + if (!invoke) { + return; + } + // A throwing move still destroys the pending operation. Successful moves + // release its allocation before invoking the callable, as Asio requires. + auto function = std::move(self->function); + owned.reset(); + std::move(function)(); + } + + Function function; + storage_allocator allocator; + }; + + // This state can outlive the Asio service when a handler destroys its context. + // Allocate it with a copy of the original allocator, not execution_context's + // allocator adapter, whose implementation is destroyed with that context. + class control { + public: + control() : queue_(em_proxying_queue_create()) { + if (queue_ == nullptr) { + boost::asio::detail::throw_exception(std::bad_alloc()); + } + } + + ~control() { em_proxying_queue_destroy(queue_); } + + void post(operation* pending, const std::shared_ptr& self) { + std::unique_lock lock(mutex_); + if (stopped_) { + lock.unlock(); + pending->finish(pending, false); + return; + } + pending_.push_back(*pending); + if (active_ || notification_) { + return; + } + // One notification drains our queue. It owns the control even if the + // context is destroyed before the SDK starts delivering that notification. + notification_ = self; + if (!emscripten_proxy_async(queue_, emscripten_main_runtime_thread_id(), &deliver, + this)) { + notification_.reset(); + pending_.erase(pending_.iterator_to(*pending)); + lock.unlock(); + pending->finish(pending, false); + boost::asio::detail::throw_exception(std::bad_alloc()); + } + } + + void stop() { + boost::intrusive::list discarded; + bool drain = false; + { + const std::scoped_lock lock(mutex_); + stopped_ = true; + discarded.splice(discarded.end(), pending_); + drain = !active_ && notification_ != nullptr; + } + while (!discarded.empty()) { + auto& pending = discarded.front(); + discarded.pop_front(); + pending.finish(&pending, false); + } + // The SDK rejects recursive queue execution. Active delivery already + // retains this control, and will observe the now-empty stopped queue. + if (drain) { + emscripten_proxy_execute_queue(queue_); + } + } + + private: + static void deliver(void* argument) { + auto& state = *static_cast(argument); + std::shared_ptr self; + { + const std::scoped_lock lock(state.mutex_); + self = std::move(state.notification_); + state.active_ = true; + } + bool finished = false; + const boost::scope::scope_exit cleanup([&] { + if (!finished) { + // A throwing callable must not strand queued allocations or an + // active flag. The exception still propagates to the browser. + self->stop(); + const std::scoped_lock lock(self->mutex_); + self->active_ = false; + } + }); + for (;;) { + operation* pending = nullptr; + { + const std::scoped_lock lock(self->mutex_); + if (self->pending_.empty()) { + // Atomically release the drain so a concurrent post schedules + // a fresh notification rather than missing this wakeup. + self->active_ = false; + finished = true; + return; + } + pending = &self->pending_.front(); + self->pending_.pop_front(); + } + pending->finish(pending, true); + } + } + + em_proxying_queue* queue_; + std::mutex mutex_; + boost::intrusive::list pending_; + std::shared_ptr notification_; + bool stopped_ = false; + bool active_ = false; + }; + + class service final : public boost::asio::execution_context::service { + public: + // Boost's service identity has an empty constructor and no dynamic dependencies. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,bugprone-throwing-static-initialization,cert-err58-cpp,bugprone-dynamic-static-initializers) + static inline boost::asio::execution_context::id id; + + explicit service(boost::asio::execution_context& context) + : boost::asio::execution_context::service(context) {} + + template + void start(const Allocator& allocator) { + state_ = std::allocate_shared(allocator); + } + + template + void post(Function function, const Allocator& allocator) { + using pending_type = handler_operation; + typename pending_type::storage_allocator storage(allocator); + auto* pending = + std::allocator_traits::allocate(storage, + 1); + // The guard also handles an exception from the user's function move constructor. + const auto release = [storage](pending_type* value) { + auto allocator_copy = storage; + std::allocator_traits::deallocate( + allocator_copy, value, 1); + }; + std::unique_ptr raw(pending, release); + std::allocator_traits::construct( + storage, pending, std::move(function), storage); + (void)raw.release(); + const auto state = state_; + state->post(pending, state); + } + + private: + void shutdown() override { + BOOST_ASSERT_MSG(emscripten_is_main_browser_thread(), + "main_thread_context must be destroyed on the browser main thread"); + if (state_) { + state_->stop(); + state_.reset(); + } + } + + std::shared_ptr state_; + }; + +public: + /** A standard Asio executor for nonsuspending handlers on the browser main thread. */ + class executor_type { + public: + /** Constructs an empty executor, usable only for assignment or comparison. */ + executor_type() = default; + + /** + Returns the context, which must still be alive. + + @return The execution context owning this executor. + */ + [[nodiscard]] main_thread_context& context() const noexcept { + return static_cast(owner_->context()); + } + + /** The browser runtime lifetime is controlled by the application. */ + void on_work_started() const noexcept { + } // NOLINT(readability-convert-member-functions-to-static) + + /** The browser runtime lifetime is controlled by the application. */ + void on_work_finished() const noexcept { + } // NOLINT(readability-convert-member-functions-to-static) + + /** + Dispatches inline on the browser main thread, otherwise posts. + + @tparam Function A nullary callable that does not suspend WebAssembly's stack. + @tparam Allocator A standard allocator for pending handler storage. + @param function The callable. + @param allocator The allocator used when dispatch must post. + */ + template + void dispatch(Function&& function, const Allocator& allocator) const { + if (emscripten_is_main_browser_thread()) { + std::forward(function)(); + return; + } + post(std::forward(function), allocator); + } + + /** + Posts without invoking inline, using allocator for pending handler storage. + + @tparam Function A nullary callable that does not suspend WebAssembly's stack. + @tparam Allocator A standard allocator for pending handler storage. + @param function The callable. + @param allocator The pending handler's allocator. + */ + template + void post(Function&& function, const Allocator& allocator) const { + owner_->post(std::forward(function), allocator); + } + + /** + Defers through the same main-thread queue as post. + + @tparam Function A nullary callable that does not suspend WebAssembly's stack. + @tparam Allocator A standard allocator for pending handler storage. + @param function The callable. + @param allocator The pending handler's allocator. + */ + template + void defer(Function&& function, const Allocator& allocator) const { + post(std::forward(function), allocator); + } + + /** + Compares the contexts owning two executors. + + @return True when the executors belong to the same context. + */ + friend bool operator==(const executor_type&, const executor_type&) = default; + + private: + friend class main_thread_context; + + explicit executor_type(service& owner) : owner_(&owner) {} + + service* owner_ = nullptr; + }; + + /** Constructs a queue on the browser's main runtime thread. */ + main_thread_context() : service_(boost::asio::use_service(*this)) { + service_.start(std::allocator()); + BOOST_ASSERT_MSG(emscripten_is_main_browser_thread(), + "main_thread_context must be constructed on the browser main thread"); + } + + /** + Constructs a main-thread context whose Asio service storage uses allocator. + + @tparam Allocator A standard allocator for context-owned C++ state. + @param allocator The allocator for context-owned C++ state. The Emscripten SDK + allocates its own proxy queue and notifications separately. + If a callback destroys this context, its allocator resource must remain alive + until that callback returns and the retained queue control is released. + */ + template + main_thread_context(std::allocator_arg_t /*tag*/, const Allocator& allocator) + : boost::asio::execution_context(std::allocator_arg, allocator), + service_(boost::asio::use_service(*this)) { + service_.start(allocator); + BOOST_ASSERT_MSG(emscripten_is_main_browser_thread(), + "main_thread_context must be constructed on the browser main thread"); + } + + /** + Returns an executor that can safely be copied to workers. + + @return An executor submitting work to this context on the browser main thread. + */ + [[nodiscard]] executor_type get_executor() noexcept { return executor_type(service_); } + +private: + service& service_; +}; + +} // namespace webcpp::asio::browser + +#endif +#endif // WEBCPP_ASIO_BROWSER_MAIN_THREAD_CONTEXT_HPP diff --git a/include/webcpp/asio/browser/src.hpp b/include/webcpp/asio/browser/src.hpp index 1d6aaa2..00d857b 100644 --- a/include/webcpp/asio/browser/src.hpp +++ b/include/webcpp/asio/browser/src.hpp @@ -9,6 +9,11 @@ #include +#if !WEBCPP_ASIO_HAS_BROWSER_BRIDGE +#error \ + "webcpp::asio::browser::src requires the Emscripten browser bridge; use native/WASI Asio operations on this target" +#else + /** What a program on emscripten compiles once: the JavaScript functions asio calls (detail/browser_imports.hpp), the yield of the run family and the bridge's functions among them, @@ -23,6 +28,9 @@ #include #include #include +#ifdef __EMSCRIPTEN_PTHREADS__ +#include +#endif #include #include @@ -32,6 +40,34 @@ // ExitStatus is what exit() throws. EM_JS_DEPS has Emscripten link them. EM_JS_DEPS(webcpp_asio, "$Emval,_emval_decref,$stackSave,$stackRestore,$UTF8ToString,$ExitStatus"); +#ifdef __EMSCRIPTEN_PTHREADS__ +// Emscripten 6.0.11 routes worker poll through its main-thread proxy, but main-runtime +// poll takes the synchronous path even in a suspending entry stack. Reuse its own +// descriptor wait queues there; keep worker calls on the original proxy path. +EM_JS_DEPS(webcpp_asio_threaded_poll, "$doPollAsync"); +// clang-format off +EM_ASYNC_JS(int, webcpp_asio_main_poll, (void* descriptors, unsigned count, int timeout), { + return await doPollAsync(descriptors, count, timeout); +}); +// clang-format on + +// The linker reserves this spelling for its wrapped syscall import. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" int __real___syscall_poll(void* descriptors, unsigned count, int timeout); + +// --wrap=__syscall_poll selects this only in the pthread build. The pinned wasm32 +// libc import has three i32 arguments and an i32 result. Nonblocking poll uses a +// different import and remains nonsuspending, including inside browser callbacks. +// One definition is required, exactly as for the bridge export below. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,misc-definitions-in-headers) +extern "C" int __wrap___syscall_poll(void* descriptors, unsigned count, int timeout) { + if (emscripten_is_main_runtime_thread()) { + return webcpp_asio_main_poll(descriptors, count, timeout); + } + return __real___syscall_poll(descriptors, count, timeout); +} +#endif + // clang-format off EM_ASYNC_JS(void, webcpp_asio_yield, (), { await new Promise(resolve => { @@ -165,4 +201,5 @@ extern "C" EMSCRIPTEN_KEEPALIVE void webcpp_asio_deliver(void* bridge, std::uint #endif } +#endif // WEBCPP_ASIO_HAS_BROWSER_BRIDGE #endif // WEBCPP_ASIO_BROWSER_SRC_HPP diff --git a/include/webcpp/asio/browser/transport.hpp b/include/webcpp/asio/browser/transport.hpp index 925cf07..a8723d9 100644 --- a/include/webcpp/asio/browser/transport.hpp +++ b/include/webcpp/asio/browser/transport.hpp @@ -9,6 +9,11 @@ #include +#if !WEBCPP_ASIO_HAS_BROWSER_BRIDGE +#error \ + "webcpp::asio::browser::transport requires the Emscripten browser bridge; use native/WASI Asio operations on this target" +#else + #include // lint-world: preserve completion associations #include // lint-world: unsupported browser operations #include // lint-world: socket flags @@ -366,4 +371,5 @@ class transport { } // namespace webcpp::asio::browser +#endif // WEBCPP_ASIO_HAS_BROWSER_BRIDGE #endif // WEBCPP_ASIO_BROWSER_TRANSPORT_HPP diff --git a/include/webcpp/asio/config.hpp b/include/webcpp/asio/config.hpp index bb12c89..a5d560b 100644 --- a/include/webcpp/asio/config.hpp +++ b/include/webcpp/asio/config.hpp @@ -6,13 +6,15 @@ /** The configuration of asio, which each of its headers includes first: whether - asio is built without exceptions, and the default number of handlers per turn. + asio is built without exceptions, target capabilities, and the default number + of handlers per turn. @see "Testing", in the guide. */ #ifndef WEBCPP_ASIO_CONFIG_HPP #define WEBCPP_ASIO_CONFIG_HPP +#include // lint-world: inherit Boost's configured facilities #include #ifndef WEBCPP_ASIO_DEFAULT_MAX_HANDLERS_PER_TURN @@ -66,4 +68,137 @@ #define WEBCPP_ASIO_NO_EXCEPTIONS #endif +// These are observations, never user switches. In particular, selecting the +// optional OpenSSL library is separate from having an OpenSSL-capable target. +#if defined(WEBCPP_ASIO_HAS_SOCKET_BACKEND) || defined(WEBCPP_ASIO_HAS_OPENSSL_BACKEND) || \ + defined(WEBCPP_ASIO_HAS_BROWSER_BRIDGE) || defined(WEBCPP_ASIO_HAS_BROWSER_WORKERS) || \ + defined(WEBCPP_ASIO_HAS_HOST_DNS) || defined(WEBCPP_ASIO_HAS_REVERSE_DNS) || \ + defined(WEBCPP_ASIO_HAS_WASI_STDIO) || defined(WEBCPP_ASIO_HAS_THREADS) || \ + defined(WEBCPP_ASIO_HAS_LOCAL_SOCKETS) || defined(WEBCPP_ASIO_HAS_SIGNALS) || \ + defined(WEBCPP_ASIO_HAS_SERIAL_PORT) +#error \ + "webcpp::asio: capability macros are derived by config.hpp; do not define WEBCPP_ASIO_HAS_* capabilities on the command line" +#else + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +/** 1 when Emscripten supplies the JavaScript event and Promise bridge; otherwise 0. */ +#define WEBCPP_ASIO_HAS_BROWSER_BRIDGE 1 +/** 1 when native or WASI socket APIs back TCP/UDP; grants and options remain runtime facts. */ +#define WEBCPP_ASIO_HAS_SOCKET_BACKEND 0 +/** 1 when this target can link the source-built OpenSSL provider; it does not select it. */ +#define WEBCPP_ASIO_HAS_OPENSSL_BACKEND 0 +/** 1 when the host supplies forward address lookup; it does not imply reverse DNS. */ +#define WEBCPP_ASIO_HAS_HOST_DNS 0 +#else +/** 1 when Emscripten supplies the JavaScript event and Promise bridge; otherwise 0. */ +#define WEBCPP_ASIO_HAS_BROWSER_BRIDGE 0 +/** 1 when native or WASI socket APIs back TCP/UDP; grants and options remain runtime facts. */ +#define WEBCPP_ASIO_HAS_SOCKET_BACKEND 1 +/** 1 when this target can link the source-built OpenSSL provider; it does not select it. */ +#define WEBCPP_ASIO_HAS_OPENSSL_BACKEND 1 +/** 1 when the host supplies forward address lookup; it does not imply reverse DNS. */ +#define WEBCPP_ASIO_HAS_HOST_DNS 1 +#endif + +#ifdef WEBCPP_TARGET_NATIVE +/** 1 for native reverse lookup; WASI's address lookup interface is forward-only. */ +#define WEBCPP_ASIO_HAS_REVERSE_DNS 1 +#else +/** 1 for native reverse lookup; WASI's address lookup interface is forward-only. */ +#define WEBCPP_ASIO_HAS_REVERSE_DNS 0 +#endif + +#ifdef WEBCPP_TARGET_WASIP2 +/** 1 when the pollable WASIp2 CLI stream adapter is available; otherwise 0. */ +#define WEBCPP_ASIO_HAS_WASI_STDIO 1 +#else +/** 1 when the pollable WASIp2 CLI stream adapter is available; otherwise 0. */ +#define WEBCPP_ASIO_HAS_WASI_STDIO 0 +#endif + +#ifdef BOOST_ASIO_HAS_THREADS +/** 1 when this Boost.Asio configuration enables threads, including cooperative threads. */ +#define WEBCPP_ASIO_HAS_THREADS 1 +#else +/** 1 when this Boost.Asio configuration enables threads, including cooperative threads. */ +#define WEBCPP_ASIO_HAS_THREADS 0 +#endif + +#if defined(__EMSCRIPTEN_PTHREADS__) && WEBCPP_ASIO_HAS_THREADS +/** 1 for a pthread browser profile; isolation and worker availability are runtime facts. */ +#define WEBCPP_ASIO_HAS_BROWSER_WORKERS 1 +#else +/** 1 for a pthread browser profile; isolation and worker availability are runtime facts. */ +#define WEBCPP_ASIO_HAS_BROWSER_WORKERS 0 +#endif + +#if defined(WEBCPP_TARGET_NATIVE) && defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) +/** 1 when native Boost.Asio enables local sockets; otherwise 0. */ +#define WEBCPP_ASIO_HAS_LOCAL_SOCKETS 1 +#else +/** 1 when native Boost.Asio enables local sockets; otherwise 0. */ +#define WEBCPP_ASIO_HAS_LOCAL_SOCKETS 0 +#endif +#if defined(WEBCPP_TARGET_NATIVE) && defined(BOOST_ASIO_HAS_SIGNAL) +/** 1 when native Boost.Asio enables process signals; WASI and browser events are not signals. */ +#define WEBCPP_ASIO_HAS_SIGNALS 1 +#else +/** 1 when native Boost.Asio enables process signals; WASI and browser events are not signals. */ +#define WEBCPP_ASIO_HAS_SIGNALS 0 +#endif +#if defined(WEBCPP_TARGET_NATIVE) && defined(BOOST_ASIO_HAS_SERIAL_PORT) +/** 1 when native Boost.Asio enables serial ports; otherwise 0. */ +#define WEBCPP_ASIO_HAS_SERIAL_PORT 1 +#else +/** 1 when native Boost.Asio enables serial ports; otherwise 0. */ +#define WEBCPP_ASIO_HAS_SERIAL_PORT 0 +#endif + +// A consumer can state requirements before including any library header. A +// zero or absent requirement leaves selection to the application at runtime. +#if defined(WEBCPP_ASIO_REQUIRE_SOCKET_BACKEND) && WEBCPP_ASIO_REQUIRE_SOCKET_BACKEND && \ + !WEBCPP_ASIO_HAS_SOCKET_BACKEND +#error \ + "webcpp::asio: this Emscripten target has no raw TCP/UDP socket backend; use a browser transport or a native/WASI target" +#endif +#if defined(WEBCPP_ASIO_REQUIRE_OPENSSL) && WEBCPP_ASIO_REQUIRE_OPENSSL +#if !WEBCPP_ASIO_HAS_OPENSSL_BACKEND +#error \ + "webcpp::asio: OpenSSL is unavailable in the browser profile; use browser-managed HTTPS/WSS or a native/WASI target" +#elif !defined(WEBCPP_ASIO_HAS_OPENSSL) || !WEBCPP_ASIO_HAS_OPENSSL +#error \ + "webcpp::asio: TLS requires /webcpp/asio//openssl or /webcpp/asio//tls; without B2, define WEBCPP_ASIO_HAS_OPENSSL=1 and link the matching libssl/libcrypto" +#endif +#endif +#if defined(WEBCPP_ASIO_REQUIRE_THREADS) && WEBCPP_ASIO_REQUIRE_THREADS && !WEBCPP_ASIO_HAS_THREADS +#error \ + "webcpp::asio: threads are disabled in this configuration; select a supported threading=multi profile (WASIp2 supports single only)" +#endif +#if defined(WEBCPP_ASIO_REQUIRE_LOCAL_SOCKETS) && WEBCPP_ASIO_REQUIRE_LOCAL_SOCKETS && \ + !WEBCPP_ASIO_HAS_LOCAL_SOCKETS +#error \ + "webcpp::asio: local sockets require native Boost.Asio support; WASI/browser targets must use TCP or a supplied byte stream" +#endif +#if defined(WEBCPP_ASIO_REQUIRE_SIGNALS) && WEBCPP_ASIO_REQUIRE_SIGNALS && !WEBCPP_ASIO_HAS_SIGNALS +#error \ + "webcpp::asio: process signals require a native target; use explicit application cancellation on WASI or in the browser" +#endif +#if defined(WEBCPP_ASIO_REQUIRE_SERIAL_PORT) && WEBCPP_ASIO_REQUIRE_SERIAL_PORT && \ + !WEBCPP_ASIO_HAS_SERIAL_PORT +#error \ + "webcpp::asio: serial ports require native Boost.Asio support; WASI/browser need a separate host adapter" +#endif +#if defined(WEBCPP_ASIO_REQUIRE_REVERSE_DNS) && WEBCPP_ASIO_REQUIRE_REVERSE_DNS && \ + !WEBCPP_ASIO_HAS_REVERSE_DNS +#error \ + "webcpp::asio: reverse DNS is unavailable on WASI/browser targets; use numeric endpoints or forward name lookup" +#endif + +#endif // derived capability macros + +#if defined(WEBCPP_TARGET_WASIP2) && defined(_REENTRANT) +#error \ + "webcpp::asio: WASIp2 has no supported pthread profile in the pinned SDK; select threading=single or WASIp3 cooperative threads" +#endif + #endif // WEBCPP_ASIO_CONFIG_HPP diff --git a/include/webcpp/asio/io_context.hpp b/include/webcpp/asio/io_context.hpp index 95e18e2..a3d48fe 100644 --- a/include/webcpp/asio/io_context.hpp +++ b/include/webcpp/asio/io_context.hpp @@ -17,6 +17,10 @@ #include // lint-world: the unarmed timer that makes the reactor #include +#ifdef __EMSCRIPTEN_PTHREADS__ +#include +#include +#endif #endif #include @@ -41,6 +45,10 @@ struct io_context_options { and yields to it after every turn of max_handlers_per_turn handlers. Natively and on WASIp3 it uses Boost's run family, and its options change nothing. + In a threaded browser build each context and its JavaScript bridge stay on their + constructing thread. Other threads post through its executor; the run family + rejects a runner on another thread. Multiple simultaneous runners of one browser + context are unsupported because JavaScript values are thread-local. @see "The run family", in the guide. */ @@ -114,10 +122,10 @@ class io_context : public boost::asio::io_context { // limit, and run_one so that the whole run family is this class's; hence the exemption from // bugprone-derived-method-shadowing-base-method. // - // Each of the six is called on main's stack alone: one called while another runs, from a - // handler or from a JavaScript event while run waits, or while the bridge delivers an event, - // asserts and returns 0 having run nothing. Each admits once, first, and then calls only - // private code that admits nothing (run_until_unchecked, compose, drain) or Boost's own, + // Each of the six is called on a suspension-enabled entry stack alone: one called while another + // runs, from a handler or from a JavaScript event while run waits, or while the bridge delivers + // an event, asserts and returns 0 having run nothing. Each admits once, first, and then calls + // only private code that admits nothing (run_until_unchecked, compose, drain) or Boost's own, // never another public member, whose admission would refuse the call its caller flagged. /** @@ -227,9 +235,19 @@ class io_context : public boost::asio::io_context { Tip: not noexcept, since whether the bridge delivers is read from JavaScript. */ [[nodiscard]] bool admitted() const { +#ifdef __EMSCRIPTEN_PTHREADS__ + // The bridge owns thread-local JavaScript handles. Check affinity before reading one. + const bool owner = pthread_equal(owner_, pthread_self()) != 0; + BOOST_ASSERT_MSG(owner, + "webcpp::asio: a threaded browser io_context runs only on the thread " + "that constructed it; post through its executor from other threads"); + if (!owner) { + return false; + } +#endif const bool allowed = !running_ && !bridge_.delivering(); BOOST_ASSERT_MSG(allowed, - "webcpp::asio: the run family is called on main's stack alone, " + "webcpp::asio: the run family is called on its entry stack alone, " "never from a handler or a browser event"); return allowed; } @@ -316,6 +334,10 @@ class io_context : public boost::asio::io_context { boost::asio::steady_timer reactor_{*this}; // lint-world: never armed // The bridge whose deliveries the run family refuses to run inside, looked up once. browser::bridge& bridge_ = boost::asio::use_service(*this); +#ifdef __EMSCRIPTEN_PTHREADS__ + // The context and its JavaScript bridge stay on their creating thread. + pthread_t owner_ = pthread_self(); +#endif // Whether a call of the run family is active on this context. bool running_ = false; #endif diff --git a/include/webcpp/asio/ssl.hpp b/include/webcpp/asio/ssl.hpp index 3d2690b..4ff3629 100644 --- a/include/webcpp/asio/ssl.hpp +++ b/include/webcpp/asio/ssl.hpp @@ -9,15 +9,15 @@ #include -#ifndef WEBCPP_TARGET_EMSCRIPTEN -#ifndef WEBCPP_ASIO_HAS_OPENSSL +#if WEBCPP_ASIO_HAS_OPENSSL_BACKEND +#if !defined(WEBCPP_ASIO_HAS_OPENSSL) || !WEBCPP_ASIO_HAS_OPENSSL #error \ - "webcpp::asio: needs OpenSSL on native and WASIp3 targets, and it is not linked. In the program's Jamfile, add /webcpp/asio//openssl beside /webcpp/asio//asio, as in: exe app : app.cpp /webcpp/asio//asio /webcpp/asio//openssl ; b2 builds the pinned OpenSSL sources (git submodule update --init third_party/libs/openssl). (without b2: define WEBCPP_ASIO_HAS_OPENSSL=1 and link libssl and libcrypto)" + "webcpp::asio: needs OpenSSL on native and WASI targets, and it is not linked. In the program's Jamfile, add /webcpp/asio//openssl beside /webcpp/asio//asio, as in: exe app : app.cpp /webcpp/asio//asio /webcpp/asio//openssl ; b2 builds the pinned OpenSSL sources (git submodule update --init third_party/libs/openssl). (without b2: define WEBCPP_ASIO_HAS_OPENSSL=1 and link libssl and libcrypto)" #else #include // lint-world: native TLS with explicitly linked OpenSSL namespace webcpp::asio { -/** Boost's TLS types on native and WASIp3 targets, with OpenSSL explicitly linked. */ +/** Boost's TLS types on native and WASI targets, with OpenSSL explicitly linked. */ namespace ssl = boost::asio::ssl; } // namespace webcpp::asio #endif diff --git a/include/webcpp/asio/wasi/stdio_stream.hpp b/include/webcpp/asio/wasi/stdio_stream.hpp index 34a2a35..5bb5bb1 100644 --- a/include/webcpp/asio/wasi/stdio_stream.hpp +++ b/include/webcpp/asio/wasi/stdio_stream.hpp @@ -97,8 +97,9 @@ class stdio_stream { @param stream Channel to close. */ void beast_close_socket(stdio_stream& stream); } // namespace webcpp::asio::wasi -#elif !defined(__wasip2__) -#error "webcpp::asio::wasi::stdio_stream currently requires WASIp2" +#elif !WEBCPP_ASIO_HAS_WASI_STDIO +#error \ + "webcpp::asio::wasi::stdio_stream requires WASIp2 CLI streams; use a supplied stream or native descriptor adapter on other targets" #else #include #include diff --git a/src/cobalt_main.cpp b/src/cobalt_main.cpp index f5981d9..a1449f2 100644 --- a/src/cobalt_main.cpp +++ b/src/cobalt_main.cpp @@ -16,7 +16,7 @@ #include -#ifndef __wasip3__ +#if !defined(WEBCPP_TARGET_WASIP2) && !defined(WEBCPP_TARGET_WASIP3) #include // lint-world: preserves Cobalt's signal cancellation #include #endif @@ -30,7 +30,7 @@ namespace boost::cobalt::detail { // Match Boost's non-static promise interface even when no signal set needs cleanup. // NOLINTNEXTLINE(readability-convert-member-functions-to-static) auto main_promise::final_suspend() noexcept -> std::suspend_never { -#ifndef __wasip3__ +#if !defined(WEBCPP_TARGET_WASIP2) && !defined(WEBCPP_TARGET_WASIP3) system::error_code ec; if (signal_set != nullptr) { // Preserve Boost's nonthrowing cleanup; the return duplicates ec. @@ -50,8 +50,8 @@ int main_promise::run_main(::boost::cobalt::main mn) { mn.promise->exec.emplace(ctx.get_executor()); mn.promise->exec_ = mn.promise->exec->get_executor(); const auto coroutine = std::coroutine_handle::from_promise(*mn.promise); -#ifdef __wasip3__ - // WASIp3 has no POSIX process-signal delivery. wasi-libc's optional signal +#if defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) + // WASI has no POSIX process-signal delivery. wasi-libc's optional signal // emulation does not provide host SIGINT/SIGTERM notifications. Omit that // bridge, including its headers and final-suspend cleanup, but retain // Cobalt's internal cancellation signal. Host-requested graceful shutdown diff --git a/src/openssl_on_webassembly.hpp b/src/openssl_on_webassembly.hpp index 6928974..acd8088 100644 --- a/src/openssl_on_webassembly.hpp +++ b/src/openssl_on_webassembly.hpp @@ -7,9 +7,9 @@ #ifndef WEBCPP_ASIO_SRC_OPENSSL_ON_WEBASSEMBLY_HPP #define WEBCPP_ASIO_SRC_OPENSSL_ON_WEBASSEMBLY_HPP -// Forced into every source when a WebAssembly program names the OpenSSL target. +// Forced into every source when an Emscripten program names the OpenSSL target. #if defined(__EMSCRIPTEN__) || defined(WEBCPP_TEST_ASIO_AS_WEBASSEMBLY) #error \ - "webcpp::asio: /webcpp/asio//openssl is named in a build for WebAssembly, and OpenSSL is native only: there is a record of the TLS settings and links no library, and nothing of OpenSSL would be in the .wasm. In the program's Jamfile, name OpenSSL for native builds alone, by a condition in the project's requirements: project : requirements @native-openssl ; rule native-openssl ( properties * ) { if ! emscripten in $(properties) { return /webcpp/asio//openssl ; } } (without b2: link OpenSSL into the native program only)" + "webcpp::asio: /webcpp/asio//openssl is named in a build for Emscripten, whose browser profile does not link OpenSSL: there is a record of the TLS settings and links no library, and nothing of OpenSSL would be in the .wasm. In the program's Jamfile, name OpenSSL for native and WASI builds alone, by a condition in the project's requirements: project : requirements @native-openssl ; rule native-openssl ( properties * ) { if ! emscripten in $(properties) { return /webcpp/asio//openssl ; } } (without b2: link OpenSSL into native and WASI programs only)" #endif #endif // WEBCPP_ASIO_SRC_OPENSSL_ON_WEBASSEMBLY_HPP diff --git a/test/Jamfile b/test/Jamfile index e2b1217..c320797 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -64,8 +64,12 @@ webcpp.headers-alone asio : ../include : asio.hpp asio/basic_datagram_socket.hpp asio/io_context.hpp asio/steady_timer.hpp asio/system_timer.hpp asio/ip/*.hpp ; # The browser's headers name Emscripten's own, and compile on emscripten # alone. -webcpp.headers-alone asio : ../include : asio/browser/*.hpp asio/detail/browser_*.hpp +webcpp.headers-alone asio : ../include : asio/browser/async_await.hpp + asio/browser/async_wait_event.hpp asio/browser/bridge.hpp asio/browser/error.hpp + asio/browser/src.hpp asio/browser/transport.hpp asio/detail/browser_*.hpp asio/detail/post_completion.hpp asio/detail/flag_scope.hpp : : emscripten ; +webcpp.headers-alone asio : ../include : asio/browser/main_thread_context.hpp + : multi : emscripten ; # config.hpp follows the collection exception setting and preserves a # developer definition that disables this library alone. @@ -323,3 +327,6 @@ webcpp.compile-fail openssl_named_c_on_emscripten : openssl_named_c_test.c build-project tls ; build-project wasip2 ; +build-project capabilities ; +build-project capability_wasi ; +build-project wasip2_tls_cobalt ; diff --git a/test/browser/Jamfile b/test/browser/Jamfile index c42a1f7..a9dd129 100644 --- a/test/browser/Jamfile +++ b/test/browser/Jamfile @@ -40,3 +40,45 @@ webcpp.drive browser_loader : .//page_program : run.mjs : --mode loader ; webcpp.lane browser : loader_node browser_idle browser_render browser_loader : emscripten ; + +# The threaded profile retains the selected suspension mechanism. A pool starts +# browser workers before a handler needs them. Applications choose its size. +webcpp.drive browser_workers : worker_program.cpp + : multi 60 /webcpp/asio//asio + /webcpp//node-test -sPTHREAD_POOL_SIZE=1 + : run.mjs : --mode workers ; + +# Assertions normally diagnose invalid runner affinity. This executable observes +# the same guard's release-build result without terminating the test process. +webcpp.drive browser_worker_affinity : worker_program.cpp + : multi 60 /webcpp/asio//asio + /webcpp//node-test -sPTHREAD_POOL_SIZE=1 + BOOST_DISABLE_ASSERTS WEBCPP_TEST_WORKER_AFFINITY + : run.mjs : --mode workers ; + +webcpp.drive browser_worker_main : main_profile_program.cpp + : multi 60 /webcpp/asio//asio + /webcpp//node-test + : run.mjs : --mode workers ; + +webcpp.drive browser_worker_cobalt : ../cobalt_thread_test.cpp + : multi 60 /webcpp/asio//cobalt + /webcpp//node-test -sPTHREAD_POOL_SIZE=1 + : run.mjs : --mode workers ; + +webcpp.lane browser-workers : browser_workers browser_worker_affinity + browser_worker_main browser_worker_cobalt : emscripten ; + +# This dependency-only probe is compiled for header/tooling coverage. Run its +# JSPI and Asyncify artifacts explicitly to characterize pthread return values. +webcpp.compile browser_pthread_return_probe : probes/pthread_return.cpp + : multi : emscripten ; + +# A test-only trampoline catches the deliberate C++ exception before it crosses +# the SDK's callback boundary. Its queue and notification remain the real SDK's. +webcpp.drive browser_worker_move_failure : move_failure_program.cpp + : multi on 60 + /webcpp/asio//asio /webcpp//node-test + -Wl,--wrap=emscripten_proxy_async + : run.mjs : --mode workers ; +webcpp.lane browser-worker-exceptions : browser_worker_move_failure : emscripten ; diff --git a/test/browser/main_profile_program.cpp b/test/browser/main_profile_program.cpp new file mode 100644 index 0000000..7952876 --- /dev/null +++ b/test/browser/main_profile_program.cpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A threaded build keeps the ordinary main-thread run and DOM-event contract. +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct state { + webcpp::asio::io_context io; + boost::asio::executor_work_guard work{ + io.get_executor()}; + int completed = 0; +}; +} // namespace + +extern "C" EMSCRIPTEN_KEEPALIVE void complete_main(state* pending) { + boost::asio::post(pending->io, [pending] { + BOOST_TEST(emscripten_is_main_browser_thread()); + ++pending->completed; + pending->work.reset(); + }); +} + +int main() { + state pending; + EM_ASM({ setTimeout(function() { _complete_main($0); }, 30); }, &pending); + BOOST_TEST_EQ(pending.io.run(), 1U); // lint-run: ordinary browser main entry stack + BOOST_TEST_EQ(pending.completed, 1); + std::puts("worker profile main complete"); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/browser/move_failure_program.cpp b/test/browser/move_failure_program.cpp new file mode 100644 index 0000000..3b1ebc6 --- /dev/null +++ b/test/browser/move_failure_program.cpp @@ -0,0 +1,135 @@ +// 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) + +// Catch the deliberately thrown handler move at the caller's SDK boundary, so +// the real browser queue can finish normally and allocation release is observable. +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { +struct move_failure : std::exception { + bool* caught; + + explicit move_failure(bool* observed) : caught(observed) {} + + [[nodiscard]] const char* what() const noexcept override { return "deliberate handler move"; } +}; + +struct forwarded_call { + void (*function)(void*); + void* argument; +}; + +void catch_move_failure(void* argument) { + const std::unique_ptr pending(static_cast(argument)); + try { + pending->function(pending->argument); + } catch (const move_failure& failure) { + *failure.caught = true; + } +} + +class counting_resource final : public std::pmr::memory_resource { +public: + int live = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++live; + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* pointer, std::size_t bytes, std::size_t alignment) override { + --live; + std::pmr::new_delete_resource()->deallocate(pointer, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +struct throwing_move { + bool* armed; + bool* caught; + int* calls; + + throwing_move(bool& enabled, bool& observed, int& invoked) + : armed(&enabled), caught(&observed), calls(&invoked) {} + + // Deliberately exercise the executor's exceptional move cleanup. + // NOLINTNEXTLINE(bugprone-exception-escape,performance-noexcept-move-constructor) + throwing_move(throwing_move&& other) + : armed(other.armed), caught(other.caught), calls(other.calls) { + if (*armed) { + throw move_failure{caught}; + } + } + + throwing_move(const throwing_move&) = delete; + throwing_move& operator=(const throwing_move&) = delete; + throwing_move& operator=(throwing_move&&) = delete; + ~throwing_move() = default; + + void operator()() const { ++*calls; } +}; + +EM_ASYNC_JS(void, settle_move_failure, (), + { await new Promise(function(resolve) { setTimeout(resolve, 30); }); }); +} // namespace + +// These are the linker's required ABI spellings, used only by this fixture. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" bool __real_emscripten_proxy_async(em_proxying_queue* queue, pthread_t thread, + void (*function)(void*), void* argument); + +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" bool __wrap_emscripten_proxy_async(em_proxying_queue* queue, pthread_t thread, + void (*function)(void*), void* argument) { + auto forwarded = std::make_unique(function, argument); + if (!__real_emscripten_proxy_async(queue, thread, catch_move_failure, forwarded.get())) { + return false; + } + // The queued SDK callback now owns this trampoline. + (void)forwarded.release(); // NOLINT(bugprone-unused-return-value) + return true; +} + +int main() { + counting_resource allocations; + bool armed = false; + bool caught = false; + int calls = 0; + { + webcpp::asio::browser::main_thread_context context; + boost::asio::post( + context.get_executor(), + boost::asio::bind_allocator(std::pmr::polymorphic_allocator(&allocations), + throwing_move(armed, caught, calls))); + boost::asio::post( + context.get_executor(), + boost::asio::bind_allocator(std::pmr::polymorphic_allocator(&allocations), + [&] { ++calls; })); + armed = true; + settle_move_failure(); + BOOST_TEST(caught); + BOOST_TEST_EQ(calls, 0); + BOOST_TEST_EQ(allocations.live, 0); + } + BOOST_TEST_EQ(allocations.live, 0); + std::puts("worker throwing move cleanup complete"); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/browser/probes/pthread_return.cpp b/test/browser/probes/pthread_return.cpp new file mode 100644 index 0000000..ade2d12 --- /dev/null +++ b/test/browser/probes/pthread_return.cpp @@ -0,0 +1,63 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A dependency-only witness: a suspended pthread entry must return its own value. +#include +#include +#include +#include + +// clang-format off +EM_ASYNC_JS(int, suspend_worker, (), { + await new Promise(resolve => setTimeout(resolve, 20)); + return 42; +}); + +// clang-format on + +extern "C" EMSCRIPTEN_KEEPALIVE int try_join_worker(pthread_t thread, void** value) { + return pthread_tryjoin_np(thread, value); +} + +// clang-format off +EM_ASYNC_JS(int, join_worker, (pthread_t thread, void** value, int busy), { + const deadline = performance.now() + 5000; + let status; + while ((status = _try_join_worker(thread, value)) === busy) { + if (performance.now() > deadline) throw new Error('worker did not exit'); + await new Promise(resolve => setTimeout(resolve, 5)); + } + return status; +}); + +// clang-format on + +void* worker(void* /*unused*/) { + const int result = suspend_worker(); + std::printf("worker suspended result %d\n", result); + return reinterpret_cast(result); +} + +int main() { + pthread_t thread{}; + const int created = pthread_create(&thread, nullptr, worker, nullptr); + if (created != 0) { + return created; + } + void* value = nullptr; + const int joined = join_worker(thread, &value, EBUSY); + std::printf("join result %d value %ld\n", joined, reinterpret_cast(value)); + const int status = joined || reinterpret_cast(value) != 42; + EM_ASM( + { + if (Module['webcppTestFinished']) { + Module['webcppTestFinished']($0); + } + }, + status); + std::puts("worker runtime complete"); + return status; +} diff --git a/test/browser/run.mjs b/test/browser/run.mjs index b2638bd..bbba7f2 100644 --- a/test/browser/run.mjs +++ b/test/browser/run.mjs @@ -5,7 +5,7 @@ // https://www.boost.org/LICENSE_1_0.txt) // The real browser checks: idle waits, animation opportunities and variant loading. -// node run.mjs --mode +// node run.mjs --mode // CHROME names the browser; on macOS the newest cached Playwright headless shell is used. // Each invocation owns its loopback server, Chrome process and temporary profile. import assert from 'node:assert/strict' @@ -19,10 +19,11 @@ import {setTimeout as delay} from 'node:timers/promises' import {fileURLToPath} from 'node:url' const args = process.argv.slice(2) -assert.equal(args.length, 3, 'usage: run.mjs --mode ') +assert.equal(args.length, 3, 'usage: run.mjs --mode ') assert.equal(args[0], '--mode') const mode = args[1] -assert.ok(['idle', 'render', 'loader'].includes(mode), `unknown mode ${mode}`) +assert.ok(['idle', 'render', 'loader', 'workers'].includes(mode), `unknown mode ${mode}`) +const workerVariant = args[2].includes('asyncify') ? 'asyncify' : 'jspi' const here = dirname(fileURLToPath(import.meta.url)) const build = dirname(resolve(args[2])) const findChrome = () => { @@ -76,7 +77,9 @@ const startServer = async () => { return } const content = readFileSync(file) - response.writeHead(200, {'Content-Type': types[extname(file)] ?? 'application/octet-stream'}) + response.writeHead(200, {'Content-Type': types[extname(file)] ?? 'application/octet-stream', + 'Cross-Origin-Opener-Policy': 'same-origin', + 'Cross-Origin-Embedder-Policy': 'require-corp'}) .end(content) } catch { response.writeHead(404).end() @@ -215,10 +218,12 @@ const openPage = async (devtools, base, program, variant) => { await send('Page.addScriptToEvaluateOnNewDocument', {source: 'delete WebAssembly.Suspending'}) } const observer = mode === 'idle' ? observeIdle : observeTurns - if (mode !== 'loader') { + if (mode !== 'loader' && mode !== 'workers') { await send('Page.addScriptToEvaluateOnNewDocument', {source: `(${observer.toString()})()`}) } - await send('Page.navigate', {url: `${base}/page.html?manifest=/build/${program}.variants.json`}) + await send('Page.navigate', {url: mode === 'workers' + ? `${base}/worker_page.html?script=/build/${program}&variant=${variant}` + : `${base}/page.html?manifest=/build/${program}.variants.json`}) const snapshot = async () => { const result = await send('Runtime.evaluate', { expression: '({report: window.report, timers: window.timers, turns: window.turns})', @@ -278,13 +283,26 @@ const renderStats = ({report, turns}, limited) => { try { const base = await startServer() const devtools = await startChrome() - for (const variant of ['jspi', 'asyncify']) { + for (const variant of mode === 'workers' ? [workerVariant] : ['jspi', 'asyncify']) { const programs = mode === 'render' ? ['render_program', 'render_unlimited_program'] - : [mode === 'idle' ? 'idle_program' : 'page_program'] + : [mode === 'workers' ? resolve(args[2]).split(sep).at(-1) + : mode === 'idle' ? 'idle_program' : 'page_program'] for (const program of programs) { const page = await openPage(devtools, base, program, variant) try { - if (mode === 'loader') { + if (mode === 'workers') { + const {report} = await page.waitFor(/^(worker .* complete|cobalt: thread coroutine completed and joined)$/) + assert.equal(report.status, 0, JSON.stringify(report)) + assert.equal(report.isolated, true) + if (!program.includes('cobalt') && !program.includes('worker_return') && + !program.includes('move_failure')) { + const worker = !program.includes('_main-') + assert.ok(report.polls.some(poll => poll.worker === worker && poll.timeout > 0), + `missing ${worker ? 'original worker proxy' : 'main adapter'} wait: ${JSON.stringify(report.polls)}`) + } + console.log(`workers ${variant}: ${program} completed with status 0`) + for (const warning of report.warnings) console.log(`SDK notice: ${warning}`) + } else if (mode === 'loader') { const {report} = await page.waitFor(/^ran 3 handlers$/) assert.deepEqual(report.lines.map(entry => entry.line), ['ran 3 handlers']) console.log(`loader ${variant}: ran 3 handlers`) diff --git a/test/browser/worker_page.html b/test/browser/worker_page.html new file mode 100644 index 0000000..7f50eaf --- /dev/null +++ b/test/browser/worker_page.html @@ -0,0 +1,47 @@ + + + +asio browser workers + + diff --git a/test/browser/worker_program.cpp b/test/browser/worker_program.cpp new file mode 100644 index 0000000..ab64868 --- /dev/null +++ b/test/browser/worker_program.cpp @@ -0,0 +1,214 @@ +// 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 worker waits in the real reactor. Timer completion crosses to the browser main +// executor, touches the DOM and posts back to wake the original worker context. +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { +struct allocation_counts { + int allocated = 0; + int live = 0; +}; + +template +struct tracking_allocator { + using value_type = T; + allocation_counts* counts; + + explicit tracking_allocator(allocation_counts& value) : counts(&value) {} + + template + explicit tracking_allocator(const tracking_allocator& other) : counts(other.counts) {} + + T* allocate(std::size_t count) { + ++counts->allocated; + ++counts->live; + return std::allocator{}.allocate(count); + } + + void deallocate(T* value, std::size_t count) { + --counts->live; + std::allocator{}.deallocate(value, count); + } + + template + bool operator==(const tracking_allocator& other) const { + return counts == other.counts; + } +}; + +struct results { + webcpp::asio::browser::main_thread_context main; + std::atomic done{0}; + std::atomic errors{0}; + int callbacks = 0; + int cancellations = 0; +}; + +void* run_worker(void* pointer) { + auto& result = *static_cast(pointer); + webcpp::asio::io_context io; + auto work = boost::asio::make_work_guard(io); + int returned = 0; + const auto return_to_worker = [&] { + boost::asio::post(io, [&] { + if (emscripten_is_main_browser_thread()) { + ++result.errors; + } + if (++returned == 2) { + work.reset(); + } + }); + }; + boost::asio::cancellation_signal signal; + boost::asio::steady_timer cancelled(io, std::chrono::hours(1)); + cancelled.async_wait(boost::asio::bind_cancellation_slot( + signal.slot(), boost::asio::bind_executor(result.main.get_executor(), [&](auto ec) { + if (ec != boost::asio::error::operation_aborted || + !emscripten_is_main_browser_thread()) { + ++result.errors; + } + ++result.cancellations; + return_to_worker(); + }))); + signal.emit(boost::asio::cancellation_type::all); + boost::asio::steady_timer timer(io, std::chrono::milliseconds(30)); + timer.async_wait(boost::asio::bind_executor(result.main.get_executor(), [&](auto ec) { + if (ec || !emscripten_is_main_browser_thread()) { + ++result.errors; + } + MAIN_THREAD_EM_ASM({ document.body.dataset.workerHandoff = 'complete'; }); + ++result.callbacks; +#ifdef WEBCPP_TEST_WORKER_AFFINITY + // An invalid main-thread runner is rejected before reading the worker's JS handles. + if (io.run() != 0) { + ++result.errors; + } // lint-run: negative affinity witness +#endif + return_to_worker(); + })); + if (io.run() != 4) { // lint-run: worker-owned context, real timer and wakeup + ++result.errors; + } + result.done.store(1); + return nullptr; +} + +EM_ASYNC_JS(void, wait_worker, (const void* done), { + const deadline = performance.now() + 5000; + while (!Atomics.load(HEAP32, done >>> 2)) { + if (performance.now() > deadline) + throw new Error('worker context did not finish'); + await new Promise(function(resolve) { setTimeout(resolve, 5); }); + } +}); + +EM_ASYNC_JS(void, settle, (), + { await new Promise(function(resolve) { setTimeout(resolve, 30); }); }); +} // namespace + +int main() { + results result; + pthread_t thread{}; + BOOST_TEST_EQ(pthread_create(&thread, nullptr, run_worker, &result), 0); + wait_worker(&result.done); + int joined = EBUSY; + for (int attempt = 0; attempt < 100 && joined == EBUSY; ++attempt) { + joined = pthread_tryjoin_np(thread, nullptr); + if (joined == EBUSY) { + settle(); + } + } + BOOST_TEST_EQ(joined, 0); + BOOST_TEST_EQ(result.errors.load(), 0); + BOOST_TEST_EQ(result.cancellations, 1); + BOOST_TEST_EQ(result.callbacks, 1); + BOOST_TEST_EQ( + EM_ASM_INT({ return Object.is(document.body.dataset.workerHandoff, 'complete'); }), 1); + + allocation_counts allocations; + int allocated_calls = 0; + boost::asio::post(result.main.get_executor(), + boost::asio::bind_allocator(tracking_allocator(allocations), [&] { + BOOST_TEST_EQ(allocations.live, 0); + ++allocated_calls; + })); + BOOST_TEST_EQ(allocated_calls, 0); + BOOST_TEST(allocations.allocated > 0); + settle(); + BOOST_TEST_EQ(allocated_calls, 1); + + int discarded = 0; + std::weak_ptr lifetime; + { + webcpp::asio::browser::main_thread_context shutdown; + const auto kept = std::make_shared(42); + lifetime = kept; + boost::asio::post(shutdown.get_executor(), + boost::asio::bind_allocator(tracking_allocator(allocations), + [kept, &discarded] { ++discarded; })); + } + BOOST_TEST(lifetime.expired()); + BOOST_TEST_EQ(allocations.live, 0); + settle(); + BOOST_TEST_EQ(discarded, 0); + allocation_counts context_allocations; + { + const webcpp::asio::browser::main_thread_context allocated_context( + std::allocator_arg, tracking_allocator(context_allocations)); + BOOST_TEST(context_allocations.allocated > 0); + } + BOOST_TEST_EQ(context_allocations.live, 0); + allocation_counts reentrant_context_allocations; + allocation_counts reentrant_handler_allocations; + int reentrant_calls = 0; + std::weak_ptr discarded_lifetime; + auto reentrant = std::make_unique( + std::allocator_arg, tracking_allocator(reentrant_context_allocations)); + boost::asio::post( + reentrant->get_executor(), + boost::asio::bind_allocator(tracking_allocator(reentrant_handler_allocations), [&] { + ++reentrant_calls; + reentrant.reset(); + BOOST_TEST(discarded_lifetime.expired()); + BOOST_TEST_EQ(reentrant_handler_allocations.live, 0); + })); + { + const auto held = std::make_shared(42); + discarded_lifetime = held; + boost::asio::post( + reentrant->get_executor(), + boost::asio::bind_allocator(tracking_allocator(reentrant_handler_allocations), + [held, &reentrant_calls] { ++reentrant_calls; })); + } + settle(); + BOOST_TEST_EQ(reentrant_calls, 1); + BOOST_TEST_EQ(reentrant_context_allocations.live, 0); + BOOST_TEST_EQ(reentrant_handler_allocations.live, 0); + std::printf("worker handoff and shutdown complete\n"); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capabilities/Jamfile b/test/capabilities/Jamfile new file mode 100644 index 0000000..d778423 --- /dev/null +++ b/test/capabilities/Jamfile @@ -0,0 +1,49 @@ +# 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) + +project : requirements /webcpp/asio//asio ; +import webcpp ; +webcpp.targets native wasip2 wasip3 emscripten ; + +webcpp.compile capabilities : capabilities_test.cpp ; +webcpp.compile config : ../config_test.cpp ; +webcpp.compile-fail forged_capability : requirements_test.cpp + : WEBCPP_ASIO_HAS_SOCKET_BACKEND=1 ; +webcpp.compile-diagnostic forged_diagnostic : diagnostics_test.cpp + : WEBCPP_TEST_FORGED WEBCPP_ASIO_HAS_SOCKET_BACKEND=1 ; + +webcpp.compile-diagnostic missing_tls : diagnostics_test.cpp + : WEBCPP_TEST_REQUIRE_TLS WEBCPP_ASIO_REQUIRE_OPENSSL=1 + : native wasip2 wasip3 ; +webcpp.compile-diagnostic disabled_tls : diagnostics_test.cpp + : WEBCPP_TEST_DISABLED_TLS WEBCPP_ASIO_HAS_OPENSSL=0 + : native wasip2 wasip3 ; +webcpp.compile-diagnostic browser_header : diagnostics_test.cpp + : WEBCPP_TEST_BROWSER_HEADER : native wasip2 wasip3 ; +webcpp.compile-diagnostic worker_header : diagnostics_test.cpp + : single WEBCPP_TEST_WORKER_HEADER ; +webcpp.compile-diagnostic stdio_header : diagnostics_test.cpp + : WEBCPP_TEST_STDIO_HEADER : native wasip3 ; + +webcpp.compile-fail require_THREADS : requirements_test.cpp + : single WEBCPP_ASIO_REQUIRE_THREADS=1 : wasip2 wasip3 ; +for local requirement in LOCAL_SOCKETS SIGNALS SERIAL_PORT REVERSE_DNS +{ + webcpp.compile-fail require_$(requirement) : requirements_test.cpp + : WEBCPP_ASIO_REQUIRE_$(requirement)=1 + : wasip2 wasip3 ; +} +webcpp.compile require_socket : requirements_test.cpp + : WEBCPP_ASIO_REQUIRE_SOCKET_BACKEND=1 : native wasip2 wasip3 ; +webcpp.compile-fail browser_requires_socket : requirements_test.cpp + : WEBCPP_ASIO_REQUIRE_SOCKET_BACKEND=1 : emscripten ; +webcpp.compile-fail browser_requires_tls : requirements_test.cpp + : WEBCPP_ASIO_REQUIRE_OPENSSL=1 : emscripten ; +webcpp.compile-fail browser_requires_stdio : diagnostics_test.cpp + : WEBCPP_TEST_STDIO_HEADER : emscripten ; + +# Includes alone must not ban a browser transport chosen at runtime. +webcpp.compile portable_browser : portable_browser_test.cpp : : emscripten ; diff --git a/test/capabilities/capabilities_test.cpp b/test/capabilities/capabilities_test.cpp new file mode 100644 index 0000000..1a3ba25 --- /dev/null +++ b/test/capabilities/capabilities_test.cpp @@ -0,0 +1,44 @@ +// 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 + +// The same public consumer exposes target capabilities before any feature header. +#ifdef WEBCPP_TARGET_EMSCRIPTEN +static_assert(WEBCPP_ASIO_HAS_BROWSER_BRIDGE == 1); +static_assert(WEBCPP_ASIO_HAS_SOCKET_BACKEND == 0); +static_assert(WEBCPP_ASIO_HAS_OPENSSL_BACKEND == 0); +static_assert(WEBCPP_ASIO_HAS_HOST_DNS == 0); +#else +static_assert(WEBCPP_ASIO_HAS_BROWSER_BRIDGE == 0); +static_assert(WEBCPP_ASIO_HAS_SOCKET_BACKEND == 1); +static_assert(WEBCPP_ASIO_HAS_OPENSSL_BACKEND == 1); +static_assert(WEBCPP_ASIO_HAS_HOST_DNS == 1); +#endif + +#ifdef WEBCPP_TARGET_WASIP2 +static_assert(WEBCPP_ASIO_HAS_WASI_STDIO == 1); +#else +static_assert(WEBCPP_ASIO_HAS_WASI_STDIO == 0); +#endif + +#ifndef WEBCPP_TARGET_NATIVE +static_assert(WEBCPP_ASIO_HAS_REVERSE_DNS == 0); +static_assert(WEBCPP_ASIO_HAS_LOCAL_SOCKETS == 0); +static_assert(WEBCPP_ASIO_HAS_SIGNALS == 0); +static_assert(WEBCPP_ASIO_HAS_SERIAL_PORT == 0); +#endif + +#ifdef BOOST_ASIO_HAS_THREADS +static_assert(WEBCPP_ASIO_HAS_THREADS == 1); +#else +static_assert(WEBCPP_ASIO_HAS_THREADS == 0); +#endif + +#ifdef __EMSCRIPTEN_PTHREADS__ +static_assert(WEBCPP_ASIO_HAS_BROWSER_WORKERS == 1); +#else +static_assert(WEBCPP_ASIO_HAS_BROWSER_WORKERS == 0); +#endif diff --git a/test/capabilities/diagnostics_test.cpp b/test/capabilities/diagnostics_test.cpp new file mode 100644 index 0000000..8a5e681 --- /dev/null +++ b/test/capabilities/diagnostics_test.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#if defined(WEBCPP_TEST_FORGED) +// expected-error@webcpp/asio/config.hpp:* {{capability macros are derived by config.hpp}} +#include +#elif defined(WEBCPP_TEST_REQUIRE_TLS) +// expected-error@webcpp/asio/config.hpp:* {{requires /webcpp/asio//openssl or /webcpp/asio//tls}} +#include +#elif defined(WEBCPP_TEST_DISABLED_TLS) +// expected-error@webcpp/asio/ssl.hpp:* {{needs OpenSSL on native and WASI targets, and it is not +// linked}} +#include +#elif defined(WEBCPP_TEST_BROWSER_HEADER) +// expected-error@webcpp/asio/browser/bridge.hpp:* {{requires the Emscripten browser bridge}} +#include +#elif defined(WEBCPP_TEST_WORKER_HEADER) +// expected-error@webcpp/asio/browser/main_thread_context.hpp:* {{requires Emscripten pthreads}} +#include +#elif defined(WEBCPP_TEST_STDIO_HEADER) +// expected-error@webcpp/asio/wasi/stdio_stream.hpp:* {{requires WASIp2 CLI streams}} +#include +#endif diff --git a/test/capabilities/portable_browser_test.cpp b/test/capabilities/portable_browser_test.cpp new file mode 100644 index 0000000..5b3bf6d --- /dev/null +++ b/test/capabilities/portable_browser_test.cpp @@ -0,0 +1,16 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#define WEBCPP_ASIO_REQUIRE_SOCKET_BACKEND 0 +#define WEBCPP_ASIO_REQUIRE_OPENSSL 0 +#include +#include +#include +#include + +// These settings are also consumed by browser-native WSS or custom transports. +static_assert(requires(webcpp::asio::ssl::context& context, boost::system::error_code& error) { + context.set_verify_mode(webcpp::asio::ssl::verify_peer, error); +}); diff --git a/test/capabilities/requirements_test.cpp b/test/capabilities/requirements_test.cpp new file mode 100644 index 0000000..046e6fd --- /dev/null +++ b/test/capabilities/requirements_test.cpp @@ -0,0 +1,6 @@ +// 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 diff --git a/test/capability_wasi/Jamfile b/test/capability_wasi/Jamfile new file mode 100644 index 0000000..9deb2e0 --- /dev/null +++ b/test/capability_wasi/Jamfile @@ -0,0 +1,24 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) +project : requirements /webcpp/asio//asio ; +import webcpp ; +webcpp.targets native wasip2 wasip3 ; +webcpp.run datagrams : datagrams_test.cpp : : native wasip2 wasip3 ; +webcpp.run resolver : ../wasip2/resolver_test.cpp : : wasip3 ; +webcpp.run resolver_progress : resolver_progress_test.cpp + : -Wl,--wrap=webcpp_asio_wasip3_lookup + -Wl,--wrap=wasip3_subtask_drop : wasip3 ; +webcpp.run send_retry : send_retry_test.cpp : -Wl,--wrap=send : wasip2 wasip3 ; +webcpp.run resolver_empty_list : resolver_empty_result_test.cpp + : -Wl,--wrap=webcpp_asio_wasip3_lookup : wasip3 ; +webcpp.run resolver_empty_message : resolver_empty_result_test.cpp + : WEBCPP_TEST_EMPTY_ERROR_MESSAGE + -Wl,--wrap=webcpp_asio_wasip3_lookup : wasip3 ; +webcpp.run resolver_runners : resolver_runners_test.cpp + : multi off + -Wl,--wrap=webcpp_asio_wasip3_lookup + -Wl,--wrap=wasip3_waitable_join : wasip3 ; +webcpp.lane wasi-dns-threads : resolver_runners : wasip3 ; diff --git a/test/capability_wasi/datagrams_test.cpp b/test/capability_wasi/datagrams_test.cpp new file mode 100644 index 0000000..71468a3 --- /dev/null +++ b/test/capability_wasi/datagrams_test.cpp @@ -0,0 +1,288 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../wasip2/counting_allocator.hpp" + +namespace { +namespace asio = boost::asio; +using udp = webcpp::asio::ip::udp; +#if defined(__wasip2__) || defined(__wasip3__) +constexpr std::size_t buffer_count = 80; +#else +constexpr std::size_t buffer_count = 16; +#endif + +void connected_send() { + webcpp::asio::io_context context; + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + udp::socket sender(context, udp::v4()); + boost::system::error_code connection_error; + BOOST_TEST_EQ(sender.connect(receiver.local_endpoint(), connection_error), + boost::system::error_code{}); + BOOST_TEST_EQ(connection_error, boost::system::error_code{}); + if (connection_error) { + return; + } + std::array pieces{}; + pieces.fill(asio::buffer("x", 1)); + boost::system::error_code error; + BOOST_TEST_EQ(sender.send(pieces, 0, error), buffer_count); + BOOST_TEST_EQ(error, boost::system::error_code{}); + if (!error) { + std::array received{}; + BOOST_TEST_EQ(receiver.receive(asio::buffer(received)), buffer_count); + BOOST_TEST(std::string(received.data(), buffer_count) == std::string(buffer_count, 'x')); + } + counts allocations; + int completed = 0; + sender.async_send(pieces, + asio::bind_allocator(allocator(allocations), + [&](boost::system::error_code ec, std::size_t size) { + BOOST_TEST_EQ(allocations.live, 0U); + BOOST_TEST_EQ(ec, boost::system::error_code{}); + BOOST_TEST_EQ(size, buffer_count); + error = ec; + ++completed; + })); + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: finish the public connected datagram operation + BOOST_TEST_EQ(completed, 1); + if (!error) { + std::array received{}; + BOOST_TEST_EQ(receiver.receive(asio::buffer(received)), buffer_count); + BOOST_TEST(std::string(received.data(), buffer_count) == std::string(buffer_count, 'x')); + } +} + +void scatter_receive(bool connected, bool asynchronous) { + counts context_allocations; + webcpp::asio::io_context context(std::allocator_arg, allocator(context_allocations)); + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + udp::socket sender(context, {asio::ip::address_v4::loopback(), 0}); + if (connected) { + boost::system::error_code connection_error; + BOOST_TEST_EQ(receiver.connect(sender.local_endpoint(), connection_error), + boost::system::error_code{}); + BOOST_TEST_EQ(connection_error, boost::system::error_code{}); + if (connection_error) { + return; + } + } + std::array bytes{}; + std::array pieces{}; + for (std::size_t index = 0; index != pieces.size(); ++index) { + pieces[index] = asio::buffer(&bytes[index], 1); + } + const std::string payload(100, 's'); + sender.send_to(asio::buffer(payload), receiver.local_endpoint()); + udp::endpoint peer; + boost::system::error_code error; + if (asynchronous) { + counts allocations; + int completed = 0; + auto handler = asio::bind_allocator(allocator(allocations), + [&](boost::system::error_code ec, std::size_t size) { + BOOST_TEST_EQ(allocations.live, 0U); + BOOST_TEST_EQ(ec, boost::system::error_code{}); + BOOST_TEST_EQ(size, buffer_count); + error = ec; + ++completed; + }); + if (connected) { + receiver.async_receive(pieces, handler); + } else { + receiver.async_receive_from(pieces, peer, handler); + } + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: finish the public scattered datagram receive + BOOST_TEST_EQ(completed, 1); + } else { + [[maybe_unused]] const auto before = context_allocations.allocations; + auto const size = connected ? receiver.receive(pieces, 0, error) + : receiver.receive_from(pieces, peer, 0, error); + BOOST_TEST_EQ(error, boost::system::error_code{}); + BOOST_TEST_EQ(size, buffer_count); +#if defined(__wasip2__) || defined(__wasip3__) + BOOST_TEST_EQ(context_allocations.allocations, before + 1); +#endif + } + if (!error) { + BOOST_TEST(std::string(bytes.data(), bytes.size()) == std::string(buffer_count, 's')); + if (!connected) { + BOOST_TEST(peer == sender.local_endpoint()); + } + receiver.non_blocking(true); + BOOST_TEST_EQ(receiver.receive(asio::buffer(bytes), 0, error), 0U); + BOOST_TEST(error == asio::error::would_block || error == asio::error::try_again); + } +} + +void cancel_scatter() { + webcpp::asio::io_context context; + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + std::array bytes{}; + const std::array pieces{ + asio::buffer(bytes.data(), 1), + asio::buffer(&bytes[1], 1), + }; + asio::cancellation_signal cancellation; + counts allocations; + int completed = 0; + receiver.async_receive( + pieces, asio::bind_allocator(allocator(allocations), + asio::bind_cancellation_slot( + cancellation.slot(), + [&](boost::system::error_code error, std::size_t size) { + BOOST_TEST_EQ(allocations.live, 0U); + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST_EQ(size, 0U); + ++completed; + }))); + cancellation.emit(asio::cancellation_type::all); + context.run(); // lint-run: deliver cancellation of the pending scattered receive + BOOST_TEST_EQ(completed, 1); +} + +void datagram_boundaries() { + counts context_counts; + webcpp::asio::io_context context(std::allocator_arg, allocator(context_counts)); + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + udp::socket sender(context, udp::v4()); + sender.connect(receiver.local_endpoint()); + const std::array empty{}; + std::array received{}; + boost::system::error_code error; + BOOST_TEST_EQ(sender.send(empty, 0, error), 0U); + BOOST_TEST(!error); + udp::endpoint peer; +#if defined(__wasip2__) || defined(__wasip3__) + std::array const no_capacity{}; + BOOST_TEST_EQ(receiver.receive_from(no_capacity, peer, 0, error), 0U); +#else + // macOS needs positive capacity to consume an empty datagram. + BOOST_TEST_EQ(receiver.receive_from(asio::buffer(received), peer, 0, error), 0U); +#endif + BOOST_TEST(!error); + sender.send(asio::buffer("discard", 7)); +#if defined(__wasip2__) || defined(__wasip3__) + BOOST_TEST_EQ(receiver.receive_from(no_capacity, peer, 0, error), 0U); +#else + BOOST_TEST_EQ(receiver.receive_from(asio::buffer(received), peer, 0, error), 7U); +#endif + BOOST_TEST(!error); + sender.send(asio::buffer("next", 4)); + BOOST_TEST_EQ(receiver.receive_from(asio::buffer(received), peer), 4U); + BOOST_TEST(std::string(received.data(), 4) == "next"); + + const std::string too_large(65536, 'x'); + const std::array oversized{ + asio::buffer(too_large.data(), 65535), + asio::buffer(too_large.data() + 65535, 1), + }; + const auto before = context_counts.allocations; + BOOST_TEST_EQ(sender.send(oversized, 0, error), 0U); + BOOST_TEST_EQ(error, asio::error::message_size); + BOOST_TEST_EQ(context_counts.allocations, before); + int rejected = 0; + sender.async_send(oversized, [&](boost::system::error_code ec, std::size_t size) { + BOOST_TEST_EQ(ec, asio::error::message_size); + BOOST_TEST_EQ(size, 0U); + ++rejected; + }); + BOOST_TEST_EQ(rejected, 0); + context.run(); // lint-run: oversized connected sends fail through deferred completion + BOOST_TEST_EQ(rejected, 1); + receiver.non_blocking(true); + BOOST_TEST_EQ(receiver.receive_from(asio::buffer(received), peer, 0, error), 0U); + BOOST_TEST(error == asio::error::would_block || error == asio::error::try_again); +} + +[[maybe_unused]] void asynchronous_empty_buffers() { + webcpp::asio::io_context context; + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + udp::socket sender(context, {asio::ip::address_v4::loopback(), 0}); + sender.connect(receiver.local_endpoint()); + receiver.connect(sender.local_endpoint()); + const std::array empty{}; + std::array const no_capacity{}; + int completed = 0; + sender.async_send(empty, [&](boost::system::error_code error, std::size_t size) { + BOOST_TEST(!error); + BOOST_TEST_EQ(size, 0U); + ++completed; + }); + receiver.async_receive(no_capacity, [&](boost::system::error_code error, std::size_t size) { + BOOST_TEST(!error); + BOOST_TEST_EQ(size, 0U); + ++completed; + }); + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: empty buffers still send and consume a complete datagram + BOOST_TEST_EQ(completed, 2); + context.restart(); + sender.send(asio::buffer("discard", 7)); + udp::endpoint peer; + receiver.async_receive_from(no_capacity, peer, + [&](boost::system::error_code error, std::size_t size) { + BOOST_TEST(!error); + BOOST_TEST_EQ(size, 0U); + BOOST_TEST(peer == sender.local_endpoint()); + ++completed; + }); + context.run(); // lint-run: a zero-capacity scattered receive discards the datagram remainder + BOOST_TEST_EQ(completed, 3); + sender.send(asio::buffer("next", 4)); + std::array bytes{}; + BOOST_TEST_EQ(receiver.receive(asio::buffer(bytes)), 4U); + BOOST_TEST(std::string(bytes.data(), 4) == "next"); +} + +void abandoned_receive() { + counts allocations; + bool completed = false; + std::array bytes{}; + const std::array pieces{ + asio::buffer(bytes.data(), 1), + asio::buffer(&bytes[1], 1), + }; + { + webcpp::asio::io_context context; + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + receiver.async_receive( + pieces, asio::bind_allocator( + allocator(allocations), + [&](boost::system::error_code, std::size_t) { completed = true; })); + BOOST_TEST(allocations.live != 0U); + } + BOOST_TEST(!completed); + BOOST_TEST_EQ(allocations.live, 0U); +} + +} // namespace + +int main() { + connected_send(); + for (bool const connected : {false, true}) { + for (bool const asynchronous : {false, true}) { + scatter_receive(connected, asynchronous); + } + } + cancel_scatter(); + datagram_boundaries(); + abandoned_receive(); +#if defined(__wasip2__) || defined(__wasip3__) + asynchronous_empty_buffers(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capability_wasi/resolver_empty_result_test.cpp b/test/capability_wasi/resolver_empty_result_test.cpp new file mode 100644 index 0000000..c5932d8 --- /dev/null +++ b/test/capability_wasi/resolver_empty_result_test.cpp @@ -0,0 +1,65 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include +#include +#include +#include +#include +#include "../wasip2/counting_allocator.hpp" + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" std::uint32_t __wrap_webcpp_asio_wasip3_lookup([[maybe_unused]] const char* name, + [[maybe_unused]] std::size_t size, + void* result) { + auto* bytes = static_cast(result); +#ifdef WEBCPP_TEST_EMPTY_ERROR_MESSAGE + bytes[0] = 1; + bytes[sizeof(void*)] = IP_NAME_LOOKUP_ERROR_CODE_OTHER; + bytes[2 * sizeof(void*)] = 1; + const wasip3_string_t message{.ptr = reinterpret_cast(1), .len = 0}; + std::memcpy(bytes + (3 * sizeof(void*)), &message, sizeof(message)); +#else + bytes[0] = 0; + const ip_name_lookup_list_ip_address_t addresses{ + // Empty canonical allocations encode their alignment in the pointer. + // NOLINTNEXTLINE(performance-no-int-to-ptr) + .ptr = reinterpret_cast(alignof(ip_name_lookup_ip_address_t)), + .len = 0, + }; + std::memcpy(bytes + sizeof(void*), &addresses, sizeof(addresses)); +#endif + return WASIP3_SUBTASK_RETURNED; +} + +int main() { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + webcpp::asio::io_context context; + tcp::resolver resolver(context); + counts allocations; + int completed = 0; + resolver.async_resolve("empty.test.invalid", "443", + asio::bind_allocator(allocator(allocations), + [&](boost::system::error_code error, + const tcp::resolver::results_type& results) { +#ifdef WEBCPP_TEST_EMPTY_ERROR_MESSAGE + BOOST_TEST_EQ(error, asio::error::no_recovery); +#else + BOOST_TEST_EQ(error, asio::error::host_not_found); +#endif + BOOST_TEST(results.empty()); + BOOST_TEST_EQ(allocations.live, 0U); + ++completed; + })); + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: canonical zero-byte allocations are sentinels, not freeable storage + BOOST_TEST_EQ(completed, 1); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capability_wasi/resolver_progress_test.cpp b/test/capability_wasi/resolver_progress_test.cpp new file mode 100644 index 0000000..5693d3e --- /dev/null +++ b/test/capability_wasi/resolver_progress_test.cpp @@ -0,0 +1,173 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../wasip2/counting_allocator.hpp" + +namespace { +struct test_state { + int lookups = 0; + wasip3_subtask_t pending_handle = 0; + int pending_releases = 0; +}; + +test_state& state() { + static test_state value; + return value; +} +} // namespace + +// Delay the native host boundary deterministically. This retains real component +// subtask/waitable/timer scheduling while avoiding reliance on DNS latency. +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" std::uint32_t __wrap_webcpp_asio_wasip3_lookup(const char* name, + [[maybe_unused]] std::size_t size, + void* result) { + ++state().lookups; + if (std::strncmp(name, "cancel.", 7) == 0) { + auto const status = monotonic_clock_wait_for(1000000000); + state().pending_handle = WASIP3_SUBTASK_HANDLE(status); + return status; + } + auto* address = static_cast( + std::calloc(1, sizeof(ip_name_lookup_ip_address_t))); + address->tag = SOCKETS_IP_ADDRESS_IPV4; + address->val.ipv4 = {.f0 = 127, .f1 = 0, .f2 = 0, .f3 = 1}; + const ip_name_lookup_list_ip_address_t addresses{.ptr = address, .len = 1}; + auto* bytes = static_cast(result); + bytes[0] = 0; + std::memcpy(bytes + sizeof(void*), &addresses, sizeof(addresses)); + return monotonic_clock_wait_for(50000000); +} + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" void __real_wasip3_subtask_drop(wasip3_subtask_t); + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" void __wrap_wasip3_subtask_drop(wasip3_subtask_t handle) { + if (handle == state().pending_handle && handle != 0) { + state().pending_handle = 0; + ++state().pending_releases; + } + __real_wasip3_subtask_drop(handle); +} + +namespace { +void pending_cancellation(bool per_operation) { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + webcpp::asio::io_context context; + tcp::resolver resolver(context); + counts allocations; + asio::cancellation_signal cancellation; + int completed = 0; + const auto before = state().pending_releases; + resolver.async_resolve( + "cancel.test.invalid", "443", + asio::bind_allocator( + allocator(allocations), + asio::bind_cancellation_slot( + cancellation.slot(), + [&](boost::system::error_code error, const tcp::resolver::results_type& result) { + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST(result.empty()); + BOOST_TEST_EQ(allocations.live, 0U); + BOOST_TEST_EQ(state().pending_releases, before + 1); + ++completed; + }))); + BOOST_TEST_EQ(context.poll_one(), 1U); + BOOST_TEST(state().pending_handle != 0); + if (per_operation) { + cancellation.emit(asio::cancellation_type::all); + } else { + resolver.cancel(); + } + context + .run(); // lint-run: release a genuinely pending host subtask before cancellation delivery + BOOST_TEST_EQ(completed, 1); + BOOST_TEST_EQ(state().pending_handle, 0U); +} + +void pending_shutdown() { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + counts allocations; + const auto before = state().pending_releases; + { + webcpp::asio::io_context context; + tcp::resolver resolver(context); + resolver.async_resolve( + "cancel.test.invalid", "443", + asio::bind_allocator(allocator(allocations), + [](boost::system::error_code, const tcp::resolver::results_type&) { + BOOST_ERROR("abandoned resolver completion"); + })); + BOOST_TEST_EQ(context.poll_one(), 1U); + BOOST_TEST(state().pending_handle != 0); + } + BOOST_TEST_EQ(allocations.live, 0U); + BOOST_TEST_EQ(state().pending_releases, before + 1); + BOOST_TEST_EQ(state().pending_handle, 0U); +} + +} // namespace + +int main() { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + webcpp::asio::io_context context; + tcp::resolver resolver(context); + counts allocations; + bool resolved = false; + bool timer_fired = false; + auto lazy = resolver.async_resolve("delayed.test.invalid", "443", asio::deferred); + BOOST_TEST_EQ(state().lookups, 0); + BOOST_TEST_EQ(context.poll(), 0U); + context.restart(); + std::move(lazy)(asio::bind_allocator( + allocator(allocations), + [&](boost::system::error_code error, const tcp::resolver::results_type& result) { + BOOST_TEST_EQ(error, boost::system::error_code{}); + BOOST_TEST_EQ(result.size(), 1U); + BOOST_TEST(timer_fired); + BOOST_TEST_EQ(allocations.live, 0U); + if (!result.empty()) { + BOOST_TEST_EQ(result.begin()->endpoint().port(), 443); + } + resolved = true; + })); + BOOST_TEST_EQ(state().lookups, 0); + BOOST_TEST(!resolved); + webcpp::asio::steady_timer timer(context, std::chrono::milliseconds(1)); + timer.async_wait([&](boost::system::error_code error) { + BOOST_TEST(!error); + BOOST_TEST(!resolved); + BOOST_TEST_EQ(state().lookups, 1); + timer_fired = true; + }); + context.run(); // lint-run: prove the native pending lookup permits unrelated timer progress + BOOST_TEST(resolved); + BOOST_TEST(timer_fired); + BOOST_TEST_EQ(allocations.live, 0U); + pending_cancellation(false); + pending_cancellation(true); + pending_shutdown(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capability_wasi/resolver_runners_test.cpp b/test/capability_wasi/resolver_runners_test.cpp new file mode 100644 index 0000000..e3b08f4 --- /dev/null +++ b/test/capability_wasi/resolver_runners_test.cpp @@ -0,0 +1,97 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../wasip2/counting_allocator.hpp" + +namespace { +struct test_state { + std::atomic pending_handle{0}; + std::atomic poll_owns_waitable{false}; +}; + +test_state& state() { + static test_state value; + return value; +} +} // namespace + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" std::uint32_t __wrap_webcpp_asio_wasip3_lookup([[maybe_unused]] const char* name, + [[maybe_unused]] std::size_t size, + [[maybe_unused]] void const* result) { + auto const status = monotonic_clock_wait_for(1000000000); + state().pending_handle = WASIP3_SUBTASK_HANDLE(status); + return status; +} + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" void __real_wasip3_waitable_join(std::uint32_t, wasip3_waitable_set_t); + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" void __wrap_wasip3_waitable_join(std::uint32_t waitable, wasip3_waitable_set_t set) { + __real_wasip3_waitable_join(waitable, set); + if (waitable != 0 && waitable == state().pending_handle.load()) { + state().poll_owns_waitable = set != 0; + } +} + +int main() { + namespace asio = boost::asio; + using tcp = webcpp::asio::ip::tcp; + for (bool const per_operation : {false, true}) { + webcpp::asio::io_context context; + tcp::resolver resolver(context); + asio::cancellation_signal cancellation; + counts allocations; + std::atomic completed{0}; + resolver.async_resolve( + "pending.test.invalid", "443", + asio::bind_allocator( + allocator(allocations), + asio::bind_cancellation_slot( + cancellation.slot(), [&](boost::system::error_code error, + const tcp::resolver::results_type& results) { + BOOST_TEST_EQ(error, asio::error::operation_aborted); + BOOST_TEST(results.empty()); + BOOST_TEST_EQ(allocations.live, 0U); + ++completed; + }))); + BOOST_TEST_EQ(context.poll_one(), 1U); + std::thread runner([&] { + context.run(); // lint-run: one runner owns the libc waitable poll during cancellation + }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (!state().poll_owns_waitable && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + BOOST_TEST(state().poll_owns_waitable.load()); + if (per_operation) { + cancellation.emit(asio::cancellation_type::all); + } else { + resolver.cancel(); + } + context.run(); // lint-run: a second runner must not destroy storage still borrowed by poll + runner.join(); + BOOST_TEST_EQ(completed.load(), 1); + BOOST_TEST_EQ(allocations.live, 0U); + BOOST_TEST(!state().poll_owns_waitable.load()); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capability_wasi/send_retry_test.cpp b/test/capability_wasi/send_retry_test.cpp new file mode 100644 index 0000000..c44e51b --- /dev/null +++ b/test/capability_wasi/send_retry_test.cpp @@ -0,0 +1,90 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include +#include +#include +#include +#include +#include +#include "../wasip2/counting_allocator.hpp" + +namespace { +struct test_state { + int sending_socket = -1; + int attempts = 0; +}; + +test_state& state() { + static test_state value; + return value; +} +} // namespace + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" ssize_t __real_send(int, const void*, size_t, int); + +// The linker --wrap protocol requires this exact native boundary symbol. +// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) +extern "C" ssize_t __wrap_send(int socket, const void* data, size_t size, int flags) { + if (socket == state().sending_socket && ++state().attempts == 1) { + errno = EAGAIN; + return -1; + } + return __real_send(socket, data, size, flags); +} + +int main() { + namespace asio = boost::asio; + using udp = webcpp::asio::ip::udp; + for (bool const gather : {false, true}) { + webcpp::asio::io_context context; + udp::socket receiver(context, {asio::ip::address_v4::loopback(), 0}); + udp::socket sender(context, udp::v4()); + sender.connect(receiver.local_endpoint()); + state().sending_socket = sender.native_handle(); + state().attempts = 0; + counts allocations; + int completed = 0; + int received = 0; + std::array data{}; + udp::endpoint peer; + receiver.async_receive_from(asio::buffer(data), peer, + [&](boost::system::error_code error, std::size_t size) { + BOOST_TEST(!error); + BOOST_TEST_EQ(size, 2U); + BOOST_TEST(std::string_view(data.data(), 2) == "ab"); + ++received; + }); + auto handler = asio::bind_allocator(allocator(allocations), + [&](boost::system::error_code error, std::size_t size) { + BOOST_TEST(!error); + BOOST_TEST_EQ(size, 2U); + BOOST_TEST_EQ(allocations.live, 0U); + ++completed; + }); + const std::array pieces{asio::buffer("a", 1), asio::buffer("b", 1)}; + if (gather) { + sender.async_send(pieces, handler); + } else { + sender.async_send(asio::buffer("ab", 2), handler); + } + BOOST_TEST_EQ(completed, 0); + context.run(); // lint-run: retry the transient native send after real write readiness + BOOST_TEST_EQ(completed, 1); + BOOST_TEST(state().attempts >= 2); + BOOST_TEST_EQ(received, 1); + receiver.non_blocking(true); + boost::system::error_code error; + BOOST_TEST_EQ(receiver.receive_from(asio::buffer(data), peer, 0, error), 0U); + BOOST_TEST(error == asio::error::would_block || error == asio::error::try_again); + state().sending_socket = -1; + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/cobalt_io_test.cpp b/test/cobalt_io_test.cpp index 157ec6c..88d5277 100644 --- a/test/cobalt_io_test.cpp +++ b/test/cobalt_io_test.cpp @@ -133,12 +133,8 @@ cobalt::main co_main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { io::resolver resolver(exec); const auto [resolve_error, endpoints] = co_await cobalt::as_tuple( resolver.resolve("127.0.0.1", "443", io::resolver::flags::numeric_host)); -#if defined(__wasip3__) && !defined(BOOST_ASIO_HAS_THREADS) - BOOST_TEST(resolve_error == boost::asio::error::operation_not_supported); -#else BOOST_TEST(!resolve_error); BOOST_TEST(!endpoints.empty()); -#endif watchdog.cancel(); std::puts("cobalt: compiled I/O, task, TCP, UDP, cancellation, EOF and resolver checked"); co_return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/config_test.cpp b/test/config_test.cpp index 9432c25..1ed808a 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -26,6 +26,6 @@ #endif #if !defined(WEBCPP_TARGET_NATIVE) && !defined(WEBCPP_TARGET_EMSCRIPTEN) && \ - !defined(WEBCPP_TARGET_WASIP3) + !defined(WEBCPP_TARGET_WASIP2) && !defined(WEBCPP_TARGET_WASIP3) #error "Asio must expose the collection target configuration" #endif diff --git a/test/openssl_on_webassembly_test.cpp b/test/openssl_on_webassembly_test.cpp index 8e6850c..6990fdc 100644 --- a/test/openssl_on_webassembly_test.cpp +++ b/test/openssl_on_webassembly_test.cpp @@ -4,6 +4,6 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// expected-error@*:* {{webcpp::asio: /webcpp/asio//openssl is named in a build for WebAssembly, and -// OpenSSL is native only}} +// expected-error@*:* {{is named in a build for Emscripten, whose browser profile does not link +// OpenSSL}} #include "../src/openssl_on_webassembly.hpp" diff --git a/test/ssl_without_openssl_test.cpp b/test/ssl_without_openssl_test.cpp index 1374f98..b81b75b 100644 --- a/test/ssl_without_openssl_test.cpp +++ b/test/ssl_without_openssl_test.cpp @@ -4,6 +4,6 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// expected-error@webcpp/asio/ssl.hpp:* {{webcpp::asio: needs OpenSSL -// natively, and it is not linked}} +// expected-error@webcpp/asio/ssl.hpp:* {{needs OpenSSL on native and WASI targets, and it is not +// linked}} #include diff --git a/test/wasi_contract_test.cpp b/test/wasi_contract_test.cpp index c61769d..995ddb6 100644 --- a/test/wasi_contract_test.cpp +++ b/test/wasi_contract_test.cpp @@ -58,15 +58,15 @@ int main() { BOOST_TEST_EQ(error, boost::system::error_code{}); BOOST_TEST_EQ(sent, 2U); #if defined(__wasip2__) || defined(__wasip3__) - // A refused vectored receive must not consume even the first byte. + // Scatter the same datagram across every nonempty output buffer. const std::array outputs{ asio::buffer(data.data(), 1), asio::buffer(data.data() + 1, 1), }; - BOOST_TEST_EQ(receiver.receive_from(outputs, peer, 0, error), 0U); - BOOST_TEST_EQ(error, asio::error::operation_not_supported); -#endif + BOOST_TEST_EQ(receiver.receive_from(outputs, peer, 0, error), 2U); +#else BOOST_TEST_EQ(receiver.receive_from(asio::buffer(data), peer, 0, error), 2U); +#endif BOOST_TEST_EQ(error, boost::system::error_code{}); BOOST_TEST(std::string(data.data(), 2) == "ab"); @@ -99,12 +99,9 @@ int main() { std::array distant_outputs{}; distant_outputs.front() = asio::buffer(data.data(), 1); distant_outputs.back() = asio::buffer(data.data() + 1, 1); - BOOST_TEST_EQ(receiver.receive_from(distant_outputs, peer, 0, error), 0U); - BOOST_TEST_EQ(error, asio::error::operation_not_supported); - if (error == asio::error::operation_not_supported) { - BOOST_TEST_EQ(receiver.receive_from(asio::buffer(data), peer), 2U); - BOOST_TEST(std::string(data.data(), 2) == "ab"); - } + BOOST_TEST_EQ(receiver.receive_from(distant_outputs, peer, 0, error), 2U); + BOOST_TEST_EQ(error, boost::system::error_code{}); + BOOST_TEST(std::string(data.data(), 2) == "ab"); #endif // Both connected scalar and vectored empty operations keep UDP semantics. @@ -179,13 +176,8 @@ int main() { resolver.async_resolve( "localhost", "80", [&](boost::system::error_code ec, const tcp::resolver::results_type& addresses) { -#if defined(__wasip3__) && !defined(BOOST_ASIO_HAS_THREADS) - BOOST_TEST_EQ(ec, asio::error::operation_not_supported); - BOOST_TEST(addresses.empty()); -#else BOOST_TEST_EQ(ec, boost::system::error_code{}); BOOST_TEST(!addresses.empty()); -#endif ++resolved; }); BOOST_TEST_EQ(resolved, 0); diff --git a/test/wasi_udp_gather_test.cpp b/test/wasi_udp_gather_test.cpp index 24a0801..1c7db12 100644 --- a/test/wasi_udp_gather_test.cpp +++ b/test/wasi_udp_gather_test.cpp @@ -119,7 +119,7 @@ void test_gather() { }; check_sends(context, sender, receiver, pieces, "HEADER:Hello"); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) // Gather the original sequence, before Asio's 64-entry iovec adapter. std::array many{}; many.fill(asio::buffer("x", 1)); @@ -139,7 +139,7 @@ void test_gather() { const std::array empty{}; check_sends(context, sender, receiver, empty, ""); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) boost::system::error_code error; const auto before = context_allocations.calls; BOOST_TEST_EQ(sender.send_to(pieces, receiver.local_endpoint(), 0, error), 12U); @@ -212,7 +212,7 @@ void test_gather() { #endif } -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) void test_shutdown() { allocation_counts allocations; int completions = 0; @@ -236,7 +236,7 @@ void test_shutdown() { int main() { test_gather(); -#ifdef __wasip3__ +#if defined(__wasip2__) || defined(__wasip3__) test_shutdown(); #endif return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/wasip2_tls_cobalt/Jamfile b/test/wasip2_tls_cobalt/Jamfile new file mode 100644 index 0000000..6e19da0 --- /dev/null +++ b/test/wasip2_tls_cobalt/Jamfile @@ -0,0 +1,39 @@ +# 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) + +project : requirements /webcpp/asio//asio /webcpp//node-test ; +import webcpp ; +webcpp.targets wasip2 ; +webcpp.run cobalt : ../cobalt_test.cpp : /webcpp/asio//cobalt : wasip2 ; +webcpp.run cobalt_network : ../cobalt_network_test.cpp : /webcpp/asio//cobalt : wasip2 ; +webcpp.run cobalt_io : ../cobalt_io_test.cpp : /webcpp/asio//cobalt : wasip2 ; +webcpp.run cobalt_accept_cancel : ../cobalt_accept_cancel_test.cpp + : /webcpp/asio//cobalt : wasip2 ; +webcpp.run cobalt_cancel : cobalt_cancel.cpp : /webcpp/asio//cobalt : wasip2 ; +webcpp.original python3 : ../wasip2 ; +webcpp.drive entropy : ../../../../tools/openssl/test/entropy.c + : /webcpp/third_party//openssl -Wl,--wrap=getentropy + : entropy_driver.py : : wasip2 ; +webcpp.drive cobalt_status : ../cobalt_status_test.cpp : /webcpp/asio//cobalt + : status_driver.py : : wasip2 ; +for local test in tls_client tls_client_embedded cobalt_tls_client cobalt_ssl_client + cobalt_ssl_state cobalt_ssl_cancel +{ + local args ; + local library = /webcpp/asio//tls ; + if $(test) = cobalt_tls_client { library += /webcpp/asio//cobalt ; } + if $(test) in cobalt_ssl_client cobalt_ssl_state cobalt_ssl_cancel + { library = /webcpp/asio//cobalt_ssl ; } + if $(test) != tls_client { args = --embedded ; } + if $(test) = cobalt_ssl_client { args += --require-sni ; } + if $(test) in cobalt_ssl_state cobalt_ssl_cancel { args = --state-test ; } + webcpp.drive $(test) : ../../../../tools/openssl/test/$(test).cpp + : $(library) 180 + ../../../../tools/openssl/test/tls.py + : tls_driver.py : $(args) : wasip2 ; +} +webcpp.lane wasip2-tls : entropy cobalt_status tls_client tls_client_embedded + cobalt_tls_client cobalt_ssl_client cobalt_ssl_state cobalt_ssl_cancel : wasip2 ; diff --git a/test/wasip2_tls_cobalt/cobalt_cancel.cpp b/test/wasip2_tls_cobalt/cobalt_cancel.cpp new file mode 100644 index 0000000..8100460 --- /dev/null +++ b/test/wasip2_tls_cobalt/cobalt_cancel.cpp @@ -0,0 +1,70 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace cobalt = boost::cobalt; +namespace io = cobalt::io; +namespace asio = boost::asio; + +namespace { +cobalt::promise resolve_cancelled(io::resolver& resolver) { + const auto [error, endpoints] = co_await cobalt::as_tuple(resolver.resolve("localhost", "443")); + BOOST_TEST(error == asio::error::operation_aborted); + BOOST_TEST(endpoints.empty()); +} + +cobalt::promise timer_cancelled(io::steady_timer& timer) { + const auto [error] = co_await cobalt::as_tuple(timer.wait()); + BOOST_TEST(error == asio::error::operation_aborted); +} +} // namespace + +cobalt::main co_main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { + // NOLINTNEXTLINE(readability-static-accessed-through-instance) + const auto exec = co_await cobalt::this_coro::executor; + asio::steady_timer watchdog(exec, std::chrono::seconds(5)); + watchdog.async_wait([](boost::system::error_code error) { + if (!error) { + std::abort(); + } + }); + io::resolver resolver(exec); + auto pending = resolve_cancelled(resolver); + BOOST_TEST(!pending.ready()); + resolver.cancel(); + co_await pending; + auto signal_cancelled = resolve_cancelled(resolver); + BOOST_TEST(!signal_cancelled.ready()); + signal_cancelled.cancel(); + co_await signal_cancelled; + + io::lookup lookup("localhost", "443", exec); + const auto [error, endpoints] = co_await cobalt::as_tuple(lookup); + BOOST_TEST(!error); + BOOST_TEST(!endpoints.empty()); + + io::steady_timer timer(std::chrono::hours(1), exec); + auto waiting = timer_cancelled(timer); + BOOST_TEST(!waiting.ready()); + waiting.cancel(); + co_await waiting; + watchdog.cancel(); + std::puts("cobalt: forward lookup, resolver cancellation and timer cancellation checked"); + co_return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/wasip2_tls_cobalt/entropy_driver.py b/test/wasip2_tls_cobalt/entropy_driver.py new file mode 100644 index 0000000..1ca8239 --- /dev/null +++ b/test/wasip2_tls_cobalt/entropy_driver.py @@ -0,0 +1,24 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Require actual host entropy, independent keys and fail-closed RNG failures.""" +import os +import subprocess +import sys + +launcher = [os.environ.get('WASMTIME', 'wasmtime'), 'run', '-W', 'timeout=15s', sys.argv[-1]] +keys = set() +for _ in range(3): + result = subprocess.run(launcher, capture_output=True, text=True, timeout=20, check=True) + print(result.stdout, end='') + assert 'PASS random, reseed, EC P-256, ECDSA, tamper rejection:' in result.stdout + key = next(line for line in result.stdout.splitlines() if line.startswith('PUBLIC_KEY=')) + assert key not in keys, 'Independent processes generated the same public key' + keys.add(key) +result = subprocess.run([*launcher, 'fail-entropy'], capture_output=True, text=True, + timeout=20, check=True) +print(result.stdout, end='') +assert 'PASS fail-closed:' in result.stdout, result.stdout + result.stderr diff --git a/test/wasip2_tls_cobalt/status_driver.py b/test/wasip2_tls_cobalt/status_driver.py new file mode 100644 index 0000000..e6c9c96 --- /dev/null +++ b/test/wasip2_tls_cobalt/status_driver.py @@ -0,0 +1,18 @@ +# 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 a resumed Cobalt main to return both success and failure without traps.""" +import os +import subprocess +import sys + +for status, arguments in ((7, []), (0, ['zero'])): + result = subprocess.run([os.environ.get('WASMTIME', 'wasmtime'), 'run', '-W', 'timeout=8s', + sys.argv[-1], *arguments], capture_output=True, text=True, timeout=10) + assert result.returncode == (1 if status else 0), result.stdout + result.stderr + assert result.stdout.strip() == f'cobalt: returning {status}', result.stdout + assert result.stderr == '', result.stderr + print(f'cobalt: return {status}, exact host exit status {result.returncode}') diff --git a/test/wasip2_tls_cobalt/tls_driver.py b/test/wasip2_tls_cobalt/tls_driver.py new file mode 100644 index 0000000..f016550 --- /dev/null +++ b/test/wasip2_tls_cobalt/tls_driver.py @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Drive the shared real TLS peer against the WASIp2 public consumer.""" +from pathlib import Path +import subprocess +import sys + +script = Path(__file__).resolve().parents[4] / 'tools/openssl/test/tls.py' +subprocess.run([sys.executable, str(script), sys.argv[-1], '--wasip2', *sys.argv[1:-1]], + check=True, timeout=170) From 9455076a56ece86204229c455fe64b7ed5fbf530 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 10:58:03 -0500 Subject: [PATCH 07/12] Correct WASI capability verification guidance --- doc/building.adoc | 12 ++++++++---- doc/feature-matrix.adoc | 13 +++++++++---- doc/wasip2.adoc | 3 ++- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/doc/building.adoc b/doc/building.adoc index 2dca0b6..3f28791 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -429,16 +429,20 @@ random output and key generation; they do not prove cryptographic entropy quality or snapshot/restore safety. Reseed policy after restoring a seeded instance requires separate validation. -The reproducible local test driver is `python3 tools/openssl/test/run.py --fresh` -from the superproject. It needs Python with TLS 1.3 and an OpenSSL 3 command-line +The reproducible native/WASIp3 test driver is +`python3 tools/openssl/test/run.py --fresh` from the superproject. +It needs Python with TLS 1.3 and an OpenSSL 3 command-line program only to create short-lived server fixtures. The client links the source-built library. `WASMTIME` selects the runtime executable; the recorded WASIp2/P3 checks use wasi-sdk 34.0 and Wasmtime 50.0.1. See <> for the target/variant matrix. The recurring own lane `b2 libs/asio/test/tls//tls-integration` drives those -TLS, embedded-CA, state, cancellation and entropy fixtures on native and WASIp2/P3 -profiles. `b2 libs/asio/test/tls//openssl-upstream` is native only: it requests +TLS, embedded-CA, state, cancellation and entropy fixtures on native and WASIp3 +profiles. The separate `libs/asio/test/wasip2_tls_cobalt//wasip2-tls` own lane +drives the WASIp2 fixtures with both exception modes; see <> for +the complete command, including the ordinary Cobalt consumers. +`b2 libs/asio/test/tls//openssl-upstream` is native only: it requests `webcpp-openssl-tests=on`, builds and runs upstream's full `alltests` suite, then links a TLS consumer against those exact archives. The `openssl-upstream-msvc-14.3` and `openssl-upstream-msvc-14.5` aliases exercise diff --git a/doc/feature-matrix.adoc b/doc/feature-matrix.adoc index 1afe5b7..91e521d 100644 --- a/doc/feature-matrix.adoc +++ b/doc/feature-matrix.adoc @@ -407,9 +407,12 @@ EH-off tests do not remove the pending-task move restriction in issue 287. | Cobalt `io::ssl::stream` via `cobalt_ssl` | T | T | X | T |=== -Async resolution without threads completes with `operation_not_supported`; -that negative behavior is tested. The cooperative resolver test uses a numeric -IPv4 address. It does not establish arbitrary external DNS access. +Numeric asynchronous resolution is tested through Cobalt's compiled resolver +in the supported profiles above. WASIp3's single-thread and cooperative profiles +use the native asynchronous forward resolver; the Asio consumers test localhost +lookup, deferred initiation, progress and cancellation. Arbitrary external DNS +access depends on host policy and is not established by localhost or numeric +consumers. [#asio-feature-cobalt-build-block] ===== How the Cobalt source integration works @@ -618,7 +621,9 @@ and the `cobalt_wasip3` status lane, all through the public target | Cobalt SSL wrapper | `tools/openssl/test//cobalt_ssl_client` with `tls.py --embedded --require-sni`, including `--client-arg=buffered`; `cobalt_ssl_state` and `cobalt_ssl_cancel` -with `--state-test`, for TLS 1.2/1.3 in all seven supported profiles +with `--state-test`, for TLS 1.2/1.3 in the recorded native/WASIp3 profiles. +WASIp2 has separate peer, state and cancellation evidence from +`test/wasip2_tls_cobalt//wasip2-tls` in S with EH on/off | Native/WASIp3 TLS | Superproject `tools/openssl/test/run.py`: verified TLS 1.2/1.3 handshakes, application data, shutdown and rejected peer identities in the recorded profiles diff --git a/doc/wasip2.adoc b/doc/wasip2.adoc index e613d72..edb78f0 100644 --- a/doc/wasip2.adoc +++ b/doc/wasip2.adoc @@ -33,7 +33,8 @@ real peer, trust, transfer/shutdown and cancellation consumers with: [source,bash] ---- b2 -a toolset=clang-wasip2 variant=release exception-handling=on,off \ - testing.launcher=tools/boost/asio-wasip2/run.sh libs/asio/test/wasip2_tls_cobalt + testing.launcher=tools/boost/asio-wasip2/run.sh \ + libs/asio/test/wasip2_tls_cobalt libs/asio/test/wasip2_tls_cobalt//wasip2-tls ---- The first command exercises timers, the run/poll family, TCP and UDP exchanges, From 984c7054c4cecd2d7fb7beeae2ddaa83deaea299 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 11:45:03 -0500 Subject: [PATCH 08/12] asio: document lint exceptions for executor and stream contracts --- .../webcpp/asio/browser/main_thread_context.hpp | 2 +- include/webcpp/asio/wasi/stdio_stream.hpp | 15 ++++++++------- test/browser/worker_program.cpp | 4 ++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/include/webcpp/asio/browser/main_thread_context.hpp b/include/webcpp/asio/browser/main_thread_context.hpp index b3e929f..5cd4ab2 100644 --- a/include/webcpp/asio/browser/main_thread_context.hpp +++ b/include/webcpp/asio/browser/main_thread_context.hpp @@ -16,7 +16,7 @@ #include #include -#include +#include // lint-world: Asio's exception policy #include // lint-world: owns the main-thread executor service #include #include diff --git a/include/webcpp/asio/wasi/stdio_stream.hpp b/include/webcpp/asio/wasi/stdio_stream.hpp index 5bb5bb1..1711bc4 100644 --- a/include/webcpp/asio/wasi/stdio_stream.hpp +++ b/include/webcpp/asio/wasi/stdio_stream.hpp @@ -8,7 +8,7 @@ #include #if defined(__MRDOCS__) || defined(WEBCPP_ASIO_REFERENCE) -#include +#include // lint-world: names the readiness executor #include #include @@ -103,12 +103,12 @@ void beast_close_socket(stdio_stream& stream); #else #include #include -#include -#include -#include -#include -#include -#include +#include // lint-world: preserve completion associations +#include // lint-world: borrow the caller's I/O buffers +#include // lint-world: compose pollable I/O and preserve associations +#include // lint-world: caller-owned readiness context +#include // lint-world: wait on CLI pollables +#include // lint-world: defer initiation onto the executor #include #include #include @@ -379,6 +379,7 @@ class stdio_stream { [[nodiscard]] executor_type get_executor() const noexcept { return state_->executor; } /** Returns this stream, which is its own lowest layer. */ + // lint-std: boost::asio::posix::basic_descriptor::lowest_layer returns itself lowest_layer_type& lowest_layer() noexcept { return *this; } /** Cancels outstanding operations. Subsequent operations remain usable. */ diff --git a/test/browser/worker_program.cpp b/test/browser/worker_program.cpp index ab64868..1dcf12b 100644 --- a/test/browser/worker_program.cpp +++ b/test/browser/worker_program.cpp @@ -105,9 +105,9 @@ void* run_worker(void* pointer) { ++result.callbacks; #ifdef WEBCPP_TEST_WORKER_AFFINITY // An invalid main-thread runner is rejected before reading the worker's JS handles. - if (io.run() != 0) { + if (io.run() != 0) { // lint-run: reject main-thread entry before suspension ++result.errors; - } // lint-run: negative affinity witness + } #endif return_to_worker(); })); From 059f64c4c6aa316e351b10aca1f31ca810b446e6 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 12:40:31 -0500 Subject: [PATCH 09/12] Bound browser startup discovery and report readiness failures --- test/browser/Jamfile | 6 ++- test/browser/chrome_startup.mjs | 96 +++++++++++++++++++++++++++++++++ test/browser/run.mjs | 44 +++------------ test/browser/startup_test.mjs | 87 ++++++++++++++++++++++++++++++ 4 files changed, 194 insertions(+), 39 deletions(-) create mode 100644 test/browser/chrome_startup.mjs create mode 100644 test/browser/startup_test.mjs diff --git a/test/browser/Jamfile b/test/browser/Jamfile index a9dd129..27fbc81 100644 --- a/test/browser/Jamfile +++ b/test/browser/Jamfile @@ -38,8 +38,12 @@ webcpp.drive browser_render : .//render_program webcpp.drive browser_loader : .//page_program : page_program.variants.json 120 : run.mjs : --mode loader ; +webcpp.drive browser_startup : .//page_program + : page_program.variants.json 120 + : startup_test.mjs ; -webcpp.lane browser : loader_node browser_idle browser_render browser_loader : emscripten ; +webcpp.lane browser : loader_node browser_idle browser_render browser_loader + browser_startup : emscripten ; # The threaded profile retains the selected suspension mechanism. A pool starts # browser workers before a handler needs them. Applications choose its size. diff --git a/test/browser/chrome_startup.mjs b/test/browser/chrome_startup.mjs new file mode 100644 index 0000000..55195c2 --- /dev/null +++ b/test/browser/chrome_startup.mjs @@ -0,0 +1,96 @@ +// 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) + +// Browser startup has its own deadline inside the driver's overall bound. +import assert from 'node:assert/strict' +import {existsSync, readFileSync, readdirSync} from 'node:fs' +import {homedir} from 'node:os' +import {join} from 'node:path' +import {setTimeout as delay} from 'node:timers/promises' + +export const findChrome = () => { + if (process.env.CHROME) return process.env.CHROME + assert.equal(process.platform, 'darwin', 'set CHROME to the Chrome executable') + const cache = join(homedir(), 'Library/Caches/ms-playwright') + const shells = existsSync(cache) ? readdirSync(cache) + .filter(name => /^chromium_headless_shell-\d+$/.test(name)) + .sort((a, b) => Number(b.split('-').at(-1)) - Number(a.split('-').at(-1))) : [] + for (const shell of shells) { + for (const arch of ['arm64', 'x64']) { + const path = join(cache, shell, `chrome-headless-shell-mac-${arch}`, 'chrome-headless-shell') + if (existsSync(path)) return path + } + } + throw new Error('no cached headless Chrome found; set CHROME') +} + +export const waitForChrome = async (chrome, profile, {timeout = 30000, requestTimeout = 1000} = {}) => { + const stopped = new AbortController() + let failure + let said = '' + let stage = 'waiting for DevToolsActivePort (file has not appeared)' + let lastResponse = '(none)' + const onError = error => { + failure = `Chrome failed to start: ${error.message}` + stopped.abort() + } + const onExit = (code, signal) => { + failure = `Chrome exited during startup (code ${code}, signal ${signal})` + stopped.abort() + } + const onData = data => { said = (said + data).slice(-8000) } + chrome.on('error', onError) + chrome.on('exit', onExit) + chrome.stderr?.on('data', onData) + if (chrome.exitCode !== null || chrome.signalCode !== null) { + onExit(chrome.exitCode, chrome.signalCode) + } + const deadline = performance.now() + timeout + try { + while (!failure && performance.now() < deadline) { + let port = '' + try { + port = readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0] + stage = `waiting for valid DevToolsActivePort (read ${JSON.stringify(port.slice(0, 128))})` + } catch (error) { + if (error.code !== 'ENOENT') throw error + } + if (/^\d+$/.test(port) && Number(port) > 0 && Number(port) <= 65535) { + const devtools = `http://127.0.0.1:${port}` + const endpoint = `${devtools}/json/version` + try { + const remaining = Math.max(1, Math.ceil(deadline - performance.now())) + const signal = AbortSignal.any([stopped.signal, + AbortSignal.timeout(Math.min(requestTimeout, remaining))]) + const response = await fetch(endpoint, {signal}) + lastResponse = `HTTP ${response.status} ${response.statusText}` + if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`) + const version = await response.json() + if (typeof version.Browser !== 'string' || !version.Browser) { + throw new Error('missing Browser in discovery response') + } + if (!failure) return {devtools, version} + } catch (error) { + const cause = error.cause?.code ? ` (${error.cause.code})` : '' + stage = `${endpoint}: ${error.name}: ${error.message}${cause}` + } + } + if (!failure && performance.now() < deadline) { + await delay(Math.min(50, deadline - performance.now()), undefined, + {signal: stopped.signal}).catch(error => { + if (error.name !== 'AbortError') throw error + }) + } + } + throw new Error(`${failure ?? `Chrome startup timed out after ${timeout} ms`}; ` + + `last stage: ${stage}; last discovery response: ${lastResponse}; ` + + `stderr: ${said || '(empty)'}`) + } finally { + chrome.off('error', onError) + chrome.off('exit', onExit) + chrome.stderr?.off('data', onData) + } +} diff --git a/test/browser/run.mjs b/test/browser/run.mjs index bbba7f2..e1b5196 100644 --- a/test/browser/run.mjs +++ b/test/browser/run.mjs @@ -11,12 +11,13 @@ import assert from 'node:assert/strict' import {spawn} from 'node:child_process' import {once} from 'node:events' -import {existsSync, mkdtempSync, readFileSync, readdirSync, rmSync} from 'node:fs' +import {mkdtempSync, readFileSync, rmSync} from 'node:fs' import {createServer} from 'node:http' -import {homedir, tmpdir} from 'node:os' +import {tmpdir} from 'node:os' import {dirname, extname, join, resolve, sep} from 'node:path' import {setTimeout as delay} from 'node:timers/promises' import {fileURLToPath} from 'node:url' +import {findChrome, waitForChrome} from './chrome_startup.mjs' const args = process.argv.slice(2) assert.equal(args.length, 3, 'usage: run.mjs --mode ') @@ -26,21 +27,6 @@ assert.ok(['idle', 'render', 'loader', 'workers'].includes(mode), `unknown mode const workerVariant = args[2].includes('asyncify') ? 'asyncify' : 'jspi' const here = dirname(fileURLToPath(import.meta.url)) const build = dirname(resolve(args[2])) -const findChrome = () => { - if (process.env.CHROME) return process.env.CHROME - assert.equal(process.platform, 'darwin', 'set CHROME to the Chrome executable') - const cache = join(homedir(), 'Library/Caches/ms-playwright') - const shells = existsSync(cache) ? readdirSync(cache) - .filter(name => /^chromium_headless_shell-\d+$/.test(name)) - .sort((a, b) => Number(b.split('-').at(-1)) - Number(a.split('-').at(-1))) : [] - for (const shell of shells) { - for (const arch of ['arm64', 'x64']) { - const path = join(cache, shell, `chrome-headless-shell-mac-${arch}`, 'chrome-headless-shell') - if (existsSync(path)) return path - } - } - throw new Error('no cached headless Chrome found; set CHROME') -} const left = {chrome: null, profile: null, server: null, sockets: new Set()} const exited = child => child.exitCode !== null || child.signalCode !== null @@ -101,27 +87,9 @@ const startChrome = async () => { '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1', 'about:blank' ], {stdio: ['ignore', 'ignore', 'pipe']}) left.chrome = chrome - let error - let said = '' - chrome.on('error', value => { error = value }) - chrome.stderr.on('data', data => { said = (said + data).slice(-2000) }) - const deadline = Date.now() + 10000 - while (Date.now() < deadline) { - if (error) throw error - if (exited(chrome)) throw new Error(`Chrome exited during startup: ${said}`) - const active = join(left.profile, 'DevToolsActivePort') - const port = existsSync(active) ? readFileSync(active, 'utf8').split('\n')[0] : '' - if (/^\d+$/.test(port)) { - const devtools = `http://127.0.0.1:${port}` - try { - const version = await (await fetch(`${devtools}/json/version`)).json() - console.log(`browser ${mode}: ${version.Browser}`) - return devtools - } catch {} - } - await delay(50) - } - throw new Error(`Chrome startup timed out: ${said}`) + const {devtools, version} = await waitForChrome(chrome, left.profile) + console.log(`browser ${mode}: ${version.Browser}`) + return devtools } // Installed before any program code; only page calls are recorded, not driver polling. diff --git a/test/browser/startup_test.mjs b/test/browser/startup_test.mjs new file mode 100644 index 0000000..f4da8b1 --- /dev/null +++ b/test/browser/startup_test.mjs @@ -0,0 +1,87 @@ +// 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 startup failures at the process/HTTP boundary, then delay a real +// Chrome launch beyond the former ten-second limit and load both real variants. +import assert from 'node:assert/strict' +import {spawn} from 'node:child_process' +import {once} from 'node:events' +import {mkdtempSync, rmSync, writeFileSync} from 'node:fs' +import {createServer} from 'node:http' +import {tmpdir} from 'node:os' +import {join} from 'node:path' +import {fileURLToPath} from 'node:url' +import {findChrome, waitForChrome} from './chrome_startup.mjs' + +const scratch = mkdtempSync(join(tmpdir(), 'asio-startup-test-')) +const fixture = async (response, check) => { + const profile = mkdtempSync(join(scratch, 'profile-')) + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 10000)']) + const server = response && createServer(response) + try { + if (server) { + server.listen(0, '127.0.0.1') + await once(server, 'listening') + writeFileSync(join(profile, 'DevToolsActivePort'), `${server.address().port}\n`) + } + await check(child, profile) + } finally { + if (child.exitCode === null && child.signalCode === null) { + const ended = once(child, 'exit') + child.kill() + await ended + } + if (server) { + server.closeAllConnections() + await new Promise(resolve => server.close(resolve)) + } + } +} + +try { + await fixture(null, async (child, profile) => { + await assert.rejects(waitForChrome(child, profile, {timeout: 200}), + /startup timed out.*waiting for DevToolsActivePort/s) + }) + await fixture((request, response) => response.writeHead(503).end('not ready'), + async (child, profile) => { + await assert.rejects(waitForChrome(child, profile, {timeout: 1000}), + /startup timed out.*\/json\/version.*HTTP 503/s) + }) + await fixture(() => {}, async (child, profile) => { + const start = performance.now() + await assert.rejects(waitForChrome(child, profile, {timeout: 250, requestTimeout: 100}), + /startup timed out.*\/json\/version.*TimeoutError/s) + assert.ok(performance.now() - start < 5000, 'an unanswered discovery request escaped its bound') + }) + await fixture(null, async (child, profile) => { + const waiting = waitForChrome(child, profile) + child.kill('SIGTERM') + await assert.rejects(waiting, /Chrome exited during startup.*SIGTERM/s) + }) + const missing = spawn(join(scratch, 'no-such-chrome')) + await assert.rejects(waitForChrome(missing, scratch), /Chrome failed to start.*ENOENT/s) + + const wrapper = join(scratch, 'delayed-chrome') + const quoted = `'${findChrome().replaceAll("'", "'\\''")}'` + writeFileSync(wrapper, `#!/bin/sh\nsleep 11\nexec ${quoted} "$@"\n`, {mode: 0o700}) + const driver = spawn(process.execPath, [fileURLToPath(new URL('./run.mjs', import.meta.url)), + '--mode', 'loader', process.argv.at(-1)], { + env: {...process.env, CHROME: wrapper}, stdio: ['ignore', 'pipe', 'pipe'] + }) + let output = '' + driver.stdout.on('data', data => { output += data }) + driver.stderr.on('data', data => { output += data }) + const bound = setTimeout(() => driver.kill(), 55000) + let status + try { [status] = await once(driver, 'close') } finally { clearTimeout(bound) } + assert.equal(status, 0, output) + assert.match(output, /browser loader: ok/) + process.stdout.write(output) + console.log('browser startup: bounded failures and delayed real Chrome passed') +} finally { + rmSync(scratch, {recursive: true, force: true}) +} From 70e6f5f2839e1ab0535ffea1e5da5a10a185178a Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 13:32:29 -0500 Subject: [PATCH 10/12] asio: Account for native IOCP oversized datagram errors --- test/capability_wasi/datagrams_test.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/capability_wasi/datagrams_test.cpp b/test/capability_wasi/datagrams_test.cpp index 71468a3..495acdd 100644 --- a/test/capability_wasi/datagrams_test.cpp +++ b/test/capability_wasi/datagrams_test.cpp @@ -196,7 +196,14 @@ void datagram_boundaries() { BOOST_TEST_EQ(context_counts.allocations, before); int rejected = 0; sender.async_send(oversized, [&](boost::system::error_code ec, std::size_t size) { +#ifdef BOOST_ASIO_HAS_IOCP + // Upstream forwards the IOCP error, observed as ERROR_INVALID_USER_BUFFER for this send. + const boost::system::error_code invalid_buffer(ERROR_INVALID_USER_BUFFER, + boost::system::system_category()); + BOOST_TEST(ec == asio::error::message_size || ec == invalid_buffer); +#else BOOST_TEST_EQ(ec, asio::error::message_size); +#endif BOOST_TEST_EQ(size, 0U); ++rejected; }); From 4199a45f0625ecb5a9319a5b9eb28dbd1e0a48a9 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 13:59:23 -0500 Subject: [PATCH 11/12] asio: Preserve TLS thread profiles on MSVC --- meta/libraries.json | 2 +- test/tls/Jamfile | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/meta/libraries.json b/meta/libraries.json index 7f987e3..64224a4 100644 --- a/meta/libraries.json +++ b/meta/libraries.json @@ -2,7 +2,7 @@ "key": "asio", "name": "asio", "authors": ["R"], - "description": "Boost.Asio natively, and in the browser Boost.Asio's own io_context suspended into the page's event loop.", + "description": "Boost.Asio and Cobalt for native, browser and WASIp2/P3 targets, with explicit platform capabilities.", "category": ["Concurrent", "IO"], "maintainers": ["R "], "cxxstd": "20", diff --git a/test/tls/Jamfile b/test/tls/Jamfile index 67d9da6..1b2bd78 100644 --- a/test/tls/Jamfile +++ b/test/tls/Jamfile @@ -10,9 +10,13 @@ webcpp.original python3 ; # These are the real OpenSSL/Cobalt fixtures, now part of recurring CI rather # than executables requiring a manual request. Both thread profiles are kept. +# MSVC's shared CRT forces B2 threading=multi. S fixtures select its static CRT +# so the provider actually configures no-threads. local tests ; for local threading in single multi { + local runtime ; + if $(threading) = single { runtime = msvc:static ; } for local exceptions in "on" "off" { local targets = native wasip3 ; @@ -31,7 +35,7 @@ for local threading in single multi local name = $(mode)-$(threading)-$(exceptions) ; webcpp.drive $(name) : ../../../../tools/openssl/test//$(source) : $(threading) $(exceptions) - 180 + $(runtime) 180 : driver.py : $(mode) : $(targets) ; tests += $(name) ; } @@ -49,9 +53,11 @@ webcpp.lane tls-integration : $(tests) entropy entropy-threads : native wasip3 ; # The opt-in feature isolates the upstream suite from ordinary consumer builds. for local threading in single multi { + local runtime ; + if $(threading) = single { runtime = msvc:static ; } webcpp.drive upstream-$(threading) : ../../../../tools/openssl/test//tls_client : release $(threading) on - on 180 + $(runtime) on 180 : driver.py : client : native ; } webcpp.lane openssl-upstream : upstream-single upstream-multi : native ; From db4f7fc6afc516fdef057614cc971cdc39484099 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 4 Nov 2026 05:48:24 -0500 Subject: [PATCH 12/12] asio: Include WASIp2 in guide and reference target descriptions --- doc/names.adoc | 8 ++++---- doc/sockets.adoc | 2 +- doc/testing.adoc | 9 +++++---- doc/timers.adoc | 2 +- include/webcpp/asio/io_context.hpp | 2 +- include/webcpp/asio/tls_client_context.hpp | 2 +- 6 files changed, 13 insertions(+), 12 deletions(-) diff --git a/doc/names.adoc b/doc/names.adoc index 5c664b9..ff94166 100644 --- a/doc/names.adoc +++ b/doc/names.adoc @@ -7,9 +7,9 @@ [#asio-names] == The names -asio's targets are native, emscripten and wasip3. The table below compares -native and browser interfaces; <> specifies the WASIp3 -subset, which keeps Boost's socket and timer types. A name of asio is +asio's targets are native, emscripten, wasip2 and wasip3. The table below compares +native and browser interfaces; <> specifies the WASIp2 and WASIp3 +subsets, which keep Boost's socket and timer types. A name of asio is Boost.Asio's own, or a type with Boost.Asio's interface where the browser needs one of its own: @@ -71,7 +71,7 @@ the concurrency it will see, with or without an allocator, so that Boost's idiom `+io_context io{1}+` compiles unchanged. Its one option, `max_handlers_per_turn`, 100 by default, bounds the handlers one turn of its run family runs on emscripten before it yields to the browser; 0 is -taken as 1. Natively and on WASIp3 the options are accepted and change nothing, since +taken as 1. Natively and on WASIp2/P3 the options are accepted and change nothing, since no browser page waits on these loops. On emscripten, `/webcpp/asio//asio` also gives every program the diff --git a/doc/sockets.adoc b/doc/sockets.adoc index a0c435f..6e415a0 100644 --- a/doc/sockets.adoc +++ b/doc/sockets.adoc @@ -95,7 +95,7 @@ include::{examples}/asio_resolver.expected[] === Explanation: TLS settings -Native and WASIp3 `ssl` names are Boost's, with OpenSSL explicitly linked as described +Native and WASIp2/P3 `ssl` names are Boost's, with OpenSSL explicitly linked as described in <>. In the browser, `ssl::context` records method, verification, options, additional roots and client-credential requests. It does not read files, parse certificates, implement TLS or execute verification callbacks. diff --git a/doc/testing.adoc b/doc/testing.adoc index 023f589..2136021 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -28,10 +28,11 @@ use a real browser when your contract depends on page events or animation. === What the library checks asio's tests are under `test/`, each declared in `test/Jamfile` with -webcpp's rules, for native, emscripten and wasip3: +webcpp's rules, for native, emscripten, wasip2 and wasip3: {n-tests} tests in all, {n-tests-native} natively, {n-tests-emscripten} -on emscripten, run by node, and {n-tests-wasip3} on WASIp3. -The WASIp3 profiles and local commands are in <>. Each public header is also compiled alone, as +on emscripten, run by node, {n-tests-wasip2} on WASIp2, and {n-tests-wasip3} on WASIp3. +The WASI profiles and local commands are in <> and <>. +Each public header is also compiled alone, as the only include of its translation unit, so that a header that leans on an include it does not make fails, naming it. @@ -45,7 +46,7 @@ library-specific and global WebCPP settings. [#asio-testing-lanes] === The lanes -In addition to the WASIp3 target above, asio declares these lanes for the build and test matrix, each built from scratch +In addition to the WASIp2/P3 targets above, asio declares these lanes for the build and test matrix, each built from scratch with `b2 -a` and a `--build-dir` of its own. From the root of a webcpp checkout: diff --git a/doc/timers.adoc b/doc/timers.adoc index 54b3170..e6d5ba0 100644 --- a/doc/timers.adoc +++ b/doc/timers.adoc @@ -8,7 +8,7 @@ == Timers `steady_timer`, `system_timer` and `basic_waitable_timer` are aliases of -Boost.Asio's timers on native, Emscripten and WASIp3. Their executors, completion tokens, +Boost.Asio's timers on native, Emscripten and WASIp2/P3. Their executors, completion tokens, associated allocators and per-operation cancellation slots keep Boost's interfaces and behaviour. diff --git a/include/webcpp/asio/io_context.hpp b/include/webcpp/asio/io_context.hpp index a3d48fe..2c56d70 100644 --- a/include/webcpp/asio/io_context.hpp +++ b/include/webcpp/asio/io_context.hpp @@ -44,7 +44,7 @@ struct io_context_options { Boost.Asio's io_context, whose run family on emscripten suspends into the browser's event loop and yields to it after every turn of max_handlers_per_turn handlers. - Natively and on WASIp3 it uses Boost's run family, and its options change nothing. + Natively and on WASIp2/P3 it uses Boost's run family, and its options change nothing. In a threaded browser build each context and its JavaScript bridge stay on their constructing thread. Other threads post through its executor; the run family rejects a runner on another thread. Multiple simultaneous runners of one browser diff --git a/include/webcpp/asio/tls_client_context.hpp b/include/webcpp/asio/tls_client_context.hpp index 0c27aec..98a6972 100644 --- a/include/webcpp/asio/tls_client_context.hpp +++ b/include/webcpp/asio/tls_client_context.hpp @@ -76,7 +76,7 @@ inline boost::system::error_code make_error_code(tls_context_error value) noexce /** Creates a verifying TLS client context trusting only the supplied authorities. - Native and WASIp3 contexts require TLS 1.2 or newer and enable peer verification. + Native and WASIp2/P3 contexts require TLS 1.2 or newer and enable peer verification. Input consists of one or more PEM CA certificates separated only by whitespace. The certificates are copied into an independent OpenSSL store; input need not outlive this call. No system or bundled roots are added. No context is returned