From 61bc8e03b2bdbed6f5bdc047e10d3fda292c9996 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:46:29 -0500 Subject: [PATCH] fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits --- .../launcher/runtime/GuestWorkers.kt | 5 +- tools/nativeguest/hook/exec.c | 7 +- tools/nativeguest/hook/handoff.c | 209 ++++++++++++------ tools/tests/test_native_hook_handoff.py | 67 ++++-- 4 files changed, 203 insertions(+), 85 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index 5b099db5b1..48838652a9 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -714,7 +714,10 @@ object GuestWorkers { env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path // The hook restores these in the program (tools/nativeguest/hook/handoff.c). if (request.has("sigign")) env["DDH_SIGIGN"] = request.getLong("sigign").toString() - if (request.has("nofile")) env["DDH_NOFILE"] = request.getLong("nofile").toString() + if (request.has("nofile")) { + env["DDH_NOFILE"] = request.getLong("nofile").toString() + + (if (request.has("nofilemax")) ":" + request.getLong("nofilemax") else "") + } if (request.has("umask")) env["DDH_UMASK"] = request.getLong("umask").toString() if (request.has("pgid")) env["DDH_PGID"] = request.getLong("pgid").toString() if (request.has("anchor")) env["DDH_ANCHOR"] = request.getLong("anchor").toString() diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 897c61a361..f8e5cdb8d5 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -661,12 +661,13 @@ pid_t fork(void) { if (n == 1 || n >= DDNATV_FORKS_BEFORE_REHEARSAL) prepare_exec_in_parent(n >= DDNATV_FORKS_BEFORE_REHEARSAL ? 2 : 1); } ddh_prepare(); + pid_t forker = (pid_t)syscall(SYS_gettid); pid_t pid = orig_fork(); if (pid == 0) { ddh_drop_worker_binder(); - ddh_forked(); + ddh_forked(forker); } else if (pid > 0) { - ddh_child_created(pid); + ddh_child_created(pid, 1); } // A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its // execve() is a real one (only read in the usual case, so no page is copied for it) @@ -1265,7 +1266,7 @@ int posix_spawn(pid_t *pid, const char *path, pid_t child = 0; int ret = ddnatv_posix_spawn(&child, path, file_actions, attr, argv, envp, 0); if (ret == 0) { - ddh_child_created(child); + ddh_child_created(child, 0); if (pid) *pid = child; } return ret; diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 08e18bc8e5..13659cc32f 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -106,35 +106,46 @@ static int g_ddh_preparing; // Set by the waits with __WNOTHREAD: only children this thread forked are selected. static __thread pid_t t_ddh_only_thread; -// Which of this process's threads forked which child, as the fork() and posix_spawn() wrappers saw -// it, in this process's own memory: the child may exec wrappers before it claims an entry, and those -// cannot carry it. One record per pid, at the pid's own index: two live children never share a pid, -// so nothing is ever full or pushed out, and a fork that gets a pid replaces whatever record a gone -// child left there; a record is never removed, and the child's start time in it tells it from a -// later child's. Mapped when first needed, and only the pages of pids used are ever touched. One -// word: a record is only ever whole. A child not in here (a raw clone()) is no thread's for a -// __WNOTHREAD wait. +// Which of this process's threads forked which child, in memory this process shares with the +// children it forks: the child may exec wrappers before it claims an entry, and those cannot carry +// it. One record per pid, at the pid's own index: two live children never share a pid, so nothing is +// ever full or pushed out, and a fork that gets a pid replaces whatever record a gone child left +// there; a record is never removed, and the child's start time in it tells it from a later child's. +// A child of fork() writes its own record before it can exit, so before its pid can be anyone +// else's (ddh_forked()); a posix_spawn() child runs nothing of this before its exec, so the parent +// writes its record once the call returns, by when it may be gone (ddh_forked_by()). Mapped when +// first needed, and only the pages of pids used are ever touched. One word: a record is only ever +// whole. A child not in here (a raw clone()) is no thread's for a __WNOTHREAD wait. #define DDH_FORKS (1u << 22) /* PID_MAX_LIMIT */ static uint64_t *g_ddh_forks; -// child << 42 | thread << 20 | known << 19 | the child's start time's low 19 bits: pids and thread -// ids are below 2^22 (PID_MAX_LIMIT). The start time tells the record of one child from that of a -// later one given the same pid: a handoff entry holds its forked child's start time (child_start), -// and a record that does not match it is not that child's. Without the known bit it was not read, -// and matches any; 19 bits are 2^19 clock ticks (87 minutes at 100 Hz) apart. +// child << 42 | thread << 20 | known << 19 | self << 18 | the child's start time's low 18 bits: pids +// and thread ids are below 2^22 (PID_MAX_LIMIT). The start time tells the record of one child from +// that of a later one given the same pid: a handoff entry holds its forked child's start time +// (child_start), and a record that does not match it is not that child's. Without the known bit it +// was not read, and matches any; 18 bits are 2^18 clock ticks (43 minutes at 100 Hz) apart. Self: +// the child wrote it, while it had the pid. +#define DDH_REC_KNOWN 0x80000u +#define DDH_REC_SELF 0x40000u +#define DDH_REC_START 0x3ffffu static long ddh_start_time(pid_t pid); -static uint64_t ddh_fork_record(pid_t child, pid_t thread, long start) { - uint64_t when = start > 0 ? ((uint64_t)start & 0x7ffff) | 0x80000 : 0; +static uint64_t ddh_fork_record(pid_t child, pid_t thread, long start, int self) { + uint64_t when = start > 0 ? ((uint64_t)start & DDH_REC_START) | DDH_REC_KNOWN : 0; + if (self) when |= DDH_REC_SELF; return (uint64_t)((uint32_t)child & 0x3fffff) << 42 | (uint64_t)((uint32_t)thread & 0x3fffff) << 20 | when; } static pid_t ddh_record_child(uint64_t r) { return (pid_t)(r >> 42); } static pid_t ddh_record_thread(uint64_t r) { return (pid_t)((r >> 20) & 0x3fffff); } +// Whether a record names a child that started at start (a time read for it, > 0) +static int ddh_record_started(uint64_t r, long start) { + return (r & DDH_REC_KNOWN) && start > 0 && ((uint64_t)start & DDH_REC_START) == (r & DDH_REC_START); +} static uint64_t *ddh_forks(int create) { uint64_t *map = __atomic_load_n(&g_ddh_forks, __ATOMIC_ACQUIRE); if (map || !create) return map; void *fresh = mmap(NULL, (size_t)DDH_FORKS * sizeof(uint64_t), PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); if (fresh == MAP_FAILED) return NULL; uint64_t *none = NULL; if (__atomic_compare_exchange_n(&g_ddh_forks, &none, (uint64_t *)fresh, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) @@ -147,42 +158,47 @@ static uint64_t *ddh_forks(int create) { // whose exit is not yet reported: such a child loses its __WNOTHREAD owner with its record. static int ddh_record_pending(uint64_t r) { struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); - if (!t || !(r & 0x80000)) return 0; + if (!t || !(r & DDH_REC_KNOWN)) return 0; pid_t me = getpid(), child = ddh_record_child(r); for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &t->e[i]; int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->parent == me && e->child == child && - e->child_start > 0 && ((uint64_t)e->child_start & 0x7ffff) == (r & 0x7ffff)) return 1; + ddh_record_started(r, (long)e->child_start)) return 1; } return 0; } +// The record of a posix_spawn() child, by the parent: by now the child may be gone, its pid another +// child's. static void ddh_forked_by(pid_t child, pid_t thread) { uint64_t *map = ddh_forks(1); if (!map || child <= 0) return; int saved = errno; long start = ddh_start_time(child); errno = saved; - uint64_t mine = ddh_fork_record(child, thread, start); + uint64_t mine = ddh_fork_record(child, thread, start, 0); 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. It is that child's only while the process that - // has the pid now started when it says; any other record of the pid is an earlier child's. - // A record without a start time (this child was gone before it was read) matches any child of - // the pid, a later one's too. - if (seen && ddh_record_child(seen) == child && (seen & 0x80000) && - (!(mine & 0x80000) || (seen & 0x7ffff) != (mine & 0x7ffff))) { - saved = errno; - long now = ddh_start_time(child); - errno = saved; - if (now > 0 && ((uint64_t)now & 0x7ffff) == (seen & 0x7ffff)) return; - // Neither child has the pid now: one whose program still runs in a worker, its forked - // child reaped by another thread, keeps its record unless this child's runs too. - int now_mine = (mine & 0x80000) && now > 0 && ((uint64_t)now & 0x7ffff) == (mine & 0x7ffff); - if (!now_mine && ddh_record_pending(seen) && !ddh_record_pending(mine)) return; + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_KNOWN)) { + // A child that recorded itself, started when the time read here says, has the pid: this + // one is gone, and that time was the other child's. + if ((seen & DDH_REC_SELF) && ddh_record_started(seen, start)) return; + // A later child given the pid (this one reaped while its record was being made) has + // recorded itself already: its record stays. It is that child's only while the process + // that has the pid now started when it says; any other record of the pid is an earlier + // child's. A record without a start time (this child was gone before it was read) + // matches any child of the pid, a later one's too. + if (!ddh_record_started(seen, start)) { + saved = errno; + long now = ddh_start_time(child); + errno = saved; + if (ddh_record_started(seen, now)) return; + // Neither child has the pid now: one whose program still runs in a worker, its + // forked child reaped by another thread, keeps its record unless this child's runs too. + if (!ddh_record_started(mine, now) && ddh_record_pending(seen) && !ddh_record_pending(mine)) return; + } } if (__atomic_compare_exchange_n(slot, &seen, mine, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) return; } @@ -194,18 +210,25 @@ static pid_t ddh_forking_thread(pid_t child, long child_start) { uint64_t *map = ddh_forks(0); uint64_t r = map && child > 0 ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0; if (!r || ddh_record_child(r) != child) return 0; - uint64_t when = r & 0xfffff; - if ((when & 0x80000) && child_start > 0 && (when & 0x7ffff) != ((uint64_t)child_start & 0x7ffff)) return 0; // another child's + if ((r & DDH_REC_KNOWN) && child_start > 0 && !ddh_record_started(r, child_start)) return 0; // another child's return ddh_record_thread(r); } -// In a forked child: the thread making the table did not come along, so the child may make its own. -// The parent's fork records came along too, for pids that are not the child's children: it starts -// with an empty table (none, if it cannot map one, and then hands nothing off). -static void ddh_forked(void) { +// In a forked child, by the thread that forked it: the child records itself in the parent's fork +// records first, while its pid is still its own. The thread making the table did not come along, so +// the child may make its own, and fork records of its own: it starts with an empty map (none, if it +// cannot map one, and then hands nothing off). +static void ddh_forked(pid_t thread) { __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELAXED); uint64_t *old = __atomic_exchange_n(&g_ddh_forks, NULL, __ATOMIC_ACQ_REL); if (!old) return; + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) { + int saved = errno; + pid_t me = (pid_t)syscall(SYS_getpid); + uint64_t mine = ddh_fork_record(me, thread, ddh_start_time(me), 1); + __atomic_store_n(&old[(uint32_t)me % DDH_FORKS], mine, __ATOMIC_RELEASE); + errno = saved; + } munmap(old, (size_t)DDH_FORKS * sizeof(uint64_t)); ddh_forks(1); } @@ -405,6 +428,20 @@ 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; +} + 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; @@ -413,27 +450,31 @@ static int ddh_parent_pidfd_moves(int target) { __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; + } return fd; } 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), the original is tracked again and the copy goes, - // its kept slot first so that a full list has room; otherwise the copy stays the pidfd. - char path[32], target[32]; - snprintf(path, sizeof(path), "/proc/self/fd/%d", from); - int saved = errno; - long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); - errno = saved; - if (len <= 0) return; - target[len] = 0; - if (strcmp(target, "anon_inode:[pidfd]") != 0) return; - int moved = __atomic_exchange_n(&g_ddh_parent_pidfd, from, __ATOMIC_ACQ_REL); - if (moved >= 0 && moved != from) ddh_unkeep(moved); + // 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)) { + ddh_unkeep(from); + return; + } + int moved = __atomic_exchange_n(&g_ddh_parent_pidfd, from, __ATOMIC_ACQ_REL); if (moved >= 0 && moved != from) { - saved = errno; + ddh_unkeep(moved); + int saved = errno; syscall(SYS_close, moved); errno = saved; } @@ -705,8 +746,15 @@ static void ddh_apply_inherited(void) { const char *nofile = getenv("DDH_NOFILE"); if (nofile) { struct rlimit lim; + // "SOFT:HARD": both as the forked child had them, the hard limit too, which a program can + // only lower (no higher than the worker's) if (getrlimit(RLIMIT_NOFILE, &lim) == 0) { - rlim_t want = (rlim_t)strtoull(nofile, NULL, 10); + char *end = NULL; + rlim_t want = (rlim_t)strtoull(nofile, &end, 10); + if (end && *end == ':') { + rlim_t hard = (rlim_t)strtoull(end + 1, NULL, 10); + if (hard < lim.rlim_max) lim.rlim_max = hard; + } lim.rlim_cur = want < lim.rlim_max ? want : lim.rlim_max; setrlimit(RLIMIT_NOFILE, &lim); } @@ -906,17 +954,43 @@ static const char *ddh_interpreter(const char *path, char *buf, size_t size) { return name; } -// Whether an exec of path would get as far as the program: an ELF file, or a script whose "#!" -// interpreter is there to run. Anything else fails in the exec, which must happen here then, so that -// the caller (posix_spawn() above all) gets its error rather than a worker's exit status. +// An aarch64 ELF image the kernel would load, whose interpreter, if it names one, is in the guest's +// root; fd is the image. +static int ddh_elf_startable(int fd) { + Elf64_Ehdr eh; + if (syscall(SYS_pread64, fd, &eh, sizeof(eh), 0) != (long)sizeof(eh) || eh.e_ident[EI_CLASS] != ELFCLASS64 || + eh.e_machine != EM_AARCH64 || (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || + eh.e_phentsize != sizeof(Elf64_Phdr) || eh.e_phnum == 0 || eh.e_phnum > 64) + return 0; + for (int i = 0; i < eh.e_phnum; i++) { + Elf64_Phdr ph; + if (syscall(SYS_pread64, fd, &ph, sizeof(ph), (long)(eh.e_phoff + (Elf64_Off)i * sizeof(ph))) != (long)sizeof(ph)) + return 0; + if (ph.p_type != PT_INTERP) continue; + char interp[PATH_MAX], real[PATH_MAX]; + if (ph.p_filesz == 0 || ph.p_filesz >= sizeof(interp) || + syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) + return 0; + interp[ph.p_filesz] = 0; + return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(interp, real, sizeof(real)), + R_OK, 0, 0, 0) == 0; + } + return 1; +} + +// Whether an exec of path would get as far as the program: an ELF image the kernel would load, or a +// script whose "#!" interpreter is there to run. Anything else fails in the exec, which must happen +// here then, so that the caller (posix_spawn() above all) gets its error rather than a worker's exit +// status. static int ddh_startable(const char *path) { char real[PATH_MAX], head[256]; int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(path, real, sizeof(real)), O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (fd < 0) return 0; long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)head, sizeof(head) - 1, 0, 0, 0); + int elf = n >= 4 && memcmp(head, "\177ELF", 4) == 0 && ddh_elf_startable(fd); syscall(SYS_close, fd); - if (n >= 4 && memcmp(head, "\177ELF", 4) == 0) return 1; + if (n >= 4 && memcmp(head, "\177ELF", 4) == 0) return elf; if (n < 3 || head[0] != '#' || head[1] != '!') return 0; head[n] = 0; char *p = head + 2; @@ -1274,6 +1348,8 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] ddh_putint(&b, (long)ignored); ddh_puts(&b, ",\"nofile\":"); ddh_putint(&b, (long)nofile.rlim_cur); + ddh_puts(&b, ",\"nofilemax\":"); + ddh_putint(&b, (long)nofile.rlim_max); ddh_puts(&b, ",\"umask\":"); ddh_putint(&b, (long)mask); ddh_puts(&b, ",\"pgid\":"); @@ -1502,13 +1578,13 @@ static void ddh_record_gate(void) { errno = saved; } -static void ddh_child_created(pid_t pid) { +// A new child at pid, which recorded itself (a fork() child) or is recorded here (a spawned one) +static void ddh_child_created(pid_t pid, int recorded) { if (pid <= 0) return; ddh_record_gate(); ddh_drop_stale(pid); - // after the drop, whose release forgets the pid's old record; only where children can hand off, - // and their waits forget them again - if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) ddh_forked_by(pid, (pid_t)syscall(SYS_gettid)); + // only where children can hand off + if (!recorded && __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) ddh_forked_by(pid, (pid_t)syscall(SYS_gettid)); } // Takes e's exit for a wait for pid, checked again once taken: between finding e and taking it, @@ -1684,7 +1760,12 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { errno = ENOSYS; return -1; } - if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return real(pid, status, options, ru); + // As waitid(): the kernel's alone for options it refuses (WNOWAIT among them), and for __WCLONE + // alone, which selects no forked child + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || + (options & ~(WNOHANG | WUNTRACED | WCONTINUED | __WALL | __WNOTHREAD | __WCLONE)) || + ((options & __WCLONE) && !(options & __WALL))) + return real(pid, status, options, ru); // After a nap a signal interrupted, one more look before EINTR: the signal may be the SIGCHLD // that reports an exit. int interrupted = 0; @@ -1763,7 +1844,7 @@ static pid_t ddh_wait_as_thread(pid_t pid, int *status, int options, struct rusa pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru) { return ddh_wait_as_thread(pid, status, options, ru); } pid_t waitpid(pid_t pid, int *status, int options) { return ddh_wait_as_thread(pid, status, options, NULL); } pid_t wait(int *status) { return ddh_wait(-1, status, 0, NULL); } -pid_t wait3(int *status, int options, struct rusage *ru) { return ddh_wait(-1, status, options, ru); } +pid_t wait3(int *status, int options, struct rusage *ru) { return ddh_wait_as_thread(-1, status, options, ru); } static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { typedef int (*f_t)(idtype_t, id_t, siginfo_t *, int); diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 0c4e93e9a1..efa66fe81c 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -102,20 +102,20 @@ static void *nothread_forker(void *unused) { return NULL; } -// laterecord: this thread's fork is recorded only once the hook's test gate opens, by when its child -// is gone and a later child of the main thread has its pid, handed off and its forked child reaped -static int late_pid[2], late_hold[2], late_gate; +// laterecord: a program this thread spawns (not listed: glibc's posix_spawn(), recorded by the +// parent) is recorded only once the hook's test gate opens, by when it is gone and a later child of +// the main thread has its pid, handed off and its forked child reaped +static int late_done[2], late_hold[2], late_gate; -static void *late_forker(void *unused) { +static void *late_spawner(void *unused) { (void)unused; char gate[32]; snprintf(gate, sizeof(gate), "%d %d", late_gate, (int)syscall(SYS_gettid)); setenv("DDH_TEST_RECORD_GATE", gate, 1); - pid_t pid = fork(); - if (pid == 0) { - pid_t me = getpid(); - _exit(write(late_pid[1], &me, sizeof(me)) == sizeof(me) ? 0 : 1); - } + pid_t pid = 0; + char *args[] = {"wrap", NULL}; // exits at once: nothing to wrap + int err = posix_spawn(&pid, "/bin/wrap", NULL, NULL, args, environ); + if (write(late_done[1], &err, sizeof(err)) != sizeof(err)) _exit(123); // recorded char c; if (read(late_hold[0], &c, 1) != 1) _exit(124); // alive while the main thread's wait looks return NULL; @@ -123,13 +123,15 @@ static void *late_forker(void *unused) { static int late_record(const char *arg) { int gate[2]; - if (pipe(gate) != 0 || pipe(late_pid) != 0 || pipe(late_hold) != 0) return 1; + if (pipe(gate) != 0 || pipe(late_done) != 0 || pipe(late_hold) != 0) return 1; late_gate = gate[0]; - pthread_t forker; - pthread_create(&forker, NULL, late_forker, NULL); + pthread_t spawner; + pthread_create(&spawner, NULL, late_spawner, NULL); + // the spawned program, reaped: the only child yet pid_t first = 0; int status = 0; - if (read(late_pid[0], &first, sizeof(first)) != sizeof(first) || waitpid(first, &status, 0) != first) return 1; + for (int i = 0; i < 3000 && (first = waitpid(-1, &status, WNOHANG)) <= 0; i++) usleep(10000); + if (first <= 0) return 1; // the next fork gets the pid again FILE *f = fopen("/proc/sys/kernel/ns_last_pid", "w"); if (!f) return 1; @@ -149,13 +151,14 @@ static int late_record(const char *arg) { usleep(10000); } printf("reaped\t%d\n", access(path, F_OK) != 0); - if (write(gate[1], "1", 1) != 1) return 1; - usleep(300000); // the forking thread has recorded its own fork by now + int err = -1; + if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; + printf("spawned\t%d\n", err); printf("own\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WNOTHREAD) == 0); kill(pid, SIGKILL); printf("ended\t%d\n", waitpid(pid, &status, 0) == pid && WIFSIGNALED(status)); if (write(late_hold[1], "1", 1) != 1) return 1; - pthread_join(forker, NULL); + pthread_join(spawner, NULL); return 0; } @@ -251,6 +254,7 @@ int main(int argc, char **argv) { int status = 0; printf("other\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WNOTHREAD)); printf("otherpid\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + printf("otherwait3\t%d\n", (int)wait3(&status, WNOHANG | __WNOTHREAD, NULL)); nothread_go(2); pthread_join(forker, NULL); return 0; @@ -324,6 +328,14 @@ int main(int argc, char **argv) { printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); return 0; } + if (strcmp(argv[1], "badopts") == 0) { + usleep(1500000); // the program has exited by now + // refused (WNOWAIT is waitid()'s) or selecting no forked child (__WCLONE alone): the exit stays + errno = 0; + printf("nowait\t%d\n", (int)wait4(-1, &status, WNOHANG | WNOWAIT, NULL) == -1 && errno == EINVAL); + printf("clone\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WCLONE) != pid); + printf("cloneall\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WCLONE) != pid); + } int group = strcmp(argv[1], "group") == 0; if (group) { setpgid(pid, pid); @@ -719,9 +731,27 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual(1, len(requests), out.stderr) self.assertEqual("-1", result.get("other"), out.stdout) self.assertEqual("-1", result.get("otherpid"), out.stdout) + self.assertEqual("-1", result.get("otherwait3"), out.stdout) self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), out.stdout) + def test_a_wait_with_options_wait4_refuses_or_clone_only_leaves_the_exit(self): + result, requests, out = self.run_parent("badopts", "5") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("nowait"), out.stdout) + self.assertEqual("1", result.get("clone"), out.stdout) + self.assertEqual("1", result.get("cloneall"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("5", result.get("exit"), out.stdout) + + def test_a_posix_spawn_of_a_file_with_only_the_elf_magic_fails_as_it_would(self): + stub = self.root / "bin/stub" + stub.write_bytes(b"\x7fELF") + stub.chmod(0o755) + result, requests, out = self.run_parent("spawn", "6", "/bin/stub", handoff="stub") + self.assertEqual([], requests) + self.assertNotEqual("0", result.get("spawned"), out.stdout) + def test_wnothread_child_goes_to_the_first_live_thread(self): # The forking thread and the main one both ended. Which thread the kernel gives the child to # (qemu-user has a thread of its own first) is what the same program shows without the hook. @@ -744,7 +774,7 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), out.stdout) - def test_a_late_record_of_an_earlier_child_keeps_a_handed_off_childs_owner(self): + def test_a_late_record_of_a_spawned_child_keeps_a_handoffs_owner(self): # the pid has to be given again, which only a pid namespace of the test's own allows if not os.environ.get("DDH_TEST_PIDNS"): unshare = shutil.which("unshare") @@ -756,8 +786,11 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual(0, out.returncode, out.stderr) self.assertNotIn("skipped", out.stderr, out.stderr) return + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so nothing can be spawned") result, requests, out = self.run_parent("laterecord", "sleep") self.assertEqual("1", result.get("reused"), out.stdout + out.stderr) + self.assertEqual("0", result.get("spawned"), out.stdout) self.assertEqual("1", result.get("reaped"), out.stdout) self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("own"), out.stdout)