Files
The412Banner 9f5c35f088 fix(bionic): hand off app-data starts only where SELinux lets them run; bare names stay here
Follow-up to 7d95564f7 (review, and a Pocket FIT test of its pack):

- 7d95564f7 kept 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.
2026-12-01 08:24:24 -05:00

411 lines
15 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_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) {
// 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 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};