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 48838652a9..b771951b48 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -328,13 +328,12 @@ object GuestWorkers { * [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends. * [commit] runs with the pid before the worker may run the program; false, and it does not. * [confirmed] runs once the worker has taken it on, just before it is told to run it; false, and it does not. + * [owner]: the session asking (the one a guest's request names), else the latest. */ private fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }, - confirmed: () -> Boolean = { true }): Int { + confirmed: () -> Boolean = { true }, owner: Int = session): Int { val app = context.applicationContext - // The session asking: a cold bind can take long enough for it to stop and another to start - val owner = session if (guest && owner <= stopped) { Log.w(TAG, "session $owner is stopping: not starting ${argv.firstOrNull()}") return -1 @@ -737,7 +736,11 @@ object GuestWorkers { var answered = false // the hook's last word, sent once the worker has taken the program on and before it runs it var confirmedToHook = false - val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, onExit = { code -> + // 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 + 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) exited.countDown() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index bfdcfd2eef..5775c3341e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -712,7 +712,10 @@ class SessionService : Service() { if (gen != sessionGen || !SessionState.running) 0 else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it } } - if (ownWorkers > 0) guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this)) + if (ownWorkers > 0) { + guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this)) + guest.add("DD_SPAWN_SESSION=$ownWorkers") + } } // Proton builds up to 11.12 report X11 text fields under this name. guest.add("BL_LAUNCH_DIR=" + sessionRoot.path) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn index 55c13280a3..0f8bcc32a7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn @@ -75,7 +75,10 @@ def main(): s.connect("\0" + name) except OSError: return fallback(args, wait, pid_file) - payload = json.dumps({"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}).encode() + 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 + 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]))]) reply = s.makefile("r") diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index dd4b0ca9c9..8086f5b0e3 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -1439,6 +1439,12 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] ddh_putint(&b, (long)mask); ddh_puts(&b, ",\"pgid\":"); ddh_putint(&b, (long)group); + // the session it belongs to (DD_SPAWN_SESSION), which the app starts it for, not a later one + const char *session = ddh_env(envp, "DD_SPAWN_SESSION"); + if (session && *session >= '1' && *session <= '9') { + ddh_puts(&b, ",\"session\":"); + ddh_putint(&b, strtol(session, NULL, 10)); + } ddh_puts(&b, ",\"sigmask\":"); ddh_putint(&b, (long)blocked_bits); ddh_puts(&b, ",\"anchor\":"); @@ -1864,6 +1870,46 @@ 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) { @@ -1906,6 +1952,12 @@ 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); @@ -1929,6 +1981,8 @@ 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; @@ -1944,8 +1998,12 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { ((live || (options & WNOHANG)) ? WNOHANG : 0); siginfo_t seen; memset(&seen, 0, sizeof(seen)); - pid_t r = (pid_t)call_orig_syscall(SYS_waitid, (unsigned long)type, (unsigned long)id, (unsigned long)&seen, - (unsigned long)look, 0, 0); + // libc's waitid(): a blocking look stays a cancellation point, as the wait4() it stands for is + static int (*libc_waitid)(idtype_t, id_t, siginfo_t *, int); + if (!libc_waitid) libc_waitid = (int (*)(idtype_t, id_t, siginfo_t *, int))dlsym(RTLD_NEXT, "waitid"); + pid_t r = libc_waitid ? libc_waitid(type, id, &seen, look) + : (pid_t)call_orig_syscall(SYS_waitid, (unsigned long)type, (unsigned long)id, (unsigned long)&seen, + (unsigned long)look, 0, 0); if (r == 0 && seen.si_pid > 0) { pid_t child = seen.si_pid; ddh_wait_gate(); @@ -2070,6 +2128,19 @@ 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 19483eb203..5e63f9817c 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -92,6 +92,7 @@ static void *nothread_forker(void *unused) { execl("/bin/target", "target", nothread_arg, (char *)NULL); _exit(127); } + if (pid < 0) _exit(121); nothread_child = pid; usleep(1500000); // the program has exited by now nothread_go(1); @@ -171,6 +172,7 @@ static int late_record(const char *arg, int live) { execl("/bin/target", "target", arg, (char *)NULL); _exit(127); } + if (pid < 0) return 1; printf("reused\t%d\n", pid == first); int err = -1; if (live == 1) { @@ -213,6 +215,7 @@ static void *gone_forker(void *unused) { execl("/bin/target", "target", nothread_arg, (char *)NULL); _exit(127); } + if (pid < 0) _exit(121); nothread_child = pid; return NULL; // the thread ends: its child goes to the main thread } @@ -451,6 +454,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", "sleep", (char *)NULL); _exit(127); } + if (own < 0) return 1; nothread_arg = argv[2]; pthread_t forker; pthread_create(&forker, NULL, nothread_forker, NULL); @@ -504,6 +508,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } + if (pid < 0) return 1; pthread_join(release, NULL); pthread_join(closer, NULL); printf("ranged\t%ld\n", prep_closed); @@ -516,6 +521,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } + if (again < 0) return 1; printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); } printf("acked\t%d\n", prep_acked); @@ -534,6 +540,7 @@ int main(int argc, char **argv) { for (int i = 0; i < 3; i++) { pid_t quick = fork(); if (quick == 0) _exit(0); + if (quick < 0) return 1; waitpid(quick, &status, 0); } printf("tables\t%d\n", tables_open()); @@ -544,6 +551,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } + 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()); return 0; @@ -555,6 +563,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", "sleep", (char *)NULL); _exit(127); } + if (child < 0) return 1; pthread_t waiter; pthread_create(&waiter, NULL, nowait_waiter, NULL); char c; @@ -582,16 +591,40 @@ int main(int argc, char **argv) { execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } + if (grandchild < 0) _exit(123); int status = 0; if (waitpid(grandchild, &status, 0) != grandchild) _exit(124); _exit(WIFEXITED(status) ? WEXITSTATUS(status) : 125); } + if (child < 0) return 1; int status = 0; printf("child\t%d\n", waitpid(child, &status, 0) == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); if (write(prep_in[1], "1", 1) != 1) return 1; 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(); @@ -599,6 +632,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", "sleep", (char *)NULL); _exit(127); } + if (first < 0) return 1; pthread_t waiter; pthread_create(&waiter, NULL, reuse_waiter, NULL); char c; @@ -612,7 +646,14 @@ int main(int argc, char **argv) { execl("/bin/target", "target", "sleep", (char *)NULL); _exit(127); } - usleep(1500000); // handed off, its forked child exited + if (second < 0) { + if (write(reuse_in[1], "1111", 4) != 4) return 1; // the waiter let go before the fixture fails + return 1; + } + // handed off, its forked child exited (its exit not taken: the waiter is held) + int exited = 0; + for (int i = 0; i < 500 && !(exited = zombie(second)); i++) usleep(10000); + printf("secondexited\t%d\n", exited); if (write(reuse_in[1], "1111", 4) != 4) return 1; // for this reap and any after it usleep(500000); kill(second, SIGTERM); @@ -627,6 +668,7 @@ int main(int argc, char **argv) { execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } + if (peek_child < 0) return 1; usleep(300000); // its handoff is with the app (the fake spawner holds its reply) syscall(SYS_tgkill, peek_child, peek_child, SIGSTOP); pthread_t waiter; @@ -679,6 +721,7 @@ int main(int argc, char **argv) { execl(argc > 3 ? argv[3] : "/bin/target", "target", argv[2], (char *)NULL); _exit(127); } + if (pid < 0) return 1; int status = 0; if (strcmp(argv[1], "waitidpid") == 0) { struct sigaction sa; @@ -1146,6 +1189,13 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("7", result.get("exit"), out.stdout) self.assertEqual("-1", result.get("again"), out.stdout) + def test_a_request_names_the_session_it_belongs_to(self): + # the app starts the program for that session, not a later one begun meanwhile + result, requests, out = self.run_parent("wait", "7", extra_env={"DD_SPAWN_SESSION": "12"}) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual(12, requests[0].get("session"), requests[0]) + self.assertEqual("7", result.get("exit"), out.stdout) + def test_a_child_that_closed_its_inherited_fds_is_handed_off(self): result, requests, out = self.run_parent("closefds", "5") if result.get("closerange") != "0": @@ -1324,11 +1374,21 @@ class NativeHookHandoffTest(unittest.TestCase): def test_a_late_mark_of_a_reused_slot_leaves_the_new_child_once(self): result, requests, out = self.run_parent("reapreuse", "sleep") self.assertEqual(2, len(requests), out.stderr) + # the second child took the first's slot, and had handed off before the late mark came + self.assertEqual(requests[0]["slot"], requests[1]["slot"], requests) self.assertEqual("1", result.get("first"), out.stdout + out.stderr) + self.assertEqual("1", result.get("secondexited"), out.stdout) self.assertEqual("1", result.get("reports"), out.stdout) 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(1, len(requests), out.stderr)