From e8c449e44ab45856a2027d7dfef4077cdaf69824 Mon Sep 17 00:00:00 2001 From: Javier Mateos Date: Sun, 8 Nov 2026 23:15:00 +0000 Subject: [PATCH] util: set FD_CLOEXEC atomically in SocketPair when SOCK_CLOEXEC is available SocketPair() created the sockets with socketpair() and then set FD_CLOEXEC on each end with separate fcntl() calls. If another thread called fork() in between, the child inherited the descriptors without FD_CLOEXEC and could keep them open across exec. Pass SOCK_CLOEXEC to socketpair() where it is defined so the flag is set atomically at creation. SpawnProcess relies on FD_CLOEXEC to close its error-reporting socket on a successful exec, and SOCK_CLOEXEC sets the same descriptor flag, so behavior is unchanged apart from closing the race. Platforms without SOCK_CLOEXEC (e.g. macOS) keep using fcntl(), but now close both descriptors before throwing if fcntl() fails, instead of leaking them. --- src/mp/util.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/mp/util.cpp b/src/mp/util.cpp index e1eae4dc..e9710eaa 100644 --- a/src/mp/util.cpp +++ b/src/mp/util.cpp @@ -351,10 +351,23 @@ SocketId StartSpawned(const SpawnConnectInfo& connect_info) std::array SocketPair() { + // Set FD_CLOEXEC atomically when possible. Setting it with fcntl() after + // socketpair() leaves a window where a fork() in another thread can leak + // the descriptors into an unrelated child process. SpawnProcess relies on + // FD_CLOEXEC to close its error-reporting socket on successful exec, and + // SOCK_CLOEXEC sets the same descriptor flag. int pair[2]; +#ifdef SOCK_CLOEXEC + KJ_SYSCALL(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair)); +#else KJ_SYSCALL(socketpair(AF_UNIX, SOCK_STREAM, 0, pair)); - KJ_SYSCALL(fcntl(pair[0], F_SETFD, FD_CLOEXEC)); - KJ_SYSCALL(fcntl(pair[1], F_SETFD, FD_CLOEXEC)); + if (fcntl(pair[0], F_SETFD, FD_CLOEXEC) == -1 || fcntl(pair[1], F_SETFD, FD_CLOEXEC) == -1) { + const int err = errno; + (void)close(pair[0]); + (void)close(pair[1]); + KJ_FAIL_SYSCALL("fcntl", err); + } +#endif return {pair[0], pair[1]}; }