From 21c8870031d43cd3a0dfd085cfb1ee8c63efb629 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Sat, 4 Jul 2026 23:04:27 -0700 Subject: [PATCH 01/15] export safe asio objects --- include/tmc/asio/safe_acceptor.hpp | 117 +++++++++++++++ include/tmc/asio/safe_socket.hpp | 161 ++++++++++++++++++++ include/tmc/asio/safe_timer.hpp | 75 ++++++++++ include/tmc/detail/tiny_mutex.hpp | 227 +++++++++++++++++++++++++++++ 4 files changed, 580 insertions(+) create mode 100644 include/tmc/asio/safe_acceptor.hpp create mode 100644 include/tmc/asio/safe_socket.hpp create mode 100644 include/tmc/asio/safe_timer.hpp create mode 100644 include/tmc/detail/tiny_mutex.hpp diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp new file mode 100644 index 00000000..d9328491 --- /dev/null +++ b/include/tmc/asio/safe_acceptor.hpp @@ -0,0 +1,117 @@ +// Copyright (c) 2023-2026 Logan McDougall +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include "tmc/asio/aw_asio.hpp" +#include "tmc/task.hpp" + +#include "tmc/detail/tiny_mutex.hpp" + +#include + +#include +#include + +namespace tmc { + +// Type that serializes acceptor operations so they can be initiated safely from +// different coroutines. The tiny_mutex is released automatically when the +// coroutine next suspends. +class SafeAcceptor { +public: + using acceptor_type = boost::asio::ip::tcp::acceptor; + using endpoint_type = boost::asio::ip::tcp::endpoint; + using protocol_type = boost::asio::ip::tcp; + using socket_type = boost::asio::ip::tcp::socket; + using error_code = boost::system::error_code; + +private: + acceptor_type acceptor_; + tmc::tiny_mutex mut_; + +public: + explicit SafeAcceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} + + acceptor_type& acceptor_unsafe() noexcept { return acceptor_; } + const acceptor_type& acceptor_unsafe() const noexcept { return acceptor_; } + + bool is_open() const noexcept { return acceptor_.is_open(); } + + tmc::task open(protocol_type protocol) { + co_await mut_; + + error_code ec; + acceptor_.open(protocol, ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } + + template + tmc::task set_option(SettableSocketOption option) { + co_await mut_; + + error_code ec; + acceptor_.set_option(option, ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } + + tmc::task bind(endpoint_type endpoint) { + co_await mut_; + + error_code ec; + acceptor_.bind(endpoint, ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } + + tmc::task + listen(int backlog = boost::asio::socket_base::max_listen_connections) { + co_await mut_; + + error_code ec; + acceptor_.listen(backlog, ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } + + tmc::task> async_accept() { + co_await mut_; + co_return co_await acceptor_.async_accept(tmc::aw_asio); + } + + tmc::task cancel() { + co_await mut_; + + error_code ec; + acceptor_.cancel(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } + + tmc::task close() { + co_await mut_; + + error_code ec; + acceptor_.close(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } +}; + +} // namespace tmc diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp new file mode 100644 index 00000000..1fb9189e --- /dev/null +++ b/include/tmc/asio/safe_socket.hpp @@ -0,0 +1,161 @@ +// Copyright (c) 2023-2026 Logan McDougall +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include "tmc/asio/aw_asio.hpp" +#include "tmc/task.hpp" + +#include "tmc/detail/tiny_mutex.hpp" + +#include +#include +#include + +#include +#include +#include + +namespace tmc { + +// Type that serializes socket operations so they can be initiated safely from +// different coroutines. The tiny_mutex is released automatically when the +// coroutine next suspends. +class SafeSocket { +public: + using socket_type = boost::asio::ip::tcp::socket; + using error_code = boost::system::error_code; + +private: + socket_type socket_; + tmc::tiny_mutex mut_; + +public: + explicit SafeSocket(socket_type socket) : socket_(std::move(socket)) {} + + socket_type& socket_unsafe() noexcept { return socket_; } + const socket_type& socket_unsafe() const noexcept { return socket_; } + + bool is_open() const noexcept { return socket_.is_open(); } + + tmc::task> + async_connect(boost::asio::ip::tcp::endpoint endpoint) { + co_await mut_; + + co_return co_await socket_.async_connect(endpoint, tmc::aw_asio); + } + + template + tmc::task> + async_read(MutableBufferSequence buffers) { + co_await mut_; + + co_return co_await boost::asio::async_read(socket_, std::move(buffers), tmc::aw_asio); + } + + template + tmc::task> + async_read_some(MutableBufferSequence buffers) { + co_await mut_; + + co_return co_await socket_.async_read_some(std::move(buffers), tmc::aw_asio); + } + + template + tmc::task> + async_write(ConstBufferSequence buffers) { + co_await mut_; + + co_return co_await boost::asio::async_write( + socket_, std::move(buffers), tmc::aw_asio + ); + } + + template + tmc::task> + async_write_some(ConstBufferSequence buffers) { + co_await mut_; + + co_return co_await socket_.async_write_some(std::move(buffers), tmc::aw_asio); + } + + tmc::task cancel() { + co_await mut_; + + error_code ec; + socket_.cancel(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } + + // tmc::task + // shutdown(boost::asio::ip::tcp::socket::shutdown_type how) { + // co_await mut_; + + // error_code ec; + // socket_.shutdown(how, ec); + + // // Manual unlock is required since this coro didn't suspend + // co_await mut_.co_unlock(); + + // co_return ec; + // } + + // tmc::task close() { + // co_await mut_; + + // error_code ec; + // socket_.close(ec); + + // // Manual unlock is required since this coro didn't suspend + // co_await mut_.co_unlock(); + + // co_return ec; + // } + + tmc::task shutdown_full() { + co_await mut_; + + // TODO - may be useful to split this into cancel + shutdown_send, then + // drain the rest of incoming messages and then shutdown_recv and close(), + // if necessary to make the protocol shutdown properly graceful. Linux + // kernel may send RST if there is read pending data after the shutdown was + // processed. + + // The most graceful shutdown: + // On the close initiator side: + // 1. Wait until current write operation completes (this doesn't means that + // data are sent). + // 2. Call shutdown(SD_SEND/SHUT_WR). + // 3. Wait until read operation returns EOF. + // 4. Close socket. + + // On the other side: + // 1. Close starts if EOF is received. + // 2. Wait until current write operation completes. + // 3. Call shutdown(SD_SEND/SHUT_WR). + // 4. EOF was already received, so we can close the socket. + + error_code ec; + + if (socket_.is_open()) { + // cancels pending operations (shutdown doesn't do this) + // this cannot be called on a closed socket, hence the is_open() check + socket_.cancel(); + // send FIN packet to other end + socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); + // destroy the connection + socket_.close(ec); + } + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } +}; + +} // namespace tmc diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp new file mode 100644 index 00000000..64ca4dd6 --- /dev/null +++ b/include/tmc/asio/safe_timer.hpp @@ -0,0 +1,75 @@ +// Copyright (c) 2023-2026 Logan McDougall +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include "tmc/asio/aw_asio.hpp" +#include "tmc/task.hpp" + +#include "tmc/detail/tiny_mutex.hpp" + +#include + +#include +#include +#include + +namespace tmc { + +// Type that serializes timer operations so expiry updates and waits can be +// initiated safely from different coroutines. The tiny_mutex is released +// automatically when the coroutine next suspends. +class SafeTimer { +public: + using timer_type = boost::asio::steady_timer; + using error_code = boost::system::error_code; + using duration = timer_type::duration; + using time_point = timer_type::time_point; + +private: + timer_type timer_; + tmc::tiny_mutex mut_; + +public: + explicit SafeTimer(timer_type timer) : timer_(std::move(timer)) {} + + timer_type& timer_unsafe() noexcept { return timer_; } + const timer_type& timer_unsafe() const noexcept { return timer_; } + + tmc::task> async_wait() { + co_await mut_; + + co_return co_await timer_.async_wait(tmc::aw_asio); + } + + template + tmc::task> + async_wait_for(std::chrono::duration expiry) { + co_await mut_; + + timer_.expires_after(expiry); + co_return co_await timer_.async_wait(tmc::aw_asio); + } + + tmc::task> async_wait_until(time_point expiry) { + co_await mut_; + + timer_.expires_at(expiry); + co_return co_await timer_.async_wait(tmc::aw_asio); + } + + tmc::task cancel() { + co_await mut_; + + error_code ec; + timer_.cancel(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + std::unreachable(); + } +}; + +} // namespace tmc diff --git a/include/tmc/detail/tiny_mutex.hpp b/include/tmc/detail/tiny_mutex.hpp new file mode 100644 index 00000000..dabee2b6 --- /dev/null +++ b/include/tmc/detail/tiny_mutex.hpp @@ -0,0 +1,227 @@ +// Copyright (c) 2023-2026 Logan McDougall +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include "tmc/aw_yield.hpp" +#include "tmc/detail/concepts_awaitable.hpp" +#include "tmc/ex_any.hpp" +#include "tmc/task.hpp" + +#include +#include +#include +#include + +namespace tmc { +class tiny_mutex; + +namespace detail { +struct tiny_mutex_waiter { + tiny_mutex_waiter* next; + std::coroutine_handle<> continuation; + tmc::ex_any* continuation_executor; + size_t continuation_priority; +}; + +struct tiny_mutex_state { + static inline constexpr uintptr_t RUNNING = 0x1; + + std::atomic waiters; + std::atomic refs; + + inline tiny_mutex_state() noexcept : waiters{0}, refs{1} {} +}; + +// Ensure that it's safe to use pointer tagging to synchronize. +static_assert(alignof(tiny_mutex_waiter) >= 2); + +[[nodiscard]] inline bool tiny_mutex_running(uintptr_t Value) noexcept { + return 0 != (Value & tiny_mutex_state::RUNNING); +} + +template +using tiny_mutex_return_storage_t = std::conditional_t< + std::is_lvalue_reference_v, Result, std::remove_cvref_t>; + +} // namespace detail + +class [[nodiscard( + "You must co_await aw_tiny_mutex_lock for it to have any effect." +)]] aw_tiny_mutex_lock : tmc::detail::AwaitTagNoGroupAsIs { + tmc::detail::tiny_mutex_waiter me; + std::atomic parent; + + friend class tiny_mutex; + + inline aw_tiny_mutex_lock(tiny_mutex& Parent) noexcept : parent(&Parent) {} + +public: + inline bool await_ready() noexcept { return false; } + + std::coroutine_handle<> await_suspend(std::coroutine_handle<> Outer) noexcept; + + inline void await_resume() noexcept {} + + aw_tiny_mutex_lock(aw_tiny_mutex_lock const&) = delete; + aw_tiny_mutex_lock& operator=(aw_tiny_mutex_lock const&) = delete; + aw_tiny_mutex_lock(aw_tiny_mutex_lock&&) = delete; + aw_tiny_mutex_lock& operator=(aw_tiny_mutex_lock&&) = delete; +}; + +template +class [[nodiscard( + "You must co_await aw_tiny_mutex_co_unlock_return for it to have any " + "effect." +)]] aw_tiny_mutex_co_unlock_return : tmc::detail::AwaitTagNoGroupAsIs { + + // Store lvalues by reference. Move rvalues into this. + using ReturnValueStorage = std::conditional_t< + std::is_lvalue_reference_v, Result, std::remove_cvref_t>; + + // Handle value return and void return. + struct empty {}; + using ResultStorage = + std::conditional_t, empty, ReturnValueStorage>; + TMC_NO_UNIQUE_ADDRESS ResultStorage result; + + friend class tiny_mutex; + + template + inline explicit aw_tiny_mutex_co_unlock_return(ResultArg&& ResultIn) noexcept + : result(static_cast(ResultIn)) {} + + inline aw_tiny_mutex_co_unlock_return() noexcept {} + +public: + inline bool await_ready() noexcept { return false; } + + template + void await_suspend(std::coroutine_handle

