fix(handoff): a thread that unshares its fd table keeps its own copy of the kept fds

This commit is contained in:
Kurt Himebauch committed 2026-12-01 12:27:39 -05:00
1 parent feedf92d3e
commit 840ac0bad6
7 files changed
+215 -44

No files matched your search

+19 -14
View File
@@ -317,6 +317,7 @@ pid_t fork(void) {
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
@@ -330,7 +331,7 @@ int close(int fd) {
static int (*orig_close)(int) = NULL;
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
uint64_t ticket = kept_close_begin();
if (g_kept_fd_count > 0 && is_kept_fd(fd)) {
if (kept_any() > 0 && is_kept_fd(fd)) {
kept_close_end(ticket);
return 0;
}
@@ -379,6 +380,10 @@ static int close_range_part(unsigned int first, unsigned int last, void *flags)
return (int)syscall(__NR_close_range, first, last, *(int *)flags);
}
static int close_range_unshare(void) {
return (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE);
}
int close_range(unsigned int first, unsigned int last, int flags) {
// what the kernel refuses, refused before the range is split or the table unshared
if (first > last || (flags & ~(int)(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))) {
@@ -386,19 +391,19 @@ int close_range(unsigned int first, unsigned int last, int flags) {
return -1;
}
uint64_t ticket = kept_close_begin();
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
int r;
if (count == 0) {
r = close_range_part(first, last, &flags);
} else {
r = 0;
if (flags & CLOSE_RANGE_UNSHARE) {
r = (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE);
flags &= ~(int)CLOSE_RANGE_UNSHARE;
}
if (r == 0) r = for_each_range_without(first, last, kept, count, close_range_part, &flags);
int r = 0;
// The table is unshared first, once, and this thread goes on with its own copy of the kept list
// (kept_split())
if (flags & CLOSE_RANGE_UNSHARE) {
r = kept_split(close_range_unshare);
flags &= ~(int)CLOSE_RANGE_UNSHARE;
}
if (r == 0) {
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
r = count == 0 ? close_range_part(first, last, &flags)
: for_each_range_without(first, last, kept, count, close_range_part, &flags);
}
int saved = errno;
kept_close_end(ticket);
+1
View File
@@ -665,6 +665,7 @@ pid_t fork(void) {
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
+42 -17
View File
@@ -267,7 +267,8 @@ static void ddh_prepare(void) {
// the parent records which thread forks each child (ddh_forked_by()); a child refuses a handoff
// when it cannot (ddh_try())
if (getenv("DD_SPAWN")) ddh_forks(1);
if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN")) return;
// A thread with a table of its own makes none: its fd would be in no other thread's table.
if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN") || t_kept_split) return;
// Not cancelled from taking the guard to giving it back (the wait for earlier closes sleeps, a
// cancellation point, and asynchronous cancellation could strike anywhere), which would leave the
// guard taken and the candidate's state half kept for every later fork. The guard goes back
@@ -430,14 +431,16 @@ static int g_ddh_nbinder;
static pid_t g_ddh_worker;
// Both change the list only between kept_change_begin() and kept_change_end() (hook/privileged.c),
// as other threads may be reading it.
// as other threads may be reading it. A thread with a table of its own changes its own copy.
static void ddh_unkeep(int fd) {
kept_change_begin();
int n = g_kept_fd_count;
int *fds = t_kept_split ? t_kept_fds : g_kept_fds;
int *count = t_kept_split ? &t_kept_count : &g_kept_fd_count;
int n = *count;
for (int i = 0; i < n; i++) {
if (g_kept_fds[i] != fd) continue;
for (int j = i; j + 1 < n; j++) __atomic_store_n(&g_kept_fds[j], g_kept_fds[j + 1], __ATOMIC_RELAXED);
__atomic_store_n(&g_kept_fd_count, n - 1, __ATOMIC_RELAXED);
if (fds[i] != fd) continue;
for (int j = i; j + 1 < n; j++) __atomic_store_n(&fds[j], fds[j + 1], __ATOMIC_RELAXED);
__atomic_store_n(count, n - 1, __ATOMIC_RELAXED);
break;
}
kept_change_end();
@@ -445,16 +448,18 @@ static void ddh_unkeep(int fd) {
static void ddh_keep(int fd) {
kept_change_begin();
int n = g_kept_fd_count, found = 0;
for (int i = 0; i < n; i++) found |= g_kept_fds[i] == fd;
int *fds = t_kept_split ? t_kept_fds : g_kept_fds;
int *count = t_kept_split ? &t_kept_count : &g_kept_fd_count;
int n = *count, found = 0;
for (int i = 0; i < n; i++) found |= fds[i] == fd;
if (n < DDNATV_MAX_KEPT_FDS && !found) {
int i = n;
while (i > 0 && g_kept_fds[i - 1] > fd) {
__atomic_store_n(&g_kept_fds[i], g_kept_fds[i - 1], __ATOMIC_RELAXED);
while (i > 0 && fds[i - 1] > fd) {
__atomic_store_n(&fds[i], fds[i - 1], __ATOMIC_RELAXED);
i--;
}
__atomic_store_n(&g_kept_fds[i], fd, __ATOMIC_RELAXED);
__atomic_store_n(&g_kept_fd_count, n + 1, __ATOMIC_RELAXED);
__atomic_store_n(&fds[i], fd, __ATOMIC_RELAXED);
__atomic_store_n(count, n + 1, __ATOMIC_RELAXED);
}
kept_change_end();
}
@@ -523,6 +528,9 @@ static int g_ddh_parent_spare = -1;
static int g_ddh_pidfd_move;
static int ddh_parent_pidfd_moves(int target) {
// In a table of its own, a kept number the program takes over is let go of in this thread's copy
// only: the other threads' pidfd stays where it is.
if (t_kept_split) return target >= 0 && is_kept_fd(target) ? target : -1;
int fd = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE);
int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE);
if (target < 0 || (target != fd && target != spare)) return -1;
@@ -539,6 +547,10 @@ static int ddh_parent_pidfd_moves(int target) {
static void ddh_parent_pidfd_settle(int from, int done) {
if (from < 0) return;
if (t_kept_split) {
if (done) ddh_unkeep(from);
return;
}
int move = g_ddh_pidfd_move;
g_ddh_pidfd_move = 0;
// the program's file now: its close() closes it
@@ -1302,6 +1314,13 @@ static void ddh_try_as(const char *filename, char *const argv[], char *const env
table = g_ddh_up;
table_fd = g_ddh_up_fd;
} else {
table = NULL;
table_fd = -1;
}
// After a split (here or in the thread that forked this process), the table's number is this
// table's only while it is still kept here: one made later by another thread is in no copy.
if (table_fd >= 0 && (t_kept_split || g_kept_split) && !is_kept_fd(table_fd)) table_fd = -1;
if (table_fd < 0) {
if (ddh_env(envp, "DD_HANDOFF_DEBUG")) {
char why[160];
snprintf(why, sizeof(why), "not a child its parent can track (table %d owner %d up %d up-owner %d ppid %d):",
@@ -2231,13 +2250,19 @@ static int ddh_parent_lives(pid_t parent, long child_start) {
int blocked = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) >= 0 &&
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0) == 0;
int locked = blocked && pthread_mutex_trylock(&g_ddh_pidfd_lock) == 0;
int fd = locked ? __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) : -1;
int held = locked ? __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) : -1;
int fd = held;
if (fd >= 0 && t_kept_split && !is_kept_fd(fd)) {
// a table of its own, where the program took that number over: the spare, if still there
int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE);
fd = spare >= 0 && is_kept_fd(spare) ? spare : -1;
}
if (parent == g_ddh_report_parent && fd >= 0) {
// No new fd, and exited counts whether reaped or not. Only while the number still is that
// pidfd, before and after the poll (a raw close() can take it), and only a clear answer:
// anything else asks /proc.
char path[32], before[32], after[32];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
// anything else asks /proc. This thread's table, which is not the first thread's after a split.
char path[40], before[32], after[32];
snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", fd);
int saved = errno;
long len = syscall(SYS_readlinkat, AT_FDCWD, path, before, sizeof(before) - 1);
struct pollfd p = {fd, POLLIN, 0};
@@ -2247,7 +2272,7 @@ static int ddh_parent_lives(pid_t parent, long child_start) {
if (len > 0) before[len] = 0;
if (len2 > 0) after[len2] = 0;
int clear = n >= 0 && len2 > 0 && strcmp(before, "anon_inode:[pidfd]") == 0 && strcmp(after, before) == 0 &&
__atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) == fd && !(p.revents & (POLLNVAL | POLLERR));
__atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) == held && !(p.revents & (POLLNVAL | POLLERR));
pthread_mutex_unlock(&g_ddh_pidfd_lock);
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0);
if (clear) return !(p.revents & POLLIN);
+69
View File
@@ -24,7 +24,23 @@ static unsigned g_kept_seq;
static pthread_mutex_t g_kept_lock = PTHREAD_MUTEX_INITIALIZER;
static __thread uint64_t t_kept_mask;
// A thread that split its descriptor table from the others' (close_range() with
// CLOSE_RANGE_UNSHARE) goes on with a copy of the list made at the split, which only it reads and
// changes: the shared list keeps describing the other threads' table, so a kept fd this thread's
// program takes over (a dup2() onto the parent's pidfd) stays kept there. A child it forks takes the
// copy over as its list (kept_forked()).
static __thread int t_kept_split;
static __thread int t_kept_fds[DDNATV_MAX_KEPT_FDS];
static __thread int t_kept_count;
// In a process forked from such a thread: numbers published for the shared table (the handoff table's)
// may name other files here, or none.
static int g_kept_split;
static int kept_snapshot(int *out) {
if (t_kept_split) {
for (int i = 0; i < t_kept_count; i++) out[i] = t_kept_fds[i];
return t_kept_count;
}
for (;;) {
unsigned seq = __atomic_load_n(&g_kept_seq, __ATOMIC_ACQUIRE);
if (seq & 1) continue;
@@ -59,6 +75,59 @@ static void kept_change_end(void) {
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&t_kept_mask, 0, 8, 0, 0);
}
static int kept_any(void) {
return t_kept_split ? t_kept_count : __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED);
}
// The process's threads (/proc/self/stat), or 0 when it cannot be read.
static int kept_threads(void) {
char buf[512];
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc/self/stat",
O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)buf, sizeof(buf) - 1, 0, 0, 0);
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
if (n <= 0) return 0;
buf[n] = 0;
char *p = strrchr(buf, ')');
// after the name: state, then 16 fields to num_threads
for (int field = 0; p && field < 18; field++) p = strchr(p + 1, ' ');
return p ? atoi(p + 1) : 0;
}
// The calling thread's table split by split() (0, or -1 with errno), with the list copied for it in
// the same step: no keep or let-go of another thread falls between the copy and the split. A process
// with one thread keeps one table (the system copies only a shared one), and so one list. Threads that
// a thread with a table of its own starts later share that table but not its copy: not followed.
static int kept_split(int (*split)(void)) {
if (t_kept_split) return split();
uint64_t all = ~0ull, mask = 0;
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0);
pthread_mutex_lock(&g_kept_lock);
int shared = kept_threads() != 1;
int r = split();
int saved = errno;
if (r == 0 && shared) {
int n = g_kept_fd_count;
for (int i = 0; i < n; i++) t_kept_fds[i] = g_kept_fds[i];
t_kept_count = n;
t_kept_split = 1;
}
pthread_mutex_unlock(&g_kept_lock);
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0);
errno = saved;
return r;
}
// In a forked child, whose only thread is the one that forked: a split thread's table is the child's.
static void kept_forked(void) {
if (!t_kept_split) return;
for (int i = 0; i < t_kept_count; i++) g_kept_fds[i] = t_kept_fds[i];
g_kept_fd_count = t_kept_count;
t_kept_split = 0;
g_kept_split = 1;
}
static int is_kept_fd(int fd) {
int kept[DDNATV_MAX_KEPT_FDS];
int n = kept_snapshot(kept);
+1 -1
View File
@@ -242,7 +242,7 @@ int close(int fd) {
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
uint64_t ticket = kept_close_begin();
// The ARM translator's memory file (privileged.c): left open, as if it were closed
if (g_kept_fd_count > 0 && is_kept_fd(fd)) {
if (kept_any() > 0 && is_kept_fd(fd)) {
kept_close_end(ticket);
return 0;
}
+19 -12
View File
@@ -428,24 +428,31 @@ static int close_range_part(unsigned int first, unsigned int last, void *flags)
return close_range_all(first, last, *(int *)flags);
}
// The system call itself on the one number no fd has (close_range_all() would emulate a missing call
// by closing fds)
static int close_range_unshare(void) {
static long (*raw_syscall)(long, ...) = NULL;
if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (!raw_syscall) {
errno = ENOSYS;
return -1;
}
return raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) == 0 ? 0 : -1;
}
static int close_range_kept(unsigned int first, unsigned int last, int flags) {
// The table is unshared first, once, even when every fd in the range is kept, and this thread
// goes on with its own copy of the kept list (kept_split()). Without the system call, it is
// emulated where nothing is kept, and refused otherwise.
if (flags & CLOSE_RANGE_UNSHARE) {
if (kept_split(close_range_unshare) == 0) flags &= ~CLOSE_RANGE_UNSHARE;
else if (errno != ENOSYS || kept_any() > 0) return -1;
}
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
if (kept_count == 0) return close_range_part(first, last, &flags);
// The table is unshared once, even when every fd in the range is kept: the system call itself on
// the one number no fd has (close_range_all() would emulate a missing call by closing fds)
if (flags & CLOSE_RANGE_UNSHARE) {
static long (*raw_syscall)(long, ...) = NULL;
if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (!raw_syscall) {
errno = ENOSYS;
return -1;
}
if (raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) != 0) return -1;
flags &= ~CLOSE_RANGE_UNSHARE;
}
return for_each_range_without(first, last, kept, kept_count, close_range_part, &flags);
}
+64
View File
@@ -919,6 +919,59 @@ int main(void) {
}
"""
# A worker's program where one thread gives itself a table of its own (close_range() with
# CLOSE_RANGE_UNSHARE) and takes the parent's pidfd number over with dup2(), then closes it there.
# The first thread's table still holds the pidfd, which its close() leaves open.
SPLIT = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef CLOSE_RANGE_UNSHARE
#define CLOSE_RANGE_UNSHARE (1U << 1)
#endif
static int split_closed, own_closed;
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 void *splitter(void *file) {
long r = syscall(SYS_close_range, 950, 950, CLOSE_RANGE_UNSHARE);
split_closed = r == 0 && fcntl(950, F_GETFD) == -1;
dup2(*(int *)file, 900);
close(900);
own_closed = fcntl(900, F_GETFD) == -1;
return NULL;
}
int main(void) {
printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]"));
int file = open("/dev/null", O_WRONLY);
if (dup2(file, 950) != 950) return 1;
pthread_t thread;
pthread_create(&thread, NULL, splitter, &file);
pthread_join(thread, NULL);
printf("split\t%d\n", split_closed);
printf("own\t%d\n", own_closed);
printf("shared\t%d\n", is(950, "/dev/null"));
close(900);
printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]"));
printf("parent\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>
@@ -1654,6 +1707,17 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual("1", result.get("table"), out.stdout)
self.assertEqual(str(parent), result.get("parent"), out.stdout)
def test_a_thread_with_a_table_of_its_own_takes_the_pidfd_number_there_only(self):
parent, result, out = self.run_worker_program("split", SPLIT)
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual("1", result.get("kept"), out.stdout + out.stderr)
# the split thread closed its own copies, the first thread's table is untouched
self.assertEqual("1", result.get("split"), out.stdout)
self.assertEqual("1", result.get("own"), out.stdout)
self.assertEqual("1", result.get("shared"), out.stdout)
self.assertEqual("1", result.get("pidfd"), out.stdout)
self.assertEqual(str(parent), result.get("parent"), out.stdout)
def test_a_table_made_while_a_close_range_runs_stays_open(self):
# made by the first fork, as when making it at the start failed
result, requests, out = self.run_parent("prepclose", "4", extra_env={"DDH_TEST_LATE_TABLE": "1"})