diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index f8e5cdb8d5..247ebd36a5 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -664,6 +664,7 @@ pid_t fork(void) { pid_t forker = (pid_t)syscall(SYS_gettid); pid_t pid = orig_fork(); if (pid == 0) { + kept_close_forked(); ddh_drop_worker_binder(); ddh_forked(forker); } else if (pid > 0) { diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 43bf79b8c0..1939094a67 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -38,7 +38,7 @@ struct ddh_entry { int32_t app[2] __attribute__((aligned(8))); int64_t child_start; // the forked child's start time: tells it from a later process given its pid int32_t guessed; // the status is the timeout's guess: set only while the entry is held (TAKEN) - int32_t pad2; + int32_t gen; // moved on by every claim of the slot, never 0, kept through a release (ddh_reaped()) // When its worker was first seen gone, with the child that was for: child << 32 | seconds. Set by // compare-and-swap only, so a waiter that looked before the slot changed hands cannot overwrite it. uint64_t gone; @@ -170,23 +170,6 @@ static int ddh_record_pending(uint64_t r) { return 0; } -// Whether child has a handoff under way, whose program is running or whose exit is not yet reported, -// other than one of a child that started at start (a time read for it; -1: any) -static int ddh_pid_pending_other(pid_t child, long start) { - struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); - if (!t) return 0; - pid_t me = getpid(); - 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_CLAIMED && st != DDH_HANDED && st != DDH_EXITED && st != DDH_TAKEN) || e->parent != me || e->child != child) - continue; - if (!(start > 0 && e->child_start > 0 && ((uint64_t)e->child_start & DDH_REC_START) == ((uint64_t)start & DDH_REC_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) { @@ -200,12 +183,11 @@ static void ddh_forked_by(pid_t child, pid_t thread) { uint64_t seen = __atomic_load_n(slot, __ATOMIC_ACQUIRE); for (;;) { // A fork child that could not read its own start time (out of fds, say) has no time to tell its - // record by: it stays while the pid has any handoff under way. The time read here may be that - // child's, whose handoff it then is, so it tells nothing. (Two children of the pid with a - // handoff under way each, this one's too, is the limit of one record per pid.) - if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_SELF) && !(seen & DDH_REC_KNOWN) && - ddh_pid_pending_other(child, -1)) - return; + // record by, and the time read here may be that child's own: whether it is a later child than + // this one, maybe yet to hand its program off, cannot be told. Its record stays. (The cost: + // this child, if the fork child was an earlier one, has no record; a handoff it makes through + // a wrapper is then no thread's for a __WNOTHREAD wait.) + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_SELF) && !(seen & DDH_REC_KNOWN)) 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. @@ -260,6 +242,16 @@ static void ddh_forked(pid_t thread) { ddh_forks(1); } +// Tests only ("FD"): once the table's fd is kept, before the wait for earlier closes, a byte to FD. +static void ddh_table_kept_gate(void) { + const char *gate = getenv("DDH_TEST_TABLE_KEPT"); + if (!gate) return; + int saved = errno; + char c = 1; + syscall(SYS_write, atoi(gate), &c, 1); + errno = saved; +} + static int ddh_prepare_table(void); static int ddh_is_table(int fd, const struct ddh_table *t); @@ -315,11 +307,12 @@ static int ddh_prepare_table(void) { // Another thread's close() or close_range() that looked at the kept fds before this one was among // them may have closed it (and an open() taken the number): once those are over, it is still this // table, or it is given up and made again. - int settled = kept_settle(); - if (!settled || !ddh_is_table(fd, p)) { - int ours = ddh_is_table(fd, p); + // Given up, the number is not closed here: a close still under way may close it any time, and + // another thread then reuse it before a close here would come. Left to that close, or open and + // unkept, close-on-exec, until the program closes it or execs. + ddh_table_kept_gate(); + if (!kept_settle() || !ddh_is_table(fd, p)) { ddh_unkeep(fd); - if (ours) syscall(SYS_close, fd); munmap(p, sizeof(struct ddh_table)); return 0; } @@ -1315,6 +1308,8 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] } if (slot < 0) return; struct ddh_entry *e = &table->e[slot]; + int32_t gen = __atomic_load_n(&e->gen, __ATOMIC_RELAXED) + 1; + __atomic_store_n(&e->gen, gen ? gen : 1, __ATOMIC_RELEASE); pid_t me = getpid(), parent = (pid_t)syscall(SYS_getppid); // Before the request: the app checks them before it reports an exit into this entry, which a // later handoff may have taken over by then. @@ -1529,6 +1524,24 @@ static struct ddh_entry *ddh_find(pid_t child) { return NULL; } +// Whether e's forked child is reaped. A wait marks it with the generation e had when the wait found it +// (ddh_mark_reaped()), so a mark that comes after the slot went to a later handoff, the wait having +// been held up between its reap and the mark, marks nothing: the later child still counts as not +// reaped, and a reap of it later finds it or ECHILD, which is the same. +static int ddh_reaped(const struct ddh_entry *e) { + int32_t mark = __atomic_load_n(&e->reaped, __ATOMIC_ACQUIRE); + return mark != 0 && mark == __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE); +} + +static void ddh_mark_reaped(struct ddh_entry *e, int32_t gen) { __atomic_store_n(&e->reaped, gen, __ATOMIC_RELEASE); } + +// The generation of e, the entry of child: 0 when the slot has gone to another child meanwhile. +static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) { + int32_t gen = __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE); + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0; +} + // Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it. static int ddh_take(struct ddh_entry *e) { int expected = DDH_EXITED; @@ -1776,6 +1789,19 @@ static void ddh_wait_gate(void) { // The forked child of an entry whose program has exited: 1 once reaped (or already gone), 0 when it is // still exiting and WNOHANG was asked for, or the wait was interrupted. Gone means another wait reaped // it, and that one never reports it (ddh_wait()). +// Tests only ("IN OUT TID"): as ddh_wait_gate(), once thread TID's wait has reaped a forked child +// that handed its program off and before it marks the entry. +static void ddh_reap_gate(void) { + const char *gate = getenv("DDH_TEST_REAP_GATE"); + int in, out, tid; + if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c = 1; + syscall(SYS_write, out, &c, 1); + while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + static int ddh_reap_shim(ddh_wait4_f real, struct ddh_entry *e, pid_t child, int options) { (void)e; pid_t r = real(child, NULL, options & (WNOHANG | __WALL | __WNOTHREAD), NULL); @@ -1792,11 +1818,11 @@ static pid_t ddh_reap_exited(ddh_wait4_f real, pid_t pid, int *status, int keep, struct ddh_entry *e = &t->e[i]; if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_EXITED || !ddh_take_for(e, pid)) continue; pid_t child = e->child; - if (!e->reaped && !ddh_reap_shim(real, e, child, WNOHANG | flags)) { + if (!ddh_reaped(e) && !ddh_reap_shim(real, e, child, WNOHANG | flags)) { ddh_untake(e); continue; } - e->reaped = 1; + ddh_mark_reaped(e, __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE)); if (keep) { if (status) *status = ddh_status(e); ddh_untake(e); @@ -1850,12 +1876,13 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { struct ddh_entry *e = pid > 0 ? ddh_find(pid) : NULL; if (e && !ddh_selects(e, pid)) e = NULL; if (pid > 0 && e) { - if (!e->reaped && real(pid, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL) == pid) - __atomic_store_n(&e->reaped, 1, __ATOMIC_RELEASE); + int32_t gen = ddh_gen_of(e, pid); + if (gen && !ddh_reaped(e) && real(pid, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL) == pid) + ddh_mark_reaped(e, gen); if (ddh_take_for(e, pid)) { // the forked child is between its last write and its exit: reap it first, or a later // wait() would report its pid a second time (not blocking for WNOHANG: then later) - if (!e->reaped && !ddh_reap_shim(real, e, pid, options)) { + if (!ddh_reaped(e) && !ddh_reap_shim(real, e, pid, options)) { ddh_untake(e); return (options & WNOHANG) ? 0 : -1; } @@ -1895,12 +1922,29 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { // A stop or a continue reaps nothing: reported as it is, the entry and the claim left alone int ended = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED; struct ddh_entry *h = ended ? ddh_find(child) : NULL; - if (h && !h->reaped) { + int32_t gen = h ? ddh_gen_of(h, child) : 0; + if (gen && !ddh_reaped(h)) { real(child, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL); - __atomic_store_n(&h->reaped, 1, __ATOMIC_RELEASE); // the forked child that handed its program off + ddh_reap_gate(); + ddh_mark_reaped(h, gen); // the forked child that handed its program off continue; } int wstatus = 0; + if (!ended) { + // Only the kind of event looked at: the child may have gone on since, handed its + // program off and exited, and a wait4() would take that exit, the forked child's. + siginfo_t got; + memset(&got, 0, sizeof(got)); + int kind = seen.si_code == CLD_CONTINUED ? WCONTINUED : WSTOPPED; + if (call_orig_syscall(SYS_waitid, P_PID, (unsigned long)child, (unsigned long)&got, + (unsigned long)(kind | WNOHANG | (options & (__WALL | __WNOTHREAD))), 0, 0) != 0 || + got.si_pid != child) + continue; // another wait took it + wstatus = got.si_code == CLD_CONTINUED ? 0xffff : ((got.si_status & 0xff) << 8) | 0x7f; + if (ru) memset(ru, 0, sizeof(*ru)); + if (status) *status = wstatus; + return child; + } r = real(child, &wstatus, options | WNOHANG, ru); if (r != child) continue; // another wait took it // A forked child that died while handing its program off (a signal): its entry is done. @@ -2007,9 +2051,10 @@ static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { pid_t child = seen.si_pid; int exited = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED; struct ddh_entry *h = exited ? ddh_find(child) : NULL; - if (h && !h->reaped) { + int32_t gen = h ? ddh_gen_of(h, child) : 0; + if (gen && !ddh_reaped(h)) { if (w4 && w4(child, NULL, WNOHANG | carried, NULL) == child) - __atomic_store_n(&h->reaped, 1, __ATOMIC_RELEASE); // the forked child that handed its program off + ddh_mark_reaped(h, gen); // the forked child that handed its program off continue; } if (options & WNOWAIT) { diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index d78c087236..6405c20b94 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -76,17 +76,32 @@ static int is_kept_fd(int fd) { // the one before (kept_settle()), and only then trusts the fd to be its own still. static unsigned g_close_epoch; static int g_closers[2]; +// This thread's own, a close a signal's handler interrupted among them +static __thread int t_closing[2]; static unsigned kept_close_begin(void) { for (;;) { unsigned epoch = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1; __atomic_add_fetch(&g_closers[epoch], 1, __ATOMIC_SEQ_CST); - if ((__atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1) == epoch) return epoch; + if ((__atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1) == epoch) { + t_closing[epoch]++; + return epoch; + } __atomic_sub_fetch(&g_closers[epoch], 1, __ATOMIC_SEQ_CST); } } -static void kept_close_end(unsigned epoch) { __atomic_sub_fetch(&g_closers[epoch], 1, __ATOMIC_SEQ_CST); } +static void kept_close_end(unsigned epoch) { + t_closing[epoch]--; + __atomic_sub_fetch(&g_closers[epoch], 1, __ATOMIC_SEQ_CST); +} + +// In a forked child: the closes other threads of the parent were making did not come along, and +// only the forking thread's own (one a handler interrupted to fork) end here. +static void kept_close_forked(void) { + __atomic_store_n(&g_closers[0], t_closing[0], __ATOMIC_SEQ_CST); + __atomic_store_n(&g_closers[1], t_closing[1], __ATOMIC_SEQ_CST); +} static int kept_drained(unsigned epoch) { for (int i = 0; i < 1000; i++) { diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 382c3bf49c..f62b3374a8 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -43,6 +43,7 @@ PARENT = r""" #define _GNU_SOURCE #include #include +#include #include #include #include @@ -121,8 +122,25 @@ static void *late_spawner(void *unused) { return NULL; } -// live: the late record is made while the later child is still handing its program off (the fake -// spawner holds its reply), so the start time it reads is that child's +// Whether the hook's table (at any number here) has child's entry claimed: its handoff is with the app +static int claimed(pid_t child) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[4]; // child, real, parent, state + if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && head[3] == 3) + return 1; + } + } + return 0; +} + +// live 1: the late record is made while the later child is still handing its program off (the fake +// spawner holds its reply), so the start time it reads is that child's. live 2: made once the later +// child has recorded itself, before it execs and starts its handoff. static int late_record(const char *arg, int live) { int gate[2]; if (pipe(gate) != 0 || pipe(late_done) != 0 || pipe(late_hold) != 0) return 1; @@ -139,17 +157,31 @@ static int late_record(const char *arg, int live) { if (!f) return 1; fprintf(f, "%d", (int)first - 1); if (fclose(f) != 0) return 1; + int hold[2]; + if (live == 2 && pipe(hold) != 0) return 1; pid_t pid = fork(); if (pid == 0) { + if (live == 2) { + char c; + close(hold[1]); + if (read(hold[0], &c, 1) != 1) _exit(126); // recorded itself already, in the fork + } execl("/bin/target", "target", arg, (char *)NULL); _exit(127); } printf("reused\t%d\n", pid == first); int err = -1; - if (live) { - usleep(300000); // its handoff is with the app + if (live == 1) { + int claim = 0; + for (int i = 0; i < 500 && !(claim = claimed(pid)); i++) usleep(10000); + printf("claimed\t%d\n", claim); if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; } + if (live == 2) { + if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; + close(hold[0]); + if (write(hold[1], "1", 1) != 1) return 1; + } // its forked child exits once the program runs: reaped here, the program's exit left alone char path[64]; snprintf(path, sizeof(path), "/proc/%d", (int)pid); @@ -203,22 +235,32 @@ static void *prep_closer(void *unused) { return NULL; } -static int prep_hold_ms = 0; // after the table's fd is there: past the hook's wait for the close +static int prep_hold_ms = 0; // after the table's fd is kept: past the hook's wait for the close +static int prep_kept[2]; // the hook's word that it has kept the table's fd (DDH_TEST_TABLE_KEPT) +static int prep_acked; static void *prep_release(void *unused) { (void)unused; - // once the first fork has made the table's fd, while it waits for the close to end - char target[64]; - for (int i = 0; i < 1000; i++) { - ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1); - if (n > 0 && (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) == 0)) break; - usleep(1000); - } + // once the first fork has made and kept the table's fd, while it waits for the close to end + struct pollfd p = {prep_kept[0], POLLIN, 0}; + char c; + prep_acked = poll(&p, 1, 10000) == 1 && read(prep_kept[0], &c, 1) == 1; usleep(prep_hold_ms * 1000); if (write(prep_in[1], "1", 1) != 1) _exit(122); return NULL; } +// Whether a table of the hook's is open here, at any number +static int table_open(void) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n > 0 && (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) == 0)) return 1; + } + return 0; +} + // twowaits: one thread's wait has found the forked child (held there by the hook's test gate, for // longer than any other wait would wait for it) when another thread's wait takes the program's exit; // the child is reported once @@ -242,6 +284,49 @@ static void *releaser(void *unused) { return NULL; } +// reapreuse: one thread's wait has reaped the first child's forked child and is held before it marks +// the entry (the hook's reap gate), while the first child is collected, its slot freed, and a second +// child takes the slot; that wait then reports the second child once, with its program's status +static int reuse_in[2], reuse_out[2]; + +static void *reuse_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", reuse_in[0], reuse_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_REAP_GATE", gate, 1); + int status = 0, reports = 0, last = 0, sig = -1; + pid_t r; + while ((r = waitpid(-1, &status, 0)) > 0) { + reports++; + last = r; + sig = WIFSIGNALED(status) ? WTERMSIG(status) : -1; + } + printf("reports\t%d\n", reports); + printf("last\t%d\n", last); + printf("lastsignal\t%d\n", sig); + return NULL; +} + +// stoppeek: one thread's wait for a child stopped while its handoff is with the app has seen the stop +// (held there by the hook's wait gate) when the child goes on, hands its program off and its forked +// child exits; that wait reports the program's exit, not the forked child's +static int peek_in[2], peek_out[2]; +static pid_t peek_child; + +static void *peek_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", peek_in[0], peek_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + int status = 0; + pid_t r = waitpid(peek_child, &status, WUNTRACED); + // the stop is gone by the time it takes the event: what it reports is the program's end + if (r == peek_child && WIFSTOPPED(status)) r = waitpid(peek_child, &status, 0); + printf("waited\t%d\n", r == peek_child); + printf("code\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return NULL; +} + static void *bystander(void *unused) { (void)unused; int status = 0; @@ -285,6 +370,7 @@ static void *late_bystander(void *unused) { } int main(int argc, char **argv) { + setvbuf(stdout, NULL, _IONBF, 0); // what it got to, also when it does not finish pid_t pid; if (strcmp(argv[1], "nothreadheir") == 0) { nothread_arg = argv[2]; @@ -299,6 +385,7 @@ int main(int argc, char **argv) { } if (strcmp(argv[1], "laterecord") == 0) return late_record(argv[2], 0); if (strcmp(argv[1], "laterecordlive") == 0) return late_record(argv[2], 1); + if (strcmp(argv[1], "laterecordearly") == 0) return late_record(argv[2], 2); if (strcmp(argv[1], "nothreadgone") == 0) { nothread_arg = argv[2]; pthread_t forker; @@ -361,7 +448,10 @@ int main(int argc, char **argv) { // makes the table then int late = argv[1][9] != 0; prep_hold_ms = late ? 1500 : 0; - if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + if (pipe(prep_in) != 0 || pipe(prep_out) != 0 || pipe(prep_kept) != 0) return 1; + char kept[16]; + snprintf(kept, sizeof(kept), "%d", prep_kept[1]); + setenv("DDH_TEST_TABLE_KEPT", kept, 1); pthread_t closer, release; pthread_create(&closer, NULL, prep_closer, NULL); char c; @@ -386,10 +476,80 @@ int main(int argc, char **argv) { } printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); } - char target[64]; - ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1); - if (n > 0) target[n] = 0; - printf("table\t%d\n", n > 0 && strncmp(target, "/memfd:ddnatv-handoff", 21) == 0); + printf("acked\t%d\n", prep_acked); + printf("table\t%d\n", table_open()); + return 0; + } + if (strcmp(argv[1], "forkclose") == 0) { + // another thread's close_range() is under way (held on the test gate) when this forks a child, + // which then makes a table of its own for a child of its own: it waits for no close of its parent's + if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + pthread_t closer; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; + pid_t child = fork(); + if (child == 0) { + pid_t grandchild = fork(); + if (grandchild == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + int status = 0; + if (waitpid(grandchild, &status, 0) != grandchild) _exit(124); + _exit(WIFEXITED(status) ? WEXITSTATUS(status) : 125); + } + int status = 0; + printf("child\t%d\n", waitpid(child, &status, 0) == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (write(prep_in[1], "1", 1) != 1) return 1; + pthread_join(closer, NULL); + return 0; + } + if (strcmp(argv[1], "reapreuse") == 0) { + if (pipe(reuse_in) != 0 || pipe(reuse_out) != 0) return 1; + pid_t first = fork(); + if (first == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + pthread_t waiter; + pthread_create(&waiter, NULL, reuse_waiter, NULL); + char c; + if (read(reuse_out[0], &c, 1) != 1) return 1; // it has reaped the first's forked child + kill(first, SIGTERM); + usleep(1000000); // the program's end is reported + int status = 0; + printf("first\t%d\n", waitpid(first, &status, 0) == first && WIFSIGNALED(status)); + pid_t second = fork(); + if (second == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + usleep(1500000); // handed off, its forked child exited + if (write(reuse_in[1], "1111", 4) != 4) return 1; // for this reap and any after it + usleep(500000); + kill(second, SIGTERM); + pthread_join(waiter, NULL); + printf("second\t%d\n", (int)second); + return 0; + } + if (strcmp(argv[1], "stoppeek") == 0) { + if (pipe(peek_in) != 0 || pipe(peek_out) != 0) return 1; + peek_child = fork(); + if (peek_child == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + usleep(300000); // its handoff is with the app (the fake spawner holds its reply) + syscall(SYS_tgkill, peek_child, peek_child, SIGSTOP); + pthread_t waiter; + pthread_create(&waiter, NULL, peek_waiter, NULL); + char c; + if (read(peek_out[0], &c, 1) != 1) return 1; // it has seen the stop + syscall(SYS_tgkill, peek_child, peek_child, SIGCONT); + usleep(2000000); // the reply has come, the program runs, the forked child has exited + if (write(peek_in[1], "11111111", 8) != 8) return 1; // for each look + pthread_join(waiter, NULL); return 0; } // waitidpid: the child holds before its exec until the parent's wait has begun @@ -661,6 +821,7 @@ class FakeSpawner(threading.Thread): self.root = root self.reports = reports # False: as an app that died with its worker, no exit report self.requests = [] + self.pids = [] # the programs it ran, ended with the test whatever becomes of them def run(self): while True: @@ -694,6 +855,8 @@ class FakeSpawner(threading.Thread): # once the hook takes it on with "go" gate_r, gate_w = os.pipe() pid = os.fork() + if pid: + self.pids.append(pid) if pid == 0: os.close(gate_w) if os.read(gate_r, 1) == b"1": @@ -778,6 +941,14 @@ class NativeHookHandoffTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() + @staticmethod + def end_programs(spawner): + for pid in spawner.pids: + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False, delay=0, extra_env=None): name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook) @@ -835,8 +1006,19 @@ class NativeHookHandoffTest(unittest.TestCase): given = {"input": ""} if stdin == subprocess.PIPE else {"stdin": stdin} # Without a terminal of its own, a session of its own: run from a terminal's foreground job, the # fixture would otherwise be that job too, which keeps its children local near the limit. - out = subprocess.run(cmd + [parent, *argv], env=env, stdout=subprocess.PIPE, stderr=stderr, preexec_fn=ctty, - start_new_session=not terminal, pass_fds=passed, text=True, timeout=120, **given) + self.addCleanup(self.end_programs, spawner) + proc = subprocess.Popen(cmd + [parent, *argv], env=env, stdout=subprocess.PIPE, stderr=stderr, preexec_fn=ctty, + start_new_session=not terminal, pass_fds=passed, text=True, + stdin=subprocess.PIPE if "input" in given else given.get("stdin")) + try: + stdout, err = proc.communicate(given.get("input"), timeout=120) + except subprocess.TimeoutExpired: + # the programs the spawner ran hold the fixture's output open too + self.end_programs(spawner) + proc.kill() + stdout, err = proc.communicate() + self.fail("the fixture did not finish:\n%s\n%s" % (stdout, err)) + out = subprocess.CompletedProcess(proc.args, proc.returncode, stdout, err) result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line) return result, spawner.requests, out @@ -1010,6 +1192,26 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), out.stdout) + def test_a_forked_child_waits_for_no_close_of_its_parents(self): + # no table in the parent (a close held across its tries), so the child makes one + result, requests, out = self.run_parent("forkclose", "3", extra_env={"DDH_TEST_LATE_TABLE": "1"}) + self.assertEqual(1, len(requests), out.stdout + out.stderr) + self.assertEqual("3", result.get("child"), out.stdout) + + def test_a_late_mark_of_a_reused_slot_leaves_the_new_child_once(self): + result, requests, out = self.run_parent("reapreuse", "sleep") + self.assertEqual(2, len(requests), out.stderr) + self.assertEqual("1", result.get("first"), out.stdout + out.stderr) + self.assertEqual("1", result.get("reports"), out.stdout) + self.assertEqual(result.get("second"), result.get("last"), out.stdout) + self.assertEqual(str(signal.SIGTERM.value), result.get("lastsignal"), out.stdout) + + def test_a_stop_seen_before_the_child_hands_off_reports_its_program(self): + result, requests, out = self.run_parent("stoppeek", "6", delay=1.0) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("waited"), out.stdout + out.stderr) + self.assertEqual("6", result.get("code"), out.stdout) + def test_two_waits_report_a_handed_off_child_once(self): result, requests, out = self.run_parent("twowaits", "sleep") self.assertEqual(1, len(requests), out.stderr) @@ -1086,9 +1288,14 @@ class NativeHookHandoffTest(unittest.TestCase): def test_a_late_record_reading_the_new_childs_start_keeps_its_owner(self): # made while the later child, which could not read its own start, still hands its program off - self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live=True) + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="live") - def late_record(self, env=None, live=False): + def test_a_late_record_before_the_new_child_execs_keeps_its_owner(self): + # made once the later child, which could not read its own start, has recorded itself and + # before it execs: no handoff of it yet to tell by + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="early") + + def late_record(self, env=None, live=None): if self.child_status != "3": self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so nothing can be spawned") # the pid has to be given again, which only a pid namespace of the test's own allows @@ -1105,9 +1312,11 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual(0, out.returncode, out.stderr) self.assertNotIn("skipped", out.stderr, out.stderr) return - result, requests, out = self.run_parent("laterecordlive" if live else "laterecord", "sleep", extra_env=env, - delay=1.0 if live else 0) + result, requests, out = self.run_parent("laterecord" + (live or ""), "sleep", extra_env=env, + delay=1.0 if live == "live" else 0) self.assertEqual("1", result.get("reused"), out.stdout + out.stderr) + if live == "live": + self.assertEqual("1", result.get("claimed"), out.stdout) self.assertEqual("0", result.get("spawned"), out.stdout) self.assertEqual("1", result.get("reaped"), out.stdout) self.assertEqual(1, len(requests), out.stderr) @@ -1228,6 +1437,7 @@ class NativeHookHandoffTest(unittest.TestCase): # 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"}) self.assertEqual("0", result.get("ranged"), out.stdout + out.stderr) + self.assertEqual("1", result.get("acked"), out.stdout) self.assertEqual("1", result.get("table"), out.stdout) self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("same"), out.stdout) @@ -1240,6 +1450,7 @@ class NativeHookHandoffTest(unittest.TestCase): # fork makes the table result, requests, out = self.run_parent("prepcloselate", "4", extra_env={"DDH_TEST_LATE_TABLE": "1"}) self.assertEqual("0", result.get("ranged"), out.stdout + out.stderr) + self.assertEqual("1", result.get("acked"), out.stdout) self.assertEqual("1", result.get("same"), out.stdout) self.assertEqual("4", result.get("exit"), out.stdout) self.assertEqual("4", result.get("again"), out.stdout)