Outer) noexcept { + if constexpr (std::is_void_v) { + Outer.promise().return_void(); + } else { + Outer.promise().return_value(static_cast(result)); + } + Outer.promise().customizer.post_continuation(Outer); + } + + // Never runs; post_continuation destroys this coroutine. + [[maybe_unused]] inline void await_resume() noexcept {} + + aw_tiny_mutex_co_unlock_return(aw_tiny_mutex_co_unlock_return const&) = + delete; + aw_tiny_mutex_co_unlock_return& + operator=(aw_tiny_mutex_co_unlock_return const&) = delete; + aw_tiny_mutex_co_unlock_return(aw_tiny_mutex_co_unlock_return&&) = delete; + aw_tiny_mutex_co_unlock_return& + operator=(aw_tiny_mutex_co_unlock_return&&) = delete; +}; + +/// A serializing primitive similar to `tmc::mutex`, except ownership ends when +/// the acquiring coroutine next suspends. This makes it suitable for protecting +/// short, synchronous stretches of coroutine execution without carrying the +/// lock across later awaits. +class tiny_mutex { + friend class aw_tiny_mutex_lock; + + tmc::detail::tiny_mutex_state* state; + + std::coroutine_handle<> + enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept; + + static tmc::task run_loop(tmc::detail::tiny_mutex_state* State); + +public: + inline tiny_mutex() noexcept : state(new tmc::detail::tiny_mutex_state) {} + + /// Returns true if a runner is currently executing queued work for the mutex. + /// This value is not guaranteed to be consistent with any other operation. + inline bool is_locked() noexcept { + return tmc::detail::tiny_mutex_running( + state->waiters.load(std::memory_order_relaxed) + ); + } + + /// Suspend this coroutine and resubmit it to its current executor. Since the + /// lock is owned by the runner rather than the caller, this releases the + /// mutex before the coroutine resumes later. + inline aw_yield co_unlock() noexcept { return tmc::yield(); } + + /// Completes this coroutine immediately, returns value to its parent + /// coroutine, and resubmits the parent to its current executor. Since the + /// lock is owned by the runner rather than the caller, this releases the + /// mutex before the coroutine resumes later. + /// + /// The purpose of this is to skip a round-trip through the executor when + /// you want to unlock this mutex immediately before returning. + /// + /// ``` + /// // You can replace this: + /// co_await mut.co_unlock(); + /// co_return result; + /// + /// // With this: + /// co_await mut.co_unlock_return(result); + /// std::unreachable(); + /// ``` + template + inline aw_tiny_mutex_co_unlock_return + co_unlock_return(Result&& result) noexcept { + return aw_tiny_mutex_co_unlock_return( + static_cast(result) + ); + } + + /// Completes this coroutine immediately and resubmits the parent to its + /// current executor. Since the lock is owned by the runner rather than the + /// caller, this releases the mutex before the coroutine resumes later. + /// + /// The purpose of this is to skip a round-trip through the executor when + /// you want to unlock this mutex immediately before returning. + /// + /// ``` + /// // You can replace this: + /// co_await mut.co_unlock(); + /// co_return; + /// + /// // With this: + /// co_await mut.co_unlock_return(); + /// std::unreachable(); + /// ``` + inline aw_tiny_mutex_co_unlock_return co_unlock_return() noexcept { + return aw_tiny_mutex_co_unlock_return(); + } + + /// Queue this coroutine to run under the mutex until it next suspends. + inline aw_tiny_mutex_lock operator co_await() noexcept { + return aw_tiny_mutex_lock(*this); + } + + /// Destruction is only valid once all queued work has completed and no + /// runner is active. + ~tiny_mutex(); + +private: + tiny_mutex(tiny_mutex const& Other) = delete; + tiny_mutex& operator=(tiny_mutex const& Other) = delete; + tiny_mutex(tiny_mutex&& Other) = delete; + tiny_mutex& operator=(tiny_mutex&& Other) = delete; +}; + +namespace detail { +template <> struct awaitable_traits { + static constexpr configure_mode mode = WRAPPER; + + using result_type = void; + using self_type = tmc::tiny_mutex; + using awaiter_type = tmc::aw_tiny_mutex_lock; + + static awaiter_type get_awaiter(self_type& Awaitable) noexcept { + return Awaitable.operator co_await(); + } +}; +} // namespace detail +} // namespace tmc From c91497e894762f37b7c7be58b690856124b81442 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Fri, 10 Jul 2026 15:57:07 -0700 Subject: [PATCH 02/15] cleanup port --- include/tmc/asio/safe_acceptor.hpp | 43 +++++++---- include/tmc/asio/safe_socket.hpp | 110 ++++++++++++++++++++++++----- include/tmc/asio/safe_timer.hpp | 32 +++++++-- include/tmc/detail/compat.hpp | 12 ++++ include/tmc/detail/tiny_mutex.hpp | 19 +++-- include/tmc/detail/tiny_mutex.ipp | 107 ++++++++++++++++++++++++++++ 6 files changed, 281 insertions(+), 42 deletions(-) create mode 100644 include/tmc/detail/tiny_mutex.ipp diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index d9328491..4449a829 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -6,27 +6,45 @@ #pragma once #include "tmc/asio/aw_asio.hpp" +#include "tmc/detail/compat.hpp" #include "tmc/task.hpp" #include "tmc/detail/tiny_mutex.hpp" +#ifdef TMC_USE_BOOST_ASIO #include +#include +#else +#include +#include +#endif #include #include namespace tmc { +namespace detail { +#ifdef TMC_USE_BOOST_ASIO +namespace asio_impl = ::boost::asio; +#else +namespace asio_impl = ::asio; +#endif +} // namespace detail // Type that serializes acceptor operations so they can be initiated safely from // different coroutines. The tiny_mutex is released automatically when the // coroutine next suspends. class SafeAcceptor { public: - using acceptor_type = boost::asio::ip::tcp::acceptor; - using endpoint_type = boost::asio::ip::tcp::endpoint; - using protocol_type = boost::asio::ip::tcp; - using socket_type = boost::asio::ip::tcp::socket; + using acceptor_type = tmc::detail::asio_impl::ip::tcp::acceptor; + using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; + using protocol_type = tmc::detail::asio_impl::ip::tcp; + using socket_type = tmc::detail::asio_impl::ip::tcp::socket; +#ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; +#else + using error_code = asio::error_code; +#endif private: acceptor_type acceptor_; @@ -48,7 +66,7 @@ class SafeAcceptor { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } template @@ -60,7 +78,7 @@ class SafeAcceptor { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } tmc::task bind(endpoint_type endpoint) { @@ -71,11 +89,12 @@ class SafeAcceptor { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } - tmc::task - listen(int backlog = boost::asio::socket_base::max_listen_connections) { + tmc::task listen( + int backlog = tmc::detail::asio_impl::socket_base::max_listen_connections + ) { co_await mut_; error_code ec; @@ -83,7 +102,7 @@ class SafeAcceptor { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } tmc::task> async_accept() { @@ -99,7 +118,7 @@ class SafeAcceptor { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } tmc::task close() { @@ -110,7 +129,7 @@ class SafeAcceptor { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } }; diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 1fb9189e..73a05bc9 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -6,27 +6,48 @@ #pragma once #include "tmc/asio/aw_asio.hpp" +#include "tmc/detail/compat.hpp" #include "tmc/task.hpp" #include "tmc/detail/tiny_mutex.hpp" +#ifdef TMC_USE_BOOST_ASIO +#include +#include #include -#include -#include +#include +#else +#include +#include +#include +#include +#endif #include #include #include namespace tmc { +namespace detail { +#ifdef TMC_USE_BOOST_ASIO +namespace asio_impl = ::boost::asio; +#else +namespace asio_impl = ::asio; +#endif +} // namespace detail // Type that serializes socket operations so they can be initiated safely from // different coroutines. The tiny_mutex is released automatically when the // coroutine next suspends. class SafeSocket { public: - using socket_type = boost::asio::ip::tcp::socket; + using socket_type = tmc::detail::asio_impl::ip::tcp::socket; + using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; +#ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; +#else + using error_code = asio::error_code; +#endif private: socket_type socket_; @@ -40,19 +61,39 @@ class SafeSocket { bool is_open() const noexcept { return socket_.is_open(); } - tmc::task> - async_connect(boost::asio::ip::tcp::endpoint endpoint) { + tmc::task> async_connect(endpoint_type endpoint) { co_await mut_; co_return co_await socket_.async_connect(endpoint, tmc::aw_asio); } + // Reads until the buffer sequence is full, EOF, or another error occurs + // (like `asio::async_read`). Unlike the asio composed operation - whose + // intermediate re-initiations would run on the I/O executor, outside the + // mutex - this is implemented as a loop of single-shot reads, so every + // initiation is serialized against other operations on this object. A + // concurrent cancel() or shutdown_full() takes effect at a chunk boundary. + // + // Only one read may be in flight at a time (the usual asio stream contract). template tmc::task> async_read(MutableBufferSequence buffers) { - co_await mut_; - - co_return co_await boost::asio::async_read(socket_, std::move(buffers), tmc::aw_asio); + std::size_t total = 0; + auto it = tmc::detail::asio_impl::buffer_sequence_begin(buffers); + auto end = tmc::detail::asio_impl::buffer_sequence_end(buffers); + for (; it != end; ++it) { + tmc::detail::asio_impl::mutable_buffer b = *it; + while (b.size() != 0) { + co_await mut_; + auto [ec, n] = co_await socket_.async_read_some(b, tmc::aw_asio); + total += n; + b += n; + if (ec) { + co_return std::tuple{ec, total}; + } + } + } + co_return std::tuple{error_code{}, total}; } template @@ -63,14 +104,33 @@ class SafeSocket { co_return co_await socket_.async_read_some(std::move(buffers), tmc::aw_asio); } + // Writes the entire buffer sequence unless an error occurs (like + // `asio::async_write`). Unlike the asio composed operation - whose + // intermediate re-initiations would run on the I/O executor, outside the + // mutex - this is implemented as a loop of single-shot writes, so every + // initiation is serialized against other operations on this object. A + // concurrent cancel() or shutdown_full() takes effect at a chunk boundary. + // + // Only one write may be in flight at a time (the usual asio stream contract). template tmc::task> async_write(ConstBufferSequence buffers) { - co_await mut_; - - co_return co_await boost::asio::async_write( - socket_, std::move(buffers), tmc::aw_asio - ); + std::size_t total = 0; + auto it = tmc::detail::asio_impl::buffer_sequence_begin(buffers); + auto end = tmc::detail::asio_impl::buffer_sequence_end(buffers); + for (; it != end; ++it) { + tmc::detail::asio_impl::const_buffer b = *it; + while (b.size() != 0) { + co_await mut_; + auto [ec, n] = co_await socket_.async_write_some(b, tmc::aw_asio); + total += n; + b += n; + if (ec) { + co_return std::tuple{ec, total}; + } + } + } + co_return std::tuple{error_code{}, total}; } template @@ -89,7 +149,7 @@ class SafeSocket { // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } // tmc::task @@ -117,6 +177,9 @@ class SafeSocket { // co_return ec; // } + // Cancels pending operations, sends FIN, and closes the socket. Returns the + // first error encountered, except that `not_connected` from shutdown() is + // treated as success (the peer already closed the connection). tmc::task shutdown_full() { co_await mut_; @@ -145,16 +208,27 @@ class SafeSocket { if (socket_.is_open()) { // cancels pending operations (shutdown doesn't do this) // this cannot be called on a closed socket, hence the is_open() check - socket_.cancel(); + socket_.cancel(ec); // send FIN packet to other end - socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); + error_code shutdownEc; + socket_.shutdown(socket_type::shutdown_both, shutdownEc); + if (shutdownEc == tmc::detail::asio_impl::error::not_connected) { + shutdownEc = {}; + } + if (!ec) { + ec = shutdownEc; + } // destroy the connection - socket_.close(ec); + error_code closeEc; + socket_.close(closeEc); + if (!ec) { + ec = closeEc; + } } // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); - std::unreachable(); + TMC_UNREACHABLE; } }; diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index 64ca4dd6..e9de8afc 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -6,25 +6,44 @@ #pragma once #include "tmc/asio/aw_asio.hpp" +#include "tmc/detail/compat.hpp" #include "tmc/task.hpp" #include "tmc/detail/tiny_mutex.hpp" +#ifdef TMC_USE_BOOST_ASIO #include +#include +#else +#include +#include +#endif #include +#include #include #include namespace tmc { +namespace detail { +#ifdef TMC_USE_BOOST_ASIO +namespace asio_impl = ::boost::asio; +#else +namespace asio_impl = ::asio; +#endif +} // namespace detail // Type that serializes timer operations so expiry updates and waits can be // initiated safely from different coroutines. The tiny_mutex is released // automatically when the coroutine next suspends. class SafeTimer { public: - using timer_type = boost::asio::steady_timer; + using timer_type = tmc::detail::asio_impl::steady_timer; +#ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; +#else + using error_code = asio::error_code; +#endif using duration = timer_type::duration; using time_point = timer_type::time_point; @@ -60,15 +79,16 @@ class SafeTimer { co_return co_await timer_.async_wait(tmc::aw_asio); } - tmc::task cancel() { + // Cancels any outstanding waits, which will complete with + // `operation_aborted`. Returns the number of waits that were cancelled. + tmc::task cancel() { co_await mut_; - error_code ec; - timer_.cancel(ec); + std::size_t count = timer_.cancel(); // Manual unlock is required since this coro didn't suspend - co_await mut_.co_unlock_return(ec); - std::unreachable(); + co_await mut_.co_unlock_return(count); + TMC_UNREACHABLE; } }; diff --git a/include/tmc/detail/compat.hpp b/include/tmc/detail/compat.hpp index 4454277c..1be8b690 100644 --- a/include/tmc/detail/compat.hpp +++ b/include/tmc/detail/compat.hpp @@ -297,3 +297,15 @@ static_assert(std::atomic::is_always_lock_free); #else #define TMC_AWAIT_RESUME #endif + +// Marks a point that control flow can never reach. +// std::unreachable() requires C++23; fall back to intrinsics on C++20. +#include +#if defined(__cpp_lib_unreachable) && __cpp_lib_unreachable >= 202202L +#include +#define TMC_UNREACHABLE std::unreachable() +#elif defined(_MSC_VER) && !defined(__clang__) +#define TMC_UNREACHABLE __assume(false) +#else +#define TMC_UNREACHABLE __builtin_unreachable() +#endif diff --git a/include/tmc/detail/tiny_mutex.hpp b/include/tmc/detail/tiny_mutex.hpp index dabee2b6..31ea6d7f 100644 --- a/include/tmc/detail/tiny_mutex.hpp +++ b/include/tmc/detail/tiny_mutex.hpp @@ -4,6 +4,7 @@ // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once +#include "tmc/detail/impl.hpp" // IWYU pragma: keep #include "tmc/aw_yield.hpp" #include "tmc/detail/concepts_awaitable.hpp" @@ -61,7 +62,8 @@ class [[nodiscard( public: inline bool await_ready() noexcept { return false; } - std::coroutine_handle<> await_suspend(std::coroutine_handle<> Outer) noexcept; + TMC_DECL std::coroutine_handle<> + await_suspend(std::coroutine_handle<> Outer) noexcept; inline void await_resume() noexcept {} @@ -129,10 +131,11 @@ class tiny_mutex { tmc::detail::tiny_mutex_state* state; - std::coroutine_handle<> + TMC_DECL std::coroutine_handle<> enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept; - static tmc::task run_loop(tmc::detail::tiny_mutex_state* State); + static TMC_DECL tmc::task + run_loop(tmc::detail::tiny_mutex_state* State); public: inline tiny_mutex() noexcept : state(new tmc::detail::tiny_mutex_state) {} @@ -165,7 +168,7 @@ class tiny_mutex { /// /// // With this: /// co_await mut.co_unlock_return(result); - /// std::unreachable(); + /// TMC_UNREACHABLE; /// ``` template inline aw_tiny_mutex_co_unlock_return @@ -189,7 +192,7 @@ class tiny_mutex { /// /// // With this: /// co_await mut.co_unlock_return(); - /// std::unreachable(); + /// TMC_UNREACHABLE; /// ``` inline aw_tiny_mutex_co_unlock_return co_unlock_return() noexcept { return aw_tiny_mutex_co_unlock_return(); @@ -202,7 +205,7 @@ class tiny_mutex { /// Destruction is only valid once all queued work has completed and no /// runner is active. - ~tiny_mutex(); + TMC_DECL ~tiny_mutex(); private: tiny_mutex(tiny_mutex const& Other) = delete; @@ -225,3 +228,7 @@ template <> struct awaitable_traits { }; } // namespace detail } // namespace tmc + +#if !defined(TMC_STANDALONE_COMPILATION) || defined(TMC_IMPL) +#include "tmc/detail/tiny_mutex.ipp" +#endif diff --git a/include/tmc/detail/tiny_mutex.ipp b/include/tmc/detail/tiny_mutex.ipp new file mode 100644 index 00000000..a85a5186 --- /dev/null +++ b/include/tmc/detail/tiny_mutex.ipp @@ -0,0 +1,107 @@ +// Copyright (c) 2023-2026 Logan McDougall +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include "tmc/detail/impl.hpp" // IWYU pragma: keep + +#include "tmc/aw_resume_on.hpp" +#include "tmc/detail/thread_locals.hpp" +#include "tmc/detail/tiny_mutex.hpp" + +#include +#include +#include +#include + +namespace tmc { +namespace detail { + +[[nodiscard]] inline tiny_mutex_waiter* +tiny_mutex_waiters(uintptr_t Value) noexcept { + return reinterpret_cast( + Value & ~tiny_mutex_state::RUNNING + ); +} + +inline void release_tiny_mutex_state(tiny_mutex_state* State) noexcept { + if (State->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) { + assert(State->waiters.load(std::memory_order_acquire) == 0); + delete State; + } +} +} // namespace detail + +std::coroutine_handle<> +aw_tiny_mutex_lock::await_suspend(std::coroutine_handle<> Outer) noexcept { + auto* mutex = parent.load(std::memory_order_acquire); + me.continuation = Outer; + me.continuation_executor = tmc::detail::this_thread::executor(); + me.continuation_priority = tmc::detail::this_thread::this_task().prio; + return mutex->enqueue(me); +} + +std::coroutine_handle<> +tiny_mutex::enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept { + auto* State = state; + uintptr_t head = State->waiters.load(std::memory_order_acquire); + uintptr_t desired; + do { + Waiter.next = tmc::detail::tiny_mutex_waiters(head); + desired = reinterpret_cast(&Waiter) | + tmc::detail::tiny_mutex_state::RUNNING; + } while (!State->waiters.compare_exchange_strong( + head, desired, std::memory_order_acq_rel, std::memory_order_acquire + )); + + if (tmc::detail::tiny_mutex_running(head)) { + return std::noop_coroutine(); + } + + // No runner existed prior to the CAS above, so this await_suspend path + // cannot be resumed until we return the new runner handle. + return static_cast>(run_loop(State)); +} + +tmc::task tiny_mutex::run_loop(tmc::detail::tiny_mutex_state* State) { + State->refs.fetch_add(1, std::memory_order_relaxed); + while (true) { + auto stateWord = State->waiters.exchange( + tmc::detail::tiny_mutex_state::RUNNING, std::memory_order_acq_rel + ); + auto* curr = tmc::detail::tiny_mutex_waiters(stateWord); + if (curr == nullptr) { + uintptr_t expected = tmc::detail::tiny_mutex_state::RUNNING; + if (State->waiters.compare_exchange_strong( + expected, 0, std::memory_order_acq_rel, std::memory_order_acquire + )) { + break; + } + continue; + } + + while (curr != nullptr) { + auto* next = curr->next; + auto continuation = curr->continuation; + tmc::ex_any* continuationExecutor = curr->continuation_executor; + auto continuationPriority = curr->continuation_priority; + + co_await tmc::resume_on(continuationExecutor) + .with_priority(continuationPriority); + + continuation.resume(); + curr = next; + } + } + tmc::detail::release_tiny_mutex_state(State); +} + +tiny_mutex::~tiny_mutex() { + auto* State = state; + // 0 (no waiters) or 1 (this is the running task) are valid + assert(State->waiters.load(std::memory_order_acquire) < 2); + tmc::detail::release_tiny_mutex_state(State); +} +} // namespace tmc From 56ac021ff61fa7fd60c6344bdfb68b300dee656d Mon Sep 17 00:00:00 2001 From: tzcnt Date: Fri, 10 Jul 2026 21:32:25 -0700 Subject: [PATCH 03/15] define tiny_mutex inline --- include/tmc/detail/tiny_mutex.hpp | 118 ++++++++++++++++++++++++------ include/tmc/detail/tiny_mutex.ipp | 107 --------------------------- 2 files changed, 94 insertions(+), 131 deletions(-) delete mode 100644 include/tmc/detail/tiny_mutex.ipp diff --git a/include/tmc/detail/tiny_mutex.hpp b/include/tmc/detail/tiny_mutex.hpp index 31ea6d7f..8f7ed220 100644 --- a/include/tmc/detail/tiny_mutex.hpp +++ b/include/tmc/detail/tiny_mutex.hpp @@ -4,14 +4,16 @@ // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once -#include "tmc/detail/impl.hpp" // IWYU pragma: keep +#include "tmc/aw_resume_on.hpp" #include "tmc/aw_yield.hpp" #include "tmc/detail/concepts_awaitable.hpp" +#include "tmc/detail/thread_locals.hpp" #include "tmc/ex_any.hpp" #include "tmc/task.hpp" #include +#include #include #include #include @@ -43,15 +45,25 @@ static_assert(alignof(tiny_mutex_waiter) >= 2); return 0 != (Value & tiny_mutex_state::RUNNING); } +[[nodiscard]] inline tiny_mutex_waiter* tiny_mutex_waiters(uintptr_t Value) noexcept { + return reinterpret_cast(Value & ~tiny_mutex_state::RUNNING); +} + +inline void release_tiny_mutex_state(tiny_mutex_state* State) noexcept { + if (State->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) { + assert(State->waiters.load(std::memory_order_acquire) == 0); + delete State; + } +} + template using tiny_mutex_return_storage_t = std::conditional_t< std::is_lvalue_reference_v, Result, std::remove_cvref_t>; } // namespace detail -class [[nodiscard( - "You must co_await aw_tiny_mutex_lock for it to have any effect." -)]] aw_tiny_mutex_lock : tmc::detail::AwaitTagNoGroupAsIs { +class [[nodiscard("You must co_await aw_tiny_mutex_lock for it to have any effect.")]] +aw_tiny_mutex_lock : tmc::detail::AwaitTagNoGroupAsIs { tmc::detail::tiny_mutex_waiter me; std::atomic parent; @@ -62,8 +74,7 @@ class [[nodiscard( public: inline bool await_ready() noexcept { return false; } - TMC_DECL std::coroutine_handle<> - await_suspend(std::coroutine_handle<> Outer) noexcept; + std::coroutine_handle<> await_suspend(std::coroutine_handle<> Outer) noexcept; inline void await_resume() noexcept {} @@ -100,8 +111,7 @@ class [[nodiscard( public: inline bool await_ready() noexcept { return false; } - template - void await_suspend(std::coroutine_handle

