Compare commits

..
Author SHA1 Message Date
Kurt Himebauch afbd1f2bba fix(handoff): a listed program a shell runs as a job-control job stays counted 2026-11-28 15:58:22 -05:00
Kurt Himebauch f89326c709 docs(phantom): job-control jobs stay counted; listed programs report no stops 2026-11-28 15:46:35 -05:00
Kurt Himebauch d7f0ce82d8 fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup 2026-11-28 15:43:59 -05:00
Kurt Himebauch 80ec4d7517 fix(handoff): table setup not cancellable; test spawner never runs what it cannot end 2026-11-28 15:23:15 -05:00
Kurt Himebauch d2f270d93c fix(handoff): requests name their session; stops of handed-off programs reported; cancellable look 2026-11-28 15:13:39 -05:00
Kurt Himebauch be7f59d983 fix(handoff): one given-up table at most, whole stop codes and rusage, WNOWAIT exits rechecked 2026-11-28 15:01:12 -05:00
Kurt Himebauch 081e4e1223 fix(handoff): generation-checked reap marks, stops taken as stops, close counts reset in a fork 2026-11-28 14:36:29 -05:00
Kurt Himebauch dfcd07c24d fix(hook): settle waits out earlier epochs; unknown-start fork records kept for any handoff under way 2026-11-28 13:29:11 -05:00
Kurt Himebauch 1c888d88e9 fix(handoff): waits look before they reap, so a handed-off fork's child is never reported 2026-11-28 13:17:36 -05:00
Kurt Himebauch 5b07d85296 fix(hook): a table made at runtime outlives closes begun before it; unknown-start fork records kept 2026-11-28 13:04:06 -05:00
Kurt Himebauch 5eea46b9c6 fix(handoff): one report per handed-off child; stops keep a claim; nested waits keep their selector 2026-11-28 12:42:37 -05:00
Kurt Himebauch 1b3c2a77d9 fix(hook): change the kept fd list under a sequence lock; readers take a copy 2026-11-28 12:16:42 -05:00
Kurt Himebauch 8c9904d016 test(handoff): require ENOEXEC for an ELF stub; skip the namespace run without binfmt 2026-11-28 12:04:38 -05:00
Kurt Himebauch ab3d7d96fe Merge remote-tracking branch 'origin/main' into research/phantom-process-limit
# Conflicts:
#	tools/tests/test_native_hook_named_semaphores.py
2026-11-28 12:02:53 -05:00
Kurt Himebauch 441773012f fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd 2026-11-28 12:02:16 -05:00
Kurt Himebauch b1dbfb54da test(handoff): find the module in the namespace run under discover too 2026-11-28 11:49:19 -05:00
Kurt Himebauch 61bc8e03b2 fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits 2026-11-28 11:46:29 -05:00
Kurt Himebauch de573892f2 fix(handoff): an unknown-start fork record never replaces a pending one 2026-11-28 11:20:27 -05:00
Kurt Himebauch 68706c544a fix(handoff): keep a pending child's fork record when an older fork records late 2026-11-28 11:01:11 -05:00
Kurt Himebauch 13a327cfa7 Merge remote-tracking branch 'origin/main' into research/phantom-process-limit
# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
2026-11-28 11:01:11 -05:00
Kurt Himebauch 8fa2e65a42 fix(handoff): a fork record stays only for the pid's current process 2026-11-28 10:00:42 -05:00
Kurt Himebauch c16515fc49 fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept 2026-11-28 09:51:07 -05:00
Kurt Himebauch adb0a27a68 fix(handoff): a known-start bit in fork records 2026-11-28 09:37:18 -05:00
Kurt Himebauch 056be5f3a1 test(semaphores): count only reaped children, only futex waits as emulator stalls 2026-11-28 09:29:27 -05:00
Kurt Himebauch 63f5ac5b5e fix(handoff): fork records matched by the child's start time, never removed 2026-11-28 09:16:28 -05:00
Kurt Himebauch 7221782940 test(semaphores): tell a child hung in qemu-user from a guest deadlock 2026-11-28 09:00:40 -05:00
Kurt Himebauch 4c90e9175d fix(handoff): every dup in a pidfd process locks, fork prep blocks signals 2026-11-28 08:31:24 -05:00
Kurt Himebauch b65af1fa9f fix(handoff): fork record generations, no pidfd restore after a failed move 2026-11-28 08:10:02 -05:00
Kurt Himebauch f7a90151ec fix(handoff): lock only dups onto the pidfd, with signals blocked 2026-11-28 07:56:31 -05:00
Kurt Himebauch 2748ae9f5a fix(handoff): liveness check under the pidfd lock, forget only a reaped pid's record 2026-11-28 07:41:36 -05:00
Kurt Himebauch 784df6260a fix(handoff): one lock over a pidfd move, its dup and the undo 2026-11-28 07:27:31 -05:00
Kurt Himebauch 87fbe91940 fix(handoff): fresh fork records in a forked child, heir is the first live thread 2026-11-28 07:13:56 -05:00
Kurt Himebauch b47a2c9c0e fix(handoff): undo a pidfd move when dup fails, recheck it after the poll 2026-11-28 07:01:20 -05:00
Kurt Himebauch 597f083ab9 fix(handoff): no handoff without fork records, unknown thread state keeps the owner 2026-11-28 06:52:17 -05:00
Kurt Himebauch 4475a122bf fix(handoff): keep the parent pidfd through dup2 and check it before use 2026-11-28 06:41:00 -05:00
Kurt Himebauch 68a3fa1d52 fix(handoff): fork records by pid, a gone thread's children go to the main one 2026-11-28 06:29:59 -05:00
Kurt Himebauch f1dd51f0aa fix(handoff): watch the forking parent through a pidfd opened at start 2026-11-28 06:20:33 -05:00
Kurt Himebauch 1b8187c94a fix(handoff): one-word fork records, changed only by compare-and-swap 2026-11-28 05:29:43 -05:00
Kurt Himebauch 60175ec3ec fix(handoff): a parent /proc cannot read is checked with kill(), then given up 2026-11-28 05:20:49 -05:00
Kurt Himebauch 9463765104 fix(handoff): a child whose forking thread ended is any thread's 2026-11-28 05:17:49 -05:00
Kurt Himebauch a77abf3293 fix(handoff): controlling-terminal check via /dev/tty, owned records only 2026-11-28 05:13:51 -05:00
Kurt Himebauch 3e0e13468e fix(handoff): the thread selector applies to claims in progress too 2026-11-28 04:56:43 -05:00
Kurt Himebauch 3754f505f4 fix(handoff): keep a child's forking thread until its end is taken 2026-11-28 04:54:21 -05:00
Kurt Himebauch 98663031ca fix(handoff): a wait that finds no child rechecks live handoffs 2026-11-28 04:45:49 -05:00
Kurt Himebauch b581fc8bdc fix(handoff): keep the forking thread of each child in the parent 2026-11-28 04:19:08 -05:00
Kurt Himebauch 574f1f8700 fix(handoff): __WNOTHREAD on waits for a pid, flags on every shim reap 2026-11-28 03:59:33 -05:00
Kurt Himebauch b801fb820f fix(handoff): stop waiting on a held entry once its parent has exited 2026-11-28 03:50:09 -05:00
Kurt Himebauch 3c9ba04b23 fix(handoff): honor __WNOTHREAD and check every argument for Steam 2026-11-28 03:41:51 -05:00
Kurt Himebauch 3565752fe9 test(handoff): require a zombie parent in the unreaped-parent case 2026-11-28 03:29:53 -05:00
Kurt Himebauch b68437ab63 fix(handoff): keep __WALL waitid calls on the handoff path 2026-11-28 03:28:30 -05:00
Kurt Himebauch 1dfefac571 fix(handoff): getppid() gives init for an exited or replaced parent 2026-11-28 03:21:47 -05:00
Kurt Himebauch 25d97a414b fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports 2026-11-28 03:11:47 -05:00
Kurt Himebauch 12a15a5526 fix(handoff): a handed-off program's getppid() is its forking process 2026-11-28 02:47:38 -05:00
Kurt Himebauch d629f83b8c fix(agent): tag handed-off game windows outside the reaper 2026-11-28 02:18:42 -05:00
Kurt Himebauch 404f540709 feat(handoff): hand off shell children near Android's process limit 2026-11-28 01:14:30 -05:00
Kurt Himebauch a91c2e8cfd fix(handoff): exact waitid events, safe exit timer, bounded request receipt 2026-11-28 00:29:56 -05:00
Kurt Himebauch 9940445ac1 fix(session): every exit-only waitid goes through the handoff wait 2026-11-28 00:07:30 -05:00
Kurt Himebauch 6906c65446 test(native): check the unlisted child's status only where a child can exec aarch64 2026-11-27 23:59:47 -05:00
Kurt Himebauch e559535ca2 fix(session): silent failed launches, bounded spawn requests and held check-gone writes 2026-11-27 23:46:40 -05:00
Kurt Himebauch e9444a0ddc fix(session): tell a reused pid's old entry by start time, not the reaped flag 2026-11-27 23:35:17 -05:00
Kurt Himebauch 41ba1f47c4 Merge remote-tracking branch 'origin/main' into research/phantom-process-limit
# Conflicts:
#	tools/nativeguest/hook/exec.c
2026-11-27 23:03:27 -05:00
Kurt Himebauch 144a85114e fix(session): confirm the hook before the worker runs, prefer a late report and free a reused pid 2026-11-27 23:01:58 -05:00
Kurt Himebauch 7c10d1fa85 test(native): skip the popen test where a spawn child cannot exec aarch64 2026-11-27 22:43:50 -05:00
Kurt Himebauch 25dbc97e68 test(native): run the popen test program with a clean environment 2026-11-27 22:32:40 -05:00
Kurt Himebauch 536759fca7 test(native): popen test shell is static, as the other hook fixtures 2026-11-27 22:12:37 -05:00
Kurt Himebauch 445a13abf4 fix(session): three-step launch, tagged exit reports and lock-free popen and system children 2026-11-27 22:05:56 -05:00
Kurt Himebauch 6f42e1cf1a fix(session): recheck a taken exit's child and commit a launch only on a whole go line 2026-11-27 19:03:38 -05:00
Kurt Himebauch 2ba290c2f1 fix(session): send a working directory outside the program's root by its real path 2026-11-27 18:44:40 -05:00
Kurt Himebauch 5aac22f277 fix(session): one owner per handoff exit, worker launch answers and spawn edge cases 2026-11-27 18:23:55 -05:00
Kurt Himebauch ca1f12ebb4 Merge remote-tracking branch 'origin/main' into research/phantom-process-limit
# Conflicts:
#	app/src/main/res/values-ar/strings.xml
#	app/src/main/res/values-b+es+419/strings.xml
#	app/src/main/res/values-bg/strings.xml
#	app/src/main/res/values-cs/strings.xml
#	app/src/main/res/values-da/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-el/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-fi/strings.xml
#	app/src/main/res/values-fr/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values-hu/strings.xml
#	app/src/main/res/values-in/strings.xml
#	app/src/main/res/values-it/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ko/strings.xml
#	app/src/main/res/values-ms/strings.xml
#	app/src/main/res/values-nb/strings.xml
#	app/src/main/res/values-pl/strings.xml
#	app/src/main/res/values-pt-rPT/strings.xml
#	app/src/main/res/values-pt/strings.xml
#	app/src/main/res/values-ro/strings.xml
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values-sv/strings.xml
#	app/src/main/res/values-th/strings.xml
#	app/src/main/res/values-uk/strings.xml
#	app/src/main/res/values-vi/strings.xml
#	app/src/main/res/values-zh-rCN/strings.xml
#	app/src/main/res/values-zh-rHK/strings.xml
#	app/src/main/res/values-zh-rTW/strings.xml
2026-11-27 17:57:31 -05:00
Kurt Himebauch af481e5159 fix(session): confirm handoffs, honour wait selectors and stop spawns at teardown 2026-11-27 17:56:37 -05:00
Kurt Himebauch f90d91bfa1 fix(session): let a worker wait for its launch commit on the main thread 2026-11-27 17:25:22 -05:00
Kurt Himebauch 4e2bfa5cdc fix(session): commit each worker launch explicitly and keep workers with the session that asked 2026-11-27 17:06:08 -05:00
Kurt Himebauch 924ad4e9a3 fix(nativeguest): address review findings in handoff waits, signals and spawn errors 2026-11-27 16:35:53 -05:00
Kurt Himebauch ba9b0b0422 perf(session): exec a worker as soon as its reply is in and keep two bound ahead; fix review findings 2026-11-27 16:18:08 -05:00
Kurt Himebauch ae6863d016 fix(nativeguest): let Steam end a handed-off game and keep process-group signals 2026-11-27 15:27:40 -05:00
Kurt Himebauch e418f99aa0 feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive 2026-11-27 14:27:43 -05:00
Kurt Himebauch a969998075 feat(audio): run PulseAudio outside the child-process count 2026-11-27 13:11:13 -05:00
Kurt Himebauch 9b673f59fa feat(setup): the child-process limit no longer blocks Steam while the session runs in workers 2026-11-27 12:56:50 -05:00
Kurt Himebauch bbb4d11bf0 feat(session): run the session root, its jobs and the gamescope chain outside the child-process count 2026-11-27 12:44:11 -05:00
Kurt Himebauch 592d03f69a test(nativeguest): cover the exec handoff's wait and kill 2026-11-27 11:15:56 -05:00
Kurt Himebauch 146b93dd6c test(session): run the session bus block with dd_spawn 2026-11-27 11:12:47 -05:00
Kurt Himebauch aedac67f6d feat(nativeguest): hand long-lived programs to uncounted worker processes 2026-11-27 11:07:04 -05:00
Kurt Himebauch 1e022e2430 feat(session): start long-lived daemons in uncounted worker processes 2026-11-27 10:11:27 -05:00
Kurt Himebauch 1c20437fe6 docs: confirm the child-process gaps on the Thor 2026-11-27 09:50:20 -05:00
Kurt Himebauch 2e170ae12b docs: research Android's child-process limit without developer options 2026-11-27 09:45:04 -05:00
84 changed files with 7481 additions and 137 deletions

No files matched your search

