Skip to content

util: manage SpawnProcess socket descriptors with RAII - #395

Merged
ryanofsky merged 1 commit into
bitcoin-core:masterfrom
javierpmateos:raii-socket-fds
Dec 2, 2026
Merged

ryanofsky merged 1 commit into
bitcoin-core:masterfrom
javierpmateos:raii-socket-fds

Conversation

@javierpmateos

Copy link
Copy Markdown
Contributor

Follow-up to #394, based on ryanofsky's suggestion to use kj::AutoCloseFd instead of handling descriptor cleanup manually.

SpawnProcess() could leak file descriptors if the second SocketPair(), connect_info_to_args, or MakeArgv() threw an exception.

This change wraps the descriptors in kj::AutoCloseFd as soon as they're created, releasing them when they're explicitly closed or handed off. It also uses RAII in the SocketPair() fallback for platforms without SOCK_CLOEXEC. The existing close error handling and child behavior are preserved.

Testing:

  • Added a test that throws from connect_info_to_args and checks that the socket is closed. It fails on master and passes with this change.
  • All 30 mptest cases pass, both normally and with SOCK_CLOEXEC disabled.
  • Checked with strace: when the callback throws, all four descriptors are closed with this change, while master leaves them open.

There are two minor differences: the fallback's fcntl error now includes the full expression, and on error paths two descriptors are closed after killing the child rather than before. Neither changes the intended behavior.

This doesn't address unexpected exceptions after fork() that could leave the child running. ReadSpawnResult() can't throw today, so this is only theoretical.

I used an AI coding assistant for the implementation. I reviewed the diff and ran the tests myself.

@DrahtBot

DrahtBot commented Nov 14, 2026 •

Copy link
Copy Markdown

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK ryanofsky
Stale ACK ViniciusCestarii

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

@ViniciusCestarii ViniciusCestarii left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK 2f6e432

Tested with mpexamples trying to make it faill closing fds. It is much cleaner with RAII

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review ACK 2f6e432. This fixes a descriptor leak on master, where SpawnProcess() never closes the first socket pair if the second SocketPair() call, connect_info_to_args(), or MakeArgv() throws, and replaces the hand-written close() calls on every error path with kj::AutoCloseFd ownership, so error paths added later can't miss one.

I ran the new test with master's util.cpp and it fails there and passes here. I left one optional suggestion inline, to avoid duplicate having duplicate fds[x] and fdx_owner variables . Thanks for following up on #394!

Comment thread src/mp/util.cpp Outdated
Comment on lines +255 to +260
auto fds{SocketPair()};
kj::AutoCloseFd fds0_owner{fds[0]}, fds1_owner{fds[1]};
// Only used for the child to report errors back to the parent, so a one-way
// pipe would be sufficient, but reuse the existing SocketPair() helper.
auto error_fds{SocketPair()};
kj::AutoCloseFd error_fds0_owner{error_fds[0]}, error_fds1_owner{error_fds[1]};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In commit "util: manage SpawnProcess socket descriptors with RAII" (2f6e432)

Optional suggestion, fine to keep as is: this gives each descriptor two names, the raw fds[i]/error_fds[i] value and the *_owner object, so reading the rest of the function means checking which one each line uses, and a later change that closes fds[1] directly would close it twice. A small helper would leave one owning array per socket pair, with .get() and .release() at each use:

//! Call SocketPair() and take ownership of the descriptors, so they are closed
//! if an exception is thrown before they are released.
std::array<kj::AutoCloseFd, 2> OwnedSocketPair()
{
    const auto fds{SocketPair()};
    return {kj::AutoCloseFd{fds[0]}, kj::AutoCloseFd{fds[1]}};
}

Then this becomes auto fds{OwnedSocketPair()}; and the close below reads close(pid ? fds[0].release() : fds[1].get()). I checked the full change below builds with the default CI config (-Werror, IWYU) and passes mptest, including the new test.

