Files
DroidDeck/tools/phantomlab/jni/lab.c
T
5cd6fe8864 feat(session): run the session outside Android's child-process count (#3338)
* 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 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.

* 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 <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
2026-12-02 14:02:55 -05:00

423 lines
15 KiB
C

// Native half of phantomlab: forks sleepers, execs in place, and probes what a process may do.
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#include <android/log.h>
#define TAG "PLAB"
JNIEXPORT jint JNICALL Java_com_droiddeck_phantomlab_Native_spawn(JNIEnv *env, jclass cls, jint n) {
int made = 0;
for (int i = 0; i < n; i++) {
pid_t pid = fork();
if (pid == 0) {
for (;;) pause();
}
if (pid > 0) made++;
}
return made;
}
struct kept_fd {
int fd, flags;
};
static int keep_binder_fds(struct kept_fd *kept, int max) {
DIR *d = opendir("/proc/self/fd");
if (!d) return 0;
int count = 0;
struct dirent *e;
char path[64], target[256];
while ((e = readdir(d)) != NULL && count < max) {
int fd = atoi(e->d_name);
if (fd <= 2) continue;
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len <= 0) continue;
target[len] = 0;
if (strstr(target, "binder")) {
int flags = fcntl(fd, F_GETFD);
if (flags < 0 || fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) != 0) continue;
kept[count].fd = fd;
kept[count].flags = flags;
count++;
__android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target);
}
}
closedir(d);
return count;
}
JNIEXPORT void JNICALL Java_com_droiddeck_phantomlab_Native_execInPlace(JNIEnv *env, jclass cls, jobjectArray jargv, jboolean keep) {
int n = (*env)->GetArrayLength(env, jargv);
char **argv = calloc(n + 1, sizeof(char *));
for (int i = 0; i < n; i++) {
jstring s = (*env)->GetObjectArrayElement(env, jargv, i);
const char *c = (*env)->GetStringUTFChars(env, s, NULL);
argv[i] = strdup(c);
}
struct kept_fd kept[16];
int kept_count = keep ? keep_binder_fds(kept, 16) : 0;
execv(argv[0], argv);
__android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno));
for (int i = 0; i < kept_count; i++) fcntl(kept[i].fd, F_SETFD, kept[i].flags);
}
static char *report;
static size_t report_len, report_cap;
static void out(const char *fmt, ...) {
char line[1024];
va_list ap;
va_start(ap, fmt);
int len = vsnprintf(line, sizeof(line), fmt, ap);
va_end(ap);
if (len < 0) return;
if (len >= (int)sizeof(line)) len = sizeof(line) - 1;
if (report_len + len + 2 > report_cap) {
report_cap = (report_len + len + 2) * 2;
report = realloc(report, report_cap);
}
memcpy(report + report_len, line, len);
report_len += len;
report[report_len++] = '\n';
report[report_len] = 0;
}
static void read_small(const char *path, char *buf, size_t size) {
buf[0] = 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
snprintf(buf, size, "<%s>", strerror(errno));
return;
}
ssize_t n = read(fd, buf, size - 1);
close(fd);
if (n < 0) n = 0;
buf[n] = 0;
for (ssize_t i = 0; i < n; i++) if (buf[i] == '\n' || buf[i] == 0) buf[i] = ' ';
}
#if defined(__aarch64__)
static const unsigned char ret42[] = {0x40, 0x05, 0x80, 0x52, 0xc0, 0x03, 0x5f, 0xd6};
#else
static const unsigned char ret42[] = {0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3};
#endif
static int call_code(void *code) {
__builtin___clear_cache((char *)code, (char *)code + sizeof(ret42));
return ((int (*)(void))code)();
}
static void probe_memfd_exec(void) {
int fd = syscall(SYS_memfd_create, "lab", 0);
if (fd < 0) {
out("memfd_exec: memfd_create %s", strerror(errno));
return;
}
write(fd, ret42, sizeof(ret42));
void *p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) out("memfd_exec: mmap exec %s", strerror(errno));
else out("memfd_exec: ran, returned %d", call_code(p));
close(fd);
}
static void probe_anon_exec(void) {
void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memcpy(p, ret42, sizeof(ret42));
if (mprotect(p, 4096, PROT_READ | PROT_EXEC) != 0) out("anon_exec: mprotect %s", strerror(errno));
else out("anon_exec: ran, returned %d", call_code(p));
}
static int run_child(char *const argv[], int execfd) {
pid_t pid = fork();
if (pid < 0) {
out("fork: %s", strerror(errno));
return -1;
}
if (pid == 0) {
if (execfd >= 0) syscall(SYS_execveat, execfd, "", argv, environ, AT_EMPTY_PATH);
else execv(argv[0], argv);
_exit(100 + errno);
}
int status = 0;
waitpid(pid, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1000 + WTERMSIG(status);
}
static const char *exec_result(int st, const char *ran) {
if (st < 0) return "not run";
return st >= 100 && st < 1000 ? strerror(st - 100) : ran;
}
static int wait_fd(int fd, short events) {
struct pollfd p = {.fd = fd, .events = events};
int r = poll(&p, 1, 2000);
if (r == 0) errno = ETIMEDOUT;
return r > 0 ? 0 : -1;
}
static void probe_tcp(int i, int fd) {
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)};
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
int fl = fcntl(fd, F_GETFL);
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) != 0) {
out("fd%d tcp: fcntl %s", i, strerror(errno));
return;
}
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
if (r != 0 && errno == EINPROGRESS) {
int err = 0;
socklen_t el = sizeof(err);
if (wait_fd(fd, POLLOUT) == 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) == 0) {
r = err ? -1 : 0;
errno = err;
} else {
r = -1;
}
}
if (r != 0) {
out("fd%d tcp: connect %s", i, strerror(errno));
} else {
const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n";
if (wait_fd(fd, POLLOUT) != 0 || write(fd, req, strlen(req)) < 0) {
out("fd%d tcp: connected, write %s", i, strerror(errno));
} else {
char resp[64] = "";
ssize_t n = wait_fd(fd, POLLIN) == 0 ? read(fd, resp, sizeof(resp) - 1) : -1;
if (n > 0) resp[n] = 0;
char *nl = strchr(resp, '\r');
if (nl) *nl = 0;
out("fd%d tcp: connected, got \"%s\"", i, n > 0 ? resp : strerror(errno));
}
}
fcntl(fd, F_SETFL, fl);
}
static void probe_exec(void) {
char *argv[] = {"/system/bin/true", NULL};
int st = run_child(argv, -1);
out("execve /system/bin/true: %s", exec_result(st, st == 0 ? "ok" : "status"));
int src = open("/system/bin/toybox", O_RDONLY);
int mfd = syscall(SYS_memfd_create, "toybox", 0);
char buf[65536];
ssize_t n;
while (src >= 0 && (n = read(src, buf, sizeof(buf))) > 0) write(mfd, buf, n);
if (src >= 0) close(src);
char *targv[] = {"true", NULL};
st = run_child(targv, mfd);
out("execveat memfd(toybox true): %s", exec_result(st, st == 0 ? "ok" : "status"));
close(mfd);
}
static void probe_fd(int i, int fd) {
struct stat st;
if (fstat(fd, &st) != 0) {
out("fd%d: fstat %s", i, strerror(errno));
return;
}
char target[256] = "";
char path[64];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len > 0) target[len] = 0;
if (S_ISSOCK(st.st_mode)) {
int type = 0, family = 0;
socklen_t sl = sizeof(type);
getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &sl);
struct sockaddr_storage ss;
socklen_t al = sizeof(ss);
getsockname(fd, (struct sockaddr *)&ss, &al);
family = ss.ss_family;
if (family == AF_INET && type == SOCK_STREAM) {
probe_tcp(i, fd);
} else if (family == AF_INET && type == SOCK_DGRAM) {
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(53)};
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
out("fd%d udp: connect %s", i, r == 0 ? "ok" : strerror(errno));
} else {
char buf[64] = "";
ssize_t r = wait_fd(fd, POLLIN) == 0 ? read(fd, buf, sizeof(buf) - 1) : -1;
if (r > 0) buf[r - 1] = 0;
out("fd%d unix(family %d): read %s", i, family, r > 0 ? buf : strerror(errno));
}
return;
}
if (S_ISDIR(st.st_mode)) {
int f = openat(fd, "probe.txt", O_RDONLY);
out("fd%d dir %s: openat child %s", i, target, f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
return;
}
char buf[64] = "";
ssize_t r = pread(fd, buf, sizeof(buf) - 1, 0);
if (r > 0) buf[r - 1] = 0;
out("fd%d file %s: read %s", i, target, r >= 0 ? buf : strerror(errno));
void *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
out("fd%d mmap read: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
if (p != MAP_FAILED) munmap(p, 4096);
p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
out("fd%d mmap exec: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
if (p != MAP_FAILED) munmap(p, 4096);
char *argv[] = {"x", NULL};
int st2 = run_child(argv, fd);
out("fd%d execveat: %s", i, exec_result(st2, "ran"));
}
static void probe_self(void) {
char buf[512];
out("uid=%d gid=%d pid=%d ppid=%d", getuid(), getgid(), getpid(), getppid());
read_small("/proc/self/attr/current", buf, sizeof(buf));
out("selinux: %s", buf);
read_small("/proc/self/cgroup", buf, sizeof(buf));
out("cgroup: %s", buf);
int s = socket(AF_INET, SOCK_STREAM, 0);
out("socket(AF_INET): %s", s >= 0 ? "ok" : strerror(errno));
if (s >= 0) close(s);
s = socket(AF_UNIX, SOCK_STREAM, 0);
out("socket(AF_UNIX): %s", s >= 0 ? "ok" : strerror(errno));
if (s >= 0) close(s);
int f = open("/data/data/com.droiddeck.phantomlab/files/probe.txt", O_RDONLY);
out("open app data by path: %s", f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
const char *gpus[] = {"/dev/kgsl-3d0", "/dev/mali0", "/dev/dri/renderD128", NULL};
for (int i = 0; gpus[i]; i++) {
if (access(gpus[i], F_OK) != 0) continue;
f = open(gpus[i], O_RDWR);
out("open %s: %s", gpus[i], f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
}
}
static void probe_pid(const char *spec) {
int pid = atoi(spec);
char path[64], buf[256];
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
read_small(path, buf, sizeof(buf));
out("read /proc/%d/cmdline: %s", pid, buf);
out("kill(%d, 0): %s", pid, kill(pid, 0) == 0 ? "ok" : strerror(errno));
out("kill(%d, SIGCONT): %s", pid, kill(pid, SIGCONT) == 0 ? "ok" : strerror(errno));
}
static void try_write(const char *path, const char *value) {
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) {
out("write %s: open %s", path, strerror(errno));
return;
}
ssize_t n = write(fd, value, strlen(value));
out("write %s: %s", path, n >= 0 ? "ok" : strerror(errno));
close(fd);
}
// Every way a process could leave the cgroup Android counts it in.
static void probe_escape(void) {
char own[256], pid[32], path[300];
read_small("/proc/self/cgroup", own, sizeof(own));
char *v2 = strstr(own, "0::");
char dir[200] = "";
if (v2) sscanf(v2 + 3, "%199s", dir);
snprintf(pid, sizeof(pid), "%d", getpid());
try_write("/sys/fs/cgroup/cgroup.procs", pid);
char parent[200];
snprintf(parent, sizeof(parent), "%s", dir);
char *slash = strrchr(parent, '/');
if (slash) *slash = 0;
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/cgroup.procs", parent);
try_write(path, pid);
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/lab", dir);
out("mkdir %s: %s", path, mkdir(path, 0755) == 0 ? "ok" : strerror(errno));
int r = syscall(SYS_unshare, 0x10000000 /* CLONE_NEWUSER */);
out("unshare(CLONE_NEWUSER): %s", r == 0 ? "ok" : strerror(errno));
r = syscall(SYS_unshare, 0x02000000 /* CLONE_NEWCGROUP */);
out("unshare(CLONE_NEWCGROUP): %s", r == 0 ? "ok" : strerror(errno));
int cg = open("/sys/fs/cgroup", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (cg < 0) {
out("open /sys/fs/cgroup: %s", strerror(errno));
} else {
struct {
unsigned long long flags, pidfd, child_tid, parent_tid, exit_signal, stack, stack_size, tls, set_tid,
set_tid_size, cgroup;
} args = {.flags = 0x200000000ULL /* CLONE_INTO_CGROUP */, .exit_signal = SIGCHLD, .cgroup = (unsigned)cg};
long child = syscall(435 /* clone3 */, &args, sizeof(args));
if (child == 0) _exit(0);
if (child > 0) waitpid(child, NULL, 0);
out("clone3(CLONE_INTO_CGROUP, root): %s", child > 0 ? "ok" : strerror(errno));
close(cg);
}
}
// Runs path with fd as its fd 3 and its stderr captured.
static void probe_libexec(const char *path, int fd) {
int pipefd[2];
if (pipe(pipefd) != 0) {
out("exec %s: pipe %s", path, strerror(errno));
return;
}
pid_t pid = fork();
if (pid < 0) {
out("exec %s: fork %s", path, strerror(errno));
close(pipefd[0]);
close(pipefd[1]);
return;
}
if (pid == 0) {
dup2(pipefd[1], 2);
if (fd >= 0) dup2(fd, 3);
char *argv[] = {(char *)path, NULL};
execv(path, argv);
dprintf(2, "execv: %s", strerror(errno));
_exit(127);
}
close(pipefd[1]);
char buf[512] = "";
ssize_t n = read(pipefd[0], buf, sizeof(buf) - 1);
if (n > 0) buf[n] = 0;
char *nl = strchr(buf, '\n');
if (nl) *nl = 0;
close(pipefd[0]);
int status = 0;
waitpid(pid, &status, 0);
out("exec %s: status %d, said \"%s\"", path, WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status), buf);
}
JNIEXPORT jstring JNICALL Java_com_droiddeck_phantomlab_Native_probe(JNIEnv *env, jclass cls, jstring jwhat, jintArray jfds) {
report_len = 0;
if (report) report[0] = 0;
const char *what = jwhat ? (*env)->GetStringUTFChars(env, jwhat, NULL) : "self";
int n = (*env)->GetArrayLength(env, jfds);
jint *fds = (*env)->GetIntArrayElements(env, jfds, NULL);
char spec[1024];
snprintf(spec, sizeof(spec), "%s", what);
char *save = NULL;
for (char *tok = strtok_r(spec, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
if (!strcmp(tok, "self")) probe_self();
else if (!strcmp(tok, "memfd_exec")) probe_memfd_exec();
else if (!strcmp(tok, "anon_exec")) probe_anon_exec();
else if (!strcmp(tok, "exec")) probe_exec();
else if (!strcmp(tok, "fds")) for (int i = 0; i < n; i++) probe_fd(i, fds[i]);
else if (!strncmp(tok, "pid=", 4)) probe_pid(tok + 4);
else if (!strcmp(tok, "escape")) probe_escape();
else if (!strncmp(tok, "libexec=", 8)) probe_libexec(tok + 8, n > 0 ? fds[0] : -1);
}
(*env)->ReleaseIntArrayElements(env, jfds, fds, 0);
return (*env)->NewStringUTF(env, report ? report : "");
}