diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 313c636e93..08e18bc8e5 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -171,16 +171,18 @@ static void ddh_forked_by(pid_t child, pid_t thread) { // 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. - if (seen && ddh_record_child(seen) == child && (seen & 0x80000) && (mine & 0x80000) && - (seen & 0x7ffff) != (mine & 0x7ffff)) { + // 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. - if (!(now > 0 && ((uint64_t)now & 0x7ffff) == (mine & 0x7ffff)) && - ddh_record_pending(seen) && !ddh_record_pending(mine)) return; + 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 (__atomic_compare_exchange_n(slot, &seen, mine, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) return; } @@ -1489,8 +1491,20 @@ static void ddh_drop_stale(pid_t pid) { } } +// Tests only ("FD TID"): holds the record of thread TID's forks until a byte can be read from FD, as a +// parent thread descheduled between its fork and the record would be. +static void ddh_record_gate(void) { + const char *gate = getenv("DDH_TEST_RECORD_GATE"), *tid = gate ? strchr(gate, ' ') : NULL; + if (!tid || atoi(tid + 1) != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c; + while (syscall(SYS_read, atoi(gate), &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + static void ddh_child_created(pid_t pid) { 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 diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 3b1b056fcd..0c4e93e9a1 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -7,6 +7,7 @@ import signal import socket import struct import subprocess +import sys import tempfile import termios import threading @@ -46,6 +47,7 @@ PARENT = r""" #include #include #include +#include #include #include #include @@ -100,6 +102,63 @@ 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; + +static void *late_forker(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); + } + char c; + if (read(late_hold[0], &c, 1) != 1) _exit(124); // alive while the main thread's wait looks + return NULL; +} + +static int late_record(const char *arg) { + int gate[2]; + if (pipe(gate) != 0 || pipe(late_pid) != 0 || pipe(late_hold) != 0) return 1; + late_gate = gate[0]; + pthread_t forker; + pthread_create(&forker, NULL, late_forker, NULL); + pid_t first = 0; + int status = 0; + if (read(late_pid[0], &first, sizeof(first)) != sizeof(first) || waitpid(first, &status, 0) != first) return 1; + // the next fork gets the pid again + FILE *f = fopen("/proc/sys/kernel/ns_last_pid", "w"); + if (!f) return 1; + fprintf(f, "%d", (int)first - 1); + if (fclose(f) != 0) return 1; + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + printf("reused\t%d\n", pid == first); + // 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); + for (int i = 0; i < 1000 && access(path, F_OK) == 0; i++) { + waitpid(-1, &status, WNOHANG); + 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 + 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); + return 0; +} + static void *gone_forker(void *unused) { (void)unused; pid_t pid = fork(); @@ -166,6 +225,7 @@ int main(int argc, char **argv) { nothread_go(1); pthread_exit(NULL); // the main thread ends too; the others finish the process } + if (strcmp(argv[1], "laterecord") == 0) return late_record(argv[2]); if (strcmp(argv[1], "nothreadgone") == 0) { nothread_arg = argv[2]; pthread_t forker; @@ -684,6 +744,25 @@ 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): + # 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") + if not unshare or subprocess.run([unshare, "-Urpf", "--mount-proc", "true"], capture_output=True).returncode: + self.skipTest("no user and pid namespace for this test") + out = subprocess.run([unshare, "-Urpf", "--mount-proc", sys.executable, "-m", "unittest", self.id()], + env={**os.environ, "DDH_TEST_PIDNS": "1"}, cwd=Path(__file__).resolve().parents[2], + capture_output=True, text=True, timeout=300) + self.assertEqual(0, out.returncode, out.stderr) + self.assertNotIn("skipped", out.stderr, out.stderr) + return + result, requests, out = self.run_parent("laterecord", "sleep") + self.assertEqual("1", result.get("reused"), out.stdout + out.stderr) + self.assertEqual("1", result.get("reaped"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("1", result.get("ended"), out.stdout) + def test_wnothread_takes_a_program_started_through_a_wrapper(self): if self.child_status != "3": self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so the wrapper cannot run")