Diff
diff --git a/src/mp/util.cpp b/src/mp/util.cpp
index 9ab3e49..2d0f498 100644
--- a/src/mp/util.cpp
+++ b/src/mp/util.cpp
@@ -175,6 +175,14 @@ void KillAndReapChild(ProcessId pid)
     while (::waitpid(pid, /*status=*/nullptr, /*options=*/0) == -1 && errno == EINTR) {}
 }

+//! Call SocketPair() and take ownership of the descriptors, so they are closed
+//! if an exception is thrown before they are released.
+std::array<kj::AutoCloseFd, 2> OwnedSocketPair()
+{
+    const auto fds{SocketPair()};
+    return {kj::AutoCloseFd{fds[0]}, kj::AutoCloseFd{fds[1]}};
+}
+
 } // namespace

 // Copied from https://github.com/bitcoin/bitcoin/blob/d3e40af2597/src/util/threadnames.cpp#L21-L36
@@ -252,12 +260,10 @@ std::string LogEscape(const kj::StringTree& string, size_t max_size)

 std::tuple<ProcessId, SocketId> SpawnProcess(SpawnConnectInfoToArgsFn&& connect_info_to_args)
 {
-    auto fds{SocketPair()};
-    kj::AutoCloseFd fds0_owner{fds[0]}, fds1_owner{fds[1]};
+    auto fds{OwnedSocketPair()};
     // Only used for the child to report errors back to the parent, so a one-way
     // pipe would be sufficient, but reuse the existing SocketPair() helper.
-    auto error_fds{SocketPair()};
-    kj::AutoCloseFd error_fds0_owner{error_fds[0]}, error_fds1_owner{error_fds[1]};
+    auto error_fds{OwnedSocketPair()};

     // Evaluate the callback and build the argv array before forking.
     //
@@ -265,7 +271,7 @@ std::tuple<ProcessId, SocketId> SpawnProcess(SpawnConnectInfoToArgsFn&& connect_
     // locks at fork time. In that case, running code that allocates memory or
     // takes locks in the child between fork() and exec() can deadlock
     // indefinitely. Precomputing arguments in the parent avoids this.
-    const std::vector<std::string> args{connect_info_to_args(std::to_string(fds[0]))};
+    const std::vector<std::string> args{connect_info_to_args(std::to_string(fds[0].get()))};
     const std::vector<char*> argv{MakeArgv(args)};

     ProcessId pid = fork();
@@ -273,19 +279,19 @@ std::tuple<ProcessId, SocketId> SpawnProcess(SpawnConnectInfoToArgsFn&& connect_
         const int err = errno;
         throw std::system_error(err, std::system_category(), "fork");
     }
-    // The child keeps using the raw descriptors and never runs the
-    // AutoCloseFd destructors, because it only leaves via execvp() or _exit().
+    // The child never runs the AutoCloseFd destructors, because it only
+    // leaves via execvp() or _exit().
     //
     // Parent process closes the descriptor for socket 0, child closes the
     // descriptor for socket 1. On failure, the parent throws, but the child
     // must _exit(126) (post-fork child must not throw).
-    if (close(pid ? fds0_owner.release() : fds[1]) != 0) {
+    if (close(pid ? fds[0].release() : fds[1].get()) != 0) {
         const int err = errno;
         if (pid) {
             KillAndReapChild(pid);
             throw std::system_error(err, std::system_category(), "close");
         }
-        WriteSpawnError(error_fds[0], {.which = SpawnErrorOp::CLOSE, .err = err});
+        WriteSpawnError(error_fds[0].get(), {.which = SpawnErrorOp::CLOSE, .err = err});
         _exit(126);
     }

@@ -295,7 +300,7 @@ std::tuple<ProcessId, SocketId> SpawnProcess(SpawnConnectInfoToArgsFn&& connect_
         // do non-fork-safe work here.
         const int maxFd = MaxFd();
         for (int fd = 3; fd < maxFd; ++fd) {
-            if (fd != fds[0] && fd != error_fds[0]) {
+            if (fd != fds[0].get() && fd != error_fds[0].get()) {
                 close(fd);
             }
         }
@@ -305,34 +310,34 @@ std::tuple<ProcessId, SocketId> SpawnProcess(SpawnConnectInfoToArgsFn&& connect_
         // concurrent fork in another thread would leak the descriptor into an
         // unrelated child process (which would not clear it).
         // fcntl is async-signal-safe.
-        const int fds0_flags = fcntl(fds[0], F_GETFD);
-        if (fds0_flags == -1 || fcntl(fds[0], F_SETFD, fds0_flags & ~FD_CLOEXEC) == -1) {
+        const int fds0_flags = fcntl(fds[0].get(), F_GETFD);
+        if (fds0_flags == -1 || fcntl(fds[0].get(), F_SETFD, fds0_flags & ~FD_CLOEXEC) == -1) {
             const int err = errno;
-            WriteSpawnError(error_fds[0], {.which = SpawnErrorOp::FCNTL, .err = err});
+            WriteSpawnError(error_fds[0].get(), {.which = SpawnErrorOp::FCNTL, .err = err});
             _exit(126);
         }

         execvp(argv[0], argv.data());

         const int err = errno;
-        WriteSpawnError(error_fds[0], {.which = SpawnErrorOp::EXECVP, .err = err});
+        WriteSpawnError(error_fds[0].get(), {.which = SpawnErrorOp::EXECVP, .err = err});
         _exit(127);
     }

     // Close the parent's copy of the child's write end.
-    if (close(error_fds0_owner.release()) != 0) {
+    if (close(error_fds[0].release()) != 0) {
         const int err = errno;
         KillAndReapChild(pid);
         throw std::system_error(err, std::system_category(), "close");
     }

-    const std::optional<SpawnError> error{ReadSpawnResult(error_fds[1])};
-    (void)close(error_fds1_owner.release());
+    const std::optional<SpawnError> error{ReadSpawnResult(error_fds[1].get())};
+    (void)close(error_fds[1].release());
     if (error) {
         KillAndReapChild(pid);
         throw std::system_error(error->err, std::system_category(), SpawnErrorName(error->which));
     }
-    return {pid, fds1_owner.release()};
+    return {pid, fds[1].release()};
 }

 SocketId StartSpawned(const SpawnConnectInfo& connect_info)

SpawnProcess could leak file descriptors if the second SocketPair(),
connect_info_to_args, or MakeArgv threw an exception.

Use kj::AutoCloseFd to take ownership of the descriptors as soon as
they're created. Release them when closing or returning them, keeping
the existing error handling and child behavior unchanged. Do the same
in the SocketPair() fallback path used when SOCK_CLOEXEC is not
available.

Add a test that throws from the callback and checks that its socket is
closed.

Co-authored-by: Ryan Ofsky <[email protected]>
@javierpmateos

Copy link
Copy Markdown
Contributor Author

Gracias Ryan! Hice el cambio de tu sugerencia, incorporando OwnedSocketPair(), ya que simplifica la gestión de la propiedad de los descriptores, evitando mantener variables separadas para los descriptores (y sus respectivos objetos de gestión RAII).

El código ya actualizado compiló correctamente y todos los tests pasan (incluido el nuevo). Me pareció correcto agregarte como coautor del commit.


Thanks, Ryan! I’ve applied your suggestion by incorporating OwnedSocketPair(); this simplifies descriptor ownership management, as it eliminates the need to maintain separate variables for the descriptors (and their corresponding RAII management objects).

The updated code compiled successfully, and all tests pass (including the new one). I thought it appropriate to add you as a co-author of the commit.

git range-diff 2f6e432...b403d6d

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review ACK b403d6d. Only change since my last review is applying the OwnedSocketPair() suggestion, which leaves one owning array per socket pair instead of separate raw and owner variables. Thanks for the quick update!

@ryanofsky
ryanofsky merged commit ba7c19d into bitcoin-core:master Dec 2, 2026
14 checks passed
@javierpmateos
javierpmateos deleted the raii-socket-fds branch December 2, 2026 13:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants