fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd

This commit is contained in:
Kurt Himebauch committed 2026-11-28 12:02:16 -05:00
1 parent b1dbfb54da
commit 441773012f
2 files changed
+121 -42

No files matched your search

+44 -42
View File
@@ -375,9 +375,9 @@ static void ddh_keep(int fd) {
g_kept_fd_count++;
}
// A dup2() or dup3() onto the parent's pidfd (ddh_parent_lives()): the pidfd moves to another number
// first, so that the program gets the number it asked for and the check keeps its pidfd; if the call
// then fails, the move is undone (ddh_parent_pidfd_settle()). Returns the number moved from, or -1.
// A dup2() or dup3() onto the parent's pidfd (ddh_parent_lives()) or its spare: the check goes on with
// the other, so that the program gets the number it asked for; if the call then fails, nothing has
// changed (ddh_parent_pidfd_settle()). Returns the number the program takes over, or -1.
static int ddh_parent_pidfd_moves(int target);
static void ddh_parent_pidfd_settle(int from, int done);
static int ddh_parent_pidfd_lock(int target);
@@ -428,55 +428,46 @@ static pid_t g_ddh_report_child;
// The forked parent as a pidfd, opened at the start: readable once it has exited, reaped or not.
static int g_ddh_parent_pidfd = -1;
// Whether fd is a pidfd. Checked once it is kept: until then another thread's close() or
// close_range() could close it (and an open() take its number), and once kept nothing of the program
// closes it.
static int ddh_is_pidfd(int fd) {
char path[32], target[32];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
int saved = errno;
long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1);
errno = saved;
if (len <= 0) return 0;
target[len] = 0;
return strcmp(target, "anon_inode:[pidfd]") == 0;
}
// A second copy of it, made with it: a dup2() onto the pidfd's number moves the check to the spare,
// and no descriptor is ever made later, when another thread's close() or close_range() could be
// closing the number it would get. Both are kept (close() and close_range() leave them alone) from
// the start, before the program runs. Without a spare (a second dup2() onto it), the pidfd is given
// up and /proc answers.
static int g_ddh_parent_spare = -1;
// What the dup2() under way takes over: 1 the pidfd (the spare is the pidfd meanwhile), 2 the spare.
// Only changed with g_ddh_pidfd_lock held.
static int g_ddh_pidfd_move;
static int ddh_parent_pidfd_moves(int target) {
int fd = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE);
if (fd < 0 || target != fd) return -1;
int moved = (int)call_orig_syscall(SYS_fcntl, (unsigned long)fd, F_DUPFD_CLOEXEC, 900, 0, 0, 0);
ddh_unkeep(fd);
__atomic_store_n(&g_ddh_parent_pidfd, moved, __ATOMIC_RELEASE);
if (moved < 0) return -1; // no copy (out of fds): the pidfd is given up, /proc answers from now on
ddh_keep(moved);
if (!ddh_is_pidfd(moved)) {
// closed before it was kept: given up, the number left to whatever has it now
ddh_unkeep(moved);
__atomic_store_n(&g_ddh_parent_pidfd, -1, __ATOMIC_RELEASE);
return -1;
int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE);
if (target < 0 || (target != fd && target != spare)) return -1;
if (target == fd) {
__atomic_store_n(&g_ddh_parent_spare, -1, __ATOMIC_RELEASE);
__atomic_store_n(&g_ddh_parent_pidfd, spare, __ATOMIC_RELEASE);
g_ddh_pidfd_move = 1;
} else {
__atomic_store_n(&g_ddh_parent_spare, -1, __ATOMIC_RELEASE);
g_ddh_pidfd_move = 2;
}
return fd;
return target;
}
static void ddh_parent_pidfd_settle(int from, int done) {
if (from < 0 || done) return;
// The dup failed and left the number as it was. If it still is the pidfd (no other thread's
// dup2() has put a file there since the move, nor closed it), the original is tracked again and
// the copy goes; otherwise, or with no room to keep the original, the copy stays the pidfd.
if (!ddh_is_pidfd(from)) return;
ddh_keep(from);
if (!is_kept_fd(from)) return;
if (!ddh_is_pidfd(from)) {
if (from < 0) return;
int move = g_ddh_pidfd_move;
g_ddh_pidfd_move = 0;
// the program's file now: its close() closes it
if (done) {
ddh_unkeep(from);
return;
}
int moved = __atomic_exchange_n(&g_ddh_parent_pidfd, from, __ATOMIC_ACQ_REL);
if (moved >= 0 && moved != from) {
ddh_unkeep(moved);
int saved = errno;
syscall(SYS_close, moved);
errno = saved;
// the dup failed and left the number as it was, still the pidfd (or the spare) and still kept
if (move == 1) {
int spare = __atomic_exchange_n(&g_ddh_parent_pidfd, from, __ATOMIC_ACQ_REL);
__atomic_store_n(&g_ddh_parent_spare, spare, __ATOMIC_RELEASE);
} else if (move == 2) {
__atomic_store_n(&g_ddh_parent_spare, from, __ATOMIC_RELEASE);
}
}
@@ -717,7 +708,18 @@ static void ddh_setup_report(void) {
pidfd = high;
}
ddh_keep(pidfd);
if (!is_kept_fd(pidfd)) {
// no room in the kept list: the program could close it, and /proc answers
syscall(SYS_close, pidfd);
pidfd = -1;
}
}
if (pidfd >= 0) {
g_ddh_parent_pidfd = pidfd;
int spare = (int)call_orig_syscall(SYS_fcntl, (unsigned long)pidfd, F_DUPFD_CLOEXEC, 900, 0, 0, 0);
if (spare >= 0) ddh_keep(spare);
if (spare >= 0 && is_kept_fd(spare)) g_ddh_parent_spare = spare;
else if (spare >= 0) syscall(SYS_close, spare);
__atomic_store_n(&g_ddh_had_pidfd, 1, __ATOMIC_RELEASE);
pthread_atfork(ddh_pidfd_hold, ddh_pidfd_release, ddh_pidfd_release);
}
+77
View File
@@ -368,6 +368,55 @@ int main(int argc, char **argv) {
}
"""
# A worker's program that puts files where the hook keeps its parent's pidfd: it gets the numbers, the
# hook makes no descriptor for it, and its parent stays known
DUPOVER = r"""
#define _GNU_SOURCE
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
static int is(int fd, const char *what) {
char path[64], target[64];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
ssize_t n = readlink(path, target, sizeof(target) - 1);
if (n <= 0) return 0;
target[n] = 0;
return strcmp(target, what) == 0;
}
static unsigned long fds(void) { // a sum over the open fds, the listing's own left out
DIR *d = opendir("/proc/self/fd");
unsigned long sum = 0;
struct dirent *e;
while (d && (e = readdir(d))) {
if (e->d_name[0] == '.' || atoi(e->d_name) == dirfd(d)) continue;
sum = sum * 31 + (unsigned long)atoi(e->d_name) + 1;
}
if (d) closedir(d);
return sum;
}
int main(void) {
printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]"));
int file = open("/dev/null", O_WRONLY);
unsigned long before = fds();
dup2(file, 900);
printf("nonew\t%d\n", fds() == before);
printf("taken\t%d\n", is(900, "/dev/null"));
printf("moved\t%d\n", (int)getppid());
dup2(file, 901); // the spare too: no pidfd left, /proc answers
printf("again\t%d\n", (int)getppid());
syscall(SYS_close_range, 3, ~0U, 0);
printf("closed\t%d\n", (int)getppid());
return 0;
}
"""
# An unlisted program that execs the next one, as env and shell wrappers do
WRAP = r"""
#include <unistd.h>
@@ -869,6 +918,34 @@ class NativeHookHandoffTest(unittest.TestCase):
def test_any_other_program_has_its_real_parent(self):
self.assertEqual(str(os.getpid()), self.ppid_in_worker(None))
def test_a_dup2_onto_the_parents_pidfd_makes_no_descriptor_and_keeps_the_parent(self):
tmp = Path(self.tmp.name)
probe = tmp / "dupover"
(tmp / "dupover.c").write_text(DUPOVER)
subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "dupover.c")], check=True)
# a table for the worker's program: slot 0 for a child that started after any parent
table = os.memfd_create("ddh-test-table", 0)
self.addCleanup(os.close, table)
os.ftruncate(table, 64 + 1024 * 64)
os.pwrite(table, struct.pack("<i", 0x6464686F), 0)
os.pwrite(table, struct.pack("<q", 1 << 62), 64 + 40)
forker = subprocess.Popen(["sleep", "60"])
self.addCleanup(forker.wait)
self.addCleanup(forker.kill)
env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root), "DDH_TABLE": "%d:0:%d:0" % (table, forker.pid)}
settings = " ".join("-E %s=%s" % item for item in env.items()) if self.prefix else \
" ".join("%s=%s" % item for item in env.items())
worker = "-E DDH_WORKER_PID=$$" if self.prefix else "DDH_WORKER_PID=$$"
runner = " ".join(self.prefix) + " " + settings + " " + worker if self.prefix else "env " + settings + " " + worker
out = subprocess.run(["sh", "-c", "exec %s %s" % (runner, probe)], capture_output=True, text=True, timeout=60,
pass_fds=(table,))
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr)
self.assertEqual("1", result.get("nonew"), out.stdout)
self.assertEqual("1", result.get("taken"), out.stdout)
for step in ("moved", "again", "closed"):
self.assertEqual(str(forker.pid), result.get(step), out.stdout)
def test_a_program_not_listed_is_a_normal_child(self):
result, requests, out = self.run_parent("wait", "3", handoff="other")
self.assertEqual([], requests)