fix(handoff): controlling-terminal check via /dev/tty, owned records only

This commit is contained in:
Kurt Himebauch committed 2026-11-28 05:13:51 -05:00
1 parent 3e0e13468e
commit a77abf3293
3 files changed
+69 -38

No files matched your search

+5 -5
View File
@@ -249,11 +249,11 @@ 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 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
their children stay. A job in the foreground of its controlling terminal (`TIOCGPGRP` on
`/dev/tty`, whatever its standard fds are: `cmd | less`, `less < file`) stays too: 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, in the
foreground group reading `/dev/null`, and goes. 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
+38 -30
View File
@@ -119,25 +119,32 @@ static struct ddh_fork {
static struct ddh_entry *ddh_find(pid_t child);
static void ddh_forked_by(pid_t child, pid_t thread) {
struct ddh_fork *free_one = NULL;
for (int i = 0; i < DDH_FORKS; i++) {
pid_t seen = __atomic_load_n(&g_ddh_forks[i].child, __ATOMIC_ACQUIRE);
if (seen == child) {
if (__atomic_load_n(&g_ddh_forks[i].child, __ATOMIC_ACQUIRE) == child) {
__atomic_store_n(&g_ddh_forks[i].thread, thread, __ATOMIC_RELEASE);
return;
}
if (seen == 0 && !free_one) free_one = &g_ddh_forks[i];
}
for (int i = 0; !free_one && i < DDH_FORKS; i++) {
// all in use: one whose child is gone and has no entry
pid_t seen = __atomic_load_n(&g_ddh_forks[i].child, __ATOMIC_ACQUIRE);
int saved = errno;
if (seen > 0 && syscall(SYS_kill, seen, 0) != 0 && errno == ESRCH && !ddh_find(seen)) free_one = &g_ddh_forks[i];
errno = saved;
// A record is taken by compare-and-swap of its child (another thread may be recording a fork of
// its own), then given the thread: until then it names no thread, which no __WNOTHREAD wait takes.
for (int pass = 0; pass < 2; pass++) {
for (int i = 0; i < DDH_FORKS; i++) {
struct ddh_fork *f = &g_ddh_forks[i];
pid_t seen = __atomic_load_n(&f->child, __ATOMIC_ACQUIRE);
if (pass == 0 ? seen != 0 : seen <= 0) continue;
if (pass == 1) {
// all in use: one whose child is gone and has no entry
int saved = errno;
int stale = syscall(SYS_kill, seen, 0) != 0 && errno == ESRCH && !ddh_find(seen);
errno = saved;
if (!stale) continue;
}
__atomic_store_n(&f->thread, 0, __ATOMIC_RELEASE);
if (!__atomic_compare_exchange_n(&f->child, &seen, child, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) continue;
__atomic_store_n(&f->thread, thread, __ATOMIC_RELEASE);
return;
}
}
if (!free_one) return;
__atomic_store_n(&free_one->thread, thread, __ATOMIC_RELEASE);
__atomic_store_n(&free_one->child, child, __ATOMIC_RELEASE);
}
static pid_t ddh_forking_thread(pid_t child) {
@@ -929,22 +936,20 @@ 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;
// 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;
}
// 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.
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);
int foreground = tty >= 0 && syscall(SYS_ioctl, tty, TIOCGPGRP, &fg) == 0 && fg == (pid_t)syscall(SYS_getpgid, 0);
if (tty >= 0) syscall(SYS_close, tty);
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))
if (call_orig_syscall(SYS_fstat, 0, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISCHR(st.st_mode) ||
st.st_rdev != makedev(1, 3))
return 0;
}
return ddh_counted() >= ddh_pressure(envp);
@@ -1252,8 +1257,8 @@ static void ddh_untake(struct ddh_entry *e) { __atomic_store_n(&e->state, DDH_EX
// Whether a wait for pid (-1: any child, 0: one in our group, -G: one in group G) takes e's child.
static int ddh_selects(const struct ddh_entry *e, pid_t pid) {
if (t_ddh_only_thread) {
pid_t thread = ddh_forking_thread(e->child);
if (thread && thread != t_ddh_only_thread) return 0;
// not this thread's, or not known yet (the fork is still being recorded): not for this wait
if (ddh_forking_thread(e->child) != t_ddh_only_thread) return 0;
}
if (pid > 0) return e->child == pid;
if (pid == -1) return 1;
@@ -1705,8 +1710,11 @@ static int ddh_parent_lives(pid_t parent, long child_start) {
snprintf(path, sizeof(path), "/proc/%d/stat", (int)parent);
int saved = errno;
long n = ddh_read_proc(path, stat, sizeof(stat));
int failed = errno;
errno = saved;
char *s = n > 0 ? strrchr(stat, ')') : NULL;
// only a parent known gone: a lookup that failed otherwise (out of fds, say) proves nothing
if (n <= 0) return !(failed == ENOENT || failed == ESRCH);
char *s = strrchr(stat, ')');
if (!s || s[1] != ' ' || s[2] == 'Z' || s[2] == 'X') return 0;
for (int field = 2; s && field < 22; field++) s = strchr(s + 1, ' ');
long start = s ? atol(s + 1) : -1;
+26 -3
View File
@@ -382,23 +382,34 @@ class NativeHookHandoffTest(unittest.TestCase):
cmd = []
env.update(hook_env)
stdin, stderr, ctty = None, subprocess.PIPE, None
passed = ()
if terminal:
# 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")
# (terminal=True); as stderr with stdin a pipe, /dev/null or a file ("pipe", "null",
# "file"); or on no standard fd at all, stdin a pipe ("hidden")
master, slave = os.openpty()
self.addCleanup(os.close, master)
self.addCleanup(os.close, slave)
if terminal is True:
stdin, fd = slave, 0
elif terminal == "hidden":
stdin, fd, passed = subprocess.PIPE, slave, (slave,)
else:
stdin, stderr, fd = (subprocess.PIPE if terminal == "pipe" else subprocess.DEVNULL), slave, 2
if terminal == "file":
data = Path(self.tmp.name) / "input.txt"
data.write_text("input\n")
stdin = open(data)
self.addCleanup(stdin.close)
else:
stdin = subprocess.PIPE if terminal == "pipe" else subprocess.DEVNULL
stderr, fd = slave, 2
def ctty():
os.setsid()
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)
pass_fds=passed, 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
@@ -528,6 +539,18 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual([], requests)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_near_the_limit_a_foreground_job_reading_a_file_is_not(self):
# "less < file"
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="file")
self.assertEqual([], requests)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_near_the_limit_a_foreground_job_with_no_terminal_fd_is_not(self):
# "cmd | less > out 2> err": the controlling terminal on none of its standard fds
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="hidden")
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")