diff --git a/CMakeLists.txt b/CMakeLists.txt index 7b87e89c..bb7fa83d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,7 +13,9 @@ endif() include("cmake/compat_find.cmake") find_package(Threads REQUIRED) -find_package(CapnProto 0.9 NO_MODULE) +# 0.10.3 is the oldest version with CallContextHook::from() that is not +# affected by CVE-2022-46149 (https://github.com/advisories/GHSA-qqff-4vw4-f6hx). +find_package(CapnProto 0.10.3 NO_MODULE) if(NOT CapnProto_FOUND) message(FATAL_ERROR "Cap'n Proto is required but was not found.\n" @@ -23,59 +25,21 @@ find_package(CapnProto 0.9 NO_MODULE) ) endif() -# Cap'n Proto compatibility checks -set(CAPNPROTO_ISSUES "") -set(CAPNPROTO_CVE_AFFECTED FALSE) -set(CAPNPROTO_CLANG_INCOMPATIBLE FALSE) - -# Check for list-of-pointers memory access bug from Nov 2022 -# https://nvd.nist.gov/vuln/detail/CVE-2022-46149 -# https://github.com/advisories/GHSA-qqff-4vw4-f6hx -# https://github.com/capnproto/capnproto/security/advisories/GHSA-qqff-4vw4-f6hx -# https://github.com/capnproto/capnproto/blob/master/security-advisories/2022-11-30-0-pointer-list-bounds.md -# https://capnproto.org/news/2022-11-30-CVE-2022-46149-security-advisory.html -# https://dwrensha.github.io/capnproto-rust/2022/11/30/out_of_bounds_memory_access_bug.html -if(CapnProto_VERSION STREQUAL "0.9.0" - OR CapnProto_VERSION STREQUAL "0.9.1" - OR CapnProto_VERSION STREQUAL "0.10.0" - OR CapnProto_VERSION STREQUAL "0.10.1" - OR CapnProto_VERSION STREQUAL "0.10.2") - set(CAPNPROTO_CVE_AFFECTED TRUE) - string(APPEND CAPNPROTO_ISSUES "- CVE-2022-46149 security vulnerability (details: https://github.com/advisories/GHSA-qqff-4vw4-f6hx)\n") -endif() - # Check for Cap'n Proto / Clang / C++20 incompatibility -# Cap'n Proto 0.9.x and 0.10.x are incompatible with Clang 16+ when using C++20 +# Cap'n Proto 0.10.x is incompatible with Clang 16+ when using C++20 # due to P2468R2 implementation. This was fixed in Cap'n Proto 1.0+. # See: https://github.com/bitcoin-core/libmultiprocess/issues/199 -if((CapnProto_VERSION VERSION_GREATER_EQUAL "0.9.0") AND - (CapnProto_VERSION VERSION_LESS "1.0.0") AND +if((CapnProto_VERSION VERSION_LESS "1.0.0") AND (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL "16") AND (CMAKE_CXX_STANDARD EQUAL 20)) - set(CAPNPROTO_CLANG_INCOMPATIBLE TRUE) - string(APPEND CAPNPROTO_ISSUES "- Incompatible with Clang ${CMAKE_CXX_COMPILER_VERSION} when using C++20\n") -endif() - -if(CAPNPROTO_CVE_AFFECTED OR CAPNPROTO_CLANG_INCOMPATIBLE) - set(RESOLUTION_OPTIONS "") - - # Fixes both issues - string(APPEND RESOLUTION_OPTIONS " - Upgrade to Cap'n Proto version 1.0 or newer (recommended)\n") - - if(CAPNPROTO_CVE_AFFECTED AND NOT CAPNPROTO_CLANG_INCOMPATIBLE) - string(APPEND RESOLUTION_OPTIONS " - Upgrade to a patched minor version (0.9.2, 0.10.3, or later)\n") - elseif(CAPNPROTO_CLANG_INCOMPATIBLE AND NOT CAPNPROTO_CVE_AFFECTED) - string(APPEND RESOLUTION_OPTIONS " - Use GCC instead of Clang\n") - endif() - - string(APPEND RESOLUTION_OPTIONS " - For Bitcoin Core compilation build with -DENABLE_IPC=OFF to disable multiprocess support\n") - message(FATAL_ERROR "The version of Cap'n Proto detected: ${CapnProto_VERSION} has known compatibility issues:\n" - "${CAPNPROTO_ISSUES}" + "- Incompatible with Clang ${CMAKE_CXX_COMPILER_VERSION} when using C++20\n" "To resolve, choose one of the following:\n" - "${RESOLUTION_OPTIONS}" + " - Upgrade to Cap'n Proto version 1.0 or newer (recommended)\n" + " - Use GCC instead of Clang\n" + " - For Bitcoin Core compilation build with -DENABLE_IPC=OFF to disable multiprocess support\n" ) endif() diff --git a/ci/configs/olddeps.bash b/ci/configs/olddeps.bash index b2bc08b0..825eb263 100644 --- a/ci/configs/olddeps.bash +++ b/ci/configs/olddeps.bash @@ -3,6 +3,6 @@ CI_DIR=build-olddeps # Pin olddeps to an older Nixpkgs channel, to be able to test an older GCC. CI_NIXPKGS_CHANNEL=nixos-25.05 export CXXFLAGS="-Werror -Wall -Wextra -Wpedantic -Wunused -Wunused-const-variable -Wno-error=array-bounds" -CAPNP_CHECKOUT=v0.9.2 # Use a checkout to compile it with the selected GCC +CAPNP_CHECKOUT=v0.10.3 # Use a checkout to compile it with the selected GCC NIX_ARGS=(--argstr capnprotoVersion "none" --argstr cmakeVersion "3.12.4" --argstr gccVersion "10") BUILD_ARGS=(-k) diff --git a/doc/install.md b/doc/install.md index 015cfd19..60ff1c8f 100644 --- a/doc/install.md +++ b/doc/install.md @@ -1,6 +1,6 @@ # libmultiprocess Installation -Installation currently requires Cap'n Proto 0.9 or higher: +Installation currently requires Cap'n Proto 0.10.3 or higher: ```sh apt install libcapnp-dev capnproto diff --git a/include/mp/proxy-io.h b/include/mp/proxy-io.h index 00530898..30f48b3d 100644 --- a/include/mp/proxy-io.h +++ b/include/mp/proxy-io.h @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -34,6 +35,14 @@ struct Listener; struct InvokeContext { + explicit InvokeContext(Connection& connection) : connection{connection} {} + virtual ~InvokeContext() = default; + + //! Call fn() on the event loop thread, for code that has to run there, + //! like GetCapability() and SyncValue(). ServerInvokeContext overrides this + //! to skip fn() if the request was canceled. + virtual void syncRequest(kj::FunctionParam fn); + Connection& connection; }; @@ -55,23 +64,42 @@ struct ServerInvokeContext : InvokeContext CallContext& call_context; int req; //! For IPC methods that execute asynchronously, not on the event-loop - //! thread: lock preventing the event-loop thread from freeing the params or - //! results structs if the request is canceled while the worker thread is - //! reading params (`call_context.getParams()`) or writing results - //! (`call_context.getResults()`). - Lock* cancel_lock{nullptr}; - //! For IPC methods that execute asynchronously, not on the event-loop - //! thread, this is set to true if the IPC call was canceled by the client - //! or canceled by a disconnection. If the call runs on the event-loop - //! thread, it can't be canceled. This should be accessed with cancel_lock - //! held if it is not null, since in the asynchronous case it is accessed - //! from multiple threads. - bool request_canceled{false}; + //! thread, this is set to true by the event loop thread if the IPC call was + //! canceled by the client or canceled by a disconnection. The params and + //! results structs stay valid after cancellation, because the worker holds + //! a reference to the call context (see PassField for mp.Context). + std::atomic request_canceled{false}; ServerInvokeContext(ProxyServer& proxy_server, CallContext& call_context, int req) : InvokeContext{*proxy_server.m_context.connection}, proxy_server{proxy_server}, call_context{call_context}, req{req} { } + + //! Call fn() on the event loop thread, or skip it if the request was + //! canceled, and throw InterruptException in that case. Checking + //! request_canceled on the event loop thread is enough to order fn() + //! against cancellation, because only the event loop thread sets it, and + //! ~Connection sets it (through m_canceler) before destroying anything. + void syncRequest(kj::FunctionParam fn) override + { + throwIfCanceledAfter([&] { + proxy_server.m_context.loop->sync([&] { + if (!request_canceled) fn(); + }); + }); + } + + //! Call fn(), then throw InterruptException if the request was canceled, + //! so the caller stops instead of building results for a canceled request. + //! If fn() itself threw, the InterruptException takes precedence over its + //! exception, which could not be returned to the canceled caller anyway. + template + decltype(auto) throwIfCanceledAfter(Fn&& fn) + { + return TryFinally(std::forward(fn), [&] { + if (request_canceled) throw InterruptException{"canceled"}; + }); + } }; template @@ -551,6 +579,57 @@ class Connection CleanupList m_sync_cleanup_fns; }; +//! Take the capability held by a Cap'n Proto field. Must be called on the +//! event loop thread (see GetCapability()). +template +auto TakeCapability(Input&& input) +{ + using Client = std::remove_cvref_t; + if constexpr (std::is_lvalue_reference_v) { + // The input holds a client that was already read from the message, for + // example a ValueField from ReadList(). + return Client{kj::mv(input.get())}; + } else { + return Client{input.get()}; + } +} + +//! Call fn() on the event loop thread and return its result. +//! +//! Use this for code that uses invoke_context.connection, like building a +//! ProxyClient or ProxyServer. The Connection is destroyed on the event loop +//! thread, and ~Connection cancels the server requests using it before +//! destroying anything, so for a server request, fn() either runs before +//! ~Connection, or is skipped because the request is canceled, and +//! InterruptException is thrown instead. +template +auto SyncValue(InvokeContext& invoke_context, Fn&& fn) -> decltype(fn()) +{ + auto& loop{*invoke_context.connection.m_loop}; + // Testing hooks to simulate a disconnect before and after fn() runs. + if (loop.testing_hook_misc) loop.testing_hook_misc(std::string{"SyncValue:before"}); + std::optional result; + invoke_context.syncRequest([&] { result.emplace(fn()); }); + // If the request was canceled, syncRequest() threw InterruptException + // instead of returning without setting result. + assert(result); + if (loop.testing_hook_misc) loop.testing_hook_misc(std::string{"SyncValue:after"}); + return std::move(*result); +} + +//! Read a capability from a Cap'n Proto field on the event loop thread. +//! +//! Reading a capability adds a reference to its ClientHook, and ClientHook +//! reference counts are not atomic. The event loop thread updates the same +//! counts when other messages refer to the capability, when it is released, and +//! when the connection is closed, so reading it on another thread is a data +//! race that could free the ClientHook while it is still in use. +template +auto GetCapability(InvokeContext& invoke_context, Input&& input) +{ + return SyncValue(invoke_context, [&] { return TakeCapability(input); }); +} + //! Vat id for server side of connection. Required argument to RpcSystem::bootStrap() //! //! "Vat" is Cap'n Proto nomenclature for a host of various objects that facilitates diff --git a/include/mp/proxy-types.h b/include/mp/proxy-types.h index 05a4fbce..b0b7e174 100644 --- a/include/mp/proxy-types.h +++ b/include/mp/proxy-types.h @@ -322,11 +322,21 @@ decltype(auto) ReadList(TypeList, InvokeContext& invoke_context, Inpu return read_dest.update([&](auto& value) { auto data = input.get(); init(value, data.size()); - for (auto item : data) { + auto read_item{[&](auto&& item) { ReadField(TypeList(), invoke_context, Make(item), ReadDestEmplace(TypeList(), [&emplace, &value](auto&&... args) -> decltype(auto) { return emplace(value, std::forward(args)...); })); + }}; + if constexpr (std::is_base_of_v<::capnp::Capability::Client, std::remove_cvref_t>) { + // Iterating over a list of capabilities reads them, so read each + // one on the event loop thread (see GetCapability()). + for (unsigned int i = 0; i < data.size(); ++i) { + struct Item { decltype(data)& list; unsigned int index; auto get() const { return list[index]; } }; + read_item(GetCapability(invoke_context, Item{data, i})); + } + } else { + for (auto item : data) read_item(item); } }); } @@ -351,7 +361,9 @@ auto PassField(Priority<1>, TypeList, ServerContext& server_context, const auto& params = server_context.call_context.getParams(); const auto& input = Make(params); using Interface = typename Decay::Calls; - auto param = std::make_unique>(input.get(), server_context.proxy_server.m_context.connection, false); + auto param = SyncValue(server_context, [&] { + return std::make_unique>(TakeCapability(input), server_context.proxy_server.m_context.connection, false); + }); fn.invoke(server_context, std::forward(args)..., *param); } @@ -546,37 +558,19 @@ struct ServerCall template decltype(auto) invoke(ServerContext& server_context, TypeList<>, Args&&... args) const { - // If cancel_lock is set, release it while executing the method, and - // reacquire it afterwards. The lock is needed to prevent params and - // response structs from being deleted by the event loop thread if the - // request is canceled, so it is only needed before and after method - // execution. It is important to release the lock during execution - // because the method can take arbitrarily long to return and the event - // loop will need the lock itself in on_cancel if the call is canceled. - if (server_context.cancel_lock) server_context.cancel_lock->m_lock.unlock(); - return TryFinally( - [&]() -> decltype(auto) { - return ProxyServerMethodTraits< - typename std::remove_reference_t::Interface, - typename decltype(server_context.call_context.getParams())::Reads - >::invoke(server_context, std::forward(args)...); - }, - [&] { - if (server_context.cancel_lock) server_context.cancel_lock->m_lock.lock(); - // If the IPC request was canceled, throw InterruptException - // because there is no point continuing and trying to fill the - // call_context.getResults() struct. It's also important to stop - // executing because the connection may have been destroyed as - // described in https://github.com/bitcoin/bitcoin/issues/34250 - // and there could be invalid references to the destroyed - // Connection object if this continued. - // If the IPC method itself threw an exception, the - // InterruptException thrown below will take precedence over it. - // Since the call has been canceled that exception can't be - // returned to the caller, so it needs to be discarded like - // other result values. - if (server_context.request_canceled) throw InterruptException{"canceled"}; - }); + // If the call was canceled while the method ran, throw + // InterruptException afterwards, because there is no point continuing + // and trying to fill the call_context.getResults() struct. It's also + // important to stop executing because the connection may have been + // destroyed as described in https://github.com/bitcoin/bitcoin/issues/34250 + // and there could be invalid references to the destroyed Connection + // object if this continued. + return server_context.throwIfCanceledAfter([&]() -> decltype(auto) { + return ProxyServerMethodTraits< + typename std::remove_reference_t::Interface, + typename decltype(server_context.call_context.getParams())::Reads + >::invoke(server_context, std::forward(args)...); + }); } }; diff --git a/include/mp/type-context.h b/include/mp/type-context.h index 55f11b2d..c520e028 100644 --- a/include/mp/type-context.h +++ b/include/mp/type-context.h @@ -8,6 +8,8 @@ #include #include +#include + #include namespace mp { @@ -99,9 +101,11 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn& auto& request_threads = thread_context.request_threads; ConnThread request_thread; bool inserted{false}; - Mutex cancel_mutex; - Lock cancel_lock{cancel_mutex}; - server_context.cancel_lock = &cancel_lock; + // Reference to the call context, keeping the params and results + // structs alive until this request finishes, even if it is canceled. + // Taken and released on the event loop thread, because CallContextHook + // reference counts are not atomic. + kj::Own<::capnp::CallContextHook> call_ref; loop.sync([&] { // Detect request being canceled before it executes. if (cancel_monitor.m_canceled) { @@ -110,22 +114,13 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn& } // Detect request being canceled while it executes. assert(!cancel_monitor.m_on_cancel); - cancel_monitor.m_on_cancel = [&loop, &server_context, &cancel_mutex, req]() { + cancel_monitor.m_on_cancel = [&loop, &server_context, req]() { MP_LOG(loop, Log::Info) << "IPC server request #" << req << " canceled while executing."; - // Lock cancel_mutex here to block the event loop - // thread and prevent it from deleting the request's - // params and response structs while the execution - // thread is accessing them. Because this lock is - // released before the event loop thread does delete - // the structs, the mutex does not provide any - // protection from the event loop deleting the - // structs _before_ the execution thread acquires - // it. So in addition to locking the mutex, the - // execution thread always checks request_canceled - // as well before accessing the structs. - Lock cancel_lock{cancel_mutex}; + // Only set a flag. The params and results structs are kept + // alive by call_ref, so this never waits for the worker thread. server_context.request_canceled = true; }; + call_ref = ::capnp::CallContextHook::from(call_context).addRef(); // Update requests_threads map if not canceled. We know // the request is not canceled currently because // cancel_monitor.m_canceled was checked above and this @@ -154,14 +149,6 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn& // makes another IPC call), so avoid modifying the map. const bool erase_thread{inserted}; KJ_DEFER( - // Release the cancel lock before calling loop->sync and - // waiting for the event loop thread, because if a - // cancellation happened, it needs to run the on_cancel - // callback above. It's safe to release cancel_lock at - // this point because the fn.invoke() call below will be - // finished and no longer accessing the params or - // results structs. - cancel_lock.m_lock.unlock(); // Erase the request_threads entry on the event loop // thread with loop->sync(), so if the connection is // broken there is not a race between this thread and @@ -174,9 +161,13 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn& // cancellation happened. So we do not need to be // notified of cancellations after this point. Also // we do not want to be notified because - // cancel_mutex and server_context could be out of - // scope when it happens. + // server_context could be out of scope when it + // happens. cancel_monitor.m_on_cancel = nullptr; + // Release the call context on the event loop thread. If the + // request was canceled, this is the last reference, and + // ~RpcCallContext sends the cancellation return here. + call_ref = nullptr; auto self_dispose{kj::mv(self)}; auto active_call_dispose{kj::mv(active_call)}; if (erase_thread) { diff --git a/include/mp/type-function.h b/include/mp/type-function.h index fade9b42..43b58264 100644 --- a/include/mp/type-function.h +++ b/include/mp/type-function.h @@ -30,8 +30,10 @@ void CustomBuildField(TypeList>, if (value) { using Interface = typename decltype(output.get())::Calls; using Callback = ProxyCallbackImpl; - output.set(kj::heap>( - std::make_shared(std::forward(value)), invoke_context.connection)); + auto callback{std::make_shared(std::forward(value))}; + invoke_context.syncRequest([&] { + output.set(kj::heap>(std::move(callback), invoke_context.connection)); + }); } } @@ -56,8 +58,10 @@ decltype(auto) CustomReadField(TypeList> types, { if (CustomHasField(types, invoke_context, input)) { using Interface = typename Decay::Calls; - auto client = std::make_shared>( - input.get(), &invoke_context.connection, /* destroy_connection= */ false); + auto client = SyncValue(invoke_context, [&] { + return std::make_shared>( + TakeCapability(input), &invoke_context.connection, /* destroy_connection= */ false); + }); return read_dest.construct(ProxyCallFn{std::move(client)}); } return read_dest.construct(); diff --git a/include/mp/type-interface.h b/include/mp/type-interface.h index 39bb5ce6..5ec641cd 100644 --- a/include/mp/type-interface.h +++ b/include/mp/type-interface.h @@ -30,7 +30,8 @@ void CustomBuildField(TypeList>, { if (value) { using Interface = typename decltype(output.get())::Calls; - output.set(CustomMakeProxyServer(invoke_context, std::shared_ptr(value.release()))); + std::shared_ptr impl(value.release()); + invoke_context.syncRequest([&] { output.set(CustomMakeProxyServer(invoke_context, std::move(impl))); }); } } @@ -44,7 +45,8 @@ void CustomBuildField(TypeList>, { if (value) { using Interface = typename decltype(output.get())::Calls; - output.set(CustomMakeProxyServer(invoke_context, std::forward(value))); + std::shared_ptr impl(std::forward(value)); + invoke_context.syncRequest([&] { output.set(CustomMakeProxyServer(invoke_context, std::move(impl))); }); } } @@ -60,7 +62,7 @@ void CustomBuildField(TypeList, // wrapped implementation when the proxy client is destroyed or // disconnected. using Interface = typename decltype(output.get())::Calls; - output.set(CustomMakeProxyServer(invoke_context, std::shared_ptr(&value, [](Impl*){}))); + invoke_context.syncRequest([&] { output.set(CustomMakeProxyServer(invoke_context, std::shared_ptr(&value, [](Impl*){}))); }); } template @@ -87,7 +89,7 @@ decltype(auto) CustomReadField(TypeList>, using Interface = typename Decay::Calls; if (CustomHasField(TypeList(), invoke_context, input)) { return read_dest.construct( - CustomMakeProxyClient(invoke_context, std::move(input.get()))); + SyncValue(invoke_context, [&] { return CustomMakeProxyClient(invoke_context, TakeCapability(input)); })); } return read_dest.construct(); } @@ -103,7 +105,7 @@ decltype(auto) CustomReadField(TypeList>, using Interface = typename Decay::Calls; if (CustomHasField(TypeList(), invoke_context, input)) { return read_dest.construct( - CustomMakeProxyClient(invoke_context, std::move(input.get()))); + SyncValue(invoke_context, [&] { return CustomMakeProxyClient(invoke_context, TakeCapability(input)); })); } return read_dest.construct(); } diff --git a/include/mp/type-threadmap.h b/include/mp/type-threadmap.h index 86521591..be885568 100644 --- a/include/mp/type-threadmap.h +++ b/include/mp/type-threadmap.h @@ -25,7 +25,7 @@ void CustomBuildField(TypeList<>, InvokeContext& invoke_context, Output&& output) { - output.set(kj::heap>(invoke_context.connection)); + invoke_context.syncRequest([&] { output.set(kj::heap>(invoke_context.connection)); }); } template @@ -35,7 +35,7 @@ decltype(auto) CustomReadField(TypeList<>, InvokeContext& invoke_context, Input&& input) { - invoke_context.connection.m_thread_map = input.get(); + invoke_context.syncRequest([&] { invoke_context.connection.m_thread_map = input.get(); }); } } // namespace mp diff --git a/src/mp/proxy.cpp b/src/mp/proxy.cpp index c10eca7e..c31e8173 100644 --- a/src/mp/proxy.cpp +++ b/src/mp/proxy.cpp @@ -284,6 +284,11 @@ void EventLoop::loop() m_cv.notify_all(); } +void InvokeContext::syncRequest(kj::FunctionParam fn) +{ + connection.m_loop->sync(fn); +} + void EventLoop::sync(kj::FunctionParam fn) { if (std::this_thread::get_id() == m_thread_id) { diff --git a/test/mp/test/foo.capnp b/test/mp/test/foo.capnp index 0c76b3db..d4fb6137 100644 --- a/test/mp/test/foo.capnp +++ b/test/mp/test/foo.capnp @@ -40,6 +40,7 @@ interface FooInterface $Proxy.wrap("mp::test::FooImplementation") { listBars @25 (context :Proxy.Context, n :Int32) -> (result :List(BarInterface)); callMessageAsync @26 (context :Proxy.Context) -> (result :FooMessage); callbackFlat @27 (context :Proxy.Context, callback :FlatCallback, arg: Int32) -> (result :Int32); + sumBars @28 (context :Proxy.Context, bars :List(BarInterface)) -> (result :Int32); } interface FooInit $Proxy.wrap("mp::test::FooInit") { diff --git a/test/mp/test/foo.h b/test/mp/test/foo.h index 6ca9a351..d30b768d 100644 --- a/test/mp/test/foo.h +++ b/test/mp/test/foo.h @@ -145,6 +145,12 @@ class FooImplementation for (int i = 0; i < n; ++i) result.push_back(std::make_unique(i)); return result; } + int sumBars(std::vector> bars) + { + int sum{0}; + for (auto& bar : bars) sum += bar->value(); + return sum; + } std::shared_ptr m_callback; void callFn() { assert(m_fn); m_fn(); } void callFnAsync() { assert(m_fn); m_fn(); } diff --git a/test/mp/test/test.cpp b/test/mp/test/test.cpp index cfbe2f68..1aedcbad 100644 --- a/test/mp/test/test.cpp +++ b/test/mp/test/test.cpp @@ -1012,5 +1012,90 @@ KJ_TEST("Calling IPC method after destroy and destroy during a call") loop.sync([&] { bar2.reset(); }); } +KJ_TEST("Canceling a call while reading a list of capability params") +{ + // Item 0 of the list is read, then the request is canceled before item 1 + // is read. GetCapability() throws InterruptException, and item 0's + // ProxyClient is destroyed while unwinding, which calls the remote + // destroy() method and waits for the event loop thread. This must not + // deadlock, so the event loop thread must not wait for the worker thread + // when the request is canceled. + TestSetup setup{/*client_owns_connection=*/false}; + ProxyClient* foo = setup.client.get(); + foo->initThreadMap(); + EventLoop& loop{*setup.server->m_context.loop}; + int reads{0}; + // Wait for the server request to finish before the test ends, so the + // worker is no longer using the hook or the variables it refers to. + std::promise request_done; + bool request_done_set{false}; + loop.testing_hook_async_request_done = [&] { + if (!request_done_set) request_done.set_value(); + request_done_set = true; + }; + loop.testing_hook_misc = [&](std::any arg) { + auto* name{std::any_cast(&arg)}; + // Each list item calls SyncValue() twice: once to read the + // capability and once to build its ProxyClient. Item 1 is read by the + // third call. + if (!name || *name != "SyncValue:before") return; + if (++reads != 3) return; + // Before item 1 is read: disconnect and give the event loop time + // to cancel the request. + setup.client_disconnect(); + std::this_thread::sleep_for(std::chrono::milliseconds{500}); + }; + std::vector> bars; + bars.push_back(std::make_unique(1)); + bars.push_back(std::make_unique(2)); + EXPECT_EXCEPTION(foo->sumBars(std::move(bars)), "IPC client method call interrupted by disconnect."); + request_done.get_future().get(); +} + +//! Disconnect at a hook point on the worker thread while it reads a callback +//! param, and check that the request is interrupted instead of using the +//! server Connection after it is destroyed. +static void TestDisconnectAtHook(const std::string& hook_name) +{ + TestSetup setup{/*client_owns_connection=*/false}; + ProxyClient* foo = setup.client.get(); + foo->initThreadMap(); + EventLoop& loop{*setup.server->m_context.loop}; + bool fired{false}; + // Wait for the server request to finish before the test ends, so the + // worker is no longer using the hook or the variables it refers to. + std::promise request_done; + bool request_done_set{false}; + loop.testing_hook_async_request_done = [&] { + if (!request_done_set) request_done.set_value(); + request_done_set = true; + }; + loop.testing_hook_misc = [&](std::any arg) { + auto* name{std::any_cast(&arg)}; + if (!name || *name != hook_name || fired) return; + fired = true; + setup.client_disconnect(); + std::this_thread::sleep_for(std::chrono::milliseconds{500}); + }; + class Callback : public FooCallback + { + public: + int call(int arg) override { return arg; } + }; + EXPECT_EXCEPTION(foo->callbackUnique(std::make_unique(), 1), "IPC client method call interrupted by disconnect."); + request_done.get_future().get(); + KJ_EXPECT(fired); +} + +KJ_TEST("Server connection destroyed before a ProxyClient param is built") +{ + TestDisconnectAtHook("SyncValue:before"); +} + +KJ_TEST("Server connection destroyed after a ProxyClient param is built") +{ + TestDisconnectAtHook("SyncValue:after"); +} + } // namespace test } // namespace mp