From e418f99aa066af6ddf61f3c3a9b6ca2525ebdf2f Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:27:43 -0500 Subject: [PATCH] feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive --- docs/phantom-processes.md | 57 ++++- .../overlay/usr/local/bin/droiddeck-session | 4 +- tools/nativeguest/hook/exec.c | 137 ++++++++++- tools/nativeguest/hook/handoff.c | 229 ++++++++++++++++-- tools/tests/test_native_hook_handoff.py | 42 +++- 5 files changed, 439 insertions(+), 30 deletions(-) diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md index 20112ba2b9..b5f3162859 100644 --- a/docs/phantom-processes.md +++ b/docs/phantom-processes.md @@ -6,8 +6,8 @@ Android must not kill a Steam session for having too many Linux processes, and t need developer options. Status: **working on the AYN Thor (Android 13).** With Android's limit on and no developer option, -a Steam session with a game running keeps 14 processes in the app's counted cgroup (63 without -this work), and Android killed nothing in 3 minutes of forced scans. DroidDeck's Setup reports the +a Steam session with a game running keeps 12 processes in the app's counted cgroups (63 without +this work), and Android killed nothing in minutes of forced scans. DroidDeck's Setup reports the limit as handled and no longer blocks Steam. Both counting gaps below are in identical code on Android 12 through 16; a stock Android 14+ phone is still to be tested. The experiments are in `tools/phantomlab` (see the end). @@ -297,9 +297,10 @@ Things this needed, found the hard way: took the whole app down once). - **The table is made at a process's first fork,** not only when `DD_SPAWN` is in its environment at start: a shell that exports it has no sign of it in its own environment. -- **Exit status:** the program's hook records it with `on_exit` into the parent's table; the app's - `ApplicationExitInfo` is only the fallback (signals, `_exit`). A program inherits its forked - parent's ignored signals, open-files limit and umask (`DDH_SIGIGN`, `DDH_NOFILE`, `DDH_UMASK`). +- **Exit status:** the program's hook records it with `on_exit` or in `_exit()` into the parent's + table; the app's `ApplicationExitInfo` is only the fallback (signals). A program inherits its + forked parent's ignored signals, open-files limit and umask (`DDH_SIGIGN`, `DDH_NOFILE`, + `DDH_UMASK`). Measured on the Thor, Bully under Proton, Android's limit on (default 32), a scan forced every 20 s: @@ -307,12 +308,48 @@ Measured on the Thor, Bully under Proton, Android's limit on (default 32), a sca |---|---|---|---| | main (no handoff) | 48 | 63 | 33, session failed | | first round | 26 | 29 | 0 | -| **second round** | **9** | **14** | **0** | -| + PulseAudio in a worker | 8 | | | +| second round | 9 | 14 | 0 | +| **third round** | **7–9** | **12** | **0** in 2 min, game kept focus | Still counted at idle: `run_gamescope`'s subshell, Steam, its web helper's browser and -two utility processes, the session bus's activation babysitter and Decky's sound-effects worker -(forks without an exec). Quitting the game, stopping the session (no worker is left) and starting +two or three utility processes, the session bus's activation babysitter and Decky's +multiprocessing child (forks without an exec). In game, also Steam's launch chain (`sh`, +`pw-audio-namespace`, `reaper`) and the `wineserver` daemon (a fork of its first process, which +lingers in its worker; see below). + +### Third round + +- **PulseAudio in a worker** (above). +- **`posix_spawn()`:** Python 3.13+ (`subprocess`, even with `close_fds`) and GLib's `g_spawn` start + programs with `posix_spawn()`, whose child makes the exec system call itself, past the hook. A + listed program is now spawned with `fork()` and the hook's `execve()`; the hook replays glibc's + file actions and attributes in the child, and a close-on-exec pipe returns an exec error as + `posix_spawn()`'s result. Proton's Wine and at-spi's bus came out of the count this way. +- **The table fd survives a child that closes every inherited fd** (Python's `subprocess` before + exec): it sits at fd 800 or above and is one of the hook's kept fds. Reopening it from + `/proc//fd` does not work on Android (EACCES). A nonce in the table's header tells it from + a file a program put at that number (inode numbers are rewritten by the hardlink emulation). +- **The exit status comes from the program itself.** The worker first runs a `bash` that `cd`s and + execs the program; that `bash` closed the `DDH_TABLE` fd as someone else's table, so the + program after it could never report, and statuses came from `ApplicationExitInfo`, late or + unknown. The `DDH_TABLE` fd is now kept through that exec, and `_exit()` reports as `exit()` does. +- **Daemons:** Android kills every process in a worker's cgroup when the worker's own process ends + (`libprocessgroup: Successfully killed process cgroup`). `wineserver` forks the server and leaves + with `_exit(0)`, so the server died with it and Wine stopped with "the wine server failed to run". + A handed-off program's process now reports its status and then stays, with no fds but the + binder's and all signals blocked, until no other process is left in its cgroup (found through + `/proc//cgroup`, as `cgroup.procs` is not readable). It does so only when it is + single-threaded at exit, and never for the processes the app starts itself (the session root), + whose exit the app waits for. +- **`reap_orphans`** in the session script killed every process whose parent was zygote (all the + app's workers, the session root among them) when the inner `droiddeck-session` ended in a + worker: the guest cannot see zygote in `/proc`. It now stands down when `DDH_WORKER_PID` is + its own pid. +- **`DD_HANDOFF_DEBUG=/path`** appends the hook's trace to a file. On stderr it broke Steam's + login, and the trace from a game's processes went to a pipe nobody read. +- **Finding the sender of a SIGKILL:** shell can enable the `signal/signal_generate` ftrace event + on the Thor (`/sys/kernel/tracing`), which names the sending thread; Perfetto recorded nothing + there. Quitting the game, stopping the session (no worker is left) and starting again all work. Started from the front end with the limit on, Setup shows "Child-process limit handled by DroidDeck" and Steam starts. @@ -329,9 +366,11 @@ the old behavior and the old requirement. 2. ~~B for the processes DroidDeck and the session script start themselves~~ done. 3. ~~B inside the hook, with pid translation~~ done. 4. ~~The session root, its jobs, the log pipeline, the gamescope chain~~ done: 9 idle, 14 in game. + Third round (PulseAudio, `posix_spawn`, daemons): 7–9 idle, 12 in game. 5. ~~Setup no longer requires the developer option while the session runs in workers~~ done. 6. Open: - ~~PulseAudio in a worker~~ done; + - ~~`posix_spawn()` and daemons in workers~~ done; - `/proc//stat` showing the virtual parent, so that Steam and its web helper can be handed off too; - pre-started workers, so that a handoff costs no zygote fork (about 100 ms now); diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 544aaa621c..04f43b4b56 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -658,7 +658,9 @@ export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11 reap_orphans() { local round p stat pid left # Started by the app as an Android process of its own: its parent is zygote, whose other - # children are the app's processes. + # children are the app's processes. The guest may not see zygote in /proc; a worker's own + # program has DDH_WORKER_PID. + [ "${DDH_WORKER_PID:-}" = "$$" ] && return 0 case "$(tr -d '\0' < "/proc/$PPID/cmdline" 2>/dev/null)" in zygote*) return 0 ;; esac for round in 1 2 3 4 5; do left= diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index bb33f270f8..b1afebd855 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -1068,6 +1068,136 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, static int apply_closefrom(posix_spawn_file_actions_t *actions); +// glibc's file actions (posix/spawn_int.h, unchanged since 2.35) +struct ddh_spawn_action { + enum { DDH_DO_CLOSE, DDH_DO_DUP2, DDH_DO_OPEN, DDH_DO_CHDIR, DDH_DO_FCHDIR, DDH_DO_CLOSEFROM, DDH_DO_TCSETPGRP } tag; + union { + struct { int fd; } close_action; + struct { int fd; int newfd; } dup2_action; + struct { int fd; char *path; int oflag; mode_t mode; } open_action; + struct { char *path; } chdir_action; + struct { int fd; } fchdir_action; + struct { int from; } closefrom_action; + struct { int fd; } setpgrp_action; + } action; +}; + +#ifndef POSIX_SPAWN_SETSID +#define POSIX_SPAWN_SETSID 0x80 +#endif + +// What glibc's spawn child does before its exec (posix/spawni.c), as an errno. +static int ddh_spawn_child_setup(const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr) { + short flags = 0; + if (attr) posix_spawnattr_getflags(attr, &flags); + if (flags & POSIX_SPAWN_SETSIGDEF) { + sigset_t def; + posix_spawnattr_getsigdefault(attr, &def); + for (int sig = 1; sig < _NSIG; sig++) { + if (sigismember(&def, sig) == 1) signal(sig, SIG_DFL); + } + } + if ((flags & POSIX_SPAWN_SETSID) && setsid() < 0) return errno; + if (flags & POSIX_SPAWN_SETPGROUP) { + pid_t group = 0; + posix_spawnattr_getpgroup(attr, &group); + if (setpgid(0, group) != 0) return errno; + } + if (flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)) { + struct sched_param param; + posix_spawnattr_getschedparam(attr, ¶m); + int policy = 0; + posix_spawnattr_getschedpolicy(attr, &policy); + int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, ¶m) : sched_setparam(0, ¶m); + if (r == -1) return errno; + } + const struct ddh_spawn_action *a = fa ? (const struct ddh_spawn_action *)fa->__actions : NULL; + for (int i = 0; a && i < fa->__used; i++) { + switch (a[i].tag) { + case DDH_DO_CLOSE: + close(a[i].action.close_action.fd); + break; + case DDH_DO_OPEN: { + int fd = open(a[i].action.open_action.path, a[i].action.open_action.oflag, a[i].action.open_action.mode); + if (fd < 0) return errno; + if (fd != a[i].action.open_action.fd) { + if (dup2(fd, a[i].action.open_action.fd) < 0) return errno; + close(fd); + } + break; + } + case DDH_DO_DUP2: + if (a[i].action.dup2_action.fd == a[i].action.dup2_action.newfd) { + int fdflags = fcntl(a[i].action.dup2_action.fd, F_GETFD); + if (fdflags < 0 || fcntl(a[i].action.dup2_action.fd, F_SETFD, fdflags & ~FD_CLOEXEC) < 0) return errno; + } else if (dup2(a[i].action.dup2_action.fd, a[i].action.dup2_action.newfd) < 0) { + return errno; + } + break; + case DDH_DO_CHDIR: + if (chdir(a[i].action.chdir_action.path) != 0) return errno; + break; + case DDH_DO_FCHDIR: + if (fchdir(a[i].action.fchdir_action.fd) != 0) return errno; + break; + case DDH_DO_CLOSEFROM: + close_range((unsigned int)a[i].action.closefrom_action.from, ~0U, 0); + break; + case DDH_DO_TCSETPGRP: + if (tcsetpgrp(a[i].action.setpgrp_action.fd, getpgrp()) != 0) return errno; + break; + } + } + if (flags & POSIX_SPAWN_SETSIGMASK) { + sigset_t mask; + posix_spawnattr_getsigmask(attr, &mask); + sigprocmask(SIG_SETMASK, &mask, NULL); + } + return 0; +} + +// posix_spawn() as fork() and execve(), so that ddh_try() sees the exec. -1 when it cannot be. +static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + if (fa) { + const struct ddh_spawn_action *a = (const struct ddh_spawn_action *)fa->__actions; + for (int i = 0; i < fa->__used; i++) { + if ((unsigned)a[i].tag > DDH_DO_TCSETPGRP) return -1; + } + } + int report[2]; + if (pipe2(report, O_CLOEXEC) != 0) return -1; + pid_t child = fork(); + if (child < 0) { + int err = errno; + close(report[0]); + close(report[1]); + return err; + } + if (child == 0) { + close(report[0]); + int err = ddh_spawn_child_setup(fa, attr); + if (!err) { + execve(path, argv, envp); + err = errno; + } + syscall(SYS_write, report[1], &err, sizeof(err)); + _exit(127); + } + close(report[1]); + int err = 0; + ssize_t n; + do n = read(report[0], &err, sizeof(err)); + while (n < 0 && errno == EINTR); + close(report[0]); + if (n == (ssize_t)sizeof(err)) { + waitpid(child, NULL, 0); + return err; + } + if (pid) *pid = child; + return 0; +} + int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, @@ -1077,7 +1207,12 @@ int posix_spawn(pid_t *pid, const char *path, if (bad) return bad; } posix_spawnattr_t sanitized; - return ddnatv_posix_spawn(pid, path, file_actions, spawn_attr_for_android(attrp, &sanitized), argv, envp, 0); + const posix_spawnattr_t *attr = spawn_attr_for_android(attrp, &sanitized); + if (ddh_spawn_wanted(path, argv, envp ? envp : environ)) { + int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ); + if (ret != -1) return ret; + } + return ddnatv_posix_spawn(pid, path, file_actions, attr, argv, envp, 0); } int posix_spawnp(pid_t *pid, const char *file, diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 9195489eb5..3cdf262d0e 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -17,6 +17,7 @@ #define DDH_HANDED 1 #define DDH_EXITED 2 #define DDH_MAGIC 0x6464686f +#define DDH_TABLE_FD 800 struct ddh_entry { int32_t child; // the pid the parent got from fork() @@ -50,14 +51,31 @@ static const char *ddh_env(char *const envp[], const char *name) { return NULL; } +// DD_HANDOFF_DEBUG=1 writes the trace to stderr; an absolute path appends it to that file instead +// (stderr can be a pipe a program parses, or one nobody reads). +static void ddh_log(const char *setting, const char *line, size_t len) { + if (!setting || len == 0) return; + if (setting[0] != '/') { + syscall(SYS_write, 2, line, len); + return; + } + int fd = (int)syscall(SYS_openat, AT_FDCWD, setting, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644); + if (fd < 0) return; + syscall(SYS_write, fd, line, len); + syscall(SYS_close, fd); +} + // In the parent, before fork(): the table the children write to. static void ddh_prepare_failed(const char *step) { - if (!getenv("DD_HANDOFF_DEBUG")) return; + const char *debug = getenv("DD_HANDOFF_DEBUG"); + if (!debug) return; char line[96]; int len = snprintf(line, sizeof(line), "ddnatv handoff: %d no table: %s errno %d\n", (int)getpid(), step, errno); - if (len > 0) syscall(SYS_write, 2, line, (size_t)len); + if (len > 0) ddh_log(debug, line, (size_t)len); } +static void ddh_keep(int fd); + // The table the children write to: at start when DD_SPAWN is set, else at the first fork() (a // shell that exports DD_SPAWN itself has no sign of it in its own environment). static void ddh_prepare(int any) { @@ -78,18 +96,46 @@ static void ddh_prepare(int any) { close(fd); return; } + // 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. + int high = (int)syscall(SYS_fcntl, fd, F_DUPFD_CLOEXEC, DDH_TABLE_FD); + if (high >= 0) { + syscall(SYS_close, fd); + fd = high; + } + ddh_keep(fd); g_ddh = p; g_ddh->magic = DDH_MAGIC; g_ddh->pad[0] = getpid(); + // A nonce that tells this table's fd from any other (inode numbers are rewritten by the hardlink emulation) + if (syscall(SYS_getrandom, &g_ddh->pad[1], 2 * sizeof(int32_t), 0) != 2 * (long)sizeof(int32_t)) { + g_ddh->pad[1] = (int32_t)time(NULL); + g_ddh->pad[2] = (int32_t)(intptr_t)p; + } g_ddh_fd = fd; g_ddh_owner = getpid(); } +// 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]; + if (fd < 0 || syscall(SYS_pread64, fd, head, sizeof(head), 0) != (long)sizeof(head)) return 0; + return head[0] == t->magic && head[1] == t->pad[0] && head[2] == t->pad[1] && head[3] == t->pad[2]; +} + // A table inherited across exec: the parent's if its owner is still our parent, else closed. static void ddh_find_parent_table(void) { char path[64], target[64]; pid_t parent = getppid(); + // The table a worker's program reports its exit to (DDH_TABLE), also for what it execs + int report = -1; + const char *spec = getenv("DDH_TABLE"); + if (spec && getenv("DDH_WORKER_PID") && atoi(getenv("DDH_WORKER_PID")) == getpid()) report = atoi(spec); for (int fd = 3; fd < 1024; fd++) { + if (fd == report) { + ddh_keep(fd); + continue; + } int n = snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); if (n <= 0) continue; long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); @@ -101,6 +147,7 @@ static void ddh_find_parent_table(void) { g_ddh_up = t; g_ddh_up_fd = fd; syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC); + ddh_keep(fd); continue; } if (t != MAP_FAILED) munmap(t, sizeof(struct ddh_table)); @@ -166,18 +213,152 @@ static void ddh_find_worker_binder(void) { // In the program a worker runs for a handed-off child (DDH_TABLE "FD:SLOT:PARENT"): its exit status // goes into the parent's table here; the app reports it from Android's exit record only when the -// program never got to exit() (a signal, _exit()). +// program never got to exit() or _exit() (a signal). static struct ddh_table *g_ddh_report; static int g_ddh_report_slot = -1; static pid_t g_ddh_report_parent; -static void ddh_report_exit(int status, void *unused) { - (void)unused; +// The line of /proc/PID/cgroup that names the app's per-process cgroup ("...:/uid_U/pid_P"). +static int ddh_cgroup_line(pid_t pid, const char *want, char *out, size_t size) { + char path[48], buf[512]; + snprintf(path, sizeof(path), "/proc/%d/cgroup", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, buf, sizeof(buf) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + buf[n] = 0; + if (want) return strstr(buf, want) != NULL; + char mine[32]; + snprintf(mine, sizeof(mine), "/pid_%d\n", (int)pid); + char *at = strstr(buf, mine); + if (!at) return 0; + char *start = at; + while (start > buf && start[-1] != '\n') start--; + size_t len = (size_t)(at - start) + strlen(mine); + if (len + 1 > size) return 0; + memcpy(out, start, len); + out[len] = 0; + return 1; +} + +// A live process (not a zombie) in the cgroup that line names. +static int ddh_cgroup_member(pid_t pid, const char *line) { + char path[48], stat[256]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + stat[n] = 0; + char *paren = strrchr(stat, ')'); + if (!paren || paren[1] != ' ' || paren[2] == 'Z' || paren[2] == 'X') return 0; + return ddh_cgroup_line(pid, line, NULL, 0); +} + +static pid_t ddh_find_cgroup_member(const char *line, pid_t self) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return 0; + char entries[8192]; + pid_t found = 0; + long n; + while (!found && (n = syscall(SYS_getdents64, dir, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n && !found;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (name[0] < '1' || name[0] > '9') continue; + pid_t pid = (pid_t)atoi(name); + if (pid != self && ddh_cgroup_member(pid, line)) found = pid; + } + } + syscall(SYS_close, dir); + return found; +} + +static void ddh_linger_note(const char *what, long value) { + const char *debug = getenv("DD_HANDOFF_DEBUG"); + if (!debug) return; + char text[160]; + int len = snprintf(text, sizeof(text), "ddnatv handoff: %d linger: %s %ld\n", (int)getpid(), what, value); + if (len > 0) ddh_log(debug, text, (size_t)len); +} + +// Android kills every process in a worker's cgroup when the worker's own process ends: a program's +// daemon (wineserver forks it and exits) or a job it left running would die with it. So the program's +// process stays, as if it had exited (no fds but the worker's binder, no signals), until they are gone. +static void ddh_linger(int flush) { + char line[160]; + pid_t self = getpid(); + // Not with other threads, which would go on running the program's code meanwhile. + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return; + char entries[512]; + int threads = 0; + long n = syscall(SYS_getdents64, dir, entries, sizeof(entries)); + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + threads += entries[off + 19] >= '1' && entries[off + 19] <= '9'; + off += reclen ? reclen : n; + } + syscall(SYS_close, dir); + if (threads != 1) { + ddh_linger_note("threads", threads); + return; + } + if (!ddh_cgroup_line(self, NULL, line, sizeof(line))) { + ddh_linger_note("no cgroup line", 0); + return; + } + pid_t member = ddh_find_cgroup_member(line, self); + ddh_linger_note("cgroup member", member); + if (member <= 0) return; + if (flush) fflush(NULL); + sigset_t all; + sigfillset(&all); + sigprocmask(SIG_SETMASK, &all, NULL); + close_range(0, ~0U, 0); + while (member > 0) { + while (syscall(SYS_wait4, -1, NULL, WNOHANG, NULL) > 0) { + } + struct timespec second = {1, 0}; + nanosleep(&second, NULL); + if (!ddh_cgroup_member(member, line)) member = ddh_find_cgroup_member(line, self); + } +} + +// From exit() (on_exit, arg 1) or _exit() (arg NULL) in a worker's own process. +// Only a handed-off child lingers: the app waits for the death of the programs it starts itself +// (the session's root) to tear everything down. +static void ddh_report_exit(int status, void *from_exit) { if (!g_ddh_report || getpid() != g_ddh_worker) return; struct ddh_entry *e = &g_ddh_report->e[g_ddh_report_slot]; e->status = (status & 0xff) << 8; __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); if (g_ddh_report_parent > 0) syscall(SYS_kill, g_ddh_report_parent, SIGCHLD); + ddh_linger(from_exit != NULL); +} + +// A program that leaves with _exit() skips on_exit(): a daemon's first process does, once it has +// forked the daemon (wineserver), and its parent waits for that status. +__attribute__((noreturn)) static void ddh_real_exit(const char *name, int status) { + void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, name); + if (real) real(status); + syscall(SYS_exit_group, status); + __builtin_unreachable(); +} + +void _exit(int status) { + ddh_report_exit(status, NULL); + ddh_real_exit("_exit", status); +} + +void _Exit(int status) { + ddh_report_exit(status, NULL); + ddh_real_exit("_Exit", status); } static void ddh_setup_report(void) { @@ -190,7 +371,7 @@ static void ddh_setup_report(void) { g_ddh_report = t; g_ddh_report_slot = slot; g_ddh_report_parent = parent; - on_exit(ddh_report_exit, NULL); + on_exit(ddh_report_exit, (void *)1); } // In a program a worker started: the state its forked parent had, sent along with the exec. @@ -389,9 +570,27 @@ static const char *ddh_interpreter(const char *path, char *buf, size_t size) { return name; } +static int ddh_program_listed(const char *list, const char *filename, char *const argv[]) { + char shebang[256]; + const char *interp; + // "python3 SCRIPT" and "sh SCRIPT" are matched by the script's name too + const char *script = argv && argv[0] && argv[1] && argv[1][0] != '-' ? ddh_base(argv[1]) : NULL; + return ddh_listed(list, ddh_base(filename), argv) || (argv && ddh_listed(list, ddh_base(argv[0]), argv)) || + (script && ddh_listed(list, script, argv)) || + ((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv)); +} + +// Whether a posix_spawn() of this program should be handed off: glibc's spawn child makes the exec +// system call itself, past ddh_try(), so such a spawn is started with fork() and execve() instead. +static int ddh_spawn_wanted(const char *path, char *const argv[], char *const envp[]) { + const char *list = ddh_env(envp, "DD_HANDOFF"); + return path && ddh_env(envp, "DD_SPAWN") && list && ddh_program_listed(list, path, argv); +} + // In a forked child at execve(): hands the program to a worker and exits, or returns to exec it here. static void ddh_debug(char *const envp[], const char *what, const char *filename) { - if (!ddh_env(envp, "DD_HANDOFF_DEBUG")) return; + const char *debug = ddh_env(envp, "DD_HANDOFF_DEBUG"); + if (!debug) return; char line[512]; struct ddh_buf b = {line, 0, sizeof(line) - 1}; ddh_puts(&b, "ddnatv handoff: "); @@ -402,7 +601,7 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename ddh_puts(&b, filename ? filename : "?"); ddh_puts(&b, "\n"); if (b.len > b.cap) b.len = b.cap; - syscall(SYS_write, 2, line, b.len); + ddh_log(debug, line, b.len); } static void ddh_try(const char *filename, char *const argv[], char *const envp[]) { @@ -430,15 +629,13 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] ddh_debug(envp, "not executable here:", filename); return; } + if (!ddh_is_table(table_fd, table)) { + ddh_debug(envp, "table fd lost:", filename); + return; + } // Whatever this exec becomes can still hand off its own exec (a wrapper, a script). syscall(SYS_fcntl, table_fd, F_SETFD, 0); - char shebang[256]; - const char *interp = NULL; - // "python3 SCRIPT" and "sh SCRIPT" are matched by the script's name too - const char *script = argv && argv[0] && argv[1] && argv[1][0] != '-' ? ddh_base(argv[1]) : NULL; - if (!ddh_listed(list, ddh_base(filename), argv) && !(argv && ddh_listed(list, ddh_base(argv[0]), argv)) && - !(script && ddh_listed(list, script, argv)) && - !((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv))) { + if (!ddh_program_listed(list, filename, argv)) { ddh_debug(envp, "not listed:", filename); return; } @@ -763,7 +960,7 @@ int kill(pid_t pid, int sig) { syscall(SYS_close, fd); } int len = snprintf(line, sizeof(line), "ddnatv handoff: %d (%s) kill(%d, %d)\n", (int)getpid(), comm, (int)pid, sig); - if (len > 0) syscall(SYS_write, 2, line, (size_t)len); + if (len > 0) ddh_log(getenv("DD_HANDOFF_DEBUG"), line, (size_t)len); } return (int)syscall(SYS_kill, pid, sig); } diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index ff2339b9e7..eb41f3e865 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -14,15 +14,31 @@ from tools.tests.test_usr2_preload import runner HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" PARENT = r""" +#define _GNU_SOURCE #include +#include #include #include +#include #include #include +extern char **environ; + int main(int argc, char **argv) { - pid_t pid = fork(); - if (pid == 0) { + pid_t pid; + if (strcmp(argv[1], "spawn") == 0) { + // as Python's subprocess does since 3.13, with its close_fds as a file action + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_addclosefrom_np(&actions, 3); + char *args[] = {"target", argv[2], NULL}; + int err = posix_spawn(&pid, argc > 3 ? argv[3] : "/bin/target", &actions, NULL, args, environ); + printf("spawned\t%d\n", err); + if (err) return 0; + } else if ((pid = fork()) == 0) { + // as Python's subprocess does before exec + if (strcmp(argv[1], "closefds") == 0) syscall(SYS_close_range, 3, ~0U, 0); execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } @@ -128,7 +144,7 @@ class NativeHookHandoffTest(unittest.TestCase): cls.tmp.cleanup() def run_parent(self, *argv, handoff="target"): - name = "dd-handoff-test-%d-%s" % (os.getpid(), self.id().rsplit(".", 1)[-1]) + name = "dd-handoff-test-%d-%s-%s" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff) spawner = FakeSpawner(name, self.prefix or [], self.root) spawner.start() self.addCleanup(spawner.sock.close) @@ -153,6 +169,26 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("7", result.get("exit"), out.stdout) self.assertEqual("-1", result.get("again"), out.stdout) + def test_a_child_that_closed_its_inherited_fds_is_handed_off(self): + result, requests, out = self.run_parent("closefds", "5") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("5", result.get("exit"), out.stdout) + + def test_a_posix_spawn_is_handed_off(self): + result, requests, out = self.run_parent("spawn", "6") + self.assertEqual("0", result.get("spawned"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual(["target", "6"], requests[0]["argv"]) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("6", result.get("exit"), out.stdout) + + def test_a_posix_spawn_of_a_missing_program_fails_as_it_would(self): + listed, requests, out = self.run_parent("spawn", "6", "/bin/missing") + unlisted, _, _ = self.run_parent("spawn", "6", "/bin/missing", handoff="other") + self.assertEqual([], requests) + self.assertEqual((unlisted.get("spawned"), unlisted.get("exit")), (listed.get("spawned"), listed.get("exit")), out.stdout) + def test_kill_reaches_the_program_and_its_signal_is_reported(self): result, requests, out = self.run_parent("kill", "sleep") self.assertEqual(1, len(requests), out.stderr)