Outer) noexcept { + template void await_suspend(std::coroutine_handle

Outer) noexcept { if constexpr (std::is_void_v) { Outer.promise().return_void(); } else { @@ -113,13 +123,11 @@ class [[nodiscard( // Never runs; post_continuation destroys this coroutine. [[maybe_unused]] inline void await_resume() noexcept {} - aw_tiny_mutex_co_unlock_return(aw_tiny_mutex_co_unlock_return const&) = - delete; + aw_tiny_mutex_co_unlock_return(aw_tiny_mutex_co_unlock_return const&) = delete; aw_tiny_mutex_co_unlock_return& operator=(aw_tiny_mutex_co_unlock_return const&) = delete; aw_tiny_mutex_co_unlock_return(aw_tiny_mutex_co_unlock_return&&) = delete; - aw_tiny_mutex_co_unlock_return& - operator=(aw_tiny_mutex_co_unlock_return&&) = delete; + aw_tiny_mutex_co_unlock_return& operator=(aw_tiny_mutex_co_unlock_return&&) = delete; }; /// A serializing primitive similar to `tmc::mutex`, except ownership ends when @@ -131,11 +139,9 @@ class tiny_mutex { tmc::detail::tiny_mutex_state* state; - TMC_DECL std::coroutine_handle<> - enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept; + std::coroutine_handle<> enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept; - static TMC_DECL tmc::task - run_loop(tmc::detail::tiny_mutex_state* State); + static tmc::task run_loop(tmc::detail::tiny_mutex_state* State); public: inline tiny_mutex() noexcept : state(new tmc::detail::tiny_mutex_state) {} @@ -173,9 +179,7 @@ class tiny_mutex { template inline aw_tiny_mutex_co_unlock_return co_unlock_return(Result&& result) noexcept { - return aw_tiny_mutex_co_unlock_return( - static_cast(result) - ); + return aw_tiny_mutex_co_unlock_return(static_cast(result)); } /// Completes this coroutine immediately and resubmits the parent to its @@ -205,7 +209,7 @@ class tiny_mutex { /// Destruction is only valid once all queued work has completed and no /// runner is active. - TMC_DECL ~tiny_mutex(); + ~tiny_mutex(); private: tiny_mutex(tiny_mutex const& Other) = delete; @@ -214,6 +218,76 @@ class tiny_mutex { tiny_mutex& operator=(tiny_mutex&& Other) = delete; }; +inline std::coroutine_handle<> +aw_tiny_mutex_lock::await_suspend(std::coroutine_handle<> Outer) noexcept { + auto* mutex = parent.load(std::memory_order_acquire); + me.continuation = Outer; + me.continuation_executor = tmc::detail::this_thread::executor(); + me.continuation_priority = tmc::detail::this_thread::this_task().prio; + return mutex->enqueue(me); +} + +inline std::coroutine_handle<> +tiny_mutex::enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept { + auto* State = state; + uintptr_t head = State->waiters.load(std::memory_order_acquire); + uintptr_t desired; + do { + Waiter.next = tmc::detail::tiny_mutex_waiters(head); + desired = + reinterpret_cast(&Waiter) | tmc::detail::tiny_mutex_state::RUNNING; + } while (!State->waiters.compare_exchange_strong( + head, desired, std::memory_order_acq_rel, std::memory_order_acquire + )); + + if (tmc::detail::tiny_mutex_running(head)) { + return std::noop_coroutine(); + } + + // No runner existed prior to the CAS above, so this await_suspend path + // cannot be resumed until we return the new runner handle. + return static_cast>(run_loop(State)); +} + +inline tmc::task tiny_mutex::run_loop(tmc::detail::tiny_mutex_state* State) { + State->refs.fetch_add(1, std::memory_order_relaxed); + while (true) { + auto stateWord = State->waiters.exchange( + tmc::detail::tiny_mutex_state::RUNNING, std::memory_order_acq_rel + ); + auto* curr = tmc::detail::tiny_mutex_waiters(stateWord); + if (curr == nullptr) { + uintptr_t expected = tmc::detail::tiny_mutex_state::RUNNING; + if (State->waiters.compare_exchange_strong( + expected, 0, std::memory_order_acq_rel, std::memory_order_acquire + )) { + break; + } + continue; + } + + while (curr != nullptr) { + auto* next = curr->next; + auto continuation = curr->continuation; + tmc::ex_any* continuationExecutor = curr->continuation_executor; + auto continuationPriority = curr->continuation_priority; + + co_await tmc::resume_on(continuationExecutor).with_priority(continuationPriority); + + continuation.resume(); + curr = next; + } + } + tmc::detail::release_tiny_mutex_state(State); +} + +inline tiny_mutex::~tiny_mutex() { + auto* State = state; + // 0 (no waiters) or 1 (this is the running task) are valid + assert(State->waiters.load(std::memory_order_acquire) < 2); + tmc::detail::release_tiny_mutex_state(State); +} + namespace detail { template <> struct awaitable_traits { static constexpr configure_mode mode = WRAPPER; @@ -228,7 +302,3 @@ template <> struct awaitable_traits { }; } // namespace detail } // namespace tmc - -#if !defined(TMC_STANDALONE_COMPILATION) || defined(TMC_IMPL) -#include "tmc/detail/tiny_mutex.ipp" -#endif diff --git a/include/tmc/detail/tiny_mutex.ipp b/include/tmc/detail/tiny_mutex.ipp deleted file mode 100644 index a85a5186..00000000 --- a/include/tmc/detail/tiny_mutex.ipp +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2023-2026 Logan McDougall -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) - -#pragma once - -#include "tmc/detail/impl.hpp" // IWYU pragma: keep - -#include "tmc/aw_resume_on.hpp" -#include "tmc/detail/thread_locals.hpp" -#include "tmc/detail/tiny_mutex.hpp" - -#include -#include -#include -#include - -namespace tmc { -namespace detail { - -[[nodiscard]] inline tiny_mutex_waiter* -tiny_mutex_waiters(uintptr_t Value) noexcept { - return reinterpret_cast( - Value & ~tiny_mutex_state::RUNNING - ); -} - -inline void release_tiny_mutex_state(tiny_mutex_state* State) noexcept { - if (State->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) { - assert(State->waiters.load(std::memory_order_acquire) == 0); - delete State; - } -} -} // namespace detail - -std::coroutine_handle<> -aw_tiny_mutex_lock::await_suspend(std::coroutine_handle<> Outer) noexcept { - auto* mutex = parent.load(std::memory_order_acquire); - me.continuation = Outer; - me.continuation_executor = tmc::detail::this_thread::executor(); - me.continuation_priority = tmc::detail::this_thread::this_task().prio; - return mutex->enqueue(me); -} - -std::coroutine_handle<> -tiny_mutex::enqueue(tmc::detail::tiny_mutex_waiter& Waiter) noexcept { - auto* State = state; - uintptr_t head = State->waiters.load(std::memory_order_acquire); - uintptr_t desired; - do { - Waiter.next = tmc::detail::tiny_mutex_waiters(head); - desired = reinterpret_cast(&Waiter) | - tmc::detail::tiny_mutex_state::RUNNING; - } while (!State->waiters.compare_exchange_strong( - head, desired, std::memory_order_acq_rel, std::memory_order_acquire - )); - - if (tmc::detail::tiny_mutex_running(head)) { - return std::noop_coroutine(); - } - - // No runner existed prior to the CAS above, so this await_suspend path - // cannot be resumed until we return the new runner handle. - return static_cast>(run_loop(State)); -} - -tmc::task tiny_mutex::run_loop(tmc::detail::tiny_mutex_state* State) { - State->refs.fetch_add(1, std::memory_order_relaxed); - while (true) { - auto stateWord = State->waiters.exchange( - tmc::detail::tiny_mutex_state::RUNNING, std::memory_order_acq_rel - ); - auto* curr = tmc::detail::tiny_mutex_waiters(stateWord); - if (curr == nullptr) { - uintptr_t expected = tmc::detail::tiny_mutex_state::RUNNING; - if (State->waiters.compare_exchange_strong( - expected, 0, std::memory_order_acq_rel, std::memory_order_acquire - )) { - break; - } - continue; - } - - while (curr != nullptr) { - auto* next = curr->next; - auto continuation = curr->continuation; - tmc::ex_any* continuationExecutor = curr->continuation_executor; - auto continuationPriority = curr->continuation_priority; - - co_await tmc::resume_on(continuationExecutor) - .with_priority(continuationPriority); - - continuation.resume(); - curr = next; - } - } - tmc::detail::release_tiny_mutex_state(State); -} - -tiny_mutex::~tiny_mutex() { - auto* State = state; - // 0 (no waiters) or 1 (this is the running task) are valid - assert(State->waiters.load(std::memory_order_acquire) < 2); - tmc::detail::release_tiny_mutex_state(State); -} -} // namespace tmc From e8af0221643aec362a264f7cb75580c318d7effc Mon Sep 17 00:00:00 2001 From: tzcnt Date: Fri, 10 Jul 2026 22:42:24 -0700 Subject: [PATCH 04/15] restore separate close() / shutdown() methods --- include/tmc/asio/aw_asio.hpp | 12 +++++ include/tmc/asio/safe_acceptor.hpp | 12 ++--- include/tmc/asio/safe_socket.hpp | 83 +++++------------------------- 3 files changed, 31 insertions(+), 76 deletions(-) diff --git a/include/tmc/asio/aw_asio.hpp b/include/tmc/asio/aw_asio.hpp index 49b696c9..6114f757 100644 --- a/include/tmc/asio/aw_asio.hpp +++ b/include/tmc/asio/aw_asio.hpp @@ -22,6 +22,18 @@ #include #include +// asio's synchronous (error_code&) operations report failure through the ec +// out-parameter. In asio's default configuration they *also* return that same +// error_code redundantly; defining ASIO_NO_DEPRECATED / BOOST_ASIO_NO_DEPRECATED +// makes the return type void instead. This discards the redundant return - so it +// doesn't trip clang-tidy's bugprone-unused-return-value - while compiling +// correctly in either configuration. +#if defined(ASIO_NO_DEPRECATED) || defined(BOOST_ASIO_NO_DEPRECATED) +#define TMC_ASIO_SYNC_DISCARD(...) __VA_ARGS__ +#else +#define TMC_ASIO_SYNC_DISCARD(...) std::ignore = (__VA_ARGS__) +#endif + namespace tmc { namespace detail { struct AwAsioTag {}; diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index 4449a829..ff5c0e23 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -62,7 +62,7 @@ class SafeAcceptor { co_await mut_; error_code ec; - acceptor_.open(protocol, ec); + TMC_ASIO_SYNC_DISCARD(acceptor_.open(protocol, ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); @@ -74,7 +74,7 @@ class SafeAcceptor { co_await mut_; error_code ec; - acceptor_.set_option(option, ec); + TMC_ASIO_SYNC_DISCARD(acceptor_.set_option(option, ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); @@ -85,7 +85,7 @@ class SafeAcceptor { co_await mut_; error_code ec; - acceptor_.bind(endpoint, ec); + TMC_ASIO_SYNC_DISCARD(acceptor_.bind(endpoint, ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); @@ -98,7 +98,7 @@ class SafeAcceptor { co_await mut_; error_code ec; - acceptor_.listen(backlog, ec); + TMC_ASIO_SYNC_DISCARD(acceptor_.listen(backlog, ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); @@ -114,7 +114,7 @@ class SafeAcceptor { co_await mut_; error_code ec; - acceptor_.cancel(ec); + TMC_ASIO_SYNC_DISCARD(acceptor_.cancel(ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); @@ -125,7 +125,7 @@ class SafeAcceptor { co_await mut_; error_code ec; - acceptor_.close(ec); + TMC_ASIO_SYNC_DISCARD(acceptor_.close(ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 73a05bc9..dd7d44bc 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -72,7 +72,7 @@ class SafeSocket { // intermediate re-initiations would run on the I/O executor, outside the // mutex - this is implemented as a loop of single-shot reads, so every // initiation is serialized against other operations on this object. A - // concurrent cancel() or shutdown_full() takes effect at a chunk boundary. + // concurrent cancel() or close() takes effect at a chunk boundary. // // Only one read may be in flight at a time (the usual asio stream contract). template @@ -109,7 +109,7 @@ class SafeSocket { // intermediate re-initiations would run on the I/O executor, outside the // mutex - this is implemented as a loop of single-shot writes, so every // initiation is serialized against other operations on this object. A - // concurrent cancel() or shutdown_full() takes effect at a chunk boundary. + // concurrent cancel() or close() takes effect at a chunk boundary. // // Only one write may be in flight at a time (the usual asio stream contract). template @@ -145,86 +145,29 @@ class SafeSocket { co_await mut_; error_code ec; - socket_.cancel(ec); + TMC_ASIO_SYNC_DISCARD(socket_.cancel(ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); TMC_UNREACHABLE; } - // tmc::task - // shutdown(boost::asio::ip::tcp::socket::shutdown_type how) { - // co_await mut_; - - // error_code ec; - // socket_.shutdown(how, ec); - - // // Manual unlock is required since this coro didn't suspend - // co_await mut_.co_unlock(); - - // co_return ec; - // } - - // tmc::task close() { - // co_await mut_; - - // error_code ec; - // socket_.close(ec); + tmc::task shutdown(socket_type::shutdown_type how) { + co_await mut_; - // // Manual unlock is required since this coro didn't suspend - // co_await mut_.co_unlock(); + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.shutdown(how, ec)); - // co_return ec; - // } + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } - // Cancels pending operations, sends FIN, and closes the socket. Returns the - // first error encountered, except that `not_connected` from shutdown() is - // treated as success (the peer already closed the connection). - tmc::task shutdown_full() { + tmc::task close() { co_await mut_; - // TODO - may be useful to split this into cancel + shutdown_send, then - // drain the rest of incoming messages and then shutdown_recv and close(), - // if necessary to make the protocol shutdown properly graceful. Linux - // kernel may send RST if there is read pending data after the shutdown was - // processed. - - // The most graceful shutdown: - // On the close initiator side: - // 1. Wait until current write operation completes (this doesn't means that - // data are sent). - // 2. Call shutdown(SD_SEND/SHUT_WR). - // 3. Wait until read operation returns EOF. - // 4. Close socket. - - // On the other side: - // 1. Close starts if EOF is received. - // 2. Wait until current write operation completes. - // 3. Call shutdown(SD_SEND/SHUT_WR). - // 4. EOF was already received, so we can close the socket. - error_code ec; - - if (socket_.is_open()) { - // cancels pending operations (shutdown doesn't do this) - // this cannot be called on a closed socket, hence the is_open() check - socket_.cancel(ec); - // send FIN packet to other end - error_code shutdownEc; - socket_.shutdown(socket_type::shutdown_both, shutdownEc); - if (shutdownEc == tmc::detail::asio_impl::error::not_connected) { - shutdownEc = {}; - } - if (!ec) { - ec = shutdownEc; - } - // destroy the connection - error_code closeEc; - socket_.close(closeEc); - if (!ec) { - ec = closeEc; - } - } + TMC_ASIO_SYNC_DISCARD(socket_.close(ec)); // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); From 75de6910af02617adc2224ffba2fa6e70fa4f260 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 10:08:13 -0700 Subject: [PATCH 05/15] fix: is_open must also be mutex-protected --- include/tmc/asio/safe_acceptor.hpp | 12 ++++++++---- include/tmc/asio/safe_socket.hpp | 7 ++++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index ff5c0e23..343ee82a 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -56,7 +56,12 @@ class SafeAcceptor { acceptor_type& acceptor_unsafe() noexcept { return acceptor_; } const acceptor_type& acceptor_unsafe() const noexcept { return acceptor_; } - bool is_open() const noexcept { return acceptor_.is_open(); } + tmc::task is_open() noexcept { + co_await mut_; + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(acceptor_.is_open()); + TMC_UNREACHABLE; + } tmc::task open(protocol_type protocol) { co_await mut_; @@ -92,9 +97,8 @@ class SafeAcceptor { TMC_UNREACHABLE; } - tmc::task listen( - int backlog = tmc::detail::asio_impl::socket_base::max_listen_connections - ) { + tmc::task + listen(int backlog = tmc::detail::asio_impl::socket_base::max_listen_connections) { co_await mut_; error_code ec; diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index dd7d44bc..96d4477a 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -59,7 +59,12 @@ class SafeSocket { socket_type& socket_unsafe() noexcept { return socket_; } const socket_type& socket_unsafe() const noexcept { return socket_; } - bool is_open() const noexcept { return socket_.is_open(); } + tmc::task is_open() noexcept { + co_await mut_; + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(socket_.is_open()); + TMC_UNREACHABLE; + } tmc::task> async_connect(endpoint_type endpoint) { co_await mut_; From a487b008224c13bb83e5a0ee3fea5c471d4a523b Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 10:50:34 -0700 Subject: [PATCH 06/15] cancel multishot socket read/write reliably --- include/tmc/asio/safe_socket.hpp | 42 +++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 96d4477a..cf10c024 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -53,6 +53,13 @@ class SafeSocket { socket_type socket_; tmc::tiny_mutex mut_; + // Set true while a composed async_read()/async_write() is running, and + // cleared by cancel(). This closes the window where a cancel() lands between + // the composed operation's single-shot reads/writes - when nothing is pending + // on the socket for socket_.cancel() to hit. Only touched under mut_. + bool read_active_ = false; + bool write_active_ = false; + public: explicit SafeSocket(socket_type socket) : socket_(std::move(socket)) {} @@ -76,8 +83,7 @@ class SafeSocket { // (like `asio::async_read`). Unlike the asio composed operation - whose // intermediate re-initiations would run on the I/O executor, outside the // mutex - this is implemented as a loop of single-shot reads, so every - // initiation is serialized against other operations on this object. A - // concurrent cancel() or close() takes effect at a chunk boundary. + // initiation is serialized against other operations on this object. // // Only one read may be in flight at a time (the usual asio stream contract). template @@ -86,10 +92,21 @@ class SafeSocket { std::size_t total = 0; auto it = tmc::detail::asio_impl::buffer_sequence_begin(buffers); auto end = tmc::detail::asio_impl::buffer_sequence_end(buffers); + bool started = false; for (; it != end; ++it) { tmc::detail::asio_impl::mutable_buffer b = *it; while (b.size() != 0) { co_await mut_; + // A cancel() that landed between our single-shot reads (when nothing + // was pending for socket_.cancel() to hit) cleared read_active_. Abort + // here at the chunk boundary so the cancel is never silently dropped. + if (started && !read_active_) { + co_return std::tuple{ + error_code(tmc::detail::asio_impl::error::operation_aborted), total + }; + } + read_active_ = true; + started = true; auto [ec, n] = co_await socket_.async_read_some(b, tmc::aw_asio); total += n; b += n; @@ -113,8 +130,7 @@ class SafeSocket { // `asio::async_write`). Unlike the asio composed operation - whose // intermediate re-initiations would run on the I/O executor, outside the // mutex - this is implemented as a loop of single-shot writes, so every - // initiation is serialized against other operations on this object. A - // concurrent cancel() or close() takes effect at a chunk boundary. + // initiation is serialized against other operations on this object. // // Only one write may be in flight at a time (the usual asio stream contract). template @@ -123,10 +139,21 @@ class SafeSocket { std::size_t total = 0; auto it = tmc::detail::asio_impl::buffer_sequence_begin(buffers); auto end = tmc::detail::asio_impl::buffer_sequence_end(buffers); + bool started = false; for (; it != end; ++it) { tmc::detail::asio_impl::const_buffer b = *it; while (b.size() != 0) { co_await mut_; + // A cancel() that landed between our single-shot writes (when nothing + // was pending for socket_.cancel() to hit) cleared write_active_. Abort + // here at the chunk boundary so the cancel is never silently dropped. + if (started && !write_active_) { + co_return std::tuple{ + error_code(tmc::detail::asio_impl::error::operation_aborted), total + }; + } + write_active_ = true; + started = true; auto [ec, n] = co_await socket_.async_write_some(b, tmc::aw_asio); total += n; b += n; @@ -149,9 +176,16 @@ class SafeSocket { tmc::task cancel() { co_await mut_; + // Cancel any single-shot operation currently pending on the socket... error_code ec; TMC_ASIO_SYNC_DISCARD(socket_.cancel(ec)); + // ...and, in case a composed async_read()/async_write() is sitting between + // its single-shot operations (where there is nothing pending for the call + // above to hit), signal it to abort when it re-acquires the mutex. + read_active_ = false; + write_active_ = false; + // Manual unlock is required since this coro didn't suspend co_await mut_.co_unlock_return(ec); TMC_UNREACHABLE; From 33fd1ddbaf3bc3cda442561a8fa543d9c2cb02d8 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 13:46:44 -0700 Subject: [PATCH 07/15] match library naming convention / add comments --- include/tmc/asio/safe_acceptor.hpp | 21 +++++++++++++---- include/tmc/asio/safe_socket.hpp | 26 +++++++++++++++++---- include/tmc/asio/safe_timer.hpp | 37 +++++++++++++++++++++--------- 3 files changed, 63 insertions(+), 21 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index 343ee82a..442c2af1 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -31,10 +31,18 @@ namespace asio_impl = ::asio; #endif } // namespace detail -// Type that serializes acceptor operations so they can be initiated safely from -// different coroutines. The tiny_mutex is released automatically when the -// coroutine next suspends. -class SafeAcceptor { +/// Type that serializes Asio acceptor operations so they can be initiated safely from +/// different coroutines. Unlike a strand, this only serializes the initiation of +/// operations; it does not serialize full handlers. +/// +/// Methods behave exactly as the underlying object's methods with the same name, except: +/// - methods are thread-safe +/// - methods implicitly use the `tmc::aw_asio` completion +/// +/// The safe_acceptor must outlive every task that uses it, including any task still +/// waiting to acquire its mutex. Destroying it while such tasks exist is a +/// use-after-free. +class safe_acceptor { public: using acceptor_type = tmc::detail::asio_impl::ip::tcp::acceptor; using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; @@ -51,9 +59,12 @@ class SafeAcceptor { tmc::tiny_mutex mut_; public: - explicit SafeAcceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} + /// Constructs this from an Asio ip::tcp::acceptor. + explicit safe_acceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} + /// Allows access to the underlying (unsynchronized) Asio object. acceptor_type& acceptor_unsafe() noexcept { return acceptor_; } + /// Allows access to the underlying (unsynchronized) Asio object. const acceptor_type& acceptor_unsafe() const noexcept { return acceptor_; } tmc::task is_open() noexcept { diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index cf10c024..4e05b30d 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -36,10 +36,22 @@ namespace asio_impl = ::asio; #endif } // namespace detail -// Type that serializes socket operations so they can be initiated safely from -// different coroutines. The tiny_mutex is released automatically when the -// coroutine next suspends. -class SafeSocket { +/// Type that serializes Asio socket operations so they can be initiated safely from +/// different coroutines. Unlike a strand, this only serializes the initiation of +/// operations; it does not serialize full handlers. +/// +/// It does not prevent overlapping reads and writes. The user is responsible +/// for ensuring at most 1 read and 1 write are active at any time, per the usual Asio +/// contract. +/// +/// Methods behave exactly as the underlying object's methods with the same name, except: +/// - methods are thread-safe +/// - methods implicitly use the `tmc::aw_asio` completion +/// +/// The safe_socket must outlive every task that uses it, including any task still +/// waiting to acquire its mutex. Destroying it while such tasks exist is a +/// use-after-free. +class safe_socket { public: using socket_type = tmc::detail::asio_impl::ip::tcp::socket; using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; @@ -61,9 +73,13 @@ class SafeSocket { bool write_active_ = false; public: - explicit SafeSocket(socket_type socket) : socket_(std::move(socket)) {} + /// Constructs this from an Asio ip::tcp::socket. + explicit safe_socket(socket_type socket) : socket_(std::move(socket)) {} + /// Allows access to the underlying (unsynchronized) Asio object. socket_type& socket_unsafe() noexcept { return socket_; } + + /// Allows access to the underlying (unsynchronized) Asio object. const socket_type& socket_unsafe() const noexcept { return socket_; } tmc::task is_open() noexcept { diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index e9de8afc..2202420e 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -19,7 +19,6 @@ #include #endif -#include #include #include #include @@ -33,10 +32,18 @@ namespace asio_impl = ::asio; #endif } // namespace detail -// Type that serializes timer operations so expiry updates and waits can be -// initiated safely from different coroutines. The tiny_mutex is released -// automatically when the coroutine next suspends. -class SafeTimer { +/// Type that serializes Asio timer operations so expiry updates and waits can be +/// initiated safely from different coroutines. Unlike a strand, this only serializes the +/// initiation of operations; it does not serialize full handlers. +/// +/// Methods behave exactly as the underlying object's methods with the same name, except: +/// - methods are thread-safe +/// - methods implicitly use the `tmc::aw_asio` completion +/// +/// The safe_timer must outlive every task that uses it, +/// including any task still waiting to acquire its mutex. Destroying it while such tasks +/// exist is a use-after-free. +class safe_timer { public: using timer_type = tmc::detail::asio_impl::steady_timer; #ifdef TMC_USE_BOOST_ASIO @@ -52,26 +59,34 @@ class SafeTimer { tmc::tiny_mutex mut_; public: - explicit SafeTimer(timer_type timer) : timer_(std::move(timer)) {} + /// Constructs this from an Asio steady_timer. + explicit safe_timer(timer_type timer) : timer_(std::move(timer)) {} + /// Allows access to the underlying (unsynchronized) Asio object. timer_type& timer_unsafe() noexcept { return timer_; } + /// Allows access to the underlying (unsynchronized) Asio object. const timer_type& timer_unsafe() const noexcept { return timer_; } + /// Initiates a new wait. Does not modify the expiry or cancel outstanding waits. tmc::task> async_wait() { co_await mut_; co_return co_await timer_.async_wait(tmc::aw_asio); } - template - tmc::task> - async_wait_for(std::chrono::duration expiry) { + /// Resets the timer's expiry and then waits for it. Changing the expiry cancels + /// every outstanding wait on this timer before the new wait begins; those + /// cancelled waits complete with operation_aborted. + tmc::task> async_wait_for(duration expiry) { co_await mut_; timer_.expires_after(expiry); co_return co_await timer_.async_wait(tmc::aw_asio); } + /// Sets the timer's expiry and then waits for it. Like async_wait_for, changing + /// the expiry cancels every outstanding wait before the new wait begins; those + /// cancelled waits complete with operation_aborted. tmc::task> async_wait_until(time_point expiry) { co_await mut_; @@ -79,8 +94,8 @@ class SafeTimer { co_return co_await timer_.async_wait(tmc::aw_asio); } - // Cancels any outstanding waits, which will complete with - // `operation_aborted`. Returns the number of waits that were cancelled. + /// Cancels any outstanding waits, which will complete with + /// `operation_aborted`. Returns the number of waits that were cancelled. tmc::task cancel() { co_await mut_; From a11a219ff0ac9974562a122353bffaa08447974e Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 14:56:56 -0700 Subject: [PATCH 08/15] add remaining Asio methods --- include/tmc/asio/safe_acceptor.hpp | 134 +++++++++++++++++ include/tmc/asio/safe_socket.hpp | 225 +++++++++++++++++++++++++++++ include/tmc/asio/safe_timer.hpp | 56 ++++++- 3 files changed, 410 insertions(+), 5 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index 442c2af1..4d81d834 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -48,6 +48,9 @@ class safe_acceptor { using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; using protocol_type = tmc::detail::asio_impl::ip::tcp; using socket_type = tmc::detail::asio_impl::ip::tcp::socket; + using executor_type = acceptor_type::executor_type; + using native_handle_type = acceptor_type::native_handle_type; + using wait_type = acceptor_type::wait_type; #ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; #else @@ -125,6 +128,21 @@ class safe_acceptor { co_return co_await acceptor_.async_accept(tmc::aw_asio); } + tmc::task> async_accept_endpoint() { + co_await mut_; + // `peer` is filled before the completion handler runs; it lives in this + // coroutine frame, so it outlives the async operation. + endpoint_type peer; + auto [ec, sock] = co_await acceptor_.async_accept(peer, tmc::aw_asio); + co_return std::tuple{ec, std::move(sock), std::move(peer)}; + } + + tmc::task> async_wait(wait_type w) { + co_await mut_; + + co_return co_await acceptor_.async_wait(w, tmc::aw_asio); + } + tmc::task cancel() { co_await mut_; @@ -146,6 +164,122 @@ class safe_acceptor { co_await mut_.co_unlock_return(ec); TMC_UNREACHABLE; } + + tmc::task get_executor() { + co_await mut_; + + executor_type ex = acceptor_.get_executor(); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::move(ex)); + TMC_UNREACHABLE; + } + + tmc::task + assign(protocol_type protocol, native_handle_type native_acceptor) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(acceptor_.assign(protocol, native_acceptor, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task> release() { + co_await mut_; + + error_code ec; + native_handle_type handle = acceptor_.release(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, handle}); + TMC_UNREACHABLE; + } + + template + tmc::task> + get_option(GettableSocketOption option) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(acceptor_.get_option(option, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(option)}); + TMC_UNREACHABLE; + } + + template + tmc::task> + io_control(IoControlCommand command) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(acceptor_.io_control(command, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(command)}); + TMC_UNREACHABLE; + } + + tmc::task non_blocking() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(acceptor_.non_blocking()); + TMC_UNREACHABLE; + } + + tmc::task non_blocking(bool mode) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(acceptor_.non_blocking(mode, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task native_non_blocking() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(acceptor_.native_non_blocking()); + TMC_UNREACHABLE; + } + + tmc::task native_non_blocking(bool mode) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(acceptor_.native_non_blocking(mode, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task> local_endpoint() { + co_await mut_; + + error_code ec; + endpoint_type ep = acceptor_.local_endpoint(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(ep)}); + TMC_UNREACHABLE; + } + + tmc::task native_handle() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(acceptor_.native_handle()); + TMC_UNREACHABLE; + } }; } // namespace tmc diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 4e05b30d..3f2087ab 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -55,6 +55,11 @@ class safe_socket { public: using socket_type = tmc::detail::asio_impl::ip::tcp::socket; using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; + using protocol_type = socket_type::protocol_type; + using executor_type = socket_type::executor_type; + using native_handle_type = socket_type::native_handle_type; + using wait_type = socket_type::wait_type; + using message_flags = socket_type::message_flags; #ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; #else @@ -228,6 +233,226 @@ class safe_socket { co_await mut_.co_unlock_return(ec); TMC_UNREACHABLE; } + + tmc::task> async_wait(wait_type w) { + co_await mut_; + + co_return co_await socket_.async_wait(w, tmc::aw_asio); + } + + template + tmc::task> async_send(ConstBufferSequence buffers) { + co_await mut_; + + co_return co_await socket_.async_send(std::move(buffers), tmc::aw_asio); + } + + template + tmc::task> + async_send(ConstBufferSequence buffers, message_flags flags) { + co_await mut_; + + co_return co_await socket_.async_send(std::move(buffers), flags, tmc::aw_asio); + } + + template + tmc::task> + async_receive(MutableBufferSequence buffers) { + co_await mut_; + + co_return co_await socket_.async_receive(std::move(buffers), tmc::aw_asio); + } + + template + tmc::task> + async_receive(MutableBufferSequence buffers, message_flags flags) { + co_await mut_; + + co_return co_await socket_.async_receive(std::move(buffers), flags, tmc::aw_asio); + } + + tmc::task get_executor() { + co_await mut_; + + executor_type ex = socket_.get_executor(); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::move(ex)); + TMC_UNREACHABLE; + } + + tmc::task open(protocol_type protocol) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.open(protocol, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task assign(protocol_type protocol, native_handle_type native_socket) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.assign(protocol, native_socket, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task> release() { + co_await mut_; + + error_code ec; + native_handle_type handle = socket_.release(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, handle}); + TMC_UNREACHABLE; + } + + tmc::task bind(endpoint_type endpoint) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.bind(endpoint, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + template + tmc::task set_option(SettableSocketOption option) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.set_option(option, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + template + tmc::task> + get_option(GettableSocketOption option) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.get_option(option, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(option)}); + TMC_UNREACHABLE; + } + + template + tmc::task> + io_control(IoControlCommand command) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.io_control(command, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(command)}); + TMC_UNREACHABLE; + } + + /// Returns the non-blocking mode of the socket. + tmc::task non_blocking() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(socket_.non_blocking()); + TMC_UNREACHABLE; + } + + tmc::task non_blocking(bool mode) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.non_blocking(mode, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task native_non_blocking() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(socket_.native_non_blocking()); + TMC_UNREACHABLE; + } + + tmc::task native_non_blocking(bool mode) { + co_await mut_; + + error_code ec; + TMC_ASIO_SYNC_DISCARD(socket_.native_non_blocking(mode, ec)); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(ec); + TMC_UNREACHABLE; + } + + tmc::task> local_endpoint() { + co_await mut_; + + error_code ec; + endpoint_type ep = socket_.local_endpoint(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(ep)}); + TMC_UNREACHABLE; + } + + tmc::task> remote_endpoint() { + co_await mut_; + + error_code ec; + endpoint_type ep = socket_.remote_endpoint(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, std::move(ep)}); + TMC_UNREACHABLE; + } + + tmc::task> at_mark() { + co_await mut_; + + error_code ec; + bool marked = socket_.at_mark(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, marked}); + TMC_UNREACHABLE; + } + + tmc::task> available() { + co_await mut_; + + error_code ec; + std::size_t n = socket_.available(ec); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::tuple{ec, n}); + TMC_UNREACHABLE; + } + + tmc::task native_handle() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(socket_.native_handle()); + TMC_UNREACHABLE; + } }; } // namespace tmc diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index 2202420e..c8a8a48b 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -53,6 +53,7 @@ class safe_timer { #endif using duration = timer_type::duration; using time_point = timer_type::time_point; + using executor_type = timer_type::executor_type; private: timer_type timer_; @@ -67,14 +68,13 @@ class safe_timer { /// Allows access to the underlying (unsynchronized) Asio object. const timer_type& timer_unsafe() const noexcept { return timer_; } - /// Initiates a new wait. Does not modify the expiry or cancel outstanding waits. tmc::task> async_wait() { co_await mut_; co_return co_await timer_.async_wait(tmc::aw_asio); } - /// Resets the timer's expiry and then waits for it. Changing the expiry cancels + /// Combines expires_after and async_wait. Changing the expiry cancels /// every outstanding wait on this timer before the new wait begins; those /// cancelled waits complete with operation_aborted. tmc::task> async_wait_for(duration expiry) { @@ -84,7 +84,7 @@ class safe_timer { co_return co_await timer_.async_wait(tmc::aw_asio); } - /// Sets the timer's expiry and then waits for it. Like async_wait_for, changing + /// Combines expires_at and async_wait. Like async_wait_for, changing /// the expiry cancels every outstanding wait before the new wait begins; those /// cancelled waits complete with operation_aborted. tmc::task> async_wait_until(time_point expiry) { @@ -94,8 +94,6 @@ class safe_timer { co_return co_await timer_.async_wait(tmc::aw_asio); } - /// Cancels any outstanding waits, which will complete with - /// `operation_aborted`. Returns the number of waits that were cancelled. tmc::task cancel() { co_await mut_; @@ -105,6 +103,54 @@ class safe_timer { co_await mut_.co_unlock_return(count); TMC_UNREACHABLE; } + + tmc::task cancel_one() { + co_await mut_; + + std::size_t count = timer_.cancel_one(); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(count); + TMC_UNREACHABLE; + } + + tmc::task expiry() { + co_await mut_; + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(timer_.expiry()); + TMC_UNREACHABLE; + } + + tmc::task expires_at(time_point expiry) { + co_await mut_; + + std::size_t count = timer_.expires_at(expiry); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(count); + TMC_UNREACHABLE; + } + + tmc::task expires_after(duration expiry) { + co_await mut_; + + std::size_t count = timer_.expires_after(expiry); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(count); + TMC_UNREACHABLE; + } + + tmc::task get_executor() { + co_await mut_; + + executor_type ex = timer_.get_executor(); + + // Manual unlock is required since this coro didn't suspend + co_await mut_.co_unlock_return(std::move(ex)); + TMC_UNREACHABLE; + } }; } // namespace tmc From 67637ef6584c27014c3dea5effcfff6381e7d2ac Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 14:58:31 -0700 Subject: [PATCH 09/15] formatting --- include/tmc/asio/safe_timer.hpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index c8a8a48b..3fa7fc92 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -40,9 +40,8 @@ namespace asio_impl = ::asio; /// - methods are thread-safe /// - methods implicitly use the `tmc::aw_asio` completion /// -/// The safe_timer must outlive every task that uses it, -/// including any task still waiting to acquire its mutex. Destroying it while such tasks -/// exist is a use-after-free. +/// The safe_timer must outlive every task that uses it, including any task still waiting +/// to acquire its mutex. Destroying it while such tasks exist is a use-after-free. class safe_timer { public: using timer_type = tmc::detail::asio_impl::steady_timer; From d510e3f5ecc8fca4cada4af87936253424318411 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 16:09:02 -0700 Subject: [PATCH 10/15] make acceptor/socket templated on protocol type --- include/tmc/asio/safe_acceptor.hpp | 28 +++++++++++++-------- include/tmc/asio/safe_socket.hpp | 40 ++++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 20 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index 4d81d834..75ba267d 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -42,15 +42,23 @@ namespace asio_impl = ::asio; /// The safe_acceptor must outlive every task that uses it, including any task still /// waiting to acquire its mutex. Destroying it while such tasks exist is a /// use-after-free. -class safe_acceptor { +/// +/// Templated on the underlying Asio acceptor type so it can serialize acceptors +/// for any AcceptableProtocol (e.g. `ip::tcp`, `local::stream_protocol`). All +/// associated types are derived from `Acceptor`. +template +class basic_safe_acceptor { public: - using acceptor_type = tmc::detail::asio_impl::ip::tcp::acceptor; - using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; - using protocol_type = tmc::detail::asio_impl::ip::tcp; - using socket_type = tmc::detail::asio_impl::ip::tcp::socket; - using executor_type = acceptor_type::executor_type; - using native_handle_type = acceptor_type::native_handle_type; - using wait_type = acceptor_type::wait_type; + using acceptor_type = Acceptor; + using protocol_type = typename Acceptor::protocol_type; + using endpoint_type = typename Acceptor::endpoint_type; + using executor_type = typename Acceptor::executor_type; + using native_handle_type = typename Acceptor::native_handle_type; + using wait_type = typename Acceptor::wait_type; + // The socket type produced by `async_accept()`: the protocol's socket rebound + // to the acceptor's executor (matches Asio's own accept-return type). + using socket_type = + typename protocol_type::socket::template rebind_executor::other; #ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; #else @@ -62,8 +70,8 @@ class safe_acceptor { tmc::tiny_mutex mut_; public: - /// Constructs this from an Asio ip::tcp::acceptor. - explicit safe_acceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} + /// Constructs this from an Asio acceptor. + explicit basic_safe_acceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} /// Allows access to the underlying (unsynchronized) Asio object. acceptor_type& acceptor_unsafe() noexcept { return acceptor_; } diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 3f2087ab..c680ddf2 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -51,15 +51,23 @@ namespace asio_impl = ::asio; /// The safe_socket must outlive every task that uses it, including any task still /// waiting to acquire its mutex. Destroying it while such tasks exist is a /// use-after-free. -class safe_socket { +/// +/// Templated on the underlying Asio socket type so it can serialize sockets for +/// any protocol. The stream-oriented composed operations (`async_read`, +/// `async_write`) and their single-shot forms (`async_read_some`, +/// `async_write_some`) are constrained to stream sockets; on a socket type that +/// lacks them (e.g. a datagram socket) they are not present. All other operations work +/// for any socket. +template +class basic_safe_socket { public: - using socket_type = tmc::detail::asio_impl::ip::tcp::socket; - using endpoint_type = tmc::detail::asio_impl::ip::tcp::endpoint; - using protocol_type = socket_type::protocol_type; - using executor_type = socket_type::executor_type; - using native_handle_type = socket_type::native_handle_type; - using wait_type = socket_type::wait_type; - using message_flags = socket_type::message_flags; + using socket_type = Socket; + using protocol_type = typename Socket::protocol_type; + using endpoint_type = typename Socket::endpoint_type; + using executor_type = typename Socket::executor_type; + using native_handle_type = typename Socket::native_handle_type; + using wait_type = typename Socket::wait_type; + using message_flags = typename Socket::message_flags; #ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; #else @@ -78,8 +86,8 @@ class safe_socket { bool write_active_ = false; public: - /// Constructs this from an Asio ip::tcp::socket. - explicit safe_socket(socket_type socket) : socket_(std::move(socket)) {} + /// Constructs this from an Asio socket. + explicit basic_safe_socket(socket_type socket) : socket_(std::move(socket)) {} /// Allows access to the underlying (unsynchronized) Asio object. socket_type& socket_unsafe() noexcept { return socket_; } @@ -108,6 +116,9 @@ class safe_socket { // // Only one read may be in flight at a time (the usual asio stream contract). template + requires requires(socket_type& S, MutableBufferSequence B) { + S.async_read_some(B, tmc::aw_asio); + } tmc::task> async_read(MutableBufferSequence buffers) { std::size_t total = 0; @@ -140,6 +151,9 @@ class safe_socket { } template + requires requires(socket_type& S, MutableBufferSequence B) { + S.async_read_some(B, tmc::aw_asio); + } tmc::task> async_read_some(MutableBufferSequence buffers) { co_await mut_; @@ -155,6 +169,9 @@ class safe_socket { // // Only one write may be in flight at a time (the usual asio stream contract). template + requires requires(socket_type& S, ConstBufferSequence B) { + S.async_write_some(B, tmc::aw_asio); + } tmc::task> async_write(ConstBufferSequence buffers) { std::size_t total = 0; @@ -187,6 +204,9 @@ class safe_socket { } template + requires requires(socket_type& S, ConstBufferSequence B) { + S.async_write_some(B, tmc::aw_asio); + } tmc::task> async_write_some(ConstBufferSequence buffers) { co_await mut_; From ec7990f39ad23831d9dbd3d79650f2e4e00653c6 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 16:36:18 -0700 Subject: [PATCH 11/15] rename asio namespace alias --- include/tmc/asio/safe_acceptor.hpp | 8 ++++---- include/tmc/asio/safe_socket.hpp | 22 +++++++++++----------- include/tmc/asio/safe_timer.hpp | 6 +++--- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index 75ba267d..bd563a2a 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -25,9 +25,9 @@ namespace tmc { namespace detail { #ifdef TMC_USE_BOOST_ASIO -namespace asio_impl = ::boost::asio; +namespace asio_ns = ::boost::asio; #else -namespace asio_impl = ::asio; +namespace asio_ns = ::asio; #endif } // namespace detail @@ -46,7 +46,7 @@ namespace asio_impl = ::asio; /// Templated on the underlying Asio acceptor type so it can serialize acceptors /// for any AcceptableProtocol (e.g. `ip::tcp`, `local::stream_protocol`). All /// associated types are derived from `Acceptor`. -template +template class basic_safe_acceptor { public: using acceptor_type = Acceptor; @@ -120,7 +120,7 @@ class basic_safe_acceptor { } tmc::task - listen(int backlog = tmc::detail::asio_impl::socket_base::max_listen_connections) { + listen(int backlog = tmc::detail::asio_ns::socket_base::max_listen_connections) { co_await mut_; error_code ec; diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index c680ddf2..d59c6916 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -30,9 +30,9 @@ namespace tmc { namespace detail { #ifdef TMC_USE_BOOST_ASIO -namespace asio_impl = ::boost::asio; +namespace asio_ns = ::boost::asio; #else -namespace asio_impl = ::asio; +namespace asio_ns = ::asio; #endif } // namespace detail @@ -58,7 +58,7 @@ namespace asio_impl = ::asio; /// `async_write_some`) are constrained to stream sockets; on a socket type that /// lacks them (e.g. a datagram socket) they are not present. All other operations work /// for any socket. -template +template class basic_safe_socket { public: using socket_type = Socket; @@ -122,11 +122,11 @@ class basic_safe_socket { tmc::task> async_read(MutableBufferSequence buffers) { std::size_t total = 0; - auto it = tmc::detail::asio_impl::buffer_sequence_begin(buffers); - auto end = tmc::detail::asio_impl::buffer_sequence_end(buffers); + auto it = tmc::detail::asio_ns::buffer_sequence_begin(buffers); + auto end = tmc::detail::asio_ns::buffer_sequence_end(buffers); bool started = false; for (; it != end; ++it) { - tmc::detail::asio_impl::mutable_buffer b = *it; + tmc::detail::asio_ns::mutable_buffer b = *it; while (b.size() != 0) { co_await mut_; // A cancel() that landed between our single-shot reads (when nothing @@ -134,7 +134,7 @@ class basic_safe_socket { // here at the chunk boundary so the cancel is never silently dropped. if (started && !read_active_) { co_return std::tuple{ - error_code(tmc::detail::asio_impl::error::operation_aborted), total + error_code(tmc::detail::asio_ns::error::operation_aborted), total }; } read_active_ = true; @@ -175,11 +175,11 @@ class basic_safe_socket { tmc::task> async_write(ConstBufferSequence buffers) { std::size_t total = 0; - auto it = tmc::detail::asio_impl::buffer_sequence_begin(buffers); - auto end = tmc::detail::asio_impl::buffer_sequence_end(buffers); + auto it = tmc::detail::asio_ns::buffer_sequence_begin(buffers); + auto end = tmc::detail::asio_ns::buffer_sequence_end(buffers); bool started = false; for (; it != end; ++it) { - tmc::detail::asio_impl::const_buffer b = *it; + tmc::detail::asio_ns::const_buffer b = *it; while (b.size() != 0) { co_await mut_; // A cancel() that landed between our single-shot writes (when nothing @@ -187,7 +187,7 @@ class basic_safe_socket { // here at the chunk boundary so the cancel is never silently dropped. if (started && !write_active_) { co_return std::tuple{ - error_code(tmc::detail::asio_impl::error::operation_aborted), total + error_code(tmc::detail::asio_ns::error::operation_aborted), total }; } write_active_ = true; diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index 3fa7fc92..b6298cc9 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -26,9 +26,9 @@ namespace tmc { namespace detail { #ifdef TMC_USE_BOOST_ASIO -namespace asio_impl = ::boost::asio; +namespace asio_ns = ::boost::asio; #else -namespace asio_impl = ::asio; +namespace asio_ns = ::asio; #endif } // namespace detail @@ -44,7 +44,7 @@ namespace asio_impl = ::asio; /// to acquire its mutex. Destroying it while such tasks exist is a use-after-free. class safe_timer { public: - using timer_type = tmc::detail::asio_impl::steady_timer; + using timer_type = tmc::detail::asio_ns::steady_timer; #ifdef TMC_USE_BOOST_ASIO using error_code = boost::system::error_code; #else From 6799b623a3c9e4010d4d5a8d186f402c37383286 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 16:39:42 -0700 Subject: [PATCH 12/15] rename to asio_safe_* --- include/tmc/asio/safe_acceptor.hpp | 6 +++--- include/tmc/asio/safe_socket.hpp | 6 +++--- include/tmc/asio/safe_timer.hpp | 9 +++++---- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index bd563a2a..b646b543 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -39,7 +39,7 @@ namespace asio_ns = ::asio; /// - methods are thread-safe /// - methods implicitly use the `tmc::aw_asio` completion /// -/// The safe_acceptor must outlive every task that uses it, including any task still +/// The asio_safe_acceptor must outlive every task that uses it, including any task still /// waiting to acquire its mutex. Destroying it while such tasks exist is a /// use-after-free. /// @@ -47,7 +47,7 @@ namespace asio_ns = ::asio; /// for any AcceptableProtocol (e.g. `ip::tcp`, `local::stream_protocol`). All /// associated types are derived from `Acceptor`. template -class basic_safe_acceptor { +class asio_safe_acceptor { public: using acceptor_type = Acceptor; using protocol_type = typename Acceptor::protocol_type; @@ -71,7 +71,7 @@ class basic_safe_acceptor { public: /// Constructs this from an Asio acceptor. - explicit basic_safe_acceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} + explicit asio_safe_acceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} /// Allows access to the underlying (unsynchronized) Asio object. acceptor_type& acceptor_unsafe() noexcept { return acceptor_; } diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index d59c6916..344634a9 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -48,7 +48,7 @@ namespace asio_ns = ::asio; /// - methods are thread-safe /// - methods implicitly use the `tmc::aw_asio` completion /// -/// The safe_socket must outlive every task that uses it, including any task still +/// The asio_safe_socket must outlive every task that uses it, including any task still /// waiting to acquire its mutex. Destroying it while such tasks exist is a /// use-after-free. /// @@ -59,7 +59,7 @@ namespace asio_ns = ::asio; /// lacks them (e.g. a datagram socket) they are not present. All other operations work /// for any socket. template -class basic_safe_socket { +class asio_safe_socket { public: using socket_type = Socket; using protocol_type = typename Socket::protocol_type; @@ -87,7 +87,7 @@ class basic_safe_socket { public: /// Constructs this from an Asio socket. - explicit basic_safe_socket(socket_type socket) : socket_(std::move(socket)) {} + explicit asio_safe_socket(socket_type socket) : socket_(std::move(socket)) {} /// Allows access to the underlying (unsynchronized) Asio object. socket_type& socket_unsafe() noexcept { return socket_; } diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index b6298cc9..dae7f479 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -40,9 +40,10 @@ namespace asio_ns = ::asio; /// - methods are thread-safe /// - methods implicitly use the `tmc::aw_asio` completion /// -/// The safe_timer must outlive every task that uses it, including any task still waiting -/// to acquire its mutex. Destroying it while such tasks exist is a use-after-free. -class safe_timer { +/// The asio_safe_timer must outlive every task that uses it, including any task still +/// waiting to acquire its mutex. Destroying it while such tasks exist is a +/// use-after-free. +class asio_safe_timer { public: using timer_type = tmc::detail::asio_ns::steady_timer; #ifdef TMC_USE_BOOST_ASIO @@ -60,7 +61,7 @@ class safe_timer { public: /// Constructs this from an Asio steady_timer. - explicit safe_timer(timer_type timer) : timer_(std::move(timer)) {} + explicit asio_safe_timer(timer_type timer) : timer_(std::move(timer)) {} /// Allows access to the underlying (unsynchronized) Asio object. timer_type& timer_unsafe() noexcept { return timer_; } From bad4a421944d16b1c2f4626bc21cdb53c3b02776 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 17:20:36 -0700 Subject: [PATCH 13/15] add constructor argument deduction guides --- include/tmc/asio/safe_acceptor.hpp | 2 ++ include/tmc/asio/safe_socket.hpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index b646b543..dd4a0a3b 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -290,4 +290,6 @@ class asio_safe_acceptor { } }; +template asio_safe_acceptor(Acceptor) -> asio_safe_acceptor; + } // namespace tmc diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 344634a9..6ddca410 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -475,4 +475,6 @@ class asio_safe_socket { } }; +template asio_safe_socket(Socket) -> asio_safe_socket; + } // namespace tmc From dfac86b3aa0ffed484bc8005d3282bb3122bde97 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Tue, 14 Jul 2026 18:06:34 -0700 Subject: [PATCH 14/15] tiny_mutex becomes movable --- include/tmc/detail/tiny_mutex.hpp | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/include/tmc/detail/tiny_mutex.hpp b/include/tmc/detail/tiny_mutex.hpp index 8f7ed220..2e25c286 100644 --- a/include/tmc/detail/tiny_mutex.hpp +++ b/include/tmc/detail/tiny_mutex.hpp @@ -146,6 +146,30 @@ class tiny_mutex { public: inline tiny_mutex() noexcept : state(new tmc::detail::tiny_mutex_state) {} + /// Move construction transfers ownership of the shared state. The refcount is + /// unchanged (ownership moves, it is not shared). Do not move a mutex while + /// another thread may be concurrently locking it. + inline tiny_mutex(tiny_mutex&& Other) noexcept : state(Other.state) { + Other.state = nullptr; + } + + /// Move assignment releases this mutex's current state (following the same + /// "no queued waiters" contract as destruction) and adopts Other's. Do not + /// move a mutex while another thread may be concurrently locking either one. + inline tiny_mutex& operator=(tiny_mutex&& Other) noexcept { + if (this == &Other) { + return *this; + } + if (state != nullptr) { + // 0 (no waiters) or 1 (a runner is active with an empty queue) are valid. + assert(state->waiters.load(std::memory_order_acquire) < 2); + tmc::detail::release_tiny_mutex_state(state); + } + state = Other.state; + Other.state = nullptr; + return *this; + } + /// Returns true if a runner is currently executing queued work for the mutex. /// This value is not guaranteed to be consistent with any other operation. inline bool is_locked() noexcept { @@ -214,8 +238,6 @@ class tiny_mutex { private: tiny_mutex(tiny_mutex const& Other) = delete; tiny_mutex& operator=(tiny_mutex const& Other) = delete; - tiny_mutex(tiny_mutex&& Other) = delete; - tiny_mutex& operator=(tiny_mutex&& Other) = delete; }; inline std::coroutine_handle<> @@ -283,6 +305,9 @@ inline tmc::task tiny_mutex::run_loop(tmc::detail::tiny_mutex_state* State inline tiny_mutex::~tiny_mutex() { auto* State = state; + if (State == nullptr) { + return; // moved-from + } // 0 (no waiters) or 1 (this is the running task) are valid assert(State->waiters.load(std::memory_order_acquire) < 2); tmc::detail::release_tiny_mutex_state(State); From 2966a644f50b63a7612b1c8ebdf29797b20ef4c1 Mon Sep 17 00:00:00 2001 From: tzcnt Date: Wed, 15 Jul 2026 08:38:54 -0700 Subject: [PATCH 15/15] rename unwrapper functions to inner() --- include/tmc/asio/safe_acceptor.hpp | 4 ++-- include/tmc/asio/safe_socket.hpp | 4 ++-- include/tmc/asio/safe_timer.hpp | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/include/tmc/asio/safe_acceptor.hpp b/include/tmc/asio/safe_acceptor.hpp index dd4a0a3b..dbe8062d 100644 --- a/include/tmc/asio/safe_acceptor.hpp +++ b/include/tmc/asio/safe_acceptor.hpp @@ -74,9 +74,9 @@ class asio_safe_acceptor { explicit asio_safe_acceptor(acceptor_type acceptor) : acceptor_(std::move(acceptor)) {} /// Allows access to the underlying (unsynchronized) Asio object. - acceptor_type& acceptor_unsafe() noexcept { return acceptor_; } + acceptor_type& inner() noexcept { return acceptor_; } /// Allows access to the underlying (unsynchronized) Asio object. - const acceptor_type& acceptor_unsafe() const noexcept { return acceptor_; } + const acceptor_type& inner() const noexcept { return acceptor_; } tmc::task is_open() noexcept { co_await mut_; diff --git a/include/tmc/asio/safe_socket.hpp b/include/tmc/asio/safe_socket.hpp index 6ddca410..bf663eb1 100644 --- a/include/tmc/asio/safe_socket.hpp +++ b/include/tmc/asio/safe_socket.hpp @@ -90,10 +90,10 @@ class asio_safe_socket { explicit asio_safe_socket(socket_type socket) : socket_(std::move(socket)) {} /// Allows access to the underlying (unsynchronized) Asio object. - socket_type& socket_unsafe() noexcept { return socket_; } + socket_type& inner() noexcept { return socket_; } /// Allows access to the underlying (unsynchronized) Asio object. - const socket_type& socket_unsafe() const noexcept { return socket_; } + const socket_type& inner() const noexcept { return socket_; } tmc::task is_open() noexcept { co_await mut_; diff --git a/include/tmc/asio/safe_timer.hpp b/include/tmc/asio/safe_timer.hpp index dae7f479..f0c15ff1 100644 --- a/include/tmc/asio/safe_timer.hpp +++ b/include/tmc/asio/safe_timer.hpp @@ -64,9 +64,9 @@ class asio_safe_timer { explicit asio_safe_timer(timer_type timer) : timer_(std::move(timer)) {} /// Allows access to the underlying (unsynchronized) Asio object. - timer_type& timer_unsafe() noexcept { return timer_; } + timer_type& inner() noexcept { return timer_; } /// Allows access to the underlying (unsynchronized) Asio object. - const timer_type& timer_unsafe() const noexcept { return timer_; } + const timer_type& inner() const noexcept { return timer_; } tmc::task> async_wait() { co_await mut_;