Skip to content

Use-after-free race in ConnectStream when passing a disconnected socket #308

Description

@xyzconstant

While adding coverage for ConnectStream in #298, the CI job for NetBSD 9.4 was crashing in the new test "Passing a disconnected socket will throw" with:

[ TEST ] connect_tests.cpp:94: Passing a disconnected socket will throw
assertion "m_loop" failed: file "/home/runner/work/libmultiprocess/libmultiprocess/include/mp/proxy.h", line 59, function "mp::EventLoop& mp::EventLoopRef::operator*() const"
*** Received signal #6: Abort trap
stack: 

The race occurs on all platforms, the NetBSD runner is just slow enough that the event loop thread always wins. Asked Claude to try to reproduce it locally and came up with placing (in ConnectStream)

std::this_thread::sleep_for(std::chrono::milliseconds(100));

between the loop.sync(...) block and the client construction to extend the race window so that the event loop thread wins the race (as it consistently did in the failing job), thereby exposing the issue.

The sequence of events is as follows:

  1. ConnectStream runs a loop.sync(...) block (which executes the body on the event loop thread) that creates the Connection, obtains init_client, and registers an onDisconnect handler that runs delete connection_ptr. At this point, the ProxyClient instance that will own the connection does not yet exist.
  2. The RPC system hits EOF on its first read of the disconnected socket.
  3. The event loop then resolves m_network.onDisconnect(), running the handler from step 1, resulting in the Connection being deleted.
  4. Connection::~Connection resets its EventLoopRef m_loop member, and the memory is freed.
  5. The caller thread then wakes up and constructs the ProxyClient<InitInterface>, whose ProxyContext constructor reads the freed Connection:
    ProxyContext::ProxyContext(Connection* connection) : connection(connection), loop{*connection->m_loop} {}

Steps 2-4 run on the event loop thread, while step 5 runs on the caller thread, with no ordering between them so an early disconnect lets the deletion win.

The fix is already available in #298, I'm opening this issue to make it more visible and easier to review.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions