fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept

This commit is contained in:
Kurt Himebauch committed 2026-11-28 09:51:07 -05:00
1 parent adb0a27a68
commit c16515fc49
2 files changed
+20 -5

No files matched your search

+12 -1
View File
@@ -149,7 +149,18 @@ static void ddh_forked_by(pid_t child, pid_t thread) {
int saved = errno;
long start = ddh_start_time(child);
errno = saved;
__atomic_store_n(&map[(uint32_t)child % DDH_FORKS], ddh_fork_record(child, thread, start), __ATOMIC_RELEASE);
uint64_t mine = ddh_fork_record(child, thread, start);
uint64_t *slot = &map[(uint32_t)child % DDH_FORKS];
uint64_t seen = __atomic_load_n(slot, __ATOMIC_ACQUIRE);
for (;;) {
// A later child given the pid (this one reaped while its fork was being recorded) has
// recorded itself already: its record stays. Start times compared within their 19 bits.
if (seen && ddh_record_child(seen) == child && (seen & 0x80000) && (mine & 0x80000)) {
uint64_t theirs = seen & 0x7ffff, ours = mine & 0x7ffff;
if (theirs != ours && ((theirs - ours) & 0x7ffff) < 0x40000) return;
}
if (__atomic_compare_exchange_n(slot, &seen, mine, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) return;
}
}
// The thread that forked child, by the record of the fork whose child started at child_start (-1:
+8 -4
View File
@@ -251,11 +251,13 @@ int close(int fd) {
int dup2(int oldfd, int newfd) {
static int (*orig_dup2)(int, int) = NULL;
if (!orig_dup2) orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
int pidfd_from = -1, locked = ddh_parent_pidfd_lock(oldfd != newfd ? newfd : -1);
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
pidfd_from = ddh_parent_pidfd_moves(newfd);
// the bookkeeping's own locks before the pidfd's: its holder waits on nothing else
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
@@ -269,11 +271,13 @@ int dup2(int oldfd, int newfd) {
int dup3(int oldfd, int newfd, int flags) {
static int (*orig_dup3)(int, int, int) = NULL;
if (!orig_dup3) orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
int pidfd_from = -1, locked = ddh_parent_pidfd_lock(oldfd != newfd ? newfd : -1);
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
pidfd_from = ddh_parent_pidfd_moves(newfd);
// the bookkeeping's own locks before the pidfd's: its holder waits on nothing else
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);