mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
docs: research Android's child-process limit without developer options
This commit is contained in:
1 parent
b08d8e8e19
commit
2e170ae12b
21 files changed
+1050
No files matched your search
@@ -0,0 +1,216 @@
|
||||
# Android's child-process limit without developer options
|
||||
|
||||
Research log for removing DroidDeck's requirement to turn off "Restrict child processes" (or run
|
||||
`settings put global settings_enable_monitor_phantom_procs false` over wireless ADB). The goal:
|
||||
Android must not kill a Steam session for having too many Linux processes, and the user must not
|
||||
need developer options.
|
||||
|
||||
Status: **two gaps in Android's process counting are confirmed on Android 15 (emulator)**; both
|
||||
are in identical code on Android 12 through 16. Verification on the Thor (Android 13) and a
|
||||
DroidDeck prototype are next. The experiments are in `tools/phantomlab` (see the end).
|
||||
|
||||
## How Android counts and kills
|
||||
|
||||
Source: `frameworks/base/services/core/java/com/android/server/am/PhantomProcessList.java`
|
||||
(android12-release to android16-release and main; the parts below are unchanged across them).
|
||||
|
||||
1. **What is counted.** For every app process AMS knows (`mPidsSelfLocked`),
|
||||
`lookForPhantomProcessesLocked(app)` reads
|
||||
`/sys/fs/cgroup/uid_<app.info.uid>/pid_<pid>/cgroup.procs` (`/acct/...` on cgroup v1). Every
|
||||
pid listed there other than the app process itself is a "phantom process". `cgroup.procs`
|
||||
lists thread-group ids, so threads never count.
|
||||
2. **What is skipped.**
|
||||
- `if (app.appZygote || app.isKilled() || app.isKilledByAm()) return;`. `appZygote` is true
|
||||
for uids in `FIRST_APP_ZYGOTE_ISOLATED_UID..LAST_APP_ZYGOTE_ISOLATED_UID` (90000–98999),
|
||||
i.e. every process forked from an app zygote (`ProcessRecord` constructor).
|
||||
- A pid that is itself an app process (`mPidsSelfLocked.get(pid) != null`).
|
||||
- A pid whose `/proc/<pid>/cmdline` cannot be opened, whose uid cannot be read, or for which
|
||||
`pidfd_open` fails. These only happen once the process is gone (an empty cmdline reads as
|
||||
`""`, not `null`, so it is still counted).
|
||||
3. **When.** Only after AMS refreshes CPU stats (`AppProfiler.updateCpuStatsNow` →
|
||||
`updateProcessCpuStatesLocked`), at most every 5 s (`MONITOR_CPU_MIN_TIME`), and only when
|
||||
something asks for it: activity and process lifecycle events, mostly. Also from
|
||||
`setProcessGroupForPhantomProcessOfApp` when an app changes scheduling group. A new phantom
|
||||
schedules `trimPhantomProcessesIfNecessary`.
|
||||
4. **The kill.** When the device-wide total exceeds `max_phantom_processes` (32), phantoms are
|
||||
sorted by their app's oom adj (least important first), then youngest first, and the surplus is
|
||||
killed (`SIGKILL` and `killProcessGroup`). As the foreground app, other apps' phantoms go first,
|
||||
so the practical budget is our own 32. The newest process (often the game just launched) is the
|
||||
first of ours to go.
|
||||
5. **The second killer.** `ActivityManagerService.updatePhantomProcessCpuTimeLPr`: when the app is
|
||||
at `PROCESS_STATE_HOME` or below (backgrounded, no foreground service) and a phantom used
|
||||
"excessive" CPU, `killPhantomProcessGroupLocked` kills every phantom of that app **and the app**.
|
||||
|
||||
Both are switched off only by `settings_enable_monitor_phantom_procs=false` (the developer option)
|
||||
or by raising `max_phantom_processes` through `device_config` (shell only).
|
||||
|
||||
Today an idle Steam session is about 30 processes and a session with a game about 45 (#566, #575).
|
||||
|
||||
## Gap 1: an isolated process's children are never counted
|
||||
|
||||
Two independent reasons, either of which is enough:
|
||||
|
||||
- **Wrong cgroup path.** The path is built from `app.info.uid`, the *package's* uid (10148 here),
|
||||
but an isolated process runs as its own uid (99000+ for `android:isolatedProcess`, 90000+ from an
|
||||
app zygote) and its cgroup is `uid_<isolated uid>/pid_<pid>`. The lookup finds nothing
|
||||
(`FileNotFoundException`, logged only with `DEBUG_PROCESSES`) and the process is skipped.
|
||||
- **App zygote skip.** Processes forked from an app zygote (`android:useAppZygote="true"`) are
|
||||
skipped outright by the `app.appZygote` check, by design ("doesn't have its own acct entry").
|
||||
This one survives even if Google fixes the path.
|
||||
|
||||
Measured on the Android 15 x86_64 emulator, kernel 6.6, `max_phantom_processes=4`, monitoring on:
|
||||
|
||||
| Where the children were forked | Children | Phantoms Android listed | Killed |
|
||||
|---|---|---|---|
|
||||
| Main app process (control) | 10 | 10 | 6 ("Trimming phantom processes") |
|
||||
| `isolatedProcess` + `useAppZygote` service (uid 90000) | 40 | 0 | 0 |
|
||||
| plain `isolatedProcess` service (uid 99000) | 10 | 0 | 0 |
|
||||
|
||||
`cgroup.procs` of `/sys/fs/cgroup/uid_90000/pid_<service>` held all 41 pids the whole time; the
|
||||
phantom list (`dumpsys activity processes`, "All Active App Child Processes") only ever showed the
|
||||
main process's children.
|
||||
|
||||
## Gap 2: a process that execs in place is an app process, not a phantom
|
||||
|
||||
An `android:process` service process can `execve()` a Linux program in place. If it first clears
|
||||
`FD_CLOEXEC` on its binder fd, the binder node stays alive, so AMS never sees the process die. The
|
||||
pid stays in `mPidsSelfLocked` and is never counted. Its own children are counted as usual.
|
||||
|
||||
| Worker `:wN` | Result |
|
||||
|---|---|
|
||||
| exec `/system/bin/sleep`, binder fd closed by exec (control) | "has died" at once; AMS restarts the service |
|
||||
| exec `/system/bin/sleep`, binder fd kept | stays `fg`/`(service)` while bound; survives a density change, `am send-trim-memory`, Home/back cycles |
|
||||
| exec `sh` forking 6 `sleep`s, binder fd kept | `sh` not counted; its 6 children counted (2 trimmed at limit 4) |
|
||||
| guest exits (killed) | AMS logs "has died" and removes the cgroup, as for any app process |
|
||||
|
||||
Calls AMS makes into the process after the exec fail cleanly: the kernel logs
|
||||
`binder_alloc_buf, no vma` and AMS gets `DeadObjectException` ("Failed for dead process.
|
||||
ClientTransactionItem=ConfigurationChangeItem", "Remote exception" for trim). Nothing kills the
|
||||
process for it. It is frozen like any cached process when the app goes to the background without a
|
||||
foreground service.
|
||||
|
||||
## What else was tried
|
||||
|
||||
| Idea | Result |
|
||||
|---|---|
|
||||
| Move a process to another cgroup (`cgroup.procs` of root, of `uid_N`) | `EACCES`: dirs are `system:system 0775` and SELinux denies `cgroup_v2` writes to apps |
|
||||
| Make a sub-cgroup under our `pid_N` (children of a sub-cgroup are not in its `cgroup.procs`) | `EACCES` |
|
||||
| `clone3(CLONE_INTO_CGROUP)` | apps cannot open `/sys/fs/cgroup` (SELinux `read` denied) |
|
||||
| `unshare(CLONE_NEWUSER)` / `CLONE_NEWCGROUP` | `EINVAL` (no user namespaces in GKI) / `EPERM` |
|
||||
| Empty `/proc/<pid>/cmdline` | read as `""`, still counted; changing it needs `PR_SET_MM` (`CAP_SYS_RESOURCE`) |
|
||||
| Run "processes" as threads (`CLONE_THREAD`) | only with a shared address space; Steam, Chromium and Wine rely on real processes |
|
||||
| More `android:process` services hosting the tree | each process's children are still phantoms; only the process itself is free (Gap 2) |
|
||||
| Rely on kill order | we are the foreground app, so our own newest processes die first |
|
||||
|
||||
## What an isolated process can do
|
||||
|
||||
Measured from both isolated variants (domain `isolated_app`) against the normal app
|
||||
(`untrusted_app`), with fds created by the app and passed over binder:
|
||||
|
||||
| | app | isolated |
|
||||
|---|---|---|
|
||||
| `fork` | ✅ | ✅ (children uncounted) |
|
||||
| `execve` of an executable in the APK's lib dir (as `libddexec.so`) | ✅ | ✅ |
|
||||
| `execve` of `/system/bin/*` | ✅ | ✅ |
|
||||
| create `AF_INET` socket | ✅ | ❌ `EACCES` |
|
||||
| `connect`/`send`/`recv` on a TCP or UDP socket the app created | ✅ | ✅ (policy: "network sockets received over IPC") |
|
||||
| read/write a passed unix stream socket / pipe | ✅ | ✅ |
|
||||
| `open()` an app data file by path | ✅ | ❌ `ENOENT` (not mounted) |
|
||||
| read/write/`mmap` a passed app data file | ✅ | ✅ |
|
||||
| `mmap(PROT_EXEC)` of a passed app data file | ✅ | ❌ `EACCES` |
|
||||
| receive a passed directory fd | ✅ | ❌ (binder refuses the transaction) |
|
||||
| `mmap(PROT_EXEC)` of a memfd, anonymous RWX (JIT) | ✅ | ✅ |
|
||||
| GPU device (`/dev/kgsl-3d0`, `/dev/mali0`) | ✅ | ❌ (`neverallow`, also for passed fds) |
|
||||
| signal or read `/proc` of the app's processes | ✅ | ❌ (`EPERM`, `EACCES`) |
|
||||
|
||||
Isolated processes can talk to each other through abstract unix sockets. Everything else in the
|
||||
app's world (files, sockets to the app's servers, the GPU) has to be brokered through fds.
|
||||
|
||||
## Routes
|
||||
|
||||
### A. An isolated tier for everything that does not touch the GPU
|
||||
|
||||
Run a session's GPU-free processes inside one app-zygote isolated service; their whole fork tree is
|
||||
invisible. Needed:
|
||||
|
||||
- **Loader:** `libddexec.so` already starts programs without the kernel loading them; it would take
|
||||
its ELF from an inherited fd and copy segments into anonymous or memfd memory, since isolated
|
||||
processes cannot map app files executable. A broker can hand out one sealed memfd per library so
|
||||
pages stay shared.
|
||||
- **File broker:** the native hook already funnels path calls through `rewrite_path`; in the
|
||||
isolated tier those calls become requests to a broker in the app, which opens the file and returns
|
||||
the fd. Directories cannot be passed, so `opendir`/`getdents` are served from listings.
|
||||
Raw syscalls (Wine's preloader, FEX internals) need a seccomp `SIGSYS` trap, which the hook
|
||||
already uses for Android's own filter.
|
||||
- **Sockets:** `socket(AF_INET*)` → broker-created socket; then the process connects itself.
|
||||
Unix sockets between isolated processes become abstract sockets; connections to servers in the
|
||||
app (compositor, PipeWire, VkBridge) are connected by the broker.
|
||||
- **No signals across the boundary:** a process and everything it signals or ptraces must be on the
|
||||
same side. Wine's processes all depend on `wineserver` signalling them, so Wine stays with the game.
|
||||
- **GPU:** only through a remoting layer such as VkBridge (already used on Mali), never directly.
|
||||
|
||||
Candidates for the tier: the Steam client and its web helper's renderer/utility processes (with
|
||||
the web helper's GPU work remoted or in software), the session scripts, D-Bus services, PipeWire
|
||||
helpers, Python daemons. A cross-tier launch (Steam starting the game's `reaper`) runs through the
|
||||
broker, with a small stand-in process left in the tier for Steam to wait on. Stand-ins are free
|
||||
there.
|
||||
|
||||
### B. Exec-in-place workers for long-lived processes
|
||||
|
||||
Declare a pool of `android:process` services (`:g0`…`:g95`). Each long-lived program runs as the
|
||||
main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc`
|
||||
(same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits:
|
||||
|
||||
- A worker is a zygote fork (~100 ms); a pre-started pool removes the wait.
|
||||
- Only the worker's main process is free; its children count. So each long-lived program must be
|
||||
started in its own worker, not forked by its parent.
|
||||
- Programs the app or the session script start and do not wait on (Xwayland, D-Bus, PipeWire,
|
||||
helpers, `wineserver -p`) can move with a `droiddeck-spawn` client and no other change.
|
||||
- A program another guest forks and waits on (Wine's processes, Steam's children) needs the hook to
|
||||
hand the exec to a worker and translate the pid for the parent: `wait4`, `kill`, `/proc/<pid>`,
|
||||
`SIGCHLD`. All app processes share zygote's session (sid 0, pgid of zygote), so `setpgid` and
|
||||
process-group signals across workers are possible.
|
||||
- Relies on AMS never pinging a process; today it only sends oneway calls that fail harmlessly.
|
||||
|
||||
### C. Plan
|
||||
|
||||
1. Verify both gaps on the Thor (Android 13, 5.15) and one Android 14 device.
|
||||
2. B for the processes DroidDeck and the session script start themselves (no pid translation).
|
||||
Measure the session's count.
|
||||
3. A for the Steam client tree if 2 is not enough. Only GPU, Wine and game processes then stay in
|
||||
the counted cgroup, about 15 with a game running.
|
||||
4. Keep the developer-option check as a fallback until the count with a game running stays well
|
||||
under 32 on every supported device, then turn it into a warning.
|
||||
|
||||
## Robustness
|
||||
|
||||
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
|
||||
zygote isolated services so either one is enough.
|
||||
- Gap 2 depends on AMS not probing liveness. A future check (a ping, or watching a pidfd for the
|
||||
binder) would end it; the session would then fall back to counted processes, which is today's
|
||||
behavior.
|
||||
- OEM ROMs with their own process managers (MIUI/HyperOS, ColorOS) are outside this.
|
||||
|
||||
## phantomlab
|
||||
|
||||
`tools/phantomlab` is a standalone test app (package `com.droiddeck.phantomlab`, no Gradle). It
|
||||
forks sleepers from the main process, a plain isolated service, an app-zygote isolated service and
|
||||
eight `:wN` workers, execs in place, and probes what a process may do.
|
||||
|
||||
```
|
||||
tools/phantomlab/build.sh # build/phantomlab.apk, debug-signed
|
||||
adb install -r tools/phantomlab/build/phantomlab.apk
|
||||
adb shell device_config set_sync_disabled_for_tests persistent
|
||||
adb shell device_config put activity_manager max_phantom_processes 4
|
||||
adb shell settings put global settings_enable_monitor_phantom_procs true
|
||||
adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso:a --ei n 40
|
||||
adb shell "am start -n com.droiddeck.phantomlab/.Main --es cmd exec --es target w0 --ei keep 1 --es argv '/system/bin/sleep|100000'"
|
||||
adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd probe --es target iso:a --es what self,memfd_exec,exec,fds,escape,libexec --es fds tcp,udp,unix,file:probe.txt
|
||||
adb logcat -s PLAB ActivityManager | grep -i 'PLAB\|Trimming'
|
||||
```
|
||||
|
||||
Targets: `main`, `proc` (`:proc`), `isoplain`, `iso:<name>` (one app-zygote instance per name),
|
||||
`w0`…`w7`. Android scans only on CPU-stat refreshes, so switch apps a few times (5 s apart) before
|
||||
reading the phantom list. Restore afterwards with
|
||||
`device_config delete activity_manager max_phantom_processes` and
|
||||
`device_config set_sync_disabled_for_tests none`.
|
||||
@@ -0,0 +1 @@
|
||||
build/
|
||||
@@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.droiddeck.phantomlab">
|
||||
|
||||
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:label="PhantomLab"
|
||||
android:extractNativeLibs="true"
|
||||
android:zygotePreloadName="com.droiddeck.phantomlab.Preload">
|
||||
|
||||
<activity android:name=".Main" android:exported="true" android:launchMode="singleTask"
|
||||
android:configChanges="density|orientation|screenSize|screenLayout|smallestScreenSize|uiMode|keyboard|keyboardHidden|navigation|fontScale">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service android:name=".Iso" android:exported="false"
|
||||
android:isolatedProcess="true" android:useAppZygote="true" />
|
||||
<service android:name=".IsoPlain" android:exported="false"
|
||||
android:isolatedProcess="true" />
|
||||
<service android:name=".Proc" android:exported="false" android:process=":proc" />
|
||||
|
||||
<service android:name=".W0" android:exported="false" android:process=":w0" />
|
||||
<service android:name=".W1" android:exported="false" android:process=":w1" />
|
||||
<service android:name=".W2" android:exported="false" android:process=":w2" />
|
||||
<service android:name=".W3" android:exported="false" android:process=":w3" />
|
||||
<service android:name=".W4" android:exported="false" android:process=":w4" />
|
||||
<service android:name=".W5" android:exported="false" android:process=":w5" />
|
||||
<service android:name=".W6" android:exported="false" android:process=":w6" />
|
||||
<service android:name=".W7" android:exported="false" android:process=":w7" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds phantomlab.apk without Gradle: javac, d8, aapt2, the NDK's clang, apksigner (debug key).
|
||||
# usage: tools/phantomlab/build.sh [out.apk] (ANDROID_SDK_ROOT or ANDROID_HOME must be set)
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
sdk=${ANDROID_SDK_ROOT:-${ANDROID_HOME:?set ANDROID_SDK_ROOT}}
|
||||
bt=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1)
|
||||
platform=$(ls -d "$sdk"/platforms/android-* | sort -V | tail -1)
|
||||
ndk=${ANDROID_NDK_ROOT:-$(ls -d "$sdk"/ndk/* | sort -V | tail -1)}
|
||||
out=${1:-$here/build/phantomlab.apk}
|
||||
work=$here/build
|
||||
exe=""
|
||||
case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) exe=".exe" ;; esac
|
||||
bat=""
|
||||
[ -n "$exe" ] && bat=".bat"
|
||||
|
||||
rm -rf "$work/classes" "$work/dex" "$work/lib" "$work/unsigned.apk"
|
||||
mkdir -p "$work/classes" "$work/dex"
|
||||
|
||||
javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" $(find "$here/src" -name '*.java') 2>&1 | grep -v "^warning\|^Note:" || true
|
||||
"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" $(find "$work/classes" -name '*.class')
|
||||
|
||||
host=$(ls -d "$ndk"/toolchains/llvm/prebuilt/* | head -1)
|
||||
for abi in arm64-v8a x86_64; do
|
||||
case $abi in arm64-v8a) triple=aarch64-linux-android29 ;; x86_64) triple=x86_64-linux-android29 ;; esac
|
||||
mkdir -p "$work/lib/$abi"
|
||||
"$host/bin/clang$exe" --target=$triple -shared -fPIC -O2 -Wall -o "$work/lib/$abi/liblab.so" "$here/jni/lab.c" -llog
|
||||
"$host/bin/clang$exe" --target=$triple -fPIE -pie -O2 -Wall -o "$work/lib/$abi/libplabexe.so" "$here/jni/exe.c"
|
||||
done
|
||||
|
||||
"$bt/aapt2$exe" link -o "$work/unsigned.apk" -I "$platform/android.jar" --manifest "$here/AndroidManifest.xml"
|
||||
python3 - "$work" <<'EOF'
|
||||
import os, sys, zipfile
|
||||
work = sys.argv[1]
|
||||
with zipfile.ZipFile(os.path.join(work, "unsigned.apk"), "a", zipfile.ZIP_DEFLATED) as z:
|
||||
z.write(os.path.join(work, "dex", "classes.dex"), "classes.dex")
|
||||
for abi in os.listdir(os.path.join(work, "lib")):
|
||||
for so in ("liblab.so", "libplabexe.so"):
|
||||
z.write(os.path.join(work, "lib", abi, so), "lib/%s/%s" % (abi, so))
|
||||
EOF
|
||||
|
||||
key=$work/debug.keystore
|
||||
[ -f "$key" ] || keytool -genkeypair -keystore "$key" -storepass android -keypass android -alias lab \
|
||||
-keyalg RSA -keysize 2048 -validity 10000 -dname "CN=phantomlab" >/dev/null 2>&1
|
||||
"$bt/zipalign$exe" -f -p 4 "$work/unsigned.apk" "$work/aligned.apk"
|
||||
"$bt/apksigner$bat" sign --ks "$key" --ks-pass pass:android --out "$out" "$work/aligned.apk"
|
||||
echo "$out"
|
||||
@@ -0,0 +1,21 @@
|
||||
// libplabexe.so: an executable shipped as a "library" so the APK's lib directory holds it.
|
||||
// Reports its identity and reads fd 3 when it is open, then exits with status 7.
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char buf[128] = "";
|
||||
ssize_t n = read(3, buf, sizeof(buf) - 1);
|
||||
if (n > 0) buf[n] = 0;
|
||||
char ctx[128] = "";
|
||||
int fd = open("/proc/self/attr/current", O_RDONLY);
|
||||
if (fd >= 0) {
|
||||
ssize_t m = read(fd, ctx, sizeof(ctx) - 1);
|
||||
if (m > 0) ctx[m] = 0;
|
||||
close(fd);
|
||||
}
|
||||
dprintf(2, "plabexe uid=%d ctx=%s fd3=%s\n", getuid(), ctx, n > 0 ? buf : "none");
|
||||
return 7;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
// 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 <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;
|
||||
}
|
||||
|
||||
static void keep_binder_fds(void) {
|
||||
DIR *d = opendir("/proc/self/fd");
|
||||
if (!d) return;
|
||||
struct dirent *e;
|
||||
char path[64], target[256];
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
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")) {
|
||||
fcntl(fd, F_SETFD, 0);
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
if (keep) keep_binder_fds();
|
||||
execv(argv[0], argv);
|
||||
__android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno));
|
||||
}
|
||||
|
||||
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) {
|
||||
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 void probe_exec(void) {
|
||||
char *argv[] = {"/system/bin/true", NULL};
|
||||
int st = run_child(argv, -1);
|
||||
out("execve /system/bin/true: %s", st == 0 ? "ok" : (st >= 100 && st < 1000 ? strerror(st - 100) : "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", st == 0 ? "ok" : (st >= 100 && st < 1000 ? strerror(st - 100) : "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) {
|
||||
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)};
|
||||
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
|
||||
if (connect(fd, (struct sockaddr *)&a, sizeof(a)) != 0) {
|
||||
out("fd%d tcp: connect %s", i, strerror(errno));
|
||||
return;
|
||||
}
|
||||
const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n";
|
||||
write(fd, req, strlen(req));
|
||||
char resp[64] = "";
|
||||
ssize_t r = read(fd, resp, sizeof(resp) - 1);
|
||||
if (r > 0) resp[r] = 0;
|
||||
char *nl = strchr(resp, '\r');
|
||||
if (nl) *nl = 0;
|
||||
out("fd%d tcp: connected, got \"%s\"", i, r > 0 ? resp : strerror(errno));
|
||||
} 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 = read(fd, buf, sizeof(buf) - 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, st2 >= 100 && st2 < 1000 ? strerror(st2 - 100) : "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];
|
||||
pipe(pipefd);
|
||||
pid_t pid = fork();
|
||||
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 : "");
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class Iso extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class IsoPlain extends LabService {}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.os.Parcel;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
public class LabService extends Service {
|
||||
static final int SPAWN = 1;
|
||||
static final int PROBE = 2;
|
||||
static final int EXEC = 3;
|
||||
static final int WHO = 4;
|
||||
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final Binder binder = new Binder() {
|
||||
@Override
|
||||
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
|
||||
switch (code) {
|
||||
case SPAWN: {
|
||||
int n = data.readInt();
|
||||
reply.writeInt(Native.spawn(n));
|
||||
return true;
|
||||
}
|
||||
case PROBE: {
|
||||
String what = data.readString().replace("libexec",
|
||||
"libexec=" + getApplicationInfo().nativeLibraryDir + "/libplabexe.so");
|
||||
int[] fds = readFds(data);
|
||||
reply.writeString(Native.probe(what, fds));
|
||||
return true;
|
||||
}
|
||||
case EXEC: {
|
||||
final String[] argv = data.createStringArray();
|
||||
final boolean keep = data.readInt() != 0;
|
||||
Log.i(Main.TAG, "pid " + Process.myPid() + " execs " + String.join(" ", argv) + " keepBinder=" + keep);
|
||||
handler.postDelayed(() -> Native.execInPlace(argv, keep), 500);
|
||||
reply.writeInt(Process.myPid());
|
||||
return true;
|
||||
}
|
||||
case WHO:
|
||||
reply.writeString("pid=" + Process.myPid() + " uid=" + Process.myUid()
|
||||
+ " isolated=" + Process.isIsolated());
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private static int[] readFds(Parcel data) {
|
||||
int n = data.readInt();
|
||||
int[] fds = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
ParcelFileDescriptor pfd = data.readFileDescriptor();
|
||||
fds[i] = pfd == null ? -1 : pfd.detachFd();
|
||||
}
|
||||
return fds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
Log.i(Main.TAG, getClass().getSimpleName() + " bound in pid " + Process.myPid() + " uid " + Process.myUid());
|
||||
return binder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
import android.os.Parcel;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.os.Process;
|
||||
import android.system.Os;
|
||||
import android.system.OsConstants;
|
||||
import android.util.Log;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileDescriptor;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Drive with: am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso --ei n 40
|
||||
* Results go to logcat under the PLAB tag.
|
||||
*/
|
||||
public class Main extends Activity {
|
||||
static final String TAG = "PLAB";
|
||||
|
||||
private static final Map<String, IBinder> binders = new HashMap<>();
|
||||
private static final Map<String, List<Runnable>> pending = new HashMap<>();
|
||||
private static final Map<String, ServiceConnection> connections = new HashMap<>();
|
||||
private TextView text;
|
||||
private static final List<FileDescriptor> keep = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
text = new TextView(this);
|
||||
setContentView(text);
|
||||
log("main pid " + Process.myPid() + " uid " + Process.myUid());
|
||||
handle(getIntent());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
handle(intent);
|
||||
}
|
||||
|
||||
private void log(String s) {
|
||||
Log.i(TAG, s);
|
||||
text.append(s + "\n");
|
||||
}
|
||||
|
||||
private static Class<?> serviceClass(String target) {
|
||||
String base = target.contains(":") ? target.substring(0, target.indexOf(':')) : target;
|
||||
switch (base) {
|
||||
case "iso": return Iso.class;
|
||||
case "isoplain": return IsoPlain.class;
|
||||
case "proc": return Proc.class;
|
||||
default:
|
||||
if (base.startsWith("w")) {
|
||||
try {
|
||||
return Class.forName("com.droiddeck.phantomlab.W" + base.substring(1));
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new IllegalArgumentException(target);
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException(target);
|
||||
}
|
||||
}
|
||||
|
||||
private void withBinder(String target, Runnable op) {
|
||||
if (binders.containsKey(target)) {
|
||||
op.run();
|
||||
return;
|
||||
}
|
||||
List<Runnable> q = pending.get(target);
|
||||
if (q != null) {
|
||||
q.add(op);
|
||||
return;
|
||||
}
|
||||
q = new ArrayList<>();
|
||||
q.add(op);
|
||||
pending.put(target, q);
|
||||
ServiceConnection conn = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName name, IBinder service) {
|
||||
log("connected " + target);
|
||||
binders.put(target, service);
|
||||
List<Runnable> ops = pending.remove(target);
|
||||
if (ops != null) for (Runnable r : ops) r.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName name) {
|
||||
log("DISCONNECTED " + target);
|
||||
binders.remove(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindingDied(ComponentName name) {
|
||||
log("BINDING DIED " + target);
|
||||
}
|
||||
};
|
||||
connections.put(target, conn);
|
||||
Intent intent = new Intent(this, serviceClass(target));
|
||||
int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT;
|
||||
boolean ok;
|
||||
if (target.contains(":")) {
|
||||
ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn);
|
||||
} else {
|
||||
ok = getApplicationContext().bindService(intent, conn, flags);
|
||||
}
|
||||
log("bind " + target + " -> " + ok);
|
||||
}
|
||||
|
||||
private Parcel call(String target, int code, Parcel data) throws Exception {
|
||||
Parcel reply = Parcel.obtain();
|
||||
binders.get(target).transact(code, data, reply, 0);
|
||||
return reply;
|
||||
}
|
||||
|
||||
private void handle(Intent intent) {
|
||||
String cmd = intent.getStringExtra("cmd");
|
||||
if (cmd == null) return;
|
||||
String target = intent.getStringExtra("target");
|
||||
try {
|
||||
switch (cmd) {
|
||||
case "spawn": {
|
||||
int n = intent.getIntExtra("n", 10);
|
||||
if ("main".equals(target)) {
|
||||
log("main spawned " + Native.spawn(n));
|
||||
return;
|
||||
}
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeInt(n);
|
||||
log(target + " spawned " + call(target, LabService.SPAWN, d).readInt());
|
||||
} catch (Exception e) {
|
||||
log(target + " spawn failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "who":
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
log(target + " " + call(target, LabService.WHO, Parcel.obtain()).readString());
|
||||
} catch (Exception e) {
|
||||
log(target + " who failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
case "exec": {
|
||||
String[] argv = intent.getStringExtra("argv").split("\\|");
|
||||
boolean keepBinder = intent.getIntExtra("keep", 1) != 0;
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeStringArray(argv);
|
||||
d.writeInt(keepBinder ? 1 : 0);
|
||||
log(target + " exec in pid " + call(target, LabService.EXEC, d).readInt());
|
||||
} catch (Exception e) {
|
||||
log(target + " exec failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "probe": {
|
||||
String what = intent.getStringExtra("what");
|
||||
List<ParcelFileDescriptor> fds = probeFds(intent.getStringExtra("fds"));
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeString(what);
|
||||
d.writeInt(fds.size());
|
||||
for (ParcelFileDescriptor p : fds) d.writeFileDescriptor(p.getFileDescriptor());
|
||||
for (String line : call(target, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line);
|
||||
} catch (Exception e) {
|
||||
log(target + " probe failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "unbind": {
|
||||
ServiceConnection c = connections.remove(target);
|
||||
binders.remove(target);
|
||||
if (c != null) getApplicationContext().unbindService(c);
|
||||
log("unbound " + target);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
log("unknown cmd " + cmd);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log(cmd + " failed " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/** fds: comma separated list of tcp, udp, file:<name>, unix, memfd. */
|
||||
private List<ParcelFileDescriptor> probeFds(String spec) throws Exception {
|
||||
List<ParcelFileDescriptor> out = new ArrayList<>();
|
||||
if (spec == null || spec.isEmpty()) return out;
|
||||
for (String s : spec.split(",")) {
|
||||
if (s.equals("tcp") || s.equals("udp")) {
|
||||
FileDescriptor fd = Os.socket(OsConstants.AF_INET,
|
||||
s.equals("tcp") ? OsConstants.SOCK_STREAM : OsConstants.SOCK_DGRAM, 0);
|
||||
keep.add(fd);
|
||||
out.add(ParcelFileDescriptor.dup(fd));
|
||||
} else if (s.equals("unix")) {
|
||||
FileDescriptor a = new FileDescriptor();
|
||||
FileDescriptor b = new FileDescriptor();
|
||||
Os.socketpair(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0, a, b);
|
||||
Os.write(a, "hello from main\n".getBytes(), 0, 16);
|
||||
keep.add(a);
|
||||
out.add(ParcelFileDescriptor.dup(b));
|
||||
} else if (s.startsWith("file:")) {
|
||||
File f = new File(getFilesDir(), s.substring(5));
|
||||
if (!f.exists()) {
|
||||
try (FileOutputStream o = new FileOutputStream(f)) {
|
||||
o.write("data file contents\n".getBytes());
|
||||
}
|
||||
}
|
||||
out.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE));
|
||||
} else if (s.startsWith("path:")) {
|
||||
out.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY));
|
||||
} else if (s.equals("dir")) {
|
||||
out.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
final class Native {
|
||||
static {
|
||||
System.loadLibrary("lab");
|
||||
}
|
||||
|
||||
/** Forks n children that sleep until killed; returns how many were started. */
|
||||
static native int spawn(int n);
|
||||
|
||||
/** execve(argv) in this process; with keepBinder, the binder fds stay open across it. */
|
||||
static native void execInPlace(String[] argv, boolean keepBinder);
|
||||
|
||||
/** Runs the capability probes named in what, using the given fds; returns a report. */
|
||||
static native String probe(String what, int[] fds);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.ZygotePreload;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
|
||||
public class Preload implements ZygotePreload {
|
||||
@Override
|
||||
public void doPreload(ApplicationInfo appInfo) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class Proc extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W0 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W1 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W2 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W3 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W4 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W5 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W6 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W7 extends LabService {}
|
||||
Reference in new issue
Block a user