diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 61c0693e73..f09ae81284 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -37,7 +37,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 thread; // the parent's thread that forked the child (__WNOTHREAD), 0 when unknown + int32_t pad2; // 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; @@ -101,16 +101,50 @@ static int ddh_is_binder(const char *target) { // One thread makes it; a fork() while another thread is making it goes without (its child runs here). static int g_ddh_preparing; -// In a forked child: the thread making the table did not come along, so the child may make its own. -static void ddh_forked(void) { __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELAXED); } -// The thread about to fork, as its child inherits it: the entry the child claims names it. -static __thread pid_t t_ddh_forker; -// Set by waitid() with __WNOTHREAD: only children this thread forked are selected. +// 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. A child not in here (a raw clone(), or one pushed out by many others) is any +// thread's. +#define DDH_FORKS 1024 +static struct ddh_fork { + pid_t child; + pid_t thread; +} g_ddh_forks[DDH_FORKS]; + +static void ddh_forked_by(pid_t child, pid_t thread) { + struct ddh_fork *home = &g_ddh_forks[(unsigned)child % DDH_FORKS]; + for (int i = 0; i < 8; i++) { + struct ddh_fork *f = &g_ddh_forks[((unsigned)child + i) % DDH_FORKS]; + pid_t seen = __atomic_load_n(&f->child, __ATOMIC_ACQUIRE); + if (seen == child || (seen == 0 && __atomic_compare_exchange_n(&f->child, &seen, child, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))) { + __atomic_store_n(&f->thread, thread, __ATOMIC_RELEASE); + return; + } + } + __atomic_store_n(&home->child, child, __ATOMIC_RELEASE); + __atomic_store_n(&home->thread, thread, __ATOMIC_RELEASE); +} + +static pid_t ddh_forking_thread(pid_t child) { + for (int i = 0; i < 8; i++) { + struct ddh_fork *f = &g_ddh_forks[((unsigned)child + i) % DDH_FORKS]; + if (__atomic_load_n(&f->child, __ATOMIC_ACQUIRE) == child) return __atomic_load_n(&f->thread, __ATOMIC_ACQUIRE); + } + return 0; +} + +// In a forked child: the thread making the table did not come along, so the child may make its own; +// the parent's children are not its own. +static void ddh_forked(void) { + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELAXED); + memset(g_ddh_forks, 0, sizeof(g_ddh_forks)); +} + static void ddh_prepare(void) { - t_ddh_forker = (pid_t)syscall(SYS_gettid); if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN")) return; if (__atomic_exchange_n(&g_ddh_preparing, 1, __ATOMIC_ACQ_REL)) return; if (g_ddh) { @@ -989,7 +1023,6 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] e->status = DDH_NO_STATUS; __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); e->child_start = ddh_start_time(me); - e->thread = t_ddh_forker; char cwd[PATH_MAX]; // The guest's name for it, else the kernel's (the worker's cd takes either). A directory with no // name (removed) cannot be sent: the exec stays here, in it. @@ -1200,7 +1233,10 @@ static void ddh_untake(struct ddh_entry *e) { __atomic_store_n(&e->state, DDH_EX // Whether a wait for pid (-1: any child, 0: one in our group, -G: one in group G) takes e's child. static int ddh_selects(const struct ddh_entry *e, pid_t pid) { - if (t_ddh_only_thread && e->thread && e->thread != t_ddh_only_thread) return 0; + if (t_ddh_only_thread) { + pid_t thread = ddh_forking_thread(e->child); + if (thread && thread != t_ddh_only_thread) return 0; + } if (pid > 0) return e->child == pid; if (pid == -1) return 1; return e->pad[1] == (pid == 0 ? getpgrp() : -pid); @@ -1217,6 +1253,7 @@ static void ddh_release(struct ddh_entry *e, int *status); // Without both start times (the new child already reaped too) nothing is dropped: an entry of the // new child's own must not be, and a stale one needs the pid space to wrap besides. static void ddh_child_created(pid_t pid) { + if (pid > 0) ddh_forked_by(pid, (pid_t)syscall(SYS_gettid)); struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); if (!t || pid <= 0) return; pid_t me = getpid(); @@ -1330,7 +1367,6 @@ static void ddh_release(struct ddh_entry *e, int *status) { e->pad[0] = 0; e->pad[1] = 0; e->guessed = 0; - e->thread = 0; __atomic_store_n(&e->gone, 0, __ATOMIC_RELAXED); __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index c98270cd90..137f4d6e49 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -62,6 +62,7 @@ static void open_gate(int sig) { // nothread: a second thread forks the child; __WNOTHREAD waits see only their own thread's children static char *nothread_arg; +static int nothread_wrap; static pthread_mutex_t nothread_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t nothread_cond = PTHREAD_COND_INITIALIZER; static int nothread_step; @@ -84,6 +85,7 @@ static void *nothread_forker(void *unused) { (void)unused; pid_t pid = fork(); if (pid == 0) { + if (nothread_wrap) execl("/bin/wrap", "wrap", "/bin/target", "target", nothread_arg, (char *)NULL); execl("/bin/target", "target", nothread_arg, (char *)NULL); _exit(127); } @@ -100,8 +102,9 @@ static void *nothread_forker(void *unused) { int main(int argc, char **argv) { pid_t pid; - if (strcmp(argv[1], "nothread") == 0) { + if (strcmp(argv[1], "nothread") == 0 || strcmp(argv[1], "nothreadwrap") == 0) { nothread_arg = argv[2]; + nothread_wrap = argv[1][8] != 0; pthread_t forker; pthread_create(&forker, NULL, nothread_forker, NULL); nothread_await(1); @@ -213,6 +216,17 @@ int main(int argc, char **argv) { } """ +# An unlisted program that execs the next one, as env and shell wrappers do +WRAP = r""" +#include + +int main(int argc, char **argv) { + if (argc < 3) return 2; + execv(argv[1], argv + 2); // wrap PATH ARGV0 ARGS... + return 127; +} +""" + class FakeSpawner(threading.Thread): """Stands in for the app's spawn socket: runs the program and reports its exit into the table.""" @@ -325,6 +339,8 @@ class NativeHookHandoffTest(unittest.TestCase): (cls.root / "bin").mkdir(parents=True) (tmp / "target.c").write_text(TARGET) subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/target"), str(tmp / "target.c")], check=True) + (tmp / "wrap.c").write_text(WRAP) + subprocess.run([cls.cc, "-O1", "-o", str(cls.root / "bin/wrap"), str(tmp / "wrap.c")], check=True) # What a child here gets from exec'ing an aarch64 program: 3 where the kernel runs them # (binfmt_misc with qemu-user), 127 on a plain x86 runner, which does not. A handed-off program is # started by the fake spawner through the runner itself either way. @@ -349,6 +365,9 @@ class NativeHookHandoffTest(unittest.TestCase): hook_env["LD_PRELOAD"] = str(self.hook) if pressure is not None: hook_env["DD_HANDOFF_PRESSURE"] = str(pressure) + if "-L" in (self.prefix or []): + # a dynamic program a child execs runs through binfmt_misc, whose qemu-user takes its sysroot from here + hook_env["QEMU_LD_PREFIX"] = self.prefix[self.prefix.index("-L") + 1] env = {k: v for k, v in os.environ.items() if k not in hook_env} prefix, parent = list(self.prefix or []), str(self.parent) if as_shell: @@ -539,6 +558,20 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), 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") + # the hook names its own path inside the guest's root for the programs it execs + rooted = self.root / str(self.hook).lstrip("/") + rooted.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(self.hook, rooted) + result, requests, out = self.run_parent("nothreadwrap", "7") + 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("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + def test_waitid_for_a_pid_begun_before_its_claim_reports_the_program(self): result, requests, out = self.run_parent("waitidpid", "7") self.assertEqual(1, len(requests), out.stderr)