Compare commits

...
28 changed files with 1497 additions and 6 deletions

No files matched your search

+24
View File
@@ -414,5 +414,29 @@
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
tools:node="remove" />
</service>
<service android:name=".runtime.GuestWorker0" android:exported="false" android:process=":g0" />
<service android:name=".runtime.GuestWorker1" android:exported="false" android:process=":g1" />
<service android:name=".runtime.GuestWorker2" android:exported="false" android:process=":g2" />
<service android:name=".runtime.GuestWorker3" android:exported="false" android:process=":g3" />
<service android:name=".runtime.GuestWorker4" android:exported="false" android:process=":g4" />
<service android:name=".runtime.GuestWorker5" android:exported="false" android:process=":g5" />
<service android:name=".runtime.GuestWorker6" android:exported="false" android:process=":g6" />
<service android:name=".runtime.GuestWorker7" android:exported="false" android:process=":g7" />
<service android:name=".runtime.GuestWorker8" android:exported="false" android:process=":g8" />
<service android:name=".runtime.GuestWorker9" android:exported="false" android:process=":g9" />
<service android:name=".runtime.GuestWorker10" android:exported="false" android:process=":g10" />
<service android:name=".runtime.GuestWorker11" android:exported="false" android:process=":g11" />
<service android:name=".runtime.GuestWorker12" android:exported="false" android:process=":g12" />
<service android:name=".runtime.GuestWorker13" android:exported="false" android:process=":g13" />
<service android:name=".runtime.GuestWorker14" android:exported="false" android:process=":g14" />
<service android:name=".runtime.GuestWorker15" android:exported="false" android:process=":g15" />
<service android:name=".runtime.GuestWorker16" android:exported="false" android:process=":g16" />
<service android:name=".runtime.GuestWorker17" android:exported="false" android:process=":g17" />
<service android:name=".runtime.GuestWorker18" android:exported="false" android:process=":g18" />
<service android:name=".runtime.GuestWorker19" android:exported="false" android:process=":g19" />
<service android:name=".runtime.GuestWorker20" android:exported="false" android:process=":g20" />
<service android:name=".runtime.GuestWorker21" android:exported="false" android:process=":g21" />
<service android:name=".runtime.GuestWorker22" android:exported="false" android:process=":g22" />
<service android:name=".runtime.GuestWorker23" android:exported="false" android:process=":g23" />
</application>
</manifest>
@@ -20,6 +20,8 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
if (android.os.Build.VERSION.SDK_INT >= 28 &&
com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
@@ -0,0 +1,271 @@
package com.droiddeck.launcher.runtime
import android.app.ActivityManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.LocalServerSocket
import android.net.LocalSocket
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.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import android.util.Log
import org.json.JSONObject
import java.io.DataInputStream
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* A guest program run as the main process of its own Android process.
*
* Android counts the processes in an app process's cgroup against its child-process limit, but not
* the app processes themselves. The worker execs the program in place; its binder fd stays open
* across the exec, so the system keeps the process as a live service process. The program's own
* children are still counted. See docs/phantom-processes.md.
*/
open class GuestWorker : Service() {
private val binder = object : Binder() {
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (code != RUN) return super.onTransact(code, data, reply, flags)
val argv = data.createStringArray() ?: return false
val env = data.createStringArray() ?: return false
val stdio = List(data.readInt()) { data.readFileDescriptor() }
reply?.writeInt(Process.myPid())
Handler(Looper.getMainLooper()).postDelayed({ exec(argv, env, stdio) }, EXEC_DELAY_MS)
return true
}
}
override fun onBind(intent: Intent): IBinder = binder
private fun exec(argv: Array<String>, env: Array<String>, stdio: List<ParcelFileDescriptor?>) {
try {
stdio.forEachIndexed { fd, pfd -> if (pfd != null) Os.dup2(pfd.fileDescriptor, fd) }
keepBinderOpen()
Os.execve(argv[0], argv, env)
} catch (e: ErrnoException) {
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
}
Process.killProcess(Process.myPid())
}
private fun keepBinderOpen() {
File("/proc/self/fd").listFiles()?.forEach { link ->
val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
if (!target.contains("binder")) return@forEach
val fd = ParcelFileDescriptor.adoptFd(link.name.toIntOrNull() ?: return@forEach)
Os.fcntlInt(fd.fileDescriptor, OsConstants.F_SETFD, 0)
kept.add(fd)
}
}
companion object {
const val RUN = IBinder.FIRST_CALL_TRANSACTION
private const val EXEC_DELAY_MS = 100L
private const val TAG = "GuestWorker"
private val kept = ArrayList<ParcelFileDescriptor>()
fun isWorkerProcess(context: Context, process: String?): Boolean =
process != null && process.startsWith(context.packageName + ":g") &&
process.substring(context.packageName.length + 2).all { it.isDigit() }
}
}
class GuestWorker0 : GuestWorker()
class GuestWorker1 : GuestWorker()
class GuestWorker2 : GuestWorker()
class GuestWorker3 : GuestWorker()
class GuestWorker4 : GuestWorker()
class GuestWorker5 : GuestWorker()
class GuestWorker6 : GuestWorker()
class GuestWorker7 : GuestWorker()
class GuestWorker8 : GuestWorker()
class GuestWorker9 : GuestWorker()
class GuestWorker10 : GuestWorker()
class GuestWorker11 : GuestWorker()
class GuestWorker12 : GuestWorker()
class GuestWorker13 : GuestWorker()
class GuestWorker14 : GuestWorker()
class GuestWorker15 : GuestWorker()
class GuestWorker16 : GuestWorker()
class GuestWorker17 : GuestWorker()
class GuestWorker18 : GuestWorker()
class GuestWorker19 : GuestWorker()
class GuestWorker20 : GuestWorker()
class GuestWorker21 : GuestWorker()
class GuestWorker22 : GuestWorker()
class GuestWorker23 : GuestWorker()
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
object GuestWorkers {
private const val TAG = "GuestWorkers"
private val classes: List<Class<out GuestWorker>> = listOf(
GuestWorker0::class.java, GuestWorker1::class.java, GuestWorker2::class.java, GuestWorker3::class.java,
GuestWorker4::class.java, GuestWorker5::class.java, GuestWorker6::class.java, GuestWorker7::class.java,
GuestWorker8::class.java, GuestWorker9::class.java, GuestWorker10::class.java, GuestWorker11::class.java,
GuestWorker12::class.java, GuestWorker13::class.java, GuestWorker14::class.java, GuestWorker15::class.java,
GuestWorker16::class.java, GuestWorker17::class.java, GuestWorker18::class.java, GuestWorker19::class.java,
GuestWorker20::class.java, GuestWorker21::class.java, GuestWorker22::class.java, GuestWorker23::class.java,
)
private class Slot(val index: Int, val connection: ServiceConnection) {
@Volatile var pid = -1
}
private val slots = arrayOfNulls<Slot>(classes.size)
@Volatile private var server: Thread? = null
fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid()
/**
* Runs [argv] (a host command line) as the main process of a free worker with [env] and the
* fds in [stdio] as its 0, 1 and 2. Returns its pid, or -1. Blocks: not for the main thread.
* [onExit] runs once the process is gone.
*/
fun start(context: Context, argv: List<String>, env: List<String>, stdio: List<ParcelFileDescriptor>, onExit: (Int) -> Unit): Int {
val app = context.applicationContext
val connected = CountDownLatch(1)
var service: IBinder? = null
val slot: Slot
synchronized(slots) {
val index = slots.indexOfFirst { it == null }
if (index < 0) {
Log.w(TAG, "all ${slots.size} workers are busy")
return -1
}
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
service = binder
connected.countDown()
}
override fun onServiceDisconnected(name: ComponentName) = release(app, index, onExit)
override fun onBindingDied(name: ComponentName) = release(app, index, onExit)
}
slot = Slot(index, connection)
slots[index] = slot
}
val intent = Intent(app, classes[slot.index])
if (!app.bindService(intent, slot.connection, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT) ||
!connected.await(10, TimeUnit.SECONDS)) {
Log.w(TAG, "worker ${slot.index} did not start")
release(app, slot.index, null)
return -1
}
val data = Parcel.obtain()
val reply = Parcel.obtain()
try {
data.writeStringArray(argv.toTypedArray())
data.writeStringArray(env.toTypedArray())
data.writeInt(stdio.size)
stdio.forEach { data.writeFileDescriptor(it.fileDescriptor) }
service!!.transact(GuestWorker.RUN, data, reply, 0)
slot.pid = reply.readInt()
} catch (e: Exception) {
Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
release(app, slot.index, null)
return -1
} finally {
data.recycle()
reply.recycle()
}
Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
return slot.pid
}
private fun release(app: Context, index: Int, onExit: ((Int) -> Unit)?) {
val slot = synchronized(slots) { slots[index]?.also { slots[index] = null } } ?: return
runCatching { app.unbindService(slot.connection) }
if (onExit != null) Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start()
}
private fun exitStatus(app: Context, pid: Int): Int {
if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1
val am = app.getSystemService(ActivityManager::class.java)
repeat(20) {
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let { return it.status }
Thread.sleep(50)
}
return -1
}
/** Kills every worker's program; for session teardown. */
fun stopAll() {
val pids = synchronized(slots) { slots.mapNotNull { it?.pid?.takeIf { pid -> pid > 0 } } }
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
Thread.sleep(500)
pids.forEach { Process.killProcess(it) }
}
/** Listens for `droiddeck-spawn` requests from the session's guests. */
fun serve(context: Context) {
val app = context.applicationContext
synchronized(this) {
if (server != null) return
server = Thread({
val socket = try {
LocalServerSocket(socketName(app))
} catch (e: Exception) {
Log.e(TAG, "no spawn socket", e)
return@Thread
}
while (true) {
val client = runCatching { socket.accept() }.getOrNull() ?: continue
Thread({ handle(app, client) }, "guest-spawn").start()
}
}, "guest-spawn-server").apply { isDaemon = true; start() }
}
}
private fun handle(app: Context, client: LocalSocket) {
client.use {
if (client.peerCredentials.uid != Process.myUid()) return
val input = DataInputStream(client.inputStream)
val payload = ByteArray(input.readInt()).also { input.readFully(it) }
val fds = client.ancillaryFileDescriptors.orEmpty().map { ParcelFileDescriptor.dup(it) }
client.ancillaryFileDescriptors?.forEach { runCatching { Os.close(it) } }
val request = JSONObject(String(payload))
val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } }
val envObject = request.getJSONObject("env")
val env = LinkedHashMap<String, String>()
envObject.keys().forEach { env[it] = envObject.getString(it) }
val cwd = request.optString("cwd", "/")
val wait = request.optBoolean("wait", false)
val root = env["DDNATV_ROOT"]?.let(::File)
val out = client.outputStream
if (root == null || argv.isEmpty()) {
out.write("error no guest root or program\n".toByteArray())
return
}
val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile }
val script = "cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\""
val command = NativeGuest.command(root, shell, listOf("-c", script, "droiddeck-spawn", cwd) + argv)
env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path
val exited = CountDownLatch(1)
var status = -1
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, fds) { code ->
status = code
exited.countDown()
}
fds.forEach { runCatching { it.close() } }
out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
out.flush()
if (pid > 0 && wait) {
exited.await()
out.write("exit $status\n".toByteArray())
out.flush()
}
}
}
}
@@ -129,6 +129,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
@@ -701,6 +701,10 @@ class SessionService : Service() {
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
if (com.droiddeck.launcher.runtime.NativeGuest.enabled(this)) {
com.droiddeck.launcher.runtime.GuestWorkers.serve(this)
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
}
// Proton builds up to 11.12 report X11 text fields under this name.
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
@@ -1522,6 +1526,7 @@ class SessionService : Service() {
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
if (!stillSameProcess()) return
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopAll()
val tree = descendants(prootPid)
if (!stillSameProcess()) return
saveWineRegistries(tree)
+252
View File
@@ -0,0 +1,252 @@
# 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 the AYN Thor (Android 13,
kernel 5.15) and the Android 15 emulator**; both are in identical code on Android 12 through 16.
A DroidDeck prototype is 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 (most important first), then youngest first, and the surplus is
killed from the end of that list (`SIGKILL` and `killProcessGroup`): the least important app's
oldest processes go first. As the foreground app, other apps' phantoms go first, so the
practical budget is our own 32, and of ours the **oldest** die first: the session's PipeWire,
D-Bus and Steam itself, not the game that pushed the count over.
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 with `max_phantom_processes=4` and monitoring on, children killed by Android:
| Where the children were forked | Children | Thor (Android 13) | Emulator (Android 15) |
|---|---|---|---|
| Main app process (control) | 10 | 6 ("Trimming phantom processes") | 6 |
| plain `isolatedProcess` service (uid 99000+) | 10 | 0 | 0 |
| `isolatedProcess` + `useAppZygote` service (uid 90000) | 40 | 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. With the limit at 4, the Thor also trimmed another app's `logcat` child,
as expected for the device-wide count.
## 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.
Same results on the Thor and the emulator:
| 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`) |
This table is the emulator (stock, enforcing policy). **The Thor's ROM runs `isolated_app`
permissive** (every isolated denial logs `permissive=1`; `untrusted_app` is enforcing): there an
isolated process could also create inet sockets and open `/dev/kgsl-3d0`. That is an AYN quirk and
must not be relied on; design for the enforcing column.
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.
### Measured on the Thor: a real session
An idle Steam session (Big Picture at the library, Decky on, 0.7.11 / main `b08d8e8e1`) holds
**48 counted processes** in the app's cgroup, well past 32 before any game starts:
9 bash, 6 python3, 5 dbus-daemon (with the portals and at-spi under the session bus), 4 Decky
PluginLoader, 4 steamwebhelper, 2 Xwayland, gamescope and its reaper, PipeWire and WirePlumber,
Steam, the clipboard bridge, and the app's own logcat, PulseAudio and audio relay.
Prototype of B on this branch (`runtime/GuestWorkers.kt`, `droiddeck-spawn`, `dd_spawn` in the
session script; `DD_SPAWN_DAEMONS=0` turns it off): 24 `:gN` worker services, a spawn socket in the
app, and the session script starting the clipboard bridge, the system bus, login1 and the session
bus through it. Result:
- Each of the four runs as its own app process (`/sys/fs/cgroup/uid_<app>/pid_<worker>` with one
process). login1's sleep handshake, NetworkManager (state 70, full connectivity) and the Steam
library all work.
- Counted processes: **45** instead of 48. The session bus took its 9 activated children with it, so
they are still counted, under its worker.
So starting top-level daemons in workers is not enough. What is left is the processes other
programs start. Of the 47 counted processes in that session, **40 are exec'd programs** and only 7
are forks without an exec (the session script's `( … ) &` subshells). A handoff inside the native
hook, at `execve()` in a forked child, could move all 40, leaving about 7 counted at idle. That needs
the pid translation described in B (the parent keeps the forked pid; `wait4`, `kill`, `SIGCHLD` and
`/proc/<pid>` go to the worker's process).
### C. Plan
1. ~~Verify both gaps on the Thor (Android 13, 5.15)~~ done; still to do on one stock Android 14+
phone with an enforcing `isolated_app`.
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`.
@@ -14,6 +14,22 @@ export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
# Starts a long-lived program in its own Android process, which Android does not count against
# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
# Its pid is in $dd_spawned either way.
dd_spawn() {
dd_spawned=
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ] && [ -x /usr/local/bin/droiddeck-spawn ]; then
local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$
if /usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@"; then
dd_spawned=$(cat "$f" 2>/dev/null)
rm -f "$f"
[ -n "$dd_spawned" ] && return 0
fi
fi
"$@" &
dd_spawned=$!
}
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
[ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_STEAM_EXIT_FILE"
@@ -628,7 +644,7 @@ reap_orphans() {
}
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
fi
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
@@ -1384,8 +1400,8 @@ case $mode in
fi
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
system_bus=$!
dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile
system_bus=$dd_spawned
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
sleep 0.1
@@ -1393,8 +1409,8 @@ case $mode in
if [ -S /run/dbus/system_bus_socket ]; then
echo "== network: system bus up, NetworkManager stand-in running"
rm -f "$DD_LAUNCH_DIR/steam-sleep-ready"
droiddeck-login1 --with-netmanager &
login_manager=$!
dd_spawn droiddeck-login1 --with-netmanager
login_manager=$dd_spawned
for ((_i = 0; _i < 50; _i++)); do
[ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break
kill -0 "$login_manager" 2>/dev/null || break
@@ -1418,7 +1434,7 @@ case $mode in
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
_dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
rm -f "$_dd_bus"
dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile &
dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile
for _ in $(seq 1 50); do
[ -S "$_dd_bus" ] && break
nap 0.1
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Starts a program as the main process of its own Android process, outside the session's cgroup.
usage: droiddeck-spawn [--wait] [--pid-file FILE] [--] PROGRAM [ARGS...]
Android counts the session's processes against its child-process limit; a program started this
way is not counted (its own children are). It gets this process's environment, working directory
and stdin/stdout/stderr, and is not a child of the caller: the pid printed on stdout (or written to
FILE) is the one to signal. Without --wait this returns once the program has started; with --wait
it waits for it and exits with its status. Where the app offers no spawner, the program is started as a normal child.
"""
import array
import json
import os
import socket
import struct
import sys
def report(pid, pid_file):
if pid_file:
with open(pid_file, "w") as f:
f.write("%s\n" % pid)
else:
print(pid, flush=True)
def fallback(argv, wait, pid_file):
pid = os.fork()
if pid == 0:
try:
os.execvp(argv[0], argv)
except OSError as e:
print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr)
os._exit(127)
report(pid, pid_file)
if wait:
return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
return 0
def main():
args = sys.argv[1:]
wait = False
pid_file = None
while args and args[0].startswith("--"):
flag = args.pop(0)
if flag == "--":
break
if flag == "--wait":
wait = True
elif flag == "--pid-file" and args:
pid_file = args.pop(0)
else:
print(__doc__.strip(), file=sys.stderr)
return 2
if not args:
print(__doc__.strip(), file=sys.stderr)
return 2
name = os.environ.get("DD_SPAWN")
if not name:
return fallback(args, wait, pid_file)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
s.connect("\0" + name)
except OSError:
return fallback(args, wait, pid_file)
payload = json.dumps({"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}).encode()
s.sendmsg([struct.pack(">I", len(payload)), payload],
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))])
reply = s.makefile("r")
first = reply.readline().split()
if len(first) != 2 or first[0] != "pid":
print("droiddeck-spawn: %s; starting %s as a child" % (" ".join(first[1:]) or "no answer", args[0]),
file=sys.stderr)
return fallback(args, wait, pid_file)
report(first[1], pid_file)
if not wait:
return 0
done = reply.readline().split()
status = int(done[1]) if len(done) == 2 and done[0] == "exit" else 1
return status if 0 <= status < 256 else 128 + (status & 0x7f)
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
build/
+36
View File
@@ -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>
+47
View File
@@ -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"
+21
View File
@@ -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;
}
+360
View File
@@ -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 {}