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);