mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
fix(nativeguest): reap the zombies session processes adopt as subreapers and never wait for (#3610)
This commit is contained in:
1 parent
4ab9635ceb
commit
20df8b1858
7 files changed
+464
-2
No files matched your search
@@ -531,6 +531,35 @@ the old behavior and the old requirement.
|
||||
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
|
||||
broker and keeps the GPU outside.
|
||||
|
||||
## Zombies
|
||||
|
||||
Every session process is a child subreaper (`tools/linuxfs/preload/subreaper.c`, so that a
|
||||
double-forked Xwayland is not left to init, which some vendor kernels kill), and most programs
|
||||
never wait for a child they did not fork. What they adopted stayed a zombie: the grandchildren of
|
||||
Qt's `startDetached()` under Plasma's shell, KWin and kaccess, Wine's double-forked processes,
|
||||
wlroots' Xwayland under gamescope. A parent that never waits at all (Plasma's shell, for what it
|
||||
launches) also kept the forked child of each program it handed off. On the Thor, main had 4
|
||||
zombies in Steam mode at rest and 19 in Bully, and the desktop gained one per app closed.
|
||||
|
||||
The hook now reaps them from SIGCHLD (`ddh_reap_unclaimed()`):
|
||||
|
||||
- **Adopted:** each process records, at its pid, the parent that started it and its own start
|
||||
time, in one file for the session (`DD_PARENTS`). A fork's child does it at the fork, any other
|
||||
program at its start. A zombie child whose record names another parent was adopted. An own child
|
||||
(recorded with this parent, or with no record, such as a static program a `vfork()` started) is
|
||||
left for its program's wait.
|
||||
- **A handed-off program's forked child,** as a wait's look reaps it: the program's exit stays in
|
||||
the table for the parent's wait.
|
||||
|
||||
The program's SIGCHLD action runs first, and `sigaction()` shows it as the program set it.
|
||||
`SIG_IGN` and `SA_NOCLDWAIT` stay the kernel's. A program that leaves SIGCHLD alone gets the
|
||||
handler only when `DD_REAP_ADOPTED` names it (Plasma's programs, D-Bus, gamescope, Wine's
|
||||
launchers, Decky's loader): with a handler, `poll()`, `sleep()` and the like return `EINTR` when a
|
||||
child exits. With these changes there are no zombies left in either mode, Bully included.
|
||||
|
||||
qemu-user has no `PR_SET_CHILD_SUBREAPER`, so the adoption tests skip under it (CI) and were run on
|
||||
the Thor's kernel.
|
||||
|
||||
## Robustness
|
||||
|
||||
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
|
||||
|
||||
@@ -87,6 +87,11 @@ static const char *rewrite_path(const char *path, char *out, size_t size) {
|
||||
return path;
|
||||
}
|
||||
|
||||
// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their
|
||||
// first parent for the session's subreapers, and reap nothing themselves.
|
||||
static void ddnatv_manage_sigchld(void) {}
|
||||
static void ddh_reap_unclaimed(void) __attribute__((unused));
|
||||
|
||||
#include "../nativeguest/hook/kept.c"
|
||||
#include "../nativeguest/hook/handoff.c"
|
||||
|
||||
@@ -315,12 +320,14 @@ pid_t fork(void) {
|
||||
}
|
||||
ddh_prepare();
|
||||
pid_t forker = (pid_t)syscall(SYS_gettid);
|
||||
pid_t forking = (pid_t)syscall(SYS_getpid);
|
||||
pid_t pid = orig_fork();
|
||||
if (pid == 0) {
|
||||
kept_forked();
|
||||
kept_close_forked();
|
||||
ddh_drop_worker_binder();
|
||||
ddh_forked(forker);
|
||||
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
|
||||
} else if (pid > 0) {
|
||||
ddh_child_created(pid, 1);
|
||||
}
|
||||
|
||||
@@ -66,8 +66,13 @@ if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
|
||||
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker}
|
||||
# The programs these start for the user (an app from the panel, a file opened in Dolphin)
|
||||
export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin}
|
||||
# Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and
|
||||
# the programs that reap them even while they leave SIGCHLD alone (hook/signals.c)
|
||||
rm -f /run/droiddeck-parents.* 2>/dev/null
|
||||
export DD_PARENTS=/run/droiddeck-parents.$$
|
||||
export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real}
|
||||
else
|
||||
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS
|
||||
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED
|
||||
fi
|
||||
steam_setup_failed() {
|
||||
echo "== steam: the Steam client could not be set up (status $1)"
|
||||
|
||||
@@ -661,12 +661,14 @@ pid_t fork(void) {
|
||||
}
|
||||
ddh_prepare();
|
||||
pid_t forker = (pid_t)syscall(SYS_gettid);
|
||||
pid_t forking = (pid_t)syscall(SYS_getpid);
|
||||
pid_t pid = orig_fork();
|
||||
if (pid == 0) {
|
||||
kept_forked();
|
||||
kept_close_forked();
|
||||
ddh_drop_worker_binder();
|
||||
ddh_forked(forker);
|
||||
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
|
||||
} else if (pid > 0) {
|
||||
ddh_child_created(pid, 1);
|
||||
}
|
||||
|
||||
@@ -878,6 +878,9 @@ static void ddh_apply_inherited(void) {
|
||||
}
|
||||
}
|
||||
|
||||
static void ddh_open_parents(void);
|
||||
static void ddh_record_own_parent(void);
|
||||
|
||||
__attribute__((constructor)) static void ddh_init(void) {
|
||||
ddh_apply_inherited();
|
||||
ddh_find_worker_binder();
|
||||
@@ -885,6 +888,9 @@ __attribute__((constructor)) static void ddh_init(void) {
|
||||
ddh_find_parent_table();
|
||||
// tests only: as when the table could not be made here, and the first fork makes it
|
||||
if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare();
|
||||
ddh_open_parents();
|
||||
ddh_record_own_parent();
|
||||
ddnatv_manage_sigchld();
|
||||
}
|
||||
|
||||
static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) {
|
||||
@@ -1326,7 +1332,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename
|
||||
struct ddh_buf b = {line, 0, sizeof(line) - 1};
|
||||
ddh_puts(&b, "ddnatv handoff: ");
|
||||
ddh_putint(&b, getpid());
|
||||
ddh_puts(&b, " ");
|
||||
ddh_puts(&b, " (parent ");
|
||||
ddh_putint(&b, (long)syscall(SYS_getppid));
|
||||
ddh_puts(&b, ", session ");
|
||||
ddh_putint(&b, (long)syscall(SYS_getsid, 0));
|
||||
ddh_puts(&b, ") ");
|
||||
ddh_puts(&b, what);
|
||||
ddh_puts(&b, " ");
|
||||
ddh_puts(&b, filename ? filename : "?");
|
||||
@@ -1669,6 +1679,158 @@ static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) {
|
||||
return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0;
|
||||
}
|
||||
|
||||
// ---- children no wait will come for ------------------------------------------------------------
|
||||
//
|
||||
// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose
|
||||
// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels
|
||||
// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the
|
||||
// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records
|
||||
// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the
|
||||
// session): a zombie whose record names another parent was adopted.
|
||||
static uint64_t *g_ddh_parents;
|
||||
|
||||
static void ddh_open_parents(void) {
|
||||
const char *name = getenv("DD_PARENTS");
|
||||
if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return;
|
||||
char path[PATH_MAX];
|
||||
const char *real = rewrite_path(name, path, sizeof(path));
|
||||
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
|
||||
O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0);
|
||||
if (fd < 0) return;
|
||||
size_t size = (size_t)DDH_FORKS * sizeof(uint64_t);
|
||||
struct stat st;
|
||||
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size)
|
||||
call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0);
|
||||
// past the file's end a page would fault (SIGBUS): mapped only once the file has its size
|
||||
void *map = MAP_FAILED;
|
||||
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size)
|
||||
map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
syscall(SYS_close, fd);
|
||||
if (map == MAP_FAILED) return;
|
||||
uint64_t *none = NULL;
|
||||
if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))
|
||||
munmap(map, size);
|
||||
}
|
||||
|
||||
static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; }
|
||||
|
||||
static void ddh_record_parent(pid_t me, pid_t parent) {
|
||||
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
|
||||
if (!map || me <= 0) return;
|
||||
int saved = errno;
|
||||
long start = ddh_start_time(me);
|
||||
errno = saved;
|
||||
if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own
|
||||
// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is
|
||||
// still the one that started it (a vfork()'s waits for the exec).
|
||||
static void ddh_record_own_parent(void) {
|
||||
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
|
||||
if (!map) return;
|
||||
pid_t me = (pid_t)syscall(SYS_getpid);
|
||||
int saved = errno;
|
||||
long start = ddh_start_time(me);
|
||||
errno = saved;
|
||||
if (start <= 0) return;
|
||||
uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE);
|
||||
if ((uint32_t)r == (uint32_t)start && r >> 32) return;
|
||||
__atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read.
|
||||
static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) {
|
||||
char path[48] = "/proc/", digits[16], stat[512];
|
||||
int n = 0, len = 6;
|
||||
for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10);
|
||||
while (n) path[len++] = digits[--n];
|
||||
memcpy(path + len, "/stat", 6);
|
||||
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
|
||||
if (fd < 0) return 0;
|
||||
long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0);
|
||||
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
|
||||
if (got <= 0) return 0;
|
||||
stat[got] = 0;
|
||||
char *p = strrchr(stat, ')');
|
||||
if (!p || p[1] != ' ' || !p[2]) return 0;
|
||||
*state = p[2];
|
||||
// ") S PPID": field 4; starttime is field 22
|
||||
long parent = 0;
|
||||
for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0');
|
||||
*ppid = (pid_t)parent;
|
||||
for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' ');
|
||||
long t = 0;
|
||||
for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0');
|
||||
*start = t;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's
|
||||
// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this
|
||||
// process adopted. 1 when it did.
|
||||
static int ddh_reap_unwaited(pid_t me, pid_t child) {
|
||||
char state = 0;
|
||||
long start = 0;
|
||||
pid_t ppid = 0;
|
||||
if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0;
|
||||
struct ddh_entry *e = ddh_find(child);
|
||||
int32_t gen = e ? ddh_gen_of(e, child) : 0;
|
||||
if (gen) {
|
||||
if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0;
|
||||
ddh_mark_reaped(e, gen);
|
||||
return 1;
|
||||
}
|
||||
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
|
||||
uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0;
|
||||
if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0;
|
||||
return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child;
|
||||
}
|
||||
|
||||
// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will
|
||||
// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc.
|
||||
static void ddh_reap_unclaimed(void) {
|
||||
if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return;
|
||||
int saved = errno;
|
||||
pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0);
|
||||
// past 64 reaped this way, the rest from /proc too
|
||||
int scan = 1;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
siginfo_t si;
|
||||
memset(&si, 0, sizeof(si));
|
||||
if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) {
|
||||
scan = 0;
|
||||
break;
|
||||
}
|
||||
if (!ddh_reap_unwaited(me, si.si_pid)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc",
|
||||
O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1;
|
||||
char buf[2048];
|
||||
while (dir >= 0) {
|
||||
long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0);
|
||||
if (n <= 0) break;
|
||||
for (long off = 0; off < n;) {
|
||||
struct ddh_reap_dirent {
|
||||
uint64_t ino;
|
||||
int64_t off;
|
||||
unsigned short reclen;
|
||||
unsigned char type;
|
||||
char name[];
|
||||
} *d = (struct ddh_reap_dirent *)(buf + off);
|
||||
off += d->reclen;
|
||||
long pid = 0;
|
||||
const char *c = d->name;
|
||||
for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0');
|
||||
if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid);
|
||||
}
|
||||
}
|
||||
if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0);
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it.
|
||||
static int ddh_take(struct ddh_entry *e) {
|
||||
int expected = DDH_EXITED;
|
||||
|
||||
@@ -174,10 +174,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) {
|
||||
real_sig(SIGSYS, &sa, NULL);
|
||||
}
|
||||
|
||||
// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it
|
||||
// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for
|
||||
// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD
|
||||
// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the
|
||||
// like return EINTR when a child exits, which a program that never had one may not expect.
|
||||
static struct sigaction g_app_sigchld;
|
||||
static int g_sigchld_managed;
|
||||
static int g_sigchld_on_default;
|
||||
|
||||
static void ddh_reap_unclaimed(void);
|
||||
static int ddh_listed(const char *list, const char *name, char *const argv[]);
|
||||
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *));
|
||||
|
||||
static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) {
|
||||
struct sigaction app = g_app_sigchld;
|
||||
if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) {
|
||||
if (app.sa_flags & SA_RESETHAND) {
|
||||
// as the kernel would: the default from now on, with the handler only for a named program
|
||||
g_app_sigchld.sa_handler = SIG_DFL;
|
||||
g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND);
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
int saved = errno;
|
||||
if (real_sig) ddnatv_apply_sigchld(real_sig);
|
||||
errno = saved;
|
||||
}
|
||||
if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx);
|
||||
else app.sa_handler(sig);
|
||||
}
|
||||
ddh_reap_unclaimed();
|
||||
}
|
||||
|
||||
// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN,
|
||||
// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above.
|
||||
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) {
|
||||
const struct sigaction *app = &g_app_sigchld;
|
||||
int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN;
|
||||
if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default))
|
||||
return real_sig(SIGCHLD, app, NULL);
|
||||
struct sigaction k;
|
||||
memset(&k, 0, sizeof(k));
|
||||
k.sa_sigaction = ddnatv_sigchld_handler;
|
||||
k.sa_mask = app->sa_mask;
|
||||
k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP));
|
||||
return real_sig(SIGCHLD, &k, NULL);
|
||||
}
|
||||
|
||||
static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *),
|
||||
const struct sigaction *act, struct sigaction *oldact) {
|
||||
struct sigaction prev = g_app_sigchld;
|
||||
if (act) {
|
||||
g_app_sigchld = *act;
|
||||
if (ddnatv_apply_sigchld(real_sig) != 0) {
|
||||
int err = errno;
|
||||
g_app_sigchld = prev;
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (oldact) *oldact = prev;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// From the hook's start (handoff.c), once the parents file is open
|
||||
static void ddnatv_manage_sigchld(void) {
|
||||
if (!getenv("DD_PARENTS")) return;
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return;
|
||||
const char *named = getenv("DD_REAP_ADOPTED");
|
||||
g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL);
|
||||
if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1;
|
||||
}
|
||||
|
||||
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
if (!real_sig) return -1;
|
||||
|
||||
if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact);
|
||||
if (signum == SIGSYS) {
|
||||
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
|
||||
return real_sig(signum, act, oldact);
|
||||
@@ -192,6 +265,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda
|
||||
static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL;
|
||||
if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction");
|
||||
|
||||
if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact);
|
||||
if (signum == SIGSYS) {
|
||||
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
|
||||
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0;
|
||||
@@ -210,6 +284,16 @@ typedef void (*sighandler_t)(int);
|
||||
sighandler_t signal(int signum, sighandler_t handler) {
|
||||
static sighandler_t (*orig_signal)(int, sighandler_t) = NULL;
|
||||
if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal");
|
||||
if (signum == SIGCHLD && g_sigchld_managed) {
|
||||
// glibc's signal(): BSD semantics
|
||||
struct sigaction act, old;
|
||||
memset(&act, 0, sizeof(act));
|
||||
act.sa_handler = handler;
|
||||
act.sa_flags = SA_RESTART;
|
||||
sigemptyset(&act.sa_mask);
|
||||
sigaddset(&act.sa_mask, SIGCHLD);
|
||||
return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR;
|
||||
}
|
||||
if (signum == SIGSYS) {
|
||||
struct sigaction act, old;
|
||||
memset(&act, 0, sizeof(act));
|
||||
|
||||
@@ -1025,6 +1025,19 @@ int main(int argc, char **argv) {
|
||||
errno = 0;
|
||||
printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH);
|
||||
}
|
||||
if (strcmp(argv[1], "nowait") == 0) {
|
||||
// no wait until the program has long exited, as Plasma's shell never waits for what it launches
|
||||
usleep(2000000);
|
||||
char path[64], line[256] = "";
|
||||
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (f) {
|
||||
if (!fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
fclose(f);
|
||||
}
|
||||
char *s = strrchr(line, ')');
|
||||
printf("zombie\t%d\n", s && s[1] == ' ' && s[2] == 'Z');
|
||||
}
|
||||
int group = strcmp(argv[1], "group") == 0;
|
||||
if (group) {
|
||||
setpgid(pid, pid);
|
||||
@@ -1139,6 +1152,93 @@ int main(void) {
|
||||
}
|
||||
"""
|
||||
|
||||
# A child subreaper, as every session process is (preload/subreaper.c), that never waits for a child
|
||||
# it did not fork. adopt: a child that exits at once leaves a grandchild, which exits once the child is
|
||||
# gone; own: its own child, which it waits for only later; vfork: one vfork() made, its program static
|
||||
# (no hook, so no record of it); handler: as adopt, with a SIGCHLD handler of its own; ignore: SIGCHLD
|
||||
# ignored, so the kernel reaps.
|
||||
ORPHANS = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static volatile sig_atomic_t calls;
|
||||
static void counted(int sig) { (void)sig; calls++; }
|
||||
|
||||
static void nap(long ms) {
|
||||
struct timespec t = {ms / 1000, (ms % 1000) * 1000000L};
|
||||
while (nanosleep(&t, &t) != 0 && errno == EINTR) {}
|
||||
}
|
||||
|
||||
static int zombie(pid_t pid) {
|
||||
char path[64], line[256] = "";
|
||||
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return 0;
|
||||
if (!fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
fclose(f);
|
||||
char *s = strrchr(line, ')');
|
||||
return s && s[1] == ' ' && s[2] == 'Z';
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *mode = argv[1];
|
||||
int subreaper = 0;
|
||||
printf("subreaper\t%d\n", prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 && prctl(PR_GET_CHILD_SUBREAPER, &subreaper) == 0 && subreaper);
|
||||
fflush(stdout);
|
||||
if (strcmp(mode, "handler") == 0) {
|
||||
struct sigaction sa, seen;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_handler = counted;
|
||||
sa.sa_flags = SA_RESTART;
|
||||
sigaction(SIGCHLD, &sa, NULL);
|
||||
sigaction(SIGCHLD, NULL, &seen);
|
||||
printf("view\t%d\n", seen.sa_handler == counted);
|
||||
}
|
||||
if (strcmp(mode, "ignore") == 0) signal(SIGCHLD, SIG_IGN);
|
||||
if (strcmp(mode, "own") == 0 || strcmp(mode, "vfork") == 0) {
|
||||
pid_t child = strcmp(mode, "vfork") == 0 ? vfork() : fork();
|
||||
if (child == 0) {
|
||||
if (argc > 2) execl(argv[2], "target", "7", (char *)NULL);
|
||||
_exit(7);
|
||||
}
|
||||
nap(1500);
|
||||
int status = 0;
|
||||
pid_t r = waitpid(child, &status, 0);
|
||||
printf("own\t%d\n", r == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd) != 0) return 1;
|
||||
pid_t middle = fork();
|
||||
if (middle == 0) {
|
||||
pid_t grandchild = fork();
|
||||
if (grandchild == 0) {
|
||||
nap(300); // its parent is gone by then
|
||||
_exit(5);
|
||||
}
|
||||
if (write(pipefd[1], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) _exit(1);
|
||||
_exit(0);
|
||||
}
|
||||
pid_t grandchild = 0;
|
||||
if (read(pipefd[0], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) return 1;
|
||||
int status = 0;
|
||||
printf("middle\t%d\n", waitpid(middle, &status, 0) == middle);
|
||||
nap(1500);
|
||||
printf("orphan\t%d\n", zombie(grandchild));
|
||||
printf("adopted\t%d\n", waitpid(grandchild, &status, WNOHANG) == grandchild);
|
||||
if (strcmp(mode, "handler") == 0) printf("calls\t%d\n", calls > 0);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
DUPRACE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
@@ -2280,6 +2380,79 @@ class NativeHookHandoffTest(unittest.TestCase):
|
||||
pass_fds=(table,))
|
||||
return parent, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
|
||||
|
||||
def run_orphans(self, mode, named=True, parents=True, *args):
|
||||
tmp = Path(self.tmp.name)
|
||||
probe = tmp / "orphans"
|
||||
if not probe.exists():
|
||||
(tmp / "orphans.c").write_text(ORPHANS)
|
||||
subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "orphans.c")], check=True)
|
||||
(self.root / "run").mkdir(exist_ok=True)
|
||||
env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)}
|
||||
if parents:
|
||||
env["DD_PARENTS"] = "/run/parents-%s" % self.id().rsplit(".", 1)[-1]
|
||||
if named:
|
||||
env["DD_REAP_ADOPTED"] = "other:orphans"
|
||||
# not a session's own settings, when run inside one
|
||||
inherited = {k: v for k, v in os.environ.items() if k not in ("DD_PARENTS", "DD_REAP_ADOPTED")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in env.items() for arg in ("-E", f"{key}={value}")]
|
||||
run_env = inherited
|
||||
else:
|
||||
cmd = []
|
||||
run_env = dict(inherited, **env)
|
||||
out = subprocess.run(cmd + [str(probe), mode, *args], env=run_env, capture_output=True, text=True, timeout=60)
|
||||
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
|
||||
if mode == "adopt" and result.get("subreaper") != "1":
|
||||
self.skipTest("no child subreaper here (qemu-user has no PR_SET_CHILD_SUBREAPER)")
|
||||
return result, out
|
||||
|
||||
def test_a_subreaper_reaps_the_zombie_it_adopted(self):
|
||||
result, out = self.run_orphans("adopt")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual("1", result.get("middle"), out.stdout)
|
||||
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
|
||||
self.assertEqual("0", result.get("adopted"), out.stdout)
|
||||
|
||||
def test_a_program_not_named_keeps_its_default_sigchld_and_its_adopted_zombie(self):
|
||||
result, out = self.run_orphans("adopt", False)
|
||||
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
|
||||
self.assertEqual("1", result.get("adopted"), out.stdout)
|
||||
|
||||
def test_without_a_parents_file_nothing_is_reaped(self):
|
||||
result, out = self.run_orphans("adopt", True, False)
|
||||
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
|
||||
|
||||
def test_a_subreapers_own_child_waits_for_its_wait(self):
|
||||
result, out = self.run_orphans("own")
|
||||
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
|
||||
|
||||
def test_a_vfork_child_with_no_record_waits_for_its_parents_wait(self):
|
||||
result, out = self.run_orphans("vfork", True, True, "/bin/target")
|
||||
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
|
||||
|
||||
def test_a_programs_own_sigchld_handler_runs_and_shows_as_its_own(self):
|
||||
result, out = self.run_orphans("handler", False)
|
||||
self.assertEqual("1", result.get("view"), out.stdout + out.stderr)
|
||||
self.assertEqual("1", result.get("calls"), out.stdout)
|
||||
if result.get("subreaper") == "1":
|
||||
self.assertEqual("0", result.get("orphan"), out.stdout)
|
||||
|
||||
def test_an_ignored_sigchld_stays_the_kernels(self):
|
||||
result, out = self.run_orphans("ignore")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
|
||||
|
||||
def test_an_unwaited_handoffs_child_is_reaped(self):
|
||||
# a parent that never waits until its program has long exited, as Plasma's shell
|
||||
(self.root / "run").mkdir(exist_ok=True)
|
||||
env = {"DD_PARENTS": "/run/parents-nowait", "DD_REAP_ADOPTED": "parent"}
|
||||
result, requests, out = self.run_parent("nowait", "6", extra_env=env)
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual("0", result.get("zombie"), out.stdout + out.stderr)
|
||||
# its program's exit, still there for the wait that comes at last
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
self.assertEqual("6", result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_guest_sees_no_pidfd_support_so_its_waits_go_through_the_handoff(self):
|
||||
parent, result, out = self.run_worker_program("pidfd", PIDFD_PROBE)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
|
||||
Reference in new issue
Block a user