mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-02 20:21:59 -05:00
* docs: research Android's child-process limit without developer options * docs: confirm the child-process gaps on the Thor * feat(session): start long-lived daemons in uncounted worker processes * feat(nativeguest): hand long-lived programs to uncounted worker processes * test(session): run the session bus block with dd_spawn * test(nativeguest): cover the exec handoff's wait and kill * feat(session): run the session root, its jobs and the gamescope chain outside the child-process count * feat(setup): the child-process limit no longer blocks Steam while the session runs in workers * feat(audio): run PulseAudio outside the child-process count * feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive * fix(nativeguest): let Steam end a handed-off game and keep process-group signals * perf(session): exec a worker as soon as its reply is in and keep two bound ahead; fix review findings * fix(nativeguest): address review findings in handoff waits, signals and spawn errors * fix(session): commit each worker launch explicitly and keep workers with the session that asked * fix(session): let a worker wait for its launch commit on the main thread * fix(session): confirm handoffs, honour wait selectors and stop spawns at teardown * fix(session): one owner per handoff exit, worker launch answers and spawn edge cases * fix(session): send a working directory outside the program's root by its real path * fix(session): recheck a taken exit's child and commit a launch only on a whole go line * fix(session): three-step launch, tagged exit reports and lock-free popen and system children * test(native): popen test shell is static, as the other hook fixtures * test(native): run the popen test program with a clean environment * test(native): skip the popen test where a spawn child cannot exec aarch64 * fix(session): confirm the hook before the worker runs, prefer a late report and free a reused pid * fix(session): tell a reused pid's old entry by start time, not the reaped flag * fix(session): silent failed launches, bounded spawn requests and held check-gone writes * test(native): check the unlisted child's status only where a child can exec aarch64 * fix(session): every exit-only waitid goes through the handoff wait * fix(handoff): exact waitid events, safe exit timer, bounded request receipt * feat(handoff): hand off shell children near Android's process limit * fix(agent): tag handed-off game windows outside the reaper * fix(handoff): a handed-off program's getppid() is its forking process * fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports * fix(handoff): getppid() gives init for an exited or replaced parent * fix(handoff): keep __WALL waitid calls on the handoff path * test(handoff): require a zombie parent in the unreaped-parent case * fix(handoff): honor __WNOTHREAD and check every argument for Steam * fix(handoff): stop waiting on a held entry once its parent has exited * fix(handoff): __WNOTHREAD on waits for a pid, flags on every shim reap * fix(handoff): keep the forking thread of each child in the parent * fix(handoff): a wait that finds no child rechecks live handoffs * fix(handoff): keep a child's forking thread until its end is taken * fix(handoff): the thread selector applies to claims in progress too * fix(handoff): controlling-terminal check via /dev/tty, owned records only * fix(handoff): a child whose forking thread ended is any thread's * fix(handoff): a parent /proc cannot read is checked with kill(), then given up * fix(handoff): one-word fork records, changed only by compare-and-swap * fix(handoff): watch the forking parent through a pidfd opened at start * fix(handoff): fork records by pid, a gone thread's children go to the main one * fix(handoff): keep the parent pidfd through dup2 and check it before use * fix(handoff): no handoff without fork records, unknown thread state keeps the owner * fix(handoff): undo a pidfd move when dup fails, recheck it after the poll * fix(handoff): fresh fork records in a forked child, heir is the first live thread * fix(handoff): one lock over a pidfd move, its dup and the undo * fix(handoff): liveness check under the pidfd lock, forget only a reaped pid's record * fix(handoff): lock only dups onto the pidfd, with signals blocked * fix(handoff): fork record generations, no pidfd restore after a failed move * fix(handoff): every dup in a pidfd process locks, fork prep blocks signals * test(semaphores): tell a child hung in qemu-user from a guest deadlock * fix(handoff): fork records matched by the child's start time, never removed * test(semaphores): count only reaped children, only futex waits as emulator stalls * fix(handoff): a known-start bit in fork records * fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept * fix(handoff): a fork record stays only for the pid's current process * fix(handoff): keep a pending child's fork record when an older fork records late * fix(handoff): an unknown-start fork record never replaces a pending one * fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits * test(handoff): find the module in the namespace run under discover too * fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd * test(handoff): require ENOEXEC for an ELF stub; skip the namespace run without binfmt * fix(hook): change the kept fd list under a sequence lock; readers take a copy * fix(handoff): one report per handed-off child; stops keep a claim; nested waits keep their selector * fix(hook): a table made at runtime outlives closes begun before it; unknown-start fork records kept * fix(handoff): waits look before they reap, so a handed-off fork's child is never reported * fix(hook): settle waits out earlier epochs; unknown-start fork records kept for any handoff under way * fix(handoff): generation-checked reap marks, stops taken as stops, close counts reset in a fork * fix(handoff): one given-up table at most, whole stop codes and rusage, WNOWAIT exits rechecked * fix(handoff): requests name their session; stops of handed-off programs reported; cancellable look * fix(handoff): table setup not cancellable; test spawner never runs what it cannot end * fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup * docs(phantom): job-control jobs stay counted; listed programs report no stops * fix(handoff): a listed program a shell runs as a job-control job stays counted * refactor(hook): kept descriptors in their own part, a handoff matched by another program The descriptors close(), close_range() and closefrom() leave open move from privileged.c to hook/kept.c (unchanged), so the bionic runtime's exec shim can build the handoff with them. ddh_try_as() matches DD_HANDOFF against one program and sends another: the bionic shim sends "/system/bin/linker64 PROGRAM ARGS" and lists it by PROGRAM. ddh_try() is ddh_try_as() with both the same. * feat(bionic): hand the bionic runtime's Wine programs to the app's workers The glibc session's hook never sees DroidDeck-Bionic's processes (Wine on Android's libc), so a bionic game's Wine programs all stayed counted under the worker running the tool's launch.sh. The handoff is now built into the runtime's exec shim (tools/bionic-runtime/handoff.c, part of libexecshim.so): - hook/handoff.c and hook/kept.c with what the native hook's other parts do around them: fork(), close(), close_range(), dup2(), dup3(), and exit() for the on_exit() bionic lacks - bionic's execv(), execvp(), execl*() reach the execve system call inside libc, past execshim's execve(); Wine starts its preloader with execv(), so the shim defines them on top of its execve() - a linker64 start is listed by its program - the app starts a handed-off program from the glibc root's bash, which cannot load the runtime's LD_PRELOAD/LD_LIBRARY_PATH: they go as arguments of /system/bin/env, which puts them back for the program - launch.sh keeps DD_SPAWN, DD_SPAWN_SESSION, DD_HANDOFF*, DDH_* and DDNATV_ROOT, and its /proc/N/environ reads no longer print "Permission denied" for idle workers (2>/dev/null before the redirect) Pocket FIT, DroidDeck-Bionic 14.1-r67 with this shim and launcher, handoff on: counted during Brawlhalla 25 -> 17, DiRT Showdown 24-27 -> 16, whole run 28 -> 19-20; with Android's limit on no DroidDeck process and no other app's process was killed (before: Discord, BatteryLog helpers); DiRT 75 fps either way. docs/phantom-processes.md: "The bionic runtime". * fix(bionic): hand off only starts that would succeed here; bionic's execvp fallbacks Review follow-ups on the bionic runtime's handoff (tools/bionic-runtime/handoff.c): - A start is handed to a worker only when it would get past execve() in this process: the file is a regular executable outside the app's data (Android refuses execve() there), and for a linker64 start the program it loads is a readable regular file. A start that failed in the worker failed where the caller could not see it, so Wine never tried its next candidate. The hook's own check looked at /system/bin/env, not the program. - A start whose argv[0] is not its file stays here: env starts FILE with FILE as argv[0]. linker64 and interpreter starts are unaffected (their argv[0] is the file). An empty argv stays here too. - Nothing is built for the handoff without DD_SPAWN and DD_HANDOFF. - execvp()/execvpe()/execlp() follow bionic's: an unset PATH is libc's default, an empty PATH or entry is the current directory, and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh. - close_range() refuses first > last and unknown flags before it splits the range or unshares the table. - The debug line reads the table's owner only once the table is seen published. * fix(bionic): hand off app-data starts only where SELinux lets them run; bare names stay here Follow-up to7d95564f7(review, and a Pocket FIT test of its pack): -7d95564f7kept every start of a file in the app's data here. Wine's preloader is one (a static ELF, so execshim.c cannot make it a linker64 start), and where SELinux is permissive, as on AYANEO's firmware, it runs: Wine then never reached its loader, and its programs ran here, counted again (Pocket FIT: Brawlhalla 26-28 counted vs 16-17 before). Where SELinux enforces, Android refuses the exec, here and in a worker alike, and Wine falls back to its loader, which goes as a linker64 start. Such a start is now handed off when /sys/fs/selinux/enforce reads 0, and stays here otherwise (also when the setting cannot be read). - The program a start would run is checked with the hook's own ddh_startable() (an ELF the kernel loads with its interpreter there, or a script with its interpreter): for a linker64 start, the program it loads. - A file name without '/' stays here: env would look it up in PATH, the exec here in the caller's working directory. - execvpe() skips a PATH entry whose candidate exceeds PATH_MAX (ENAMETOOLONG) instead of copying it onto the stack. * fix(handoff): spawn blocks signals and cancellation across the fork; root flag stored under the stop lock * fix(handoff): a thread that unshares its fd table keeps its own copy of the kept fds * fix(handoff): register the kept list's fork handlers before a split takes its lock * test(handoff): cover WNOHANG with a held forked child, early reaps, blocked waitid and pidfd parents; keep the counted-process exception in translations * test(handoff): exited-entry precondition, atomic checkpoints, a pidfd-only zombie check; validate the shim hold fd * test(handoff): WNOHANG with two handed-off children and for a group; a program's exit while its entry is held * test(handoff): a held exit with no free fd, with and without the parent's pidfd * test(handoff): held-exit tests require the program's own exit status * test(handoff): time held exits from the run, and only once the program is at its exit * perf(handoff): keep the asker's priority, quick tools local, workers bound ahead of a game (#3582) Three fixes that bring handoff-on speed to within 1-2 % of handoff off (AIO D3D11 same session: 3196 -> 3520 fps, 1 % low 444 -> 637) with the same counted processes (benchmark mean 18.5, peak 23): - A handed-off program keeps its asker's priority. Workers are bound from the top app with BIND_IMPORTANT, so Android boosts their main thread to THREAD_PRIORITY_TOP_APP_BOOST (-10); the program the worker execs inherited it. The asker's nice value is sent with the request and set before execve, and a watcher resets it if Android boosts it again. - Quick script tools (awk, sed, grep, cat, ...) stay where they are when the count is near the limit. Sent to a worker, the forked child waits (counted) while a worker starts; run locally it is counted for a few ms. - Workers are bound ahead when a Steam game is queued (16 for 20 s), so Wine's services do not wait on zygote forks at game start. --------- Co-authored-by: The412Banner <[email protected]> Co-authored-by: The412Banner <[email protected]>
416 lines
16 KiB
C
416 lines
16 KiB
C
// handoff: part of libexecshim.so, preloaded into the bionic Wine processes. The native hook's exec
|
|
// handoff (tools/nativeguest/hook/handoff.c, docs/phantom-processes.md) built for bionic: a program a
|
|
// Wine process forks and execs runs as the main process of one of the app's worker processes instead of
|
|
// as a child Android counts against its limit. The glibc session's hook cannot reach these processes
|
|
// (they run on Android's libc), so without this every Wine process of a bionic game was counted.
|
|
//
|
|
// What the native hook does around the handoff and this file does too: fork() records the child for
|
|
// its parent's table, close(), close_range(), dup2() and dup3() leave the table and the worker's binder
|
|
// fds alone (hook/kept.c), and execve() offers the exec to the app before it runs (execshim.c calls
|
|
// ddh_bionic_exec() with the start it is about to make: "/system/bin/linker64 PROGRAM ARGS" for a
|
|
// program in the app's data, matched against DD_HANDOFF by PROGRAM). wait*(), kill() and _exit() are
|
|
// the handoff's own (hook/handoff.c). Nothing here acts without DD_SPAWN and DD_HANDOFF in the
|
|
// environment (tools/bionic-runtime/tool/launch.sh keeps them).
|
|
#define _GNU_SOURCE
|
|
#include <dlfcn.h>
|
|
#include <elf.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <limits.h>
|
|
#include <pthread.h>
|
|
#include <sched.h>
|
|
#include <signal.h>
|
|
#include <stdarg.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
#include <sys/mman.h>
|
|
#include <sys/resource.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/syscall.h>
|
|
#include <sys/types.h>
|
|
#include <sys/uio.h>
|
|
#include <sys/un.h>
|
|
#include <sys/wait.h>
|
|
|
|
// bionic has no thread cancellation: nothing can cancel the table's setup
|
|
#ifndef PTHREAD_CANCEL_ENABLE
|
|
#define PTHREAD_CANCEL_ENABLE 0
|
|
#define PTHREAD_CANCEL_DISABLE 1
|
|
static int pthread_setcancelstate(int state, int *old) {
|
|
(void)state;
|
|
if (old) *old = PTHREAD_CANCEL_ENABLE;
|
|
return 0;
|
|
}
|
|
#endif
|
|
#ifndef CLOSE_RANGE_UNSHARE
|
|
#define CLOSE_RANGE_UNSHARE (1U << 1)
|
|
#endif
|
|
#ifndef CLOSE_RANGE_CLOEXEC
|
|
#define CLOSE_RANGE_CLOEXEC (1U << 2)
|
|
#endif
|
|
#ifndef __NR_close_range
|
|
#define __NR_close_range 436
|
|
#endif
|
|
|
|
#include <sys/sysmacros.h>
|
|
static void pthread_testcancel(void) {}
|
|
int close_range(unsigned int first, unsigned int last, int flags);
|
|
|
|
// bionic has no on_exit(): the handoff reports a program's exit status from it (exit() runs it).
|
|
// atexit() handlers get no status, so exit() below notes it first; a return from main() reaches
|
|
// exit() inside libc and reports 0.
|
|
static void (*g_on_exit_fn)(int, void *);
|
|
static void *g_on_exit_arg;
|
|
static int g_exit_status;
|
|
static void run_on_exit(void) {
|
|
if (g_on_exit_fn) g_on_exit_fn(g_exit_status, g_on_exit_arg);
|
|
}
|
|
static int on_exit(void (*fn)(int, void *), void *arg) {
|
|
g_on_exit_fn = fn;
|
|
g_on_exit_arg = arg;
|
|
return atexit(run_on_exit);
|
|
}
|
|
|
|
// The native hook's names for the plain system call and for a guest path: here there is no guest root.
|
|
static long call_orig_syscall(long nr, unsigned long a, unsigned long b, unsigned long c, unsigned long d,
|
|
unsigned long e, unsigned long f) {
|
|
return syscall(nr, a, b, c, d, e, f);
|
|
}
|
|
static const char *rewrite_path(const char *path, char *out, size_t size) {
|
|
(void)out;
|
|
(void)size;
|
|
return path;
|
|
}
|
|
|
|
#include "../nativeguest/hook/kept.c"
|
|
#include "../nativeguest/hook/handoff.c"
|
|
|
|
void exit(int status) {
|
|
g_exit_status = status;
|
|
void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, "exit");
|
|
if (real) real(status);
|
|
syscall(SYS_exit_group, status);
|
|
__builtin_unreachable();
|
|
}
|
|
|
|
static int ddh_is_linker(const char *path) {
|
|
const char *base = path ? strrchr(path, '/') : NULL;
|
|
return base && strcmp(base + 1, "linker64") == 0;
|
|
}
|
|
|
|
static int ddh_regular(const char *path, int mode) {
|
|
struct stat st;
|
|
return path && stat(path, &st) == 0 && S_ISREG(st.st_mode) && access(path, mode) == 0;
|
|
}
|
|
|
|
// Android refuses execve() of a file in the app's data unless SELinux is permissive (execshim.c makes the
|
|
// dynamic ones linker64 starts). An unreadable setting counts as enforcing.
|
|
static int ddh_selinux_permissive(void) {
|
|
char c = 0;
|
|
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC, 0);
|
|
if (fd < 0) return 0;
|
|
long n = syscall(SYS_read, fd, &c, 1);
|
|
syscall(SYS_close, fd);
|
|
return n == 1 && c == '0';
|
|
}
|
|
|
|
// A handed-off start that fails fails in the worker, where the caller cannot see it and try its next
|
|
// candidate (Wine tries its preloader, then its loader), so only a start that would succeed here goes.
|
|
static int ddh_bionic_startable(const char *file, char *const args[]) {
|
|
char real[PATH_MAX];
|
|
// env takes an argument with '=' for a variable, and looks a name without '/' up in PATH
|
|
if (!file || strchr(file, '=') || !strchr(file, '/')) return 0;
|
|
if (!ddh_regular(file, X_OK) || !realpath(file, real)) return 0;
|
|
if (ddh_is_linker(real))
|
|
return args && args[0] && args[1] && args[1][0] != '-' && ddh_regular(args[1], R_OK) && ddh_startable(args[1]);
|
|
if (strncmp(real, "/data/", 6) == 0 && !ddh_selinux_permissive()) return 0;
|
|
// env starts FILE with FILE as argv[0]
|
|
return args && args[0] && strcmp(args[0], file) == 0 && ddh_startable(file);
|
|
}
|
|
|
|
void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]) {
|
|
if (ddh_env(envp, "DD_HANDOFF_DEBUG")) {
|
|
char why[200];
|
|
struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE);
|
|
snprintf(why, sizeof(why), "bionic exec (spawn %d list %d table %d owner %d up %d ppid %d) of", ddh_env(envp, "DD_SPAWN") != NULL,
|
|
ddh_env(envp, "DD_HANDOFF") != NULL, own != NULL, own ? (int)g_ddh_owner : 0, g_ddh_up != NULL, (int)getppid());
|
|
ddh_debug(envp, why, path ? path : "(null)");
|
|
}
|
|
if (!ddh_env(envp, "DD_SPAWN") || !ddh_env(envp, "DD_HANDOFF")) return;
|
|
if (!ddh_bionic_startable(file, args)) {
|
|
ddh_debug(envp, "bionic exec stays here (not startable as a handoff):", path ? path : "(null)");
|
|
return;
|
|
}
|
|
// Wine's own starts through the system linker ("/system/bin/linker64 PROGRAM ARGS") are listed by PROGRAM
|
|
const char *match = path;
|
|
char *const *match_argv = argv;
|
|
if (ddh_is_linker(path) && argv && argv[0] && argv[1]) {
|
|
match = argv[1];
|
|
match_argv = argv + 1;
|
|
}
|
|
// The app starts a handed-off program from the glibc root's shell (GuestWorkers), which cannot load this
|
|
// runtime's LD_PRELOAD and LD_LIBRARY_PATH (bionic libraries). The request carries them as arguments of
|
|
// Android's env instead, which the shell execs and which puts them back for the program: the worker's main
|
|
// process ends up as the program all the same. Stack only (this may run in a vfork child).
|
|
int nargs = 0, nenv = 0;
|
|
while (args[nargs]) nargs++;
|
|
while (envp && envp[nenv]) nenv++;
|
|
// env, up to two loader variables, FILE, args[1..], NULL (nargs >= 1: ddh_bionic_startable)
|
|
char *wrapped[nargs + 4];
|
|
char *trimmed[nenv + 1];
|
|
int w = 0, t = 0;
|
|
wrapped[w++] = (char *)"/system/bin/env";
|
|
for (int i = 0; i < nenv; i++) {
|
|
if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0 || strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) {
|
|
if (w < 3) wrapped[w++] = envp[i];
|
|
} else {
|
|
trimmed[t++] = envp[i];
|
|
}
|
|
}
|
|
trimmed[t] = NULL;
|
|
// env runs the program by the path its first argument gives: the start's file, then the rest of its argv
|
|
wrapped[w++] = (char *)file;
|
|
for (int i = 1; i < nargs; i++) wrapped[w++] = args[i];
|
|
wrapped[w] = NULL;
|
|
ddh_try_as("/system/bin/env", wrapped, trimmed, match, match_argv);
|
|
ddh_debug(envp, "bionic exec stays here:", path ? path : "(null)");
|
|
}
|
|
|
|
// bionic's exec functions call the execve system call stub inside libc, past execshim.c's execve(): Wine
|
|
// starts its programs with execv() (its preloader) and execvp(), so these go through execve() here.
|
|
extern char **environ;
|
|
|
|
int execv(const char *path, char *const argv[]) { return execve(path, argv, environ); }
|
|
|
|
// bionic's execvpe(), through execve() here: an unset PATH is libc's default (Android 14's; an empty one, and an empty
|
|
// entry, are the current directory), and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh.
|
|
#define DDH_DEFPATH "/product/bin:/apex/com.android.runtime/bin:/apex/com.android.art/bin:/system_ext/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin"
|
|
|
|
static int exec_as_script(const char *file, char *const argv[], char *const envp[]) {
|
|
int n = 0;
|
|
while (argv && argv[n]) n++;
|
|
char *script[(n > 0 ? n : 1) + 2];
|
|
int s = 0;
|
|
script[s++] = (char *)"sh";
|
|
script[s++] = (char *)file;
|
|
for (int i = 1; i < n; i++) script[s++] = argv[i];
|
|
script[s] = NULL;
|
|
return execve("/system/bin/sh", script, envp);
|
|
}
|
|
|
|
int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
|
if (!file || !*file) {
|
|
errno = ENOENT;
|
|
return -1;
|
|
}
|
|
if (strchr(file, '/')) {
|
|
execve(file, argv, envp);
|
|
return errno == ENOEXEC ? exec_as_script(file, argv, envp) : -1;
|
|
}
|
|
const char *dirs = getenv("PATH");
|
|
if (!dirs) dirs = DDH_DEFPATH;
|
|
int saw_eacces = 0;
|
|
size_t flen = strlen(file);
|
|
for (const char *p = dirs;;) {
|
|
const char *end = strchr(p, ':');
|
|
size_t len = end ? (size_t)(end - p) : strlen(p);
|
|
const char *dir = len ? p : ".";
|
|
if (!len) len = 1;
|
|
char full[PATH_MAX];
|
|
if (len + flen + 2 > sizeof(full)) {
|
|
errno = ENAMETOOLONG;
|
|
} else {
|
|
memcpy(full, dir, len);
|
|
full[len] = '/';
|
|
memcpy(full + len + 1, file, flen + 1);
|
|
execve(full, argv, envp);
|
|
}
|
|
switch (errno) {
|
|
case EISDIR:
|
|
case ELOOP:
|
|
case ENAMETOOLONG:
|
|
case ENOENT:
|
|
case ENOTDIR:
|
|
break;
|
|
case ENOEXEC:
|
|
return exec_as_script(full, argv, envp);
|
|
case EACCES:
|
|
saw_eacces = 1;
|
|
break;
|
|
default:
|
|
return -1;
|
|
}
|
|
if (!end) break;
|
|
p = end + 1;
|
|
}
|
|
if (saw_eacces) errno = EACCES;
|
|
return -1;
|
|
}
|
|
|
|
int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); }
|
|
|
|
// execl(), execlp(), execle(): the list as an argv on the stack
|
|
#define EXECL_ARGV(first, ap, n) \
|
|
do { \
|
|
va_list count_ap; \
|
|
va_copy(count_ap, ap); \
|
|
n = first ? 1 : 0; \
|
|
if (first) \
|
|
while (va_arg(count_ap, const char *)) n++; \
|
|
va_end(count_ap); \
|
|
} while (0)
|
|
|
|
int execl(const char *path, const char *arg0, ...) {
|
|
va_list ap;
|
|
va_start(ap, arg0);
|
|
int n;
|
|
EXECL_ARGV(arg0, ap, n);
|
|
char *argv[n + 1];
|
|
argv[0] = (char *)arg0;
|
|
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
|
|
argv[n] = NULL;
|
|
va_end(ap);
|
|
return execve(path, argv, environ);
|
|
}
|
|
|
|
int execlp(const char *file, const char *arg0, ...) {
|
|
va_list ap;
|
|
va_start(ap, arg0);
|
|
int n;
|
|
EXECL_ARGV(arg0, ap, n);
|
|
char *argv[n + 1];
|
|
argv[0] = (char *)arg0;
|
|
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
|
|
argv[n] = NULL;
|
|
va_end(ap);
|
|
return execvp(file, argv);
|
|
}
|
|
|
|
int execle(const char *path, const char *arg0, ...) {
|
|
va_list ap;
|
|
va_start(ap, arg0);
|
|
int n;
|
|
EXECL_ARGV(arg0, ap, n);
|
|
char *argv[n + 1];
|
|
argv[0] = (char *)arg0;
|
|
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
|
|
argv[n] = NULL;
|
|
if (arg0) (void)va_arg(ap, char *); // the list's NULL
|
|
char *const *envp = va_arg(ap, char *const *);
|
|
va_end(ap);
|
|
return execve(path, argv, envp);
|
|
}
|
|
|
|
pid_t fork(void) {
|
|
static pid_t (*orig_fork)(void) = NULL;
|
|
if (!orig_fork) orig_fork = (pid_t (*)(void))dlsym(RTLD_NEXT, "fork");
|
|
if (!orig_fork) {
|
|
errno = ENOSYS;
|
|
return -1;
|
|
}
|
|
ddh_prepare();
|
|
pid_t forker = (pid_t)syscall(SYS_gettid);
|
|
pid_t pid = orig_fork();
|
|
if (pid == 0) {
|
|
kept_forked();
|
|
kept_close_forked();
|
|
ddh_drop_worker_binder();
|
|
ddh_forked(forker);
|
|
} else if (pid > 0) {
|
|
ddh_child_created(pid, 1);
|
|
}
|
|
return pid;
|
|
}
|
|
|
|
int close(int fd) {
|
|
static int (*orig_close)(int) = NULL;
|
|
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
|
|
uint64_t ticket = kept_close_begin();
|
|
if (kept_any() > 0 && is_kept_fd(fd)) {
|
|
kept_close_end(ticket);
|
|
return 0;
|
|
}
|
|
int r = orig_close ? orig_close(fd) : (errno = ENOSYS, -1);
|
|
int saved = errno;
|
|
kept_close_end(ticket);
|
|
errno = saved;
|
|
return r;
|
|
}
|
|
|
|
static int dup_moved(int (*dup_fn)(int, int, int), int oldfd, int newfd, int flags) {
|
|
int pidfd_from = -1, locked = 0;
|
|
if (oldfd != newfd) {
|
|
locked = ddh_parent_pidfd_lock(newfd);
|
|
pidfd_from = ddh_parent_pidfd_moves(newfd);
|
|
}
|
|
int ret = dup_fn(oldfd, newfd, flags);
|
|
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
|
|
int saved = errno;
|
|
ddh_parent_pidfd_unlock(locked);
|
|
errno = saved;
|
|
return ret;
|
|
}
|
|
|
|
static int (*g_orig_dup2)(int, int);
|
|
static int (*g_orig_dup3)(int, int, int);
|
|
static int call_dup2(int oldfd, int newfd, int flags) {
|
|
(void)flags;
|
|
return g_orig_dup2 ? g_orig_dup2(oldfd, newfd) : (errno = ENOSYS, -1);
|
|
}
|
|
static int call_dup3(int oldfd, int newfd, int flags) {
|
|
return g_orig_dup3 ? g_orig_dup3(oldfd, newfd, flags) : (errno = ENOSYS, -1);
|
|
}
|
|
|
|
int dup2(int oldfd, int newfd) {
|
|
if (!g_orig_dup2) g_orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
|
|
return dup_moved(call_dup2, oldfd, newfd, 0);
|
|
}
|
|
|
|
int dup3(int oldfd, int newfd, int flags) {
|
|
if (!g_orig_dup3) g_orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
|
|
return dup_moved(call_dup3, oldfd, newfd, flags);
|
|
}
|
|
|
|
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
|
|
return (int)syscall(__NR_close_range, first, last, *(int *)flags);
|
|
}
|
|
|
|
static int close_range_unshare(void) {
|
|
return (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE);
|
|
}
|
|
|
|
int close_range(unsigned int first, unsigned int last, int flags) {
|
|
// what the kernel refuses, refused before the range is split or the table unshared
|
|
if (first > last || (flags & ~(int)(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))) {
|
|
errno = EINVAL;
|
|
return -1;
|
|
}
|
|
uint64_t ticket = kept_close_begin();
|
|
int r = 0;
|
|
// The table is unshared first, once, and this thread goes on with its own copy of the kept list
|
|
// (kept_split())
|
|
if (flags & CLOSE_RANGE_UNSHARE) {
|
|
r = kept_split(close_range_unshare);
|
|
flags &= ~(int)CLOSE_RANGE_UNSHARE;
|
|
}
|
|
if (r == 0) {
|
|
int snapshot[DDNATV_MAX_KEPT_FDS];
|
|
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
|
|
int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
|
|
r = count == 0 ? close_range_part(first, last, &flags)
|
|
: for_each_range_without(first, last, kept, count, close_range_part, &flags);
|
|
}
|
|
int saved = errno;
|
|
kept_close_end(ticket);
|
|
errno = saved;
|
|
return r;
|
|
}
|
|
|
|
// The native hook's own uses of these (exec.c) have no counterpart here
|
|
__attribute__((unused)) static void *const glibc_only[] = {(void *)ddh_try, (void *)ddh_spawn_wanted};
|