diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index bd1f5fafa8..ac12c68774 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -91,6 +91,7 @@ static void ddh_prepare_failed(const char *step) { } static void ddh_keep(int fd); +static void ddh_unkeep(int fd); // An fd's target that is one of Android's binder devices (directly or through binderfs). static int ddh_is_binder(const char *target) { @@ -169,6 +170,22 @@ static int ddh_record_pending(uint64_t r) { return 0; } +// Whether child has a handoff 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, else 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_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) { @@ -181,6 +198,11 @@ static void ddh_forked_by(pid_t child, pid_t thread) { uint64_t *slot = &map[(uint32_t)child % DDH_FORKS]; 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 a handoff pending that is not this child's. + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_SELF) && !(seen & DDH_REC_KNOWN) && + ddh_pid_pending_other(child, start)) + 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. @@ -225,7 +247,9 @@ static void ddh_forked(pid_t thread) { 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); + // tests only: as a child that cannot read its start time + long start = getenv("DDH_TEST_FORK_START_UNKNOWN") ? -1 : ddh_start_time(me); + uint64_t mine = ddh_fork_record(me, thread, start, 1); __atomic_store_n(&old[(uint32_t)me % DDH_FORKS], mine, __ATOMIC_RELEASE); errno = saved; } @@ -233,6 +257,9 @@ static void ddh_forked(pid_t thread) { ddh_forks(1); } +static int ddh_prepare_table(void); +static int ddh_is_table(int fd, const struct ddh_table *t); + static void ddh_prepare(void) { // the parent records which thread forks each child (ddh_forked_by()); a child refuses a handoff // when it cannot (ddh_try()) @@ -243,24 +270,29 @@ static void ddh_prepare(void) { __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); return; } + // a second try for a table another thread's close took before it was kept + for (int attempt = 0; attempt < 2 && !ddh_prepare_table(); attempt++) {} + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); +} + +// 1 when the table is made (g_ddh), 0 when its fd went to another thread's close before that one +// could see it was kept; the other failures are logged and end the trying too (1). +static int ddh_prepare_table(void) { int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); if (fd < 0) { ddh_prepare_failed("memfd_create"); - __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); - return; + return 1; } if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { ddh_prepare_failed("ftruncate"); close(fd); - __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); - return; + return 1; } struct ddh_table *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { ddh_prepare_failed("mmap"); close(fd); - __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); - return; + return 1; } // Out of the way of the numbers programs redirect, and kept open when a child closes every // inherited fd before exec (Python's subprocess does): the child needs it for its handoff. @@ -277,12 +309,24 @@ static void ddh_prepare(void) { p->pad[1] = (int32_t)time(NULL); p->pad[2] = (int32_t)(intptr_t)p; } + // 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); + ddh_unkeep(fd); + if (ours) syscall(SYS_close, fd); + munmap(p, sizeof(struct ddh_table)); + return 0; + } g_ddh_fd = fd; g_ddh_owner = getpid(); __atomic_store_n(&g_ddh, p, __ATOMIC_RELEASE); - __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); + return 1; } + // Whether fd is still this table: a program may have put a file of its own at that number. static int ddh_is_table(int fd, const struct ddh_table *t) { int32_t head[4]; @@ -797,7 +841,8 @@ __attribute__((constructor)) static void ddh_init(void) { ddh_find_worker_binder(); ddh_setup_report(); ddh_find_parent_table(); - ddh_prepare(); + // tests only: as when the table could not be made here, and the first fork makes it + if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare(); } static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) { diff --git a/tools/nativeguest/hook/net.c b/tools/nativeguest/hook/net.c index e08f74a837..a4e4dd1e2b 100644 --- a/tools/nativeguest/hook/net.c +++ b/tools/nativeguest/hook/net.c @@ -240,12 +240,20 @@ static void clear_dns_redirect(int fd) { int close(int fd) { static int (*orig_close)(int) = NULL; if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close"); + unsigned epoch = kept_close_begin(); // The ARM translator's memory file (privileged.c): left open, as if it were closed - if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0; + if (g_kept_fd_count > 0 && is_kept_fd(fd)) { + kept_close_end(epoch); + return 0; + } clear_dns_redirect(fd); set_chosen_port_fd(fd, 0); forget_proc_root_fd(fd); - return orig_close ? orig_close(fd) : -1; + int r = orig_close ? orig_close(fd) : -1; + int saved = errno; + kept_close_end(epoch); + errno = saved; + return r; } int dup2(int oldfd, int newfd) { diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 32088d50b2..e8e63ccc86 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -70,6 +70,36 @@ static int is_kept_fd(int fd) { return 0; } +// Closes under way (close(), close_range()), counted by the epoch they began in: one that looked at +// the list before a fd was added to it may still close that fd. A thread that makes and keeps a fd +// while others run (hook/handoff.c's table) moves the epoch on afterwards, waits for the closes of +// 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]; + +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; + __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); } + +// 1 once every close that began before now has ended; 0 after a second without (one interrupted by +// a signal whose handler is the caller, say): then nothing it made since can be trusted. +static int kept_settle(void) { + unsigned old = __atomic_fetch_add(&g_close_epoch, 1, __ATOMIC_SEQ_CST) & 1; + for (int i = 0; i < 1000; i++) { + if (__atomic_load_n(&g_closers[old], __ATOMIC_SEQ_CST) == 0) return 1; + struct timespec pause = {0, 1000 * 1000}; + nanosleep(&pause, NULL); + } + return 0; +} + // Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending); // the first nonzero answer of fn is returned, else 0. static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept, @@ -493,8 +523,9 @@ int setns(int fd, int nstype) { static int close_range_all(unsigned int first, unsigned int last, int flags); -// Tests only ("IN OUT TID"): after each part it closes, thread TID's close_range() writes a byte to -// OUT and waits for one on IN, as a thread descheduled between the parts would. +// Tests only ("IN OUT TID"): before each part it closes, once it has looked at the kept fds, thread +// TID's close_range() writes a byte to OUT and waits for one on IN, as a thread descheduled there +// would. static void close_range_test_gate(void) { const char *gate = getenv("DDNATV_TEST_CLOSE_RANGE_GATE"); int in, out, tid; @@ -507,18 +538,16 @@ static void close_range_test_gate(void) { } static int close_range_part(unsigned int first, unsigned int last, void *flags) { - int r = close_range_all(first, last, *(int *)flags); close_range_test_gate(); - return r; + return close_range_all(first, last, *(int *)flags); } -int close_range(unsigned int first, unsigned int last, int flags) { - if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last); +static int close_range_kept(unsigned int first, unsigned int last, int flags) { // Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open int snapshot[DDNATV_MAX_KEPT_FDS]; const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot; int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot); - if (kept_count == 0) return close_range_all(first, last, flags); + if (kept_count == 0) return close_range_part(first, last, &flags); // The table is unshared once, even when every fd in the range is kept: the system call itself on // the one number no fd has (close_range_all() would emulate a missing call by closing fds) if (flags & CLOSE_RANGE_UNSHARE) { @@ -534,6 +563,16 @@ int close_range(unsigned int first, unsigned int last, int flags) { return for_each_range_without(first, last, kept, kept_count, close_range_part, &flags); } +int close_range(unsigned int first, unsigned int last, int flags) { + if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last); + unsigned epoch = kept_close_begin(); + int r = close_range_kept(first, last, flags); + int saved = errno; + kept_close_end(epoch); + errno = saved; + return r; +} + // glibc's closefrom() makes the close_range system call itself, past the function above void closefrom(int lowfd) { close_range(lowfd < 0 ? 0U : (unsigned int)lowfd, ~0U, 0); diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 3c96108c3a..6f8592507f 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -183,6 +183,27 @@ static void nested_wait(int sig) { errno = saved; } +// prepclose: another thread's close_range(799, 801) has looked at the kept fds, none of them the +// table's yet, and waits on the hook's test gate while the first fork makes the table at 800 +static int prep_in[2], prep_out[2]; +static long prep_closed = -2; + +static void *prep_closer(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", prep_in[0], prep_out[1], (int)syscall(SYS_gettid)); + setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); + prep_closed = syscall(SYS_close_range, 799, 801, 0); + return NULL; +} + +static void *prep_release(void *unused) { + (void)unused; + usleep(300000); // the fork is making the table by now + if (write(prep_in[1], "1", 1) != 1) _exit(122); + return NULL; +} + // 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]; @@ -318,6 +339,30 @@ int main(int argc, char **argv) { pthread_join(forker, NULL); return 0; } + if (strcmp(argv[1], "prepclose") == 0) { + if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + pthread_t closer, release; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; // it has looked + pthread_create(&release, NULL, prep_release, NULL); + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + pthread_join(release, NULL); + pthread_join(closer, NULL); + printf("ranged\t%ld\n", prep_closed); + 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); + int status = 0; + printf("same\t%d\n", waitpid(pid, &status, 0) == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return 0; + } // waitidpid: the child holds before its exec until the parent's wait has begun if (strcmp(argv[1], "waitidpid") == 0 && pipe(gate) != 0) return 1; if (strcmp(argv[1], "spawn") == 0) { @@ -521,6 +566,7 @@ DUPRACE = r""" #include static int in[2], out[2]; +static long closed = -2; static int is(int fd, const char *what) { char path[64], target[64]; @@ -536,13 +582,14 @@ static void *closer(void *unused) { char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", in[0], out[1], (int)syscall(SYS_gettid)); setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); - syscall(SYS_close_range, 899, 2000, 0); + closed = syscall(SYS_close_range, 899, 2000, 0); return NULL; } int main(void) { printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]") && is(1000, "/memfd:")); int file = open("/dev/null", O_WRONLY); + if (dup2(file, 950) != 950) return 1; // an ordinary fd in the range, which it closes if (pipe(in) != 0 || pipe(out) != 0) return 1; pthread_t thread; pthread_create(&thread, NULL, closer, NULL); @@ -551,6 +598,8 @@ int main(void) { dup2(file, 900); if (write(in[1], "111", 3) != 3) return 1; // one for each part pthread_join(thread, NULL); + printf("ranged\t%ld\n", closed); + printf("ordinary\t%d\n", fcntl(950, F_GETFD) == -1); printf("spare\t%d\n", is(901, "anon_inode:[pidfd]")); printf("table\t%d\n", is(1000, "/memfd:")); printf("parent\t%d\n", (int)getppid()); @@ -701,7 +750,7 @@ class NativeHookHandoffTest(unittest.TestCase): cls.tmp.cleanup() def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False, - delay=0): + delay=0, extra_env=None): 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, delay) spawner.start() @@ -711,6 +760,7 @@ class NativeHookHandoffTest(unittest.TestCase): hook_env["LD_PRELOAD"] = str(self.hook) if pressure is not None: hook_env["DD_HANDOFF_PRESSURE"] = str(pressure) + hook_env.update(extra_env or {}) 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] @@ -999,6 +1049,13 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("7", result.get("exit"), out.stdout) def test_a_late_record_of_a_spawned_child_keeps_a_handoffs_owner(self): + self.late_record() + + def test_a_late_record_keeps_an_owner_whose_start_was_not_read(self): + # the fork's child could not read its own start time: its record has none to be told by + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}) + + def late_record(self, env=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 @@ -1015,7 +1072,7 @@ 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("laterecord", "sleep") + result, requests, out = self.run_parent("laterecord", "sleep", extra_env=env) 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) @@ -1126,10 +1183,22 @@ class NativeHookHandoffTest(unittest.TestCase): parent, result, out = self.run_worker_program("duprace", DUPRACE, table_fd=1000) self.assertEqual(0, out.returncode, out.stderr) self.assertEqual("1", result.get("kept"), out.stdout + out.stderr) + # the close_range() worked: an ordinary fd in its range is closed, the kept ones above 900 are not + self.assertEqual("0", result.get("ranged"), out.stdout) + self.assertEqual("1", result.get("ordinary"), out.stdout) self.assertEqual("1", result.get("spare"), out.stdout) self.assertEqual("1", result.get("table"), out.stdout) self.assertEqual(str(parent), result.get("parent"), out.stdout) + def test_a_table_made_while_a_close_range_runs_stays_open(self): + # 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("table"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("4", result.get("exit"), out.stdout) + def test_a_dup2_onto_the_parents_pidfd_makes_no_descriptor_and_keeps_the_parent(self): parent, result, out = self.run_worker_program("dupover", DUPOVER) self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr)