import errno import json import os import shutil import signal import socket import struct import subprocess import tempfile import threading import unittest from pathlib import Path from tools.tests.test_usr2_preload import runner HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" PARENT = r""" #define _GNU_SOURCE #include #include #include #include #include #include #include #include extern char **environ; int main(int argc, char **argv) { pid_t pid; 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); execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } int status = 0; 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]); } """ 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): super().__init__(daemon=True) 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.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"] # 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" conn.close() for fd in fds: if fd != table: os.close(fd) if went: os.write(gate_w, b"1") os.close(gate_w) if not went: os.waitpid(pid, 0) os.close(table) continue threading.Thread(target=self.report, 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 report(pid, table, request): code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) status = (-code) & 0x7F if code < 0 else (code & 0xFF) << 8 entry = 64 + request["slot"] * 32 os.pwrite(table, struct.pack("