From 445a13abf4008556ac3d872b2b1efc5a3858ab6d Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:05:56 -0500 Subject: [PATCH] fix(session): three-step launch, tagged exit reports and lock-free popen and system children --- .../launcher/runtime/GuestWorkers.kt | 39 +++--- docs/phantom-processes.md | 9 +- tools/nativeguest/hook/exec.c | 64 +++++++--- tools/nativeguest/hook/handoff.c | 113 ++++++++++++------ tools/tests/test_native_hook_handoff.py | 11 +- tools/tests/test_native_hook_popen.py | 112 +++++++++++++++++ 6 files changed, 272 insertions(+), 76 deletions(-) create mode 100644 tools/tests/test_native_hook_popen.py diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index 5c3dcf26a1..eed453000b 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -53,12 +53,15 @@ open class GuestWorker : Service() { // poll() with a timeout counts as network I/O to StrictMode on the main thread android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX) val committed = runCatching { - val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() } - val ready = Os.poll(arrayOf(poll), GO_TIMEOUT_MS) - val got = if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1 - why = "poll $ready revents ${poll.revents} read $got" - // and the answer the app waits for before it reports the launch as started - got == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 + fun byte(): Int { + val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() } + val ready = Os.poll(arrayOf(poll), GO_TIMEOUT_MS) + return (if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1) + .also { why = "poll $ready revents ${poll.revents} read $it" } + } + // The commit, an answer, and the app's word that it has the answer: the app may + // have stopped waiting for it (and started the program another way) meanwhile. + byte() == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 && byte() == 1 }.getOrElse { why = it.toString(); false } go.close() if (committed) exec(argv, env, fds, targets, fillBinderFd) @@ -367,7 +370,10 @@ object GuestWorkers { } Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) val answer = StructPollfd().apply { fd = go[1].fileDescriptor; events = OsConstants.POLLIN.toShort() } - val accepted = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 + // then the word to run it: given only here, once its answer is in, so that a worker whose + // answer came too late never runs a program this call reports as not started + val accepted = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 && + Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 if (!accepted) { Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on") slot.started = false @@ -669,6 +675,9 @@ object GuestWorkers { if (!answered) { out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray()) out.flush() + } else { + // The hook's last word: the worker runs it, or nothing does and the hook runs it itself + runCatching { out.write(if (pid > 0) "ok\n".toByteArray() else "error not started\n".toByteArray()); out.flush() } } if (pid > 0 && wait) { exited.await() @@ -683,23 +692,23 @@ object GuestWorkers { } } - // Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 32-byte - // entries of int32 child, real, parent, state, status, ... - // Written only while the entry is still this program's (state CLAIMED or HANDED, its child, parent - // and worker): the parent may have reaped it and a later handoff taken the entry over meanwhile. + // Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 64-byte + // entries of int32 child, real, parent, state, ..., and at 32 the app's report: int32 status, child. + // The report is one 8-byte write tagged with the child it is for; only the hook changes an + // entry's state, so a report that lands after the entry went to another child is ignored there. private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int, child: Int, worker: Int) { runCatching { - val entry = 64L + slot * 32L + val entry = 64L + slot * 64L val head = java.nio.ByteBuffer.allocate(16).order(java.nio.ByteOrder.nativeOrder()) Os.pread(table.fileDescriptor, head, entry) val real = head.getInt(4) val state = head.getInt(12) if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || (state != 1 && state != 3)) return@runCatching - val word = java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.nativeOrder()) // An exit Android has no record of is reported as a failure, not as a signal. - Os.pwrite(table.fileDescriptor, word.putInt(0, if (status < 0) 1 shl 8 else status).also { it.rewind() }, entry + 16) - Os.pwrite(table.fileDescriptor, word.putInt(0, 2).also { it.rewind() }, entry + 12) + val report = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.nativeOrder()) + .putInt(0, if (status < 0) 1 shl 8 else status).putInt(4, child) + Os.pwrite(table.fileDescriptor, report, entry + 32) if (parent > 0) Process.sendSignal(parent, OsConstants.SIGCHLD) }.onFailure { Log.w(TAG, "could not report an exit to the guest's parent", it) } runCatching { table.close() } diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md index 124ce7b97f..8c96580d71 100644 --- a/docs/phantom-processes.md +++ b/docs/phantom-processes.md @@ -220,8 +220,13 @@ the pid translation described in B (the parent keeps the forked pid; `wait4`, `k environment, the working directory and every inheritable fd with its number, and a worker execs the program with those fds in place. The child records "my pid is now worker pid P" in a memfd table its parent created, and exits. In the parent, `wait4`/`waitpid`/`wait`/`wait3`/`waitid` and -`kill` treat the forked pid as P until P exits; the app writes P's exit status (from -`ApplicationExitInfo`) into the table and sends the parent `SIGCHLD`. The child's side is +`kill` treat the forked pid as P until P exits. P's hook writes its exit status into the table; for +a program that ends without `exit()` (a signal) the app writes a report tagged with the child it is +for (from `ApplicationExitInfo`), which the parent's hook takes once P is gone, and sends the parent +`SIGCHLD`. Only the hook moves an entry to "exited", by compare-and-swap. A launch takes three +answers: the hook's "go" once it has P's pid, the worker's answer to the app's commit, and the +app's "ok" once the worker runs the program; without any of them the program runs locally instead, +never twice. The child's side is vfork-safe (Python's subprocess execs under `vfork`). Details that mattered: - **Scripts:** the list also matches the `#!` interpreter (`python3` for `droiddeck-agent`). diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index e69aad8769..a5ad59209d 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -662,7 +662,10 @@ pid_t fork(void) { } ddh_prepare(); pid_t pid = orig_fork(); - if (pid == 0) ddh_drop_worker_binder(); + if (pid == 0) { + ddh_drop_worker_binder(); + ddh_forked(); + } // A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its // execve() is a real one (only read in the usual case, so no page is copied for it) if (pid == 0 && __atomic_load_n(&g_exec_rehearsal, __ATOMIC_RELAXED)) __atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELAXED); @@ -1339,6 +1342,7 @@ int system(const char *command) { int status = -1; pid_t pid = start_shell(command, -1, -1, &old, &intr, &quit, 0); + if (pid < 0) status = 127 << 8; // as glibc's system() when the shell could not be started if (pid > 0) { while (waitpid(pid, &status, 0) < 0) { if (errno != EINTR) { @@ -1370,28 +1374,52 @@ static pthread_mutex_t g_popen_lock = PTHREAD_MUTEX_INITIALIZER; static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask, const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams) { - pid_t pid = fork(); - if (pid != 0) return pid; - if (intr) sigaction(SIGINT, intr, NULL); - if (quit) sigaction(SIGQUIT, quit, NULL); - if (mask) sigprocmask(SIG_SETMASK, mask, NULL); + // Through posix_spawn(), as glibc does: its child only makes system calls. A forked child running + // the exec code here would take locks (the program's own malloc's among them) that another thread + // of a multithreaded caller may have held at fork(), and wait for them forever (Steam's popen()s). + posix_spawn_file_actions_t actions; + posix_spawnattr_t attr; + if (posix_spawn_file_actions_init(&actions) != 0) return -1; + if (posix_spawnattr_init(&attr) != 0) { + posix_spawn_file_actions_destroy(&actions); + return -1; + } + int err = 0; if (child_fd >= 0) { - if (child_fd == target_fd) { - fcntl(target_fd, F_SETFD, 0); - } else if (dup2(child_fd, target_fd) < 0) { - _exit(127); - } + // dup2 onto itself clears FD_CLOEXEC in the child (glibc 2.29 and later) + err = posix_spawn_file_actions_adddup2(&actions, child_fd, target_fd); } // POSIX: the streams of earlier popen() calls are not open in the new shell - if (close_popen_streams) { - for (struct ddnatv_popen *p = g_popen_streams; p; p = p->next) { - int fd = fileno(p->fp); - if (fd >= 0 && fd != target_fd) close(fd); - } + for (struct ddnatv_popen *p = g_popen_streams; !err && close_popen_streams && p; p = p->next) { + int fd = fileno(p->fp); + if (fd >= 0 && fd != target_fd) err = posix_spawn_file_actions_addclose(&actions, fd); } + short flags = 0; + if (!err && mask) { + posix_spawnattr_setsigmask(&attr, mask); + flags |= POSIX_SPAWN_SETSIGMASK; + } + // SIGINT and SIGQUIT as they were before system() ignored them: an exec keeps an ignored signal + // ignored and puts a handled one back to the default + sigset_t defaults; + sigemptyset(&defaults); + if (intr && intr->sa_handler != SIG_IGN) sigaddset(&defaults, SIGINT); + if (quit && quit->sa_handler != SIG_IGN) sigaddset(&defaults, SIGQUIT); + if (!err && (intr || quit)) { + posix_spawnattr_setsigdefault(&attr, &defaults); + flags |= POSIX_SPAWN_SETSIGDEF; + } + if (!err) err = posix_spawnattr_setflags(&attr, flags); + pid_t pid = -1; char *const argv[] = { (char *)"sh", (char *)"-c", (char *)command, NULL }; - ddnatv_execve("/bin/sh", argv, environ, 0); - _exit(127); + if (!err) err = posix_spawn(&pid, "/bin/sh", &actions, &attr, argv, environ); + posix_spawn_file_actions_destroy(&actions); + posix_spawnattr_destroy(&attr); + if (err) { + errno = err; + return -1; + } + return pid; } FILE *popen(const char *command, const char *type) { diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 532baad36a..c9bae634bc 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -5,8 +5,9 @@ // fork() + execve() can instead run as the main process of one of the app's worker processes: the // forked child sends the exec to the app (DD_SPAWN, an abstract socket) with its open fds, records // the worker's pid in a table it shares with its parent, and exits. For the parent nothing changes: -// wait*(), kill() and SIGCHLD treat the pid fork() returned as that program until it exits; the app -// writes its exit status into the table and sends the parent SIGCHLD. +// wait*(), kill() and SIGCHLD treat the pid fork() returned as that program until it exits; its exit +// status reaches the table from the program's hook, or for a signal from the app's report (see +// ddh_check_gone()), and the parent gets SIGCHLD. // // Only programs named in DD_HANDOFF (basenames separated by ':', or "*") are handed off. The child's // side runs where vfork() children run too, so it allocates nothing and writes no globals. @@ -26,9 +27,13 @@ struct ddh_entry { int32_t real; // the worker's pid int32_t parent; int32_t state; - int32_t status; // wait status, written by the app + int32_t status; // wait status int32_t reaped; // the parent has reaped the forked child itself int32_t pad[2]; + // The app's report of a program that died without exit() or _exit() (GuestWorkers.reportExit): + // the wait status and the child it is for, in one 8-byte write. Only this side changes state. + int32_t app[2] __attribute__((aligned(8))); + int32_t pad2[6]; }; struct ddh_table { @@ -87,31 +92,35 @@ static int ddh_is_binder(const char *target) { // The table the children write to, in a process of a session that hands programs off (DD_SPAWN). // One thread makes it; a fork() while another thread is making it goes without (its child runs here). +static int g_ddh_preparing; + +// In a forked child: the thread making the table did not come along, so the child may make its own. +static void ddh_forked(void) { __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELAXED); } + static void ddh_prepare(void) { - static int busy; if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN")) return; - if (__atomic_exchange_n(&busy, 1, __ATOMIC_ACQ_REL)) return; + if (__atomic_exchange_n(&g_ddh_preparing, 1, __ATOMIC_ACQ_REL)) return; if (g_ddh) { - __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); return; } int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); if (fd < 0) { ddh_prepare_failed("memfd_create"); - __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); return; } if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { ddh_prepare_failed("ftruncate"); close(fd); - __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); return; } struct ddh_table *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { ddh_prepare_failed("mmap"); close(fd); - __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); return; } // Out of the way of the numbers programs redirect, and kept open when a child closes every @@ -132,7 +141,7 @@ static void ddh_prepare(void) { g_ddh_fd = fd; g_ddh_owner = getpid(); __atomic_store_n(&g_ddh, p, __ATOMIC_RELEASE); - __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); } // Whether fd is still this table: a program may have put a file of its own at that number. @@ -398,12 +407,16 @@ static void ddh_report_exit(int status, void *from_exit) { struct ddh_entry *e = &g_ddh_report->e[g_ddh_report_slot]; // Still this program's entry: the parent frees it when the forked child dies before handing off // (and a later child may have it by now). + // From the state read (the forked child may still move it from CLAIMED to HANDED): a parent + // that freed the entry meanwhile keeps it freed. int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); - if ((st == DDH_HANDED || st == DDH_CLAIMED) && e->parent == g_ddh_report_parent && - (g_ddh_report_child <= 0 || e->child == g_ddh_report_child)) { + while ((st == DDH_HANDED || st == DDH_CLAIMED) && e->parent == g_ddh_report_parent && + (g_ddh_report_child <= 0 || e->child == g_ddh_report_child)) { e->status = (status & 0xff) << 8; - __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); - if (g_ddh_report_parent > 0) syscall(SYS_kill, g_ddh_report_parent, SIGCHLD); + if (__atomic_compare_exchange_n(&e->state, &st, DDH_EXITED, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { + if (g_ddh_report_parent > 0) syscall(SYS_kill, g_ddh_report_parent, SIGCHLD); + break; + } } ddh_linger(from_exit != NULL); ddh_unregister_group(); @@ -734,7 +747,7 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename static void ddh_try(const char *filename, char *const argv[], char *const envp[]) { struct ddh_table *table; int table_fd; - if (g_ddh && getpid() != g_ddh_owner) { + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) && getpid() != g_ddh_owner) { table = g_ddh; table_fd = g_ddh_fd; } else if (g_ddh_up && getppid() == g_ddh_up->pad[0]) { @@ -796,6 +809,7 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] pid_t real_group = getpgrp(); e->pad[1] = real_group; e->status = DDH_NO_STATUS; + __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); char cwd[PATH_MAX]; // The guest's name for it, else the kernel's (the worker's cd takes either). A directory with no // name (removed) cannot be sent: the exec stays here, in it. @@ -943,6 +957,20 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] if (strncmp(reply, "pid ", 4) == 0) pid = atol(reply + 4); // Without it the app does not let the worker run the program, and it runs here. if (pid > 0 && syscall(SYS_sendto, s, "go\n", 3, MSG_NOSIGNAL, NULL, 0) != 3) pid = -1; + // Then the app's last word, once the worker has taken the program on: "ok", or it + // never runs there and runs here. + if (pid > 0) { + char last[32]; + size_t have = 0; + while (have < sizeof(last) - 1) { + long r = syscall(SYS_read, s, last + have, 1); + if (r < 0 && errno == EINTR) continue; + if (r <= 0 || last[have] == '\n') break; + have++; + } + last[have] = 0; + if (strcmp(last, "ok") != 0) pid = -1; + } } } } @@ -966,7 +994,7 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] // ---- the parent's side ----------------------------------------------------------------------- static struct ddh_entry *ddh_find(pid_t child) { - if (!g_ddh || child <= 0) return NULL; + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || child <= 0) return NULL; pid_t me = getpid(); for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &g_ddh->e[i]; @@ -1003,7 +1031,7 @@ static int ddh_take_for(struct ddh_entry *e, pid_t pid) { } static int ddh_any_live(pid_t pid) { - if (!g_ddh) return 0; + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return 0; pid_t me = getpid(); for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &g_ddh->e[i]; @@ -1014,7 +1042,7 @@ static int ddh_any_live(pid_t pid) { } static struct ddh_entry *ddh_exited(pid_t pid) { - if (!g_ddh) return NULL; + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return NULL; pid_t me = getpid(); for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &g_ddh->e[i]; @@ -1025,7 +1053,7 @@ static struct ddh_entry *ddh_exited(pid_t pid) { // The entry of child while it is still handing its program off (its request is with the app). static struct ddh_entry *ddh_claiming(pid_t child) { - if (!g_ddh || child <= 0) return NULL; + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || child <= 0) return NULL; pid_t me = getpid(); for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &g_ddh->e[i]; @@ -1035,27 +1063,37 @@ static struct ddh_entry *ddh_claiming(pid_t child) { } // A worker that is gone with no status from the app (it crashed with the app): reported as killed. +// A worker that is gone: its program's end as the app reported it (a signal), else, with no report +// after a while (the app crashed with it), as killed. static void ddh_check_gone(void) { - if (!g_ddh) return; + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t) return; pid_t me = getpid(); for (int i = 0; i < DDH_SLOTS; i++) { - struct ddh_entry *e = &g_ddh->e[i]; + struct ddh_entry *e = &t->e[i]; if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_HANDED || e->parent != me) continue; if (syscall(SYS_kill, e->real, 0) == 0 || errno != ESRCH) continue; - // The app looks the status up for up to a second after the worker's death: wait longer. - struct timespec now; - clock_gettime(CLOCK_MONOTONIC, &now); - if (e->pad[0] == 0) { - e->pad[0] = (int32_t)now.tv_sec + 1; - continue; - } - if (now.tv_sec + 1 - e->pad[0] >= 3) { - // only where no status was written (the app's or the program's own wins) - int32_t none = DDH_NO_STATUS; - __atomic_compare_exchange_n(&e->status, &none, SIGKILL, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); - int expected = DDH_HANDED; - __atomic_compare_exchange_n(&e->state, &expected, DDH_EXITED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + int32_t report[2]; + uint64_t both = __atomic_load_n((uint64_t *)e->app, __ATOMIC_ACQUIRE); + memcpy(report, &both, sizeof(report)); + int32_t status = SIGKILL; + if (report[1] == e->child && report[1] != 0) { + status = report[0]; + } else { + // The app looks the status up for up to a second after the worker's death: wait longer. + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + if (e->pad[0] == 0) { + e->pad[0] = (int32_t)now.tv_sec + 1; + continue; + } + if (now.tv_sec + 1 - e->pad[0] < 3) continue; } + // Only this side moves HANDED to EXITED; a status the program wrote itself is kept. + int32_t none = DDH_NO_STATUS; + __atomic_compare_exchange_n(&e->status, &none, status, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + int expected = DDH_HANDED; + __atomic_compare_exchange_n(&e->state, &expected, DDH_EXITED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); } } @@ -1066,6 +1104,7 @@ static void ddh_release(struct ddh_entry *e, int *status) { e->reaped = 0; e->pad[0] = 0; e->pad[1] = 0; + __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); } @@ -1113,7 +1152,7 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { errno = ENOSYS; return -1; } - if (!g_ddh) return real(pid, status, options, ru); + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return real(pid, status, options, ru); // After a nap a signal interrupted, one more look before EINTR: the signal may be the SIGCHLD // that reports an exit. int interrupted = 0; @@ -1193,7 +1232,7 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { // An ordinary child asked for by pid: the real call, with all its options (stops, WNOWAIT). // As a waitpid() selector: a pid, -1 for any child, 0 for our group, -G for group G pid_t which = idtype == P_PID ? (pid_t)id : idtype == P_PGID ? (id == 0 ? 0 : -(pid_t)id) : -1; - if (!g_ddh || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || (idtype == P_PID ? !ddh_find(which) : !ddh_any_live(which))) return real(idtype, id, info, options); // Only exits are asked for here: answer through ddh_wait and describe the result as waitid does. @@ -1463,7 +1502,7 @@ int killpg(int pgrp, int sig) { } int kill(pid_t pid, int sig) { - if (g_ddh && pid > 0) { + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) && pid > 0) { // A child still handing its program off: the signal is for the program, which the forked // child (stopped or killed by it) could no longer hand off or account for. Up to 3 s for the // app's answer; a cold worker start takes well under one. diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 1414141b3e..cb1d02a056 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -136,12 +136,14 @@ class FakeSpawner(threading.Thread): 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") + if request.get("ack"): + conn.sendall(b"ok\n") # the app's last word, once the worker runs it + conn.close() os.close(gate_w) if not went: os.waitpid(pid, 0) @@ -163,9 +165,10 @@ class FakeSpawner(threading.Thread): 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(" +#include +#include + +int main(int argc, char **argv) { + if (argc < 3 || strcmp(argv[1], "-c") != 0) return 2; + if (strncmp(argv[2], "echo ", 5) == 0) { + puts(argv[2] + 5); + return 0; + } + if (strncmp(argv[2], "exit ", 5) == 0) return atoi(argv[2] + 5); + return 127; +} +""" + +# popen() and system() through the hook (which starts the shell with posix_spawn()) +PROGRAM = r""" +#include +#include +#include +#include + +int main(int argc, char **argv) { + if (strcmp(argv[1], "system") == 0) { + int status = system("exit 3"); + printf("system\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; + } + // a second stream open while the first is read: the shell of the first must not hold it + FILE *other = popen("echo other", "r"); + FILE *f = popen("echo from the shell", "r"); + char line[64] = ""; + if (f && !fgets(line, sizeof(line), f)) line[0] = 0; + line[strcspn(line, "\n")] = 0; + int status = f ? pclose(f) : -1; + if (other) pclose(other); + printf("popen\t%s\n", line); + printf("pclose\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + + +class NativeHookPopenTest(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) + cls.root = tmp / "root" + (cls.root / "bin").mkdir(parents=True) + (tmp / "sh.c").write_text(SHELL) + # A dynamic shell, as the rootfs' dash is: the root gets the runner's loader and libc for it. + libs = Path("/usr/aarch64-linux-gnu/lib") if cls.prefix else Path("/lib/aarch64-linux-gnu") + loader = Path("/usr/aarch64-linux-gnu/lib/ld-linux-aarch64.so.1") if cls.prefix else Path("/lib/ld-linux-aarch64.so.1") + if not (libs / "libc.so.6").is_file() or not loader.is_file(): + raise unittest.SkipTest("no aarch64 libc to put in the test root") + for d in ("lib", "lib/aarch64-linux-gnu", "usr/lib/aarch64-linux-gnu"): + (cls.root / d).mkdir(parents=True, exist_ok=True) + shutil.copy2(loader, cls.root / "lib/ld-linux-aarch64.so.1") + shutil.copy2(libs / "libc.so.6", cls.root / "lib/aarch64-linux-gnu/libc.so.6") + shutil.copy2(libs / "libc.so.6", cls.root / "usr/lib/aarch64-linux-gnu/libc.so.6") + subprocess.run([cls.cc, "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True) + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cls.cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, mode): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k not in hook_env} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.program), mode], env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, out.returncode, out.stderr) + return dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out + + def test_popen_reads_the_shells_output(self): + result, out = self.run_program("popen") + self.assertEqual("from the shell", result.get("popen"), out.stdout + out.stderr) + self.assertEqual("0", result.get("pclose"), out.stdout) + + def test_system_returns_the_shells_status(self): + result, out = self.run_program("system") + self.assertEqual("3", result.get("system"), out.stdout + out.stderr) + + +if __name__ == "__main__": + unittest.main()