fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports

This commit is contained in:
Kurt Himebauch committed 2026-11-28 03:11:47 -05:00
1 parent 12a15a5526
commit 25d97a414b
4 files changed
+166 -51

No files matched your search

@@ -626,22 +626,6 @@ object GuestWorkers {
client.soTimeout = ms.toInt()
}
val input = DataInputStream(client.inputStream)
fun fill(bytes: ByteArray) {
var got = 0
while (got < bytes.size) {
left()
val n = input.read(bytes, got, bytes.size - got)
if (n < 0) throw java.io.EOFException("spawn request ended at $got of ${bytes.size} bytes")
got += n
}
}
val length = ByteArray(4).also { fill(it) }.let { java.nio.ByteBuffer.wrap(it).int }
if (length !in 1..MAX_REQUEST_BYTES) {
Log.w(TAG, "spawn request of $length bytes refused")
return
}
val payload = ByteArray(length).also { fill(it) }
val request = JSONObject(String(payload))
val fds = ArrayList<ParcelFileDescriptor>()
fun take() {
val received = client.ancillaryFileDescriptors.orEmpty()
@@ -651,9 +635,27 @@ object GuestWorkers {
received.forEach { runCatching { Os.close(it) } }
}
}
// Until start() has them: closed on every way out before that, from the first chunk on
// fds can come with any read, the request's own bytes too: each read's are taken at once
fun fill(bytes: ByteArray) {
var got = 0
while (got < bytes.size) {
left()
val n = input.read(bytes, got, bytes.size - got)
take()
if (n < 0) throw java.io.EOFException("spawn request ended at $got of ${bytes.size} bytes")
got += n
}
}
// Until start() has them: closed on every way out before that, from the first byte on
var handedOver = false
try {
val length = ByteArray(4).also { fill(it) }.let { java.nio.ByteBuffer.wrap(it).int }
if (length !in 1..MAX_REQUEST_BYTES) {
Log.w(TAG, "spawn request of $length bytes refused")
return
}
val payload = ByteArray(length).also { fill(it) }
val request = JSONObject(String(payload))
if (request.has("fdchunks")) {
// The hook sends its fds after the request, a chunk with each byte (hook/handoff.c)
val total = (request.optJSONArray("fds")?.length() ?: 0) + (if (request.has("table")) 1 else 0)
@@ -795,7 +797,9 @@ object GuestWorkers {
Os.pread(table.fileDescriptor, head, entry)
val real = head.getInt(4)
val state = head.getInt(12)
if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || (state != 1 && state != 3))
// Also while the hook holds the entry (TAKEN) or has already guessed its end (EXITED):
// the report is for this child only, and wins over the timeout's guess (ddh_status)
if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || state !in 1..4)
return@runCatching
// An exit Android has no record of is reported as a failure, not as a signal.
val report = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.nativeOrder())
+7 -3
View File
@@ -249,9 +249,13 @@ vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
a child of `bash`, `sh`, `dash`, `zsh`, `ksh`, `fish`, `make` or `xargs` is handed off even when
it is not listed. Those parents wait with `wait()`, which the hook answers; Qt's `QProcess` and
other parents that watch a child by pidfd or `/proc` would see the forked child end at once, so
their children stay. A job in the foreground of the terminal it reads (`TIOCGPGRP` on stdin) stays
too: a handed-off program has no controlling terminal, so `/dev/tty`, ^C and job control would
miss it. A job started with `&` reads `/dev/null` or runs in a background group. In the desktop
their children stay. A job in the foreground of its terminal (`TIOCGPGRP` on whichever standard fd
is the controlling terminal) stays too when it reads the terminal, a pipe or a socket (`less` in
`cmd | less` opens `/dev/tty`): a handed-off program has no controlling terminal, so `/dev/tty`,
^C and job control would miss it. A job started with `&` runs in a background group, or, from a
shell without job control, reads `/dev/null`. Steam's client and launch chain (`steam`, its
web helper, `droiddeck-steam-x64`, `reaper`, `steam-launch-wrapper`, `pw-audio-namespace`,
gamescope, anything under `Steam/`) never go this way. In the desktop
session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at
61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and
at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a
+62 -19
View File
@@ -417,10 +417,11 @@ static void ddh_report_exit(int status, void *from_exit) {
// From the state read (the forked child may still move it from CLAIMED to HANDED): a parent
// that freed the entry meanwhile keeps it freed.
int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE);
for (int waits = 0;;) {
// TAKEN for a moment: the parent's check of a gone worker holds the entry (ddh_check_gone()) and
// gives it back as it was when it is not the child it looked at. Wait that out, briefly.
if (st == DDH_TAKEN && waits++ < 200) {
for (;;) {
// TAKEN: the parent's check of a gone worker holds the entry (ddh_check_gone()) and gives it
// back as it was when it is not the child it looked at. Wait that out, however long the parent
// takes, while there is a parent to give it back.
if (st == DDH_TAKEN && (syscall(SYS_kill, e->parent, 0) == 0 || errno != ESRCH)) {
struct timespec ts = {0, 1000 * 1000};
syscall(SYS_nanosleep, &ts, NULL);
st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE);
@@ -776,6 +777,7 @@ static int ddh_exec_stub(const char *path) {
static int ddh_waiter(pid_t pid);
static int ddh_counted(void);
static int ddh_pressure_keeps(const char *filename, char *const argv[]);
// DD_HANDOFF_PRESSURE sets another count (tests)
static int ddh_pressure(char *const envp[]) {
@@ -788,7 +790,7 @@ static int ddh_spawn_wanted(const char *path, char *const argv[], char *const en
const char *list = ddh_env(envp, "DD_HANDOFF");
if (!ddh_env(envp, "DD_SPAWN") || !list) return 0;
// as ddh_pressed() would in the child (GNU make spawns its recipes' shells)
return ddh_program_listed(list, path, argv) || (ddh_waiter(getpid()) && ddh_counted() >= ddh_pressure(envp));
return ddh_program_listed(list, path, argv) || (!ddh_pressure_keeps(path, argv) && ddh_waiter(getpid()) && ddh_counted() >= ddh_pressure(envp));
}
static long ddh_read_proc(const char *path, char *buf, size_t size) {
@@ -849,14 +851,43 @@ static int ddh_waiter(pid_t pid) {
return 0;
}
static int ddh_pressed(const char *filename, char *const envp[]) {
if (ddh_exec_stub(filename) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0;
// Not one that reads the terminal it is in the foreground of: a handed-off program has no
// controlling terminal (the worker's setsid()), so /dev/tty, ^C and job control would miss it.
// A job started with & reads /dev/null, or runs in a background group.
// (TIOCGPGRP answers only for the caller's controlling terminal)
pid_t fg = 0;
if (syscall(SYS_ioctl, 0, TIOCGPGRP, &fg) == 0 && fg == (pid_t)syscall(SYS_getpgid, 0)) return 0;
// Never handed off for want of room: the Steam client and its launch chain, which the client tracks
// as its own processes (see the docs' "Not handed off" and "Tried and dropped"), however started (the
// arm64 client directly or through env, the x86-64 one through droiddeck-steam-x64).
static int ddh_pressure_keeps(const char *filename, char *const argv[]) {
static const char *const kept[] = {"steam", "steam.sh", "steamwebhelper", "droiddeck-steam-x64", "reaper",
"steam-launch-wrapper", "pw-audio-namespace", "gamescope", "gamescopereaper"};
for (int i = -1; i < 32 && (i < 0 || (argv && argv[i])); i++) {
const char *s = i < 0 ? filename : argv[i];
if (!s) continue;
if (strstr(s, "/Steam/") || strstr(s, "/.steam/")) return 1;
for (size_t k = 0; k < sizeof(kept) / sizeof(kept[0]); k++) {
if (strcmp(ddh_base(s), kept[k]) == 0) return 1;
}
}
return 0;
}
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;
// Not a job in the foreground of its terminal that reads it, or a pipe (less in "cmd | less"
// opens /dev/tty): a handed-off program has no controlling terminal (the worker's setsid()), so
// /dev/tty, ^C and job control would miss it. A job started with & runs in a background group,
// or, from a shell without job control, reads /dev/null. TIOCGPGRP answers only for the caller's
// controlling terminal, on whichever of its standard fds that is.
pid_t group = (pid_t)syscall(SYS_getpgid, 0);
int foreground = 0;
for (int fd = 0; fd <= 2 && !foreground; fd++) {
pid_t fg = 0;
foreground = syscall(SYS_ioctl, fd, TIOCGPGRP, &fg) == 0 && fg == group;
}
if (foreground) {
struct stat st;
unsigned char t[64]; // the kernel's struct termios, which TCGETS fills, is smaller
if (syscall(SYS_ioctl, 0, TCGETS, t) == 0 || call_orig_syscall(SYS_fstat, 0, (unsigned long)&st, 0, 0, 0, 0) != 0 ||
S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
return 0;
}
return ddh_counted() >= ddh_pressure(envp);
}
@@ -911,7 +942,7 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[]
}
// Whatever this exec becomes can still hand off its own exec (a wrapper, a script).
syscall(SYS_fcntl, table_fd, F_SETFD, 0);
if (!ddh_program_listed(list, filename, argv) && !ddh_pressed(filename, envp)) {
if (!ddh_program_listed(list, filename, argv) && !ddh_pressed(filename, argv, envp)) {
ddh_debug(envp, "not listed:", filename);
return;
}
@@ -1436,9 +1467,12 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) {
errno = ENOSYS;
return -1;
}
// A wait without exits never takes a forked child's exit for the program's.
// A wait without exits never takes a forked child's exit for the program's. Other option bits
// (invalid ones too, which the kernel refuses) and group 1 (init's, which a waitpid() selector of
// -1 would take for any child): the real call.
if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !(options & WEXITED) ||
(idtype != P_PID && idtype != P_ALL && idtype != P_PGID))
(options & ~(WEXITED | WSTOPPED | WCONTINUED | WNOHANG | WNOWAIT)) ||
(idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || (idtype == P_PGID && id == 1))
return real(idtype, id, info, options);
if ((idtype == P_PID && (pid_t)id <= 0) || (idtype == P_PGID && (pid_t)id < 0)) {
errno = EINVAL;
@@ -1460,7 +1494,7 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) {
memset(info, 0, sizeof(*info));
info->si_signo = SIGCHLD;
info->si_pid = r;
info->si_uid = getuid();
info->si_uid = (uid_t)call_orig_syscall(SYS_getuid, 0, 0, 0, 0, 0, 0); // the real one, as the kernel reports, not the root the hook shows
if (WIFEXITED(status)) {
info->si_code = CLD_EXITED;
info->si_status = WEXITSTATUS(status);
@@ -1475,7 +1509,13 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) {
siginfo_t seen;
memset(&seen, 0, sizeof(seen));
if (real(idtype, id, &seen, options | WNOWAIT | (live ? WNOHANG : 0)) < 0) {
if (!live || errno != ECHILD) return -1;
if (errno != ECHILD) return -1;
// a handoff may have claimed its entry since the look above, and another waiter reaped
// its forked child: the program still runs
if (!live && !(live = ddh_any_live(which))) {
errno = ECHILD;
return -1;
}
} else if (seen.si_pid > 0) {
pid_t child = seen.si_pid;
int exited = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED;
@@ -1488,9 +1528,12 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) {
if (info) *info = seen;
return 0;
}
// Only the kind of event looked at: a stop's child may have gone on since, handed its
// program off and exited, and that exit is the forked child's, not one to report.
int kind = exited ? WEXITED : seen.si_code == CLD_CONTINUED ? WCONTINUED : WSTOPPED;
siginfo_t got;
memset(&got, 0, sizeof(got));
if (real(P_PID, (id_t)child, &got, options | WNOHANG) < 0 || got.si_pid != child) continue; // another waiter took it
if (real(P_PID, (id_t)child, &got, kind | WNOHANG) < 0 || got.si_pid != child) continue; // another waiter took it
// A forked child that died while handing its program off (a signal): its entry is done.
int died = got.si_code == CLD_EXITED || got.si_code == CLD_KILLED || got.si_code == CLD_DUMPED;
if (died && !ddh_find(child) && (h = ddh_claiming(child))) ddh_release(h, NULL);
+75 -11
View File
@@ -52,8 +52,17 @@ PARENT = r"""
extern char **environ;
static int gate[2] = {-1, -1};
static void open_gate(int sig) {
(void)sig;
if (write(gate[1], "1", 1) != 1) _exit(125);
}
int main(int argc, char **argv) {
pid_t pid;
// 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) {
// as Python's subprocess does since 3.13, with its close_fds as a file action
posix_spawn_file_actions_t actions;
@@ -72,10 +81,31 @@ int main(int argc, char **argv) {
fflush(stdout);
}
if (strcmp(argv[1], "group") == 0) setpgid(0, 0);
execl("/bin/target", "target", argv[2], (char *)NULL);
if (gate[0] >= 0) {
char c;
close(gate[1]);
if (read(gate[0], &c, 1) != 1) _exit(126);
}
execl(argc > 3 ? argv[3] : "/bin/target", "target", argv[2], (char *)NULL);
_exit(127);
}
int status = 0;
if (strcmp(argv[1], "waitidpid") == 0) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = open_gate;
sa.sa_flags = SA_RESTART;
sigaction(SIGALRM, &sa, NULL);
alarm(1);
siginfo_t si;
memset(&si, 0, sizeof(si));
int r = waitid(P_PID, pid, &si, WEXITED);
printf("same\t%d\n", r == 0 && si.si_pid == pid);
printf("code\t%d\n", si.si_code);
printf("exit\t%d\n", si.si_status);
printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG));
return 0;
}
if (strcmp(argv[1], "waitid") == 0) {
// at once, before the child has claimed its handoff, and for stops too
siginfo_t si;
@@ -86,7 +116,7 @@ int main(int argc, char **argv) {
printf("same\t%d\n", r == 0 && si.si_pid == pid);
printf("code\t%d\n", si.si_code);
printf("exit\t%d\n", si.si_status);
printf("uid\t%d\n", si.si_uid == getuid());
printf("uid\t%d\n", (int)si.si_uid);
printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG));
return 0;
}
@@ -271,18 +301,24 @@ class NativeHookHandoffTest(unittest.TestCase):
else:
cmd = []
env.update(hook_env)
stdin, ctty = None, None
stdin, stderr, ctty = None, subprocess.PIPE, None
if terminal:
# as a shell's foreground job: a terminal as stdin, controlling terminal of the parent's session
master, stdin = os.openpty()
# as a shell's foreground job: the controlling terminal of the parent's session as stdin
# (terminal=True), or as stderr with stdin a pipe or /dev/null (terminal="pipe", "null")
master, slave = os.openpty()
self.addCleanup(os.close, master)
self.addCleanup(os.close, stdin)
self.addCleanup(os.close, slave)
if terminal is True:
stdin, fd = slave, 0
else:
stdin, stderr, fd = (subprocess.PIPE if terminal == "pipe" else subprocess.DEVNULL), slave, 2
def ctty():
os.setsid()
fcntl.ioctl(0, termios.TIOCSCTTY, 0)
out = subprocess.run(cmd + [parent, *argv], env=env, stdin=stdin, preexec_fn=ctty, capture_output=True,
text=True, timeout=120)
fcntl.ioctl(fd, termios.TIOCSCTTY, 0)
given = {"input": ""} if stdin == subprocess.PIPE else {"stdin": stdin}
out = subprocess.run(cmd + [parent, *argv], env=env, stdout=subprocess.PIPE, stderr=stderr, preexec_fn=ctty,
text=True, timeout=120, **given)
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
return result, spawner.requests, out
@@ -371,7 +407,7 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual(str(CLD_EXITED), result.get("code"), out.stdout)
self.assertEqual("7", result.get("exit"), out.stdout)
self.assertEqual("1", result.get("uid"), out.stdout)
self.assertEqual(str(os.getuid()), result.get("uid"), out.stdout)
self.assertEqual("-1", result.get("again"), out.stdout)
def test_waitid_for_a_child_not_listed_is_the_kernels(self):
@@ -380,7 +416,7 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual(str(CLD_EXITED), result.get("code"), out.stdout)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
self.assertEqual("1", result.get("uid"), out.stdout)
self.assertEqual(str(os.getuid()), result.get("uid"), out.stdout)
def test_near_the_limit_a_shells_child_is_handed_off(self):
result, requests, out = self.run_parent("wait", "7", handoff="other", pressure=0, as_shell=True)
@@ -398,6 +434,34 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual([], requests)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_near_the_limit_a_foreground_pipe_reader_is_not(self):
# less in "cmd | less": stdin a pipe, the terminal on another fd
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="pipe")
self.assertEqual([], requests)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_near_the_limit_a_job_reading_dev_null_is_handed_off(self):
# "cmd &" from a shell without job control: the foreground group, stdin /dev/null
result, requests, out = self.run_parent("wait", "7", handoff="other", pressure=0, as_shell=True, terminal="null")
self.assertEqual(1, len(requests), out.stdout)
self.assertEqual("7", result.get("exit"), out.stdout)
def test_near_the_limit_the_steam_client_is_not(self):
steam = self.root / "bin/steam"
if not steam.exists():
shutil.copy(self.root / "bin/target", steam)
result, requests, out = self.run_parent("wait", "3", "/bin/steam", handoff="other", pressure=0, as_shell=True)
self.assertEqual([], requests)
self.assertEqual(self.child_status, 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)
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual(str(CLD_EXITED), result.get("code"), out.stdout)
self.assertEqual("7", result.get("exit"), out.stdout)
self.assertEqual("-1", result.get("again"), out.stdout)
def test_near_the_limit_a_terminals_foreground_job_is_not(self):
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal=True)
self.assertEqual([], requests)