import errno import fcntl import json import os import select import shutil import signal import socket import struct import subprocess import sys import tempfile import termios import threading import time import unittest from pathlib import Path from tools.tests.test_usr2_preload import runner CLD_EXITED = 1 HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" # fork() and exec argv[1] with "3", without the hook: prints the exit status it got EXEC_PROBE = r""" #include #include #include int main(int argc, char **argv) { pid_t pid = fork(); if (pid == 0) { execl(argv[1], "target", "3", (char *)NULL); _exit(127); } int status = 0; if (waitpid(pid, &status, 0) != pid) return 1; printf("%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); return 0; } """ PARENT = r""" #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include 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); } // nothread: a second thread forks the child; __WNOTHREAD waits see only their own thread's children static char *nothread_arg; static int nothread_wrap; static pthread_mutex_t nothread_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t nothread_cond = PTHREAD_COND_INITIALIZER; static int nothread_step; static pid_t nothread_child; static void nothread_await(int step) { pthread_mutex_lock(¬hread_lock); while (nothread_step < step) pthread_cond_wait(¬hread_cond, ¬hread_lock); pthread_mutex_unlock(¬hread_lock); } static void nothread_go(int step) { pthread_mutex_lock(¬hread_lock); nothread_step = step; pthread_cond_broadcast(¬hread_cond); pthread_mutex_unlock(¬hread_lock); } static void *nothread_forker(void *unused) { (void)unused; pid_t pid = fork(); if (pid == 0) { if (nothread_wrap) execl("/bin/wrap", "wrap", "/bin/target", "target", nothread_arg, (char *)NULL); 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); nothread_await(2); int status = 0; pid_t r = waitpid(pid, &status, __WNOTHREAD); printf("own\t%d\n", r == pid); if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); return NULL; } // laterecord: a program this thread spawns (not listed: glibc's posix_spawn(), recorded by the // parent) is recorded only once the hook's test gate opens, by when it is gone and a later child of // the main thread has its pid, handed off and its forked child reaped static int late_done[2], late_hold[2], late_gate; static void *late_spawner(void *unused) { (void)unused; char gate[32]; snprintf(gate, sizeof(gate), "%d %d", late_gate, (int)syscall(SYS_gettid)); setenv("DDH_TEST_RECORD_GATE", gate, 1); pid_t pid = 0; char *args[] = {"wrap", NULL}; // exits at once: nothing to wrap int err = posix_spawn(&pid, "/bin/wrap", NULL, NULL, args, environ); if (write(late_done[1], &err, sizeof(err)) != sizeof(err)) _exit(123); // recorded char c; if (read(late_hold[0], &c, 1) != 1) _exit(124); // alive while the main thread's wait looks return NULL; } // Whether the hook's table (at any number here) has child's entry claimed: its handoff is with the app static int claimed(pid_t child) { char path[32], target[64]; for (int fd = 3; fd < 4096; fd++) { snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; for (int slot = 0; slot < 1024; slot++) { int32_t head[4]; // child, real, parent, state if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && head[3] == 3) return 1; } } return 0; } // live 1: the late record is made while the later child is still handing its program off (the fake // spawner holds its reply), so the start time it reads is that child's. live 2: made once the later // child has recorded itself, before it execs and starts its handoff. static int late_record(const char *arg, int live) { int gate[2]; if (pipe(gate) != 0 || pipe(late_done) != 0 || pipe(late_hold) != 0) return 1; late_gate = gate[0]; pthread_t spawner; pthread_create(&spawner, NULL, late_spawner, NULL); // the spawned program, reaped: the only child yet pid_t first = 0; int status = 0; for (int i = 0; i < 3000 && (first = waitpid(-1, &status, WNOHANG)) <= 0; i++) usleep(10000); if (first <= 0) return 1; // the next fork gets the pid again FILE *f = fopen("/proc/sys/kernel/ns_last_pid", "w"); if (!f) return 1; fprintf(f, "%d", (int)first - 1); if (fclose(f) != 0) return 1; int hold[2], at[2]; if (live == 2 && (pipe(hold) != 0 || pipe(at) != 0)) return 1; pid_t pid = fork(); if (pid == 0) { if (live == 2) { // back from fork(), whose hook has recorded it: the parent's word to go on comes after the // late record char c = 1; close(hold[1]); if (write(at[1], &c, 1) != 1 || read(hold[0], &c, 1) != 1) _exit(126); } 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) { int claim = 0; for (int i = 0; i < 500 && !(claim = claimed(pid)); i++) usleep(10000); printf("claimed\t%d\n", claim); if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; } if (live == 2) { char c; struct pollfd p = {at[0], POLLIN, 0}; int ready = poll(&p, 1, 10000) == 1 && read(at[0], &c, 1) == 1; printf("recorded\t%d\n", ready); if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; close(hold[0]); if (write(hold[1], "1", 1) != 1) return 1; } // its forked child exits once the program runs: reaped here, the program's exit left alone char path[64]; snprintf(path, sizeof(path), "/proc/%d", (int)pid); for (int i = 0; i < 1000 && access(path, F_OK) == 0; i++) { waitpid(-1, &status, WNOHANG); usleep(10000); } printf("reaped\t%d\n", access(path, F_OK) != 0); if (!live && (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err))) return 1; printf("spawned\t%d\n", err); printf("own\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WNOTHREAD) == 0); kill(pid, SIGKILL); printf("ended\t%d\n", waitpid(pid, &status, 0) == pid && WIFSIGNALED(status)); if (write(late_hold[1], "1", 1) != 1) return 1; pthread_join(spawner, NULL); return 0; } static void *gone_forker(void *unused) { (void)unused; pid_t pid = fork(); if (pid == 0) { 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 } // nothreadnested: a signal's handler waits, with no __WNOTHREAD, while it interrupts the main // thread's __WNOTHREAD wait; that wait still takes only the main thread's children afterwards static void nested_wait(int sig) { (void)sig; int status = 0; int saved = errno; waitpid(4194303, &status, WNOHANG); // no such child: takes nothing errno = saved; } // prepclose: another thread's close_range(799, 801) has looked at the kept fds, none of them the // table's yet, and waits on the hook's test gate while the first fork makes the table at 800 static int prep_in[2], prep_out[2]; static long prep_closed = -2; static void *prep_closer(void *unused) { (void)unused; char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", prep_in[0], prep_out[1], (int)syscall(SYS_gettid)); setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); prep_closed = syscall(SYS_close_range, 799, 801, 0); return NULL; } static int prep_hold_ms = 0; // after the table's fd is kept: past the hook's wait for the close static int prep_kept[2]; // the hook's word that it has kept the table's fd (DDH_TEST_TABLE_KEPT) static int prep_acked; static void *prep_release(void *unused) { (void)unused; // once the first fork has made and kept the table's fd, while it waits for the close to end struct pollfd p = {prep_kept[0], POLLIN, 0}; char c; prep_acked = poll(&p, 1, 10000) == 1 && read(prep_kept[0], &c, 1) == 1; usleep(prep_hold_ms * 1000); if (write(prep_in[1], "1", 1) != 1) _exit(122); return NULL; } // How many of the hook's tables are open here, at any numbers static int tables_open(void) { char path[32], target[64]; int count = 0; for (int fd = 3; fd < 4096; fd++) { snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n > 0 && (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) == 0)) count++; } return count; } static int table_open(void) { return tables_open() > 0; } // nowaitpeek: one thread's waitid(WNOWAIT) has seen the exit of a forked child that handed its // program off (held there by the hook's wait gate) when another wait takes the program's exit and // frees the entry; that look reports nothing, not the forked child's exit static int nowait_in[2], nowait_out[2]; static void *nowait_waiter(void *unused) { (void)unused; char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", nowait_in[0], nowait_out[1], (int)syscall(SYS_gettid)); setenv("DDH_TEST_WAIT_GATE", gate, 1); siginfo_t si; memset(&si, 0, sizeof(si)); errno = 0; int r = waitid(P_ALL, 0, &si, WEXITED | WNOWAIT); printf("looked\t%d\n", r); printf("echild\t%d\n", r == -1 && errno == ECHILD); printf("lookedpid\t%d\n", r == 0 ? (int)si.si_pid : 0); return NULL; } // twowaits: one thread's wait has found the forked child (held there by the hook's test gate, for // longer than any other wait would wait for it) when another thread's wait takes the program's exit; // the child is reported once static int two_in[2], two_out[2]; static void *first_waiter(void *unused) { (void)unused; char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", two_in[0], two_out[1], (int)syscall(SYS_gettid)); setenv("DDH_TEST_WAIT_GATE", gate, 1); int status = 0; pid_t r = waitpid(-1, &status, 0); printf("first\t%d\n", (int)r); return NULL; } static void *releaser(void *unused) { (void)unused; usleep(1500000); // the other wait is under way by now, and has had more than a second if (write(two_in[1], "1", 1) != 1) _exit(122); return NULL; } // reapreuse: one thread's wait has reaped the first child's forked child and is held before it marks // the entry (the hook's reap gate), while the first child is collected, its slot freed, and a second // child takes the slot; that wait then reports the second child once, with its program's status static int reuse_in[2], reuse_out[2]; static void *reuse_waiter(void *unused) { (void)unused; char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", reuse_in[0], reuse_out[1], (int)syscall(SYS_gettid)); setenv("DDH_TEST_REAP_GATE", gate, 1); int status = 0, reports = 0, last = 0, sig = -1; pid_t r; while ((r = waitpid(-1, &status, 0)) > 0) { reports++; last = r; sig = WIFSIGNALED(status) ? WTERMSIG(status) : -1; } printf("reports\t%d\n", reports); printf("last\t%d\n", last); printf("lastsignal\t%d\n", sig); return NULL; } // stoppeek: one thread's wait for a child stopped while its handoff is with the app has seen the stop // (held there by the hook's wait gate) when the child goes on, hands its program off and its forked // child exits; that wait reports the program's exit, not the forked child's static int peek_in[2], peek_out[2]; static pid_t peek_child; static void *peek_waiter(void *unused) { (void)unused; char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", peek_in[0], peek_out[1], (int)syscall(SYS_gettid)); setenv("DDH_TEST_WAIT_GATE", gate, 1); int status = 0; // the stop is gone by the time it takes the event: this one wait reports the program's end pid_t r = waitpid(peek_child, &status, WUNTRACED); printf("waited\t%d\n", r == peek_child); printf("stopped\t%d\n", r == peek_child && WIFSTOPPED(status)); printf("code\t%d\n", r == peek_child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); return NULL; } // Whether pid is a zombie here, its exit not taken (the kernel's word, no wait of any kind) static int zombie(pid_t pid) { char path[64], stat[256]; snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); FILE *f = fopen(path, "r"); if (!f) return 0; size_t n = fread(stat, 1, sizeof(stat) - 1, f); fclose(f); stat[n] = 0; char *end = strrchr(stat, ')'); return end && end[1] == ' ' && end[2] == 'Z'; } // A thread's state letter (R, S, Z...), or 0 static char thread_state(pid_t tid) { char path[64], stat[256]; snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)tid); FILE *f = fopen(path, "r"); if (!f) return 0; size_t n = fread(stat, 1, sizeof(stat) - 1, f); fclose(f); stat[n] = 0; char *end = strrchr(stat, ')'); return end && end[1] == ' ' ? end[2] : 0; } // The state of the hook's table entry for child (any table here), or -1 when it has none: a forked // child of this process when child is 0 (its pid in *found) static int entry_state_of(pid_t child, pid_t *found) { char path[32], target[64]; for (int fd = 3; fd < 4096; fd++) { snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; for (int slot = 0; slot < 1024; slot++) { int32_t head[4]; // child, real, parent, state if (pread(fd, head, sizeof(head), 64 + slot * 64) != (ssize_t)sizeof(head) || head[3] == 0) continue; if (child ? head[0] == child : head[2] == getpid()) { if (found) *found = head[0]; return head[3]; } } } return -1; } // Whether the app's report of child's program (status, child: 32 bytes into its entry) is in the table static int reported(pid_t child) { char path[32], target[64]; for (int fd = 3; fd < 4096; fd++) { snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; for (int slot = 0; slot < 1024; slot++) { int32_t head[1], report[2]; if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && pread(fd, report, sizeof(report), 64 + slot * 64 + 32) == (ssize_t)sizeof(report) && report[1] == child) return 1; } } return 0; } // nohangtwo: a handed-off child A whose program has exited while its forked child is held (the hook's // test switch), and a child B that is ready: a WNOHANG wait reports B. kind 0: B ordinary, any child; // 1: B handed off too (its program exited, its forked child free to go); 2: a wait for our group // (waitpid(0)), with B ordinary and an exited child D in a group of its own, which it must not take. static int nohang_two(const char *arg, int kind) { int hold[2]; if (pipe(hold) != 0) return 1; char fd[16]; snprintf(fd, sizeof(fd), "%d", hold[0]); setenv("DDH_TEST_SHIM_HOLD", fd, 1); pid_t a = fork(); if (a == 0) { execl("/bin/target", "target", arg, (char *)NULL); _exit(127); } if (a < 0) return 1; unsetenv("DDH_TEST_SHIM_HOLD"); // exited in the table (2), or handed off (1) with the app's report of its exit in: either is an exit // the wait's look for exited entries reaches, not a claim (3) still under way int done = 0; for (int i = 0; i < 1000 && !done; i++) { int st = entry_state_of(a, NULL); done = st == 2 || (st == 1 && reported(a)); if (!done) usleep(10000); } printf("aexited\t%d\n", done); pid_t d = 0; if (kind == 2) { d = fork(); if (d == 0) { setpgid(0, 0); _exit(6); } if (d < 0) return 1; } pid_t b = fork(); if (b == 0) { if (kind == 1) { execl("/bin/target", "target", "5", (char *)NULL); _exit(127); } _exit(5); } if (b < 0) return 1; int ready = 0; for (int i = 0; i < 1000 && !ready; i++) { int st = kind == 1 ? entry_state_of(b, NULL) : 0; // a handed-off B: its exit in the table and its forked child exited, so nothing holds it back ready = zombie(b) && (kind != 1 || st == 2 || (st == 1 && reported(b))) && (!d || zombie(d)); if (!ready) usleep(10000); } printf("bwaitable\t%d\n", ready); char path[32]; snprintf(path, sizeof(path), "/proc/%d", (int)a); printf("aheld\t%d\n", access(path, F_OK) == 0 && !zombie(a)); pid_t which = kind == 2 ? 0 : -1; int status = 0; pid_t r = waitpid(which, &status, WNOHANG); printf("first\t%d\n", r == b); printf("firstexit\t%d\n", r == b && WIFEXITED(status) ? WEXITSTATUS(status) : -1); if (write(hold[1], "1", 1) != 1) return 1; r = waitpid(which, &status, 0); printf("second\t%d\n", r == a); printf("exit\t%d\n", r == a && WIFEXITED(status) ? WEXITSTATUS(status) : -1); if (d) { r = waitpid(d, &status, WNOHANG); printf("other\t%d\n", r == d && WIFEXITED(status) ? WEXITSTATUS(status) : -1); } printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); return 0; } // reapbeforerecord: a thread forks a listed child and is held before its fork is recorded (the hook's // record gate); meanwhile another thread's blocking wait reaps the child's forked child and must go // on waiting for the program, not drop it when the record is made static int rbr_gate[2]; static pid_t rbr_pid; // all three read before the join of their writer: atomic static pid_t rbr_got = -2; static int rbr_status; static void *rbr_forker(void *arg) { char gate[32]; snprintf(gate, sizeof(gate), "%d %d", rbr_gate[0], (int)syscall(SYS_gettid)); setenv("DDH_TEST_RECORD_GATE", gate, 1); pid_t pid = fork(); if (pid == 0) { execl("/bin/target", "target", (const char *)arg, (char *)NULL); _exit(127); } __atomic_store_n(&rbr_pid, pid, __ATOMIC_RELEASE); return NULL; } static void *rbr_waiter(void *unused) { (void)unused; int status = 0; pid_t r = waitpid(-1, &status, 0); rbr_status = status; __atomic_store_n(&rbr_got, r, __ATOMIC_RELEASE); return NULL; } static int reap_before_record(const char *arg) { if (pipe(rbr_gate) != 0) return 1; pthread_t forker, waiter; pthread_create(&forker, NULL, rbr_forker, (void *)arg); pid_t child = 0; int st = -1; for (int i = 0; i < 1000 && (st = entry_state_of(0, &child)) != 1; i++) usleep(10000); int exited = 0; for (int i = 0; st == 1 && child > 0 && i < 500 && !(exited = zombie(child)); i++) usleep(10000); int handed = st == 1 && child > 0 && exited; printf("handed\t%d\n", handed); if (!handed) { // no handed-off child to go on with: the forker let go, and nothing signalled if (write(rbr_gate[1], "1", 1) != 1) return 1; pthread_join(forker, NULL); return 0; } pthread_create(&waiter, NULL, rbr_waiter, NULL); char path[32]; snprintf(path, sizeof(path), "/proc/%d", (int)child); int reaped = 0; for (int i = 0; i < 500 && !(reaped = access(path, F_OK) != 0); i++) usleep(10000); printf("shimreaped\t%d\n", reaped); printf("unrecorded\t%d\n", __atomic_load_n(&rbr_pid, __ATOMIC_ACQUIRE) == 0); if (write(rbr_gate[1], "1", 1) != 1) return 1; pthread_join(forker, NULL); printf("forked\t%d\n", rbr_pid == child); usleep(500000); printf("waiting\t%d\n", __atomic_load_n(&rbr_got, __ATOMIC_ACQUIRE) == -2); kill(child, SIGTERM); pthread_join(waiter, NULL); printf("got\t%d\n", rbr_got == child); printf("signal\t%d\n", rbr_got == child && WIFSIGNALED(rbr_status) ? WTERMSIG(rbr_status) : -1); return 0; } // waitidblocked: the child holds before its exec until the parent's waitid(P_PID) has been seen blocked // (its thread asleep) with no entry claimed yet, so the wait begins before the handoff exists static siginfo_t wb_info; // read only after the join static int wb_done = -2; // these two polled meanwhile: atomic static pid_t wb_tid; static pid_t wb_child; static void *wb_waiter(void *unused) { (void)unused; memset(&wb_info, 0, sizeof(wb_info)); __atomic_store_n(&wb_tid, (pid_t)syscall(SYS_gettid), __ATOMIC_RELEASE); int r = waitid(P_PID, (id_t)wb_child, &wb_info, WEXITED); __atomic_store_n(&wb_done, r, __ATOMIC_RELEASE); return NULL; } static int waitid_blocked(const char *arg) { int go[2]; if (pipe(go) != 0) return 1; wb_child = fork(); if (wb_child == 0) { char c; close(go[1]); if (read(go[0], &c, 1) != 1) _exit(126); execl("/bin/target", "target", arg, (char *)NULL); _exit(127); } if (wb_child < 0) return 1; close(go[0]); pthread_t waiter; pthread_create(&waiter, NULL, wb_waiter, NULL); int asleep = 0; for (int i = 0; i < 500 && asleep < 10; i++) { usleep(20000); pid_t tid = __atomic_load_n(&wb_tid, __ATOMIC_ACQUIRE); asleep = tid && __atomic_load_n(&wb_done, __ATOMIC_ACQUIRE) == -2 && thread_state(tid) == 'S' ? asleep + 1 : 0; } printf("blocked\t%d\n", asleep >= 10); printf("unclaimed\t%d\n", entry_state_of(wb_child, NULL) < 0); if (write(go[1], "1", 1) != 1) return 1; pthread_join(waiter, NULL); printf("same\t%d\n", wb_done == 0 && wb_info.si_pid == wb_child); printf("code\t%d\n", wb_info.si_code); printf("exit\t%d\n", wb_info.si_status); int status = 0; printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); return 0; } static void *bystander(void *unused) { (void)unused; int status = 0; printf("bystander\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); return NULL; } // nothreadheir: the main thread and the forking one both end; the kernel gives the child to the // group's first live thread, the heir (created first), and not to the bystander static void *heir(void *unused) { (void)unused; nothread_await(2); int status = 0; pid_t r = waitpid(nothread_child, &status, __WNOTHREAD); printf("own\t%d\n", r == nothread_child); if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); return NULL; } static void *late_bystander(void *unused) { (void)unused; nothread_await(1); // both waits only once the main thread has ended (its task a zombie) char path[64], stat[256]; snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)getpid()); int ended = 0; for (int i = 0; i < 500 && !ended; i++) { FILE *f = fopen(path, "r"); size_t n = f ? fread(stat, 1, sizeof(stat) - 1, f) : 0; if (f) fclose(f); stat[n] = 0; char *s = strrchr(stat, ')'); ended = f && s && s[1] == ' ' && (s[2] == 'Z' || s[2] == 'X'); if (!ended) usleep(10000); } printf("mainended\t%d\n", ended); int status = 0; printf("bystander\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); nothread_go(2); return NULL; } int main(int argc, char **argv) { setvbuf(stdout, NULL, _IONBF, 0); // what it got to, also when it does not finish pid_t pid; if (strcmp(argv[1], "nothreadheir") == 0) { nothread_arg = argv[2]; pthread_t first, forker, other; pthread_create(&first, NULL, heir, NULL); pthread_create(&forker, NULL, gone_forker, NULL); pthread_join(forker, NULL); pthread_create(&other, NULL, late_bystander, NULL); usleep(1500000); // the program has exited by now nothread_go(1); pthread_exit(NULL); // the main thread ends too; the others finish the process } if (strcmp(argv[1], "nohangtwo") == 0) return nohang_two(argv[2], 0); if (strcmp(argv[1], "nohangtwohanded") == 0) return nohang_two(argv[2], 1); if (strcmp(argv[1], "nohangtwogroup") == 0) return nohang_two(argv[2], 2); if (strcmp(argv[1], "reapbeforerecord") == 0) return reap_before_record(argv[2]); if (strcmp(argv[1], "waitidblocked") == 0) return waitid_blocked(argv[2]); if (strcmp(argv[1], "laterecord") == 0) return late_record(argv[2], 0); if (strcmp(argv[1], "laterecordlive") == 0) return late_record(argv[2], 1); if (strcmp(argv[1], "laterecordearly") == 0) return late_record(argv[2], 2); if (strcmp(argv[1], "nothreadgone") == 0) { nothread_arg = argv[2]; pthread_t forker; pthread_create(&forker, NULL, gone_forker, NULL); pthread_join(forker, NULL); usleep(1500000); // the program has exited by now // another thread than the one the child went to: not its child pthread_t other; pthread_create(&other, NULL, bystander, NULL); pthread_join(other, NULL); int status = 0; pid_t r = waitpid(nothread_child, &status, __WNOTHREAD); printf("own\t%d\n", r == nothread_child); if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); return 0; } if (strcmp(argv[1], "nothreadnested") == 0) { // the main thread's own program runs on; the other thread's has exited by the time it waits pid_t own = fork(); if (own == 0) { 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); nothread_await(1); struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = nested_wait; // no SA_RESTART: the wait ends with EINTR after one more look sigaction(SIGALRM, &sa, NULL); alarm(1); int status = 0; errno = 0; pid_t r = waitpid(-1, &status, __WNOTHREAD); printf("outer\t%d\n", (int)r); printf("eintr\t%d\n", r == -1 && errno == EINTR); kill(own, SIGKILL); printf("ownend\t%d\n", waitpid(own, &status, 0) == own && WIFSIGNALED(status)); nothread_go(2); pthread_join(forker, NULL); return 0; } if (strcmp(argv[1], "nothread") == 0 || strcmp(argv[1], "nothreadwrap") == 0) { nothread_arg = argv[2]; nothread_wrap = argv[1][8] != 0; pthread_t forker; pthread_create(&forker, NULL, nothread_forker, NULL); nothread_await(1); int status = 0; printf("other\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WNOTHREAD)); printf("otherpid\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); printf("otherwait3\t%d\n", (int)wait3(&status, WNOHANG | __WNOTHREAD, NULL)); nothread_go(2); pthread_join(forker, NULL); return 0; } if (strcmp(argv[1], "prepclose") == 0 || strcmp(argv[1], "prepcloselate") == 0) { // late: the close goes on past the hook's wait for it, through its second try; a later fork // makes the table then int late = argv[1][9] != 0; prep_hold_ms = late ? 1500 : 0; if (pipe(prep_in) != 0 || pipe(prep_out) != 0 || pipe(prep_kept) != 0) return 1; char kept[16]; snprintf(kept, sizeof(kept), "%d", prep_kept[1]); setenv("DDH_TEST_TABLE_KEPT", kept, 1); pthread_t closer, release; pthread_create(&closer, NULL, prep_closer, NULL); char c; if (read(prep_out[0], &c, 1) != 1) return 1; // it has looked pthread_create(&release, NULL, prep_release, NULL); pid_t pid = fork(); if (pid == 0) { 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); int status = 0; printf("same\t%d\n", waitpid(pid, &status, 0) == pid); if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); if (late) { pid_t again = fork(); if (again == 0) { 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); printf("table\t%d\n", table_open()); return 0; } if (strcmp(argv[1], "prepcloseheld") == 0) { // the close stays under way through three forks, each of whose tries gives the table up: one // table's fd at most is left for it, tried again, not another made each time if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; pthread_t closer; pthread_create(&closer, NULL, prep_closer, NULL); char c; if (read(prep_out[0], &c, 1) != 1) return 1; int status = 0; 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()); if (write(prep_in[1], "1", 1) != 1) return 1; pthread_join(closer, NULL); // The close has closed the given-up table's 800 by now; a file of the program's own takes the // number, as another thread's open could, and outlives the next try, which finds no table there. char target[64]; printf("freed800\t%d\n", readlink("/proc/self/fd/800", target, sizeof(target)) < 0); int mine = open("/dev/null", O_RDONLY); if (mine < 0 || dup2(mine, 800) != 800) return 1; close(mine); pid_t again = fork(); // the close is over: the table is made now if (again == 0) { 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()); ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1); if (n > 0) target[n] = 0; printf("mine800\t%d\n", n > 0 && strcmp(target, "/dev/null") == 0); return 0; } if (strcmp(argv[1], "nowaitpeek") == 0) { if (pipe(nowait_in) != 0 || pipe(nowait_out) != 0) return 1; pid_t child = fork(); if (child == 0) { 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; if (read(nowait_out[0], &c, 1) != 1) return 1; // it has seen the forked child's exit kill(child, SIGTERM); int status = 0; printf("taken\t%d\n", waitpid(child, &status, 0) == child && WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM); if (write(nowait_in[1], "1111", 4) != 4) return 1; pthread_join(waiter, NULL); printf("child\t%d\n", (int)child); return 0; } if (strcmp(argv[1], "forkclose") == 0) { // another thread's close_range() is under way (held on the test gate) when this forks a child, // which then makes a table of its own for a child of its own: it waits for no close of its parent's if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; pthread_t closer; pthread_create(&closer, NULL, prep_closer, NULL); char c; if (read(prep_out[0], &c, 1) != 1) return 1; pid_t child = fork(); if (child == 0) { pid_t grandchild = fork(); if (grandchild == 0) { 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], "reapreuse") == 0) { if (pipe(reuse_in) != 0 || pipe(reuse_out) != 0) return 1; pid_t first = fork(); if (first == 0) { 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; if (read(reuse_out[0], &c, 1) != 1) return 1; // it has reaped the first's forked child kill(first, SIGTERM); usleep(1000000); // the program's end is reported int status = 0; printf("first\t%d\n", waitpid(first, &status, 0) == first && WIFSIGNALED(status)); pid_t second = fork(); if (second == 0) { execl("/bin/target", "target", "sleep", (char *)NULL); _exit(127); } 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); pthread_join(waiter, NULL); printf("second\t%d\n", (int)second); return 0; } if (strcmp(argv[1], "stoppeek") == 0) { if (pipe(peek_in) != 0 || pipe(peek_out) != 0) return 1; peek_child = fork(); if (peek_child == 0) { 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; pthread_create(&waiter, NULL, peek_waiter, NULL); char c; if (read(peek_out[0], &c, 1) != 1) return 1; // it has seen an event: the gate says which printf("peeked\t%d\n", c); if (c != CLD_STOPPED) return 0; // not the stop, so not the ordering this is about: the test fails syscall(SYS_tgkill, peek_child, peek_child, SIGCONT); // the reply has come, the program runs, the forked child has exited (its exit still not taken) int gone = 0; for (int i = 0; i < 500 && !(gone = zombie(peek_child)); i++) usleep(10000); printf("shimexited\t%d\n", gone); if (write(peek_in[1], "11111111", 8) != 8) return 1; // for each look pthread_join(waiter, NULL); return 0; } // 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; 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) { if (strcmp(argv[1], "closefds") == 0) { // as Python's subprocess does before exec; an ordinary fd shows that it closed them int probe = open("/dev/null", O_RDONLY); printf("closerange\t%ld\n", (long)syscall(SYS_close_range, 3, ~0U, 0)); printf("closed\t%d\n", probe >= 3 && fcntl(probe, F_GETFD) < 0); fflush(stdout); } if (strcmp(argv[1], "group") == 0) setpgid(0, 0); if (gate[0] >= 0) { char c; close(gate[1]); if (read(gate[0], &c, 1) != 1) _exit(126); } if (strcmp(argv[1], "manyargs") == 0) { // argv[3] after 32 others, as a long env-wrapped launch has it char *args[37] = {"target", argv[2]}; for (int i = 2; i < 34; i++) args[i] = "x"; args[34] = argv[3]; args[35] = NULL; execv("/bin/target", args); _exit(127); } 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; 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; } int all = strcmp(argv[1], "waitidall") == 0 ? __WALL : 0; if (strcmp(argv[1], "waitid") == 0 || all) { // at once, before the child has claimed its handoff, and for stops too (and with __WALL) siginfo_t si; errno = 0; printf("pid0\t%d\n", waitid(P_PID, 0, &si, WEXITED) < 0 && errno == EINVAL); memset(&si, 0, sizeof(si)); int r = waitid(P_ALL, 0, &si, WEXITED | WSTOPPED | all); 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", (int)si.si_uid); printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); return 0; } if (strcmp(argv[1], "twowaits") == 0) { if (pipe(two_in) != 0 || pipe(two_out) != 0) return 1; pthread_t first, release; pthread_create(&first, NULL, first_waiter, NULL); char c; if (read(two_out[0], &c, 1) != 1) return 1; // the first wait has reaped the forked child kill(pid, SIGTERM); // the program's: it ends, and its exit is ready usleep(1000000); pthread_create(&release, NULL, releaser, NULL); pid_t r = -1; for (int i = 0; i < 300 && (r = waitpid(-1, &status, WNOHANG)) == 0; i++) usleep(10000); printf("second\t%d\n", (int)r); printf("signal\t%d\n", r == pid && WIFSIGNALED(status) ? WTERMSIG(status) : -1); pthread_join(release, NULL); pthread_join(first, NULL); printf("child\t%d\n", (int)pid); return 0; } if (strcmp(argv[1], "stopclaim") == 0) { // stopped while its handoff is with the app (the fake spawner holds its reply), then continued: by // tgkill(), as a group's stop reaches it, where kill() would hold the signal for the program usleep(300000); syscall(SYS_tgkill, pid, pid, SIGSTOP); printf("stopped\t%d\n", waitpid(pid, &status, WUNTRACED) == pid && WIFSTOPPED(status)); usleep(1500000); // the reply has come meanwhile syscall(SYS_tgkill, pid, pid, SIGCONT); } if (strcmp(argv[1], "badopts") == 0) { usleep(1500000); // the program has exited by now // refused (WNOWAIT is waitid()'s) or selecting no forked child (__WCLONE alone): the exit stays errno = 0; printf("nowait\t%d\n", (int)wait4(-1, &status, WNOHANG | WNOWAIT, NULL) == -1 && errno == EINVAL); printf("clone\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WCLONE) != pid); printf("cloneall\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WCLONE) != pid); 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); usleep(300000); // the child is in a group of its own: not ours printf("ours\t%d\n", (int)waitpid(0, &status, WNOHANG)); } if (strcmp(argv[1], "kill") == 0) { printf("nohang\t%d\n", (int)waitpid(pid, &status, WNOHANG)); usleep(300000); printf("kill\t%d\n", kill(pid, SIGTERM)); } pid_t r = waitpid(group ? -pid : pid, &status, 0); printf("same\t%d\n", r == pid); if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); if (WIFSIGNALED(status)) printf("signal\t%d\n", WTERMSIG(status)); printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); return 0; } """ TARGET = r""" #include #include #include int main(int argc, char **argv) { if (strcmp(argv[1], "sleep") == 0) for (;;) pause(); return atoi(argv[1]); } """ # A worker's program that puts files where the hook keeps its parent's pidfd: it gets the numbers, the # hook makes no descriptor for it, and its parent stays known DUPOVER = r""" #define _GNU_SOURCE #include #include #include #include #include #include #include static int is(int fd, const char *what) { char path[64], target[64]; snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n <= 0) return 0; target[n] = 0; return strcmp(target, what) == 0; } static unsigned long fds(void) { // a sum over the open fds, the listing's own left out DIR *d = opendir("/proc/self/fd"); unsigned long sum = 0; struct dirent *e; while (d && (e = readdir(d))) { if (e->d_name[0] == '.' || atoi(e->d_name) == dirfd(d)) continue; sum = sum * 31 + (unsigned long)atoi(e->d_name) + 1; } if (d) closedir(d); return sum; } int main(void) { printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); int file = open("/dev/null", O_WRONLY); unsigned long before = fds(); dup2(file, 900); printf("nonew\t%d\n", fds() == before); printf("taken\t%d\n", is(900, "/dev/null")); printf("moved\t%d\n", (int)getppid()); dup2(file, 901); // the spare too: no pidfd left, /proc answers printf("again\t%d\n", (int)getppid()); long closed = syscall(SYS_close_range, 3, ~0U, 0); printf("closerange\t%ld\n", closed); printf("fileclosed\t%d\n", fcntl(file, F_GETFD) == -1); printf("closed\t%d\n", (int)getppid()); return 0; } """ # A worker's program with its table at fd 1000 (kept, as 900 and 901 are): a dup2() onto the pidfd # lets go of 900 while another thread's close_range(899, 2000) is between its parts, held there by the # hook's test gate. The kept fds above 900 stay open. PIDFD_PROBE = r""" #define _GNU_SOURCE #include #include #include #include #include #include #include int main(void) { errno = 0; long r = syscall(SYS_waitid, 3, INT_MAX, NULL, WEXITED | WNOHANG, NULL); printf("waitid\t%ld %d\n", r, errno); int pidfd = -1; errno = 0; r = syscall(SYS_clone, 0x00001000 | SIGCHLD, NULL, &pidfd, NULL, 0); if (r == 0) _exit(9); printf("clone\t%ld %d %d\n", r < 0 ? -1L : 1L, errno, pidfd); if (r > 0) waitpid((pid_t)r, NULL, 0); r = syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0); if (r == 0) _exit(7); int status = 0; printf("fork\t%d\n", r > 0 && waitpid((pid_t)r, &status, 0) == r && WIFEXITED(status) ? WEXITSTATUS(status) : -1); return 0; } """ # 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 #include #include #include #include #include #include #include #include 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 #include #include #include #include #include #include static int in[2], out[2]; static long closed = -2; static int is(int fd, const char *what) { char path[64], target[64]; snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n <= 0) return 0; target[n] = 0; return strncmp(target, what, strlen(what)) == 0; } static void *closer(void *unused) { (void)unused; char gate[48]; snprintf(gate, sizeof(gate), "%d %d %d", in[0], out[1], (int)syscall(SYS_gettid)); setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); closed = syscall(SYS_close_range, 899, 2000, 0); return NULL; } int main(void) { printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]") && is(1000, "/memfd:")); int file = open("/dev/null", O_WRONLY); if (dup2(file, 950) != 950) return 1; // an ordinary fd in the range, which it closes if (pipe(in) != 0 || pipe(out) != 0) return 1; pthread_t thread; pthread_create(&thread, NULL, closer, NULL); char c; if (read(out[0], &c, 1) != 1) return 1; // between the parts dup2(file, 900); if (write(in[1], "111", 3) != 3) return 1; // one for each part pthread_join(thread, NULL); printf("ranged\t%ld\n", closed); printf("ordinary\t%d\n", fcntl(950, F_GETFD) == -1); printf("spare\t%d\n", is(901, "anon_inode:[pidfd]")); printf("table\t%d\n", is(1000, "/memfd:")); printf("parent\t%d\n", (int)getppid()); return 0; } """ # A worker's program where one thread gives itself a table of its own (close_range() with # CLOSE_RANGE_UNSHARE) and takes the parent's pidfd number over with dup2(), then closes it there. # The first thread's table still holds the pidfd, which its close() leaves open. SPLIT = r""" #define _GNU_SOURCE #include #include #include #include #include #include #ifndef CLOSE_RANGE_UNSHARE #define CLOSE_RANGE_UNSHARE (1U << 1) #endif static int split_closed, own_closed; static int is(int fd, const char *what) { char path[64], target[64]; snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); ssize_t n = readlink(path, target, sizeof(target) - 1); if (n <= 0) return 0; target[n] = 0; return strcmp(target, what) == 0; } static void *splitter(void *file) { long r = syscall(SYS_close_range, 950, 950, CLOSE_RANGE_UNSHARE); split_closed = r == 0 && fcntl(950, F_GETFD) == -1; dup2(*(int *)file, 900); close(900); own_closed = fcntl(900, F_GETFD) == -1; return NULL; } int main(void) { printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); int file = open("/dev/null", O_WRONLY); if (dup2(file, 950) != 950) return 1; pthread_t thread; pthread_create(&thread, NULL, splitter, &file); pthread_join(thread, NULL); printf("split\t%d\n", split_closed); printf("own\t%d\n", own_closed); printf("shared\t%d\n", is(950, "/dev/null")); close(900); printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); printf("parent\t%d\n", (int)getppid()); return 0; } """ # A worker's program that checks its parent through the hook's pidfd (kept at 900) when it has one. # Built with NOFDS, it first takes every free descriptor, so that /proc cannot be read: the answer can # then only come from the pidfd, which needs no new one (and /proc's failure counts as alive). PIDFDPPID = r""" #include #include #include #include #include int main(void) { char target[64]; ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); target[n > 0 ? n : 0] = 0; printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); fflush(stdout); #ifdef NOFDS struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open setrlimit(RLIMIT_NOFILE, &lim); while (open("/dev/null", O_RDONLY) >= 0) {} printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); #endif printf("parent\t%d\n", (int)getppid()); return 0; } """ # A worker's program that says whether it has the hook's pidfd of its parent (kept at 900) and exits # with 9 at once. Built with NOFDS, it first takes every free descriptor (/proc then cannot be read). EXIT9 = r""" #include #include #include #include #include int main(void) { char target[64]; ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); target[n > 0 ? n : 0] = 0; printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); #ifdef NOFDS struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open setrlimit(RLIMIT_NOFILE, &lim); while (open("/dev/null", O_RDONLY) >= 0) {} printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); #endif fflush(stdout); return 9; } """ # An unlisted program that execs the next one, as env and shell wrappers do WRAP = r""" #include int main(int argc, char **argv) { if (argc < 3) return 2; execv(argv[1], argv + 2); // wrap PATH ARGV0 ARGS... return 127; } """ class FakeSpawner(threading.Thread): """Stands in for the app's spawn socket: runs the program and reports its exit into the table.""" def __init__(self, name, prefix, root, reports=True, delay=0): super().__init__(daemon=True) self.delay = delay # seconds before the reply: the forked child waits with its entry claimed self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.bind("\0" + name) self.sock.listen(4) self.prefix = prefix self.root = root self.reports = reports # False: as an app that died with its worker, no exit report self.requests = [] # The programs it ran, as pidfds: ended with the test whatever becomes of them, and never another # process given a pid of theirs once they have been reaped. A program it could not have one for # is never run (failures says so); none is started once the ending has begun (closed). self.pidfds = [] self.failures = [] self.closed = False self.lock = threading.Lock() def run(self): while True: try: conn, _ = self.sock.accept() except OSError: return header = self.read(conn, 4) payload = self.read(conn, struct.unpack(">I", header)[0]) if header else b"" if not payload: conn.close() continue request = json.loads(payload) fds = [] while len(fds) < len(request["fds"]) + 1: data, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"]) fds.extend(chunk) if not data: break # the client went away between chunks if len(fds) < len(request["fds"]) + 1: for fd in fds: os.close(fd) conn.close() continue self.requests.append(request) table = fds[request["table"]] program = str(self.root) + request["file"] if self.delay: threading.Event().wait(self.delay) # As a worker does: a process whose pid goes back first, which runs the program only # once the hook takes it on with "go" with self.lock: pid, pidfd = -1, None if not self.closed: gate_r, gate_w = os.pipe() pid = os.fork() if pid == 0: os.close(gate_w) if os.read(gate_r, 1) == b"1": argv = list(self.prefix) + [program] + request["argv"][1:] os.execv(argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0]), argv) os._exit(127) os.close(gate_r) try: pidfd = os.pidfd_open(pid) self.pidfds.append(pidfd) except (AttributeError, OSError) as error: self.failures.append("no pidfd for a worker: %s" % error) went = False try: if pidfd is not None: conn.sendall(b"pid %d\n" % pid) went = not request.get("ack") or self.read(conn, 3) == b"go\n" if went and request.get("ack"): conn.sendall(b"ok\n") # the app's last word, before the worker may run it if went: os.write(gate_w, b"1") except OSError: went = False # the fixture went away mid-handshake finally: for fd in fds: if fd != table: os.close(fd) conn.close() if pid > 0: os.close(gate_w) # a worker not told to go ends at once if not went: if pid > 0: os.waitpid(pid, 0) os.close(table) continue threading.Thread(target=self.report if self.reports else self.reap, args=(pid, table, request), daemon=True).start() @staticmethod def read(conn, size): data = b"" while len(data) < size: more = conn.recv(size - len(data)) if not more: return b"" # the client went away data += more return data @staticmethod def reap(pid, table, request): os.waitpid(pid, 0) os.close(table) @staticmethod def report(pid, table, request): code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) status = (-code) & 0x7F if code < 0 else (code & 0xFF) << 8 # as GuestWorkers.reportExit: one write of the status and the child it is for; the hook # moves the entry to exited itself entry = 64 + request["slot"] * 64 os.pwrite(table, struct.pack(" 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") 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_near_the_limit_a_quick_tool_is_not(self): # sed, grep, sort...: a few milliseconds of work, not an app process of their own sed = self.root / "bin/sed" if not sed.exists(): shutil.copy(self.root / "bin/target", sed) result, requests, out = self.run_parent("wait", "3", "/bin/sed", handoff="other", pressure=0, as_shell=True) self.assertEqual([], requests) self.assertEqual(self.child_status, result.get("exit"), out.stdout) def test_near_the_limit_a_quick_tool_named_only_in_an_argument_is_handed_off(self): # only the program itself counts: "target ... sed" is not sed result, requests, out = self.run_parent("manyargs", "7", "sed", handoff="other", pressure=0, as_shell=True) self.assertEqual(1, len(requests), out.stderr) def test_near_the_limit_a_launch_naming_steam_in_any_argument_is_not(self): # as "env ... /path/Steam/steamrtarm64/steam", with the path after 32 other arguments result, requests, out = self.run_parent("manyargs", "3", "/root/.local/share/Steam/steamrtarm64/steam", handoff="other", pressure=0, as_shell=True) self.assertEqual([], requests) self.assertEqual("1", result.get("same"), out.stdout) self.assertEqual(self.child_status, result.get("exit"), out.stdout) def test_a_wait_of_another_thread_with_wnothread_does_not_take_the_program(self): result, requests, out = self.run_parent("nothread", "7") self.assertEqual(1, len(requests), out.stderr) self.assertEqual("-1", result.get("other"), out.stdout) self.assertEqual("-1", result.get("otherpid"), out.stdout) self.assertEqual("-1", result.get("otherwait3"), out.stdout) self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), out.stdout) def test_a_table_given_up_again_and_again_costs_one_fd(self): if self.child_status != "3": self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc)") result, requests, out = self.run_parent("prepcloseheld", "5", extra_env={"DDH_TEST_LATE_TABLE": "1"}) self.assertEqual("1", result.get("tables"), out.stdout + out.stderr) # the given-up table's number, closed by the close and then the program's own file, stays its self.assertEqual("1", result.get("freed800"), out.stdout) self.assertEqual("1", result.get("mine800"), out.stdout) self.assertEqual("5", result.get("again"), out.stdout) self.assertEqual("1", result.get("table"), out.stdout) self.assertEqual(1, len(requests), out.stderr) def test_a_waitid_nowait_reports_no_child_whose_entry_went_meanwhile(self): result, requests, out = self.run_parent("nowaitpeek", "sleep") self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("taken"), out.stdout + out.stderr) self.assertEqual("1", result.get("echild"), out.stdout) self.assertEqual("0", result.get("lookedpid"), out.stdout) def test_a_forked_child_waits_for_no_close_of_its_parents(self): # no table in the parent (a close held across its tries), so the child makes one result, requests, out = self.run_parent("forkclose", "3", extra_env={"DDH_TEST_LATE_TABLE": "1"}) self.assertEqual(1, len(requests), out.stdout + out.stderr) self.assertEqual("3", result.get("child"), out.stdout) 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_stop_seen_before_the_child_hands_off_reports_its_program(self): result, requests, out = self.run_parent("stoppeek", "6", delay=1.0) self.assertEqual(str(os.CLD_STOPPED), result.get("peeked"), out.stdout + out.stderr) # the look saw the stop self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("shimexited"), out.stdout + out.stderr) # the one wait that saw the stop reports the program's end, not a stop and not the forked child's self.assertEqual("1", result.get("waited"), out.stdout) self.assertEqual("0", result.get("stopped"), out.stdout) self.assertEqual("6", result.get("code"), out.stdout) def test_two_waits_report_a_handed_off_child_once(self): result, requests, out = self.run_parent("twowaits", "sleep") self.assertEqual(1, len(requests), out.stderr) child = result.get("child") self.assertEqual(child, result.get("second"), out.stdout) self.assertEqual(str(signal.SIGTERM.value), result.get("signal"), out.stdout) self.assertEqual("-1", result.get("first"), out.stdout) def test_a_stop_while_the_handoff_is_claimed_keeps_the_claim(self): result, requests, out = self.run_parent("stopclaim", "6", delay=1.0) self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("stopped"), out.stdout) self.assertEqual("1", result.get("same"), out.stdout) self.assertEqual("6", result.get("exit"), out.stdout) def test_a_wnothread_wait_a_handler_interrupts_keeps_to_its_thread(self): result, requests, out = self.run_parent("nothreadnested", "7") self.assertEqual(2, len(requests), out.stderr) self.assertEqual("1", result.get("eintr"), out.stdout) self.assertEqual("1", result.get("ownend"), out.stdout) # the other thread's child is still its own self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), out.stdout) def test_a_wait_with_options_wait4_refuses_or_clone_only_leaves_the_exit(self): result, requests, out = self.run_parent("badopts", "5") self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("nowait"), out.stdout) self.assertEqual("1", result.get("clone"), out.stdout) self.assertEqual("1", result.get("cloneall"), out.stdout) self.assertEqual("1", result.get("intmin"), out.stdout) self.assertEqual("1", result.get("same"), out.stdout) self.assertEqual("5", result.get("exit"), out.stdout) def test_a_posix_spawn_of_a_file_with_only_the_elf_magic_fails_as_it_would(self): stub = self.root / "bin/stub" stub.write_bytes(b"\x7fELF") stub.chmod(0o755) result, requests, out = self.run_parent("spawn", "6", "/bin/stub", handoff="stub") self.assertEqual(0, out.returncode, out.stderr) self.assertEqual([], requests) self.assertEqual(str(errno.ENOEXEC), result.get("spawned"), out.stdout) self.assertNotIn("exit", result, out.stdout) self.assertNotIn("signal", result, out.stdout) def test_wnothread_child_goes_to_the_first_live_thread(self): # The forking thread and the main one both ended. Which thread the kernel gives the child to # (qemu-user has a thread of its own first) is what the same program shows without the hook. result, requests, out = self.run_parent("nothreadheir", "7") plain, _, plain_out = self.run_parent("nothreadheir", "7", hook=False) # the waits ran only after the main thread had ended, in both runs self.assertEqual("1", result.get("mainended"), out.stdout) self.assertEqual("1", plain.get("mainended"), plain_out.stdout) self.assertEqual(1, len(requests), out.stderr) self.assertEqual(plain.get("bystander"), result.get("bystander"), (out.stdout, plain_out.stdout)) self.assertEqual(plain.get("own"), result.get("own"), (out.stdout, plain_out.stdout)) if result.get("own") == "1": self.assertEqual("7", result.get("exit"), out.stdout) def test_wnothread_takes_a_child_whose_thread_ended(self): # the kernel gives it to the main thread: another thread's wait does not take it result, requests, out = self.run_parent("nothreadgone", "7") self.assertEqual(1, len(requests), out.stderr) self.assertEqual("-1", result.get("bystander"), out.stdout) self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", result.get("exit"), out.stdout) def test_a_late_record_of_a_spawned_child_keeps_a_handoffs_owner(self): self.late_record() def test_a_late_record_keeps_an_owner_whose_start_was_not_read(self): # the fork's child could not read its own start time: its record has none to be told by self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}) def test_a_late_record_reading_the_new_childs_start_keeps_its_owner(self): # made while the later child, which could not read its own start, still hands its program off self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="live") def test_a_late_record_before_the_new_child_execs_keeps_its_owner(self): # made once the later child, which could not read its own start, has recorded itself and # before it execs: no handoff of it yet to tell by self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="early") def late_record(self, env=None, live=None): if self.child_status != "3": self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so nothing can be spawned") # the pid has to be given again, which only a pid namespace of the test's own allows if not os.environ.get("DDH_TEST_PIDNS"): unshare = shutil.which("unshare") if not unshare or subprocess.run([unshare, "-Urpf", "--mount-proc", "true"], capture_output=True).returncode: self.skipTest("no user and pid namespace for this test") # this module by the name it was loaded as, from the repository's root or this directory here, top = Path(__file__).resolve().parent, Path(__file__).resolve().parents[2] path = os.pathsep.join([str(here), str(top)] + ([os.environ["PYTHONPATH"]] if os.environ.get("PYTHONPATH") else [])) out = subprocess.run([unshare, "-Urpf", "--mount-proc", sys.executable, "-m", "unittest", self.id()], env={**os.environ, "DDH_TEST_PIDNS": "1", "PYTHONPATH": path}, cwd=top, capture_output=True, text=True, timeout=300) self.assertEqual(0, out.returncode, out.stderr) self.assertNotIn("skipped", out.stderr, out.stderr) return result, requests, out = self.run_parent("laterecord" + (live or ""), "sleep", extra_env=env, delay=1.0 if live == "live" else 0) self.assertEqual("1", result.get("reused"), out.stdout + out.stderr) if live == "live": self.assertEqual("1", result.get("claimed"), out.stdout) if live == "early": self.assertEqual("1", result.get("recorded"), out.stdout) self.assertEqual("0", result.get("spawned"), out.stdout) self.assertEqual("1", result.get("reaped"), out.stdout) self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("1", result.get("ended"), out.stdout) def test_wnothread_takes_a_program_started_through_a_wrapper(self): if self.child_status != "3": self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so the wrapper cannot run") # the hook names its own path inside the guest's root for the programs it execs rooted = self.root / str(self.hook).lstrip("/") rooted.parent.mkdir(parents=True, exist_ok=True) shutil.copy(self.hook, rooted) result, requests, out = self.run_parent("nothreadwrap", "7") self.assertEqual(1, len(requests), out.stderr) self.assertEqual("-1", result.get("other"), out.stdout) self.assertEqual("-1", result.get("otherpid"), out.stdout) self.assertEqual("1", result.get("own"), out.stdout) self.assertEqual("7", 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) self.assertEqual(self.child_status, result.get("exit"), out.stdout) def ppid_in_worker(self, parent): # as a worker's own program: DDH_WORKER_PID is its pid, DDH_TABLE names the process that forked it tmp = Path(self.tmp.name) probe = tmp / "ppid" if not probe.exists(): (tmp / "ppid.c").write_text('#include \n#include \nint main(void) { printf("%d", (int)getppid()); return 0; }\n') subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "ppid.c")], check=True) env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)} if parent is not None: env["DDH_TABLE"] = "3:0:%d:0" % parent settings = " ".join("-E %s=%s" % item for item in env.items()) if self.prefix else \ " ".join("%s=%s" % item for item in env.items()) worker = "-E DDH_WORKER_PID=$$" if self.prefix else "DDH_WORKER_PID=$$" runner = " ".join(self.prefix) + " " + settings + " " + worker if self.prefix else "env " + settings + " " + worker out = subprocess.run(["sh", "-c", "exec %s %s" % (runner, probe)], capture_output=True, text=True, timeout=60) return out.stdout.strip() def test_a_handed_off_programs_parent_is_the_process_that_forked_it(self): forker = subprocess.Popen(["sleep", "60"]) self.addCleanup(forker.wait) self.addCleanup(forker.kill) self.assertEqual(str(forker.pid), self.ppid_in_worker(forker.pid)) def test_a_handed_off_program_whose_forking_process_is_gone_has_init_as_parent(self): self.assertEqual("1", self.ppid_in_worker(4194303)) def test_a_handed_off_program_whose_forking_process_exited_unreaped_has_init_as_parent(self): forker = subprocess.Popen(["true"]) self.addCleanup(forker.wait) stat = Path("/proc/%d/stat" % forker.pid) pause = threading.Event() for _ in range(100): if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": break pause.wait(0.05) # exited and not reaped (Popen reaps only in wait() or poll()) self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) self.assertEqual("1", self.ppid_in_worker(forker.pid)) self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) def test_through_its_pidfd_a_handed_off_programs_live_parent_is_its_parent(self): parent, result, out = self.run_worker_program("pidfdlive", PIDFDPPID) self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) self.assertEqual(str(parent), result.get("parent"), out.stdout) def test_through_its_pidfd_a_handed_off_programs_unreaped_parent_is_gone(self): forker = subprocess.Popen(["true"]) self.addCleanup(forker.wait) stat = Path("/proc/%d/stat" % forker.pid) pause = threading.Event() for _ in range(100): if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": break pause.wait(0.05) self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) # a pidfd opens for an exited parent that is not reaped, and reads as exited; /proc cannot be # read meanwhile (no free fd), where a failure counts as alive: only the pidfd gives init _, result, out = self.run_worker_program("pidfdzombie", "#define NOFDS 1\n" + PIDFDPPID, parent=forker.pid) self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) self.assertEqual("1", result.get("nofds"), out.stdout) self.assertEqual("1", result.get("parent"), out.stdout) self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) def test_without_a_pidfd_a_handed_off_programs_gone_parent_is_init(self): # no process has the pid, so no pidfd: /proc answers _, result, out = self.run_worker_program("pidfdgone", PIDFDPPID, parent=4194303) self.assertEqual("0", result.get("pidfd"), out.stdout + out.stderr) self.assertEqual("1", result.get("parent"), out.stdout) def test_wnohang_reports_a_ready_child_while_a_handoffs_forked_child_runs(self): result, requests, out = self.run_parent("nohangtwo", "3") self.assertEqual(1, len(requests), out.stderr) # the state this is about: the program's exit in the table, its forked child alive, the other ready self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) self.assertEqual("1", result.get("bwaitable"), out.stdout) self.assertEqual("1", result.get("aheld"), out.stdout) self.assertEqual("1", result.get("first"), out.stdout) self.assertEqual("5", result.get("firstexit"), out.stdout) self.assertEqual("1", result.get("second"), out.stdout) self.assertEqual("3", result.get("exit"), out.stdout) self.assertEqual("-1", result.get("again"), out.stdout) def test_wnohang_reports_a_ready_handoff_while_another_ones_forked_child_runs(self): result, requests, out = self.run_parent("nohangtwohanded", "3") self.assertEqual(2, len(requests), out.stderr) self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) self.assertEqual("1", result.get("bwaitable"), out.stdout) self.assertEqual("1", result.get("aheld"), out.stdout) self.assertEqual("1", result.get("first"), out.stdout) self.assertEqual("5", result.get("firstexit"), out.stdout) self.assertEqual("1", result.get("second"), out.stdout) self.assertEqual("3", result.get("exit"), out.stdout) self.assertEqual("-1", result.get("again"), out.stdout) def test_wnohang_for_the_group_reports_its_ready_child_while_a_forked_child_runs(self): result, requests, out = self.run_parent("nohangtwogroup", "3") self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) self.assertEqual("1", result.get("bwaitable"), out.stdout) self.assertEqual("1", result.get("aheld"), out.stdout) # the group's ready child, not the exited one of another group self.assertEqual("1", result.get("first"), out.stdout) self.assertEqual("5", result.get("firstexit"), out.stdout) self.assertEqual("1", result.get("second"), out.stdout) self.assertEqual("3", result.get("exit"), out.stdout) self.assertEqual("6", result.get("other"), out.stdout) self.assertEqual("-1", result.get("again"), out.stdout) def start_worker_exit(self, name, parent, state, nofds=False, child_start=1 << 62): # A worker's program that exits with 9 at once, its entry (slot 0) given parent and state, as # the parent's check of a gone worker leaves it while it holds it (TAKEN). With nofds it first # takes every free descriptor, so that /proc cannot be read when it exits. A child_start before # the parent's start leaves it without the parent's pidfd. Returns the run and the table. tmp = Path(self.tmp.name) probe = tmp / name (tmp / (name + ".c")).write_text(("#define NOFDS 1\n" if nofds else "") + EXIT9) subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / (name + ".c"))], check=True) table = os.memfd_create("ddh-test-table", 0) self.addCleanup(os.close, table) os.ftruncate(table, 64 + 1024 * 64) os.pwrite(table, struct.pack("