mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
1269 lines
57 KiB
Python
1269 lines
57 KiB
Python
import errno
|
|
import fcntl
|
|
import json
|
|
import os
|
|
import shutil
|
|
import signal
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import termios
|
|
import threading
|
|
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 <stdio.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
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 <errno.h>
|
|
#include <fcntl.h>
|
|
#include <pthread.h>
|
|
#include <signal.h>
|
|
#include <spawn.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/syscall.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
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);
|
|
}
|
|
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;
|
|
}
|
|
|
|
// live: 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
|
|
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;
|
|
pid_t pid = fork();
|
|
if (pid == 0) {
|
|
execl("/bin/target", "target", arg, (char *)NULL);
|
|
_exit(127);
|
|
}
|
|
printf("reused\t%d\n", pid == first);
|
|
int err = -1;
|
|
if (live) {
|
|
usleep(300000); // its handoff is with the app
|
|
if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) 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);
|
|
}
|
|
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 there: past the hook's wait for the close
|
|
|
|
static void *prep_release(void *unused) {
|
|
(void)unused;
|
|
// once the first fork has made the table's fd, while it waits for the close to end
|
|
char target[64];
|
|
for (int i = 0; i < 1000; i++) {
|
|
ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1);
|
|
if (n > 0 && (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) == 0)) break;
|
|
usleep(1000);
|
|
}
|
|
usleep(prep_hold_ms * 1000);
|
|
if (write(prep_in[1], "1", 1) != 1) _exit(122);
|
|
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;
|
|
}
|
|
|
|
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) {
|
|
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], "laterecord") == 0) return late_record(argv[2], 0);
|
|
if (strcmp(argv[1], "laterecordlive") == 0) return late_record(argv[2], 1);
|
|
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);
|
|
}
|
|
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) return 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);
|
|
}
|
|
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);
|
|
}
|
|
printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
|
}
|
|
char target[64];
|
|
ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1);
|
|
if (n > 0) target[n] = 0;
|
|
printf("table\t%d\n", n > 0 && strncmp(target, "/memfd:ddnatv-handoff", 21) == 0);
|
|
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);
|
|
}
|
|
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);
|
|
}
|
|
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 <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
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 <dirent.h>
|
|
#include <fcntl.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/syscall.h>
|
|
#include <unistd.h>
|
|
|
|
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.
|
|
DUPRACE = r"""
|
|
#define _GNU_SOURCE
|
|
#include <fcntl.h>
|
|
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/syscall.h>
|
|
#include <unistd.h>
|
|
|
|
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;
|
|
}
|
|
"""
|
|
|
|
# An unlisted program that execs the next one, as env and shell wrappers do
|
|
WRAP = r"""
|
|
#include <unistd.h>
|
|
|
|
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 = []
|
|
|
|
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"
|
|
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)
|
|
conn.sendall(b"pid %d\n" % pid)
|
|
went = not request.get("ack") or self.read(conn, 3) == b"go\n"
|
|
for fd in fds:
|
|
if fd != table:
|
|
os.close(fd)
|
|
if went:
|
|
if request.get("ack"):
|
|
conn.sendall(b"ok\n") # the app's last word, before the worker may run it
|
|
os.write(gate_w, b"1")
|
|
conn.close()
|
|
os.close(gate_w)
|
|
if not went:
|
|
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("<ii", status, request["child"]), entry + 32)
|
|
os.close(table)
|
|
os.kill(request["parent"], signal.SIGCHLD)
|
|
|
|
|
|
class NativeHookHandoffTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.cc, cls.prefix = runner()
|
|
if cls.cc is None:
|
|
raise unittest.SkipTest("no aarch64 compiler and runner")
|
|
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
|
tmp = Path(cls.tmp.name)
|
|
cls.hook = tmp / "hook.so"
|
|
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
|
(tmp / "parent.c").write_text(PARENT)
|
|
cls.parent = tmp / "parent"
|
|
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.parent), str(tmp / "parent.c")], check=True)
|
|
cls.root = tmp / "root"
|
|
(cls.root / "bin").mkdir(parents=True)
|
|
(tmp / "target.c").write_text(TARGET)
|
|
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/target"), str(tmp / "target.c")], check=True)
|
|
(tmp / "wrap.c").write_text(WRAP)
|
|
subprocess.run([cls.cc, "-O1", "-o", str(cls.root / "bin/wrap"), str(tmp / "wrap.c")], check=True)
|
|
# What a child here gets from exec'ing an aarch64 program: 3 where the kernel runs them
|
|
# (binfmt_misc with qemu-user), 127 on a plain x86 runner, which does not. A handed-off program is
|
|
# started by the fake spawner through the runner itself either way.
|
|
(tmp / "execs.c").write_text(EXEC_PROBE)
|
|
subprocess.run([cls.cc, "-static", "-O1", "-o", str(tmp / "execs"), str(tmp / "execs.c")], check=True)
|
|
probe = subprocess.run(list(cls.prefix or []) + [str(tmp / "execs"), str(cls.root / "bin/target")],
|
|
capture_output=True, text=True, timeout=60)
|
|
assert probe.returncode == 0 and probe.stdout.strip() in ("3", "127"), (probe.returncode, probe.stdout, probe.stderr)
|
|
cls.child_status = probe.stdout.strip()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.tmp.cleanup()
|
|
|
|
def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False,
|
|
delay=0, extra_env=None):
|
|
name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook)
|
|
spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay)
|
|
spawner.start()
|
|
self.addCleanup(spawner.sock.close)
|
|
hook_env = {"DDNATV_ROOT": str(self.root), "DD_SPAWN": name, "DD_HANDOFF": handoff}
|
|
if hook:
|
|
hook_env["LD_PRELOAD"] = str(self.hook)
|
|
if pressure is not None:
|
|
hook_env["DD_HANDOFF_PRESSURE"] = str(pressure)
|
|
hook_env.update(extra_env or {})
|
|
if "-L" in (self.prefix or []):
|
|
# a dynamic program a child execs runs through binfmt_misc, whose qemu-user takes its sysroot from here
|
|
hook_env["QEMU_LD_PREFIX"] = self.prefix[self.prefix.index("-L") + 1]
|
|
env = {k: v for k, v in os.environ.items() if k not in hook_env}
|
|
prefix, parent = list(self.prefix or []), str(self.parent)
|
|
if as_shell:
|
|
# the hook tells a shell's child by its parent's name (qemu-user takes the program's)
|
|
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / "bash"
|
|
shell.parent.mkdir(exist_ok=True)
|
|
shutil.copy(parent, shell)
|
|
parent = str(shell)
|
|
if prefix:
|
|
cmd = prefix + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
|
else:
|
|
cmd = []
|
|
env.update(hook_env)
|
|
stdin, stderr, ctty = None, subprocess.PIPE, None
|
|
passed = ()
|
|
if terminal:
|
|
# as a shell's foreground job: the controlling terminal of the parent's session as stdin
|
|
# (terminal=True); as stderr with stdin a pipe, /dev/null or a file ("pipe", "null",
|
|
# "file"); or on no standard fd at all, stdin a pipe ("hidden")
|
|
master, slave = os.openpty()
|
|
self.addCleanup(os.close, master)
|
|
self.addCleanup(os.close, slave)
|
|
if terminal is True:
|
|
stdin, fd = slave, 0
|
|
elif terminal == "hidden":
|
|
stdin, fd, passed = subprocess.PIPE, slave, (slave,)
|
|
else:
|
|
if terminal == "file":
|
|
data = Path(self.tmp.name) / "input.txt"
|
|
data.write_text("input\n")
|
|
stdin = open(data)
|
|
self.addCleanup(stdin.close)
|
|
else:
|
|
stdin = subprocess.PIPE if terminal == "pipe" else subprocess.DEVNULL
|
|
stderr, fd = slave, 2
|
|
|
|
def ctty():
|
|
os.setsid()
|
|
fcntl.ioctl(fd, termios.TIOCSCTTY, 0)
|
|
given = {"input": ""} if stdin == subprocess.PIPE else {"stdin": stdin}
|
|
# Without a terminal of its own, a session of its own: run from a terminal's foreground job, the
|
|
# fixture would otherwise be that job too, which keeps its children local near the limit.
|
|
out = subprocess.run(cmd + [parent, *argv], env=env, stdout=subprocess.PIPE, stderr=stderr, preexec_fn=ctty,
|
|
start_new_session=not terminal, pass_fds=passed, text=True, timeout=120, **given)
|
|
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
|
|
return result, spawner.requests, out
|
|
|
|
def test_a_program_gone_without_any_report_is_reported_killed(self):
|
|
# its worker is gone and nobody reports how it ended (the app died with it): SIGKILL, after
|
|
# the grace the app's report would have had
|
|
result, requests, out = self.run_parent("wait", "7", reports=False)
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual(str(int(signal.SIGKILL)), result.get("signal"), out.stdout)
|
|
|
|
def test_the_parent_waits_for_the_handed_off_program(self):
|
|
result, requests, out = self.run_parent("wait", "7")
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("/bin/target", requests[0]["file"])
|
|
self.assertEqual(["target", "7"], requests[0]["argv"])
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual("7", result.get("exit"), out.stdout)
|
|
self.assertEqual("-1", result.get("again"), out.stdout)
|
|
|
|
def test_a_child_that_closed_its_inherited_fds_is_handed_off(self):
|
|
result, requests, out = self.run_parent("closefds", "5")
|
|
if result.get("closerange") != "0":
|
|
self.skipTest("close_range does not work here: %s" % result.get("closerange"))
|
|
self.assertEqual("1", result.get("closed"), out.stdout)
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual("5", result.get("exit"), out.stdout)
|
|
|
|
def test_a_posix_spawn_is_handed_off(self):
|
|
result, requests, out = self.run_parent("spawn", "6")
|
|
self.assertEqual("0", result.get("spawned"), out.stdout)
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual(["target", "6"], requests[0]["argv"])
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual("6", result.get("exit"), out.stdout)
|
|
|
|
def test_a_posix_spawn_of_a_missing_program_fails_as_it_would(self):
|
|
# posix_spawn() returns the exec's error, even with closefrom(3) among the file actions
|
|
result, requests, out = self.run_parent("spawn", "6", "/bin/missing", handoff="missing")
|
|
self.assertEqual(0, out.returncode, out.stderr)
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(str(errno.ENOENT), result.get("spawned"), out.stdout)
|
|
self.assertNotIn("exit", result, out.stdout)
|
|
self.assertNotIn("signal", result, out.stdout)
|
|
|
|
def test_a_posix_spawn_of_a_missing_program_not_listed_is_unchanged(self):
|
|
# As without the hook: ENOENT natively; qemu-user, which runs glibc's vfork-style spawn child
|
|
# as a separate process, gets 0 and an exit status of 127.
|
|
result, requests, out = self.run_parent("spawn", "6", "/bin/missing", handoff="other")
|
|
plain, _, plain_out = self.run_parent("spawn", "6", "/bin/missing", handoff="other", hook=False)
|
|
self.assertEqual(0, out.returncode, out.stderr)
|
|
self.assertEqual(0, plain_out.returncode, plain_out.stderr)
|
|
self.assertIn("spawned", result, out.stdout)
|
|
self.assertIn("spawned", plain, plain_out.stdout)
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(plain.get("spawned"), result.get("spawned"), out.stdout + plain_out.stdout)
|
|
self.assertEqual(plain.get("exit"), result.get("exit"), out.stdout + plain_out.stdout)
|
|
|
|
def test_a_posix_spawn_of_a_script_without_its_interpreter_fails_as_it_would(self):
|
|
script = self.root / "bin/orphan"
|
|
script.write_text("#!/bin/no-such-interpreter\n")
|
|
script.chmod(0o755)
|
|
result, requests, out = self.run_parent("spawn", "6", "/bin/orphan", handoff="orphan")
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(str(errno.ENOENT), result.get("spawned"), out.stdout)
|
|
|
|
def test_a_wait_for_a_group_takes_only_that_groups_children(self):
|
|
result, requests, out = self.run_parent("group", "4")
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("-1", result.get("ours"), out.stdout)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual("4", result.get("exit"), out.stdout)
|
|
|
|
def test_kill_reaches_the_program_and_its_signal_is_reported(self):
|
|
result, requests, out = self.run_parent("kill", "sleep")
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("0", result.get("nohang"), out.stdout)
|
|
self.assertEqual("0", result.get("kill"), out.stdout)
|
|
self.assertEqual(str(int(signal.SIGTERM)), result.get("signal"), out.stdout)
|
|
|
|
def test_waitid_for_exits_and_stops_reports_the_program(self):
|
|
result, requests, out = self.run_parent("waitid", "7")
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("1", result.get("pid0"), out.stdout)
|
|
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(str(os.getuid()), result.get("uid"), out.stdout)
|
|
self.assertEqual("-1", result.get("again"), out.stdout)
|
|
|
|
def test_waitid_with_wall_reports_the_program(self):
|
|
result, requests, out = self.run_parent("waitidall", "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_waitid_for_a_child_not_listed_is_the_kernels(self):
|
|
result, requests, out = self.run_parent("waitid", "3", handoff="other")
|
|
self.assertEqual([], requests)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual(str(CLD_EXITED), result.get("code"), out.stdout)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
self.assertEqual(str(os.getuid()), result.get("uid"), out.stdout)
|
|
|
|
def test_near_the_limit_a_shells_child_is_handed_off(self):
|
|
result, requests, out = self.run_parent("wait", "7", handoff="other", pressure=0, as_shell=True)
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual(["target", "7"], requests[0]["argv"])
|
|
self.assertEqual("7", result.get("exit"), out.stdout)
|
|
|
|
def test_below_the_limit_a_shells_child_is_not(self):
|
|
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=1000, as_shell=True)
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
|
|
def test_near_the_limit_a_child_of_another_program_is_not(self):
|
|
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0)
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
|
|
def test_near_the_limit_a_foreground_pipe_reader_is_not(self):
|
|
# less in "cmd | less": stdin a pipe, the terminal on another fd
|
|
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="pipe")
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
|
|
def test_near_the_limit_a_foreground_job_reading_a_file_is_not(self):
|
|
# "less < file". Also "cmd < file &" from a shell without job control, which looks the same
|
|
# (the foreground group, a file on stdin): kept too, as a foreground reader must be.
|
|
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="file")
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
|
|
def test_near_the_limit_a_foreground_job_with_no_terminal_fd_is_not(self):
|
|
# "cmd | less > out 2> err": the controlling terminal on none of its standard fds
|
|
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="hidden")
|
|
self.assertEqual([], requests)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
|
|
def test_near_the_limit_a_job_reading_dev_null_is_handed_off(self):
|
|
# "cmd &" from a shell without job control: the foreground group, stdin /dev/null
|
|
result, requests, out = self.run_parent("wait", "7", handoff="other", pressure=0, as_shell=True, terminal="null")
|
|
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_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_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=True)
|
|
|
|
def late_record(self, env=None, live=False):
|
|
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("laterecordlive" if live else "laterecord", "sleep", extra_env=env,
|
|
delay=1.0 if live else 0)
|
|
self.assertEqual("1", result.get("reused"), out.stdout + out.stderr)
|
|
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 <stdio.h>\n#include <unistd.h>\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_any_other_program_has_its_real_parent(self):
|
|
self.assertEqual(str(os.getpid()), self.ppid_in_worker(None))
|
|
|
|
def run_worker_program(self, name, source, table_fd=None):
|
|
# As a worker's program with a table of its own: slot 0 for a child that started after any
|
|
# parent, which is a live process here. Returns the parent's pid, what the program printed
|
|
# and the run.
|
|
tmp = Path(self.tmp.name)
|
|
probe = tmp / name
|
|
(tmp / (name + ".c")).write_text(source)
|
|
subprocess.run([self.cc, "-O1", "-pthread", "-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("<i", 0x6464686F), 0)
|
|
os.pwrite(table, struct.pack("<q", 1 << 62), 64 + 40)
|
|
if table_fd is not None:
|
|
os.dup2(table, table_fd)
|
|
self.addCleanup(os.close, table_fd)
|
|
table = table_fd
|
|
forker = subprocess.Popen(["sleep", "60"])
|
|
self.addCleanup(forker.wait)
|
|
self.addCleanup(forker.kill)
|
|
env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root), "DDH_TABLE": "%d:0:%d:0" % (table, forker.pid)}
|
|
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,
|
|
pass_fds=(table,))
|
|
return forker.pid, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
|
|
|
|
def test_a_dup2_onto_the_parents_pidfd_while_a_close_range_runs_closes_no_kept_fd(self):
|
|
parent, result, out = self.run_worker_program("duprace", DUPRACE, table_fd=1000)
|
|
self.assertEqual(0, out.returncode, out.stderr)
|
|
self.assertEqual("1", result.get("kept"), out.stdout + out.stderr)
|
|
# the close_range() worked: an ordinary fd in its range is closed, the kept ones above 900 are not
|
|
self.assertEqual("0", result.get("ranged"), out.stdout)
|
|
self.assertEqual("1", result.get("ordinary"), out.stdout)
|
|
self.assertEqual("1", result.get("spare"), out.stdout)
|
|
self.assertEqual("1", result.get("table"), out.stdout)
|
|
self.assertEqual(str(parent), result.get("parent"), out.stdout)
|
|
|
|
def test_a_table_made_while_a_close_range_runs_stays_open(self):
|
|
# made by the first fork, as when making it at the start failed
|
|
result, requests, out = self.run_parent("prepclose", "4", extra_env={"DDH_TEST_LATE_TABLE": "1"})
|
|
self.assertEqual("0", result.get("ranged"), out.stdout + out.stderr)
|
|
self.assertEqual("1", result.get("table"), out.stdout)
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual("4", result.get("exit"), out.stdout)
|
|
|
|
def test_a_table_given_up_while_a_close_runs_past_the_wait_is_made_later(self):
|
|
if self.child_status != "3":
|
|
self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so the first runs nowhere")
|
|
# the close goes on past both tries of the first fork, whose child then runs here; the next
|
|
# fork makes the table
|
|
result, requests, out = self.run_parent("prepcloselate", "4", extra_env={"DDH_TEST_LATE_TABLE": "1"})
|
|
self.assertEqual("0", result.get("ranged"), out.stdout + out.stderr)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual("4", result.get("exit"), out.stdout)
|
|
self.assertEqual("4", result.get("again"), out.stdout)
|
|
self.assertEqual(1, len(requests), out.stderr)
|
|
self.assertEqual("1", result.get("table"), out.stdout)
|
|
|
|
def test_a_dup2_onto_the_parents_pidfd_makes_no_descriptor_and_keeps_the_parent(self):
|
|
parent, result, out = self.run_worker_program("dupover", DUPOVER)
|
|
self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr)
|
|
self.assertEqual("1", result.get("nonew"), out.stdout)
|
|
self.assertEqual("1", result.get("taken"), out.stdout)
|
|
# an ordinary fd in the range closed: the parent is still known after a real close_range()
|
|
self.assertEqual("0", result.get("closerange"), out.stdout)
|
|
self.assertEqual("1", result.get("fileclosed"), out.stdout)
|
|
for step in ("moved", "again", "closed"):
|
|
self.assertEqual(str(parent), result.get(step), out.stdout)
|
|
|
|
def test_a_program_not_listed_is_a_normal_child(self):
|
|
result, requests, out = self.run_parent("wait", "3", handoff="other")
|
|
self.assertEqual([], requests)
|
|
self.assertEqual("1", result.get("same"), out.stdout)
|
|
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|