diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index c8e2204395..bd1f5fafa8 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -1712,11 +1712,43 @@ static ddh_wait4_f ddh_real_wait4(void) { // A wait interrupted by a signal: as the real call, which a handler installed with SA_RESTART restarts. // The app's and the program's SIGCHLD are the usual ones. +// Waits under way whose real call can reap a forked child that handed its program off, from before +// that call until they have marked its entry (reaped) or let it be: another waiter's ECHILD for that +// child means one of them has it, and the entry is that waiter's to mark first. Without this, both +// would report the child: one with the program's status, the other with the forked child's own. +static int g_ddh_reaping; +static void ddh_reaping(int change) { __atomic_add_fetch(&g_ddh_reaping, change, __ATOMIC_ACQ_REL); } + +// Tests only ("IN OUT TID"): thread TID's wait, once its real call has reaped a child, writes a byte +// to OUT and waits for one on IN, as a waiter descheduled before it looks at what it reaped would. +static void ddh_wait_gate(void) { + const char *gate = getenv("DDH_TEST_WAIT_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; +} + // 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. -static int ddh_reap_shim(ddh_wait4_f real, pid_t child, int options) { +static int ddh_reap_shim(ddh_wait4_f real, struct ddh_entry *e, pid_t child, int options) { pid_t r = real(child, NULL, options & (WNOHANG | __WALL | __WNOTHREAD), NULL); - return r == child || (r < 0 && errno == ECHILD); + if (r == child) return 1; + if (r >= 0 || errno != ECHILD) return 0; + // Gone: reaped by another waiter, which marks e as soon as it has looked (waited for here: it is + // between its real call and the mark, and would report the child itself if e were released + // first), or by the kernel (SIGCHLD ignored), with no waiter under way to wait for. A second at + // most, for a waiter blocked in its real call meanwhile, which has reaped nothing of e's. + int saved = errno; + for (int i = 0; i < 1000 && !__atomic_load_n(&e->reaped, __ATOMIC_ACQUIRE) && __atomic_load_n(&g_ddh_reaping, __ATOMIC_ACQUIRE); i++) { + struct timespec pause = {0, 1000 * 1000}; + nanosleep(&pause, NULL); + } + errno = saved; + return 1; } // The program of an exited entry a wait for pid takes: its pid and status, the entry released (or @@ -1729,7 +1761,7 @@ 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, child, WNOHANG | flags)) { + if (!e->reaped && !ddh_reap_shim(real, e, child, WNOHANG | flags)) { ddh_untake(e); continue; } @@ -1772,9 +1804,9 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { errno = ENOSYS; return -1; } - // 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) || + // As waitid(): the kernel's alone for options it refuses (WNOWAIT among them), for __WCLONE + // alone, which selects no forked child, and for INT_MIN, a group it refuses (ESRCH) + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || pid == INT_MIN || (options & ~(WNOHANG | WUNTRACED | WCONTINUED | __WALL | __WNOTHREAD | __WCLONE)) || ((options & __WCLONE) && !(options & __WALL))) return real(pid, status, options, ru); @@ -1787,11 +1819,16 @@ 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) e->reaped = 1; + if (!e->reaped) { + ddh_reaping(1); + if (real(pid, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL) == pid) + __atomic_store_n(&e->reaped, 1, __ATOMIC_RELEASE); + ddh_reaping(-1); + } 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, pid, options)) { + if (!e->reaped && !ddh_reap_shim(real, e, pid, options)) { ddh_untake(e); return (options & WNOHANG) ? 0 : -1; } @@ -1814,18 +1851,27 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { } int live = pid <= 0 && ddh_any_live(pid); int wstatus = 0; + ddh_reaping(1); pid_t r = real(pid, &wstatus, live ? options | WNOHANG : options, ru); if (r > 0) { - struct ddh_entry *h = ddh_find(r); + ddh_wait_gate(); + // A stop or a continue reaps nothing: reported as it is, the entry and the claim left alone + int ended = WIFEXITED(wstatus) || WIFSIGNALED(wstatus); + struct ddh_entry *h = ended ? ddh_find(r) : NULL; if (h && !h->reaped) { - h->reaped = 1; // the forked child that handed its program off + __atomic_store_n(&h->reaped, 1, __ATOMIC_RELEASE); // the forked child that handed its program off + ddh_reaping(-1); continue; } // A forked child that died while handing its program off (a signal): its entry is done. - if (!h && (h = ddh_claiming(r))) ddh_release(h, NULL); + if (ended && !h && (h = ddh_claiming(r))) ddh_release(h, NULL); + ddh_reaping(-1); if (status) *status = wstatus; return r; } + int err = errno; + ddh_reaping(-1); + errno = err; // No child left: a handoff may have claimed its entry since the look above, and another // waiter reaped its forked child. The program still runs, so this wait goes on. if (!live && r < 0 && errno == ECHILD) { @@ -1844,18 +1890,21 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { } } +// The wait's own selector, the one before it given back after: a wait from a signal's handler +// leaves the one it interrupted as it was. static pid_t ddh_wait_as_thread(pid_t pid, int *status, int options, struct rusage *ru) { + pid_t outer = t_ddh_only_thread; t_ddh_only_thread = (options & __WNOTHREAD) ? (pid_t)syscall(SYS_gettid) : 0; pid_t r = ddh_wait(pid, status, options, ru); int saved = errno; - t_ddh_only_thread = 0; + t_ddh_only_thread = outer; errno = saved; return r; } 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 wait(int *status) { return ddh_wait_as_thread(-1, status, 0, NULL); } 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) { @@ -1923,7 +1972,10 @@ static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { 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) { - if (w4 && w4(child, NULL, WNOHANG | carried, NULL) == child) h->reaped = 1; // the forked child that handed its program off + ddh_reaping(1); + 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_reaping(-1); continue; } if (options & WNOWAIT) { @@ -1955,10 +2007,11 @@ static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { } int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { + pid_t outer = t_ddh_only_thread; t_ddh_only_thread = (options & __WNOTHREAD) ? (pid_t)syscall(SYS_gettid) : 0; int r = ddh_waitid(idtype, id, info, options); int saved = errno; - t_ddh_only_thread = 0; + t_ddh_only_thread = outer; errno = saved; return r; } diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index c85fc5ca50..3c96108c3a 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -173,6 +173,38 @@ static void *gone_forker(void *unused) { return NULL; // the thread ends: its child goes to the main thread } +// nothreadnested: a signal's handler waits, with no __WNOTHREAD, while it interrupts the main +// thread's __WNOTHREAD wait; that wait still takes only the main thread's children afterwards +static void nested_wait(int sig) { + (void)sig; + int status = 0; + int saved = errno; + waitpid(4194303, &status, WNOHANG); // no such child: takes nothing + errno = saved; +} + +// twowaits: one thread's wait has reaped the forked child (held there by the hook's test gate) when +// another thread's wait takes the program's exit; the child is reported once +static int two_in[2], two_out[2]; + +static void *first_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", two_in[0], two_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + int status = 0; + pid_t r = waitpid(-1, &status, 0); + printf("first\t%d\n", (int)r); + return NULL; +} + +static void *releaser(void *unused) { + (void)unused; + usleep(300000); // the other wait is under way by now + if (write(two_in[1], "1", 1) != 1) _exit(122); + return NULL; +} + static void *bystander(void *unused) { (void)unused; int status = 0; @@ -245,6 +277,33 @@ int main(int argc, char **argv) { if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); return 0; } + if (strcmp(argv[1], "nothreadnested") == 0) { + // the main thread's own program runs on; the other thread's has exited by the time it waits + pid_t own = fork(); + if (own == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + nothread_arg = argv[2]; + pthread_t forker; + pthread_create(&forker, NULL, nothread_forker, NULL); + nothread_await(1); + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = nested_wait; // no SA_RESTART: the wait ends with EINTR after one more look + sigaction(SIGALRM, &sa, NULL); + alarm(1); + int status = 0; + errno = 0; + pid_t r = waitpid(-1, &status, __WNOTHREAD); + printf("outer\t%d\n", (int)r); + printf("eintr\t%d\n", r == -1 && errno == EINTR); + kill(own, SIGKILL); + printf("ownend\t%d\n", waitpid(own, &status, 0) == own && WIFSIGNALED(status)); + nothread_go(2); + pthread_join(forker, NULL); + return 0; + } if (strcmp(argv[1], "nothread") == 0 || strcmp(argv[1], "nothreadwrap") == 0) { nothread_arg = argv[2]; nothread_wrap = argv[1][8] != 0; @@ -328,6 +387,33 @@ int main(int argc, char **argv) { printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); return 0; } + if (strcmp(argv[1], "twowaits") == 0) { + if (pipe(two_in) != 0 || pipe(two_out) != 0) return 1; + pthread_t first, release; + pthread_create(&first, NULL, first_waiter, NULL); + char c; + if (read(two_out[0], &c, 1) != 1) return 1; // the first wait has reaped the forked child + kill(pid, SIGTERM); // the program's: it ends, and its exit is ready + usleep(1000000); + pthread_create(&release, NULL, releaser, NULL); + pid_t r = -1; + for (int i = 0; i < 300 && (r = waitpid(-1, &status, WNOHANG)) == 0; i++) usleep(10000); + printf("second\t%d\n", (int)r); + printf("signal\t%d\n", r == pid && WIFSIGNALED(status) ? WTERMSIG(status) : -1); + pthread_join(release, NULL); + pthread_join(first, NULL); + printf("child\t%d\n", (int)pid); + return 0; + } + if (strcmp(argv[1], "stopclaim") == 0) { + // stopped while its handoff is with the app (the fake spawner holds its reply), then continued: by + // tgkill(), as a group's stop reaches it, where kill() would hold the signal for the program + usleep(300000); + syscall(SYS_tgkill, pid, pid, SIGSTOP); + printf("stopped\t%d\n", waitpid(pid, &status, WUNTRACED) == pid && WIFSTOPPED(status)); + usleep(1500000); // the reply has come meanwhile + syscall(SYS_tgkill, pid, pid, SIGCONT); + } 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 @@ -335,6 +421,8 @@ int main(int argc, char **argv) { 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); + errno = 0; + printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH); } int group = strcmp(argv[1], "group") == 0; if (group) { @@ -411,7 +499,9 @@ int main(void) { printf("moved\t%d\n", (int)getppid()); dup2(file, 901); // the spare too: no pidfd left, /proc answers printf("again\t%d\n", (int)getppid()); - syscall(SYS_close_range, 3, ~0U, 0); + long closed = syscall(SYS_close_range, 3, ~0U, 0); + printf("closerange\t%ld\n", closed); + printf("fileclosed\t%d\n", fcntl(file, F_GETFD) == -1); printf("closed\t%d\n", (int)getppid()); return 0; } @@ -483,8 +573,9 @@ int main(int argc, char **argv) { class FakeSpawner(threading.Thread): """Stands in for the app's spawn socket: runs the program and reports its exit into the table.""" - def __init__(self, name, prefix, root, reports=True): + def __init__(self, name, prefix, root, reports=True, delay=0): super().__init__(daemon=True) + self.delay = delay # seconds before the reply: the forked child waits with its entry claimed self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.bind("\0" + name) self.sock.listen(4) @@ -519,6 +610,8 @@ class FakeSpawner(threading.Thread): self.requests.append(request) table = fds[request["table"]] program = str(self.root) + request["file"] + if self.delay: + threading.Event().wait(self.delay) # As a worker does: a process whose pid goes back first, which runs the program only # once the hook takes it on with "go" gate_r, gate_w = os.pipe() @@ -607,9 +700,10 @@ class NativeHookHandoffTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False): + def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False, + delay=0): name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook) - spawner = FakeSpawner(name, self.prefix or [], self.root, reports) + spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay) spawner.start() self.addCleanup(spawner.sock.close) hook_env = {"DDNATV_ROOT": str(self.root), "DD_SPAWN": name, "DD_HANDOFF": handoff} @@ -660,8 +754,10 @@ class NativeHookHandoffTest(unittest.TestCase): os.setsid() fcntl.ioctl(fd, termios.TIOCSCTTY, 0) 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, - pass_fds=passed, text=True, timeout=120, **given) + start_new_session=not terminal, pass_fds=passed, text=True, timeout=120, **given) result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line) return result, spawner.requests, out @@ -835,12 +931,37 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), 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) + child = result.get("child") + self.assertEqual(child, result.get("second"), out.stdout) + self.assertEqual(str(signal.SIGTERM.value), result.get("signal"), out.stdout) + self.assertEqual("-1", result.get("first"), out.stdout) + + def test_a_stop_while_the_handoff_is_claimed_keeps_the_claim(self): + result, requests, out = self.run_parent("stopclaim", "6", delay=1.0) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("stopped"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("6", result.get("exit"), out.stdout) + + def test_a_wnothread_wait_a_handler_interrupts_keeps_to_its_thread(self): + result, requests, out = self.run_parent("nothreadnested", "7") + self.assertEqual(2, len(requests), out.stderr) + self.assertEqual("1", result.get("eintr"), out.stdout) + self.assertEqual("1", result.get("ownend"), out.stdout) + # the other thread's child is still its own + 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("intmin"), out.stdout) self.assertEqual("1", result.get("same"), out.stdout) self.assertEqual("5", result.get("exit"), out.stdout) @@ -1014,6 +1135,9 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) self.assertEqual("1", result.get("nonew"), out.stdout) self.assertEqual("1", result.get("taken"), out.stdout) + # an ordinary fd in the range closed: the parent is still known after a real close_range() + self.assertEqual("0", result.get("closerange"), out.stdout) + self.assertEqual("1", result.get("fileclosed"), out.stdout) for step in ("moved", "again", "closed"): self.assertEqual(str(parent), result.get(step), out.stdout)