From d7f0ce82d8b84337032669a3b81b0bb987a5d81a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:43:59 -0500 Subject: [PATCH] fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup --- .../launcher/runtime/GuestWorkers.kt | 8 +- .../overlay/usr/local/bin/droiddeck-spawn | 8 +- tools/nativeguest/hook/handoff.c | 93 ++++--------------- tools/tests/test_native_hook_handoff.py | 62 ++++++------- 4 files changed, 59 insertions(+), 112 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index b771951b48..acece237d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -335,7 +335,8 @@ object GuestWorkers { confirmed: () -> Boolean = { true }, owner: Int = session): Int { val app = context.applicationContext if (guest && owner <= stopped) { - Log.w(TAG, "session $owner is stopping: not starting ${argv.firstOrNull()}") + Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") + + ": not starting ${argv.firstOrNull()}") return -1 } val slot = takeWarm() ?: bind(app)?.takeIf { fresh -> @@ -738,8 +739,9 @@ object GuestWorkers { var confirmedToHook = false // The session whose guest asks, not the latest: a new session can start (serve()) while an // older one's guests are still sending, and that older one's teardown must find its programs. - // A request that names none (a guest of an older build) is the latest's. - val owner = request.optInt("session", 0).takeIf { it > 0 } ?: session + // A request that names none is refused (start() runs nothing for session 0): the hook and + // droiddeck-spawn always name it, and which session's it is cannot be told otherwise. + val owner = request.optInt("session", 0).coerceAtLeast(0) val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, onExit = { code -> status = code if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn index 0f8bcc32a7..c0ebafccac 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn @@ -12,6 +12,7 @@ it waits for it and exits with its status. Where the app offers no spawner, the import array import json import os +import re import socket import struct import sys @@ -76,8 +77,11 @@ def main(): except OSError: return fallback(args, wait, pid_file) request = {"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait} - if os.environ.get("DD_SPAWN_SESSION", "").isdigit(): - request["session"] = int(os.environ["DD_SPAWN_SESSION"]) # the session it belongs to + # the session it belongs to, as SessionService writes it (a positive decimal); anything else is + # left out, and the app then runs nothing for it + session = os.environ.get("DD_SPAWN_SESSION", "") + if re.fullmatch(r"[1-9][0-9]{0,8}", session): + request["session"] = int(session) payload = json.dumps(request).encode() s.sendmsg([struct.pack(">I", len(payload)), payload], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))]) diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 994f245890..084f4f9641 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -268,19 +268,18 @@ static void ddh_prepare(void) { // when it cannot (ddh_try()) if (getenv("DD_SPAWN")) ddh_forks(1); 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) { - __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 - // Not cancelled meanwhile (the wait for earlier closes sleeps, a cancellation point), which would - // leave the guard taken and the candidate's state half kept for every later fork. + // Not cancelled from taking the guard to giving it back (the wait for earlier closes sleeps, a + // cancellation point, and asynchronous cancellation could strike anywhere), which would leave the + // guard taken and the candidate's state half kept for every later fork. The guard goes back + // before cancellation can come again. int cancel = PTHREAD_CANCEL_ENABLE; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel); - for (int attempt = 0; attempt < 2 && !ddh_prepare_table(); attempt++) {} + if (!__atomic_exchange_n(&g_ddh_preparing, 1, __ATOMIC_ACQ_REL)) { + // a second try for a table another thread's close took before it was kept + for (int attempt = 0; !g_ddh && attempt < 2 && !ddh_prepare_table(); attempt++) {} + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); + } pthread_setcancelstate(cancel, NULL); - __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 @@ -1241,12 +1240,16 @@ static int ddh_pressure_keeps(const char *filename, char *const argv[]) { } static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) { - if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0; + pid_t parent = (pid_t)syscall(SYS_getppid); + if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter(parent)) return 0; + // Not a job a shell with job control runs (in a process group of its own, not the shell's): the + // shell stops, continues and waits for it with WUNTRACED, and a handed-off program's stops and + // continues never reach a wait (they happen to its worker, which is not this process's child). + if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent)) return 0; // Not a job in the foreground of its controlling terminal: a handed-off program has none (the // worker's setsid()), so /dev/tty, ^C and job control would miss it, whatever its standard fds - // are ("cmd | less", "less < file", output redirected). A job started with & runs in a background - // group, or, from a shell without job control, in the foreground group reading /dev/null: that - // one goes. + // are ("cmd | less", "less < file", output redirected). A job started with & from a shell without + // job control runs in the foreground group reading /dev/null: that one goes. pid_t fg = 0; int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty", O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0); @@ -1875,49 +1878,10 @@ static pid_t ddh_reap_exited(ddh_wait4_f real, pid_t pid, int *status, int keep, return 0; } -// A process's state letter in /proc ('T' stopped, 't' stopped by its tracer), 0 when it is gone -static char ddh_proc_state(pid_t pid) { - char path[48], stat[512]; - snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); - int saved = errno; - long n = ddh_read_proc(path, stat, sizeof(stat)); - errno = saved; - if (n <= 0) return 0; - char *end = strrchr(stat, ')'); - return end && end[1] == ' ' ? end[2] : 0; -} - -// A stop or a continue of a handed-off program that a wait for pid asks for (WUNTRACED, which is -// waitid()'s WSTOPPED, or WCONTINUED): the program runs in its worker, a process of the app's, whose -// state tells it, and kill() sends a stop or a continue there. Each is reported once (e->pad[0]: 1 -// while the stop is reported and its continue not; keep, as WNOWAIT, reports and leaves it), with -// SIGSTOP for the signal, which /proc does not tell. The child, its wait status in *status, or 0. -static pid_t ddh_job_event(pid_t pid, int options, int keep, int *status) { - struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); - if (!t || !(options & (WUNTRACED | WCONTINUED))) return 0; - pid_t me = getpid(); - for (int i = 0; i < DDH_SLOTS; i++) { - struct ddh_entry *e = &t->e[i]; - if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_HANDED || e->parent != me || e->real <= 0 || !ddh_selects(e, pid)) - continue; - char state = ddh_proc_state(e->real); - int stopped = state == 'T' || state == 't'; - int32_t reported = __atomic_load_n(&e->pad[0], __ATOMIC_ACQUIRE); - int32_t want = -1; - if ((options & WUNTRACED) && stopped && reported == 0) want = 1; - else if ((options & WCONTINUED) && state && !stopped && reported == 1) want = 0; - if (want < 0) continue; - if (!keep && !__atomic_compare_exchange_n(&e->pad[0], &reported, want, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) - continue; // another wait reported it - if (status) *status = want ? (SIGSTOP << 8) | 0x7f : 0xffff; - return e->child; - } - return 0; -} - // 20 ms, or -1 (EINTR) when a signal's handler interrupted it. The read of a timerfd restarts, as a // wait does, after a handler installed with SA_RESTART; nanosleep() never does. static int ddh_nap(void) { + pthread_testcancel(); // as the wait it stands for would be: nothing is held here int fd = (int)syscall(SYS_timerfd_create, CLOCK_MONOTONIC, O_CLOEXEC); if (fd < 0) { struct timespec ts = {0, 20 * 1000 * 1000}; @@ -1957,12 +1921,6 @@ 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) { - int job = 0; - if (ddh_job_event(pid, options, 0, &job) == pid) { - if (ru) memset(ru, 0, sizeof(*ru)); - if (status) *status = job; - return pid; - } 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); @@ -1986,8 +1944,6 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { continue; } pid_t done = pid <= 0 ? ddh_reap_exited(real, pid, status, 0, options & (__WALL | __WNOTHREAD)) : 0; - int job = 0; - if (done <= 0 && pid <= 0 && (done = ddh_job_event(pid, options, 0, &job)) > 0 && status) *status = job; if (done > 0) { if (ru) memset(ru, 0, sizeof(*ru)); return done; @@ -2133,19 +2089,6 @@ static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { } return 0; } - int job = 0; - pid_t stopped = ddh_job_event(which, options & (WSTOPPED | WCONTINUED), options & WNOWAIT, &job); - if (stopped > 0) { - if (info) { - memset(info, 0, sizeof(*info)); - info->si_signo = SIGCHLD; - info->si_pid = stopped; - info->si_uid = (uid_t)call_orig_syscall(SYS_getuid, 0, 0, 0, 0, 0, 0); - info->si_code = job == 0xffff ? CLD_CONTINUED : CLD_STOPPED; - info->si_status = job == 0xffff ? SIGCONT : SIGSTOP; - } - return 0; - } int live = ddh_any_live(which); siginfo_t seen; memset(&seen, 0, sizeof(seen)); diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 7fb2af8d62..90b45bb97d 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -546,6 +546,13 @@ int main(int argc, char **argv) { printf("tables\t%d\n", tables_open()); if (write(prep_in[1], "1", 1) != 1) return 1; pthread_join(closer, NULL); + // The close has closed the given-up table's 800 by now; a file of the program's own takes the + // number, as another thread's open could, and outlives the next try, which finds no table there. + char target[64]; + printf("freed800\t%d\n", readlink("/proc/self/fd/800", target, sizeof(target)) < 0); + int mine = open("/dev/null", O_RDONLY); + if (mine < 0 || dup2(mine, 800) != 800) return 1; + close(mine); pid_t again = fork(); // the close is over: the table is made now if (again == 0) { execl("/bin/target", "target", argv[2], (char *)NULL); @@ -554,6 +561,9 @@ int main(int argc, char **argv) { if (again < 0) return 1; printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); printf("table\t%d\n", table_open()); + ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1); + if (n > 0) target[n] = 0; + printf("mine800\t%d\n", n > 0 && strcmp(target, "/dev/null") == 0); return 0; } if (strcmp(argv[1], "nowaitpeek") == 0) { @@ -603,28 +613,6 @@ int main(int argc, char **argv) { pthread_join(closer, NULL); return 0; } - if (strcmp(argv[1], "stopprog") == 0) { - // the program a child handed off is stopped and continued (kill() sends both to its worker): - // waits that ask for them see both, as for a child of the kernel's - pid_t child = fork(); - if (child == 0) { - execl("/bin/target", "target", "sleep", (char *)NULL); - _exit(127); - } - if (child < 0) return 1; - for (int i = 0; i < 500 && !zombie(child); i++) usleep(10000); // handed off, its forked child gone - int status = 0; - kill(child, SIGSTOP); - pid_t r = waitpid(child, &status, WUNTRACED); - printf("stopped\t%d\n", r == child && WIFSTOPPED(status)); - kill(child, SIGCONT); - r = waitpid(child, &status, WCONTINUED); - printf("continued\t%d\n", r == child && WIFCONTINUED(status)); - kill(child, SIGKILL); - r = waitpid(child, &status, 0); - printf("killed\t%d\n", r == child && WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL); - return 0; - } if (strcmp(argv[1], "reapreuse") == 0) { if (pipe(reuse_in) != 0 || pipe(reuse_out) != 0) return 1; pid_t first = fork(); @@ -1178,8 +1166,13 @@ class NativeHookHandoffTest(unittest.TestCase): try: stdout, err = proc.communicate(given.get("input"), timeout=120) except subprocess.TimeoutExpired: - # the programs the spawner ran, and those the fixture ran itself, hold its output open too - self.end_programs(spawner) + # the programs the spawner ran, and those the fixture ran itself, hold its output open too; + # all of it is ended, and a worker that could not be is reported after + unended = None + try: + self.end_programs(spawner) + except RuntimeError as error: + unended = error try: os.killpg(proc.pid, signal.SIGKILL) # its own session's group, as it was started except OSError: @@ -1192,7 +1185,7 @@ class NativeHookHandoffTest(unittest.TestCase): pipe.close() proc.wait(timeout=10) stdout, err = "", "(its output still open after it was ended)" - self.fail("the fixture did not finish:\n%s\n%s" % (stdout, err)) + self.fail("the fixture did not finish:\n%s\n%s%s" % (stdout, err, "\n%s" % unended if unended else "")) out = subprocess.CompletedProcess(proc.args, proc.returncode, stdout, err) if spawner.failures: self.fail("the fake spawner could not run a program safely: %s" % spawner.failures) @@ -1316,6 +1309,15 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual(["target", "7"], requests[0]["argv"]) self.assertEqual("7", result.get("exit"), out.stdout) + def test_near_the_limit_a_job_control_job_is_not(self): + # in a process group of its own, as a shell with job control runs a job: the shell waits for + # its stops, which a handed-off program's never reach + result, requests, out = self.run_parent("group", "4", handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests, out.stderr) + self.assertEqual("1", result.get("same"), out.stdout) + # run here: 4, where a child can exec an aarch64 program, else the exec's 127 + self.assertEqual("4" if self.child_status == "3" else "127", result.get("exit"), out.stdout) + def test_below_the_limit_a_shells_child_is_not(self): result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=1000, as_shell=True) self.assertEqual([], requests) @@ -1381,6 +1383,9 @@ class NativeHookHandoffTest(unittest.TestCase): self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc)") result, requests, out = self.run_parent("prepcloseheld", "5", extra_env={"DDH_TEST_LATE_TABLE": "1"}) self.assertEqual("1", result.get("tables"), out.stdout + out.stderr) + # the given-up table's number, closed by the close and then the program's own file, stays its + self.assertEqual("1", result.get("freed800"), out.stdout) + self.assertEqual("1", result.get("mine800"), out.stdout) self.assertEqual("5", result.get("again"), out.stdout) self.assertEqual("1", result.get("table"), out.stdout) self.assertEqual(1, len(requests), out.stderr) @@ -1409,13 +1414,6 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual(result.get("second"), result.get("last"), out.stdout) self.assertEqual(str(signal.SIGTERM.value), result.get("lastsignal"), out.stdout) - def test_a_handed_off_programs_stop_and_continue_reach_waits_that_ask(self): - result, requests, out = self.run_parent("stopprog", "sleep") - self.assertEqual(1, len(requests), out.stderr) - self.assertEqual("1", result.get("stopped"), out.stdout + out.stderr) - self.assertEqual("1", result.get("continued"), out.stdout) - self.assertEqual("1", result.get("killed"), 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(str(os.CLD_STOPPED), result.get("peeked"), out.stdout + out.stderr) # the look saw the stop