+64
View File
@@ -414,5 +414,69 @@
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" />
<service android:name=".runtime.GuestWorker24" android:exported="false" android:process=":g24" />
<service android:name=".runtime.GuestWorker25" android:exported="false" android:process=":g25" />
<service android:name=".runtime.GuestWorker26" android:exported="false" android:process=":g26" />
<service android:name=".runtime.GuestWorker27" android:exported="false" android:process=":g27" />
<service android:name=".runtime.GuestWorker28" android:exported="false" android:process=":g28" />
<service android:name=".runtime.GuestWorker29" android:exported="false" android:process=":g29" />
<service android:name=".runtime.GuestWorker30" android:exported="false" android:process=":g30" />
<service android:name=".runtime.GuestWorker31" android:exported="false" android:process=":g31" />
<service android:name=".runtime.GuestWorker32" android:exported="false" android:process=":g32" />
<service android:name=".runtime.GuestWorker33" android:exported="false" android:process=":g33" />
<service android:name=".runtime.GuestWorker34" android:exported="false" android:process=":g34" />
<service android:name=".runtime.GuestWorker35" android:exported="false" android:process=":g35" />
<service android:name=".runtime.GuestWorker36" android:exported="false" android:process=":g36" />
<service android:name=".runtime.GuestWorker37" android:exported="false" android:process=":g37" />
<service android:name=".runtime.GuestWorker38" android:exported="false" android:process=":g38" />
<service android:name=".runtime.GuestWorker39" android:exported="false" android:process=":g39" />
<service android:name=".runtime.GuestWorker40" android:exported="false" android:process=":g40" />
<service android:name=".runtime.GuestWorker41" android:exported="false" android:process=":g41" />
<service android:name=".runtime.GuestWorker42" android:exported="false" android:process=":g42" />
<service android:name=".runtime.GuestWorker43" android:exported="false" android:process=":g43" />
<service android:name=".runtime.GuestWorker44" android:exported="false" android:process=":g44" />
<service android:name=".runtime.GuestWorker45" android:exported="false" android:process=":g45" />
<service android:name=".runtime.GuestWorker46" android:exported="false" android:process=":g46" />
<service android:name=".runtime.GuestWorker47" android:exported="false" android:process=":g47" />
<service android:name=".runtime.GuestWorker48" android:exported="false" android:process=":g48" />
<service android:name=".runtime.GuestWorker49" android:exported="false" android:process=":g49" />
<service android:name=".runtime.GuestWorker50" android:exported="false" android:process=":g50" />
<service android:name=".runtime.GuestWorker51" android:exported="false" android:process=":g51" />
<service android:name=".runtime.GuestWorker52" android:exported="false" android:process=":g52" />
<service android:name=".runtime.GuestWorker53" android:exported="false" android:process=":g53" />
<service android:name=".runtime.GuestWorker54" android:exported="false" android:process=":g54" />
<service android:name=".runtime.GuestWorker55" android:exported="false" android:process=":g55" />
<service android:name=".runtime.GuestWorker56" android:exported="false" android:process=":g56" />
<service android:name=".runtime.GuestWorker57" android:exported="false" android:process=":g57" />
<service android:name=".runtime.GuestWorker58" android:exported="false" android:process=":g58" />
<service android:name=".runtime.GuestWorker59" android:exported="false" android:process=":g59" />
<service android:name=".runtime.GuestWorker60" android:exported="false" android:process=":g60" />
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
</application>
</manifest>
@@ -20,6 +20,10 @@ 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
if (android.os.Build.VERSION.SDK_INT >= 28 && Application.getProcessName() == packageName)
com.droiddeck.launcher.runtime.GuestWorkers.attach(this)
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
@@ -89,7 +89,7 @@ public class DirectAudioRelayComponent extends SessionPart {
}
}
final java.io.PrintWriter log = out;
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
pid = HostProcess.startUncounted(command.toString(), env.toArray(new String[0]),
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
@@ -186,13 +186,16 @@ public class PulseAudioComponent extends SessionPart {
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
// The daemon closes every fd at start but this one; in a worker process it is the binder
// fd whose closing Android takes for the process's death.
env.add("PULSE_PASSED_FD=" + com.droiddeck.launcher.runtime.GuestWorker.BINDER_FD_TOKEN);
String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so"))
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
start(generation);
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.core
import android.os.ParcelFileDescriptor
import android.util.Log
import java.io.File
import java.util.function.Consumer
@@ -7,6 +8,9 @@ import java.util.function.Consumer
object HostProcess {
private const val TAG = "HostProcess"
private const val LINKER = "/system/bin/linker64"
// sh -c WORKER_CD sh DIR NAME=VALUE... -- PROGRAM ARGS...
private const val WORKER_CD = "cd \"\$1\" || exit 126; shift; " +
"while [ \$# -gt 0 ] && [ \"\$1\" != -- ]; do export \"\$1\"; shift; done; shift; exec \"\$@\""
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
@JvmStatic
@@ -65,6 +69,77 @@ object HostProcess {
}
}
/**
* As [start], but the program runs as the main process of one of the app's worker processes,
* which Android does not count against the app's child processes (docs/phantom-processes.md).
* Falls back to [start] when no worker is available. The exit status is the program's exit
* code, or 128 plus the signal that ended it, as Process.waitFor() reports it.
*/
@JvmStatic
@JvmOverloads
fun startUncounted(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?,
outputFile: File? = null, onOutputComplete: Runnable? = null): Int {
val context = com.droiddeck.launcher.runtime.GuestWorkers.context
val argv = split(command)
// A missing working directory fails the launch (start() returns -1 for it), not the program
if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context) ||
(dir != null && !dir.isDirectory)) {
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
val environment = LinkedHashMap(System.getenv())
env?.forEach { line ->
val eq = line.indexOf('=')
if (eq > 0) environment[line.substring(0, eq)] = line.substring(eq + 1)
}
val assignments = environment.map { (k, v) -> "$k=$v" }
// A worker cannot chdir before its exec, so Android's shell does it. The shell starts with an
// environment of its own (the program's LD_PRELOAD of glibc libraries would stop it loading)
// and exports the program's before the exec.
val launch = if (dir != null) {
listOf("/system/bin/sh", "-c", WORKER_CD, "sh", dir.path) + assignments + listOf("--") + argv
} else argv
val workerEnv = if (dir != null) listOf("PATH=/system/bin") else assignments
var input: ParcelFileDescriptor? = null
var reader: ParcelFileDescriptor? = null
var output: ParcelFileDescriptor? = null
val pid = try {
input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY)
output = when {
onLine != null -> ParcelFileDescriptor.createPipe().let { reader = it[0]; it[1] }
outputFile != null -> ParcelFileDescriptor.open(outputFile,
ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND)
else -> ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_WRITE_ONLY)
}
com.droiddeck.launcher.runtime.GuestWorkers.start(context, launch, workerEnv, listOf(input, output, output)) { status ->
onExit?.accept(if (status < 0) -1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f))
}
} catch (e: Exception) {
Log.w(TAG, "no worker for ${argv.first()}", e)
-1
} finally {
runCatching { input?.close() }
runCatching { output?.close() }
}
if (pid <= 0) {
reader?.close()
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
Log.i(TAG, "started pid $pid outside the child-process count: ${argv.first()} (${argv.size - 1} arguments)")
reader?.let { pipe ->
Thread({
try {
ParcelFileDescriptor.AutoCloseInputStream(pipe).bufferedReader().useLines { lines ->
lines.forEach { onLine?.accept(it) }
}
} catch (e: Exception) {
} finally {
onOutputComplete?.run()
}
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
}
return pid
}
@JvmStatic
fun pidOf(process: Process): Int = try {
val field = process.javaClass.getDeclaredField("pid")
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.R
enum class PhantomProcessStatus {
NOT_APPLICABLE,
/** The limit is on, but the session keeps its programs out of Android's count (GuestWorkers). */
UNCOUNTED,
DISABLED,
ENABLED,
UNSET,
@@ -57,6 +59,12 @@ object PhantomProcessLimit {
fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val status = readSetting(context, sdk)
return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.limitHandled(context))
PhantomProcessStatus.UNCOUNTED else status
}
private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
val global = try {
@@ -101,7 +109,8 @@ object PhantomProcessLimit {
fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED &&
status != PhantomProcessStatus.UNCOUNTED
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
@@ -109,6 +118,7 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required
PhantomProcessStatus.UNCOUNTED -> R.string.phantom_title_uncounted
})
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -116,6 +126,7 @@ object PhantomProcessLimit {
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
PhantomProcessStatus.UNCOUNTED -> context.getString(R.string.phantom_instructions_uncounted)
}
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -132,5 +143,6 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
PhantomProcessStatus.UNCOUNTED -> "on, not needed (most of the session's programs run in uncounted worker processes)"
}
}
@@ -28,17 +28,18 @@ object SessionLogCapture {
out.flush()
writer = out
this.target = target
pid = HostProcess.start(
pid = HostProcess.startUncounted(
command(Process.myPid(), sinceMillis),
null, target.parentFile, null,
) { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
onLine = { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
}
}
}
}
},
)
if (pid == -1) {
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
out.flush()
@@ -0,0 +1,820 @@
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.system.StructPollfd
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 fds = List(data.readInt()) { data.readFileDescriptor() }
val targets = data.createIntArray() ?: IntArray(fds.size) { it }
val fillBinderFd = data.readInt() != 0
val go = data.readFileDescriptor()
reply?.writeInt(Process.myPid())
Handler(Looper.getMainLooper()).post {
// The app writes a byte once it has the reply and has taken the launch on: an exec
// before then would end this process with the reply undelivered, and with none (the
// app gave up and starts the program another way) the program must not run here.
var why = ""
// poll() with a timeout counts as network I/O to StrictMode on the main thread
android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX)
val committed = runCatching {
fun byte(timeout: Int): Int {
val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() }
val ready = Os.poll(arrayOf(poll), timeout)
return (if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1)
.also { why = "poll $ready revents ${poll.revents} read $it" }
}
// The commit, an answer, and the app's word that it has the answer: the app may
// have stopped waiting for it (and started the program another way) meanwhile.
// That last word comes, or the app closes its end (a byte or EOF): no timeout,
// which could drop a launch the app has already reported as started.
byte(GO_TIMEOUT_MS) == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 && byte(-1) == 1
}.getOrElse { why = it.toString(); false }
go.close()
if (committed) exec(argv, env, fds, targets, fillBinderFd)
else {
Log.w(TAG, "launch not committed ($why): not running ${argv.firstOrNull()}")
Process.killProcess(Process.myPid())
}
}
return true
}
}
override fun onBind(intent: Intent): IBinder = binder
private fun exec(argv: Array<String>, env: Array<String>, fds: List<ParcelFileDescriptor?>, targets: IntArray, fillBinderFd: Boolean) {
try {
val top = targets.maxOrNull() ?: 2
val (binderTop, binderFd) = keepBinderOpen(maxOf(BINDER_FDS, top + 1))
// Out of the way first, so that placing one fd cannot overwrite another not yet placed.
val above = maxOf(MOVED_FDS, top + 1, binderTop + 1)
val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, above) } }
moved.forEachIndexed { i, fd ->
if (fd == null || i >= targets.size) return@forEachIndexed
val source = ParcelFileDescriptor.adoptFd(fd).also { kept.add(it) }.fileDescriptor
Os.dup2(source, targets[i])
Os.fcntlInt(source, OsConstants.F_SETFD, OsConstants.FD_CLOEXEC)
}
// A session of its own: in zygote's process group, a program signalling its group
// (kill(0, sig)) would reach every process of the app.
runCatching { Os.setsid() }
// The native hook closes the binder fds in every other process (hook/handoff.c). Only an
// app launch asks for the number (a whole argument or variable value), never a guest's.
val fill = { arg: String ->
if (!fillBinderFd) arg
else if (arg == BINDER_FD_TOKEN) binderFd.toString()
else if (arg.endsWith("=$BINDER_FD_TOKEN")) arg.removeSuffix(BINDER_FD_TOKEN) + binderFd
else arg
}
// This thread blocks SIGQUIT, SIGUSR1 and SIGPIPE (Android's runtime), and an exec keeps
// that: the program's hook sets DDH_SIGMASK instead (none blocked, unless the request says).
val mask = if (env.any { it.startsWith("DDH_SIGMASK=") }) emptyList() else listOf("DDH_SIGMASK=0")
Os.execve(argv[0], argv.map(fill).toTypedArray(),
env.filterNot { it.startsWith("DDH_WORKER_PID=") }.map(fill).toTypedArray() + mask +
"DDH_WORKER_PID=${Process.myPid()}")
} catch (e: ErrnoException) {
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
}
Process.killProcess(Process.myPid())
}
/**
* Binder fds stay open across the exec, at [from] or above, where no fd of the program goes.
* Returns the highest fd used and the one on /dev/binder, whose closing Android takes for
* the death of this process.
*/
private fun keepBinderOpen(from: Int): Pair<Int, Int> {
var highest = from - 1
var binder = -1
File("/proc/self/fd").listFiles()?.forEach { link ->
val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
if (target !in BINDER_DEVICES && !target.startsWith("/dev/binderfs/")) return@forEach
// A copy, not adoptFd(): some of these fds are owned (fdsan) by a ParcelFileDescriptor.
val copy = runCatching { ParcelFileDescriptor.fromFd(link.name.toIntOrNull() ?: return@forEach) }.getOrNull()
?: return@forEach
val kept = Os.fcntlInt(copy.fileDescriptor, OsConstants.F_DUPFD, from)
highest = maxOf(highest, kept)
if (target.substringAfterLast('/') == "binder") binder = kept
copy.close()
}
return highest to binder
}
companion object {
const val RUN = IBinder.FIRST_CALL_TRANSACTION
/** An argument, or a variable's whole value, in an app launch: replaced by the number of its kept binder fd. */
const val BINDER_FD_TOKEN = "@DDH_WORKER_BINDER_FD@"
// Longer than the app may wait for the hook's "go" (GuestWorkers.ACK_TIMEOUT_MS) before it commits
private const val GO_TIMEOUT_MS = 15000
private val BINDER_DEVICES = setOf("/dev/binder", "/dev/hwbinder", "/dev/vndbinder")
private const val BINDER_FDS = 900
private const val MOVED_FDS = 1200
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()
class GuestWorker24 : GuestWorker()
class GuestWorker25 : GuestWorker()
class GuestWorker26 : GuestWorker()
class GuestWorker27 : GuestWorker()
class GuestWorker28 : GuestWorker()
class GuestWorker29 : GuestWorker()
class GuestWorker30 : GuestWorker()
class GuestWorker31 : GuestWorker()
class GuestWorker32 : GuestWorker()
class GuestWorker33 : GuestWorker()
class GuestWorker34 : GuestWorker()
class GuestWorker35 : GuestWorker()
class GuestWorker36 : GuestWorker()
class GuestWorker37 : GuestWorker()
class GuestWorker38 : GuestWorker()
class GuestWorker39 : GuestWorker()
class GuestWorker40 : GuestWorker()
class GuestWorker41 : GuestWorker()
class GuestWorker42 : GuestWorker()
class GuestWorker43 : GuestWorker()
class GuestWorker44 : GuestWorker()
class GuestWorker45 : GuestWorker()
class GuestWorker46 : GuestWorker()
class GuestWorker47 : GuestWorker()
class GuestWorker48 : GuestWorker()
class GuestWorker49 : GuestWorker()
class GuestWorker50 : GuestWorker()
class GuestWorker51 : GuestWorker()
class GuestWorker52 : GuestWorker()
class GuestWorker53 : GuestWorker()
class GuestWorker54 : GuestWorker()
class GuestWorker55 : GuestWorker()
class GuestWorker56 : GuestWorker()
class GuestWorker57 : GuestWorker()
class GuestWorker58 : GuestWorker()
class GuestWorker59 : GuestWorker()
class GuestWorker60 : GuestWorker()
class GuestWorker61 : GuestWorker()
class GuestWorker62 : GuestWorker()
class GuestWorker63 : 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,
GuestWorker24::class.java, GuestWorker25::class.java, GuestWorker26::class.java,
GuestWorker27::class.java, GuestWorker28::class.java, GuestWorker29::class.java,
GuestWorker30::class.java, GuestWorker31::class.java, GuestWorker32::class.java,
GuestWorker33::class.java, GuestWorker34::class.java, GuestWorker35::class.java,
GuestWorker36::class.java, GuestWorker37::class.java, GuestWorker38::class.java,
GuestWorker39::class.java, GuestWorker40::class.java, GuestWorker41::class.java,
GuestWorker42::class.java, GuestWorker43::class.java, GuestWorker44::class.java,
GuestWorker45::class.java, GuestWorker46::class.java, GuestWorker47::class.java,
GuestWorker48::class.java, GuestWorker49::class.java, GuestWorker50::class.java,
GuestWorker51::class.java, GuestWorker52::class.java, GuestWorker53::class.java,
GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java,
GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java,
GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java,
GuestWorker63::class.java,
)
private class Slot(val index: Int) {
lateinit var connection: ServiceConnection
val connected = CountDownLatch(1)
@Volatile var service: IBinder? = null
@Volatile var pid = -1
@Volatile var guest = false
/** The session it runs a program for ([serve]'s number). */
@Volatile var session = 0
@Volatile var onExit: ((Int) -> Unit)? = null
/** Set once its program was handed over: only then does its end count as the program's. */
@Volatile var started = false
/** Between the pid and the last word of a launch (under the slots lock): its end is held back. */
var launching = false
/** It ended while launching: reported once the launch turns out to have run, never otherwise. */
var endedLaunching = false
}
private val slots = arrayOfNulls<Slot>(classes.size)
// Workers bound ahead of need while a session runs: a zygote fork and the bind take about
// 60-100 ms, which every program the session starts would otherwise wait for.
private val warm = ArrayDeque<Slot>()
@Volatile private var warmTarget = 0
// Numbers the sessions: an old session's teardown can still be running when the next one starts.
@Volatile private var session = 0
// The latest session whose teardown has begun
@Volatile private var stopped = 0
// Held for a launch's last word and for marking a session stopped
private val authorizing = Any()
private val warming = java.util.concurrent.atomic.AtomicBoolean(false)
private const val WARM_WORKERS = 2
private const val ACK_TIMEOUT_MS = 5000
private const val ANSWER_TIMEOUT_MS = 5000
private const val RECEIVE_TIMEOUT_MS = 10000
// argv and the environment of one exec, with room: Linux caps them at a quarter of the stack
private const val MAX_REQUEST_BYTES = 8 shl 20
private const val MAX_RECEIVING = 32
private val receiving = java.util.concurrent.atomic.AtomicInteger()
private val connections = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "guest-worker-binder").apply { isDaemon = true } }
@Volatile private var server: Thread? = null
/** The app, once [attach] or [serve] ran in its main process; null before. */
@Volatile var context: Context? = null
private set
/** Whether the session runs its programs in workers: the native userland, and not turned off. */
fun enabled(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) &&
NativeGuest.enabled(context)
/** How the running session's root was started: in a worker (true) or counted (false); null with none running. */
@Volatile var sessionRootUncounted: Boolean? = null
/**
* Whether Android's child-process limit is out of the session's way: as the running session
* started (a proot session, or one whose root fell back to a counted start, is not), else as
* the next one would start.
*/
fun limitHandled(context: Context): Boolean =
sessionRootUncounted ?: (NativeGuest.sessionMode != false && enabled(context))
/** Whether pid is a program running in one of the workers. */
fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } }
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 =
start(context, argv, env, stdio, IntArray(stdio.size) { it }, onExit)
/** As [start], with the fds in [fds] placed at the numbers in [targets]. */
fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
onExit: (Int) -> Unit): Int = start(context, argv, env, fds, targets, false, onExit)
/**
* [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends.
* [commit] runs with the pid before the worker may run the program; false, and it does not.
* [confirmed] runs once the worker has taken it on, just before it is told to run it; false, and it does not.
* [owner]: the session asking (the one a guest's request names), else the latest.
*/
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
confirmed: () -> Boolean = { true }, owner: Int = session): Int {
val app = context.applicationContext
if (guest && owner <= stopped) {
Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") +
": not starting ${argv.firstOrNull()}")
return -1
}
val slot = takeWarm() ?: bind(app)?.takeIf { fresh ->
fresh.connected.await(10, TimeUnit.SECONDS).also { if (!it) release(app, fresh) }
} ?: run {
Log.w(TAG, "no worker started for ${argv.firstOrNull()}")
return -1
}
slot.guest = guest
slot.session = owner
slot.onExit = onExit
refill(app)
// The worker execs once a byte comes through this socket: after the reply has reached us, so
// that its exec does not cut the reply off, and after the slot is marked started. Closed
// without one, the worker ends without running the program (the caller starts it another way).
// It answers with a byte of its own: without that it gave up waiting, and nothing runs.
var go: Array<ParcelFileDescriptor>? = null
var data: Parcel? = Parcel.obtain()
val reply = Parcel.obtain()
try {
go = ParcelFileDescriptor.createSocketPair()
data!!.writeStringArray(argv.toTypedArray())
data.writeStringArray(env.toTypedArray())
data.writeInt(fds.size)
fds.forEach { data.writeFileDescriptor(it.fileDescriptor) }
data.writeIntArray(targets)
data.writeInt(if (guest) 0 else 1)
data.writeFileDescriptor(go[0].fileDescriptor)
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
// The worker has its own copy: with ours closed (and the request's, which holds one too),
// a worker that gave up leaves no reader
data.recycle()
data = null
go[0].close()
val pid = reply.readInt()
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
// would not find them.
val stopping = { guest && owner <= stopped }
if (stopping() || !commit(pid)) {
Log.w(TAG, "worker ${slot.index}: ${argv.firstOrNull()} was not taken on")
release(app, slot)
return -1
}
// launching, not started yet: an end before the last word is reported only if the launch ran
val live = synchronized(slots) {
(slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.launching = true } }
}
if (!live) {
Log.w(TAG, "worker ${slot.index} ended, or its session is stopping, before running ${argv.firstOrNull()}")
release(app, slot)
return -1
}
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1)
val answer = StructPollfd().apply { fd = go[1].fileDescriptor; events = OsConstants.POLLIN.toShort() }
// then the word to run it: given only here, once its answer is in, so that a worker whose
// answer came too late never runs a program this call reports as not started. [confirmed]
// goes first: a caller that hears nothing runs the program itself, so it must have heard
// before the worker may run it (an app dying in between loses the program, not doubles it).
// The word and a teardown's start exclude each other: a launch is authorized before stopGuests()
// marks the session stopped, and is then stopped with the pids it takes (guestPids lists a
// launching slot), or never.
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
val accepted = answered && synchronized(authorizing) {
!stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
}
val endedRunning = synchronized(slots) {
slot.launching = false
if (accepted && !slot.endedLaunching) slot.started = true
accepted && slot.endedLaunching
}
if (!accepted) {
Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on")
release(app, slot)
return -1
}
// it ran and was already gone by now: its end, once
if (endedRunning) reportEnd(app, slot)
} catch (e: Exception) {
Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
synchronized(slots) { slot.launching = false }
release(app, slot)
return -1
} finally {
data?.recycle()
reply.recycle()
go?.forEach { runCatching { it.close() } }
}
Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
return slot.pid
}
/** Binds a free worker; its [Slot.connected] opens once it is up. Null when all are in use. */
private fun bind(app: Context): Slot? {
val slot = synchronized(slots) {
val index = slots.indexOfFirst { it == null }
if (index < 0) {
Log.w(TAG, "all ${slots.size} workers are busy")
return null
}
Slot(index).also { slots[index] = it }
}
slot.connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
slot.service = binder
slot.connected.countDown()
}
override fun onServiceDisconnected(name: ComponentName) = release(app, slot)
override fun onBindingDied(name: ComponentName) = release(app, slot)
}
// Callbacks off the main thread: start() waits for onServiceConnected, and a caller holding a
// lock the main thread is waiting for (PulseAudio's launch) would otherwise wait out the timeout.
val bound = runCatching {
app.bindService(Intent(app, classes[slot.index]), Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT,
connections, slot.connection)
}.onFailure { Log.w(TAG, "worker ${slot.index} could not be bound", it) }.getOrDefault(false)
if (!bound) {
release(app, slot)
return null
}
return slot
}
private fun takeWarm(): Slot? = synchronized(slots) {
while (warm.isNotEmpty()) {
val slot = warm.removeFirst()
if (slots[slot.index] === slot && slot.service?.isBinderAlive == true) return slot
}
null
}
/** Brings the warm workers back up to [warmTarget], one at a time, off the caller's thread. */
private fun refill(app: Context) {
if (warmTarget == 0 || !warming.compareAndSet(false, true)) return
Thread({
try {
while (true) {
val missing = warmTarget - synchronized(slots) { warm.size }
if (missing <= 0) break
// all at once: the zygote forks them in parallel
val fresh = (1..missing).mapNotNull { bind(app) }
if (fresh.isEmpty()) break
for (slot in fresh) {
if (!slot.connected.await(10, TimeUnit.SECONDS)) {
release(app, slot)
continue
}
// decided once, under the lock: kept warm, or released
val kept = synchronized(slots) {
(slots[slot.index] === slot && warmTarget > 0).also { if (it) warm.addLast(slot) }
}
if (!kept) release(app, slot)
}
}
} finally {
warming.set(false)
}
}, "guest-worker-warm").apply { isDaemon = true; start() }
}
private fun release(app: Context, slot: Slot) {
var report = false
val removed = synchronized(slots) {
warm.remove(slot)
if (slot.launching) slot.endedLaunching = true else report = slot.started
(slots[slot.index] === slot).also { if (it) slots[slot.index] = null }
}
if (!removed) return
runCatching { app.unbindService(slot.connection) }
if (report) reportEnd(app, slot)
}
private fun reportEnd(app: Context, slot: Slot) {
val onExit = slot.onExit ?: return
Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start()
}
/** The worker's exit as a wait status (exit code << 8, or the signal), -1 when unknown. */
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)
var recorded = false
repeat(20) {
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let {
recorded = true
// an exit code only when the process exited itself; a signal number otherwise (a native crash)
if (it.reason == android.app.ApplicationExitInfo.REASON_EXIT_SELF) return (it.status and 0xff) shl 8
if (it.status in 1..64) return it.status and 0x7f
// Android records the death first and the zygote's status later (as UNKNOWN, 0, then
// EXIT_SELF): a reason without a status may still be completed
if (it.reason != android.app.ApplicationExitInfo.REASON_UNKNOWN) return OsConstants.SIGKILL
}
Thread.sleep(50)
}
// killed by Android with no signal recorded, not a clean exit
return if (recorded) OsConstants.SIGKILL else -1
}
/** The pids of session [of]'s guest programs running in workers. */
fun guestPids(of: Int = session): List<Int> =
synchronized(slots) { slots.mapNotNull { s -> s?.takeIf { it.guest && it.session == of }?.pid?.takeIf { it > 0 } } }
/** Ends session [of]'s guest programs that are still running, and, for the latest session, the warm workers. */
fun stopGuests(of: Int = session) {
// the check and the reset together: a new session's serve() may be under way
val drained = synchronized(authorizing) {
synchronized(slots) {
stopped = maxOf(stopped, of)
if (of != session) emptyList() else { warmTarget = 0; warm.toList().also { warm.clear() } }
}
}
context?.let { app -> drained.forEach { release(app, it) } }
val pids = guestPids(of)
if (pids.isEmpty()) return
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 attach(context: Context) {
this.context = context.applicationContext
}
/** Starts a session's use of the workers (and the spawn socket, once); returns its number. */
fun serve(context: Context): Int {
val app = context.applicationContext
this.context = app
val number = synchronized(slots) { warmTarget = WARM_WORKERS; ++session }
refill(app)
synchronized(this) {
if (server != null) return number
server = Thread({
val socket = try {
LocalServerSocket(socketName(app))
} catch (e: Exception) {
Log.e(TAG, "no spawn socket", e)
synchronized(this) { server = null }
return@Thread
}
while (true) {
val client = runCatching { socket.accept() }.getOrNull()
if (client == null) {
Thread.sleep(100) // out of fds, for one: do not spin
continue
}
// A bounded number of requests still coming in: a stalled sender holds a thread
if (receiving.incrementAndGet() > MAX_RECEIVING) {
receiving.decrementAndGet()
Log.w(TAG, "$MAX_RECEIVING spawn requests are still coming in: refusing another")
runCatching { client.close() }
continue
}
Thread({
try {
handle(app, client) { receiving.decrementAndGet() }
} catch (e: Throwable) {
Log.w(TAG, "spawn request failed", e)
}
}, "guest-spawn").start()
}
}, "guest-spawn-server").apply { isDaemon = true; start() }
}
return number
}
private fun handle(app: Context, client: LocalSocket, received: () -> Unit) {
var receiving = true
val done = { if (receiving) { receiving = false; received() } }
try {
handleRequest(app, client, done)
} finally {
done()
}
}
private fun handleRequest(app: Context, client: LocalSocket, received: () -> Unit) {
client.use {
if (client.peerCredentials.uid != Process.myUid()) return
// The whole request and its fds within this, however slowly they come (the wait for a
// program's exit is not): each read gets what is left of it
val deadline = android.os.SystemClock.elapsedRealtime() + RECEIVE_TIMEOUT_MS
fun left() {
val ms = deadline - android.os.SystemClock.elapsedRealtime()
if (ms <= 0) throw java.net.SocketTimeoutException("spawn request not received in time")
client.soTimeout = ms.toInt()
}
val input = DataInputStream(client.inputStream)
val fds = ArrayList<ParcelFileDescriptor>()
fun take() {
val received = client.ancillaryFileDescriptors.orEmpty()
try {
received.forEach { fds.add(ParcelFileDescriptor.dup(it)) }
} finally {
received.forEach { runCatching { Os.close(it) } }
}
}
// fds can come with any read, the request's own bytes too: each read's are taken at once
fun fill(bytes: ByteArray) {
var got = 0
while (got < bytes.size) {
left()
val n = input.read(bytes, got, bytes.size - got)
take()
if (n < 0) throw java.io.EOFException("spawn request ended at $got of ${bytes.size} bytes")
got += n
}
}
// Until start() has them: closed on every way out before that, from the first byte on
var handedOver = false
try {
val length = ByteArray(4).also { fill(it) }.let { java.nio.ByteBuffer.wrap(it).int }
if (length !in 1..MAX_REQUEST_BYTES) {
Log.w(TAG, "spawn request of $length bytes refused")
return
}
val payload = ByteArray(length).also { fill(it) }
val request = JSONObject(String(payload))
if (request.has("fdchunks")) {
// The hook sends its fds after the request, a chunk with each byte (hook/handoff.c)
val total = (request.optJSONArray("fds")?.length() ?: 0) + (if (request.has("table")) 1 else 0)
while (fds.size < total) {
left()
if (input.read() < 0) throw java.io.EOFException("fds ended at ${fds.size} of $total")
take()
}
} else {
take()
}
received()
val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } }
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { o -> o.keys().forEach { env[it] = o.getString(it) } }
request.optJSONArray("envlist")?.let { a ->
for (i in 0 until a.length()) a.getString(i).split('=', limit = 2).let { if (it.size == 2) env[it[0]] = it[1] }
}
// What the hook told the program that asked (it may run in a worker itself) is not this one's
env.keys.removeAll { it.startsWith("DDH_") }
val cwd = request.optString("cwd", "/")
val wait = request.optBoolean("wait", false)
// A path without a slash names a file in the cwd, as execve() takes it, not one on PATH
val file = request.optString("file", "").let { if (it.isNotEmpty() && '/' !in it) "./$it" else it }
// The handoff table (the hook's) comes last among the fds; the rest go to these numbers.
val tableIndex = request.optInt("table", -1)
val numbers = request.optJSONArray("fds")?.let { a -> IntArray(a.length()) { a.getInt(it) } } ?: IntArray(3) { it }
val table = fds.getOrNull(tableIndex)?.takeIf { pfd ->
runCatching { Os.readlink("/proc/self/fd/${pfd.fd}") }.getOrNull()?.contains("ddnatv-handoff") == true
}
val slot = request.optInt("slot", -1)
val parent = request.optInt("parent", -1)
var programFds = fds.filterIndexed { i, _ -> i != tableIndex }
var targets = numbers
if (table != null && slot >= 0) {
// The program reports its own exit status into the table (hook/handoff.c)
val tableFd = (numbers.maxOrNull() ?: 2) + 1
programFds = programFds + table
targets = numbers + tableFd
env["DDH_TABLE"] = "$tableFd:$slot:$parent:${request.optInt("child", -1)}"
}
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 args = if (file.isNotEmpty()) {
listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; a=\$2; f=\$3; shift 3; exec -a \"\$a\" \"\$f\" \"\$@\"",
"droiddeck-spawn", cwd, argv[0], file) + argv.drop(1)
} else {
listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"", "droiddeck-spawn", cwd) + argv
}
val command = NativeGuest.command(root, shell, args)
env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path
// The hook restores these in the program (tools/nativeguest/hook/handoff.c).
if (request.has("sigign")) env["DDH_SIGIGN"] = request.getLong("sigign").toString()
if (request.has("nofile")) {
env["DDH_NOFILE"] = request.getLong("nofile").toString() +
(if (request.has("nofilemax")) ":" + request.getLong("nofilemax") else "")
}
if (request.has("umask")) env["DDH_UMASK"] = request.getLong("umask").toString()
if (request.has("pgid")) env["DDH_PGID"] = request.getLong("pgid").toString()
if (request.has("anchor")) env["DDH_ANCHOR"] = request.getLong("anchor").toString()
if (request.has("pstart")) env["DDH_PSTART"] = request.getLong("pstart").toString()
if (request.has("astart")) env["DDH_ASTART"] = request.getLong("astart").toString()
env["DDH_SIGMASK"] = request.optLong("sigmask", 0L).toString()
// The shell above: the hook restores nothing there (bash changes its own signal mask),
// only in the program it execs, which no longer has this.
env["DDH_WRAPPER"] = "1"
val child = request.optInt("child", -1)
val exited = CountDownLatch(1)
var status = -1
var worker = -1
// The hook answers the pid with "go" (ack): without it (it died, or gave up and runs the
// program itself) the worker must not run it too.
val ack = request.optBoolean("ack", false)
var answered = false
// the hook's last word, sent once the worker has taken the program on and before it runs it
var confirmedToHook = false
// The session whose guest asks, not the latest: a new session can start (serve()) while an
// older one's guests are still sending, and that older one's teardown must find its programs.
// A request that names none is refused (start() runs nothing for session 0): the hook and
// droiddeck-spawn always name it, and which session's it is cannot be told otherwise.
val owner = request.optInt("session", 0).coerceAtLeast(0)
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, onExit = { code ->
status = code
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
exited.countDown()
}, confirmed = {
!ack || runCatching {
out.write("ok\n".toByteArray())
out.flush()
confirmedToHook = true
}.isSuccess
}, commit = { started ->
worker = started
if (!ack) return@start true
runCatching {
out.write("pid $started\n".toByteArray())
out.flush()
answered = true
client.soTimeout = ACK_TIMEOUT_MS
// the whole line: a hook whose write stopped short treats it as failed and runs the program itself
val line = StringBuilder()
var ended = false
while (!ended) {
val c = input.read()
if (c < 0) break
if (c == '\n'.code) ended = true else line.append(c.toChar())
}
ended && line.toString() == "go"
}.getOrDefault(false)
})
handedOver = true
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
if (pid <= 0) table?.let { runCatching { it.close() } }
if (!answered) {
out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
out.flush()
} else if (!confirmedToHook) {
// nothing runs it in a worker: the hook runs it itself
runCatching { out.write("error not started\n".toByteArray()); out.flush() }
}
if (pid > 0 && wait) {
exited.await()
// droiddeck-spawn exits with this: an exit code, or 128 plus the signal
val code = if (status < 0) 1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f)
out.write("exit $code\n".toByteArray())
out.flush()
}
} finally {
if (!handedOver) fds.forEach { runCatching { it.close() } }
}
}
}
// Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 64-byte
// entries of int32 child, real, parent, state, ..., and at 32 the app's report: int32 status, child.
// The report is one 8-byte write tagged with the child it is for; only the hook changes an
// entry's state, so a report that lands after the entry went to another child is ignored there.
private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int, child: Int, worker: Int) {
runCatching {
val entry = 64L + slot * 64L
val head = java.nio.ByteBuffer.allocate(16).order(java.nio.ByteOrder.nativeOrder())
Os.pread(table.fileDescriptor, head, entry)
val real = head.getInt(4)
val state = head.getInt(12)
// Also while the hook holds the entry (TAKEN) or has already guessed its end (EXITED):
// the report is for this child only, and wins over the timeout's guess (ddh_status)
if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || state !in 1..4)
return@runCatching
// An exit Android has no record of is reported as a failure, not as a signal.
val report = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.nativeOrder())
.putInt(0, if (status < 0) 1 shl 8 else status).putInt(4, child)
Os.pwrite(table.fileDescriptor, report, entry + 32)
if (parent > 0) Process.sendSignal(parent, OsConstants.SIGCHLD)
}.onFailure { Log.w(TAG, "could not report an exit to the guest's parent", it) }
runCatching { table.close() }
}
}
@@ -129,6 +129,8 @@ 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-log-writer" to "usr/local/bin/droiddeck-log-writer",
"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",
@@ -1098,6 +1098,9 @@ object SessionPrefs {
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
@@ -703,6 +703,20 @@ class SessionService : Service() {
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// this session's worker number: the shared field may be a newer session's by the time it is used
var ownWorkers = 0
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
// Under the lock a stop takes its number with: a stop either comes first (and this session
// starts no workers) or owns them
ownWorkers = synchronized(stopLock) {
if (gen != sessionGen || !SessionState.running) 0
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
}
if (ownWorkers > 0) {
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
guest.add("DD_SPAWN_SESSION=$ownWorkers")
}
}
// 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('"', ' ')) }
@@ -860,10 +874,10 @@ class SessionService : Service() {
watchLaunchRequests(sessionRoot)
watchSyncWanted(root)
EsyncPacks.fetchInBackground(this, root)
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = SessionEvents.step("guest-launch") { HostProcess.startUncounted(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
return@startUncounted
}
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
@@ -879,10 +893,13 @@ class SessionService : Service() {
syncWatcher = null
}
abandonStart(gen, sessionDir, started)
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
val workers = ownWorkers
if (pid > 1) Thread({ teardown(pid, workerSession = workers) }, "session-teardown").start()
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
return
}
sessionPid = pid
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid)
if (pid > 1) {
raiseTracer(pid, gen)
SessionEvents.guestStarted(pid)
@@ -1521,10 +1538,15 @@ class SessionService : Service() {
return binds
}
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
// The workers' session number of the session running now (GuestWorkers.serve)
@Volatile private var guestWorkerSession = 0
private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
if (!stillSameProcess()) return
val tree = descendants(prootPid)
// The session's programs that run in worker processes are not descendants of its root.
val workers = if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workerSession) else emptyList()
val tree = descendants(prootPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) }
if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15)
@@ -1541,6 +1563,7 @@ class SessionService : Service() {
killed++
}
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession)
}
private fun clearCachedApps() {
@@ -2311,12 +2334,16 @@ class SessionService : Service() {
return
}
completeNativeSleep()
var workers = 0
val (ended, endedArch) = synchronized(stopLock) {
if (gen != null && gen != sessionGen) return
// as it is when running is cleared: startup registers its workers under this lock too
workers = guestWorkerSession
cancelQueuedSteamGame()
gameExitWatchToken++
// also when startup stopped before the guest ran
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null
if (!SessionState.running) return
if (relaunch) SessionState.confirmRelaunchStop()
SessionEvents.record("guest.exited", mapOf("status" to status))
@@ -2377,7 +2404,8 @@ class SessionService : Service() {
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
if (prootPid > 1) teardown(prootPid, workerSession = workers)
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
killGuestLeftovers(ended)
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
@@ -2386,6 +2414,7 @@ class SessionService : Service() {
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({
com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
@@ -393,7 +393,8 @@ internal fun SetupPanel(
listOfNotNull(
gpu.displayName(ctx),
s.installed?.let { stringResource(R.string.setup_ready_runtime, it) },
stringResource(R.string.setup_ready_limit_off).takeIf { !limitBlocks },
stringResource(R.string.setup_ready_limit_off)
.takeIf { !limitBlocks && s.phantomProcessStatus != PhantomProcessStatus.UNCOUNTED },
s.offlineAccount?.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.setup_ready_signed_in, it) },
).joinToString(" · "),
open = showChecks, onDetails = { showChecks = !showChecks },
+2
View File
@@ -2544,6 +2544,8 @@
<string name="phantom_instructions_fix">%1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى.</string>
<string name="phantom_instructions_off">يمكن بدء جلسات Steam.</string>
<string name="phantom_instructions_not_applicable">لا يستخدم إصدار Android هذا هذا الحدّ.</string>
<string name="phantom_title_uncounted">يتولى DroidDeck حد العمليات الفرعية</string>
<string name="phantom_instructions_uncounted">يشغّل DroidDeck برامج الجلسة في عمليات لا يحتسبها Android، لذا يمكن إبقاء خيارات المطوّرين متوقفة.</string>
<string name="phantom_fix_toggle">فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك.</string>
<string name="phantom_fix_no_toggle">لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز.</string>
<string name="upd_block_no_apk">لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck.</string>
@@ -2536,6 +2536,8 @@
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
<string name="phantom_instructions_uncounted">DroidDeck ejecuta los programas de la sesión en procesos que Android no cuenta, así que las Opciones de desarrollador pueden quedar desactivadas.</string>
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Ако това не е възможно, свържи устройството с компютър с ADB и изпълни командата отдолу. Върни се тук и провери отново.</string>
<string name="phantom_instructions_off">Сесиите на Steam могат да стартират.</string>
<string name="phantom_instructions_not_applicable">Тази версия на Android не използва това ограничение.</string>
<string name="phantom_title_uncounted">DroidDeck се справя с ограничението за дъщерни процеси</string>
<string name="phantom_instructions_uncounted">DroidDeck изпълнява програмите на сесията в процеси, които Android не отчита, така че опциите за програмисти могат да останат изключени.</string>
<string name="phantom_fix_toggle">Включи „Деактивиране на ограниченията за дъщерните процеси“ в Опции за програмисти и остави Опции за програмисти включени след това.</string>
<string name="phantom_fix_no_toggle">Тази версия на Android няма превключвател за това. Използвай безжично отстраняване на грешки, за да го промениш от това устройство.</string>
<string name="upd_block_no_apk">Тази версия няма изтегляне за това копие на DroidDeck.</string>
+2
View File
@@ -2492,6 +2492,8 @@
<string name="phantom_instructions_fix">%1$s Pokud to není možné, připojte toto zařízení k počítači s ADB a spusťte příkaz níže. Vraťte se sem a zkontrolujte to znovu.</string>
<string name="phantom_instructions_off">Relace Steamu se mohou spouštět.</string>
<string name="phantom_instructions_not_applicable">Tato verze Androidu tento limit nepoužívá.</string>
<string name="phantom_title_uncounted">Limit podřízených procesů řeší DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck spouští programy relace v procesech, které Android nezapočítává, takže možnosti pro vývojáře mohou zůstat vypnuté.</string>
<string name="phantom_fix_toggle">Zapněte „Deaktivace omezení podřízených procesů“ v Možnostech pro vývojáře a pak je nechte zapnuté.</string>
<string name="phantom_fix_no_toggle">Tato verze Androidu pro to nemá přepínač. Použijte bezdrátové ladění a změňte to z tohoto zařízení.</string>
<string name="upd_block_no_apk">Toto sestavení nemá stažení pro tuto kopii DroidDecku.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Hvis det ikke er muligt, så forbind enheden til en computer med ADB, og køre kommandoen nedenfor. Kom tilbage hertil, og tjek igen.</string>
<string name="phantom_instructions_off">Steam-sessioner kan starte.</string>
<string name="phantom_instructions_not_applicable">Denne Android-version bruger ikke denne grænse.</string>
<string name="phantom_title_uncounted">DroidDeck håndterer grænsen for underprocesser</string>
<string name="phantom_instructions_uncounted">DroidDeck kører sessionens programmer i processer, som Android ikke tæller med, så Indstillinger for udviklere kan forblive slået fra.</string>
<string name="phantom_fix_toggle">Tænd „Deaktiver begrænsningerne for underprocesser“ i Udvikleremuligheder, og lad Udvikleremuligheder være tændt bagefter.</string>
<string name="phantom_fix_no_toggle">Denne Android-version har ingen kontakt til det. Brug Trådløs fejlretning til at ændre det fra denne enhed.</string>
<string name="upd_block_no_apk">Denne version har ingen download til denne kopi af DroidDeck.</string>
+2
View File
@@ -2432,6 +2432,8 @@
<string name="phantom_instructions_fix">%1$s Falls das nicht möglich ist, verbinde dieses Gerät per ADB mit einem Computer und führe den Befehl unten aus. Kehre dann hierher zurück und prüfe erneut.</string>
<string name="phantom_instructions_off">Steam-Sitzungen können starten.</string>
<string name="phantom_instructions_not_applicable">Diese Android-Version nutzt dieses Limit nicht.</string>
<string name="phantom_title_uncounted">Limit für untergeordnete Prozesse übernimmt DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck führt die Programme der Sitzung in Prozessen aus, die Android nicht mitzählt, daher können die Entwickleroptionen ausgeschaltet bleiben.</string>
<string name="phantom_fix_toggle">Aktiviere „Beschränkungen für Unterprozesse deaktivieren“ in den Entwickleroptionen und lass die Entwickleroptionen danach aktiviert.</string>
<string name="phantom_fix_no_toggle">Diese Android-Version hat dafür keinen Schalter. Nutze Debugging über WLAN, um es auf diesem Gerät zu ändern.</string>
<string name="upd_block_no_apk">Dieser Build hat keinen Download für diese DroidDeck-Installation.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Αν αυτό δεν είναι δυνατό, συνδέστε αυτή τη συσκευή σε έναν υπολογιστή με ADB και εκτελέστε την παρακάτω εντολή. Επιστρέψτε εδώ και ελέγξτε ξανά.</string>
<string name="phantom_instructions_off">Οι συνεδρίες Steam μπορούν να ξεκινήσουν.</string>
<string name="phantom_instructions_not_applicable">Αυτή η έκδοση Android δεν χρησιμοποιεί αυτό το όριο.</string>
<string name="phantom_title_uncounted">Το DroidDeck χειρίζεται το όριο θυγατρικών διεργασιών</string>
<string name="phantom_instructions_uncounted">Το DroidDeck εκτελεί τα προγράμματα της συνεδρίας σε διεργασίες που το Android δεν μετράει, οπότε οι Επιλογές για προγραμματιστές μπορούν να μείνουν απενεργοποιημένες.</string>
<string name="phantom_fix_toggle">Ενεργοποιήστε την «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες» στις Επιλογές προγραμματιστή και αφήστε τις Επιλογές προγραμματιστή ενεργές μετά.</string>
<string name="phantom_fix_no_toggle">Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό. Χρησιμοποιήστε τον ασύρματο εντοπισμό σφαλμάτων για να το αλλάξετε από αυτή τη συσκευή.</string>
<string name="upd_block_no_apk">Αυτή η έκδοση δεν έχει λήψη για αυτό το αντίγραφο του DroidDeck.</string>
+2
View File
@@ -2466,6 +2466,8 @@
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a un ordenador con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
<string name="phantom_instructions_uncounted">DroidDeck ejecuta los programas de la sesión en procesos que Android no cuenta, así que las Opciones para desarrolladores pueden seguir desactivadas.</string>
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Jos se ei ole mahdollista, yhdistä tämä laite tietokoneeseen ADB:llä ja suorita alla oleva komento. Palaa tähän ja tarkista uudelleen.</string>
<string name="phantom_instructions_off">Steam-istunnot voivat käynnistyä.</string>
<string name="phantom_instructions_not_applicable">Tämä Android-versio ei käytä tätä rajaa.</string>
<string name="phantom_title_uncounted">DroidDeck hoitaa aliprosessirajoituksen</string>
<string name="phantom_instructions_uncounted">DroidDeck ajaa istunnon ohjelmat prosesseissa, joita Android ei laske, joten kehittäjäasetukset voivat pysyä pois päältä.</string>
<string name="phantom_fix_toggle">Ota käyttöön ”Poista käytöstä alatason prosessirajoitukset” Kehittäjäasetuksissa, ja pidä Kehittäjäasetukset päällä sen jälkeen.</string>
<string name="phantom_fix_no_toggle">Tässä Android-versiossa ei ole kytkintä sille. Käytä langatonta virheenkorjausta muuttaaksesi sitä tältä laitteelta.</string>
<string name="upd_block_no_apk">Tälle versiolle ei ole latausta tähän DroidDeck-kopioon.</string>
+2
View File
@@ -2465,6 +2465,8 @@
<string name="phantom_instructions_fix">%1$s Si ce n\'est pas possible, connectez cet appareil à un ordinateur avec ADB et exécutez la commande ci-dessous. Revenez ensuite ici et vérifiez à nouveau.</string>
<string name="phantom_instructions_off">Les sessions Steam peuvent démarrer.</string>
<string name="phantom_instructions_not_applicable">Cette version d\'Android n\'utilise pas cette limite.</string>
<string name="phantom_title_uncounted">Limite de processus enfants gérée par DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck exécute les programmes de la session dans des processus qu’Android ne compte pas : les options pour les développeurs peuvent rester désactivées.</string>
<string name="phantom_fix_toggle">Activez « Désactiver les limites pour les processus enfant » dans les options pour les développeurs, puis laissez les options pour les développeurs activées.</string>
<string name="phantom_fix_no_toggle">Cette version d\'Android ne dispose pas de cet interrupteur. Utilisez le débogage sans fil pour le modifier depuis cet appareil.</string>
<string name="upd_block_no_apk">Cette version ne propose aucun téléchargement pour cette copie de DroidDeck.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s अगर यह संभव नहीं है, तो इस डिवाइस को ADB वाले कंप्यूटर से कनेक्ट करें और नीचे दिया कमांड चलाएं। यहां वापस आएं और फिर से जांचें।</string>
<string name="phantom_instructions_off">Steam सेशन शुरू हो सकते हैं।</string>
<string name="phantom_instructions_not_applicable">यह Android वर्शन इस सीमा का उपयोग नहीं करता।</string>
<string name="phantom_title_uncounted">चाइल्ड-प्रोसेस सीमा DroidDeck संभालता है</string>
<string name="phantom_instructions_uncounted">DroidDeck सत्र के प्रोग्राम उन प्रोसेस में चलाता है जिन्हें Android नहीं गिनता, इसलिए डेवलपर विकल्प बंद रह सकते हैं।</string>
<string name="phantom_fix_toggle">डेवलपर विकल्प में “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें, और बाद में डेवलपर विकल्प चालू रहने दें।</string>
<string name="phantom_fix_no_toggle">इस Android वर्शन में इसके लिए कोई स्विच नहीं है। इसे इस डिवाइस से बदलने के लिए वायरलेस डीबगिंग इस्तेमाल करें।</string>
<string name="upd_block_no_apk">इस बिल्ड में DroidDeck की इस कॉपी के लिए कोई डाउनलोड नहीं है।</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Ha ez nem lehetséges, csatlakoztassa ezt az eszközt egy ADB-vel rendelkező számítógéphez, és futtassa az alábbi parancsot. Térjen vissza ide, és ellenőrizze újra.</string>
<string name="phantom_instructions_off">A Steam-munkamenetek elindulhatnak.</string>
<string name="phantom_instructions_not_applicable">Ez az Android-verzió nem használja ezt a korlátot.</string>
<string name="phantom_title_uncounted">A gyermekfolyamat-korlátot a DroidDeck kezeli</string>
<string name="phantom_instructions_uncounted">A DroidDeck a munkamenet programjait olyan folyamatokban futtatja, amelyeket az Android nem számol bele, így a fejlesztői beállítások kikapcsolva maradhatnak.</string>
<string name="phantom_fix_toggle">Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget a Fejlesztői beállításokban, és utána hagyja bekapcsolva a Fejlesztői beállításokat.</string>
<string name="phantom_fix_no_toggle">Ehhez az Android-verzióhoz nincs kapcsoló. Használja a vezeték nélküli hibakeresést a módosításához erről az eszközről.</string>
<string name="upd_block_no_apk">Ehhez a buildhez nincs letöltés a DroidDeck ezen másolatához.</string>
+2
View File
@@ -2415,6 +2415,8 @@
<string name="phantom_instructions_fix">%1$s Jika itu tidak memungkinkan, sambungkan perangkat ini ke komputer dengan ADB dan jalankan perintah di bawah. Kembali ke sini dan periksa lagi.</string>
<string name="phantom_instructions_off">Sesi Steam dapat dimulai.</string>
<string name="phantom_instructions_not_applicable">Versi Android ini tidak menggunakan batas ini.</string>
<string name="phantom_title_uncounted">Batas proses anak ditangani DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck menjalankan program sesi dalam proses yang tidak dihitung Android, jadi Opsi developer bisa tetap nonaktif.</string>
<string name="phantom_fix_toggle">Aktifkan “Nonaktifkan batasan proses turunan” di Opsi developer, dan biarkan Opsi developer tetap aktif setelahnya.</string>
<string name="phantom_fix_no_toggle">Versi Android ini tidak memiliki sakelar untuk itu. Gunakan Debugging nirkabel untuk mengubahnya dari perangkat ini.</string>
<string name="upd_block_no_apk">Build ini tidak memiliki unduhan untuk salinan DroidDeck ini.</string>
+2
View File
@@ -2457,6 +2457,8 @@
<string name="phantom_instructions_fix">%1$s Se non è possibile, collega questo dispositivo a un computer con ADB ed esegui il comando qui sotto. Poi torna qui e ricontrolla.</string>
<string name="phantom_instructions_off">Le sessioni Steam possono avviarsi.</string>
<string name="phantom_instructions_not_applicable">Questa versione di Android non usa questo limite.</string>
<string name="phantom_title_uncounted">Limite dei processi figli gestito da DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck esegue i programmi della sessione in processi che Android non conteggia, quindi le Opzioni sviluppatore possono restare disattivate.</string>
<string name="phantom_fix_toggle">Attiva “Disattiva limitazioni per i processi secondari” in Opzioni sviluppatore e poi lascia attive le Opzioni sviluppatore.</string>
<string name="phantom_fix_no_toggle">Questa versione di Android non ha un interruttore per farlo. Usa il debug wireless per cambiarlo da questo dispositivo.</string>
<string name="upd_block_no_apk">Questa build non ha un download per questa copia di DroidDeck.</string>
+2
View File
@@ -2415,6 +2415,8 @@
<string name="phantom_instructions_fix">%1$s それができない場合は、このデバイスをADBが使えるPCに接続し、以下のコマンドを実行してください。その後ここに戻って再確認してください。</string>
<string name="phantom_instructions_off">Steamセッションを開始できます。</string>
<string name="phantom_instructions_not_applicable">このAndroidバージョンではこの制限は使用されません。</string>
<string name="phantom_title_uncounted">子プロセスの制限は DroidDeck が対処します</string>
<string name="phantom_instructions_uncounted">DroidDeck はセッションのプログラムを Android が数えないプロセスで実行するため、開発者向けオプションはオフのままでかまいません。</string>
<string name="phantom_fix_toggle">開発者向けオプションで「子プロセスの制限を無効化」をオンにし、その後も開発者向けオプションをオンのままにしてください。</string>
<string name="phantom_fix_no_toggle">このAndroidバージョンにはこのスイッチがありません。ワイヤレスデバッグを使って、このデバイスから変更してください。</string>
<string name="upd_block_no_apk">このビルドには、このDroidDeckコピー用のダウンロードがありません。</string>
+2
View File
@@ -2415,6 +2415,8 @@
<string name="phantom_instructions_fix">%1$s 이 방법을 사용할 수 없으면 이 기기를 ADB가 설치된 PC에 연결하고 아래 명령을 실행하세요. 그런 다음 여기로 돌아와 다시 확인하세요.</string>
<string name="phantom_instructions_off">Steam 세션을 시작할 수 있습니다.</string>
<string name="phantom_instructions_not_applicable">이 Android 버전에서는 이 제한을 사용하지 않습니다.</string>
<string name="phantom_title_uncounted">하위 프로세스 제한은 DroidDeck이 처리합니다</string>
<string name="phantom_instructions_uncounted">DroidDeck은 세션의 프로그램을 Android가 세지 않는 프로세스에서 실행하므로 개발자 옵션을 꺼 둔 채로 두어도 됩니다.</string>
<string name="phantom_fix_toggle">개발자 옵션에서 “하위 프로세스 제한 사용 중지”를 켜고, 이후에도 개발자 옵션을 켜 둔 상태로 유지하세요.</string>
<string name="phantom_fix_no_toggle">이 Android 버전에는 해당 스위치가 없습니다. 무선 디버깅을 사용하여 이 기기에서 변경하세요.</string>
<string name="upd_block_no_apk">이 빌드에는 이 DroidDeck 복사본용 다운로드가 없습니다.</string>
+2
View File
@@ -2415,6 +2415,8 @@
<string name="phantom_instructions_fix">%1$s Jika itu tidak boleh, sambungkan peranti ini ke komputer dengan ADB dan jalankan arahan di bawah. Kembali ke sini dan semak semula.</string>
<string name="phantom_instructions_off">Sesi Steam boleh dimulakan.</string>
<string name="phantom_instructions_not_applicable">Versi Android ini tidak menggunakan had ini.</string>
<string name="phantom_title_uncounted">Had proses anak dikendalikan oleh DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck menjalankan program sesi dalam proses yang tidak dikira oleh Android, jadi Pilihan pembangun boleh kekal dimatikan.</string>
<string name="phantom_fix_toggle">Hidupkan “Lumpuhkan sekatan proses anak” dalam Pilihan pembangun, dan biarkan Pilihan pembangun hidup selepas itu.</string>
<string name="phantom_fix_no_toggle">Versi Android ini tidak mempunyai suis untuknya. Gunakan Debugging Wayarles untuk menukarnya daripada peranti ini.</string>
<string name="upd_block_no_apk">Binaan ini tidak mempunyai muat turun untuk salinan DroidDeck ini.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Hvis det ikke er mulig, koble denne enheten til en datamaskin med ADB og kjør kommandoen under. Kom tilbake hit og kontroller igjen.</string>
<string name="phantom_instructions_off">Steam-sesjoner kan starte.</string>
<string name="phantom_instructions_not_applicable">Denne Android-versjonen bruker ikke denne grensen.</string>
<string name="phantom_title_uncounted">DroidDeck håndterer grensen for underprosesser</string>
<string name="phantom_instructions_uncounted">DroidDeck kjører programmene i økten i prosesser som Android ikke teller med, så utvikleralternativer kan forbli av.</string>
<string name="phantom_fix_toggle">Slå på «Slå av begrensninger for underordnede prosesser» i Utvikleralternativer, og la Utvikleralternativer stå på etterpå.</string>
<string name="phantom_fix_no_toggle">Denne Android-versjonen har ingen bryter for det. Bruk trådløs feilsøking for å endre det fra denne enheten.</string>
<string name="upd_block_no_apk">Denne builden har ingen nedlasting for denne kopien av DroidDeck.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Als dat niet mogelijk is, sluit dit apparaat aan op een computer met ADB en voer de onderstaande opdracht uit. Kom hierna terug en controleer opnieuw.</string>
<string name="phantom_instructions_off">Steam-sessies kunnen starten.</string>
<string name="phantom_instructions_not_applicable">Deze Android-versie gebruikt deze limiet niet.</string>
<string name="phantom_title_uncounted">Limiet voor onderliggende processen geregeld door DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck voert de programma\'s van de sessie uit in processen die Android niet meetelt, dus Ontwikkelaarsopties kunnen uit blijven.</string>
<string name="phantom_fix_toggle">Schakel “Beperkingen voor onderliggende processen uitzetten” in bij Ontwikkelaarsopties en laat Ontwikkelaarsopties daarna aan staan.</string>
<string name="phantom_fix_no_toggle">Deze Android-versie heeft hier geen schakelaar voor. Gebruik draadloze foutopsporing om dit vanaf dit apparaat te wijzigen.</string>
<string name="upd_block_no_apk">Deze build heeft geen download voor dit exemplaar van DroidDeck.</string>
+2
View File
@@ -2492,6 +2492,8 @@
<string name="phantom_instructions_fix">%1$s Jeśli to niemożliwe, podłącz to urządzenie do komputera z ADB i uruchom poniższe polecenie. Wróć tutaj i sprawdź ponownie.</string>
<string name="phantom_instructions_off">Sesje Steam mogą się uruchamiać.</string>
<string name="phantom_instructions_not_applicable">Ta wersja systemu Android nie używa tego limitu.</string>
<string name="phantom_title_uncounted">Limitem procesów podrzędnych zajmuje się DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck uruchamia programy sesji w procesach, których Android nie liczy, więc Opcje programisty mogą pozostać wyłączone.</string>
<string name="phantom_fix_toggle">Włącz „Wyłącz ograniczenia procesów podrzędnych aplikacji” w Opcjach programisty i nie wyłączaj potem Opcji programisty.</string>
<string name="phantom_fix_no_toggle">Ta wersja systemu Android nie ma dla niego przełącznika. Użyj debugowania bezprzewodowego, aby zmienić go z tego urządzenia.</string>
<string name="upd_block_no_apk">Ta wersja nie ma pliku do pobrania dla tej kopii DroidDeck.</string>
@@ -2472,6 +2472,8 @@
<string name="phantom_instructions_fix">%1$s Se não for possível, ligue este dispositivo a um computador com ADB e execute o comando abaixo. Volte aqui e verifique novamente.</string>
<string name="phantom_instructions_off">As sessões Steam podem ser iniciadas.</string>
<string name="phantom_instructions_not_applicable">Esta versão do Android não usa este limite.</string>
<string name="phantom_title_uncounted">Limite de processos filhos gerido pelo DroidDeck</string>
<string name="phantom_instructions_uncounted">O DroidDeck executa os programas da sessão em processos que o Android não conta, por isso as Opções de programador podem continuar desativadas.</string>
<string name="phantom_fix_toggle">Ative «Desativar restrições de processos secundários» nas Opções de programador e mantenha as Opções de programador ativadas depois.</string>
<string name="phantom_fix_no_toggle">Esta versão do Android não tem um interruptor para isto. Use a depuração sem fios para o alterar a partir deste dispositivo.</string>
<string name="upd_block_no_apk">Esta versão não tem transferência para esta cópia do DroidDeck.</string>
+2
View File
@@ -2480,6 +2480,8 @@
<string name="phantom_instructions_fix">%1$s Se não for possível, conecte este dispositivo a um computador com ADB e execute o comando abaixo. Depois volte aqui e verifique de novo.</string>
<string name="phantom_instructions_off">As sessões do Steam podem ser iniciadas.</string>
<string name="phantom_instructions_not_applicable">Esta versão do Android não usa esse limite.</string>
<string name="phantom_title_uncounted">Limite de processos filhos gerenciado pelo DroidDeck</string>
<string name="phantom_instructions_uncounted">O DroidDeck executa os programas da sessão em processos que o Android não conta, então as Opções do desenvolvedor podem continuar desativadas.</string>
<string name="phantom_fix_toggle">Ative “Desativar restrições de processos filhos” nas Opções do desenvolvedor e mantenha as Opções do desenvolvedor ativadas depois.</string>
<string name="phantom_fix_no_toggle">Esta versão do Android não tem uma chave para isso. Use a depuração por Wi-Fi para alterar pelo próprio dispositivo.</string>
<string name="upd_block_no_apk">Esta versão não tem download para esta cópia do DroidDeck.</string>
+2
View File
@@ -2466,6 +2466,8 @@
<string name="phantom_instructions_fix">%1$s Dacă nu este posibil, conectează acest dispozitiv la un computer cu ADB și rulează comanda de mai jos. Revino aici și verifică din nou.</string>
<string name="phantom_instructions_off">Sesiunile Steam pot porni.</string>
<string name="phantom_instructions_not_applicable">Această versiune de Android nu folosește această limită.</string>
<string name="phantom_title_uncounted">Limita proceselor copil este gestionată de DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck rulează programele sesiunii în procese pe care Android nu le numără, așa că Opțiunile pentru dezvoltatori pot rămâne dezactivate.</string>
<string name="phantom_fix_toggle">Activează „Dezactivează restricțiile pentru procese secundare” în Opțiunile pentru dezvoltatori, și lasă Opțiunile pentru dezvoltatori activate după aceea.</string>
<string name="phantom_fix_no_toggle">Această versiune de Android nu are un comutator pentru asta. Folosește Depanarea wireless pentru a o schimba de pe acest dispozitiv.</string>
<string name="upd_block_no_apk">Această versiune nu are o descărcare pentru această copie de DroidDeck.</string>
+2
View File
@@ -2493,6 +2493,8 @@
<string name="phantom_instructions_fix">%1$s Если это невозможно, подключите устройство к компьютеру с ADB и выполните команду ниже. Затем вернитесь сюда и проверьте снова.</string>
<string name="phantom_instructions_off">Сессии Steam могут запускаться.</string>
<string name="phantom_instructions_not_applicable">Эта версия Android не использует это ограничение.</string>
<string name="phantom_title_uncounted">Ограничение дочерних процессов обходит DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck запускает программы сеанса в процессах, которые Android не учитывает, поэтому параметры разработчика можно не включать.</string>
<string name="phantom_fix_toggle">Включите «Отключить ограничения для дочерних процессов» в разделе «Для разработчиков» и оставьте этот раздел включенным.</string>
<string name="phantom_fix_no_toggle">В этой версии Android нет такого переключателя. Измените настройку с этого устройства через отладку по Wi-Fi.</string>
<string name="upd_block_no_apk">В этой сборке нет загрузки для этой копии DroidDeck.</string>
+2
View File
@@ -2440,6 +2440,8 @@
<string name="phantom_instructions_fix">%1$s Om det inte är möjligt ansluter du den här enheten till en dator med ADB och kör kommandot nedan. Kom tillbaka hit och kontrollera igen.</string>
<string name="phantom_instructions_off">Steam-sessioner kan starta.</string>
<string name="phantom_instructions_not_applicable">Den här Android-versionen använder inte den här gränsen.</string>
<string name="phantom_title_uncounted">DroidDeck hanterar gränsen för underprocesser</string>
<string name="phantom_instructions_uncounted">DroidDeck kör sessionens program i processer som Android inte räknar, så Utvecklaralternativ kan vara avstängda.</string>
<string name="phantom_fix_toggle">Slå på ”Inaktivera begränsningar på underordnade processer” i Utvecklaralternativ, och låt Utvecklaralternativ vara kvar på efteråt.</string>
<string name="phantom_fix_no_toggle">Den här Android-versionen har ingen växel för det. Använd trådlös felsökning för att ändra det från den här enheten.</string>
<string name="upd_block_no_apk">Den här versionen har ingen nedladdning för den här kopian av DroidDeck.</string>
+2
View File
@@ -2415,6 +2415,8 @@
<string name="phantom_instructions_fix">%1$s หากทำไม่ได้ ให้เชื่อมต่ออุปกรณ์นี้กับคอมพิวเตอร์ที่มี ADB แล้วรันคำสั่งด้านล่าง กลับมาที่นี่แล้วตรวจสอบอีกครั้ง</string>
<string name="phantom_instructions_off">เซสชัน Steam สามารถเริ่มได้</string>
<string name="phantom_instructions_not_applicable">Android รุ่นนี้ไม่ใช้ขีดจำกัดนี้</string>
<string name="phantom_title_uncounted">DroidDeck จัดการขีดจำกัดโปรเซสลูกให้</string>
<string name="phantom_instructions_uncounted">DroidDeck เรียกใช้โปรแกรมของเซสชันในโปรเซสที่ Android ไม่นับ จึงปิดตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ไว้ได้</string>
<string name="phantom_fix_toggle">เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” ในตัวเลือกสำหรับนักพัฒนา และเปิดตัวเลือกสำหรับนักพัฒนาไว้ต่อไปหลังจากนั้น</string>
<string name="phantom_fix_no_toggle">Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ใช้ Wireless debugging เพื่อเปลี่ยนค่าจากอุปกรณ์นี้</string>
<string name="upd_block_no_apk">บิลด์นี้ไม่มีให้ดาวน์โหลดสำหรับสำเนานี้ของ DroidDeck</string>
+2
View File
@@ -2432,6 +2432,8 @@
<string name="phantom_instructions_fix">%1$s Bu mümkün değilse bu cihazı ADB\'li bir bilgisayara bağlayıp aşağıdaki komutu çalıştırın. Buraya dönüp yeniden kontrol edin.</string>
<string name="phantom_instructions_off">Steam oturumları başlayabilir.</string>
<string name="phantom_instructions_not_applicable">Bu Android sürümü bu sınırı kullanmaz.</string>
<string name="phantom_title_uncounted">Alt işlem sınırını DroidDeck yönetiyor</string>
<string name="phantom_instructions_uncounted">DroidDeck oturumun programlarını Android\'in saymadığı işlemlerde çalıştırır; bu yüzden Geliştirici seçenekleri kapalı kalabilir.</string>
<string name="phantom_fix_toggle">Geliştirici seçenekleri\'nde “Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açın ve sonrasında Geliştirici seçeneklerini açık tutun.</string>
<string name="phantom_fix_no_toggle">Bu Android sürümünde bunun için bir anahtar yok. Bu cihazdan değiştirmek için Kablosuz hata ayıklamayı kullanın.</string>
<string name="upd_block_no_apk">Bu derlemede bu DroidDeck kopyası için bir indirme yok.</string>
+2
View File
@@ -2492,6 +2492,8 @@
<string name="phantom_instructions_fix">%1$s Якщо це неможливо, підключіть цей пристрій до комп’ютера з ADB і виконайте команду нижче. Потім поверніться сюди і перевірте ще раз.</string>
<string name="phantom_instructions_off">Сеанси Steam можуть запускатися.</string>
<string name="phantom_instructions_not_applicable">Ця версія Android не використовує це обмеження.</string>
<string name="phantom_title_uncounted">Обмеження дочірніх процесів обходить DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck запускає програми сеансу в процесах, які Android не враховує, тож параметри розробника можна не вмикати.</string>
<string name="phantom_fix_toggle">Увімкніть «Вимкнути обмеження для дочірніх процесів» у розділі «Параметри розробника» і залишіть «Параметри розробника» увімкненими після цього.</string>
<string name="phantom_fix_no_toggle">У цій версії Android немає перемикача для цього. Змініть це з цього пристрою за допомогою бездротового налагодження.</string>
<string name="upd_block_no_apk">У цій збірці немає завантаження для цієї копії DroidDeck.</string>
+2
View File
@@ -2415,6 +2415,8 @@
<string name="phantom_instructions_fix">%1$s Nếu không thể, hãy kết nối thiết bị này với một máy tính có ADB và chạy lệnh dưới đây. Quay lại đây và kiểm tra lại.</string>
<string name="phantom_instructions_off">Phiên Steam có thể khởi động.</string>
<string name="phantom_instructions_not_applicable">Phiên bản Android này không dùng giới hạn này.</string>
<string name="phantom_title_uncounted">DroidDeck xử lý giới hạn tiến trình con</string>
<string name="phantom_instructions_uncounted">DroidDeck chạy các chương trình của phiên trong những tiến trình mà Android không tính, nên có thể để tắt Tùy chọn cho nhà phát triển.</string>
<string name="phantom_fix_toggle">Bật “Tắt các mục hạn chế đối với tiến trình con” trong Developer options, và giữ Developer options luôn mở sau đó.</string>
<string name="phantom_fix_no_toggle">Phiên bản Android này không có công tắc cho việc đó. Dùng Gỡ lỗi qua mạng không dây để đổi nó từ thiết bị này.</string>
<string name="upd_block_no_apk">Bản build này không có tệp tải cho bản DroidDeck này.</string>
@@ -2492,6 +2492,8 @@
<string name="phantom_instructions_fix">%1$s 如果无法做到,请将此设备连接到装有 ADB 的电脑并运行下方命令,然后返回此处重新检查。</string>
<string name="phantom_instructions_off">可以启动 Steam 会话了。</string>
<string name="phantom_instructions_not_applicable">此 Android 版本不使用该限制。</string>
<string name="phantom_title_uncounted">子进程限制由 DroidDeck 处理</string>
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不计数的进程中运行会话程序,因此开发者选项可以保持关闭。</string>
<string name="phantom_fix_toggle">在开发者选项中打开“停止限制子进程”,之后请保持开发者选项开启。</string>
<string name="phantom_fix_no_toggle">此 Android 版本没有该开关。请使用无线调试在此设备上更改。</string>
<string name="upd_block_no_apk">此构建没有适用于此 DroidDeck 副本的下载。</string>
@@ -2412,6 +2412,8 @@
<string name="phantom_instructions_fix">%1$s 如無法這樣做,請將此裝置連接到已安裝 ADB 的電腦,並執行以下指令,然後返回這裡再檢查一次。</string>
<string name="phantom_instructions_off">可以啟動 Steam 會話。</string>
<string name="phantom_instructions_not_applicable">此 Android 版本不使用此限制。</string>
<string name="phantom_title_uncounted">子程序限制由 DroidDeck 處理</string>
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不計算的程序中執行工作階段的程式,因此開發人員選項可以保持關閉。</string>
<string name="phantom_fix_toggle">在開發人員選項中開啟「停用對子處理過程的限制」,之後請保持開發人員選項開啟。</string>
<string name="phantom_fix_no_toggle">此 Android 版本沒有此開關。請使用無線偵錯,直接在此裝置上更改。</string>
<string name="upd_block_no_apk">此版本沒有適用於此 DroidDeck 版本的下載。</string>
@@ -2412,6 +2412,8 @@
<string name="phantom_instructions_fix">%1$s 如果無法這麼做,請將此裝置連接到裝有 ADB 的電腦並執行下方指令,然後返回這裡重新檢查。</string>
<string name="phantom_instructions_off">可以啟動 Steam 工作階段。</string>
<string name="phantom_instructions_not_applicable">此 Android 版本不使用這項限制。</string>
<string name="phantom_title_uncounted">子程序限制由 DroidDeck 處理</string>
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不計算的程序中執行工作階段的程式,因此開發人員選項可以保持關閉。</string>
<string name="phantom_fix_toggle">在開發人員選項中開啟「停止限制子程序」,之後請保持開發人員選項開啟。</string>
<string name="phantom_fix_no_toggle">此 Android 版本沒有這個開關。請使用無線偵錯,直接在此裝置上變更。</string>
<string name="upd_block_no_apk">此組建版本沒有適用於此 DroidDeck 複本的下載檔案。</string>
+2
View File
@@ -2743,6 +2743,8 @@
<string name="phantom_instructions_fix">%1$s If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again.</string>
<string name="phantom_instructions_off">Steam sessions can start.</string>
<string name="phantom_instructions_not_applicable">This Android version does not use this limit.</string>
<string name="phantom_title_uncounted">Child-process limit handled by DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck runs most of the session\'s programs in processes Android does not count, which keeps the session well under the limit, so Developer options can stay off. Steam and some of its helpers still count.</string>
<string name="phantom_fix_toggle">Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards.</string>
<string name="phantom_fix_no_toggle">This Android version has no switch for it. Use Wireless debugging to change it from this device.</string>
<string name="upd_block_no_apk">This build has no download for this copy of DroidDeck.</string>
@@ -81,4 +81,10 @@ class PhantomProcessLimitTest {
assertFalse(PhantomProcessLimit.hasDeveloperToggle(33))
assertTrue(PhantomProcessLimit.hasDeveloperToggle(34))
}
@Test
fun theLimitOnDoesNotBlockSteamWhenTheSessionStaysOutOfItsCount() {
assertFalse(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.UNCOUNTED))
assertTrue(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.ENABLED))
}
}
+527
View File
@@ -0,0 +1,527 @@
# 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: **working on the AYN Thor (Android 13).** With Android's limit on and no developer option,
a Steam session with a game running keeps 12 processes in the app's counted cgroups (63 without
this work), and Android killed nothing in minutes of forced scans. DroidDeck's Setup reports the
limit as handled and no longer blocks Steam. Both counting gaps below are in identical code on
Android 12 through 16; a stock Android 14+ phone is still to be tested. 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**.
`settings_enable_monitor_phantom_procs=false` (the developer option) switches off both on Android
12L and later; Android 12 does not have the setting, and there only the `device_config` limit below
applies. Raising
`max_phantom_processes` through `device_config` (shell only) avoids only the first: the
excessive-CPU check still runs while monitoring is on.
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).
### Handoff in the native hook (prototype, on this branch)
`tools/nativeguest/hook/handoff.c`. At `execve()` in a forked child, a program named in
`DD_HANDOFF` is sent to the app's spawn socket instead of exec'd: the request carries argv, the
environment, the working directory and every inheritable fd with its number, and a worker execs
the program with those fds in place. The child records "my pid is now worker pid P" in a memfd
table its parent created, and exits. In the parent, `wait4`/`waitpid`/`wait`/`wait3`/`waitid` and
`kill` treat the forked pid as P until P exits. P's hook writes its exit status into the table; for
a program that ends without `exit()` (a signal) the app writes a report tagged with the child it is
for (from `ApplicationExitInfo`), which the parent's hook takes once P is gone, and sends the parent
`SIGCHLD`. Only the hook moves an entry to "exited", by compare-and-swap. A launch takes three
answers: the hook's "go" once it has P's pid, the worker's answer to the app's commit, and the
app's "ok" once the worker runs the program; without any of them the program runs locally instead,
never twice. The child's side is
vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
- **Scripts:** the list also matches the `#!` interpreter (`python3` for `droiddeck-agent`).
- **Exec chains:** a forked child that first execs a wrapper (`env`, `taskset`, a shell script,
Wine re-executing itself through `wine-preloader`) keeps its parent's table fd across the exec,
so the wrapper's own exec can still be handed off.
- **Not handed off:** Steam and the web helper's browser process (gamescope finds a window's app by
walking its process's parents) and its utility processes (the client refuses its transport —
"no transport is available" — from processes that are not its children). The web helper's
renderers hand off fine.
- **Game windows outside the reaper:** gamescope finds a window's app by walking its process up to
Steam's `reaper`, which a handed-off Wine process is not under. Proton sets `STEAM_GAME` itself
from `SteamGameId`, but a store game's is a 64-bit id and is not set: Splinter Cell (Ubisoft)
ran without ever taking focus. The agent now tags such a window from its process's `SteamAppId`
also on the arm64 client.
- One-shot programs cost a worker start (~100 ms) each, so the list names long-lived programs only
(`xprop+-spy`: `name+prefix` matches only when an argument starts with prefix).
- **Near the limit, a shell's children too.** Once 20 of the app's processes are counted (the hook
counts them in `/proc`: this uid's processes in an app process's cgroup other than that process),
a child of `bash`, `sh`, `dash`, `zsh`, `ksh`, `fish`, `make` or `xargs` is handed off even when
it is not listed. Those parents wait with `wait()`, which the hook answers; Qt's `QProcess` and
other parents that watch a child by pidfd or `/proc` would see the forked child end at once, so
their children stay. A job in the foreground of its controlling terminal (`TIOCGPGRP` on
`/dev/tty`, whatever its standard fds are: `cmd | less`, `less < file`) stays too: a handed-off
program has no controlling terminal, so `/dev/tty`, ^C and job control would miss it. A job a
shell with job control runs (any process group other than the shell's, `cmd &` in an interactive
terminal, each member of its pipeline) stays as well: the shell waits for its stops and continues,
which happen to a handed-off program's worker and never reach that wait. A job started with `&`
from a shell without job control (a script, `bash -c`) runs in the shell's group reading
`/dev/null`, and goes. Steam's client and launch chain (`steam`, its
web helper, `droiddeck-steam-x64`, `reaper`, `steam-launch-wrapper`, `pw-audio-namespace`,
gamescope, anything under `Steam/`) never go this way. In the desktop
session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at
61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and
at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a
`make -j` and its compilers), the D-Bus daemon's activation helpers (forks that never exec) and
the desktop's own programs started by KDE's launchers.
Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's
`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`.
Measured on the Thor, same session and game as above:
| | counted children, idle | counted, Bully (Proton) running |
|---|---|---|
| main, no handoff | 48 | 63 |
| handoff | **26** | **29** |
With the handoff on, Bully reached its menu at 30 fps, kept focus, and Steam's library, Decky, the
portals, NetworkManager/login1 and the agent all worked.
Then Android's own limit was switched back on (`settings_enable_monitor_phantom_procs=true`,
default limit 32) with the game running, and a scan was forced every 20 s for 3 minutes
(`dumpsys meminfo` refreshes the CPU stats the scan runs on; process starts and activity changes do
too, irregularly):
| | Android listed | killed | session |
|---|---|---|---|
| no handoff (`DD_SPAWN_DAEMONS=0`, same build) | 63 | **33**, oldest first: the session's bash, Python daemons, D-Bus, Xwayland, Steam, PipeWire, gamescope's reaper | FAILED |
| handoff | 27–29 (device-wide) | **0** in 9 scans | game running throughout |
### Taken further: the session itself in workers
A second round moved most of what was still counted:
- **The app's own processes:** `HostProcess.startUncounted` runs a host command in a worker with the
same contract as `HostProcess.start` (output lines, exit code, working directory). The session
root, the app log's logcat, PulseAudio and the DirectAudio relay use it. A worker cannot `chdir`
before its exec, so Android's `sh` does it from an environment of its own and exports the
program's (`env -i` cannot be used: the APK's library path contains `==`).
- **PulseAudio** closes every inherited fd at start, the worker's binder fd included, and Android
then killed the worker as dead (the SIGKILL came from system_server's `ActivityManager` thread,
seen with the `signal_generate` ftrace event, which shell can enable on the Thor). The daemon
spares the fd named in `PULSE_PASSED_FD`; the worker replaces `@DDH_WORKER_BINDER_FD@` in a
program's arguments and environment with its `/dev/binder` fd number, so PulseAudio is given it.
Started as a normal child the token reads as fd 0, which the daemon ignores.
- **The script's long-lived subshells:** `dd_job FUNCTION` runs a function in a new `bash` that first
loads the shell's variables, functions and options from a state file, so it is an exec'd program
the hook can hand off (`bash+dd-job`). `$!`, `kill` and `wait` keep working. The zRAM scanner,
the property watcher, Decky's supervisor and the request/timer loop use it.
- **The log pipeline** is `droiddeck-log-writer`, a script of its own instead of a `{ gnudd; cat; }`
subshell.
- **gamescope, its reaper and the inner `droiddeck-session steam`** are handed off. Steam, its web
helper's browser process and its utility processes still are not (see above).
Things this needed, found the hard way:
- **The binder fd is the worker's life.** It sits above every fd number the program gets; programs
that close all inherited fds (gamescope) are kept from closing it (the hook's kept fds, also
against `CLOSE_RANGE_CLOEXEC`); children never send it along with a handoff; and the hook closes
copies in every other process (`DDH_WORKER_PID`), so a worker's exit is seen when its program
exits. A worker that lost its binder fd was killed by Android within milliseconds.
- **A session of its own (`setsid`) for every worker.** All app processes are in zygote's process
group, so a program signalling its group reached the app itself (the hook also refuses
`kill(0)`/`kill(-pgid)` into zygote's group, and `kill(-1)`). `reap_orphans` in the session
script stands down when its parent is zygote.
- **Nested handoffs** (a program in a worker handing off its own child): inherited `DDH_*`
variables are dropped from each request.
- **Requests carry up to 240 fds,** in chunks of 60 (`LocalSocket` reads at most 64 per read), after
the request itself; the spawn server catches everything per connection (an uncaught exception there
took the whole app down once).
- **The table is made at a process's first fork,** not only when `DD_SPAWN` is in its environment at
start: a shell that exports it has no sign of it in its own environment.
- **Exit status:** the program's hook records it with `on_exit` or in `_exit()` into the parent's
table; the app's `ApplicationExitInfo` is only the fallback (signals). A program inherits its
forked parent's ignored signals, open-files limit and umask (`DDH_SIGIGN`, `DDH_NOFILE`,
`DDH_UMASK`).
Measured on the Thor, Bully under Proton, Android's limit on (default 32), a scan forced every 20 s:
| | counted, idle | counted, in game | killed in 3 min |
|---|---|---|---|
| main (no handoff) | 48 | 63 | 33, session failed |
| first round | 26 | 29 | 0 |
| second round | 9 | 14 | 0 |
| **third round** | **7–9** | **12** | **0** in 2 min, game kept focus |
Still counted at idle: `run_gamescope`'s subshell, Steam, its web helper's browser and
two or three utility processes, the session bus's activation babysitter and Decky's
multiprocessing child (forks without an exec). In game, also Steam's launch chain (`sh`,
`pw-audio-namespace`, `reaper`) and the `wineserver` daemon (a fork of its first process, which
lingers in its worker; see below).
### Third round
- **PulseAudio in a worker** (above).
- **`posix_spawn()`:** Python 3.13+ (`subprocess`, even with `close_fds`) and GLib's `g_spawn` start
programs with `posix_spawn()`, whose child makes the exec system call itself, past the hook. A
listed program is now spawned with `fork()` and the hook's `execve()`; the hook replays glibc's
file actions and attributes in the child, and a close-on-exec pipe returns an exec error as
`posix_spawn()`'s result. Proton's Wine and at-spi's bus came out of the count this way.
- **The table fd survives a child that closes every inherited fd** (Python's `subprocess` before
exec): it sits at fd 800 or above and is one of the hook's kept fds. Reopening it from
`/proc/<owner>/fd` does not work on Android (EACCES). A nonce in the table's header tells it from
a file a program put at that number (inode numbers are rewritten by the hardlink emulation).
- **The exit status comes from the program itself.** The worker first runs a `bash` that `cd`s and
execs the program; that `bash` closed the `DDH_TABLE` fd as someone else's table, so the
program after it could never report, and statuses came from `ApplicationExitInfo`, late or
unknown. The `DDH_TABLE` fd is now kept through that exec, and `_exit()` reports as `exit()` does.
- **Daemons:** Android kills every process in a worker's cgroup when the worker's own process ends
(`libprocessgroup: Successfully killed process cgroup`). `wineserver` forks the server and leaves
with `_exit(0)`, so the server died with it and Wine stopped with "the wine server failed to run".
A handed-off program's process now reports its status and then stays, with no fds but the
binder's and all signals blocked, until no other process is left in its cgroup (found through
`/proc/<pid>/cgroup`, as `cgroup.procs` is not readable). It does so only when it is
single-threaded at exit, and never for the processes the app starts itself (the session root),
whose exit the app waits for.
- **`reap_orphans`** in the session script killed every process whose parent was zygote (all the
app's workers, the session root among them) when the inner `droiddeck-session` ended in a
worker: the guest cannot see zygote in `/proc`. It now stands down when `DDH_WORKER_PID` is
its own pid.
- **`DD_HANDOFF_DEBUG=/path`** appends the hook's trace to a file. On stderr it broke Steam's
login, and the trace from a game's processes went to a pipe nobody read.
- **Finding the sender of a SIGKILL:** shell can enable the `signal/signal_generate` ftrace event
on the Thor (`/sys/kernel/tracing`), which names the sending thread; Perfetto recorded nothing
there.
- **Ending a game from Steam** (`SteamClient.Apps.TerminateApp`, the overlay's Exit game) left Wine
running since the first round: Steam sends SIGINT to the launch's `reaper` and its parent, and the
reaper ends what is under it, which handed-off programs are not. Each handed-off program now
lists itself as `P<pid>` with the process that forked its child and, for when that process is
gone (Wine starts a process through a fork that exits at once), the worker's program it descended
from. A signal to `reaper SteamLaunch` from a hooked process also goes, as SIGTERM for SIGINT
(Wine takes SIGINT for a console's Ctrl+C), to the groups of every listed program under that
reaper, all found before any is signalled.
- **Process groups:** a handed-off program runs in a session of its own, outside the group its
forked parent's child was in. It lists itself as `GROUP.PID.START` for that group (`DDH_PGID`,
also for the processes it forks), and the hook's `kill(-GROUP)`, `kill(0)` and `killpg()` also
signal the groups those programs lead.
- **Tried and dropped:** handing off Steam's launch chain (`sh`, `steam-launch-wrapper`, `reaper`):
the client tracks the process it forked, which then exits at once, and called the game closed.
Showing a handed-off program's forking process as its parent in `/proc/<pid>/stat` and `status`
left Steam's UI at "Loading library data": the client checks the parents of the processes on its
IPC connections with `lsof -F R`. Only the program's own `getppid()` answers with that process
(while it lives, then 1): the GOG launch leases the game folder for as long as the launcher, its
parent, runs, and took zygote, which the guest cannot see, for a launcher already gone. And
`posix_spawn()` emulation must make only
system calls in its child (no hook wrapper takes a lock there): one Steam fork hung on a lock
another thread held.
Quitting the game (also from Steam), stopping the session (no worker is left) and starting
again all work. Started from the front end with the limit on, Setup shows "Child-process limit
handled by DroidDeck" and Steam starts.
### Cost
Measured on the Thor, Bully under Proton, the handoff on (`childProcessHandoff`) against off, two
sessions each:
| | off | on, first | on, now |
|---|---|---|---|
| one program started, `fork`+`exec` of `/usr/bin/true` | 37–39 ms | 197 ms | 80 ms |
| `start steam` to READY | 14.0–14.2 s | 20.0–20.2 s | 18.2–18.5 s |
| `launch` to the game's focus | 10.1 s | 14.7–14.8 s | 11.6–11.7 s |
| in game: frames, CPU of the app's uid, `system_server` | 29.9 fps, 1.02–1.05 s/s, 21 ms/s | 29.8 fps, 1.11 s/s, 21–27 ms/s | 29.8–29.9 fps, 1.10–1.11 s/s, 22 ms/s |
| memory of the app's processes (RSS) | 3.57–3.62 GB | 3.42–3.50 GB | 3.49–3.66 GB |
Running costs nothing measurable; starting things does. A handed-off program costs a worker: a
zygote fork, its runtime (40–50 ms of CPU) and the bind, and the worker waited 100 ms before its
exec so as not to cut off its reply. Now the app closes a pipe once it has the reply and the worker
execs then, and two workers are kept bound ahead of need while a session runs (12 MB of PSS each);
four did no better. Starting a session takes about 10 more CPU-seconds (51 s against 41 s for the
app's uid), and the last 4 s come from the session script's own steps running beside the
handed-off daemons. With only the hook's handoffs off (`DD_SPAWN_DAEMONS=0`), READY came at
14.1 s: the app's own workers (the session root, PulseAudio, logcat) cost nothing there.
**In the app:** `PhantomProcessStatus.UNCOUNTED` is reported when the limit is on but the session
runs in workers (`GuestWorkers.enabled`: the native userland, Android 11+, and the
`childProcessHandoff` session preference, on by default). It does not block Steam. Turning the
preference off (`droiddeckctl prefs set session childProcessHandoff false --type bool`, with
Setup > Developer > Debugging tools on; see `docs/agent-control.md`) brings back
the old behavior and the old requirement.
### C. Plan
1. ~~Verify both gaps on the Thor~~ done; still to do on a stock Android 14+ phone (enforcing
SELinux, unlike the Thor) and on a Mali device.
2. ~~B for the processes DroidDeck and the session script start themselves~~ done.
3. ~~B inside the hook, with pid translation~~ done.
4. ~~The session root, its jobs, the log pipeline, the gamescope chain~~ done: 9 idle, 14 in game.
Third round (PulseAudio, `posix_spawn`, daemons): 7–9 idle, 12 in game.
5. ~~Setup no longer requires the developer option while the session runs in workers~~ done.
6. Open:
- ~~PulseAudio in a worker~~ done;
- ~~`posix_spawn()` and daemons in workers~~ done;
- `/proc/<pid>/stat` showing the virtual parent, so that Steam and its web helper can be handed
off too;
- ~~pre-started workers, so that a handoff costs no zygote fork~~ done: two are kept bound;
- ~~more games and configurations~~ done on the Thor with the stock limit on, no kills in any:
Bully on GE-Proton, Proton Experimental ARM64 and DroidDeck-Proton 11 (11–14 counted), Bomb
Rush Cyberfunk (14), MGSV Ground Zeroes (13), Sekiro (13), zero-copy off (11), the x86-64
Steam client under FEX (14, against 55 without the handoff), Splinter Cell through Ubisoft
Connect (14, against 65), Star Wars: Galaxy of Heroes (EA, 14), 9 Years of Shadows (GOG, 14),
run mode with 40 background jobs (1), the desktop at rest (17–20) and
with a terminal's 40 background jobs (20). PRoot sessions keep the old behavior and still need
the developer option: with the limit on, Android killed 30 of their processes and the session
failed;
- Wine-heavy launchers and anti-cheat;
- a settings switch for `childProcessHandoff`.
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
broker and keeps the GPU outside.
## 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.
- A listed program's stops and continues (`kill -STOP`, `SIGCONT`) reach its worker, not a wait in
its parent: `waitpid(…, WUNTRACED)` and `WCONTINUED` report none for it. Listed programs are the
session's own (Steam, Wine, game helpers), whose parents start them without job control; one a
shell runs as a job-control job (`wine game.exe &` in an interactive terminal) stays counted, as
any such job does, so its shell gets its stops. Reading
the worker's state from `/proc` instead was tried and dropped: a stop and a continue can both
fall between two reads.
## 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.
The limit of 4 below is device-wide: a trim while it is set can kill other apps' child processes,
which restoring the setting does not bring back. Use a test device or an emulator with nothing else
running, and note the current values first, to put them back afterwards:
```
adb shell settings get global settings_enable_monitor_phantom_procs
adb shell device_config get activity_manager max_phantom_processes
adb shell device_config get_sync_disabled_for_tests
```
Android 12 and some Android 13 builds have no `get_sync_disabled_for_tests`; there `adb shell
device_config is_sync_disabled_for_tests` answers only true or false, so it cannot tell `persistent`
from `until_reboot`. Note `none` when it says false. When it says true, sync is already off: skip
the `set_sync_disabled_for_tests persistent` step below, which keeps whichever mode it was, and
leave the mode alone when you restore the rest.
```
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 the noted values afterwards: `adb shell device_config put
activity_manager max_phantom_processes <value>` (or `adb shell device_config delete activity_manager
max_phantom_processes` if it was null), `adb shell device_config set_sync_disabled_for_tests <mode>`
and `adb shell settings put global settings_enable_monitor_phantom_procs <value>`, and end the lab's
sleepers with `adb shell am force-stop com.droiddeck.phantomlab`.
+4 -5
View File
@@ -35,11 +35,10 @@ GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
VULKAN_HEADERS_TAG=v1.4.341
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
# Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it
# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp
LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349)
LAYER_VERSION=14.1
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
LAYER_VERSION=12.8
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
-1
View File
@@ -1,7 +1,6 @@
# GStreamer plugins packed for winegstreamer (game video/audio), from the imagefs's lib/gstreamer-1.0 by name
# (libgst<name>.so): Proton's usual set as far as this imagefs has it (no vpx; videoconvert+videoscale are videoconvertscale).
coreelements
debug
app
audioconvert
audiorate
-18
View File
@@ -109,9 +109,6 @@ export NTSYNC_SHM=$COMPAT/ntsync-shm
# DroidDeck's Force SSBS (its glibc libssbs.so preload) is bionic Wine's own WINE_FORCE_SSBS
on "${DROIDDECK_FORCE_SSBS:-}" && export WINE_FORCE_SSBS=1
export HODLL=libwow64fex.dll WINEDEBUG=err+all,fixme-all
# The network adapter list (GetAdaptersAddresses) from the layer's getifaddrs code: its default if_nameindex code never
# answered here, and the Paradox Launcher (Europa Universalis IV) waited on it forever.
export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}
export XENVIRONMENT=$TOOL/bionic/Xdefaults
# The adapter's Wayland swapchain gets its buffers back from gamescope later than DroidDeck-Proton's Turnip does;
# with gamescope's default three images the game waits for one about a fifth of the time at high frame rates.
@@ -309,21 +306,6 @@ if [ "$verb" != runinprefix ] && prefix_busy; then
fi
prefix_busy || rm -f "$NTSYNC_SHM".v*
# Steam's running client, as a game's steam_api checks it: Proton names its steam.exe (the prefix's first program,
# alive while the game runs), which this tool does not start. Here the first program is the one Steam started, so a
# launcher that starts the game and quits (EU4's dowser.exe) left a game that reported "Steam not detected". The
# PID is the one this tool's own prefixes carry.
steam_pid() {
R=$COMPAT/pfx/user.reg
[ -f "$R" ] || return 0
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
on && /^"PID"=dword:/ && $0 != "\"PID\"=dword:0000fffe" { found = 1 } END { exit !found }' "$R" || return 0
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
on && /^"PID"=dword:/ { print "\"PID\"=dword:0000fffe"; next } { print }' "$R" > "$R.dd-new.$$" && mv -f "$R.dd-new.$$" "$R" &&
echo "$(date +%H:%M:%S) Steam's process ID in the registry set to this tool's"
}
prefix_busy || steam_pid
# Links into a tool that is gone (an older DroidDeck-Bionic, a deleted DroidDeck-Proton) or to a file it no longer has.
# Wine's update cannot write over them, so drivers (network, controller) and other files stay missing. Drop them and
# clear both stamps: prepare_prefix relinks this tool's files and Wine's update puts its own back.
-16
View File
@@ -36,21 +36,6 @@ zpath() {
esac
}
# Drive links of the prefix in compatdata folder $1 that name guest paths (DroidDeck-Proton's s: for the Steam library)
# -> their Android paths, which this Wine follows. A game's mods on S: were missing otherwise. A session's start
# gives them their guest paths back (NativeGuest.relinkPrefixDrives); z: is launch.sh's.
android_drives() {
local d t a
for d in "$1"/pfx/dosdevices/[a-y]:; do
[ -L "$d" ] || continue
t=$(readlink "$d")
case "$t" in /*) ;; *) continue ;; esac
a=$(real "$t")
[ "$a" = "$t" ] && continue
ln -sfn "$a" "$d.dd-new.$$" && mv -fT "$d.dd-new.$$" "$d" && echo "drive ${d##*/} -> $a"
done
}
# Where a game launch's log goes in DroidDeck's session folder (Share logs takes that folder): the game's log folder
# when Detailed graphics logs made one (droiddeck-game-env), else a folder of its own; nothing for other verbs
session_logs() {
@@ -124,7 +109,6 @@ print(" ".join(sorted(n for n in names if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*"
PY
)
export DROIDDECK_BIONIC_KEEP
[ -n "${STEAM_COMPAT_DATA_PATH:-}" ] && android_drives "$STEAM_COMPAT_DATA_PATH" >&2
exec /system/bin/sh "$tool/bionic/launch.sh" "$verb" "$compat" "$exe" ${args[@]+"${args[@]}"} ;;
getcompatpath)
p=$(real "${1:-}")
@@ -282,8 +282,10 @@ def sandboxed_apps(proc=Path("/proc")):
def window_steam_app(win, flatpaks, proc=Path("/proc")):
match = STEAM_APP_CLASS.match(win.get("class") or "")
if match:
return match.group(1) if os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64" else None
if match and os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64":
return match.group(1)
# Gamescope finds the app of a window whose process runs under Steam's reaper. A game the
# session runs in a worker process (GuestWorkers) is not under it, whatever its class.
pid = win.get("pid")
if pid:
if under_reaper(pid, proc):
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
# Appends stdin to a session log up to a byte cap, then reads and drops the rest, so that the session
# writing into it never gets SIGPIPE. A program of its own, rather than a subshell of the session, so
# that the native hook can start it outside the app's counted child processes.
# usage: droiddeck-log-writer FILE CAP_BYTES
dd=$(command -v gnudd || echo dd)
"$dd" of="$1" oflag=append conv=notrunc iflag=count_bytes count="$2" bs=65536 status=none
exec cat >/dev/null
@@ -14,6 +14,59 @@ 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, and the ones not started as jobs in $dd_daemons, which
# the session stops as it ends.
dd_daemons=
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.$$ rc=0
/usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@" || rc=$?
dd_spawned=$(cat "$f" 2>/dev/null)
rm -f "$f"
if [ "$rc" = 0 ] && [ -n "$dd_spawned" ]; then
dd_daemons="$dd_daemons $dd_spawned"
return 0
fi
# started, but its pid is unknown: not a second time
[ "$rc" = 3 ] && { dd_spawned=; return 0; }
fi
"$@" &
dd_spawned=$!
}
dd_stop_daemons() {
[ -n "$dd_daemons" ] && kill $dd_daemons 2>/dev/null
dd_daemons=
}
dd_session_pid=$$
# Runs function $1 (with its arguments) in the background in a new bash that first loads this shell's
# variables, functions and options: a background subshell, but an exec'd program, which the native
# hook can hand to its own process (DD_HANDOFF "bash+dd-job"). $! is its pid, as for ( ... ) &.
dd_job() {
local state
if [ -n "${DD_HANDOFF:-}" ] && state=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/.dd-job.XXXXXX" 2>/dev/null); then
{
declare -p | grep -Ev '^declare -[a-zA-Z]*r|^declare -[-a-zA-Z]* (BASH[A-Z_]*|FUNCNAME|GROUPS|DIRSTACK|PIPESTATUS|COPROC|LINENO|_)='
declare -f
shopt -p
set +o
} > "$state" 2>/dev/null
/bin/bash -c 'source "$1" 2>/dev/null; rm -f "$1"; shift; "$@"' dd-job "$state" "$@" &
else
"$@" &
fi
}
# Long-lived programs the session's guests start run in their own processes too
# (tools/nativeguest/hook/handoff.c). Not Steam, its web helper's browser process (gamescope finds a
# window's app by walking its process's parents) or its utility processes (the client only accepts
# its transport from its own children).
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
else
unset DD_HANDOFF
fi
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"
@@ -24,8 +77,12 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
if [ "$(stat -c %s "$DD_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
mv -f "$DD_LOG" "$DD_LOG.1"
fi
dd=$(command -v gnudd || echo dd)
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
if [ -x /usr/local/bin/droiddeck-log-writer ]; then
exec > >(exec /usr/local/bin/droiddeck-log-writer "$DD_LOG" "${DD_LOG_CAP:-268435456}") 2>&1
else
dd=$(command -v gnudd || echo dd)
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
fi
echo "== droiddeck-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
@@ -610,6 +667,11 @@ dd_stretch_game_screen() {
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
reap_orphans() {
local round p stat pid left
# Started by the app as an Android process of its own: its parent is zygote, whose other
# children are the app's processes. The guest may not see zygote in /proc; a worker's own
# program has DDH_WORKER_PID.
[ "${DDH_WORKER_PID:-}" = "$$" ] && return 0
case "$(tr -d '\0' < "/proc/$PPID/cmdline" 2>/dev/null)" in ''|zygote*) return 0 ;; esac
for round in 1 2 3 4 5; do
left=
for p in /proc/[0-9]*; do
@@ -628,7 +690,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
@@ -771,7 +833,7 @@ case $mode in
fi
if [ "${DD_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
(
_dd_job_zram() {
dd_zram_scan() {
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0
@@ -1116,7 +1178,7 @@ case $mode in
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
while kill -0 $$ 2>/dev/null; do
while kill -0 "$dd_session_pid" 2>/dev/null; do
dd_memory_tick
if [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
@@ -1125,7 +1187,8 @@ case $mode in
nap 5
fi
done
) &
}
dd_job _dd_job_zram
fi
if [ "${DD_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] \
&& [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
@@ -1217,7 +1280,7 @@ case $mode in
) &
fi
fi
[ -z "${DD_DESKTOP:-}" ] && (
_dd_job_properties() {
stretch=0 restore=0
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
@@ -1296,8 +1359,9 @@ case $mode in
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
;;
esac
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
) &
done < <(exec xprop -spy -root "${atoms[@]}" 2>/dev/null)
}
[ -n "${DD_DESKTOP:-}" ] || dd_job _dd_job_properties
steam_hold_launch() {
local game=$1 shortcut= waited=0 status=0
_dd_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
@@ -1384,8 +1448,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 +1457,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 +1482,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
@@ -1456,7 +1520,7 @@ case $mode in
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then
(
_dd_job_decky() {
decky_child=
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
trap decky_stop TERM INT HUP
@@ -1480,7 +1544,8 @@ case $mode in
echo "== Decky: loader exited with status $decky_status; restart $((decky_exits + 1))/5 in ${decky_delay}s"
sleep "$decky_delay"
done
) &
}
dd_job _dd_job_decky
decky_supervisor=$!
echo "== Decky: session supervisor started ($decky_arch)"
else
@@ -1681,7 +1746,7 @@ case $mode in
rm -f "$DD_LAUNCH_DIR/steam-stop" "$DD_LAUNCH_DIR/steam-game" "$DD_LAUNCH_DIR/steam-game.tmp"
requests=1
fi
(
_dd_job_requests() {
tick=0
beat=0
library_job=
@@ -1859,7 +1924,8 @@ case $mode in
fi
fi
done
) &
}
dd_job _dd_job_requests
stop_watcher=$!
if [ "${DD_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then
LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /'
@@ -2013,6 +2079,7 @@ case $mode in
wait "$decky_supervisor" 2>/dev/null || true
echo "== Decky: session supervisor stopped"
fi
dd_stop_daemons
_dd_jobs=$(jobs -p)
[ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null
echo "== steam: the client on the desktop has exited"
@@ -2022,6 +2089,7 @@ case $mode in
wait "$decky_supervisor" 2>/dev/null || true
echo "== Decky: session supervisor stopped"
fi
dd_stop_daemons
_dd_jobs=$(jobs -p)
[ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null
reap_orphans
+103
View File
@@ -0,0 +1,103 @@
#!/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 re
import socket
import struct
import sys
# Exit status when the program started but its pid could not be reported: the caller must not
# start it again.
STARTED_UNREPORTED = 3
def report(pid, pid_file):
try:
if pid_file:
with open(pid_file, "w") as f:
f.write("%s\n" % pid)
else:
print(pid, flush=True)
return True
except OSError as e:
print("droiddeck-spawn: started pid %s but could not report it: %s" % (pid, e), file=sys.stderr)
return False
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)
reported = report(pid, pid_file)
if wait:
return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
return 0 if reported else STARTED_UNREPORTED
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)
request = {"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}
# the session it belongs to, as SessionService writes it (a positive decimal); anything else is
# left out, and the app then runs nothing for it
session = os.environ.get("DD_SPAWN_SESSION", "")
if re.fullmatch(r"[1-9][0-9]{0,8}", session):
request["session"] = int(session)
payload = json.dumps(request).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)
reported = report(first[1], pid_file)
if not wait:
return 0 if reported else STARTED_UNREPORTED
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
@@ -82,6 +82,7 @@
#include "hook/exec_probe.c"
#include "hook/static_programs.c"
#include "hook/go_programs.c"
#include "hook/handoff.c"
#include "hook/exec.c"
#include "hook/net.c"
#include "hook/sockets.c"
+197 -1
View File
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ENOSYS;
return -1;
}
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
// like the kernel would pass it; routing below uses the absolute form.
@@ -659,7 +660,16 @@ pid_t fork(void) {
int n = __atomic_add_fetch(&forks, 1, __ATOMIC_RELAXED);
if (n == 1 || n >= DDNATV_FORKS_BEFORE_REHEARSAL) prepare_exec_in_parent(n >= DDNATV_FORKS_BEFORE_REHEARSAL ? 2 : 1);
}
ddh_prepare();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
// A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its
// execve() is a real one (only read in the usual case, so no page is copied for it)
if (pid == 0 && __atomic_load_n(&g_exec_rehearsal, __ATOMIC_RELAXED)) __atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELAXED);
@@ -1065,6 +1075,181 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
static int apply_closefrom(posix_spawn_file_actions_t *actions);
// glibc's file actions (posix/spawn_int.h, unchanged since 2.35)
struct ddh_spawn_action {
enum { DDH_DO_CLOSE, DDH_DO_DUP2, DDH_DO_OPEN, DDH_DO_CHDIR, DDH_DO_FCHDIR, DDH_DO_CLOSEFROM, DDH_DO_TCSETPGRP } tag;
union {
struct { int fd; } close_action;
struct { int fd; int newfd; } dup2_action;
struct { int fd; char *path; int oflag; mode_t mode; } open_action;
struct { char *path; } chdir_action;
struct { int fd; } fchdir_action;
struct { int from; } closefrom_action;
struct { int fd; } setpgrp_action;
} action;
};
#ifndef POSIX_SPAWN_SETSID
#define POSIX_SPAWN_SETSID 0x80
#endif
static int ddh_spawn_errno(long ret) {
return ret < 0 ? errno : 0;
}
static int ddh_spawn_close_part(unsigned int first, unsigned int last, void *unused) {
(void)unused;
return (int)call_orig_syscall(SYS_close_range, first, last, 0, 0, 0, 0);
}
// What glibc's spawn child does before its exec (posix/spawni.c), as an errno. Its fd and
// directory work is done with system calls, not the hook's wrappers: those take locks that another
// thread of the parent may have held at fork() (Steam has many threads).
static int ddh_spawn_child_setup(const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr) {
short flags = 0;
if (attr) posix_spawnattr_getflags(attr, &flags);
if (flags & POSIX_SPAWN_SETSIGDEF) {
sigset_t def;
posix_spawnattr_getsigdefault(attr, &def);
for (int sig = 1; sig < _NSIG; sig++) {
if (sigismember(&def, sig) == 1) signal(sig, SIG_DFL);
}
}
if ((flags & POSIX_SPAWN_SETSID) && setsid() < 0) return errno;
if (flags & POSIX_SPAWN_SETPGROUP) {
pid_t group = 0;
posix_spawnattr_getpgroup(attr, &group);
if (setpgid(0, group) != 0) return errno;
}
if (flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)) {
struct sched_param param;
posix_spawnattr_getschedparam(attr, &param);
int policy = 0;
posix_spawnattr_getschedpolicy(attr, &policy);
int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, &param) : sched_setparam(0, &param);
if (r == -1) return errno;
}
const struct ddh_spawn_action *a = fa ? (const struct ddh_spawn_action *)fa->__actions : NULL;
char path[PATH_MAX];
int err;
for (int i = 0; a && i < fa->__used; i++) {
switch (a[i].tag) {
case DDH_DO_CLOSE:
// the handoff table and the worker's binder stay open (kept fds)
if (!is_kept_fd(a[i].action.close_action.fd))
call_orig_syscall(SYS_close, (unsigned long)a[i].action.close_action.fd, 0, 0, 0, 0, 0);
break;
case DDH_DO_OPEN: {
const char *real = rewrite_path(a[i].action.open_action.path, path, sizeof(path));
// as glibc: the target goes first, so a full fd table still has room for the open
if (!is_kept_fd(a[i].action.open_action.fd))
call_orig_syscall(SYS_close, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0, 0);
long fd = call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
(unsigned long)a[i].action.open_action.oflag, a[i].action.open_action.mode, 0, 0);
if (fd < 0) return errno;
if (fd != a[i].action.open_action.fd) {
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)fd, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0))))
return err;
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
}
break;
}
case DDH_DO_DUP2: {
int from = a[i].action.dup2_action.fd, to = a[i].action.dup2_action.newfd;
if (from == to) {
long fdflags = call_orig_syscall(SYS_fcntl, (unsigned long)from, F_GETFD, 0, 0, 0, 0);
if (fdflags < 0) return errno;
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fcntl, (unsigned long)from, F_SETFD, (unsigned long)(fdflags & ~FD_CLOEXEC), 0, 0, 0))))
return err;
} else if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)from, (unsigned long)to, 0, 0, 0, 0)))) {
return err;
}
break;
}
case DDH_DO_CHDIR: {
const char *real = rewrite_path_follow(a[i].action.chdir_action.path, path, sizeof(path));
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_chdir, (unsigned long)real, 0, 0, 0, 0, 0)))) return err;
break;
}
case DDH_DO_FCHDIR:
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fchdir, (unsigned long)a[i].action.fchdir_action.fd, 0, 0, 0, 0, 0))))
return err;
break;
case DDH_DO_CLOSEFROM:
for_each_range_without((unsigned int)a[i].action.closefrom_action.from, ~0U, g_kept_fds, g_kept_fd_count,
ddh_spawn_close_part, NULL);
break;
case DDH_DO_TCSETPGRP:
if (tcsetpgrp(a[i].action.setpgrp_action.fd, getpgrp()) != 0) return errno;
break;
}
}
if (flags & POSIX_SPAWN_SETSIGMASK) {
sigset_t mask;
posix_spawnattr_getsigmask(attr, &mask);
sigprocmask(SIG_SETMASK, &mask, NULL);
}
return 0;
}
// posix_spawn() as fork() and execve(), so that ddh_try() sees the exec. -1 when it cannot be.
static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
if (fa) {
const struct ddh_spawn_action *a = (const struct ddh_spawn_action *)fa->__actions;
// A terminal action stays with glibc, which blocks signals around the file actions: here a
// SIGTTOU could stop the child at tcsetpgrp() with the parent waiting on its report.
for (int i = 0; i < fa->__used; i++) {
if ((unsigned)a[i].tag >= DDH_DO_TCSETPGRP) return -1;
}
}
// A scheduling policy or priority would apply to this child, not to the worker that runs the program
short spawn_flags = 0;
if (attr && posix_spawnattr_getflags(attr, &spawn_flags) == 0 &&
(spawn_flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)))
return -1;
int report[2];
if (pipe2(report, O_CLOEXEC) != 0) return -1;
pid_t child = fork();
if (child < 0) {
int err = errno;
close(report[0]);
close(report[1]);
return err;
}
if (child == 0) {
call_orig_syscall(SYS_close, (unsigned long)report[0], 0, 0, 0, 0, 0);
// Out of the file actions' way: high, and one of the fds they leave open (closefrom(3) is common)
int to_parent = (int)call_orig_syscall(SYS_fcntl, (unsigned long)report[1], F_DUPFD_CLOEXEC, 1000, 0, 0, 0);
if (to_parent >= 0) {
call_orig_syscall(SYS_close, (unsigned long)report[1], 0, 0, 0, 0, 0);
ddh_keep(to_parent);
} else {
to_parent = report[1];
}
int err = ddh_spawn_child_setup(fa, attr);
if (!err) {
execve(path, argv, envp);
err = errno;
}
syscall(SYS_write, to_parent, &err, sizeof(err));
_exit(127);
}
close(report[1]);
int err = 0;
ssize_t n;
do n = read(report[0], &err, sizeof(err));
while (n < 0 && errno == EINTR);
close(report[0]);
if (n == (ssize_t)sizeof(err)) {
while (waitpid(child, NULL, 0) < 0 && errno == EINTR) {
}
return err;
}
if (pid) *pid = child;
return 0;
}
int posix_spawn(pid_t *pid, const char *path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp,
@@ -1074,7 +1259,18 @@ int posix_spawn(pid_t *pid, const char *path,
if (bad) return bad;
}
posix_spawnattr_t sanitized;
return ddnatv_posix_spawn(pid, path, file_actions, spawn_attr_for_android(attrp, &sanitized), argv, envp, 0);
const posix_spawnattr_t *attr = spawn_attr_for_android(attrp, &sanitized);
if (ddh_spawn_wanted(path, argv, envp ? envp : environ)) {
int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ);
if (ret != -1) return ret;
}
pid_t child = 0;
int ret = ddnatv_posix_spawn(&child, path, file_actions, attr, argv, envp, 0);
if (ret == 0) {
ddh_child_created(child, 0);
if (pid) *pid = child;
}
return ret;
}
int posix_spawnp(pid_t *pid, const char *file,
File diff suppressed because it is too large. Load diff
+26 -2
View File
@@ -240,22 +240,38 @@ static void clear_dns_redirect(int fd) {
int close(int fd) {
static int (*orig_close)(int) = NULL;
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
uint64_t ticket = kept_close_begin();
// The ARM translator's memory file (privileged.c): left open, as if it were closed
if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0;
if (g_kept_fd_count > 0 && is_kept_fd(fd)) {
kept_close_end(ticket);
return 0;
}
clear_dns_redirect(fd);
set_chosen_port_fd(fd, 0);
forget_proc_root_fd(fd);
return orig_close ? orig_close(fd) : -1;
int r = orig_close ? orig_close(fd) : -1;
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
int dup2(int oldfd, int newfd) {
static int (*orig_dup2)(int, int) = NULL;
if (!orig_dup2) orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
// the bookkeeping's own locks before the pidfd's: its holder waits on nothing else
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
int saved = errno;
ddh_parent_pidfd_unlock(locked);
errno = saved;
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
return ret;
}
@@ -263,11 +279,19 @@ int dup2(int oldfd, int newfd) {
int dup3(int oldfd, int newfd, int flags) {
static int (*orig_dup3)(int, int, int) = NULL;
if (!orig_dup3) orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
// the bookkeeping's own locks before the pidfd's: its holder waits on nothing else
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
int saved = errno;
ddh_parent_pidfd_unlock(locked);
errno = saved;
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
return ret;
}
+160 -8
View File
@@ -10,17 +10,129 @@
// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when
// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code
// themselves have none.
#define DDNATV_MAX_KEPT_FDS 4
#define DDNATV_MAX_KEPT_FDS 12
static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending
static int g_kept_fd_count = 0;
// Of those, the ones also kept from close-on-exec: a worker process's binder fds (hook/handoff.c),
// which must outlive the program's own execs.
static int g_cloexec_kept_fds[8]; // ascending
static int g_cloexec_kept_count = 0;
// The list can change while the program runs (hook/handoff.c keeps and lets go of its own fds): odd
// while a change is under way, which kept_change_begin() and kept_change_end() bracket. Readers take
// a whole copy (kept_snapshot()), so that another thread's close() or close_range() never works
// from a list half moved, which could close a kept fd.
static unsigned g_kept_seq;
static pthread_mutex_t g_kept_lock = PTHREAD_MUTEX_INITIALIZER;
static __thread uint64_t t_kept_mask;
static int kept_snapshot(int *out) {
for (;;) {
unsigned seq = __atomic_load_n(&g_kept_seq, __ATOMIC_ACQUIRE);
if (seq & 1) continue;
int n = __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED);
if (n > DDNATV_MAX_KEPT_FDS) n = DDNATV_MAX_KEPT_FDS;
for (int i = 0; i < n; i++) out[i] = __atomic_load_n(&g_kept_fds[i], __ATOMIC_RELAXED);
__atomic_thread_fence(__ATOMIC_ACQUIRE);
if (__atomic_load_n(&g_kept_seq, __ATOMIC_RELAXED) == seq) return n;
}
}
static void kept_fork_prepare(void) { pthread_mutex_lock(&g_kept_lock); }
static void kept_fork_done(void) { pthread_mutex_unlock(&g_kept_lock); }
static void kept_register_fork(void) { pthread_atfork(kept_fork_prepare, kept_fork_done, kept_fork_done); }
// Every signal blocked meanwhile, so that no handler on this thread reads the list half changed (it
// would wait for the change forever) or changes it too; a fork() waits for the change to end, so a
// child never starts with one under way.
static void kept_change_begin(void) {
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, kept_register_fork);
uint64_t all = ~0ull;
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&t_kept_mask, 8, 0, 0);
pthread_mutex_lock(&g_kept_lock);
__atomic_store_n(&g_kept_seq, g_kept_seq + 1, __ATOMIC_RELAXED);
__atomic_thread_fence(__ATOMIC_RELEASE);
}
static void kept_change_end(void) {
__atomic_store_n(&g_kept_seq, g_kept_seq + 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&g_kept_lock);
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&t_kept_mask, 0, 8, 0, 0);
}
static int is_kept_fd(int fd) {
for (int i = 0; i < g_kept_fd_count; i++) {
if (g_kept_fds[i] == fd) return 1;
int kept[DDNATV_MAX_KEPT_FDS];
int n = kept_snapshot(kept);
for (int i = 0; i < n; i++) {
if (kept[i] == fd) return 1;
}
return 0;
}
// Closes under way (close(), close_range()), counted by the epoch they began in: one that looked at
// the list before a fd was added to it may still close that fd. A thread that makes and keeps a fd
// while others run (hook/handoff.c's table) moves the epoch on afterwards, waits for the closes of
// the one before (kept_settle()), and only then trusts the fd to be its own still.
static unsigned g_close_epoch;
// Per epoch, generation << 32 | count, one word: every change is one compare-and-swap, so a fork from
// a handler that interrupted a close's begin or end never splits one in two. A forked child moves the
// generation on and starts from none (kept_close_forked()): an end whose generation is gone counts
// nothing, and a begin whose swap failed takes the child's.
static uint64_t g_closers[2];
static void kept_close_end(uint64_t ticket);
// The close's ticket: generation << 1 | epoch
static uint64_t kept_close_begin(void) {
for (;;) {
unsigned epoch = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1;
uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST);
if (!__atomic_compare_exchange_n(&g_closers[epoch], &word, word + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
continue;
uint64_t ticket = (word >> 32) << 1 | epoch;
if ((__atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1) == epoch) return ticket;
kept_close_end(ticket); // the epoch moved on meanwhile: counted in the new one instead
}
}
static void kept_close_end(uint64_t ticket) {
unsigned epoch = (unsigned)(ticket & 1);
uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST);
while ((word >> 32) == (ticket >> 1) && (word & 0xffffffffu) != 0 &&
!__atomic_compare_exchange_n(&g_closers[epoch], &word, word - 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
}
}
// In a forked child: the closes the parent's threads were making are not the child's to wait for.
// (The forking thread's own, a close a handler interrupted to fork, then goes uncounted.)
static void kept_close_forked(void) {
for (int epoch = 0; epoch < 2; epoch++) {
uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST);
__atomic_store_n(&g_closers[epoch], ((word >> 32) + 1) << 32, __ATOMIC_SEQ_CST);
}
}
static int kept_drained(unsigned epoch) {
for (int i = 0; i < 1000; i++) {
if ((__atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST) & 0xffffffffu) == 0) return 1;
struct timespec pause = {0, 1000 * 1000};
nanosleep(&pause, NULL);
}
return 0;
}
// 1 once every close that began before now has ended; 0 after a second without (one interrupted by
// a signal whose handler is the caller, say): then nothing it made since can be trusted. The epoch
// moves on only once the closes of the one before it are over too, so the two counts never mix one
// that is still under way from an earlier settle that gave up with the current one.
static int kept_settle(void) {
unsigned current = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1;
if (!kept_drained(current ^ 1)) return 0;
unsigned old = __atomic_fetch_add(&g_close_epoch, 1, __ATOMIC_SEQ_CST) & 1;
return kept_drained(old);
}
// Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending);
// the first nonzero answer of fn is returned, else 0.
static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept,
@@ -438,20 +550,60 @@ int setns(int fd, int nstype) {
#ifndef CLOSE_RANGE_CLOEXEC
#define CLOSE_RANGE_CLOEXEC (1U << 2)
#endif
#ifndef CLOSE_RANGE_UNSHARE
#define CLOSE_RANGE_UNSHARE (1U << 1)
#endif
static int close_range_all(unsigned int first, unsigned int last, int flags);
// Tests only ("IN OUT TID"): before each part it closes, once it has looked at the kept fds, thread
// TID's close_range() writes a byte to OUT and waits for one on IN, as a thread descheduled there
// would.
static void close_range_test_gate(void) {
const char *gate = getenv("DDNATV_TEST_CLOSE_RANGE_GATE");
int in, out, tid;
if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return;
int saved = errno;
char c = 1;
syscall(SYS_write, out, &c, 1);
while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {}
errno = saved;
}
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
close_range_test_gate();
return close_range_all(first, last, *(int *)flags);
}
static int close_range_kept(unsigned int first, unsigned int last, int flags) {
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
if (kept_count == 0) return close_range_part(first, last, &flags);
// The table is unshared once, even when every fd in the range is kept: the system call itself on
// the one number no fd has (close_range_all() would emulate a missing call by closing fds)
if (flags & CLOSE_RANGE_UNSHARE) {
static long (*raw_syscall)(long, ...) = NULL;
if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (!raw_syscall) {
errno = ENOSYS;
return -1;
}
if (raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) != 0) return -1;
flags &= ~CLOSE_RANGE_UNSHARE;
}
return for_each_range_without(first, last, kept, kept_count, close_range_part, &flags);
}
int close_range(unsigned int first, unsigned int last, int flags) {
if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last);
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
if (g_kept_fd_count > 0 && !(flags & CLOSE_RANGE_CLOEXEC)) {
return for_each_range_without(first, last, g_kept_fds, g_kept_fd_count, close_range_part, &flags);
}
return close_range_all(first, last, flags);
uint64_t ticket = kept_close_begin();
int r = close_range_kept(first, last, flags);
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
// glibc's closefrom() makes the close_range system call itself, past the function above
+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>
+51
View File
@@ -0,0 +1,51 @@
#!/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"
sources=()
while IFS= read -r -d '' f; do sources+=("$f"); done < <(find "$here/src" -name '*.java' -print0)
javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" "${sources[@]}" 2>&1 | { grep -v "^warning\|^Note:" || true; }
classes=()
while IFS= read -r -d '' f; do classes+=("$f"); done < <(find "$work/classes" -name '*.class' -print0)
"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" "${classes[@]}"
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"
+24
View File
@@ -0,0 +1,24 @@
// 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 <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
char buf[128] = "";
ssize_t n = -1;
struct pollfd p = {.fd = 3, .events = POLLIN};
if (poll(&p, 1, 500) > 0 && (p.revents & (POLLIN | POLLHUP))) 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;
}
+422
View File
@@ -0,0 +1,422 @@
// Native half of phantomlab: forks sleepers, execs in place, and probes what a process may do.
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#include <android/log.h>
#define TAG "PLAB"
JNIEXPORT jint JNICALL Java_com_droiddeck_phantomlab_Native_spawn(JNIEnv *env, jclass cls, jint n) {
int made = 0;
for (int i = 0; i < n; i++) {
pid_t pid = fork();
if (pid == 0) {
for (;;) pause();
}
if (pid > 0) made++;
}
return made;
}
struct kept_fd {
int fd, flags;
};
static int keep_binder_fds(struct kept_fd *kept, int max) {
DIR *d = opendir("/proc/self/fd");
if (!d) return 0;
int count = 0;
struct dirent *e;
char path[64], target[256];
while ((e = readdir(d)) != NULL && count < max) {
int fd = atoi(e->d_name);
if (fd <= 2) continue;
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len <= 0) continue;
target[len] = 0;
if (strstr(target, "binder")) {
int flags = fcntl(fd, F_GETFD);
if (flags < 0 || fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) != 0) continue;
kept[count].fd = fd;
kept[count].flags = flags;
count++;
__android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target);
}
}
closedir(d);
return count;
}
JNIEXPORT void JNICALL Java_com_droiddeck_phantomlab_Native_execInPlace(JNIEnv *env, jclass cls, jobjectArray jargv, jboolean keep) {
int n = (*env)->GetArrayLength(env, jargv);
char **argv = calloc(n + 1, sizeof(char *));
for (int i = 0; i < n; i++) {
jstring s = (*env)->GetObjectArrayElement(env, jargv, i);
const char *c = (*env)->GetStringUTFChars(env, s, NULL);
argv[i] = strdup(c);
}
struct kept_fd kept[16];
int kept_count = keep ? keep_binder_fds(kept, 16) : 0;
execv(argv[0], argv);
__android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno));
for (int i = 0; i < kept_count; i++) fcntl(kept[i].fd, F_SETFD, kept[i].flags);
}
static char *report;
static size_t report_len, report_cap;
static void out(const char *fmt, ...) {
char line[1024];
va_list ap;
va_start(ap, fmt);
int len = vsnprintf(line, sizeof(line), fmt, ap);
va_end(ap);
if (len < 0) return;
if (len >= (int)sizeof(line)) len = sizeof(line) - 1;
if (report_len + len + 2 > report_cap) {
report_cap = (report_len + len + 2) * 2;
report = realloc(report, report_cap);
}
memcpy(report + report_len, line, len);
report_len += len;
report[report_len++] = '\n';
report[report_len] = 0;
}
static void read_small(const char *path, char *buf, size_t size) {
buf[0] = 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
snprintf(buf, size, "<%s>", strerror(errno));
return;
}
ssize_t n = read(fd, buf, size - 1);
close(fd);
if (n < 0) n = 0;
buf[n] = 0;
for (ssize_t i = 0; i < n; i++) if (buf[i] == '\n' || buf[i] == 0) buf[i] = ' ';
}
#if defined(__aarch64__)
static const unsigned char ret42[] = {0x40, 0x05, 0x80, 0x52, 0xc0, 0x03, 0x5f, 0xd6};
#else
static const unsigned char ret42[] = {0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3};
#endif
static int call_code(void *code) {
__builtin___clear_cache((char *)code, (char *)code + sizeof(ret42));
return ((int (*)(void))code)();
}
static void probe_memfd_exec(void) {
int fd = syscall(SYS_memfd_create, "lab", 0);
if (fd < 0) {
out("memfd_exec: memfd_create %s", strerror(errno));
return;
}
write(fd, ret42, sizeof(ret42));
void *p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) out("memfd_exec: mmap exec %s", strerror(errno));
else out("memfd_exec: ran, returned %d", call_code(p));
close(fd);
}
static void probe_anon_exec(void) {
void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memcpy(p, ret42, sizeof(ret42));
if (mprotect(p, 4096, PROT_READ | PROT_EXEC) != 0) out("anon_exec: mprotect %s", strerror(errno));
else out("anon_exec: ran, returned %d", call_code(p));
}
static int run_child(char *const argv[], int execfd) {
pid_t pid = fork();
if (pid < 0) {
out("fork: %s", strerror(errno));
return -1;
}
if (pid == 0) {
if (execfd >= 0) syscall(SYS_execveat, execfd, "", argv, environ, AT_EMPTY_PATH);
else execv(argv[0], argv);
_exit(100 + errno);
}
int status = 0;
waitpid(pid, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1000 + WTERMSIG(status);
}
static const char *exec_result(int st, const char *ran) {
if (st < 0) return "not run";
return st >= 100 && st < 1000 ? strerror(st - 100) : ran;
}
static int wait_fd(int fd, short events) {
struct pollfd p = {.fd = fd, .events = events};
int r = poll(&p, 1, 2000);
if (r == 0) errno = ETIMEDOUT;
return r > 0 ? 0 : -1;
}
static void probe_tcp(int i, int fd) {
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)};
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
int fl = fcntl(fd, F_GETFL);
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) != 0) {
out("fd%d tcp: fcntl %s", i, strerror(errno));
return;
}
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
if (r != 0 && errno == EINPROGRESS) {
int err = 0;
socklen_t el = sizeof(err);
if (wait_fd(fd, POLLOUT) == 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) == 0) {
r = err ? -1 : 0;
errno = err;
} else {
r = -1;
}
}
if (r != 0) {
out("fd%d tcp: connect %s", i, strerror(errno));
} else {
const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n";
if (wait_fd(fd, POLLOUT) != 0 || write(fd, req, strlen(req)) < 0) {
out("fd%d tcp: connected, write %s", i, strerror(errno));
} else {
char resp[64] = "";
ssize_t n = wait_fd(fd, POLLIN) == 0 ? read(fd, resp, sizeof(resp) - 1) : -1;
if (n > 0) resp[n] = 0;
char *nl = strchr(resp, '\r');
if (nl) *nl = 0;
out("fd%d tcp: connected, got \"%s\"", i, n > 0 ? resp : strerror(errno));
}
}
fcntl(fd, F_SETFL, fl);
}
static void probe_exec(void) {
char *argv[] = {"/system/bin/true", NULL};
int st = run_child(argv, -1);
out("execve /system/bin/true: %s", exec_result(st, st == 0 ? "ok" : "status"));
int src = open("/system/bin/toybox", O_RDONLY);
int mfd = syscall(SYS_memfd_create, "toybox", 0);
char buf[65536];
ssize_t n;
while (src >= 0 && (n = read(src, buf, sizeof(buf))) > 0) write(mfd, buf, n);
if (src >= 0) close(src);
char *targv[] = {"true", NULL};
st = run_child(targv, mfd);
out("execveat memfd(toybox true): %s", exec_result(st, st == 0 ? "ok" : "status"));
close(mfd);
}
static void probe_fd(int i, int fd) {
struct stat st;
if (fstat(fd, &st) != 0) {
out("fd%d: fstat %s", i, strerror(errno));
return;
}
char target[256] = "";
char path[64];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len > 0) target[len] = 0;
if (S_ISSOCK(st.st_mode)) {
int type = 0, family = 0;
socklen_t sl = sizeof(type);
getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &sl);
struct sockaddr_storage ss;
socklen_t al = sizeof(ss);
getsockname(fd, (struct sockaddr *)&ss, &al);
family = ss.ss_family;
if (family == AF_INET && type == SOCK_STREAM) {
probe_tcp(i, fd);
} else if (family == AF_INET && type == SOCK_DGRAM) {
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(53)};
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
out("fd%d udp: connect %s", i, r == 0 ? "ok" : strerror(errno));
} else {
char buf[64] = "";
ssize_t r = wait_fd(fd, POLLIN) == 0 ? read(fd, buf, sizeof(buf) - 1) : -1;
if (r > 0) buf[r - 1] = 0;
out("fd%d unix(family %d): read %s", i, family, r > 0 ? buf : strerror(errno));
}
return;
}
if (S_ISDIR(st.st_mode)) {
int f = openat(fd, "probe.txt", O_RDONLY);
out("fd%d dir %s: openat child %s", i, target, f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
return;
}
char buf[64] = "";
ssize_t r = pread(fd, buf, sizeof(buf) - 1, 0);
if (r > 0) buf[r - 1] = 0;
out("fd%d file %s: read %s", i, target, r >= 0 ? buf : strerror(errno));
void *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
out("fd%d mmap read: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
if (p != MAP_FAILED) munmap(p, 4096);
p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
out("fd%d mmap exec: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
if (p != MAP_FAILED) munmap(p, 4096);
char *argv[] = {"x", NULL};
int st2 = run_child(argv, fd);
out("fd%d execveat: %s", i, exec_result(st2, "ran"));
}
static void probe_self(void) {
char buf[512];
out("uid=%d gid=%d pid=%d ppid=%d", getuid(), getgid(), getpid(), getppid());
read_small("/proc/self/attr/current", buf, sizeof(buf));
out("selinux: %s", buf);
read_small("/proc/self/cgroup", buf, sizeof(buf));
out("cgroup: %s", buf);
int s = socket(AF_INET, SOCK_STREAM, 0);
out("socket(AF_INET): %s", s >= 0 ? "ok" : strerror(errno));
if (s >= 0) close(s);
s = socket(AF_UNIX, SOCK_STREAM, 0);
out("socket(AF_UNIX): %s", s >= 0 ? "ok" : strerror(errno));
if (s >= 0) close(s);
int f = open("/data/data/com.droiddeck.phantomlab/files/probe.txt", O_RDONLY);
out("open app data by path: %s", f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
const char *gpus[] = {"/dev/kgsl-3d0", "/dev/mali0", "/dev/dri/renderD128", NULL};
for (int i = 0; gpus[i]; i++) {
if (access(gpus[i], F_OK) != 0) continue;
f = open(gpus[i], O_RDWR);
out("open %s: %s", gpus[i], f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
}
}
static void probe_pid(const char *spec) {
int pid = atoi(spec);
char path[64], buf[256];
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
read_small(path, buf, sizeof(buf));
out("read /proc/%d/cmdline: %s", pid, buf);
out("kill(%d, 0): %s", pid, kill(pid, 0) == 0 ? "ok" : strerror(errno));
out("kill(%d, SIGCONT): %s", pid, kill(pid, SIGCONT) == 0 ? "ok" : strerror(errno));
}
static void try_write(const char *path, const char *value) {
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) {
out("write %s: open %s", path, strerror(errno));
return;
}
ssize_t n = write(fd, value, strlen(value));
out("write %s: %s", path, n >= 0 ? "ok" : strerror(errno));
close(fd);
}
// Every way a process could leave the cgroup Android counts it in.
static void probe_escape(void) {
char own[256], pid[32], path[300];
read_small("/proc/self/cgroup", own, sizeof(own));
char *v2 = strstr(own, "0::");
char dir[200] = "";
if (v2) sscanf(v2 + 3, "%199s", dir);
snprintf(pid, sizeof(pid), "%d", getpid());
try_write("/sys/fs/cgroup/cgroup.procs", pid);
char parent[200];
snprintf(parent, sizeof(parent), "%s", dir);
char *slash = strrchr(parent, '/');
if (slash) *slash = 0;
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/cgroup.procs", parent);
try_write(path, pid);
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/lab", dir);
out("mkdir %s: %s", path, mkdir(path, 0755) == 0 ? "ok" : strerror(errno));
int r = syscall(SYS_unshare, 0x10000000 /* CLONE_NEWUSER */);
out("unshare(CLONE_NEWUSER): %s", r == 0 ? "ok" : strerror(errno));
r = syscall(SYS_unshare, 0x02000000 /* CLONE_NEWCGROUP */);
out("unshare(CLONE_NEWCGROUP): %s", r == 0 ? "ok" : strerror(errno));
int cg = open("/sys/fs/cgroup", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (cg < 0) {
out("open /sys/fs/cgroup: %s", strerror(errno));
} else {
struct {
unsigned long long flags, pidfd, child_tid, parent_tid, exit_signal, stack, stack_size, tls, set_tid,
set_tid_size, cgroup;
} args = {.flags = 0x200000000ULL /* CLONE_INTO_CGROUP */, .exit_signal = SIGCHLD, .cgroup = (unsigned)cg};
long child = syscall(435 /* clone3 */, &args, sizeof(args));
if (child == 0) _exit(0);
if (child > 0) waitpid(child, NULL, 0);
out("clone3(CLONE_INTO_CGROUP, root): %s", child > 0 ? "ok" : strerror(errno));
close(cg);
}
}
// Runs path with fd as its fd 3 and its stderr captured.
static void probe_libexec(const char *path, int fd) {
int pipefd[2];
if (pipe(pipefd) != 0) {
out("exec %s: pipe %s", path, strerror(errno));
return;
}
pid_t pid = fork();
if (pid < 0) {
out("exec %s: fork %s", path, strerror(errno));
close(pipefd[0]);
close(pipefd[1]);
return;
}
if (pid == 0) {
dup2(pipefd[1], 2);
if (fd >= 0) dup2(fd, 3);
char *argv[] = {(char *)path, NULL};
execv(path, argv);
dprintf(2, "execv: %s", strerror(errno));
_exit(127);
}
close(pipefd[1]);
char buf[512] = "";
ssize_t n = read(pipefd[0], buf, sizeof(buf) - 1);
if (n > 0) buf[n] = 0;
char *nl = strchr(buf, '\n');
if (nl) *nl = 0;
close(pipefd[0]);
int status = 0;
waitpid(pid, &status, 0);
out("exec %s: status %d, said \"%s\"", path, WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status), buf);
}
JNIEXPORT jstring JNICALL Java_com_droiddeck_phantomlab_Native_probe(JNIEnv *env, jclass cls, jstring jwhat, jintArray jfds) {
report_len = 0;
if (report) report[0] = 0;
const char *what = jwhat ? (*env)->GetStringUTFChars(env, jwhat, NULL) : "self";
int n = (*env)->GetArrayLength(env, jfds);
jint *fds = (*env)->GetIntArrayElements(env, jfds, NULL);
char spec[1024];
snprintf(spec, sizeof(spec), "%s", what);
char *save = NULL;
for (char *tok = strtok_r(spec, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
if (!strcmp(tok, "self")) probe_self();
else if (!strcmp(tok, "memfd_exec")) probe_memfd_exec();
else if (!strcmp(tok, "anon_exec")) probe_anon_exec();
else if (!strcmp(tok, "exec")) probe_exec();
else if (!strcmp(tok, "fds")) for (int i = 0; i < n; i++) probe_fd(i, fds[i]);
else if (!strncmp(tok, "pid=", 4)) probe_pid(tok + 4);
else if (!strcmp(tok, "escape")) probe_escape();
else if (!strncmp(tok, "libexec=", 8)) probe_libexec(tok + 8, n > 0 ? fds[0] : -1);
}
(*env)->ReleaseIntArrayElements(env, jfds, fds, 0);
return (*env)->NewStringUTF(env, report ? report : "");
}
@@ -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,91 @@
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;
import java.io.IOException;
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");
ParcelFileDescriptor[] pfds = readFds(data);
try {
int[] fds = new int[pfds.length];
for (int i = 0; i < fds.length; i++) fds[i] = pfds[i] == null ? -1 : pfds[i].getFd();
reply.writeString(Native.probe(what, fds));
} finally {
closeAll(pfds);
}
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 ParcelFileDescriptor[] readFds(Parcel data) {
ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[data.readInt()];
try {
for (int i = 0; i < pfds.length; i++) pfds[i] = data.readFileDescriptor();
} catch (RuntimeException e) {
closeAll(pfds);
throw e;
}
return pfds;
}
private static void closeAll(ParcelFileDescriptor[] pfds) {
for (ParcelFileDescriptor pfd : pfds) {
if (pfd == null) continue;
try {
pfd.close();
} catch (IOException e) {
Log.w(Main.TAG, "close fd failed " + e);
}
}
}
@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,333 @@
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.os.RemoteException;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.util.Log;
import android.widget.TextView;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 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<Task>> pending = new HashMap<>();
private static final Map<String, ServiceConnection> connections = new HashMap<>();
private static final ExecutorService worker = Executors.newSingleThreadExecutor();
private TextView text;
private interface Op {
void run(IBinder binder) throws Exception;
}
private final class Task {
final String target;
final String name;
final Op op;
final Closeable owned;
Task(String target, String name, Op op, Closeable owned) {
this.target = target;
this.name = name;
this.op = op;
this.owned = owned;
}
void run(IBinder binder) {
worker.execute(() -> {
try {
op.run(binder);
} catch (Exception e) {
log(target + " " + name + " failed " + e);
} finally {
release();
}
});
}
void cancel() {
log(target + " " + name + " cancelled");
release();
}
private void release() {
if (owned == null) return;
try {
owned.close();
} catch (IOException e) {
log(target + " " + name + " close failed " + e);
}
}
}
private static final class ProbeFds implements Closeable {
final List<ParcelFileDescriptor> sent = new ArrayList<>();
final List<FileDescriptor> owned = new ArrayList<>();
@Override
public void close() throws IOException {
IOException failure = null;
for (ParcelFileDescriptor p : sent) {
try {
p.close();
} catch (IOException e) {
failure = e;
}
}
for (FileDescriptor fd : owned) {
try {
Os.close(fd);
} catch (ErrnoException e) {
failure = new IOException(e);
}
}
sent.clear();
owned.clear();
if (failure != null) throw failure;
}
}
@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);
runOnUiThread(() -> 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, String name, Op op, Closeable owned) {
Task task = new Task(target, name, op, owned);
IBinder binder = binders.get(target);
if (binder != null) {
task.run(binder);
return;
}
List<Task> q = pending.get(target);
if (q == null) {
q = new ArrayList<>();
pending.put(target, q);
}
q.add(task);
if (!connections.containsKey(target)) bind(target);
}
private void bind(String target) {
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
log("connected " + target);
binders.put(target, service);
List<Task> ops = pending.remove(target);
if (ops != null) for (Task t : ops) t.run(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
log("DISCONNECTED " + target);
binders.remove(target);
}
@Override
public void onBindingDied(ComponentName name) {
log("BINDING DIED " + target);
if (connections.get(target) != this) return;
List<Task> ops = pending.remove(target);
unbind(target);
if (ops != null) {
pending.put(target, ops);
bind(target);
}
}
};
connections.put(target, conn);
boolean ok = false;
try {
Intent intent = new Intent(this, serviceClass(target));
int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT;
if (target.contains(":")) {
ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn);
} else {
ok = getApplicationContext().bindService(intent, conn, flags);
}
} finally {
log("bind " + target + " -> " + ok);
if (!ok) unbind(target);
}
}
private void unbind(String target) {
ServiceConnection c = connections.remove(target);
binders.remove(target);
List<Task> q = pending.remove(target);
if (q != null) for (Task t : q) t.cancel();
if (c == null) return;
try {
getApplicationContext().unbindService(c);
} catch (IllegalArgumentException e) {
log("unbind " + target + " " + e);
}
}
private static Parcel call(IBinder binder, int code, Parcel data) throws RemoteException {
Parcel reply = Parcel.obtain();
binder.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, "spawn", b -> {
Parcel d = Parcel.obtain();
d.writeInt(n);
log(target + " spawned " + call(b, LabService.SPAWN, d).readInt());
}, null);
return;
}
case "who":
withBinder(target, "who", b -> log(target + " " + call(b, LabService.WHO, Parcel.obtain()).readString()), null);
return;
case "exec": {
String[] argv = intent.getStringExtra("argv").split("\\|");
boolean keepBinder = intent.getIntExtra("keep", 1) != 0;
withBinder(target, "exec", b -> {
Parcel d = Parcel.obtain();
d.writeStringArray(argv);
d.writeInt(keepBinder ? 1 : 0);
log(target + " exec in pid " + call(b, LabService.EXEC, d).readInt());
}, null);
return;
}
case "probe": {
String what = intent.getStringExtra("what");
ProbeFds fds = probeFds(intent.getStringExtra("fds"));
withBinder(target, "probe", b -> {
Parcel d = Parcel.obtain();
d.writeString(what);
d.writeInt(fds.sent.size());
for (ParcelFileDescriptor p : fds.sent) d.writeFileDescriptor(p.getFileDescriptor());
for (String line : call(b, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line);
}, fds);
return;
}
case "unbind": {
unbind(target);
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 ProbeFds probeFds(String spec) throws Exception {
ProbeFds fds = new ProbeFds();
if (spec == null || spec.isEmpty()) return fds;
try {
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);
fds.owned.add(fd);
fds.sent.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);
fds.owned.add(a);
fds.owned.add(b);
Os.write(a, "hello from main\n".getBytes(), 0, 16);
fds.sent.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());
}
}
fds.sent.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE));
} else if (s.startsWith("path:")) {
fds.sent.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY));
} else if (s.equals("dir")) {
fds.sent.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY));
}
}
} catch (Exception e) {
try {
fds.close();
} catch (IOException ignored) {
}
throw e;
}
return fds;
}
}
@@ -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 {}
-47
View File
@@ -144,53 +144,6 @@ class LaunchLog(unittest.TestCase):
self.assertIn('DXVK_LOG_PATH=${DXVK_LOG_PATH:-$COMPAT}', text)
class PrefixFromProton(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.compat = Path(self.tmp.name) / 'compatdata/236850'
self.drives = self.compat / 'pfx/dosdevices'
self.drives.mkdir(parents=True)
def test_guest_drive_links_get_android_paths(self):
for name, target in (('c:', '../drive_c'), ('s:', '/root/.local/share/Steam'), ('d:', '/mnt/sd/Steam'),
('e:', '/storage/emulated/0/Games'), ('z:', '/')):
os.symlink(target, self.drives / name)
out = proton_function('android_drives "$1"', str(self.compat))
links = {p.name: os.readlink(p) for p in self.drives.iterdir()}
self.assertEqual({'c:': '../drive_c', 's:': ANDROID + '/root/.local/share/Steam', 'd:': '/storage/1234-5678/Steam/Steam',
'e:': '/storage/emulated/0/Games', 'z:': '/'}, links)
self.assertEqual(2, len(out.splitlines()))
self.assertEqual('', proton_function('android_drives "$1"', str(self.compat)))
def test_a_prefix_without_drives_is_left_alone(self):
self.assertEqual('', proton_function('android_drives "$1"', str(Path(self.tmp.name) / 'compatdata/1')))
def steam_pid(self, reg):
text = LAUNCH.read_text()
function = text[text.index('steam_pid() {'):text.index('prefix_busy || steam_pid')]
(self.compat / 'pfx/user.reg').write_text(reg)
out = subprocess.run(['sh', '-c', function + 'steam_pid'], env=dict(os.environ, COMPAT=str(self.compat)),
capture_output=True, text=True, check=True).stdout
return out, (self.compat / 'pfx/user.reg').read_text()
def test_steams_process_id_is_this_tools(self):
reg = ('[Software\\\\Valve\\\\Steam\\\\ActiveProcess] 1795314478\n#time=1dd7a2916a0be94\n"PID"=dword:00000020\n'
'"SteamPath"="C:\\\\Program Files (x86)\\\\Steam"\n\n[Software\\\\Other] 1\n"PID"=dword:00000020\n')
out, after = self.steam_pid(reg)
self.assertIn('process ID', out)
self.assertEqual(reg.replace('"PID"=dword:00000020', '"PID"=dword:0000fffe', 1), after)
out, again = self.steam_pid(after)
self.assertEqual(('', after), (out, again))
def test_a_prefix_without_steams_key_is_unchanged(self):
reg = '[Software\\\\Wine] 1\n"PID"=dword:00000020\n'
self.assertEqual(('', reg), self.steam_pid(reg))
def test_the_network_list_uses_getifaddrs(self):
self.assertIn('export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}', LAUNCH.read_text())
class StorePaths(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
+9
View File
@@ -247,6 +247,15 @@ class AgentTest(unittest.TestCase):
{"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}]
self.assertEqual(self.tag(wins), (False, []))
def test_a_proton_window_run_in_a_worker_takes_its_process_app_id(self):
# a store game's Wine process handed to a worker: its parent is zygote, not the reaper
self.fake_proc(50, 1, "SplinterCell.exe", {"SteamAppId": "2565121641", "SteamGameId": "11017113558390407168"})
self.fake_proc(20, 1, "reaper", {})
self.fake_proc(21, 20, "Bully.exe", {"SteamAppId": "12200"})
wins = [{"window": 14, "map": "viewable", "class": "steam_app_2565121641", "pid": 50},
{"window": 15, "map": "viewable", "class": "steam_app_12200", "pid": 21}]
self.assertEqual(self.tag(wins), (True, ["2565121641"]))
def test_the_x86_client_still_tags_its_game_classes(self):
win = {"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}
self.assertEqual(self.tag([win], arch="x86_64"), (True, ["550"]))
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -34,7 +34,10 @@ class SessionBusTest(unittest.TestCase):
match = re.search(r'^ *if \[ -z "\$\{DBUS_SESSION_BUS_ADDRESS:-\}" \]; then\n.*?^ *fi\n *fi\n',
SESSION.read_text(), re.M | re.S)
self.assertIsNotNone(match)
script = "nap() { sleep \"$1\"; }\n" + match.group(0) + 'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill %1 2>/dev/null\n'
spawn = re.search(r'^dd_spawn\(\) \{\n.*?^\}\n', SESSION.read_text(), re.M | re.S)
self.assertIsNotNone(spawn)
script = ("nap() { sleep \"$1\"; }\n" + spawn.group(0) + match.group(0) +
'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill $dd_spawned 2>/dev/null\n')
env = {"PATH": "%s:/usr/bin:/bin" % self.bin, "XDG_RUNTIME_DIR": str(self.runtime)}
if env_address:
env["DBUS_SESSION_BUS_ADDRESS"] = env_address