diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md index ca03513521..54355c931f 100644 --- a/docs/phantom-processes.md +++ b/docs/phantom-processes.md @@ -410,6 +410,48 @@ Quitting the game (also from Steam), stopping the session (no worker is left) an again all work. Started from the front end with the limit on, Setup shows "Child-process limit handled by DroidDeck" and Steam starts. +### The bionic runtime + +DroidDeck-Bionic runs Wine on Android's libc, outside the glibc root, so the native hook never sees +its processes: with the handoff on, a bionic game's Wine programs (the game, `services.exe`, +`winedevice.exe`, `plugplay.exe`, `svchost.exe`, `lsass.exe`, `explorer.exe`, `rpcss.exe`) all stayed +under the worker that runs the tool's `launch.sh` and were counted. The same handoff is built into +the runtime's exec shim (`tools/bionic-runtime/handoff.c`, part of `libexecshim.so`, which every Wine +process preloads): it includes `hook/handoff.c` and `hook/kept.c` (the descriptors `close()` and +`close_range()` leave open, moved out of `privileged.c` for this) and adds what the native hook's +other parts do around them (`fork()`, `close()`, `close_range()`, `dup2()`, `dup3()`, and `exit()` for +the `on_exit()` bionic lacks). What differs on bionic: + +- **bionic's `execv()`, `execvp()` and `execl*()`** make the execve system call inside libc, past an + interposed `execve()`. Wine starts its preloader with `execv()`, so the shim defines them on top + of its `execve()`. +- **A start through the system linker** (`/system/bin/linker64 PROGRAM ARGS`, which the shim makes + of a dynamic program in app data, and which Wine sometimes makes itself) is listed by PROGRAM + (`ddh_try_as()` matches one program and sends another). +- **The app starts a handed-off program from the glibc root's `bash`** (GuestWorkers), which cannot + load the runtime's `LD_PRELOAD` and `LD_LIBRARY_PATH` (bionic libraries: "libdl.so: cannot open + shared object file"). The request carries those two as arguments of `/system/bin/env` instead, + which `bash` execs and which puts them back for the program; the worker's main process is the + program all the same. +- `launch.sh` keeps `DD_SPAWN`, `DD_SPAWN_SESSION`, `DD_HANDOFF*`, `DDH_*` and `DDNATV_ROOT` (it drops + the glibc guest's environment otherwise). The "can't open /proc/N/environ: Permission denied" + lines its prefix checks printed came from idle workers (zygote forks, not dumpable), not from + handed-off programs, which are readable; the redirect is now quiet. + +Measured on an AYANEO Pocket FIT (Snapdragon G3 Gen 3, Adreno 750, Android 14), DroidDeck-Bionic 14.1-r67 with this shim and +launcher, handoff on, max counted in the app's cgroups: + +| | Brawlhalla | DiRT Showdown | whole run | other apps' processes trimmed (limit on) | +|---|---|---|---|---| +| bionic, before | 25 | 24–27 | 28 | yes (Discord, a logcat, BatteryLog's `su`) | +| bionic, with the shim | 17 | 16 | 19–20 | none | +| DroidDeck-Proton 11-14.2 | 12–13 | 12–15 | 15–17 | none | + +DiRT's benchmark held 75 fps average either way; quit through Steam, stop and restart worked with +Android's limit on, with no DroidDeck process killed. Still counted on bionic: what `launch.sh` +itself starts (the game's first Wine process, `gstag`, the wait loop's `sleep`), since Android's +`sh` has no hook, and `wineserver`'s daemon fork. + ### Cost Measured on the Thor, Bully under Proton, the handoff on (`childProcessHandoff`) against off, two diff --git a/tools/bionic-runtime/build.sh b/tools/bionic-runtime/build.sh index bca9ddbd70..2497e4df65 100755 --- a/tools/bionic-runtime/build.sh +++ b/tools/bionic-runtime/build.sh @@ -183,7 +183,7 @@ echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-taggi "$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \ -ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so" "$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so" -"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so" +"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" "$HERE/handoff.c" -ldl -o "$PACK/preload/libexecshim.so" "$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so" "$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag" "$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag" diff --git a/tools/bionic-runtime/execshim.c b/tools/bionic-runtime/execshim.c index 166b9cb6fd..8b449e8b74 100644 --- a/tools/bionic-runtime/execshim.c +++ b/tools/bionic-runtime/execshim.c @@ -25,6 +25,9 @@ typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t; #define LINKER "/system/bin/linker64" +// handoff.c: returns unless the exec was handed to one of the app's worker processes +void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]); + enum kind { PASS, VIA_LINKER, VIA_INTERP }; // What starting `path` needs; for scripts, the interpreter and its optional argument. @@ -205,6 +208,8 @@ int execve(const char *path, char *const argv[], char *const envp[]) { char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes) const char *file = path; char **args = rewrite(path, argv, &file, storage); + // the app may run it in a worker instead (handoff.c): matched by the program, sent as the start below + ddh_bionic_exec(file, args ? args : argv, envp, path, argv); int ret = real(file, args ? args : argv, envp); int saved = errno; free(args); diff --git a/tools/bionic-runtime/handoff.c b/tools/bionic-runtime/handoff.c new file mode 100644 index 0000000000..a72eaa5c61 --- /dev/null +++ b/tools/bionic-runtime/handoff.c @@ -0,0 +1,333 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// 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 +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(); +} + +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, (int)g_ddh_owner, g_ddh_up != NULL, (int)getppid()); + ddh_debug(envp, why, path ? path : "(null)"); + } + // 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; + const char *base = path ? strrchr(path, '/') : NULL; + if (base && strcmp(base + 1, "linker64") == 0 && 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 && args[nargs]) nargs++; + while (envp && envp[nenv]) nenv++; + 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); } + +int execvpe(const char *file, char *const argv[], char *const envp[]) { + if (!file || !*file) { + errno = ENOENT; + return -1; + } + if (strchr(file, '/')) return execve(file, argv, envp); + const char *dirs = getenv("PATH"); + if (!dirs || !*dirs) dirs = "/system/bin:/system/xbin"; + 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); + char full[PATH_MAX]; + if (len + flen + 2 <= sizeof(full)) { + if (len == 0) { + memcpy(full, file, flen + 1); // an empty entry is the current directory + } else { + memcpy(full, p, len); + full[len] = '/'; + memcpy(full + len + 1, file, flen + 1); + } + execve(full, argv, envp); + if (errno == EACCES) saw_eacces = 1; + else if (errno != ENOENT && errno != ENOTDIR) return -1; + } + if (!end) break; + p = end + 1; + } + errno = saw_eacces ? EACCES : ENOENT; + 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_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 (g_kept_fd_count > 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); +} + +int close_range(unsigned int first, unsigned int last, int flags) { + uint64_t ticket = kept_close_begin(); + 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); + int r; + if (count == 0) { + r = close_range_part(first, last, &flags); + } else { + r = 0; + if (flags & CLOSE_RANGE_UNSHARE) { + r = (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE); + flags &= ~(int)CLOSE_RANGE_UNSHARE; + } + if (r == 0) r = 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}; diff --git a/tools/bionic-runtime/tool/launch.sh b/tools/bionic-runtime/tool/launch.sh index b6821f7e85..38ccad9ebc 100644 --- a/tools/bionic-runtime/tool/launch.sh +++ b/tools/bionic-runtime/tool/launch.sh @@ -52,6 +52,10 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;; DROIDDECK_GUEST_ROOT) ;; VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;; + # The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the + # glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs + # in one): the first Wine process's hook knows the worker's binder fds are not its own. + DD_SPAWN|DD_SPAWN_SESSION|DD_HANDOFF|DD_HANDOFF_DEBUG|DD_HANDOFF_PRESSURE|DDH_*|DDNATV_ROOT) ;; *) unset "$v" 2>/dev/null ;; esac done @@ -255,7 +259,7 @@ prepare_prefix() { prefix_busy() { # a process of this prefix is running for p in /proc/[0-9]*; do [ "${p#/proc/}" = "$$" ] && continue - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 done return 1 } @@ -270,7 +274,7 @@ programs_left() { # a program of this prefix is still running, apart from Wine's ""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe|\ winemenubuilder|wineboot.exe|tabtip.exe) continue ;; esac - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 done return 1 } @@ -279,7 +283,7 @@ stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game wineserver_ -k 2>/dev/null sleep 1 for p in /proc/[0-9]*; do - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue [ "${p#/proc/}" = "$$" ] && continue echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)" kill -9 "${p#/proc/}" 2>/dev/null @@ -408,7 +412,7 @@ comm=$(echo "$name" | cut -c1-15) game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name) for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do p=${p%/comm} - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}" + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}" done } # The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game