From 5cd6fe8864948b215cfe7b9724e1d0e7075db47a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:02:55 -0500 Subject: [PATCH] feat(session): run the session outside Android's child-process count (#3338) * docs: research Android's child-process limit without developer options * docs: confirm the child-process gaps on the Thor * feat(session): start long-lived daemons in uncounted worker processes * feat(nativeguest): hand long-lived programs to uncounted worker processes * test(session): run the session bus block with dd_spawn * test(nativeguest): cover the exec handoff's wait and kill * feat(session): run the session root, its jobs and the gamescope chain outside the child-process count * feat(setup): the child-process limit no longer blocks Steam while the session runs in workers * feat(audio): run PulseAudio outside the child-process count * feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive * fix(nativeguest): let Steam end a handed-off game and keep process-group signals * perf(session): exec a worker as soon as its reply is in and keep two bound ahead; fix review findings * fix(nativeguest): address review findings in handoff waits, signals and spawn errors * fix(session): commit each worker launch explicitly and keep workers with the session that asked * fix(session): let a worker wait for its launch commit on the main thread * fix(session): confirm handoffs, honour wait selectors and stop spawns at teardown * fix(session): one owner per handoff exit, worker launch answers and spawn edge cases * fix(session): send a working directory outside the program's root by its real path * fix(session): recheck a taken exit's child and commit a launch only on a whole go line * fix(session): three-step launch, tagged exit reports and lock-free popen and system children * test(native): popen test shell is static, as the other hook fixtures * test(native): run the popen test program with a clean environment * test(native): skip the popen test where a spawn child cannot exec aarch64 * fix(session): confirm the hook before the worker runs, prefer a late report and free a reused pid * fix(session): tell a reused pid's old entry by start time, not the reaped flag * fix(session): silent failed launches, bounded spawn requests and held check-gone writes * test(native): check the unlisted child's status only where a child can exec aarch64 * fix(session): every exit-only waitid goes through the handoff wait * fix(handoff): exact waitid events, safe exit timer, bounded request receipt * feat(handoff): hand off shell children near Android's process limit * fix(agent): tag handed-off game windows outside the reaper * fix(handoff): a handed-off program's getppid() is its forking process * fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports * fix(handoff): getppid() gives init for an exited or replaced parent * fix(handoff): keep __WALL waitid calls on the handoff path * test(handoff): require a zombie parent in the unreaped-parent case * fix(handoff): honor __WNOTHREAD and check every argument for Steam * fix(handoff): stop waiting on a held entry once its parent has exited * fix(handoff): __WNOTHREAD on waits for a pid, flags on every shim reap * fix(handoff): keep the forking thread of each child in the parent * fix(handoff): a wait that finds no child rechecks live handoffs * fix(handoff): keep a child's forking thread until its end is taken * fix(handoff): the thread selector applies to claims in progress too * fix(handoff): controlling-terminal check via /dev/tty, owned records only * fix(handoff): a child whose forking thread ended is any thread's * fix(handoff): a parent /proc cannot read is checked with kill(), then given up * fix(handoff): one-word fork records, changed only by compare-and-swap * fix(handoff): watch the forking parent through a pidfd opened at start * fix(handoff): fork records by pid, a gone thread's children go to the main one * fix(handoff): keep the parent pidfd through dup2 and check it before use * fix(handoff): no handoff without fork records, unknown thread state keeps the owner * fix(handoff): undo a pidfd move when dup fails, recheck it after the poll * fix(handoff): fresh fork records in a forked child, heir is the first live thread * fix(handoff): one lock over a pidfd move, its dup and the undo * fix(handoff): liveness check under the pidfd lock, forget only a reaped pid's record * fix(handoff): lock only dups onto the pidfd, with signals blocked * fix(handoff): fork record generations, no pidfd restore after a failed move * fix(handoff): every dup in a pidfd process locks, fork prep blocks signals * test(semaphores): tell a child hung in qemu-user from a guest deadlock * fix(handoff): fork records matched by the child's start time, never removed * test(semaphores): count only reaped children, only futex waits as emulator stalls * fix(handoff): a known-start bit in fork records * fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept * fix(handoff): a fork record stays only for the pid's current process * fix(handoff): keep a pending child's fork record when an older fork records late * fix(handoff): an unknown-start fork record never replaces a pending one * fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits * test(handoff): find the module in the namespace run under discover too * fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd * test(handoff): require ENOEXEC for an ELF stub; skip the namespace run without binfmt * fix(hook): change the kept fd list under a sequence lock; readers take a copy * fix(handoff): one report per handed-off child; stops keep a claim; nested waits keep their selector * fix(hook): a table made at runtime outlives closes begun before it; unknown-start fork records kept * fix(handoff): waits look before they reap, so a handed-off fork's child is never reported * fix(hook): settle waits out earlier epochs; unknown-start fork records kept for any handoff under way * fix(handoff): generation-checked reap marks, stops taken as stops, close counts reset in a fork * fix(handoff): one given-up table at most, whole stop codes and rusage, WNOWAIT exits rechecked * fix(handoff): requests name their session; stops of handed-off programs reported; cancellable look * fix(handoff): table setup not cancellable; test spawner never runs what it cannot end * fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup * docs(phantom): job-control jobs stay counted; listed programs report no stops * fix(handoff): a listed program a shell runs as a job-control job stays counted * refactor(hook): kept descriptors in their own part, a handoff matched by another program The descriptors close(), close_range() and closefrom() leave open move from privileged.c to hook/kept.c (unchanged), so the bionic runtime's exec shim can build the handoff with them. ddh_try_as() matches DD_HANDOFF against one program and sends another: the bionic shim sends "/system/bin/linker64 PROGRAM ARGS" and lists it by PROGRAM. ddh_try() is ddh_try_as() with both the same. * feat(bionic): hand the bionic runtime's Wine programs to the app's workers The glibc session's hook never sees DroidDeck-Bionic's processes (Wine on Android's libc), so a bionic game's Wine programs all stayed counted under the worker running the tool's launch.sh. The handoff is now built into the runtime's exec shim (tools/bionic-runtime/handoff.c, part of libexecshim.so): - hook/handoff.c and hook/kept.c with what the native hook's other parts do around them: fork(), close(), close_range(), dup2(), dup3(), and exit() for the on_exit() bionic lacks - bionic's execv(), execvp(), execl*() reach the execve system call inside libc, past execshim's execve(); Wine starts its preloader with execv(), so the shim defines them on top of its execve() - a linker64 start is listed by its program - the app starts a handed-off program from the glibc root's bash, which cannot load the runtime's LD_PRELOAD/LD_LIBRARY_PATH: they go as arguments of /system/bin/env, which puts them back for the program - launch.sh keeps DD_SPAWN, DD_SPAWN_SESSION, DD_HANDOFF*, DDH_* and DDNATV_ROOT, and its /proc/N/environ reads no longer print "Permission denied" for idle workers (2>/dev/null before the redirect) Pocket FIT, DroidDeck-Bionic 14.1-r67 with this shim and launcher, handoff on: counted during Brawlhalla 25 -> 17, DiRT Showdown 24-27 -> 16, whole run 28 -> 19-20; with Android's limit on no DroidDeck process and no other app's process was killed (before: Discord, BatteryLog helpers); DiRT 75 fps either way. docs/phantom-processes.md: "The bionic runtime". * fix(bionic): hand off only starts that would succeed here; bionic's execvp fallbacks Review follow-ups on the bionic runtime's handoff (tools/bionic-runtime/handoff.c): - A start is handed to a worker only when it would get past execve() in this process: the file is a regular executable outside the app's data (Android refuses execve() there), and for a linker64 start the program it loads is a readable regular file. A start that failed in the worker failed where the caller could not see it, so Wine never tried its next candidate. The hook's own check looked at /system/bin/env, not the program. - A start whose argv[0] is not its file stays here: env starts FILE with FILE as argv[0]. linker64 and interpreter starts are unaffected (their argv[0] is the file). An empty argv stays here too. - Nothing is built for the handoff without DD_SPAWN and DD_HANDOFF. - execvp()/execvpe()/execlp() follow bionic's: an unset PATH is libc's default, an empty PATH or entry is the current directory, and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh. - close_range() refuses first > last and unknown flags before it splits the range or unshares the table. - The debug line reads the table's owner only once the table is seen published. * fix(bionic): hand off app-data starts only where SELinux lets them run; bare names stay here Follow-up to 7d95564f7 (review, and a Pocket FIT test of its pack): - 7d95564f7 kept every start of a file in the app's data here. Wine's preloader is one (a static ELF, so execshim.c cannot make it a linker64 start), and where SELinux is permissive, as on AYANEO's firmware, it runs: Wine then never reached its loader, and its programs ran here, counted again (Pocket FIT: Brawlhalla 26-28 counted vs 16-17 before). Where SELinux enforces, Android refuses the exec, here and in a worker alike, and Wine falls back to its loader, which goes as a linker64 start. Such a start is now handed off when /sys/fs/selinux/enforce reads 0, and stays here otherwise (also when the setting cannot be read). - The program a start would run is checked with the hook's own ddh_startable() (an ELF the kernel loads with its interpreter there, or a script with its interpreter): for a linker64 start, the program it loads. - A file name without '/' stays here: env would look it up in PATH, the exec here in the caller's working directory. - execvpe() skips a PATH entry whose candidate exceeds PATH_MAX (ENAMETOOLONG) instead of copying it onto the stack. * fix(handoff): spawn blocks signals and cancellation across the fork; root flag stored under the stop lock * fix(handoff): a thread that unshares its fd table keeps its own copy of the kept fds * fix(handoff): register the kept list's fork handlers before a split takes its lock * test(handoff): cover WNOHANG with a held forked child, early reaps, blocked waitid and pidfd parents; keep the counted-process exception in translations * test(handoff): exited-entry precondition, atomic checkpoints, a pidfd-only zombie check; validate the shim hold fd * test(handoff): WNOHANG with two handed-off children and for a group; a program's exit while its entry is held * test(handoff): a held exit with no free fd, with and without the parent's pidfd * test(handoff): held-exit tests require the program's own exit status * test(handoff): time held exits from the run, and only once the program is at its exit * perf(handoff): keep the asker's priority, quick tools local, workers bound ahead of a game (#3582) Three fixes that bring handoff-on speed to within 1-2 % of handoff off (AIO D3D11 same session: 3196 -> 3520 fps, 1 % low 444 -> 637) with the same counted processes (benchmark mean 18.5, peak 23): - A handed-off program keeps its asker's priority. Workers are bound from the top app with BIND_IMPORTANT, so Android boosts their main thread to THREAD_PRIORITY_TOP_APP_BOOST (-10); the program the worker execs inherited it. The asker's nice value is sent with the request and set before execve, and a watcher resets it if Android boosts it again. - Quick script tools (awk, sed, grep, cat, ...) stay where they are when the count is near the limit. Sent to a worker, the forked child waits (counted) while a worker starts; run locally it is counted for a few ms. - Workers are bound ahead when a Steam game is queued (16 for 20 s), so Wine's services do not wait on zygote forks at game start. --------- Co-authored-by: The412Banner Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com> --- app/src/main/AndroidManifest.xml | 64 + .../main/java/com/droiddeck/launcher/App.kt | 4 + .../audio/DirectAudioRelayComponent.java | 2 +- .../launcher/audio/PulseAudioComponent.java | 5 +- .../droiddeck/launcher/core/HostProcess.kt | 75 + .../launcher/core/PhantomProcessLimit.kt | 14 +- .../launcher/core/SessionLogCapture.kt | 17 +- .../launcher/runtime/GuestWorkers.kt | 894 ++++++ .../launcher/session/SessionFiles.kt | 2 + .../launcher/session/SessionPrefs.kt | 3 + .../launcher/session/SessionService.kt | 48 +- .../droiddeck/launcher/ui/FrontEndSetup.kt | 3 +- app/src/main/res/values-ar/strings.xml | 2 + app/src/main/res/values-b+es+419/strings.xml | 2 + app/src/main/res/values-bg/strings.xml | 2 + app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-da/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-el/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fi/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-hi/strings.xml | 2 + app/src/main/res/values-hu/strings.xml | 2 + app/src/main/res/values-in/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-ja/strings.xml | 2 + app/src/main/res/values-ko/strings.xml | 2 + app/src/main/res/values-ms/strings.xml | 2 + app/src/main/res/values-nb/strings.xml | 2 + app/src/main/res/values-nl/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-pt-rPT/strings.xml | 2 + app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ro/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 2 + app/src/main/res/values-sv/strings.xml | 2 + app/src/main/res/values-th/strings.xml | 2 + app/src/main/res/values-tr/strings.xml | 2 + app/src/main/res/values-uk/strings.xml | 2 + app/src/main/res/values-vi/strings.xml | 2 + app/src/main/res/values-zh-rCN/strings.xml | 2 + app/src/main/res/values-zh-rHK/strings.xml | 2 + app/src/main/res/values-zh-rTW/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../launcher/core/PhantomProcessLimitTest.kt | 6 + docs/phantom-processes.md | 569 ++++ tools/bionic-runtime/build.sh | 2 +- tools/bionic-runtime/execshim.c | 5 + tools/bionic-runtime/handoff.c | 415 +++ tools/bionic-runtime/tool/launch.sh | 12 +- .../overlay/usr/local/bin/droiddeck-agent | 6 +- .../usr/local/bin/droiddeck-log-writer | 8 + .../overlay/usr/local/bin/droiddeck-session | 104 +- .../overlay/usr/local/bin/droiddeck-spawn | 103 + tools/nativeguest/ddnatv-hook.c | 2 + tools/nativeguest/hook/exec.c | 233 +- tools/nativeguest/hook/handoff.c | 2587 +++++++++++++++++ tools/nativeguest/hook/kept.c | 225 ++ tools/nativeguest/hook/net.c | 28 +- tools/nativeguest/hook/privileged.c | 92 +- tools/phantomlab/.gitignore | 1 + tools/phantomlab/AndroidManifest.xml | 36 + tools/phantomlab/build.sh | 51 + tools/phantomlab/jni/exe.c | 24 + tools/phantomlab/jni/lab.c | 422 +++ .../src/com/droiddeck/phantomlab/Iso.java | 3 + .../com/droiddeck/phantomlab/IsoPlain.java | 3 + .../com/droiddeck/phantomlab/LabService.java | 91 + .../src/com/droiddeck/phantomlab/Main.java | 333 +++ .../src/com/droiddeck/phantomlab/Native.java | 16 + .../src/com/droiddeck/phantomlab/Preload.java | 10 + .../src/com/droiddeck/phantomlab/Proc.java | 3 + .../src/com/droiddeck/phantomlab/W0.java | 3 + .../src/com/droiddeck/phantomlab/W1.java | 3 + .../src/com/droiddeck/phantomlab/W2.java | 3 + .../src/com/droiddeck/phantomlab/W3.java | 3 + .../src/com/droiddeck/phantomlab/W4.java | 3 + .../src/com/droiddeck/phantomlab/W5.java | 3 + .../src/com/droiddeck/phantomlab/W6.java | 3 + .../src/com/droiddeck/phantomlab/W7.java | 3 + tools/tests/test_droiddeck_agent.py | 9 + tools/tests/test_native_hook_handoff.py | 2285 +++++++++++++++ tools/tests/test_session_bus.py | 5 +- 84 files changed, 8823 insertions(+), 87 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt create mode 100644 docs/phantom-processes.md create mode 100644 tools/bionic-runtime/handoff.c create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn create mode 100644 tools/nativeguest/hook/handoff.c create mode 100644 tools/nativeguest/hook/kept.c create mode 100644 tools/phantomlab/.gitignore create mode 100644 tools/phantomlab/AndroidManifest.xml create mode 100644 tools/phantomlab/build.sh create mode 100644 tools/phantomlab/jni/exe.c create mode 100644 tools/phantomlab/jni/lab.c create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/Main.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/Native.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W0.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W1.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W2.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W3.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W4.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W5.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W6.java create mode 100644 tools/phantomlab/src/com/droiddeck/phantomlab/W7.java create mode 100644 tools/tests/test_native_hook_handoff.py diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 566226306e..6ec55c4825 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -417,5 +417,69 @@ android:name="backend:com.google.android.datatransport.cct.CctBackendFactory" tools:node="remove" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 53a0c89298..f91157dd41 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -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() diff --git a/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java index 8d9ddcb1f0..f87aefaa14 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java @@ -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); diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 53a0a6aacf..1ff48a77cd 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -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); diff --git a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt index d4a2cdc66d..d3a03036a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt @@ -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?, dir: File?, onExit: Consumer?, onLine: Consumer?, + 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") diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt index 6e67ff495d..5bcc716d1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -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)" } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt index 650a6b8d4d..42524b5dcb 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt @@ -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() diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt new file mode 100644 index 0000000000..d0435876b7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -0,0 +1,894 @@ +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() + val nice = data.readInt() + 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, nice) + 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, env: Array, fds: List, targets: IntArray, fillBinderFd: Boolean, + nice: Int) { + 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") + // Android raised this thread to THREAD_PRIORITY_TOP_APP_BOOST (a service the top app binds with + // BIND_IMPORTANT is scheduled as the top app); the program and its threads would keep it and + // run ahead of the game. They get the asker's priority instead, as a forked child would. + runCatching { Process.setThreadPriority(nice) } + 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 { + 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() + + 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> = 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 + /** The priority it runs its program at: the asker's (a guest, or the app thread that started it). */ + @Volatile var nice = 0 + /** 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(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() + @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 + // A game's start hands off a burst of programs (Wine's services, the agent's checks) within a few + // seconds: bound ahead while the client starts it, not forked while the game draws its first frames. + private const val LAUNCH_WORKERS = 16 + private const val LAUNCH_MS = 20_000L + @Volatile private var launchUntil = 0L + private val launches = java.util.concurrent.atomic.AtomicInteger() + 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 + // Android sets a worker's main thread to THREAD_PRIORITY_TOP_APP_BOOST again each time the app returns to the top + private const val TOP_APP_BOOST = -10 + private const val PRIORITY_CHECK_MS = 2000L + @Volatile private var keeper: 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, env: List, stdio: List, 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, env: List, fds: List, 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, env: List, fds: List, targets: IntArray, + guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }, + confirmed: () -> Boolean = { true }, owner: Int = session, + nice: Int = Process.getThreadPriority(Process.myTid())): 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 + slot.nice = nice + // during a game's start the pool drains instead: its refill would fork while the game starts + if (android.os.SystemClock.elapsedRealtime() >= launchUntil) 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? = 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) + data.writeInt(nice) + 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() } + } + + /** A game is about to start: [LAUNCH_WORKERS] bound ahead, back to [WARM_WORKERS] once it is up. */ + fun expectLaunch(context: Context) { + val app = context.applicationContext + val raised = synchronized(slots) { (warmTarget > 0).also { if (it) warmTarget = LAUNCH_WORKERS } } + if (!raised) return + launchUntil = android.os.SystemClock.elapsedRealtime() + LAUNCH_MS + val launch = launches.incrementAndGet() + refill(app) + Thread({ + try { + Thread.sleep(LAUNCH_MS) + } catch (_: InterruptedException) { + return@Thread + } + if (launches.get() != launch) return@Thread + val extra = synchronized(slots) { + if (warmTarget != LAUNCH_WORKERS) emptyList() + else { + warmTarget = WARM_WORKERS + List((warm.size - WARM_WORKERS).coerceAtLeast(0)) { warm.removeLast() } + } + } + extra.forEach { release(app, it) } + refill(app) + }, "guest-worker-launch").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 = + 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 + } + + /** Puts a running program's main thread back to its asker's priority after Android boosted it (once started, never stops). */ + private fun keepPriorities() { + synchronized(this) { + if (keeper != null) return + keeper = Thread({ + while (true) { + try { + Thread.sleep(PRIORITY_CHECK_MS) + } catch (_: InterruptedException) { + return@Thread + } + val running = synchronized(slots) { + slots.filterNotNull().filter { it.started && it.pid > 0 && it.nice != TOP_APP_BOOST } + } + for (s in running) runCatching { + if (Process.getThreadPriority(s.pid) == TOP_APP_BOOST) Process.setThreadPriority(s.pid, s.nice) + } + } + }, "guest-worker-priority").apply { isDaemon = true; start() } + } + } + + /** 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) + keepPriorities() + 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() + 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() + 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) + // The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit + val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT) + val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, 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() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index fc2d6f6d46..be11f5bb90 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -130,6 +130,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", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 8dfb5adcbe..9aa2536f5e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1137,6 +1137,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() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 4c1ec74f61..eb4fed441c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -705,6 +705,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('"', ' ')) } @@ -864,10 +878,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 "") @@ -883,10 +897,19 @@ 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 + // Under the lock Stop clears it with, and only while this session still runs: a Stop since the + // check above has cleared it already, and this would set it again for no running session. + val uncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid) + synchronized(stopLock) { + if (gen == sessionGen && SessionState.running) + com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = uncounted + } if (pid > 1) { raiseTracer(pid, gen) SessionEvents.guestStarted(pid) @@ -1536,10 +1559,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) @@ -1556,6 +1584,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() { @@ -1730,6 +1759,7 @@ class SessionService : Service() { SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen)) watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId) Log.i(TAG, "queued Steam game $gameId for the running client") + com.droiddeck.launcher.runtime.GuestWorkers.expectLaunch(this) } private fun watchGameExit( @@ -2326,12 +2356,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)) @@ -2392,7 +2426,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) @@ -2401,6 +2436,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() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 30b0f1f1f9..cae3337649 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -415,7 +415,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 }, diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 81a2d7e2c5..f2345c9b2b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2554,6 +2554,8 @@ %1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى. يمكن بدء جلسات Steam. لا يستخدم إصدار Android هذا هذا الحدّ. + يتولى DroidDeck حد العمليات الفرعية + يشغّل DroidDeck معظم برامج الجلسة في عمليات لا يحتسبها Android، ما يبقي الجلسة دون الحد بكثير، لذا يمكن إبقاء خيارات المطوّرين متوقفة. ما زال Steam وبعض أدواته المساعدة محتسبة. فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك. لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز. لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index ba6eeaa153..5fcf421c1e 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -2546,6 +2546,8 @@ %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. Ya se pueden iniciar sesiones de Steam. Esta versión de Android no usa este límite. + DroidDeck gestiona el límite de procesos secundarios + DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones de desarrollador pueden quedar desactivadas. Steam y algunos de sus procesos auxiliares todavía cuentan. Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después. Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo. Esta versión no tiene descarga para esta copia de DroidDeck. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index b3b71c9d8f..d76ce39100 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2450,6 +2450,8 @@ %1$s Ако това не е възможно, свържи устройството с компютър с ADB и изпълни командата отдолу. Върни се тук и провери отново. Сесиите на Steam могат да стартират. Тази версия на Android не използва това ограничение. + DroidDeck се справя с ограничението за дъщерни процеси + DroidDeck изпълнява повечето програми на сесията в процеси, които Android не отчита, така че сесията остава далеч под лимита и опциите за програмисти могат да останат изключени. Steam и някои от помощните му процеси все още се отчитат. Включи „Деактивиране на ограниченията за дъщерните процеси“ в Опции за програмисти и остави Опции за програмисти включени след това. Тази версия на Android няма превключвател за това. Използвай безжично отстраняване на грешки, за да го промениш от това устройство. Тази версия няма изтегляне за това копие на DroidDeck. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index aa5271fa41..0d16e78c50 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2502,6 +2502,8 @@ %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. Relace Steamu se mohou spouštět. Tato verze Androidu tento limit nepoužívá. + Limit podřízených procesů řeší DroidDeck + DroidDeck spouští většinu programů relace v procesech, které Android nezapočítává, takže relace zůstává hluboko pod limitem a možnosti pro vývojáře mohou zůstat vypnuté. Steam a některé jeho pomocné procesy se stále započítávají. Zapněte „Deaktivace omezení podřízených procesů“ v Možnostech pro vývojáře a pak je nechte zapnuté. Tato verze Androidu pro to nemá přepínač. Použijte bezdrátové ladění a změňte to z tohoto zařízení. Toto sestavení nemá stažení pro tuto kopii DroidDecku. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 628b63ffda..bb73f2157e 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2450,6 +2450,8 @@ %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. Steam-sessioner kan starte. Denne Android-version bruger ikke denne grænse. + DroidDeck håndterer grænsen for underprocesser + DroidDeck kører de fleste af sessionens programmer i processer, som Android ikke tæller med, så sessionen holder sig et godt stykke under grænsen, og Indstillinger for udviklere kan forblive slået fra. Steam og nogle af dets hjælpeprocesser tæller stadig med. Tænd „Deaktiver begrænsningerne for underprocesser“ i Udvikleremuligheder, og lad Udvikleremuligheder være tændt bagefter. Denne Android-version har ingen kontakt til det. Brug Trådløs fejlretning til at ændre det fra denne enhed. Denne version har ingen download til denne kopi af DroidDeck. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index a6aeb9af47..b36e617ff1 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2442,6 +2442,8 @@ %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. Steam-Sitzungen können starten. Diese Android-Version nutzt dieses Limit nicht. + Limit für untergeordnete Prozesse übernimmt DroidDeck + DroidDeck führt die meisten Programme der Sitzung in Prozessen aus, die Android nicht mitzählt. So bleibt die Sitzung deutlich unter dem Limit, und die Entwickleroptionen können ausgeschaltet bleiben. Steam und einige seiner Hilfsprozesse zählen weiterhin mit. Aktiviere „Beschränkungen für Unterprozesse deaktivieren“ in den Entwickleroptionen und lass die Entwickleroptionen danach aktiviert. Diese Android-Version hat dafür keinen Schalter. Nutze Debugging über WLAN, um es auf diesem Gerät zu ändern. Dieser Build hat keinen Download für diese DroidDeck-Installation. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 7b7b91c949..2926f5e809 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2450,6 +2450,8 @@ %1$s Αν αυτό δεν είναι δυνατό, συνδέστε αυτή τη συσκευή σε έναν υπολογιστή με ADB και εκτελέστε την παρακάτω εντολή. Επιστρέψτε εδώ και ελέγξτε ξανά. Οι συνεδρίες Steam μπορούν να ξεκινήσουν. Αυτή η έκδοση Android δεν χρησιμοποιεί αυτό το όριο. + Το DroidDeck χειρίζεται το όριο θυγατρικών διεργασιών + Το DroidDeck εκτελεί τα περισσότερα προγράμματα της συνεδρίας σε διεργασίες που το Android δεν μετράει, ώστε η συνεδρία να μένει πολύ κάτω από το όριο και οι Επιλογές για προγραμματιστές να μπορούν να μείνουν απενεργοποιημένες. Το Steam και ορισμένες βοηθητικές διεργασίες του εξακολουθούν να μετράνε. Ενεργοποιήστε την «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες» στις Επιλογές προγραμματιστή και αφήστε τις Επιλογές προγραμματιστή ενεργές μετά. Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό. Χρησιμοποιήστε τον ασύρματο εντοπισμό σφαλμάτων για να το αλλάξετε από αυτή τη συσκευή. Αυτή η έκδοση δεν έχει λήψη για αυτό το αντίγραφο του DroidDeck. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 82f7aa68c6..177f127cfd 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2476,6 +2476,8 @@ %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. Ya se pueden iniciar sesiones de Steam. Esta versión de Android no usa este límite. + DroidDeck gestiona el límite de procesos secundarios + DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones para desarrolladores pueden seguir desactivadas. Steam y algunos de sus procesos auxiliares siguen contando. Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después. Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo. Esta versión no tiene descarga para esta copia de DroidDeck. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index bea612f362..084d6bc3d4 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2450,6 +2450,8 @@ %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. Steam-istunnot voivat käynnistyä. Tämä Android-versio ei käytä tätä rajaa. + DroidDeck hoitaa aliprosessirajoituksen + DroidDeck ajaa useimmat istunnon ohjelmat prosesseissa, joita Android ei laske, joten istunto pysyy reilusti rajan alapuolella ja kehittäjäasetukset voivat pysyä pois päältä. Steam ja osa sen apuprosesseista lasketaan edelleen. Ota käyttöön ”Poista käytöstä alatason prosessirajoitukset” Kehittäjäasetuksissa, ja pidä Kehittäjäasetukset päällä sen jälkeen. Tässä Android-versiossa ei ole kytkintä sille. Käytä langatonta virheenkorjausta muuttaaksesi sitä tältä laitteelta. Tälle versiolle ei ole latausta tähän DroidDeck-kopioon. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 1f713c136e..fb7b2e3125 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2475,6 +2475,8 @@ %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. Les sessions Steam peuvent démarrer. Cette version d\'Android n\'utilise pas cette limite. + Limite de processus enfants gérée par DroidDeck + DroidDeck exécute la plupart des programmes de la session dans des processus qu’Android ne compte pas, ce qui maintient la session bien en dessous de la limite : les options pour les développeurs peuvent rester désactivées. Steam et certains de ses processus auxiliaires sont toujours comptés. 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. Cette version d\'Android ne dispose pas de cet interrupteur. Utilisez le débogage sans fil pour le modifier depuis cet appareil. Cette version ne propose aucun téléchargement pour cette copie de DroidDeck. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 06a8bae5c6..ba6a92e527 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2450,6 +2450,8 @@ %1$s अगर यह संभव नहीं है, तो इस डिवाइस को ADB वाले कंप्यूटर से कनेक्ट करें और नीचे दिया कमांड चलाएं। यहां वापस आएं और फिर से जांचें। Steam सेशन शुरू हो सकते हैं। यह Android वर्शन इस सीमा का उपयोग नहीं करता। + चाइल्ड-प्रोसेस सीमा DroidDeck संभालता है + DroidDeck सत्र के ज़्यादातर प्रोग्राम उन प्रोसेस में चलाता है जिन्हें Android नहीं गिनता, जिससे सत्र सीमा से काफ़ी नीचे रहता है, इसलिए डेवलपर विकल्प बंद रह सकते हैं। Steam और उसके कुछ सहायक प्रोसेस अब भी गिने जाते हैं। डेवलपर विकल्प में “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें, और बाद में डेवलपर विकल्प चालू रहने दें। इस Android वर्शन में इसके लिए कोई स्विच नहीं है। इसे इस डिवाइस से बदलने के लिए वायरलेस डीबगिंग इस्तेमाल करें। इस बिल्ड में DroidDeck की इस कॉपी के लिए कोई डाउनलोड नहीं है। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index dcd4a47627..1e95248057 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2450,6 +2450,8 @@ %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. A Steam-munkamenetek elindulhatnak. Ez az Android-verzió nem használja ezt a korlátot. + A gyermekfolyamat-korlátot a DroidDeck kezeli + A DroidDeck a munkamenet legtöbb programját olyan folyamatokban futtatja, amelyeket az Android nem számol bele, így a munkamenet jóval a korlát alatt marad, és a fejlesztői beállítások kikapcsolva maradhatnak. A Steam és néhány segédfolyamata továbbra is beleszámít. 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. 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. Ehhez a buildhez nincs letöltés a DroidDeck ezen másolatához. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 33c2819a80..a40a71a131 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2425,6 +2425,8 @@ %1$s Jika itu tidak memungkinkan, sambungkan perangkat ini ke komputer dengan ADB dan jalankan perintah di bawah. Kembali ke sini dan periksa lagi. Sesi Steam dapat dimulai. Versi Android ini tidak menggunakan batas ini. + Batas proses anak ditangani DroidDeck + DroidDeck menjalankan sebagian besar program sesi dalam proses yang tidak dihitung Android, sehingga sesi tetap jauh di bawah batas dan Opsi developer bisa tetap nonaktif. Steam dan beberapa proses pembantunya masih dihitung. Aktifkan “Nonaktifkan batasan proses turunan” di Opsi developer, dan biarkan Opsi developer tetap aktif setelahnya. Versi Android ini tidak memiliki sakelar untuk itu. Gunakan Debugging nirkabel untuk mengubahnya dari perangkat ini. Build ini tidak memiliki unduhan untuk salinan DroidDeck ini. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 8bf9c2f898..5213ef5e0c 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2467,6 +2467,8 @@ %1$s Se non è possibile, collega questo dispositivo a un computer con ADB ed esegui il comando qui sotto. Poi torna qui e ricontrolla. Le sessioni Steam possono avviarsi. Questa versione di Android non usa questo limite. + Limite dei processi figli gestito da DroidDeck + DroidDeck esegue la maggior parte dei programmi della sessione in processi che Android non conteggia, così la sessione resta ben al di sotto del limite e le Opzioni sviluppatore possono restare disattivate. Steam e alcuni dei suoi processi di supporto vengono ancora conteggiati. Attiva “Disattiva limitazioni per i processi secondari” in Opzioni sviluppatore e poi lascia attive le Opzioni sviluppatore. Questa versione di Android non ha un interruttore per farlo. Usa il debug wireless per cambiarlo da questo dispositivo. Questa build non ha un download per questa copia di DroidDeck. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 6ce79c93f5..43f5008653 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2425,6 +2425,8 @@ %1$s それができない場合は、このデバイスをADBが使えるPCに接続し、以下のコマンドを実行してください。その後ここに戻って再確認してください。 Steamセッションを開始できます。 このAndroidバージョンではこの制限は使用されません。 + 子プロセスの制限は DroidDeck が対処します + DroidDeck はセッションのほとんどのプログラムを Android が数えないプロセスで実行するため、セッションは上限を大きく下回り、開発者向けオプションはオフのままでかまいません。Steam とその補助プロセスの一部は引き続き数えられます。 開発者向けオプションで「子プロセスの制限を無効化」をオンにし、その後も開発者向けオプションをオンのままにしてください。 このAndroidバージョンにはこのスイッチがありません。ワイヤレスデバッグを使って、このデバイスから変更してください。 このビルドには、このDroidDeckコピー用のダウンロードがありません。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index d6ec4b67fd..757402dcc6 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2425,6 +2425,8 @@ %1$s 이 방법을 사용할 수 없으면 이 기기를 ADB가 설치된 PC에 연결하고 아래 명령을 실행하세요. 그런 다음 여기로 돌아와 다시 확인하세요. Steam 세션을 시작할 수 있습니다. 이 Android 버전에서는 이 제한을 사용하지 않습니다. + 하위 프로세스 제한은 DroidDeck이 처리합니다 + DroidDeck은 세션 프로그램 대부분을 Android가 세지 않는 프로세스에서 실행하므로 세션이 한도보다 훨씬 낮게 유지되어 개발자 옵션을 꺼 둔 채로 두어도 됩니다. Steam과 일부 보조 프로세스는 여전히 집계됩니다. 개발자 옵션에서 “하위 프로세스 제한 사용 중지”를 켜고, 이후에도 개발자 옵션을 켜 둔 상태로 유지하세요. 이 Android 버전에는 해당 스위치가 없습니다. 무선 디버깅을 사용하여 이 기기에서 변경하세요. 이 빌드에는 이 DroidDeck 복사본용 다운로드가 없습니다. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 8a512b2378..04602fb1ff 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2425,6 +2425,8 @@ %1$s Jika itu tidak boleh, sambungkan peranti ini ke komputer dengan ADB dan jalankan arahan di bawah. Kembali ke sini dan semak semula. Sesi Steam boleh dimulakan. Versi Android ini tidak menggunakan had ini. + Had proses anak dikendalikan oleh DroidDeck + DroidDeck menjalankan kebanyakan program sesi dalam proses yang tidak dikira oleh Android, jadi sesi kekal jauh di bawah had dan Pilihan pembangun boleh kekal dimatikan. Steam dan sesetengah proses pembantunya masih dikira. Hidupkan “Lumpuhkan sekatan proses anak” dalam Pilihan pembangun, dan biarkan Pilihan pembangun hidup selepas itu. Versi Android ini tidak mempunyai suis untuknya. Gunakan Debugging Wayarles untuk menukarnya daripada peranti ini. Binaan ini tidak mempunyai muat turun untuk salinan DroidDeck ini. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index eb90ba013a..a43fcc4c14 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2450,6 +2450,8 @@ %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. Steam-sesjoner kan starte. Denne Android-versjonen bruker ikke denne grensen. + DroidDeck håndterer grensen for underprosesser + DroidDeck kjører de fleste programmene i økten i prosesser som Android ikke teller med, så økten holder seg godt under grensen og utvikleralternativer kan forbli av. Steam og noen av hjelpeprosessene dens telles fortsatt. Slå på «Slå av begrensninger for underordnede prosesser» i Utvikleralternativer, og la Utvikleralternativer stå på etterpå. Denne Android-versjonen har ingen bryter for det. Bruk trådløs feilsøking for å endre det fra denne enheten. Denne builden har ingen nedlasting for denne kopien av DroidDeck. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index bff090ecbf..22cec0f71e 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2450,6 +2450,8 @@ %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. Steam-sessies kunnen starten. Deze Android-versie gebruikt deze limiet niet. + Limiet voor onderliggende processen geregeld door DroidDeck + DroidDeck voert de meeste programma\'s van de sessie uit in processen die Android niet meetelt, zodat de sessie ruim onder de limiet blijft en Ontwikkelaarsopties uit kunnen blijven. Steam en enkele van zijn hulpprocessen tellen nog wel mee. Schakel “Beperkingen voor onderliggende processen uitzetten” in bij Ontwikkelaarsopties en laat Ontwikkelaarsopties daarna aan staan. Deze Android-versie heeft hier geen schakelaar voor. Gebruik draadloze foutopsporing om dit vanaf dit apparaat te wijzigen. Deze build heeft geen download voor dit exemplaar van DroidDeck. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 762da6dd60..274fdd1841 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2502,6 +2502,8 @@ %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. Sesje Steam mogą się uruchamiać. Ta wersja systemu Android nie używa tego limitu. + Limitem procesów podrzędnych zajmuje się DroidDeck + DroidDeck uruchamia większość programów sesji w procesach, których Android nie liczy, dzięki czemu sesja pozostaje znacznie poniżej limitu, a Opcje programisty mogą pozostać wyłączone. Steam i niektóre jego procesy pomocnicze nadal są liczone. Włącz „Wyłącz ograniczenia procesów podrzędnych aplikacji” w Opcjach programisty i nie wyłączaj potem Opcji programisty. Ta wersja systemu Android nie ma dla niego przełącznika. Użyj debugowania bezprzewodowego, aby zmienić go z tego urządzenia. Ta wersja nie ma pliku do pobrania dla tej kopii DroidDeck. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 50ade86f4b..d77b266199 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2482,6 +2482,8 @@ %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. As sessões Steam podem ser iniciadas. Esta versão do Android não usa este limite. + Limite de processos filhos gerido pelo DroidDeck + O DroidDeck executa a maioria dos programas da sessão em processos que o Android não conta, o que mantém a sessão bem abaixo do limite, por isso as Opções de programador podem continuar desativadas. O Steam e alguns dos seus processos auxiliares continuam a contar. Ative «Desativar restrições de processos secundários» nas Opções de programador e mantenha as Opções de programador ativadas depois. 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. Esta versão não tem transferência para esta cópia do DroidDeck. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 4ab1b8c9bf..831721004a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2490,6 +2490,8 @@ %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. As sessões do Steam podem ser iniciadas. Esta versão do Android não usa esse limite. + Limite de processos filhos gerenciado pelo DroidDeck + O DroidDeck executa a maioria dos programas da sessão em processos que o Android não conta, o que mantém a sessão bem abaixo do limite, então as Opções do desenvolvedor podem continuar desativadas. O Steam e alguns dos seus processos auxiliares ainda contam. Ative “Desativar restrições de processos filhos” nas Opções do desenvolvedor e mantenha as Opções do desenvolvedor ativadas depois. 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. Esta versão não tem download para esta cópia do DroidDeck. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index ecff9f03d2..fd1c57266f 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2476,6 +2476,8 @@ %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. Sesiunile Steam pot porni. Această versiune de Android nu folosește această limită. + Limita proceselor copil este gestionată de DroidDeck + DroidDeck rulează majoritatea programelor sesiunii în procese pe care Android nu le numără, astfel încât sesiunea rămâne mult sub limită, iar Opțiunile pentru dezvoltatori pot rămâne dezactivate. Steam și unele dintre procesele sale auxiliare sunt încă numărate. Activează „Dezactivează restricțiile pentru procese secundare” în Opțiunile pentru dezvoltatori, și lasă Opțiunile pentru dezvoltatori activate după aceea. Această versiune de Android nu are un comutator pentru asta. Folosește Depanarea wireless pentru a o schimba de pe acest dispozitiv. Această versiune nu are o descărcare pentru această copie de DroidDeck. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index d4ec60e21e..d101e72f83 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2503,6 +2503,8 @@ %1$s Если это невозможно, подключите устройство к компьютеру с ADB и выполните команду ниже. Затем вернитесь сюда и проверьте снова. Сессии Steam могут запускаться. Эта версия Android не использует это ограничение. + Ограничение дочерних процессов обходит DroidDeck + DroidDeck запускает большинство программ сеанса в процессах, которые Android не учитывает, поэтому сеанс остаётся намного ниже лимита и параметры разработчика можно не включать. Steam и некоторые его вспомогательные процессы по-прежнему учитываются. Включите «Отключить ограничения для дочерних процессов» в разделе «Для разработчиков» и оставьте этот раздел включенным. В этой версии Android нет такого переключателя. Измените настройку с этого устройства через отладку по Wi-Fi. В этой сборке нет загрузки для этой копии DroidDeck. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index b05dfdb1ae..8ad8bf7ec5 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2450,6 +2450,8 @@ %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. Steam-sessioner kan starta. Den här Android-versionen använder inte den här gränsen. + DroidDeck hanterar gränsen för underprocesser + DroidDeck kör de flesta av sessionens program i processer som Android inte räknar, så sessionen håller sig långt under gränsen och Utvecklaralternativ kan vara avstängda. Steam och några av dess hjälpprocesser räknas fortfarande. Slå på ”Inaktivera begränsningar på underordnade processer” i Utvecklaralternativ, och låt Utvecklaralternativ vara kvar på efteråt. 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. Den här versionen har ingen nedladdning för den här kopian av DroidDeck. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 59ff193161..e56def17ec 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2425,6 +2425,8 @@ %1$s หากทำไม่ได้ ให้เชื่อมต่ออุปกรณ์นี้กับคอมพิวเตอร์ที่มี ADB แล้วรันคำสั่งด้านล่าง กลับมาที่นี่แล้วตรวจสอบอีกครั้ง เซสชัน Steam สามารถเริ่มได้ Android รุ่นนี้ไม่ใช้ขีดจำกัดนี้ + DroidDeck จัดการขีดจำกัดโปรเซสลูกให้ + DroidDeck เรียกใช้โปรแกรมส่วนใหญ่ของเซสชันในโปรเซสที่ Android ไม่นับ เซสชันจึงต่ำกว่าขีดจำกัดมาก และปิดตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ไว้ได้ Steam และโปรเซสตัวช่วยบางตัวของ Steam ยังคงถูกนับ เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” ในตัวเลือกสำหรับนักพัฒนา และเปิดตัวเลือกสำหรับนักพัฒนาไว้ต่อไปหลังจากนั้น Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ใช้ Wireless debugging เพื่อเปลี่ยนค่าจากอุปกรณ์นี้ บิลด์นี้ไม่มีให้ดาวน์โหลดสำหรับสำเนานี้ของ DroidDeck diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 44b0ddcd0e..534ed8231e 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2442,6 +2442,8 @@ %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. Steam oturumları başlayabilir. Bu Android sürümü bu sınırı kullanmaz. + Alt işlem sınırını DroidDeck yönetiyor + DroidDeck oturumun programlarının çoğunu Android\'in saymadığı işlemlerde çalıştırır; böylece oturum sınırın çok altında kalır ve Geliştirici seçenekleri kapalı kalabilir. Steam ve bazı yardımcı işlemleri hâlâ sayılır. 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. 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. Bu derlemede bu DroidDeck kopyası için bir indirme yok. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 7b0960e582..73709f6c5d 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2502,6 +2502,8 @@ %1$s Якщо це неможливо, підключіть цей пристрій до комп’ютера з ADB і виконайте команду нижче. Потім поверніться сюди і перевірте ще раз. Сеанси Steam можуть запускатися. Ця версія Android не використовує це обмеження. + Обмеження дочірніх процесів обходить DroidDeck + DroidDeck запускає більшість програм сеансу в процесах, які Android не враховує, тож сеанс залишається значно нижче ліміту і параметри розробника можна не вмикати. Steam і деякі його допоміжні процеси все ще враховуються. Увімкніть «Вимкнути обмеження для дочірніх процесів» у розділі «Параметри розробника» і залишіть «Параметри розробника» увімкненими після цього. У цій версії Android немає перемикача для цього. Змініть це з цього пристрою за допомогою бездротового налагодження. У цій збірці немає завантаження для цієї копії DroidDeck. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 9e86fa1a73..56a841b3e5 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2425,6 +2425,8 @@ %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. Phiên Steam có thể khởi động. Phiên bản Android này không dùng giới hạn này. + DroidDeck xử lý giới hạn tiến trình con + DroidDeck chạy hầu hết 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 phiên luôn ở dưới giới hạn khá xa và có thể để tắt Tùy chọn cho nhà phát triển. Steam và một số tiến trình phụ trợ của nó vẫn được tính. 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 đó. 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. Bản build này không có tệp tải cho bản DroidDeck này. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 5e309dda05..17f7ac790c 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2502,6 +2502,8 @@ %1$s 如果无法做到,请将此设备连接到装有 ADB 的电脑并运行下方命令,然后返回此处重新检查。 可以启动 Steam 会话了。 此 Android 版本不使用该限制。 + 子进程限制由 DroidDeck 处理 + DroidDeck 在 Android 不计数的进程中运行大部分会话程序,使会话远低于上限,因此开发者选项可以保持关闭。Steam 及其部分辅助进程仍会被计数。 在开发者选项中打开“停止限制子进程”,之后请保持开发者选项开启。 此 Android 版本没有该开关。请使用无线调试在此设备上更改。 此构建没有适用于此 DroidDeck 副本的下载。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 2353da04f8..6f3b0ab240 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2422,6 +2422,8 @@ %1$s 如無法這樣做,請將此裝置連接到已安裝 ADB 的電腦,並執行以下指令,然後返回這裡再檢查一次。 可以啟動 Steam 會話。 此 Android 版本不使用此限制。 + 子程序限制由 DroidDeck 處理 + DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。 在開發人員選項中開啟「停用對子處理過程的限制」,之後請保持開發人員選項開啟。 此 Android 版本沒有此開關。請使用無線偵錯,直接在此裝置上更改。 此版本沒有適用於此 DroidDeck 版本的下載。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 273a2a78bd..ba06e45c24 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2422,6 +2422,8 @@ %1$s 如果無法這麼做,請將此裝置連接到裝有 ADB 的電腦並執行下方指令,然後返回這裡重新檢查。 可以啟動 Steam 工作階段。 此 Android 版本不使用這項限制。 + 子程序限制由 DroidDeck 處理 + DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。 在開發人員選項中開啟「停止限制子程序」,之後請保持開發人員選項開啟。 此 Android 版本沒有這個開關。請使用無線偵錯,直接在此裝置上變更。 此組建版本沒有適用於此 DroidDeck 複本的下載檔案。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e978abccd1..8081e1065d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2768,6 +2768,8 @@ %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. Steam sessions can start. This Android version does not use this limit. + Child-process limit handled by DroidDeck + 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. Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards. This Android version has no switch for it. Use Wireless debugging to change it from this device. This build has no download for this copy of DroidDeck. diff --git a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt index 3f05d01a36..5ea537d73f 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt @@ -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)) + } } diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md new file mode 100644 index 0000000000..54355c931f --- /dev/null +++ b/docs/phantom-processes.md @@ -0,0 +1,569 @@ +# 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_/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//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_/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_` 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//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/`, + `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_/pid_` 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/` 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//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//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` 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//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. + +### The bionic runtime + +DroidDeck-Bionic runs Wine on Android's libc, outside the glibc root, so the native hook never sees +its processes: with the handoff on, a bionic game's Wine programs (the game, `services.exe`, +`winedevice.exe`, `plugplay.exe`, `svchost.exe`, `lsass.exe`, `explorer.exe`, `rpcss.exe`) all stayed +under the worker that runs the tool's `launch.sh` and were counted. The same handoff is built into +the runtime's exec shim (`tools/bionic-runtime/handoff.c`, part of `libexecshim.so`, which every Wine +process preloads): it includes `hook/handoff.c` and `hook/kept.c` (the descriptors `close()` and +`close_range()` leave open, moved out of `privileged.c` for this) and adds what the native hook's +other parts do around them (`fork()`, `close()`, `close_range()`, `dup2()`, `dup3()`, and `exit()` for +the `on_exit()` bionic lacks). What differs on bionic: + +- **bionic's `execv()`, `execvp()` and `execl*()`** make the execve system call inside libc, past an + interposed `execve()`. Wine starts its preloader with `execv()`, so the shim defines them on top + of its `execve()`. +- **A start through the system linker** (`/system/bin/linker64 PROGRAM ARGS`, which the shim makes + of a dynamic program in app data, and which Wine sometimes makes itself) is listed by PROGRAM + (`ddh_try_as()` matches one program and sends another). +- **The app starts a handed-off program from the glibc root's `bash`** (GuestWorkers), which cannot + load the runtime's `LD_PRELOAD` and `LD_LIBRARY_PATH` (bionic libraries: "libdl.so: cannot open + shared object file"). The request carries those two as arguments of `/system/bin/env` instead, + which `bash` execs and which puts them back for the program; the worker's main process is the + program all the same. +- `launch.sh` keeps `DD_SPAWN`, `DD_SPAWN_SESSION`, `DD_HANDOFF*`, `DDH_*` and `DDNATV_ROOT` (it drops + the glibc guest's environment otherwise). The "can't open /proc/N/environ: Permission denied" + lines its prefix checks printed came from idle workers (zygote forks, not dumpable), not from + handed-off programs, which are readable; the redirect is now quiet. + +Measured on an AYANEO Pocket FIT (Snapdragon G3 Gen 3, Adreno 750, Android 14), DroidDeck-Bionic 14.1-r67 with this shim and +launcher, handoff on, max counted in the app's cgroups: + +| | Brawlhalla | DiRT Showdown | whole run | other apps' processes trimmed (limit on) | +|---|---|---|---|---| +| bionic, before | 25 | 24–27 | 28 | yes (Discord, a logcat, BatteryLog's `su`) | +| bionic, with the shim | 17 | 16 | 19–20 | none | +| DroidDeck-Proton 11-14.2 | 12–13 | 12–15 | 15–17 | none | + +DiRT's benchmark held 75 fps average either way; quit through Steam, stop and restart worked with +Android's limit on, with no DroidDeck process killed. Still counted on bionic: what `launch.sh` +itself starts (the game's first Wine process, `gstag`, the wait loop's `sleep`), since Android's +`sh` has no hook, and `wineserver`'s daemon fork. + +### 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//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:` (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 ` (or `adb shell device_config delete activity_manager +max_phantom_processes` if it was null), `adb shell device_config set_sync_disabled_for_tests ` +and `adb shell settings put global settings_enable_monitor_phantom_procs `, and end the lab's +sleepers with `adb shell am force-stop com.droiddeck.phantomlab`. diff --git a/tools/bionic-runtime/build.sh b/tools/bionic-runtime/build.sh index 9837fbfd3f..91314db4fd 100755 --- a/tools/bionic-runtime/build.sh +++ b/tools/bionic-runtime/build.sh @@ -184,7 +184,7 @@ echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-taggi "$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \ -ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so" "$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so" -"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so" +"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" "$HERE/handoff.c" -ldl -o "$PACK/preload/libexecshim.so" "$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so" "$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag" "$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag" diff --git a/tools/bionic-runtime/execshim.c b/tools/bionic-runtime/execshim.c index 166b9cb6fd..8b449e8b74 100644 --- a/tools/bionic-runtime/execshim.c +++ b/tools/bionic-runtime/execshim.c @@ -25,6 +25,9 @@ typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t; #define LINKER "/system/bin/linker64" +// handoff.c: returns unless the exec was handed to one of the app's worker processes +void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]); + enum kind { PASS, VIA_LINKER, VIA_INTERP }; // What starting `path` needs; for scripts, the interpreter and its optional argument. @@ -205,6 +208,8 @@ int execve(const char *path, char *const argv[], char *const envp[]) { char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes) const char *file = path; char **args = rewrite(path, argv, &file, storage); + // the app may run it in a worker instead (handoff.c): matched by the program, sent as the start below + ddh_bionic_exec(file, args ? args : argv, envp, path, argv); int ret = real(file, args ? args : argv, envp); int saved = errno; free(args); diff --git a/tools/bionic-runtime/handoff.c b/tools/bionic-runtime/handoff.c new file mode 100644 index 0000000000..406b19e7fe --- /dev/null +++ b/tools/bionic-runtime/handoff.c @@ -0,0 +1,415 @@ +// handoff: part of libexecshim.so, preloaded into the bionic Wine processes. The native hook's exec +// handoff (tools/nativeguest/hook/handoff.c, docs/phantom-processes.md) built for bionic: a program a +// Wine process forks and execs runs as the main process of one of the app's worker processes instead of +// as a child Android counts against its limit. The glibc session's hook cannot reach these processes +// (they run on Android's libc), so without this every Wine process of a bionic game was counted. +// +// What the native hook does around the handoff and this file does too: fork() records the child for +// its parent's table, close(), close_range(), dup2() and dup3() leave the table and the worker's binder +// fds alone (hook/kept.c), and execve() offers the exec to the app before it runs (execshim.c calls +// ddh_bionic_exec() with the start it is about to make: "/system/bin/linker64 PROGRAM ARGS" for a +// program in the app's data, matched against DD_HANDOFF by PROGRAM). wait*(), kill() and _exit() are +// the handoff's own (hook/handoff.c). Nothing here acts without DD_SPAWN and DD_HANDOFF in the +// environment (tools/bionic-runtime/tool/launch.sh keeps them). +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// bionic has no thread cancellation: nothing can cancel the table's setup +#ifndef PTHREAD_CANCEL_ENABLE +#define PTHREAD_CANCEL_ENABLE 0 +#define PTHREAD_CANCEL_DISABLE 1 +static int pthread_setcancelstate(int state, int *old) { + (void)state; + if (old) *old = PTHREAD_CANCEL_ENABLE; + return 0; +} +#endif +#ifndef CLOSE_RANGE_UNSHARE +#define CLOSE_RANGE_UNSHARE (1U << 1) +#endif +#ifndef CLOSE_RANGE_CLOEXEC +#define CLOSE_RANGE_CLOEXEC (1U << 2) +#endif +#ifndef __NR_close_range +#define __NR_close_range 436 +#endif + +#include +static void pthread_testcancel(void) {} +int close_range(unsigned int first, unsigned int last, int flags); + +// bionic has no on_exit(): the handoff reports a program's exit status from it (exit() runs it). +// atexit() handlers get no status, so exit() below notes it first; a return from main() reaches +// exit() inside libc and reports 0. +static void (*g_on_exit_fn)(int, void *); +static void *g_on_exit_arg; +static int g_exit_status; +static void run_on_exit(void) { + if (g_on_exit_fn) g_on_exit_fn(g_exit_status, g_on_exit_arg); +} +static int on_exit(void (*fn)(int, void *), void *arg) { + g_on_exit_fn = fn; + g_on_exit_arg = arg; + return atexit(run_on_exit); +} + +// The native hook's names for the plain system call and for a guest path: here there is no guest root. +static long call_orig_syscall(long nr, unsigned long a, unsigned long b, unsigned long c, unsigned long d, + unsigned long e, unsigned long f) { + return syscall(nr, a, b, c, d, e, f); +} +static const char *rewrite_path(const char *path, char *out, size_t size) { + (void)out; + (void)size; + return path; +} + +#include "../nativeguest/hook/kept.c" +#include "../nativeguest/hook/handoff.c" + +void exit(int status) { + g_exit_status = status; + void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, "exit"); + if (real) real(status); + syscall(SYS_exit_group, status); + __builtin_unreachable(); +} + +static int ddh_is_linker(const char *path) { + const char *base = path ? strrchr(path, '/') : NULL; + return base && strcmp(base + 1, "linker64") == 0; +} + +static int ddh_regular(const char *path, int mode) { + struct stat st; + return path && stat(path, &st) == 0 && S_ISREG(st.st_mode) && access(path, mode) == 0; +} + +// Android refuses execve() of a file in the app's data unless SELinux is permissive (execshim.c makes the +// dynamic ones linker64 starts). An unreadable setting counts as enforcing. +static int ddh_selinux_permissive(void) { + char c = 0; + int fd = (int)syscall(SYS_openat, AT_FDCWD, "/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC, 0); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, &c, 1); + syscall(SYS_close, fd); + return n == 1 && c == '0'; +} + +// A handed-off start that fails fails in the worker, where the caller cannot see it and try its next +// candidate (Wine tries its preloader, then its loader), so only a start that would succeed here goes. +static int ddh_bionic_startable(const char *file, char *const args[]) { + char real[PATH_MAX]; + // env takes an argument with '=' for a variable, and looks a name without '/' up in PATH + if (!file || strchr(file, '=') || !strchr(file, '/')) return 0; + if (!ddh_regular(file, X_OK) || !realpath(file, real)) return 0; + if (ddh_is_linker(real)) + return args && args[0] && args[1] && args[1][0] != '-' && ddh_regular(args[1], R_OK) && ddh_startable(args[1]); + if (strncmp(real, "/data/", 6) == 0 && !ddh_selinux_permissive()) return 0; + // env starts FILE with FILE as argv[0] + return args && args[0] && strcmp(args[0], file) == 0 && ddh_startable(file); +} + +void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]) { + if (ddh_env(envp, "DD_HANDOFF_DEBUG")) { + char why[200]; + struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + snprintf(why, sizeof(why), "bionic exec (spawn %d list %d table %d owner %d up %d ppid %d) of", ddh_env(envp, "DD_SPAWN") != NULL, + ddh_env(envp, "DD_HANDOFF") != NULL, own != NULL, own ? (int)g_ddh_owner : 0, g_ddh_up != NULL, (int)getppid()); + ddh_debug(envp, why, path ? path : "(null)"); + } + if (!ddh_env(envp, "DD_SPAWN") || !ddh_env(envp, "DD_HANDOFF")) return; + if (!ddh_bionic_startable(file, args)) { + ddh_debug(envp, "bionic exec stays here (not startable as a handoff):", path ? path : "(null)"); + return; + } + // Wine's own starts through the system linker ("/system/bin/linker64 PROGRAM ARGS") are listed by PROGRAM + const char *match = path; + char *const *match_argv = argv; + if (ddh_is_linker(path) && argv && argv[0] && argv[1]) { + match = argv[1]; + match_argv = argv + 1; + } + // The app starts a handed-off program from the glibc root's shell (GuestWorkers), which cannot load this + // runtime's LD_PRELOAD and LD_LIBRARY_PATH (bionic libraries). The request carries them as arguments of + // Android's env instead, which the shell execs and which puts them back for the program: the worker's main + // process ends up as the program all the same. Stack only (this may run in a vfork child). + int nargs = 0, nenv = 0; + while (args[nargs]) nargs++; + while (envp && envp[nenv]) nenv++; + // env, up to two loader variables, FILE, args[1..], NULL (nargs >= 1: ddh_bionic_startable) + char *wrapped[nargs + 4]; + char *trimmed[nenv + 1]; + int w = 0, t = 0; + wrapped[w++] = (char *)"/system/bin/env"; + for (int i = 0; i < nenv; i++) { + if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0 || strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) { + if (w < 3) wrapped[w++] = envp[i]; + } else { + trimmed[t++] = envp[i]; + } + } + trimmed[t] = NULL; + // env runs the program by the path its first argument gives: the start's file, then the rest of its argv + wrapped[w++] = (char *)file; + for (int i = 1; i < nargs; i++) wrapped[w++] = args[i]; + wrapped[w] = NULL; + ddh_try_as("/system/bin/env", wrapped, trimmed, match, match_argv); + ddh_debug(envp, "bionic exec stays here:", path ? path : "(null)"); +} + +// bionic's exec functions call the execve system call stub inside libc, past execshim.c's execve(): Wine +// starts its programs with execv() (its preloader) and execvp(), so these go through execve() here. +extern char **environ; + +int execv(const char *path, char *const argv[]) { return execve(path, argv, environ); } + +// bionic's execvpe(), through execve() here: an unset PATH is libc's default (Android 14's; an empty one, and an empty +// entry, are the current directory), and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh. +#define DDH_DEFPATH "/product/bin:/apex/com.android.runtime/bin:/apex/com.android.art/bin:/system_ext/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin" + +static int exec_as_script(const char *file, char *const argv[], char *const envp[]) { + int n = 0; + while (argv && argv[n]) n++; + char *script[(n > 0 ? n : 1) + 2]; + int s = 0; + script[s++] = (char *)"sh"; + script[s++] = (char *)file; + for (int i = 1; i < n; i++) script[s++] = argv[i]; + script[s] = NULL; + return execve("/system/bin/sh", script, envp); +} + +int execvpe(const char *file, char *const argv[], char *const envp[]) { + if (!file || !*file) { + errno = ENOENT; + return -1; + } + if (strchr(file, '/')) { + execve(file, argv, envp); + return errno == ENOEXEC ? exec_as_script(file, argv, envp) : -1; + } + const char *dirs = getenv("PATH"); + if (!dirs) dirs = DDH_DEFPATH; + int saw_eacces = 0; + size_t flen = strlen(file); + for (const char *p = dirs;;) { + const char *end = strchr(p, ':'); + size_t len = end ? (size_t)(end - p) : strlen(p); + const char *dir = len ? p : "."; + if (!len) len = 1; + char full[PATH_MAX]; + if (len + flen + 2 > sizeof(full)) { + errno = ENAMETOOLONG; + } else { + memcpy(full, dir, len); + full[len] = '/'; + memcpy(full + len + 1, file, flen + 1); + execve(full, argv, envp); + } + switch (errno) { + case EISDIR: + case ELOOP: + case ENAMETOOLONG: + case ENOENT: + case ENOTDIR: + break; + case ENOEXEC: + return exec_as_script(full, argv, envp); + case EACCES: + saw_eacces = 1; + break; + default: + return -1; + } + if (!end) break; + p = end + 1; + } + if (saw_eacces) errno = EACCES; + return -1; +} + +int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); } + +// execl(), execlp(), execle(): the list as an argv on the stack +#define EXECL_ARGV(first, ap, n) \ + do { \ + va_list count_ap; \ + va_copy(count_ap, ap); \ + n = first ? 1 : 0; \ + if (first) \ + while (va_arg(count_ap, const char *)) n++; \ + va_end(count_ap); \ + } while (0) + +int execl(const char *path, const char *arg0, ...) { + va_list ap; + va_start(ap, arg0); + int n; + EXECL_ARGV(arg0, ap, n); + char *argv[n + 1]; + argv[0] = (char *)arg0; + for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *); + argv[n] = NULL; + va_end(ap); + return execve(path, argv, environ); +} + +int execlp(const char *file, const char *arg0, ...) { + va_list ap; + va_start(ap, arg0); + int n; + EXECL_ARGV(arg0, ap, n); + char *argv[n + 1]; + argv[0] = (char *)arg0; + for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *); + argv[n] = NULL; + va_end(ap); + return execvp(file, argv); +} + +int execle(const char *path, const char *arg0, ...) { + va_list ap; + va_start(ap, arg0); + int n; + EXECL_ARGV(arg0, ap, n); + char *argv[n + 1]; + argv[0] = (char *)arg0; + for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *); + argv[n] = NULL; + if (arg0) (void)va_arg(ap, char *); // the list's NULL + char *const *envp = va_arg(ap, char *const *); + va_end(ap); + return execve(path, argv, envp); +} + +pid_t fork(void) { + static pid_t (*orig_fork)(void) = NULL; + if (!orig_fork) orig_fork = (pid_t (*)(void))dlsym(RTLD_NEXT, "fork"); + if (!orig_fork) { + errno = ENOSYS; + return -1; + } + ddh_prepare(); + pid_t forker = (pid_t)syscall(SYS_gettid); + pid_t pid = orig_fork(); + if (pid == 0) { + kept_forked(); + kept_close_forked(); + ddh_drop_worker_binder(); + ddh_forked(forker); + } else if (pid > 0) { + ddh_child_created(pid, 1); + } + return pid; +} + +int close(int fd) { + static int (*orig_close)(int) = NULL; + if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close"); + uint64_t ticket = kept_close_begin(); + if (kept_any() > 0 && is_kept_fd(fd)) { + kept_close_end(ticket); + return 0; + } + int r = orig_close ? orig_close(fd) : (errno = ENOSYS, -1); + int saved = errno; + kept_close_end(ticket); + errno = saved; + return r; +} + +static int dup_moved(int (*dup_fn)(int, int, int), int oldfd, int newfd, int flags) { + int pidfd_from = -1, locked = 0; + if (oldfd != newfd) { + locked = ddh_parent_pidfd_lock(newfd); + pidfd_from = ddh_parent_pidfd_moves(newfd); + } + int ret = dup_fn(oldfd, newfd, flags); + ddh_parent_pidfd_settle(pidfd_from, ret >= 0); + int saved = errno; + ddh_parent_pidfd_unlock(locked); + errno = saved; + return ret; +} + +static int (*g_orig_dup2)(int, int); +static int (*g_orig_dup3)(int, int, int); +static int call_dup2(int oldfd, int newfd, int flags) { + (void)flags; + return g_orig_dup2 ? g_orig_dup2(oldfd, newfd) : (errno = ENOSYS, -1); +} +static int call_dup3(int oldfd, int newfd, int flags) { + return g_orig_dup3 ? g_orig_dup3(oldfd, newfd, flags) : (errno = ENOSYS, -1); +} + +int dup2(int oldfd, int newfd) { + if (!g_orig_dup2) g_orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2"); + return dup_moved(call_dup2, oldfd, newfd, 0); +} + +int dup3(int oldfd, int newfd, int flags) { + if (!g_orig_dup3) g_orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3"); + return dup_moved(call_dup3, oldfd, newfd, flags); +} + +static int close_range_part(unsigned int first, unsigned int last, void *flags) { + return (int)syscall(__NR_close_range, first, last, *(int *)flags); +} + +static int close_range_unshare(void) { + return (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE); +} + +int close_range(unsigned int first, unsigned int last, int flags) { + // what the kernel refuses, refused before the range is split or the table unshared + if (first > last || (flags & ~(int)(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))) { + errno = EINVAL; + return -1; + } + uint64_t ticket = kept_close_begin(); + int r = 0; + // The table is unshared first, once, and this thread goes on with its own copy of the kept list + // (kept_split()) + if (flags & CLOSE_RANGE_UNSHARE) { + r = kept_split(close_range_unshare); + flags &= ~(int)CLOSE_RANGE_UNSHARE; + } + if (r == 0) { + int snapshot[DDNATV_MAX_KEPT_FDS]; + const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot; + int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot); + r = count == 0 ? close_range_part(first, last, &flags) + : for_each_range_without(first, last, kept, count, close_range_part, &flags); + } + int saved = errno; + kept_close_end(ticket); + errno = saved; + return r; +} + +// The native hook's own uses of these (exec.c) have no counterpart here +__attribute__((unused)) static void *const glibc_only[] = {(void *)ddh_try, (void *)ddh_spawn_wanted}; diff --git a/tools/bionic-runtime/tool/launch.sh b/tools/bionic-runtime/tool/launch.sh index bb72dd09a8..b3b9bd25c1 100644 --- a/tools/bionic-runtime/tool/launch.sh +++ b/tools/bionic-runtime/tool/launch.sh @@ -52,6 +52,10 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;; DROIDDECK_GUEST_ROOT) ;; VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;; + # The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the + # glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs + # in one): the first Wine process's hook knows the worker's binder fds are not its own. + DD_SPAWN|DD_SPAWN_SESSION|DD_HANDOFF|DD_HANDOFF_DEBUG|DD_HANDOFF_PRESSURE|DDH_*|DDNATV_ROOT) ;; *) unset "$v" 2>/dev/null ;; esac done @@ -259,7 +263,7 @@ prepare_prefix() { prefix_busy() { # a process of this prefix is running for p in /proc/[0-9]*; do [ "${p#/proc/}" = "$$" ] && continue - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 done return 1 } @@ -274,7 +278,7 @@ programs_left() { # a program of this prefix is still running, apart from Wine's ""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe|\ winemenubuilder|wineboot.exe|tabtip.exe) continue ;; esac - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 done return 1 } @@ -283,7 +287,7 @@ stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game wineserver_ -k 2>/dev/null sleep 1 for p in /proc/[0-9]*; do - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue [ "${p#/proc/}" = "$$" ] && continue echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)" kill -9 "${p#/proc/}" 2>/dev/null @@ -427,7 +431,7 @@ comm=$(echo "$name" | cut -c1-15) game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name) for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do p=${p%/comm} - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}" + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}" done } # The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 449c90ac93..756466bff4 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -284,8 +284,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): diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer b/tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer new file mode 100755 index 0000000000..fd49f5daed --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer @@ -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 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index c30c3098ec..a3fd527ab9 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -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)" @@ -618,6 +675,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 @@ -636,7 +698,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 @@ -779,7 +841,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 @@ -1124,7 +1186,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 @@ -1133,7 +1195,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 @@ -1226,7 +1289,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 @@ -1305,8 +1368,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'; } @@ -1393,8 +1457,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 @@ -1402,8 +1466,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 @@ -1427,7 +1491,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 @@ -1465,7 +1529,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 @@ -1489,7 +1553,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 @@ -1690,7 +1755,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= @@ -1868,7 +1933,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: /' @@ -2022,6 +2088,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" @@ -2031,6 +2098,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 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn new file mode 100755 index 0000000000..c0ebafccac --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn @@ -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()) diff --git a/tools/nativeguest/ddnatv-hook.c b/tools/nativeguest/ddnatv-hook.c index 4070f55c85..bf4c1679e2 100644 --- a/tools/nativeguest/ddnatv-hook.c +++ b/tools/nativeguest/ddnatv-hook.c @@ -77,11 +77,13 @@ #include "hook/files.c" #include "hook/fileops.c" #include "hook/identity.c" +#include "hook/kept.c" #include "hook/privileged.c" #include "hook/env.c" #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" diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index d2d707fad5..2f92fe9a0d 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -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. @@ -658,7 +659,17 @@ 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_forked(); + 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 +1076,215 @@ 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, ¶m); + int policy = 0; + posix_spawnattr_getschedpolicy(attr, &policy); + int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, ¶m) : sched_setparam(0, ¶m); + 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; + // Not cancelled while the child is being started (its report is read, and its failure reaped): + // the pid would be lost with the child still running, and the report's fd left open. + int cancel = PTHREAD_CANCEL_ENABLE; + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel); + int report[2]; + if (pipe2(report, O_CLOEXEC) != 0) { + pthread_setcancelstate(cancel, NULL); + return -1; + } + // Every signal blocked from the fork to the exec, as glibc's posix_spawn() does: a signal to the + // group during a file action (an open of a FIFO that blocks) would otherwise run the caller's + // handler, or end the child, before the program is started. The child gets back the caller's mask, + // or the one the attributes ask for, just before its exec. + sigset_t all, caller; + sigfillset(&all); + pthread_sigmask(SIG_SETMASK, &all, &caller); + pid_t child = fork(); + if (child < 0) { + int err = errno; + pthread_sigmask(SIG_SETMASK, &caller, NULL); + close(report[0]); + close(report[1]); + pthread_setcancelstate(cancel, NULL); + return err; + } + if (child > 0) pthread_sigmask(SIG_SETMASK, &caller, NULL); + 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) { + // A signal still pending when the mask is restored must not run a handler copied from the + // caller: caught signals go back to their default, ignored ones stay ignored (exec keeps + // them), and SIGSYS keeps the hook's handler. + for (int sig = 1; sig < _NSIG; sig++) { + struct sigaction old; + if (sig == SIGSYS || sig == SIGKILL || sig == SIGSTOP) continue; + if (sigaction(sig, NULL, &old) != 0) continue; + if (old.sa_handler == SIG_IGN || old.sa_handler == SIG_DFL) continue; + struct sigaction def = {0}; + def.sa_handler = SIG_DFL; + sigaction(sig, &def, NULL); + } + short flags = 0; + if (attr) posix_spawnattr_getflags(attr, &flags); + if (!(flags & POSIX_SPAWN_SETSIGMASK)) sigprocmask(SIG_SETMASK, &caller, NULL); + 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) { + } + pthread_setcancelstate(cancel, NULL); + return err; + } + if (pid) *pid = child; + pthread_setcancelstate(cancel, NULL); + 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 +1294,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, diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c new file mode 100644 index 0000000000..2d61fb8add --- /dev/null +++ b/tools/nativeguest/hook/handoff.c @@ -0,0 +1,2587 @@ +// Part of libddnatv-hook.so, included by ddnatv-hook.c after exec.c. +// +// Exec handoff. Android counts every process in the app's cgroup against its child-process limit, +// but not the app's own processes (docs/phantom-processes.md). A program a guest starts with +// fork() + execve() can instead run as the main process of one of the app's worker processes: the +// forked child sends the exec to the app (DD_SPAWN, an abstract socket) with its open fds, records +// the worker's pid in a table it shares with its parent, and exits. For the parent nothing changes: +// wait*(), kill() and SIGCHLD treat the pid fork() returned as that program until it exits; its exit +// status reaches the table from the program's hook, or for a signal from the app's report (see +// ddh_check_gone()), and the parent gets SIGCHLD. +// +// Only programs named in DD_HANDOFF (basenames separated by ':', or "*") are handed off, and, once +// the app is near Android's limit, a shell's children (ddh_pressed). The child's +// side runs where vfork() children run too, so it allocates nothing and writes no globals. +#include +#include + +#define DDH_SLOTS 1024 +#define DDH_FREE 0 +#define DDH_CLAIMED 3 +#define DDH_HANDED 1 +#define DDH_EXITED 2 +#define DDH_TAKEN 4 // its exit is being reported to one waiter +#define DDH_NO_STATUS INT32_MIN +#define DDH_MAGIC 0x6464686f +#define DDH_TABLE_FD 800 + +struct ddh_entry { + int32_t child; // the pid the parent got from fork() + int32_t real; // the worker's pid + int32_t parent; + int32_t state; + int32_t status; // wait status + int32_t reaped; // the parent has reaped the forked child itself + int32_t pad[2]; + // The app's report of a program that died without exit() or _exit() (GuestWorkers.reportExit): + // the wait status and the child it is for, in one 8-byte write. Only this side changes state. + int32_t app[2] __attribute__((aligned(8))); + int64_t child_start; // the forked child's start time: tells it from a later process given its pid + int32_t guessed; // the status is the timeout's guess: set only while the entry is held (TAKEN) + int32_t gen; // moved on by every claim of the slot, never 0, kept through a release (ddh_reaped()) + // When its worker was first seen gone, with the child that was for: child << 32 | seconds. Set by + // compare-and-swap only, so a waiter that looked before the slot changed hands cannot overwrite it. + uint64_t gone; +}; + +struct ddh_table { + int32_t magic; + int32_t pad[15]; + struct ddh_entry e[DDH_SLOTS]; +}; + +static struct ddh_table *g_ddh; // this process's table, for the children it forks +// A table given up while a close from before it was kept may still be under way: open, unkept, and +// tried again (not another made) until that close is over, so a close that never ends costs one fd. +static struct ddh_table *g_ddh_candidate; +static int g_ddh_candidate_fd = -1; +static int g_ddh_fd = -1; +static pid_t g_ddh_owner; +// The parent's table, when this image was exec'd by a child the parent forked (a wrapper such as +// env or a script that execs its program): that exec can still be handed off. +static struct ddh_table *g_ddh_up; +static int g_ddh_up_fd = -1; + +static const char *ddh_env(char *const envp[], const char *name) { + size_t n = strlen(name); + for (char *const *e = envp; e && *e; e++) { + if (strncmp(*e, name, n) == 0 && (*e)[n] == '=') return *e + n + 1; + } + return NULL; +} + +// DD_HANDOFF_DEBUG=1 writes the trace to stderr; an absolute path appends it to that file instead +// (stderr can be a pipe a program parses, or one nobody reads). +static void ddh_log(const char *setting, const char *line, size_t len) { + if (!setting || len == 0) return; + if (setting[0] != '/') { + syscall(SYS_write, 2, line, len); + return; + } + // non-blocking: a FIFO with no reader must not hold up the call being traced (a kill()) + int fd = (int)syscall(SYS_openat, AT_FDCWD, setting, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NONBLOCK, 0644); + if (fd < 0) return; + syscall(SYS_write, fd, line, len); + syscall(SYS_close, fd); +} + +// In the parent, before fork(): the table the children write to. +static void ddh_prepare_failed(const char *step) { + const char *debug = getenv("DD_HANDOFF_DEBUG"); + if (!debug) return; + char line[96]; + int len = snprintf(line, sizeof(line), "ddnatv handoff: %d no table: %s errno %d\n", (int)getpid(), step, errno); + if (len > 0) ddh_log(debug, line, (size_t)len); +} + +static void ddh_keep(int fd); +static void ddh_unkeep(int fd); + +// An fd's target that is one of Android's binder devices (directly or through binderfs). +static int ddh_is_binder(const char *target) { + return strcmp(target, "/dev/binder") == 0 || strcmp(target, "/dev/hwbinder") == 0 || + strcmp(target, "/dev/vndbinder") == 0 || strncmp(target, "/dev/binderfs/", 14) == 0; +} + +// The table the children write to, in a process of a session that hands programs off (DD_SPAWN). +// One thread makes it; a fork() while another thread is making it goes without (its child runs here). +static int g_ddh_preparing; + + +// Set by the waits with __WNOTHREAD: only children this thread forked are selected. +static __thread pid_t t_ddh_only_thread; + +// Which of this process's threads forked which child, in memory this process shares with the +// children it forks: the child may exec wrappers before it claims an entry, and those cannot carry +// it. One record per pid, at the pid's own index: two live children never share a pid, so nothing is +// ever full or pushed out, and a fork that gets a pid replaces whatever record a gone child left +// there; a record is never removed, and the child's start time in it tells it from a later child's. +// A child of fork() writes its own record before it can exit, so before its pid can be anyone +// else's (ddh_forked()); a posix_spawn() child runs nothing of this before its exec, so the parent +// writes its record once the call returns, by when it may be gone (ddh_forked_by()). Mapped when +// first needed, and only the pages of pids used are ever touched. One word: a record is only ever +// whole. A child not in here (a raw clone()) is no thread's for a __WNOTHREAD wait. +#define DDH_FORKS (1u << 22) /* PID_MAX_LIMIT */ +static uint64_t *g_ddh_forks; + +// child << 42 | thread << 20 | known << 19 | self << 18 | the child's start time's low 18 bits: pids +// and thread ids are below 2^22 (PID_MAX_LIMIT). The start time tells the record of one child from +// that of a later one given the same pid: a handoff entry holds its forked child's start time +// (child_start), and a record that does not match it is not that child's. Without the known bit it +// was not read, and matches any; 18 bits are 2^18 clock ticks (43 minutes at 100 Hz) apart. Self: +// the child wrote it, while it had the pid. +#define DDH_REC_KNOWN 0x80000u +#define DDH_REC_SELF 0x40000u +#define DDH_REC_START 0x3ffffu +static long ddh_start_time(pid_t pid); +static uint64_t ddh_fork_record(pid_t child, pid_t thread, long start, int self) { + uint64_t when = start > 0 ? ((uint64_t)start & DDH_REC_START) | DDH_REC_KNOWN : 0; + if (self) when |= DDH_REC_SELF; + return (uint64_t)((uint32_t)child & 0x3fffff) << 42 | (uint64_t)((uint32_t)thread & 0x3fffff) << 20 | when; +} +static pid_t ddh_record_child(uint64_t r) { return (pid_t)(r >> 42); } +static pid_t ddh_record_thread(uint64_t r) { return (pid_t)((r >> 20) & 0x3fffff); } +// Whether a record names a child that started at start (a time read for it, > 0) +static int ddh_record_started(uint64_t r, long start) { + return (r & DDH_REC_KNOWN) && start > 0 && ((uint64_t)start & DDH_REC_START) == (r & DDH_REC_START); +} + +static uint64_t *ddh_forks(int create) { + uint64_t *map = __atomic_load_n(&g_ddh_forks, __ATOMIC_ACQUIRE); + if (map || !create) return map; + void *fresh = mmap(NULL, (size_t)DDH_FORKS * sizeof(uint64_t), PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + if (fresh == MAP_FAILED) return NULL; + uint64_t *none = NULL; + if (__atomic_compare_exchange_n(&g_ddh_forks, &none, (uint64_t *)fresh, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) + return fresh; + munmap(fresh, (size_t)DDH_FORKS * sizeof(uint64_t)); + return none; +} + +// Whether the child a record names, started when it says, has a handoff whose program is running or +// whose exit is not yet reported: such a child loses its __WNOTHREAD owner with its record. +static int ddh_record_pending(uint64_t r) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t || !(r & DDH_REC_KNOWN)) return 0; + pid_t me = getpid(), child = ddh_record_child(r); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_CLAIMED || st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->parent == me && + e->child == child && ddh_record_started(r, (long)e->child_start)) return 1; + } + return 0; +} + +// The record of a posix_spawn() child, by the parent: by now the child may be gone, its pid another +// child's. +static void ddh_forked_by(pid_t child, pid_t thread) { + uint64_t *map = ddh_forks(1); + if (!map || child <= 0) return; + int saved = errno; + long start = ddh_start_time(child); + errno = saved; + uint64_t mine = ddh_fork_record(child, thread, start, 0); + uint64_t *slot = &map[(uint32_t)child % DDH_FORKS]; + uint64_t seen = __atomic_load_n(slot, __ATOMIC_ACQUIRE); + for (;;) { + // A fork child that could not read its own start time (out of fds, say) has no time to tell its + // record by, and the time read here may be that child's own: whether it is a later child than + // this one, maybe yet to hand its program off, cannot be told. Its record stays. (The cost: + // this child, if the fork child was an earlier one, has no record; a handoff it makes through + // a wrapper is then no thread's for a __WNOTHREAD wait.) + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_SELF) && !(seen & DDH_REC_KNOWN)) return; + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_KNOWN)) { + // A child that recorded itself, started when the time read here says, has the pid: this + // one is gone, and that time was the other child's. + if ((seen & DDH_REC_SELF) && ddh_record_started(seen, start)) return; + // A later child given the pid (this one reaped while its record was being made) has + // recorded itself already: its record stays. It is that child's only while the process + // that has the pid now started when it says; any other record of the pid is an earlier + // child's. A record without a start time (this child was gone before it was read) + // matches any child of the pid, a later one's too. + if (!ddh_record_started(seen, start)) { + saved = errno; + long now = ddh_start_time(child); + errno = saved; + if (ddh_record_started(seen, now)) return; + // Neither child has the pid now: one whose program still runs in a worker, its + // forked child reaped by another thread, keeps its record unless this child's runs too. + if (!ddh_record_started(mine, now) && ddh_record_pending(seen) && !ddh_record_pending(mine)) return; + } + } + if (__atomic_compare_exchange_n(slot, &seen, mine, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) return; + } +} + +// The thread that forked child, by the record of the fork whose child started at child_start (-1: +// any); 0 when there is none. +static pid_t ddh_forking_thread(pid_t child, long child_start) { + uint64_t *map = ddh_forks(0); + uint64_t r = map && child > 0 ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0; + if (!r || ddh_record_child(r) != child) return 0; + if ((r & DDH_REC_KNOWN) && child_start > 0 && !ddh_record_started(r, child_start)) return 0; // another child's + return ddh_record_thread(r); +} + +// In a forked child, by the thread that forked it: the child records itself in the parent's fork +// records first, while its pid is still its own. The thread making the table did not come along, so +// the child may make its own, and fork records of its own: it starts with an empty map (none, if it +// cannot map one, and then hands nothing off). +static void ddh_forked(pid_t thread) { + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELAXED); + if (g_ddh_candidate) munmap(g_ddh_candidate, sizeof(struct ddh_table)); // its fd: close-on-exec + g_ddh_candidate = NULL; + g_ddh_candidate_fd = -1; + uint64_t *old = __atomic_exchange_n(&g_ddh_forks, NULL, __ATOMIC_ACQ_REL); + if (!old) return; + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) { + int saved = errno; + pid_t me = (pid_t)syscall(SYS_getpid); + // tests only: as a child that cannot read its start time + long start = getenv("DDH_TEST_FORK_START_UNKNOWN") ? -1 : ddh_start_time(me); + uint64_t mine = ddh_fork_record(me, thread, start, 1); + __atomic_store_n(&old[(uint32_t)me % DDH_FORKS], mine, __ATOMIC_RELEASE); + errno = saved; + } + munmap(old, (size_t)DDH_FORKS * sizeof(uint64_t)); + ddh_forks(1); +} + +// Tests only ("FD"): once the table's fd is kept, before the wait for earlier closes, a byte to FD. +static void ddh_table_kept_gate(void) { + const char *gate = getenv("DDH_TEST_TABLE_KEPT"); + if (!gate) return; + int saved = errno; + char c = 1; + syscall(SYS_write, atoi(gate), &c, 1); + errno = saved; +} + +static int ddh_prepare_table(void); +static int ddh_new_table(int *made_fd, struct ddh_table **made); +static int ddh_is_table(int fd, const struct ddh_table *t); + +static void ddh_prepare(void) { + // the parent records which thread forks each child (ddh_forked_by()); a child refuses a handoff + // when it cannot (ddh_try()) + if (getenv("DD_SPAWN")) ddh_forks(1); + // A thread with a table of its own makes none: its fd would be in no other thread's table. + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN") || t_kept_split) return; + // Not cancelled from taking the guard to giving it back (the wait for earlier closes sleeps, a + // cancellation point, and asynchronous cancellation could strike anywhere), which would leave the + // guard taken and the candidate's state half kept for every later fork. The guard goes back + // before cancellation can come again. + int cancel = PTHREAD_CANCEL_ENABLE; + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel); + if (!__atomic_exchange_n(&g_ddh_preparing, 1, __ATOMIC_ACQ_REL)) { + // a second try for a table another thread's close took before it was kept + for (int attempt = 0; !g_ddh && attempt < 2 && !ddh_prepare_table(); attempt++) {} + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); + } + pthread_setcancelstate(cancel, NULL); +} + +// 1 when the table is made (g_ddh), 0 when its fd went to another thread's close before that one +// could see it was kept, or such a close was not over in time; the other failures are logged and end +// the trying too (1). +static int ddh_prepare_table(void) { + struct ddh_table *p = g_ddh_candidate; + int fd = g_ddh_candidate_fd; + g_ddh_candidate = NULL; + g_ddh_candidate_fd = -1; + if (p && ddh_is_table(fd, p)) { + ddh_keep(fd); + } else { + if (p) munmap(p, sizeof(struct ddh_table)); // closed since: a new one + if (!ddh_new_table(&fd, &p)) return 1; + } + // Another thread's close() or close_range() that looked at the kept fds before this one was among + // them may have closed it (and an open() taken the number): once those are over, it is still this + // table, or it is given up. Given up, the number is not closed here: a close still under way may + // close it any time, and another thread then reuse it before a close here would come. + ddh_table_kept_gate(); + int settled = kept_settle(); + if (!settled || !ddh_is_table(fd, p)) { + ddh_unkeep(fd); + if (!settled && ddh_is_table(fd, p)) { + g_ddh_candidate = p; + g_ddh_candidate_fd = fd; + } else { + munmap(p, sizeof(struct ddh_table)); + } + return 0; + } + g_ddh_fd = fd; + g_ddh_owner = getpid(); + __atomic_store_n(&g_ddh, p, __ATOMIC_RELEASE); + return 1; +} + +// A new table, kept: 0 when one cannot be made (logged). +static int ddh_new_table(int *made_fd, struct ddh_table **made) { + int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); + if (fd < 0) { + ddh_prepare_failed("memfd_create"); + return 0; + } + if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { + ddh_prepare_failed("ftruncate"); + close(fd); + return 0; + } + struct ddh_table *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + ddh_prepare_failed("mmap"); + close(fd); + return 0; + } + // Out of the way of the numbers programs redirect, and kept open when a child closes every + // inherited fd before exec (Python's subprocess does): the child needs it for its handoff. + int high = (int)syscall(SYS_fcntl, fd, F_DUPFD_CLOEXEC, DDH_TABLE_FD); + if (high >= 0) { + syscall(SYS_close, fd); + fd = high; + } + ddh_keep(fd); + p->magic = DDH_MAGIC; + p->pad[0] = getpid(); + // A nonce that tells this table's fd from any other (inode numbers are rewritten by the hardlink emulation) + if (syscall(SYS_getrandom, &p->pad[1], 2 * sizeof(int32_t), 0) != 2 * (long)sizeof(int32_t)) { + p->pad[1] = (int32_t)time(NULL); + p->pad[2] = (int32_t)(intptr_t)p; + } + *made_fd = fd; + *made = p; + return 1; +} + + +// Whether fd is still this table: a program may have put a file of its own at that number. +static int ddh_is_table(int fd, const struct ddh_table *t) { + int32_t head[4]; + if (fd < 0 || syscall(SYS_pread64, fd, head, sizeof(head), 0) != (long)sizeof(head)) return 0; + return head[0] == t->magic && head[1] == t->pad[0] && head[2] == t->pad[1] && head[3] == t->pad[2]; +} + +// The open fds from 3 on, ascending (as /proc lists them): how many, at most max; -1 without /proc. +static int ddh_list_fds(int *fds, int max) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + int n = 0; + char buf[4096]; + long got; + while ((got = syscall(SYS_getdents64, dir, buf, sizeof(buf))) > 0) { + for (long off = 0; off < got;) { + unsigned short reclen; + memcpy(&reclen, buf + off + 16, sizeof(reclen)); + const char *name = buf + off + 19; + off += reclen ? reclen : got; + if (name[0] < '0' || name[0] > '9') continue; + int fd = atoi(name); + if (fd >= 3 && fd != dir && n < max) fds[n++] = fd; + } + } + syscall(SYS_close, dir); + return n; +} + +#define DDH_LISTED_FDS 2048 + +// A table inherited across exec: the parent's if its owner is still our parent, else closed. +static void ddh_find_parent_table(void) { + char path[64], target[64]; + pid_t parent = (pid_t)syscall(SYS_getppid); + // The table a worker's program reports its exit to (DDH_TABLE), also for what it execs + int report = -1; + const char *spec = getenv("DDH_TABLE"); + if (spec && getenv("DDH_WORKER_PID") && atoi(getenv("DDH_WORKER_PID")) == getpid()) report = atoi(spec); + static int open_fds[DDH_LISTED_FDS]; + int count = ddh_list_fds(open_fds, DDH_LISTED_FDS); + for (int i = 0; i < count; i++) { + int fd = open_fds[i]; + if (fd == report) { + ddh_keep(fd); + continue; + } + int n = snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + if (n <= 0) continue; + long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); + if (len <= 0) continue; + target[len] = 0; + if (strncmp(target, "/memfd:ddnatv-handoff", 21) != 0) continue; + struct ddh_table *t = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (t != MAP_FAILED && t->magic == DDH_MAGIC && t->pad[0] == parent && !g_ddh_up) { + g_ddh_up = t; + g_ddh_up_fd = fd; + syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC); + ddh_keep(fd); + continue; + } + if (t != MAP_FAILED) munmap(t, sizeof(struct ddh_table)); + syscall(SYS_close, fd); + } +} + +// The worker's binder fds (DDH_WORKER_PID names the worker's process). Only that process may hold +// them: a child holding a copy keeps the worker alive in the system's eyes after its program exits. +static int g_ddh_binder[8]; +static int g_ddh_nbinder; +static pid_t g_ddh_worker; + +// Both change the list only between kept_change_begin() and kept_change_end() (hook/privileged.c), +// as other threads may be reading it. A thread with a table of its own changes its own copy. +static void ddh_unkeep(int fd) { + kept_change_begin(); + int *fds = t_kept_split ? t_kept_fds : g_kept_fds; + int *count = t_kept_split ? &t_kept_count : &g_kept_fd_count; + int n = *count; + for (int i = 0; i < n; i++) { + if (fds[i] != fd) continue; + for (int j = i; j + 1 < n; j++) __atomic_store_n(&fds[j], fds[j + 1], __ATOMIC_RELAXED); + __atomic_store_n(count, n - 1, __ATOMIC_RELAXED); + break; + } + kept_change_end(); +} + +static void ddh_keep(int fd) { + kept_change_begin(); + int *fds = t_kept_split ? t_kept_fds : g_kept_fds; + int *count = t_kept_split ? &t_kept_count : &g_kept_fd_count; + int n = *count, found = 0; + for (int i = 0; i < n; i++) found |= fds[i] == fd; + if (n < DDNATV_MAX_KEPT_FDS && !found) { + int i = n; + while (i > 0 && fds[i - 1] > fd) { + __atomic_store_n(&fds[i], fds[i - 1], __ATOMIC_RELAXED); + i--; + } + __atomic_store_n(&fds[i], fd, __ATOMIC_RELAXED); + __atomic_store_n(count, n + 1, __ATOMIC_RELAXED); + } + kept_change_end(); +} + +// A dup2() or dup3() onto the parent's pidfd (ddh_parent_lives()) or its spare: the check goes on with +// the other, so that the program gets the number it asked for; if the call then fails, nothing has +// changed (ddh_parent_pidfd_settle()). Returns the number the program takes over, or -1. +static int ddh_parent_pidfd_moves(int target); +static void ddh_parent_pidfd_settle(int from, int done); +static int ddh_parent_pidfd_lock(int target); +static void ddh_parent_pidfd_unlock(int locked); + +static void ddh_drop_worker_binder(void) { + if (g_ddh_nbinder == 0 || getpid() == g_ddh_worker) return; + for (int i = 0; i < g_ddh_nbinder; i++) { + ddh_unkeep(g_ddh_binder[i]); + syscall(SYS_close, g_ddh_binder[i]); + } + g_ddh_nbinder = 0; + g_cloexec_kept_count = 0; +} + +static void ddh_find_worker_binder(void) { + const char *worker = getenv("DDH_WORKER_PID"); + if (!worker) return; + g_ddh_worker = (pid_t)atoi(worker); + char path[64], target[32]; + static int open_fds[DDH_LISTED_FDS]; + int count = ddh_list_fds(open_fds, DDH_LISTED_FDS); + for (int i = 0; i < count && g_ddh_nbinder < 8; i++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", open_fds[i]); + long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); + if (len <= 0) continue; + target[len] = 0; + if (ddh_is_binder(target)) g_ddh_binder[g_ddh_nbinder++] = open_fds[i]; + } + if (getpid() == g_ddh_worker) { + // The program closing every fd it did not open (gamescope does) would end the worker. + for (int i = 0; i < g_ddh_nbinder; i++) { + ddh_keep(g_ddh_binder[i]); + g_cloexec_kept_fds[i] = g_ddh_binder[i]; + } + g_cloexec_kept_count = g_ddh_nbinder; + } + ddh_drop_worker_binder(); +} + +// In the program a worker runs for a handed-off child (DDH_TABLE "FD:SLOT:PARENT:CHILD"): its exit +// status goes into the parent's table here; the app reports it from Android's exit record only when +// the program never got to exit() or _exit() (a signal). +static struct ddh_table *g_ddh_report; +static int g_ddh_report_slot = -1; +static pid_t g_ddh_report_parent; +static pid_t g_ddh_report_child; +// The forked parent as a pidfd, opened at the start: readable once it has exited, reaped or not. +static int g_ddh_parent_pidfd = -1; + +// A second copy of it, made with it: a dup2() onto the pidfd's number moves the check to the spare, +// and no descriptor is ever made later, when another thread's close() or close_range() could be +// closing the number it would get. Both are kept (close() and close_range() leave them alone) from +// the start, before the program runs. Without a spare (a second dup2() onto it), the pidfd is given +// up and /proc answers. +static int g_ddh_parent_spare = -1; +// What the dup2() under way takes over: 1 the pidfd (the spare is the pidfd meanwhile), 2 the spare. +// Only changed with g_ddh_pidfd_lock held. +static int g_ddh_pidfd_move; + +static int ddh_parent_pidfd_moves(int target) { + // In a table of its own, a kept number the program takes over is let go of in this thread's copy + // only: the other threads' pidfd stays where it is. + if (t_kept_split) return target >= 0 && is_kept_fd(target) ? target : -1; + int fd = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE); + int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE); + if (target < 0 || (target != fd && target != spare)) return -1; + if (target == fd) { + __atomic_store_n(&g_ddh_parent_spare, -1, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_parent_pidfd, spare, __ATOMIC_RELEASE); + g_ddh_pidfd_move = 1; + } else { + __atomic_store_n(&g_ddh_parent_spare, -1, __ATOMIC_RELEASE); + g_ddh_pidfd_move = 2; + } + return target; +} + +static void ddh_parent_pidfd_settle(int from, int done) { + if (from < 0) return; + if (t_kept_split) { + if (done) ddh_unkeep(from); + return; + } + int move = g_ddh_pidfd_move; + g_ddh_pidfd_move = 0; + // the program's file now: its close() closes it + if (done) { + ddh_unkeep(from); + return; + } + // the dup failed and left the number as it was, still the pidfd (or the spare) and still kept + if (move == 1) { + int spare = __atomic_exchange_n(&g_ddh_parent_pidfd, from, __ATOMIC_ACQ_REL); + __atomic_store_n(&g_ddh_parent_spare, spare, __ATOMIC_RELEASE); + } else if (move == 2) { + __atomic_store_n(&g_ddh_parent_spare, from, __ATOMIC_RELEASE); + } +} + +// Held by every dup2()/dup3() of a process that has had the pidfd, from the move through the dup to +// the settling, and by fork() around the fork: no relocation can interleave with another. Every +// signal is blocked while it is held, so a handler that calls dup2() never waits for it on its own +// thread. ddh_parent_lives() only tries it. Released in a forked child. +static pthread_mutex_t g_ddh_pidfd_lock = PTHREAD_MUTEX_INITIALIZER; +static __thread uint64_t t_ddh_pidfd_mask; +static int g_ddh_had_pidfd; + +static void ddh_pidfd_hold(void) { + uint64_t all = ~0ull; + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&t_ddh_pidfd_mask, 8, 0, 0); + pthread_mutex_lock(&g_ddh_pidfd_lock); +} + +static void ddh_pidfd_release(void) { + pthread_mutex_unlock(&g_ddh_pidfd_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&t_ddh_pidfd_mask, 0, 8, 0, 0); +} + +static int ddh_parent_pidfd_lock(int target) { + (void)target; + if (!__atomic_load_n(&g_ddh_had_pidfd, __ATOMIC_ACQUIRE)) return 0; + ddh_pidfd_hold(); + return 1; +} + +static void ddh_parent_pidfd_unlock(int locked) { + if (locked) ddh_pidfd_release(); +} + +// The line of /proc/PID/cgroup that names the app's per-process cgroup ("...:/uid_U/pid_P"). +static int ddh_cgroup_line(pid_t pid, const char *want, char *out, size_t size) { + char path[48], buf[512]; + snprintf(path, sizeof(path), "/proc/%d/cgroup", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, buf, sizeof(buf) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + buf[n] = 0; + if (want) return strstr(buf, want) != NULL; + char mine[32]; + snprintf(mine, sizeof(mine), "/pid_%d\n", (int)pid); + char *at = strstr(buf, mine); + if (!at) return 0; + char *start = at; + while (start > buf && start[-1] != '\n') start--; + size_t len = (size_t)(at - start) + strlen(mine); + if (len + 1 > size) return 0; + memcpy(out, start, len); + out[len] = 0; + return 1; +} + +// A live process (not a zombie) in the cgroup that line names. +static int ddh_cgroup_member(pid_t pid, const char *line) { + char path[48], stat[256]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + stat[n] = 0; + char *paren = strrchr(stat, ')'); + if (!paren || paren[1] != ' ' || paren[2] == 'Z' || paren[2] == 'X') return 0; + return ddh_cgroup_line(pid, line, NULL, 0); +} + +static pid_t ddh_find_cgroup_member(const char *line, pid_t self) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return 0; + char entries[8192]; + pid_t found = 0; + long n; + while (!found && (n = syscall(SYS_getdents64, dir, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n && !found;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (name[0] < '1' || name[0] > '9') continue; + pid_t pid = (pid_t)atoi(name); + if (pid != self && ddh_cgroup_member(pid, line)) found = pid; + } + } + syscall(SYS_close, dir); + return found; +} + +static void ddh_linger_note(const char *what, long value) { + const char *debug = getenv("DD_HANDOFF_DEBUG"); + if (!debug) return; + char text[160]; + int len = snprintf(text, sizeof(text), "ddnatv handoff: %d linger: %s %ld\n", (int)getpid(), what, value); + if (len > 0) ddh_log(debug, text, (size_t)len); +} + +// Android kills every process in a worker's cgroup when the worker's own process ends: a program's +// daemon (wineserver forks it and exits) or a job it left running would die with it. So the program's +// process stays, as if it had exited (no fds but the worker's binder, no signals), until they are gone. +static void ddh_linger(int flush) { + char line[160]; + pid_t self = getpid(); + // Not with other threads, which would go on running the program's code meanwhile. + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return; + char entries[512]; + int threads = 0; + long n = syscall(SYS_getdents64, dir, entries, sizeof(entries)); + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + threads += entries[off + 19] >= '1' && entries[off + 19] <= '9'; + off += reclen ? reclen : n; + } + syscall(SYS_close, dir); + if (threads != 1) { + ddh_linger_note("threads", threads); + return; + } + if (!ddh_cgroup_line(self, NULL, line, sizeof(line))) { + ddh_linger_note("no cgroup line", 0); + return; + } + pid_t member = ddh_find_cgroup_member(line, self); + ddh_linger_note("cgroup member", member); + if (member <= 0) return; + if (flush) fflush(NULL); + sigset_t all; + sigfillset(&all); + sigprocmask(SIG_SETMASK, &all, NULL); + close_range(0, ~0U, 0); + while (member > 0) { + while (syscall(SYS_wait4, -1, NULL, WNOHANG, NULL) > 0) { + } + struct timespec second = {1, 0}; + nanosleep(&second, NULL); + if (!ddh_cgroup_member(member, line)) member = ddh_find_cgroup_member(line, self); + } +} + +static void ddh_register_group(void); +static void ddh_unregister_group(void); +static pid_t ddh_logical_pgrp(void); +static pid_t ddh_logical_group(pid_t real); +static long ddh_start_time(pid_t pid); +static int ddh_parent_lives(pid_t parent, long child_start); + +// From exit() (on_exit, arg 1) or _exit() (arg NULL) in a worker's own process. +// Only a handed-off child lingers: the app waits for the death of the programs it starts itself +// (the session's root) to tear everything down. +static void ddh_report_exit(int status, void *from_exit) { + if (!g_ddh_report || getpid() != g_ddh_worker) return; + // exit() flushes stdio after its on_exit() handlers: before the parent can see the exit here + if (from_exit) fflush(NULL); + struct ddh_entry *e = &g_ddh_report->e[g_ddh_report_slot]; + // Still this program's entry: the parent frees it when the forked child dies before handing off + // (and a later child may have it by now). + // From the state read (the forked child may still move it from CLAIMED to HANDED): a parent + // that freed the entry meanwhile keeps it freed. + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + for (int unknown = 0;;) { + // TAKEN: the parent's check of a gone worker holds the entry (ddh_check_gone()) and gives it + // back as it was when it is not the child it looked at. Wait that out, however long the parent + // takes, while there is a parent to give it back. When /proc cannot say (out of fds), kill() + // can, without a new fd, except for a parent that has exited and is not reaped: 5 s then. + int lives = st == DDH_TAKEN ? ddh_parent_lives(e->parent, (long)e->child_start) : 0; + if (lives < 0) { + int saved = errno; + lives = (syscall(SYS_kill, e->parent, 0) == 0 || errno != ESRCH) && unknown++ < 5000; + errno = saved; + } + if (lives) { + struct timespec ts = {0, 1000 * 1000}; + syscall(SYS_nanosleep, &ts, NULL); + st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + continue; + } + if ((st != DDH_HANDED && st != DDH_CLAIMED) || e->parent != g_ddh_report_parent || + (g_ddh_report_child > 0 && e->child != g_ddh_report_child)) + break; + e->status = (status & 0xff) << 8; + if (__atomic_compare_exchange_n(&e->state, &st, DDH_EXITED, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { + if (g_ddh_report_parent > 0) syscall(SYS_kill, g_ddh_report_parent, SIGCHLD); + break; + } + } + ddh_linger(from_exit != NULL); + ddh_unregister_group(); +} + +// A program that leaves with _exit() skips on_exit(): a daemon's first process does, once it has +// forked the daemon (wineserver), and its parent waits for that status. +__attribute__((noreturn)) static void ddh_real_exit(const char *name, int status) { + void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, name); + if (real) real(status); + syscall(SYS_exit_group, status); + __builtin_unreachable(); +} + +void _exit(int status) { + ddh_report_exit(status, NULL); + ddh_real_exit("_exit", status); +} + +void _Exit(int status) { + ddh_report_exit(status, NULL); + ddh_real_exit("_Exit", status); +} + +static void ddh_setup_report(void) { + const char *spec = getenv("DDH_TABLE"); + if (!spec || g_ddh_worker != getpid()) return; + int fd = -1, slot = -1, parent = 0, child = 0; + if (sscanf(spec, "%d:%d:%d:%d", &fd, &slot, &parent, &child) < 3 || slot < 0 || slot >= DDH_SLOTS) return; + struct ddh_table *t = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (t == MAP_FAILED || t->magic != DDH_MAGIC) return; + g_ddh_report = t; + g_ddh_report_slot = slot; + g_ddh_report_parent = parent; + g_ddh_report_child = child; + // the parent itself, not a later process given its pid (one that started after its child) + int pidfd = (int)call_orig_syscall(__NR_pidfd_open, (unsigned long)parent, 0, 0, 0, 0, 0); + long started = ddh_start_time(parent), child_start = t->e[slot].child_start; + if (pidfd >= 0 && started >= 0 && child_start >= 0 && started > child_start) { + syscall(SYS_close, pidfd); + pidfd = -1; + } + if (pidfd >= 0) { + // out of the way of the numbers programs pick for themselves + int high = (int)call_orig_syscall(SYS_fcntl, (unsigned long)pidfd, F_DUPFD_CLOEXEC, 900, 0, 0, 0); + if (high >= 0) { + syscall(SYS_close, pidfd); + pidfd = high; + } + ddh_keep(pidfd); + if (!is_kept_fd(pidfd)) { + // no room in the kept list: the program could close it, and /proc answers + syscall(SYS_close, pidfd); + pidfd = -1; + } + } + if (pidfd >= 0) { + g_ddh_parent_pidfd = pidfd; + int spare = (int)call_orig_syscall(SYS_fcntl, (unsigned long)pidfd, F_DUPFD_CLOEXEC, 900, 0, 0, 0); + if (spare >= 0) ddh_keep(spare); + if (spare >= 0 && is_kept_fd(spare)) g_ddh_parent_spare = spare; + else if (spare >= 0) syscall(SYS_close, spare); + __atomic_store_n(&g_ddh_had_pidfd, 1, __ATOMIC_RELEASE); + pthread_atfork(ddh_pidfd_hold, ddh_pidfd_release, ddh_pidfd_release); + } + on_exit(ddh_report_exit, (void *)1); + ddh_register_group(); +} + +// In a program a worker started: the state its forked parent had, sent along with the exec. Not in +// the app's shell that execs it (DDH_WRAPPER): bash changes its signal mask (it unblocks SIGCHLD), +// and its exec keeps bash's. +static void ddh_apply_inherited(void) { + if (getenv("DDH_WRAPPER")) return; + const char *ign = getenv("DDH_SIGIGN"); + if (ign) { + unsigned long mask = strtoul(ign, NULL, 10); + for (int sig = 1; sig < 32; sig++) { + if (sig == SIGKILL || sig == SIGSTOP) continue; + struct sigaction sa; + if (sigaction(sig, NULL, &sa) != 0) continue; + int want = (mask >> (sig - 1)) & 1; + if (want && sa.sa_handler != SIG_IGN) signal(sig, SIG_IGN); + else if (!want && sa.sa_handler == SIG_IGN) signal(sig, SIG_DFL); + } + unsetenv("DDH_SIGIGN"); + } + const char *nofile = getenv("DDH_NOFILE"); + if (nofile) { + struct rlimit lim; + // "SOFT:HARD": both as the forked child had them, the hard limit too, which a program can + // only lower (no higher than the worker's) + if (getrlimit(RLIMIT_NOFILE, &lim) == 0) { + char *end = NULL; + rlim_t want = (rlim_t)strtoull(nofile, &end, 10); + if (end && *end == ':') { + rlim_t hard = (rlim_t)strtoull(end + 1, NULL, 10); + if (hard < lim.rlim_max) lim.rlim_max = hard; + } + lim.rlim_cur = want < lim.rlim_max ? want : lim.rlim_max; + setrlimit(RLIMIT_NOFILE, &lim); + } + unsetenv("DDH_NOFILE"); + } + const char *mask = getenv("DDH_UMASK"); + if (mask) { + umask((mode_t)strtoul(mask, NULL, 10)); + unsetenv("DDH_UMASK"); + } + // The blocked signals: the forked parent's, or none for a program the app started. A worker + // execs from Android's main thread, which blocks SIGQUIT, SIGUSR1 and SIGPIPE. + const char *blocked = getenv("DDH_SIGMASK"); + if (blocked) { + unsigned long long bits = strtoull(blocked, NULL, 10); + sigset_t set; + sigemptyset(&set); + for (int sig = 1; sig <= 64 && sig < NSIG; sig++) { + if ((bits >> (sig - 1)) & 1) sigaddset(&set, sig); + } + sigprocmask(SIG_SETMASK, &set, NULL); + unsetenv("DDH_SIGMASK"); + } +} + +__attribute__((constructor)) static void ddh_init(void) { + ddh_apply_inherited(); + ddh_find_worker_binder(); + ddh_setup_report(); + ddh_find_parent_table(); + // tests only: as when the table could not be made here, and the first fork makes it + if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare(); +} + +static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) { + for (int i = 1; argv && argv[i]; i++) { + if (strncmp(argv[i], prefix, len) == 0) return 1; + } + return 0; +} + +// An entry is a basename, or "name+prefix" for that program only when an argument starts with prefix. +static int ddh_listed(const char *list, const char *name, char *const argv[]) { + if (!list || !name || !*name) return 0; + if (strcmp(list, "*") == 0) return 1; + size_t n = strlen(name); + for (const char *p = list; *p;) { + const char *end = strchr(p, ':'); + size_t len = end ? (size_t)(end - p) : strlen(p); + const char *plus = memchr(p, '+', len); + size_t base = plus ? (size_t)(plus - p) : len; + if (base == n && strncmp(p, name, n) == 0 && + (!plus || ddh_has_arg(argv, plus + 1, len - base - 1))) return 1; + if (!end) break; + p = end + 1; + } + return 0; +} + +static const char *ddh_base(const char *path) { + const char *s = path ? strrchr(path, '/') : NULL; + return s ? s + 1 : path; +} + +struct ddh_buf { + char *p; + size_t len, cap; +}; + +static void ddh_put(struct ddh_buf *b, const char *s, size_t n) { + if (b->p && b->len < b->cap) memcpy(b->p + b->len, s, n < b->cap - b->len ? n : b->cap - b->len); + b->len += n; +} + +static void ddh_puts(struct ddh_buf *b, const char *s) { ddh_put(b, s, strlen(s)); } + +static void ddh_putint(struct ddh_buf *b, long v) { + char tmp[24]; + int i = sizeof(tmp); + int neg = v < 0; + unsigned long u = neg ? 0UL - (unsigned long)v : (unsigned long)v; // no overflow for LONG_MIN + do { + tmp[--i] = (char)('0' + u % 10); + u /= 10; + } while (u); + if (neg) tmp[--i] = '-'; + ddh_put(b, tmp + i, sizeof(tmp) - i); +} + +static void ddh_putstr(struct ddh_buf *b, const char *s) { + static const char hex[] = "0123456789abcdef"; + ddh_put(b, "\"", 1); + for (const unsigned char *c = (const unsigned char *)s; *c; c++) { + if (*c == '"' || *c == '\\') { + char esc[2] = {'\\', (char)*c}; + ddh_put(b, esc, 2); + } else if (*c < 0x20) { + char esc[6] = {'\\', 'u', '0', '0', hex[*c >> 4], hex[*c & 15]}; + ddh_put(b, esc, 6); + } else { + ddh_put(b, (const char *)c, 1); + } + } + ddh_put(b, "\"", 1); +} + +static void ddh_putarray(struct ddh_buf *b, char *const v[]) { + ddh_put(b, "[", 1); + for (int i = 0; v && v[i]; i++) { + if (i) ddh_put(b, ",", 1); + ddh_putstr(b, v[i]); + } + ddh_put(b, "]", 1); +} + +#define DDH_MAX_FDS 240 +#define DDH_FDS_PER_CHUNK 60 + +// The fds the program would have inherited: every open fd without FD_CLOEXEC, but skip (the table). +static int ddh_open_fds(int *fds, int max, int skip) { + int n = 0; + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + char buf[4096]; + for (;;) { + long got = syscall(SYS_getdents64, dir, buf, sizeof(buf)); + if (got <= 0) break; + for (long off = 0; off < got;) { + struct { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (void *)(buf + off); + off += d->reclen; + if (d->name[0] < '0' || d->name[0] > '9') continue; + int fd = 0; + for (const char *c = d->name; *c; c++) fd = fd * 10 + (*c - '0'); + if (fd == dir || fd == skip) continue; + int flags = (int)syscall(SYS_fcntl, fd, F_GETFD); + if (flags < 0 || (flags & FD_CLOEXEC)) continue; + // A worker's binder fd, inherited from the worker this process runs in: it keeps that + // worker alive and must not take the place of the new worker's own. + char link[64], target[32]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + long tlen = syscall(SYS_readlinkat, AT_FDCWD, link, target, sizeof(target) - 1); + if (tlen > 0) { + target[tlen] = 0; + if (ddh_is_binder(target)) continue; + } + if (n == max) { + syscall(SYS_close, dir); + return -1; + } + fds[n++] = fd; + } + } + syscall(SYS_close, dir); + return n; +} + +// The interpreter a script names on its "#!" line ("/usr/bin/env NAME" gives NAME), into buf. +// In a forked child: system calls only, as the hook's own open() and close() take locks another +// thread of the parent may have held at fork(). +static const char *ddh_interpreter(const char *path, char *buf, size_t size) { + char real[PATH_MAX]; + // non-blocking, and only a regular file: the path could name a FIFO + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(path, real, sizeof(real)), + O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); + if (fd < 0) return NULL; + struct stat st; + if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) { + syscall(SYS_close, fd); + return NULL; + } + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)buf, size - 1, 0, 0, 0); + syscall(SYS_close, fd); + if (n < 3 || buf[0] != '#' || buf[1] != '!') return NULL; + buf[n] = 0; + char *p = buf + 2; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\n') end++; + char *word = NULL; + if (*end == ' ' || *end == '\t') { + word = end + 1; + while (*word == ' ' || *word == '\t') word++; + } + *end = 0; + const char *name = ddh_base(p); + if (strcmp(name, "env") == 0 && word && *word) { + end = word; + while (*end && *end != ' ' && *end != '\t' && *end != '\n') end++; + *end = 0; + return word; + } + return name; +} + +// An aarch64 ELF image the kernel would load, whose interpreter, if it names one, is in the guest's +// root; fd is the image. +static int ddh_elf_startable(int fd) { + Elf64_Ehdr eh; + if (syscall(SYS_pread64, fd, &eh, sizeof(eh), 0) != (long)sizeof(eh) || eh.e_ident[EI_CLASS] != ELFCLASS64 || + eh.e_machine != EM_AARCH64 || (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || + eh.e_phentsize != sizeof(Elf64_Phdr) || eh.e_phnum == 0 || eh.e_phnum > 64) + return 0; + for (int i = 0; i < eh.e_phnum; i++) { + Elf64_Phdr ph; + if (syscall(SYS_pread64, fd, &ph, sizeof(ph), (long)(eh.e_phoff + (Elf64_Off)i * sizeof(ph))) != (long)sizeof(ph)) + return 0; + if (ph.p_type != PT_INTERP) continue; + char interp[PATH_MAX], real[PATH_MAX]; + if (ph.p_filesz == 0 || ph.p_filesz >= sizeof(interp) || + syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) + return 0; + interp[ph.p_filesz] = 0; + return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(interp, real, sizeof(real)), + R_OK, 0, 0, 0) == 0; + } + return 1; +} + +// Whether an exec of path would get as far as the program: an ELF image the kernel would load, or a +// script whose "#!" interpreter is there to run. Anything else fails in the exec, which must happen +// here then, so that the caller (posix_spawn() above all) gets its error rather than a worker's exit +// status. +static int ddh_startable(const char *path) { + char real[PATH_MAX], head[256]; + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(path, real, sizeof(real)), + O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)head, sizeof(head) - 1, 0, 0, 0); + int elf = n >= 4 && memcmp(head, "\177ELF", 4) == 0 && ddh_elf_startable(fd); + syscall(SYS_close, fd); + if (n >= 4 && memcmp(head, "\177ELF", 4) == 0) return elf; + if (n < 3 || head[0] != '#' || head[1] != '!') return 0; + head[n] = 0; + char *p = head + 2; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\n' && *end != '\r') end++; + *end = 0; + if (*p != '/') return 0; + return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(p, real, sizeof(real)), X_OK, 0, 0, 0) == 0; +} + +// Whether s is valid UTF-8: the app reads the request as UTF-8, and any other byte would reach the +// program changed (a file name in Latin-1, say), where a local exec passes it on as it is. +static int ddh_utf8(const char *s) { + const unsigned char *p = (const unsigned char *)s; + while (*p) { + int n = *p < 0x80 ? 0 : (*p & 0xe0) == 0xc0 ? 1 : (*p & 0xf0) == 0xe0 ? 2 : (*p & 0xf8) == 0xf0 ? 3 : -1; + if (n < 0 || (n == 1 && *p < 0xc2) || (n == 3 && *p > 0xf4)) return 0; + unsigned int cp = n == 0 ? *p : *p & (0x3f >> n); + for (int i = 1; i <= n; i++) { + if ((p[i] & 0xc0) != 0x80) return 0; + cp = (cp << 6) | (p[i] & 0x3f); + } + if ((n == 2 && (cp < 0x800 || (cp >= 0xd800 && cp <= 0xdfff))) || (n == 3 && (cp < 0x10000 || cp > 0x10ffff))) return 0; + p += n + 1; + } + return 1; +} + +static int ddh_all_utf8(char *const v[]) { + for (int i = 0; v && v[i]; i++) { + if (!ddh_utf8(v[i])) return 0; + } + return 1; +} + +static int ddh_program_listed(const char *list, const char *filename, char *const argv[]) { + char shebang[256]; + const char *interp; + // "python3 SCRIPT" and "sh SCRIPT" are matched by the script's name too (and only an + // interpreter's: "pidof wineserver" is not wineserver) + const char *prog = ddh_base(filename); + int interpreter = strcmp(prog, "sh") == 0 || strcmp(prog, "bash") == 0 || strcmp(prog, "dash") == 0 || + strncmp(prog, "python", 6) == 0 || strncmp(prog, "perl", 4) == 0; + const char *script = interpreter && argv && argv[0] && argv[1] && argv[1][0] != '-' ? ddh_base(argv[1]) : NULL; + return ddh_listed(list, ddh_base(filename), argv) || (argv && ddh_listed(list, ddh_base(argv[0]), argv)) || + (script && ddh_listed(list, script, argv)) || + ((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv)); +} + +// Whether a posix_spawn() of this program should be handed off: glibc's spawn child makes the exec +// system call itself, past ddh_try(), so such a spawn is started with fork() and execve() instead. +// The hook's exec ends these at once and its posix_spawn() runs them (exec.c): never handed off. +static int ddh_exec_stub(const char *path) { + static const char *const exec_stubs[] = {"mandb", "mandb.real", "update-mime-database", "update-desktop-database", + "install-info", "install-sgmlcatalog"}; + for (size_t i = 0; path && i < sizeof(exec_stubs) / sizeof(exec_stubs[0]); i++) { + if (strcmp(ddh_base(path), exec_stubs[i]) == 0) return 1; + } + return 0; +} + +// Android's limit is 32 counted processes for the whole app. Past this many, a shell's (or make's, +// or xargs') child goes to a worker even when it is not listed: those wait for their children with +// wait(), which the hook answers. Other parents may track a child by pidfd or /proc, which would see +// the forked child exit at once. +#define DDH_PRESSURE 20 + +static int ddh_waiter(pid_t pid); +static int ddh_counted(void); +static int ddh_pressure_keeps(const char *filename, char *const argv[]); + +// DD_HANDOFF_PRESSURE sets another count (tests) +static int ddh_pressure(char *const envp[]) { + const char *v = ddh_env(envp, "DD_HANDOFF_PRESSURE"); + return v && *v ? atoi(v) : DDH_PRESSURE; +} + +static int ddh_spawn_wanted(const char *path, char *const argv[], char *const envp[]) { + if (!path || ddh_exec_stub(path)) return 0; + const char *list = ddh_env(envp, "DD_HANDOFF"); + if (!ddh_env(envp, "DD_SPAWN") || !list) return 0; + // as ddh_pressed() would in the child (GNU make spawns its recipes' shells) + return ddh_program_listed(list, path, argv) || (!ddh_pressure_keeps(path, argv) && ddh_waiter(getpid()) && ddh_counted() >= ddh_pressure(envp)); +} + +static long ddh_read_proc(const char *path, char *buf, size_t size) { + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + long n = syscall(SYS_read, fd, buf, size - 1); + syscall(SYS_close, fd); + if (n < 0) return -1; + buf[n] = 0; + return n; +} + +// How many of the app's processes Android counts against its limit (PhantomProcessList): those in an +// app process's cgroup, uid_U/pid_P, other than P. The guest sees only this uid's processes, which +// are the ones it counts. Without a usable /proc, -1. +static int ddh_counted(void) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + int counted = 0; + char buf[4096]; + for (;;) { + long n = syscall(SYS_getdents64, dir, buf, sizeof(buf)); + if (n <= 0) break; + for (long off = 0; off < n;) { + struct ddh_dirent { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (struct ddh_dirent *)(buf + off); + off += d->reclen; + if (d->name[0] < '1' || d->name[0] > '9') continue; + char path[48], cgroup[512]; + snprintf(path, sizeof(path), "/proc/%s/cgroup", d->name); + if (ddh_read_proc(path, cgroup, sizeof(cgroup)) <= 0) continue; + const char *v2 = strstr(cgroup, "0::/uid_"); + const char *app = v2 ? strstr(v2, "/pid_") : NULL; + if (!app) continue; + app += 5; + size_t len = strspn(app, "0123456789"); + if (len > 0 && (len != strlen(d->name) || strncmp(app, d->name, len) != 0)) counted++; + } + } + syscall(SYS_close, dir); + return counted; +} + +static int ddh_waiter(pid_t pid) { + char path[48], name[32]; + snprintf(path, sizeof(path), "/proc/%d/comm", (int)pid); + if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0; + name[strcspn(name, "\n")] = 0; + static const char *const waiters[] = {"bash", "sh", "dash", "zsh", "ksh", "mksh", "fish", "make", "gmake", "xargs"}; + for (size_t i = 0; i < sizeof(waiters) / sizeof(waiters[0]); i++) { + if (strcmp(name, waiters[i]) == 0) return 1; + } + return 0; +} + +// Never handed off for want of room: the Steam client and its launch chain, which the client tracks +// as its own processes (see the docs' "Not handed off" and "Tried and dropped"), however started (the +// arm64 client directly or through env, the x86-64 one through droiddeck-steam-x64). +// +// Nor the quick tools a shell runs for their output: the session's scripts run dozens at a game's start +// (droiddeck-seed-redists alone about 17 within a second), and each would be an app process of its own, +// a zygote fork and a bind, for a few milliseconds of work while the game starts. Counted for those +// milliseconds instead. Only tools that end on their own: not tail (-f), tee, sleep, timeout or env. +static int ddh_pressure_keeps(const char *filename, char *const argv[]) { + static const char *const kept[] = {"steam", "steam.sh", "steamwebhelper", "droiddeck-steam-x64", "reaper", + "steam-launch-wrapper", "pw-audio-namespace", "gamescope", "gamescopereaper"}; + static const char *const quick[] = {"awk", "basename", "cat", "cut", "date", "dirname", "egrep", "expr", "fgrep", + "gawk", "grep", "head", "id", "jq", "ls", "mawk", "mkdir", "mktemp", "pgrep", + "pidof", "printf", "ps", "readlink", "realpath", "rm", "sed", "seq", "sort", + "stat", "touch", "tr", "uname", "uniq", "wc", "xprop"}; + if (filename) { + for (size_t k = 0; k < sizeof(quick) / sizeof(quick[0]); k++) { + if (strcmp(ddh_base(filename), quick[k]) == 0) return 1; + } + } + for (int i = -1; i < 0 || (argv && argv[i]); i++) { + const char *s = i < 0 ? filename : argv[i]; + if (!s) continue; + if (strstr(s, "/Steam/") || strstr(s, "/.steam/")) return 1; + for (size_t k = 0; k < sizeof(kept) / sizeof(kept[0]); k++) { + if (strcmp(ddh_base(s), kept[k]) == 0) return 1; + } + } + return 0; +} + +// Whether this child is a job a shell with job control runs: a child of a shell, in a process group +// other than the shell's. The shell stops, continues and waits for it with WUNTRACED, and a +// handed-off program's stops and continues never reach a wait (they happen to its worker, which is +// not the shell's child), so such a job is never handed off, listed or not. +static int ddh_job_control_job(void) { + pid_t parent = (pid_t)syscall(SYS_getppid); + return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent); +} + +static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) { + if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0; + // Not a job in the foreground of its controlling terminal: a handed-off program has none (the + // worker's setsid()), so /dev/tty, ^C and job control would miss it, whatever its standard fds + // are ("cmd | less", "less < file", output redirected). A job started with & from a shell without + // job control runs in the foreground group reading /dev/null: that one goes. + pid_t fg = 0; + int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty", + O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0); + int foreground = tty >= 0 && syscall(SYS_ioctl, tty, TIOCGPGRP, &fg) == 0 && fg == (pid_t)syscall(SYS_getpgid, 0); + if (tty >= 0) syscall(SYS_close, tty); + if (foreground) { + struct stat st; + if (call_orig_syscall(SYS_fstat, 0, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISCHR(st.st_mode) || + st.st_rdev != makedev(1, 3)) + return 0; + } + return ddh_counted() >= ddh_pressure(envp); +} + +// In a forked child at execve(): hands the program to a worker and exits, or returns to exec it here. +static void ddh_debug(char *const envp[], const char *what, const char *filename) { + const char *debug = ddh_env(envp, "DD_HANDOFF_DEBUG"); + if (!debug) return; + char line[512]; + struct ddh_buf b = {line, 0, sizeof(line) - 1}; + ddh_puts(&b, "ddnatv handoff: "); + ddh_putint(&b, getpid()); + ddh_puts(&b, " "); + ddh_puts(&b, what); + ddh_puts(&b, " "); + ddh_puts(&b, filename ? filename : "?"); + ddh_puts(&b, "\n"); + if (b.len > b.cap) b.len = b.cap; + ddh_log(debug, line, b.len); +} + +// match_file and match_argv are what DD_HANDOFF is matched against; the request carries filename and +// argv. They differ where the exec itself is a start through the system linker (the bionic runtime: +// "/system/bin/linker64 PROGRAM ARGS", tools/bionic-runtime/handoff.c), which is listed by PROGRAM. +static void ddh_try_as(const char *filename, char *const argv[], char *const envp[], const char *match_file, + char *const match_argv[]) { + struct ddh_table *table; + int table_fd; + // one look: the fields are read only once the table is seen published + struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + pid_t own_owner = own ? g_ddh_owner : 0; + if (own && getpid() != own_owner) { + table = own; + table_fd = g_ddh_fd; + } else if (g_ddh_up && (pid_t)syscall(SYS_getppid) == g_ddh_up->pad[0]) { + table = g_ddh_up; + table_fd = g_ddh_up_fd; + } else { + table = NULL; + table_fd = -1; + } + // After a split (here or in the thread that forked this process), the table's number is this + // table's only while it is still kept here: one made later by another thread is in no copy. + if (table_fd >= 0 && (t_kept_split || g_kept_split) && !is_kept_fd(table_fd)) table_fd = -1; + if (table_fd < 0) { + if (ddh_env(envp, "DD_HANDOFF_DEBUG")) { + char why[160]; + snprintf(why, sizeof(why), "not a child its parent can track (table %d owner %d up %d up-owner %d ppid %d):", + own != NULL, (int)own_owner, g_ddh_up != NULL, g_ddh_up ? g_ddh_up->pad[0] : 0, (int)(pid_t)syscall(SYS_getppid)); + ddh_debug(envp, why, filename); + } + return; + } + const char *sock = ddh_env(envp, "DD_SPAWN"); + const char *list = ddh_env(envp, "DD_HANDOFF"); + if (!sock || !list) return; + if (!ddh_forks(0)) { + ddh_debug(envp, "no fork records:", filename); + return; + } + if (access(filename, X_OK) != 0) { + ddh_debug(envp, "not executable here:", filename); + return; + } + if (!ddh_is_table(table_fd, table)) { + ddh_debug(envp, "table fd lost:", filename); + return; + } + // Whatever this exec becomes can still hand off its own exec (a wrapper, a script). + syscall(SYS_fcntl, table_fd, F_SETFD, 0); + if (ddh_job_control_job()) { + ddh_debug(envp, "a job-control job:", filename); + return; + } + if (!ddh_program_listed(list, match_file, match_argv) && !ddh_pressed(match_file, match_argv, envp)) { + ddh_debug(envp, "not listed:", filename); + return; + } + if (!ddh_startable(filename)) { + ddh_debug(envp, "would not start:", filename); + return; + } + if (!ddh_utf8(filename) || !ddh_all_utf8(argv) || !ddh_all_utf8(envp)) { + ddh_debug(envp, "not all UTF-8:", filename); + return; + } + + int fds[DDH_MAX_FDS + 1]; + int nfds = ddh_open_fds(fds, DDH_MAX_FDS, table_fd); + if (nfds < 0) return; + + int slot = -1; + for (int i = 0; i < DDH_SLOTS; i++) { + int expected = DDH_FREE; + if (__atomic_compare_exchange_n(&table->e[i].state, &expected, DDH_CLAIMED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) { + slot = i; + break; + } + } + if (slot < 0) return; + struct ddh_entry *e = &table->e[slot]; + int32_t gen = __atomic_load_n(&e->gen, __ATOMIC_RELAXED) + 1; + __atomic_store_n(&e->gen, gen ? gen : 1, __ATOMIC_RELEASE); + pid_t me = getpid(), parent = (pid_t)syscall(SYS_getppid); + // Before the request: the app checks them before it reports an exit into this entry, which a + // later handoff may have taken over by then. + e->child = me; + e->parent = parent; + e->real = 0; + // One look at the group: waitpid(0) and waitpid(-GROUP) pick the child by it, and the request + // names the group it stands for from it (the parent can move this child meanwhile). + pid_t real_group = getpgrp(); + e->pad[1] = real_group; + e->status = DDH_NO_STATUS; + __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); + e->child_start = ddh_start_time(me); + char cwd[PATH_MAX]; + // The guest's name for it, else the kernel's (the worker's cd takes either). A directory with no + // name (removed) cannot be sent: the exec stays here, in it. + if (!getcwd(cwd, sizeof(cwd))) { + int err = errno; + long n = call_orig_syscall(SYS_getcwd, (unsigned long)cwd, sizeof(cwd), 0, 0, 0, 0); + // Outside this process's root (a program in Steam's runtime container): the rest is the path + // from Android's root, where the worker runs + static const char unreachable[] = "(unreachable)/"; + if (n > 0 && strncmp(cwd, unreachable, sizeof(unreachable) - 1) == 0) + memmove(cwd, cwd + sizeof(unreachable) - 2, strlen(cwd + sizeof(unreachable) - 2) + 1); + if (n <= 0 || cwd[0] != '/') { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + char why[160]; + snprintf(why, sizeof(why), "no name for the working directory (errno %d, then %ld/%d \"%.40s\"):", err, n, + n < 0 ? errno : 0, n > 0 ? cwd : ""); + ddh_debug(envp, why, filename); + return; + } + char why[64]; + snprintf(why, sizeof(why), "kernel name for the working directory (errno %d):", err); + ddh_debug(envp, why, cwd); + } + if (!ddh_utf8(cwd)) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + ddh_debug(envp, "working directory not UTF-8:", cwd); + return; + } + // What the program would have inherited here and a worker does not have: ignored signals, the + // open-files limit, the umask (ddh_apply_inherited() restores them in the program). + unsigned long ignored = 0; + for (int sig = 1; sig < 32; sig++) { + struct sigaction sa; + if (sigaction(sig, NULL, &sa) == 0 && sa.sa_handler == SIG_IGN) ignored |= 1UL << (sig - 1); + } + struct rlimit nofile = {0, 0}; + getrlimit(RLIMIT_NOFILE, &nofile); + mode_t mask = umask(0); + umask(mask); + sigset_t blocked; + pid_t anchor = getenv("DDH_WORKER_PID") ? (pid_t)atoi(getenv("DDH_WORKER_PID")) : parent; + long parent_start = ddh_start_time(parent), anchor_start = ddh_start_time(anchor); + pid_t group = ddh_logical_group(real_group); + unsigned long blocked_bits = 0; + if (sigprocmask(SIG_BLOCK, NULL, &blocked) == 0) { + for (int sig = 1; sig <= 64 && sig < NSIG; sig++) { + if (sigismember(&blocked, sig) == 1) blocked_bits |= 1UL << (sig - 1); + } + } + + struct ddh_buf b = {0}; + for (int pass = 0; pass < 2; pass++) { + b.len = 0; + ddh_puts(&b, "{\"file\":"); + ddh_putstr(&b, filename); + ddh_puts(&b, ",\"argv\":"); + ddh_putarray(&b, argv); + ddh_puts(&b, ",\"envlist\":"); + ddh_putarray(&b, envp); + ddh_puts(&b, ",\"cwd\":"); + ddh_putstr(&b, cwd); + ddh_puts(&b, ",\"fds\":["); + for (int i = 0; i < nfds; i++) { + if (i) ddh_put(&b, ",", 1); + ddh_putint(&b, fds[i]); + } + ddh_puts(&b, "],\"fdchunks\":"); + ddh_putint(&b, DDH_FDS_PER_CHUNK); + ddh_puts(&b, ",\"table\":"); + ddh_putint(&b, nfds); + ddh_puts(&b, ",\"slot\":"); + ddh_putint(&b, slot); + ddh_puts(&b, ",\"parent\":"); + ddh_putint(&b, parent); + ddh_puts(&b, ",\"child\":"); + ddh_putint(&b, me); + ddh_puts(&b, ",\"sigign\":"); + ddh_putint(&b, (long)ignored); + ddh_puts(&b, ",\"nofile\":"); + ddh_putint(&b, (long)nofile.rlim_cur); + ddh_puts(&b, ",\"nofilemax\":"); + ddh_putint(&b, (long)nofile.rlim_max); + ddh_puts(&b, ",\"umask\":"); + ddh_putint(&b, (long)mask); + ddh_puts(&b, ",\"pgid\":"); + ddh_putint(&b, (long)group); + // the session it belongs to (DD_SPAWN_SESSION), which the app starts it for, not a later one + const char *session = ddh_env(envp, "DD_SPAWN_SESSION"); + if (session && *session >= '1' && *session <= '9') { + ddh_puts(&b, ",\"session\":"); + ddh_putint(&b, strtol(session, NULL, 10)); + } + ddh_puts(&b, ",\"sigmask\":"); + ddh_putint(&b, (long)blocked_bits); + ddh_puts(&b, ",\"anchor\":"); + ddh_putint(&b, (long)anchor); + // their start times now, while both are surely the ones meant (see ddh_logical_parent) + ddh_puts(&b, ",\"pstart\":"); + ddh_putint(&b, parent_start); + ddh_puts(&b, ",\"astart\":"); + ddh_putint(&b, anchor_start); + // the worker runs the program only once this side has its pid (the "go" below) + ddh_puts(&b, ",\"ack\":true}"); + if (pass == 0) { + b.cap = b.len + 4; + b.p = mmap(NULL, b.cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (b.p == MAP_FAILED) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + return; + } + } + } + fds[nfds] = table_fd; + + long pid = -1; + int s = (int)syscall(SYS_socket, AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + size_t namelen = strlen(sock); + if (s >= 0 && namelen + 1 < sizeof(addr.sun_path)) { + memcpy(addr.sun_path + 1, sock, namelen); + socklen_t alen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + namelen); + if (syscall(SYS_connect, s, &addr, alen) == 0) { + uint32_t len = (uint32_t)b.len; + unsigned char header[4] = {(unsigned char)(len >> 24), (unsigned char)(len >> 16), (unsigned char)(len >> 8), (unsigned char)len}; + long sent = 0; + while (sent < (long)(b.len + 4)) { + long more = sent < 4 ? syscall(SYS_sendto, s, header + sent, 4 - sent, MSG_NOSIGNAL, NULL, 0) + : syscall(SYS_sendto, s, b.p + (sent - 4), b.len + 4 - sent, MSG_NOSIGNAL, NULL, 0); + if (more <= 0) break; + sent += more; + } + // Then the fds, at most DDH_FDS_PER_CHUNK with each byte: the app's LocalSocket takes + // no more than 64 fds in one read. + for (int at = 0; sent == (long)(b.len + 4) && at < nfds + 1; at += DDH_FDS_PER_CHUNK) { + int count = nfds + 1 - at < DDH_FDS_PER_CHUNK ? nfds + 1 - at : DDH_FDS_PER_CHUNK; + char marker = 'F'; + struct iovec iov = {&marker, 1}; + char control[CMSG_SPACE(sizeof(int) * DDH_FDS_PER_CHUNK)]; + struct msghdr msg = {.msg_iov = &iov, .msg_iovlen = 1, .msg_control = control, + .msg_controllen = CMSG_SPACE(sizeof(int) * count)}; + struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); + cm->cmsg_level = SOL_SOCKET; + cm->cmsg_type = SCM_RIGHTS; + cm->cmsg_len = CMSG_LEN(sizeof(int) * count); + memcpy(CMSG_DATA(cm), fds + at, sizeof(int) * count); + if (syscall(SYS_sendmsg, s, &msg, MSG_NOSIGNAL) != 1) sent = -1; + } + if (sent == (long)(b.len + 4)) { + char reply[64]; + size_t got = 0; + while (got < sizeof(reply) - 1) { + long r = syscall(SYS_read, s, reply + got, 1); + if (r < 0 && errno == EINTR) continue; // the program may already be running + if (r <= 0 || reply[got] == '\n') break; + got++; + } + reply[got] = 0; + if (strncmp(reply, "pid ", 4) == 0) pid = atol(reply + 4); + // Without it the app does not let the worker run the program, and it runs here. + if (pid > 0 && syscall(SYS_sendto, s, "go\n", 3, MSG_NOSIGNAL, NULL, 0) != 3) pid = -1; + // Then the app's last word, once the worker has taken the program on: "ok", or it + // never runs there and runs here. + if (pid > 0) { + char last[32]; + size_t have = 0; + while (have < sizeof(last) - 1) { + long r = syscall(SYS_read, s, last + have, 1); + if (r < 0 && errno == EINTR) continue; + if (r <= 0 || last[have] == '\n') break; + have++; + } + last[have] = 0; + if (strcmp(last, "ok") != 0) pid = -1; + } + } + } + } + if (s >= 0) syscall(SYS_close, s); + munmap(b.p, b.cap); + if (pid <= 0) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + ddh_debug(envp, "spawner refused", filename); + return; + } + e->child = me; + e->parent = parent; + e->real = (int32_t)pid; + e->reaped = 0; + int expected = DDH_CLAIMED; + // the app may already have written DDH_EXITED for a program that ended at once + __atomic_compare_exchange_n(&e->state, &expected, DDH_HANDED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + // Tests only ("FD"): the forked child waits for a byte on FD before it exits, as one descheduled + // here would, while its program's exit may already be in the table. + const char *hold = ddh_env(envp, "DDH_TEST_SHIM_HOLD"); + char *end = NULL; + long hold_fd = hold && *hold ? strtol(hold, &end, 10) : -1; + if (hold_fd > 0 && hold_fd < INT_MAX && end && *end == 0) { + char c; + while (syscall(SYS_read, (int)hold_fd, &c, 1) < 0 && errno == EINTR) {} + } + syscall(SYS_exit_group, 0); +} + +static void ddh_try(const char *filename, char *const argv[], char *const envp[]) { + ddh_try_as(filename, argv, envp, filename, argv); +} + +// ---- the parent's side ----------------------------------------------------------------------- + +static struct ddh_entry *ddh_find(pid_t child) { + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || child <= 0) return NULL; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &g_ddh->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->parent == me && e->child == child) return e; + } + return NULL; +} + +// Whether e's forked child is reaped. A wait marks it with the generation e had when the wait found it +// (ddh_mark_reaped()), so a mark that comes after the slot went to a later handoff, the wait having +// been held up between its reap and the mark, marks nothing: the later child still counts as not +// reaped, and a reap of it later finds it or ECHILD, which is the same. +static int ddh_reaped(const struct ddh_entry *e) { + int32_t mark = __atomic_load_n(&e->reaped, __ATOMIC_ACQUIRE); + return mark != 0 && mark == __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE); +} + +static void ddh_mark_reaped(struct ddh_entry *e, int32_t gen) { __atomic_store_n(&e->reaped, gen, __ATOMIC_RELEASE); } + +// The generation of e, the entry of child: 0 when the slot has gone to another child meanwhile. +static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) { + int32_t gen = __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE); + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0; +} + +// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it. +static int ddh_take(struct ddh_entry *e) { + int expected = DDH_EXITED; + return __atomic_compare_exchange_n(&e->state, &expected, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE); +} + +// Gives a taken exit back, for a later wait (its forked child is not reaped yet). +static void ddh_untake(struct ddh_entry *e) { __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); } + +// 1 alive, 0 exited, -1 not known (/proc could not be read, out of fds say) +static int ddh_thread_alive(pid_t thread) { + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)thread); + int saved = errno; + long n = ddh_read_proc(path, stat, sizeof(stat)); + int failed = errno; + errno = saved; + if (n <= 0) return failed == ENOENT || failed == ESRCH ? 0 : -1; + char *s = strrchr(stat, ')'); + return s && s[1] == ' ' && s[2] != 'Z' && s[2] != 'X'; +} + +// The first live thread of the group, in its thread list's order (which /proc/self/task lists), +// as the kernel picks a new parent for an exited thread's children (find_alive_thread()); 0 when +// /proc cannot say. +static pid_t ddh_first_live_thread(void) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return 0; + pid_t found = 0; + int unknown = 0; + char buf[2048]; + for (long n; !found && !unknown && (n = syscall(SYS_getdents64, dir, buf, sizeof(buf))) > 0;) { + for (long off = 0; off < n && !found && !unknown;) { + struct ddh_task_dirent { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (struct ddh_task_dirent *)(buf + off); + off += d->reclen; + pid_t tid = (pid_t)atoi(d->name); + int alive = tid > 0 ? ddh_thread_alive(tid) : 0; + if (alive < 0) unknown = 1; + else if (alive > 0) found = tid; + } + } + syscall(SYS_close, dir); + return unknown ? 0 : found; +} + +// The thread a child's exit goes to now: the one that forked it while that lives, then the one the +// kernel moved it to, the group's first live thread. Only an exit /proc confirms moves it: when /proc +// cannot say, the forking thread keeps it. +static pid_t ddh_child_owner(const struct ddh_entry *e) { + pid_t thread = ddh_forking_thread(e->child, (long)e->child_start); + if (thread <= 0 || ddh_thread_alive(thread) != 0) return thread; + pid_t heir = ddh_first_live_thread(); + return heir > 0 ? heir : thread; +} + +// Whether a wait for pid (-1: any child, 0: one in our group, -G: one in group G) takes e's child. +static int ddh_selects(const struct ddh_entry *e, pid_t pid) { + if (t_ddh_only_thread) { + // Not this thread's, or not known yet (the fork is still being recorded): not for this wait. + if (ddh_child_owner(e) != t_ddh_only_thread) return 0; + } + if (pid > 0) return e->child == pid; + if (pid == -1) return 1; + return e->pad[1] == (pid == 0 ? getpgrp() : -pid); +} + +static void ddh_release(struct ddh_entry *e, int *status); + +// A new child of ours got pid: an entry naming it for an earlier process (its forked child reaped +// early, as the wait above does, so the pid was free again) stands for a program the pid no longer +// reaches. The real child owns the pid from now on: kill() and wait() go to it, and that program's +// exit is dropped. Only after the pid space has wrapped around while that program runs. Told apart by +// start time, not by the reaped flag: another thread may have reaped that forked child and not yet +// marked it, and the new child may already have handed off a program of its own under the pid. +// Without both start times (the new child already reaped too) nothing is dropped: an entry of the +// new child's own must not be, and a stale one needs the pid space to wrap besides. +static void ddh_drop_stale(pid_t pid) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t || pid <= 0) return; + pid_t me = getpid(); + long start = -2; // read once, when an entry names the pid + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st != DDH_HANDED && st != DDH_EXITED) || e->parent != me || e->child != pid) continue; + if (start == -2) start = ddh_start_time(pid); + if (e->child_start < 0 || start < 0 || e->child_start == start) continue; + if (__atomic_compare_exchange_n(&e->state, &st, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) + ddh_release(e, NULL); + } +} + +// Tests only ("FD TID"): holds the record of thread TID's forks until a byte can be read from FD, as a +// parent thread descheduled between its fork and the record would be. +static void ddh_record_gate(void) { + const char *gate = getenv("DDH_TEST_RECORD_GATE"), *tid = gate ? strchr(gate, ' ') : NULL; + if (!tid || atoi(tid + 1) != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c; + while (syscall(SYS_read, atoi(gate), &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + +// A new child at pid, which recorded itself (a fork() child) or is recorded here (a spawned one) +static void ddh_child_created(pid_t pid, int recorded) { + if (pid <= 0) return; + ddh_record_gate(); + ddh_drop_stale(pid); + // only where children can hand off + if (!recorded && __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) ddh_forked_by(pid, (pid_t)syscall(SYS_gettid)); +} + +// Takes e's exit for a wait for pid, checked again once taken: between finding e and taking it, +// another waiter may have released the slot and a later child of ours (or one of another group) +// have exited in it. +static int ddh_take_for(struct ddh_entry *e, pid_t pid) { + if (!ddh_take(e)) return 0; + if (e->parent == getpid() && ddh_selects(e, pid)) return 1; + ddh_untake(e); + return 0; +} + +static int ddh_any_live(pid_t pid) { + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return 0; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &g_ddh->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN || st == DDH_CLAIMED) && e->parent == me && ddh_selects(e, pid)) return 1; + } + return 0; +} + +// The entry of child while it is still handing its program off (its request is with the app). +static struct ddh_entry *ddh_claiming(pid_t child) { + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || child <= 0) return NULL; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &g_ddh->e[i]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_CLAIMED && e->parent == me && e->child == child) return e; + } + return NULL; +} + +// A worker that is gone with no status from the app (it crashed with the app): reported as killed. +// A worker that is gone: its program's end as the app reported it (a signal), else, with no report +// after a while (the app crashed with it), as killed. +static void ddh_check_gone(void) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t) return; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_HANDED || e->parent != me) continue; + pid_t child = e->child; + if (syscall(SYS_kill, e->real, 0) == 0 || errno != ESRCH) continue; + int32_t report[2]; + uint64_t both = __atomic_load_n((uint64_t *)e->app, __ATOMIC_ACQUIRE); + memcpy(report, &both, sizeof(report)); + int32_t status = SIGKILL; + if (report[1] == child && report[1] != 0) { + status = report[0]; + } else { + // The app looks the status up for up to a second after the worker's death: wait longer. + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + // The time is kept with the child it is for: a slot taken over since by another child + // starts its own count. + uint64_t seen = __atomic_load_n(&e->gone, __ATOMIC_ACQUIRE); + if ((uint32_t)(seen >> 32) != (uint32_t)child) { + uint64_t mark = (uint64_t)(uint32_t)child << 32 | (uint32_t)(now.tv_sec + 1); + __atomic_compare_exchange_n(&e->gone, &seen, mark, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + continue; + } + if (now.tv_sec + 1 - (int64_t)(uint32_t)seen < 3) continue; + } + // Only this side moves HANDED to EXITED, the entry held meanwhile and still the child looked at: + // a waiter may have finished with it and a new handoff taken the slot since the look above. + int expected = DDH_HANDED; + if (!__atomic_compare_exchange_n(&e->state, &expected, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) continue; + if (e->child != child || e->parent != me) { + __atomic_store_n(&e->state, DDH_HANDED, __ATOMIC_RELEASE); + continue; + } + // a status the program wrote itself is kept + int32_t none = DDH_NO_STATUS; + if (__atomic_compare_exchange_n(&e->status, &none, status, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED) && + report[1] != child) + e->guessed = 1; // an app report that comes before the exit is taken wins (ddh_status) + __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); + } +} + +static int ddh_status(const struct ddh_entry *e) { + if (!e->guessed) return e->status; + // SIGKILL was the timeout's guess (no report then): the app's report, if it has come since + int32_t report[2]; + uint64_t both = __atomic_load_n((const uint64_t *)e->app, __ATOMIC_ACQUIRE); + memcpy(report, &both, sizeof(report)); + return report[1] != 0 && report[1] == e->child ? report[0] : e->status; +} + +static void ddh_release(struct ddh_entry *e, int *status) { + if (status) *status = ddh_status(e); + memset(e, 0, offsetof(struct ddh_entry, state)); + e->status = 0; + e->reaped = 0; + e->pad[0] = 0; + e->pad[1] = 0; + e->guessed = 0; + __atomic_store_n(&e->gone, 0, __ATOMIC_RELAXED); + __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); +} + +typedef pid_t (*ddh_wait4_f)(pid_t, int *, int, struct rusage *); + +static ddh_wait4_f ddh_real_wait4(void) { + static ddh_wait4_f f; + if (!f) f = (ddh_wait4_f)dlsym(RTLD_NEXT, "wait4"); + return f; +} + +// A wait interrupted by a signal: as the real call, which a handler installed with SA_RESTART restarts. +// The app's and the program's SIGCHLD are the usual ones. +// Tests only ("IN OUT TID"): thread TID's wait, once its look has found a child, writes a byte to OUT +// and waits for one on IN, as a waiter descheduled before it takes that child would. +static void ddh_wait_gate(int code) { + const char *gate = getenv("DDH_TEST_WAIT_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 = (char)code; // the event it found (CLD_EXITED, CLD_STOPPED...) + syscall(SYS_write, out, &c, 1); + while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + +// The forked child of an entry whose program has exited: 1 once reaped (or already gone), 0 when it is +// still exiting and WNOHANG was asked for, or the wait was interrupted. Gone means another wait reaped +// it, and that one never reports it (ddh_wait()). +// Tests only ("IN OUT TID"): as ddh_wait_gate(), once thread TID's wait has reaped a forked child +// that handed its program off and before it marks the entry. +static void ddh_reap_gate(void) { + const char *gate = getenv("DDH_TEST_REAP_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 ddh_reap_shim(ddh_wait4_f real, struct ddh_entry *e, pid_t child, int options) { + (void)e; + pid_t r = real(child, NULL, options & (WNOHANG | __WALL | __WNOTHREAD), NULL); + return r == child || (r < 0 && errno == ECHILD); +} + +// The program of an exited entry a wait for pid takes: its pid and status, the entry released (or +// left for the next wait when keep), or 0 when none is ready. Every exited entry, not just the first: +// one whose forked child is still exiting is skipped (the caller's real wait reaps that exit, or a +// later pass does) and the next one may be ready. +static pid_t ddh_reap_exited(ddh_wait4_f real, pid_t pid, int *status, int keep, int flags) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + for (int i = 0; t && i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_EXITED || !ddh_take_for(e, pid)) continue; + pid_t child = e->child; + if (!ddh_reaped(e) && !ddh_reap_shim(real, e, child, WNOHANG | flags)) { + ddh_untake(e); + continue; + } + ddh_mark_reaped(e, __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE)); + if (keep) { + if (status) *status = ddh_status(e); + ddh_untake(e); + } else { + ddh_release(e, status); + } + return child; + } + return 0; +} + +// 20 ms, or -1 (EINTR) when a signal's handler interrupted it. The read of a timerfd restarts, as a +// wait does, after a handler installed with SA_RESTART; nanosleep() never does. +static int ddh_nap(void) { + pthread_testcancel(); // as the wait it stands for would be: nothing is held here + int fd = (int)syscall(SYS_timerfd_create, CLOCK_MONOTONIC, O_CLOEXEC); + if (fd < 0) { + struct timespec ts = {0, 20 * 1000 * 1000}; + nanosleep(&ts, NULL); + return 0; + } + struct itimerspec when = {{0, 0}, {0, 20 * 1000 * 1000}}; + uint64_t ticks; + long r = syscall(SYS_timerfd_settime, fd, 0, &when, NULL) == 0 ? syscall(SYS_read, fd, &ticks, sizeof(ticks)) : 0; + int err = errno; + syscall(SYS_close, fd); + if (r < 0 && err == EINTR) { + errno = EINTR; + return -1; + } + return 0; +} + +static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { + ddh_wait4_f real = ddh_real_wait4(); + if (!real) { + errno = ENOSYS; + return -1; + } + // As waitid(): the kernel's alone for options it refuses (WNOWAIT among them), for __WCLONE + // alone, which selects no forked child, and for INT_MIN, a group it refuses (ESRCH) + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || pid == INT_MIN || + (options & ~(WNOHANG | WUNTRACED | WCONTINUED | __WALL | __WNOTHREAD | __WCLONE)) || + ((options & __WCLONE) && !(options & __WALL))) + return real(pid, status, options, ru); + // After a nap a signal interrupted, one more look before EINTR: the signal may be the SIGCHLD + // that reports an exit. + int interrupted = 0; + for (;;) { + ddh_check_gone(); + // with __WNOTHREAD, another thread's child is not one this wait may take (ddh_selects()) + struct ddh_entry *e = pid > 0 ? ddh_find(pid) : NULL; + if (e && !ddh_selects(e, pid)) e = NULL; + if (pid > 0 && e) { + int32_t gen = ddh_gen_of(e, pid); + if (gen && !ddh_reaped(e) && real(pid, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL) == pid) + ddh_mark_reaped(e, gen); + if (ddh_take_for(e, pid)) { + // the forked child is between its last write and its exit: reap it first, or a later + // wait() would report its pid a second time (not blocking for WNOHANG: then later) + if (!ddh_reaped(e) && !ddh_reap_shim(real, e, pid, options)) { + ddh_untake(e); + return (options & WNOHANG) ? 0 : -1; + } + if (ru) memset(ru, 0, sizeof(*ru)); + ddh_release(e, status); + return pid; + } + if (options & WNOHANG) return 0; + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; + continue; + } + pid_t done = pid <= 0 ? ddh_reap_exited(real, pid, status, 0, options & (__WALL | __WNOTHREAD)) : 0; + if (done > 0) { + if (ru) memset(ru, 0, sizeof(*ru)); + return done; + } + int live = pid <= 0 && ddh_any_live(pid); + // A look first (WNOWAIT), then the reap of the child it found alone. A forked child that + // handed its program off is only ever reaped here, never reported, however late this wait gets + // to it: another wait may have reported its program already. + idtype_t type = pid > 0 ? P_PID : pid == -1 ? P_ALL : P_PGID; + id_t id = pid > 0 ? (id_t)pid : pid == 0 ? (id_t)syscall(SYS_getpgid, 0) : (id_t)-pid; + int look = WEXITED | WNOWAIT | (options & (__WALL | __WNOTHREAD | __WCLONE)) | + ((options & WUNTRACED) ? WSTOPPED : 0) | ((options & WCONTINUED) ? WCONTINUED : 0) | + ((live || (options & WNOHANG)) ? WNOHANG : 0); + siginfo_t seen; + memset(&seen, 0, sizeof(seen)); + // libc's waitid(): a blocking look stays a cancellation point, as the wait4() it stands for is + static int (*libc_waitid)(idtype_t, id_t, siginfo_t *, int); + if (!libc_waitid) libc_waitid = (int (*)(idtype_t, id_t, siginfo_t *, int))dlsym(RTLD_NEXT, "waitid"); + pid_t r = libc_waitid ? libc_waitid(type, id, &seen, look) + : (pid_t)call_orig_syscall(SYS_waitid, (unsigned long)type, (unsigned long)id, (unsigned long)&seen, + (unsigned long)look, 0, 0); + if (r == 0 && seen.si_pid > 0) { + pid_t child = seen.si_pid; + ddh_wait_gate(seen.si_code); + // A stop or a continue reaps nothing: reported as it is, the entry and the claim left alone + int ended = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED; + struct ddh_entry *h = ended ? ddh_find(child) : NULL; + int32_t gen = h ? ddh_gen_of(h, child) : 0; + if (gen && !ddh_reaped(h)) { + real(child, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL); + ddh_reap_gate(); + ddh_mark_reaped(h, gen); // the forked child that handed its program off + continue; + } + int wstatus = 0; + if (!ended) { + // Only the kind of event looked at: the child may have gone on since, handed its + // program off and exited, and a wait4() would take that exit, the forked child's. + siginfo_t got; + struct rusage usage; + memset(&got, 0, sizeof(got)); + memset(&usage, 0, sizeof(usage)); + int kind = seen.si_code == CLD_CONTINUED ? WCONTINUED : WSTOPPED; + if (call_orig_syscall(SYS_waitid, P_PID, (unsigned long)child, (unsigned long)&got, + (unsigned long)(kind | WNOHANG | (options & (__WALL | __WNOTHREAD))), (unsigned long)&usage, + 0) != 0 || + got.si_pid != child) + continue; // another wait took it + // as wait4() has it: a stop's whole code (a ptrace event's bits above the signal too) + wstatus = got.si_code == CLD_CONTINUED ? 0xffff : (got.si_status << 8) | 0x7f; + if (ru) *ru = usage; + if (status) *status = wstatus; + return child; + } + r = real(child, &wstatus, options | WNOHANG, ru); + if (r != child) continue; // another wait took it + // A forked child that died while handing its program off (a signal): its entry is done. + if ((WIFEXITED(wstatus) || WIFSIGNALED(wstatus)) && (h = ddh_claiming(r))) ddh_release(h, NULL); + if (status) *status = wstatus; + return r; + } + // No child left: a handoff may have claimed its entry since the look above, and another + // waiter reaped its forked child. The program still runs, so this wait goes on. + if (!live && r < 0 && errno == ECHILD) { + struct ddh_entry *c = pid > 0 ? ddh_find(pid) : NULL, *k = pid > 0 ? ddh_claiming(pid) : NULL; + live = pid > 0 ? (c && ddh_selects(c, pid)) || (k && ddh_selects(k, pid)) : ddh_any_live(pid); + errno = ECHILD; + } + if (!live) return r; + if (r < 0 && errno != ECHILD) return r; + if (options & WNOHANG) return 0; + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; + } +} + +// The wait's own selector, the one before it given back after: a wait from a signal's handler +// leaves the one it interrupted as it was. +static pid_t ddh_wait_as_thread(pid_t pid, int *status, int options, struct rusage *ru) { + pid_t outer = t_ddh_only_thread; + t_ddh_only_thread = (options & __WNOTHREAD) ? (pid_t)syscall(SYS_gettid) : 0; + pid_t r = ddh_wait(pid, status, options, ru); + int saved = errno; + t_ddh_only_thread = outer; + errno = saved; + return r; +} + +pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru) { return ddh_wait_as_thread(pid, status, options, ru); } +pid_t waitpid(pid_t pid, int *status, int options) { return ddh_wait_as_thread(pid, status, options, NULL); } +pid_t wait(int *status) { return ddh_wait_as_thread(-1, status, 0, NULL); } +pid_t wait3(int *status, int options, struct rusage *ru) { return ddh_wait_as_thread(-1, status, options, ru); } + +static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { + typedef int (*f_t)(idtype_t, id_t, siginfo_t *, int); + static f_t real; + if (!real) real = (f_t)dlsym(RTLD_NEXT, "waitid"); + if (!real) { + errno = ENOSYS; + return -1; + } + // A wait without exits never takes a forked child's exit for the program's. Invalid option bits + // (which the kernel refuses), __WCLONE alone (which selects no forked child) and group 1 (init's, + // which a waitpid() selector of -1 would take for any child): the real call. __WALL and + // __WNOTHREAD go along with each call made here. + int carried = options & (__WALL | __WNOTHREAD); + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !(options & WEXITED) || + (options & ~(WEXITED | WSTOPPED | WCONTINUED | WNOHANG | WNOWAIT | __WALL | __WNOTHREAD | __WCLONE)) || + ((options & __WCLONE) && !(options & __WALL)) || + (idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || (idtype == P_PGID && id == 1)) + return real(idtype, id, info, options); + if ((idtype == P_PID && (pid_t)id <= 0) || (idtype == P_PGID && (pid_t)id < 0)) { + errno = EINVAL; + return -1; + } + // As a waitpid() selector: a pid, -1 for any child, 0 for our group, -G for group G + pid_t which = idtype == P_PID ? (pid_t)id : idtype == P_PGID ? (id == 0 ? 0 : -(pid_t)id) : -1; + ddh_wait4_f w4 = ddh_real_wait4(); + // Each event is looked at (WNOWAIT) before it is taken: the forked child of a handed-off program + // exits once the program has started, and that exit is reaped here and never reported. Any other + // event is then taken from that child alone, so the caller gets the kernel's siginfo for it. + int interrupted = 0; + for (;;) { + ddh_check_gone(); + int status = 0; + pid_t r = ddh_reap_exited(w4, which, &status, options & WNOWAIT, carried); + if (r > 0) { + if (info) { + memset(info, 0, sizeof(*info)); + info->si_signo = SIGCHLD; + info->si_pid = r; + info->si_uid = (uid_t)call_orig_syscall(SYS_getuid, 0, 0, 0, 0, 0, 0); // the real one, as the kernel reports, not the root the hook shows + if (WIFEXITED(status)) { + info->si_code = CLD_EXITED; + info->si_status = WEXITSTATUS(status); + } else { + info->si_code = WCOREDUMP(status) ? CLD_DUMPED : CLD_KILLED; + info->si_status = WTERMSIG(status); + } + } + return 0; + } + int live = ddh_any_live(which); + siginfo_t seen; + memset(&seen, 0, sizeof(seen)); + if (real(idtype, id, &seen, options | WNOWAIT | (live ? WNOHANG : 0)) < 0) { + if (errno != ECHILD) return -1; + // a handoff may have claimed its entry since the look above, and another waiter reaped + // its forked child: the program still runs + if (!live && !(live = ddh_any_live(which))) { + errno = ECHILD; + return -1; + } + } else if (seen.si_pid > 0) { + pid_t child = seen.si_pid; + ddh_wait_gate(seen.si_code); + int exited = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED; + struct ddh_entry *h = exited ? ddh_find(child) : NULL; + int32_t gen = h ? ddh_gen_of(h, child) : 0; + if (gen && !ddh_reaped(h)) { + if (w4 && w4(child, NULL, WNOHANG | carried, NULL) == child) + ddh_mark_reaped(h, gen); // the forked child that handed its program off + continue; + } + if (options & WNOWAIT) { + // An exit with no entry found may be a forked child whose entry another wait has + // released since the look, taking it with its program's status: still there now, it + // is no such child (its entry would have been found), else the look starts over. + if (exited) { + siginfo_t again; + memset(&again, 0, sizeof(again)); + if (real(P_PID, (id_t)child, &again, WEXITED | WNOWAIT | WNOHANG | carried) < 0 || again.si_pid != child) + continue; + seen = again; + } + if (info) *info = seen; + return 0; + } + // Only the kind of event looked at: a stop's child may have gone on since, handed its + // program off and exited, and that exit is the forked child's, not one to report. + int kind = exited ? WEXITED : seen.si_code == CLD_CONTINUED ? WCONTINUED : WSTOPPED; + siginfo_t got; + memset(&got, 0, sizeof(got)); + if (real(P_PID, (id_t)child, &got, kind | carried | WNOHANG) < 0 || got.si_pid != child) continue; // another waiter took it + // A forked child that died while handing its program off (a signal): its entry is done. + int died = got.si_code == CLD_EXITED || got.si_code == CLD_KILLED || got.si_code == CLD_DUMPED; + if (died && !ddh_find(child) && (h = ddh_claiming(child))) ddh_release(h, NULL); + if (info) *info = got; + return 0; + } + if (!live || (options & WNOHANG)) { + if (info) memset(info, 0, sizeof(*info)); + return 0; + } + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; + } +} + +int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { + pid_t outer = t_ddh_only_thread; + t_ddh_only_thread = (options & __WNOTHREAD) ? (pid_t)syscall(SYS_gettid) : 0; + int r = ddh_waitid(idtype, id, info, options); + int saved = errno; + t_ddh_only_thread = outer; + errno = saved; + return r; +} + +// Whether pgid is zygote's process group, which every process of the app is in until it starts a +// session of its own: signalling it would reach the app itself. +static int ddh_app_group(pid_t pgid) { + char path[32], name[16] = ""; + snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pgid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, name, sizeof(name) - 1); + syscall(SYS_close, fd); + return n > 0 && strncmp(name, "zygote", 6) == 0; +} + +// A handed-off program runs in a session of its own (the worker's setsid()), out of the process +// group its forked parent's child was in, so a signal to that group (Steam ends a game with one) +// would miss it. Each one is listed here as GROUP.PID.START, GROUP being the group it stands for, +// and a signal to GROUP also goes to the group the program leads. +#define DDH_GROUPS "/run/droiddeck-handoff-groups" + +static long ddh_start_time(pid_t pid) { + char path[64], stat[512]; + // its main thread's, which is the process's: an emulator (qemu-user) answers /proc//stat + // itself, with values of its own, but not the task's file, so a process and its parent read the + // same start time + snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", (int)pid, (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return -1; + stat[n] = 0; + char *p = strrchr(stat, ')'); + // starttime is field 22; after ") " comes field 3 + for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' '); + return p ? atol(p + 1) : -1; +} + +// The group a process stands for: its worker's (DDH_PGID) while it is in the group its worker leads. +static pid_t ddh_logical_group(pid_t real) { + const char *worker = getenv("DDH_WORKER_PID"), *group = getenv("DDH_PGID"); + if (worker && group && real == (pid_t)atoi(worker)) return (pid_t)atoi(group); + return real; +} + +static pid_t ddh_logical_pgrp(void) { return ddh_logical_group(getpgrp()); } + +// Whether parent is still the process that forked the child started at child_start: not gone, not +// exited and waiting to be reaped (the kernel reparents at the exit, not at the reaping), and not a +// later process given the pid, which started after that child. child_start -1: not checked. +// 1 yes, 0 no, -1 when /proc could not be read for another reason (out of fds, say). +static int ddh_parent_lives(pid_t parent, long child_start) { + // The dup2()/dup3() wrappers move the pidfd only under this lock, so no move falls between the + // look and the poll; when another thread holds it, /proc answers instead. + uint64_t all = ~0ull, mask = 0; + int blocked = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) >= 0 && + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0) == 0; + int locked = blocked && pthread_mutex_trylock(&g_ddh_pidfd_lock) == 0; + int held = locked ? __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) : -1; + int fd = held; + if (fd >= 0 && t_kept_split && !is_kept_fd(fd)) { + // a table of its own, where the program took that number over: the spare, if still there + int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE); + fd = spare >= 0 && is_kept_fd(spare) ? spare : -1; + } + if (parent == g_ddh_report_parent && fd >= 0) { + // No new fd, and exited counts whether reaped or not. Only while the number still is that + // pidfd, before and after the poll (a raw close() can take it), and only a clear answer: + // anything else asks /proc. This thread's table, which is not the first thread's after a split. + char path[40], before[32], after[32]; + snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", fd); + int saved = errno; + long len = syscall(SYS_readlinkat, AT_FDCWD, path, before, sizeof(before) - 1); + struct pollfd p = {fd, POLLIN, 0}; + long n = len > 0 ? syscall(SYS_ppoll, &p, 1, &(struct timespec){0, 0}, NULL, 0) : -1; + long len2 = n >= 0 ? syscall(SYS_readlinkat, AT_FDCWD, path, after, sizeof(after) - 1) : -1; + errno = saved; + if (len > 0) before[len] = 0; + if (len2 > 0) after[len2] = 0; + int clear = n >= 0 && len2 > 0 && strcmp(before, "anon_inode:[pidfd]") == 0 && strcmp(after, before) == 0 && + __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) == held && !(p.revents & (POLLNVAL | POLLERR)); + pthread_mutex_unlock(&g_ddh_pidfd_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0); + if (clear) return !(p.revents & POLLIN); + } else { + if (locked) pthread_mutex_unlock(&g_ddh_pidfd_lock); + if (blocked) call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0); + } + char path[48], stat[512]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)parent); + int saved = errno; + long n = ddh_read_proc(path, stat, sizeof(stat)); + int failed = errno; + errno = saved; + // only a parent known gone: a lookup that failed otherwise (out of fds, say) proves nothing (-1) + if (n <= 0) return failed == ENOENT || failed == ESRCH ? 0 : -1; + char *s = strrchr(stat, ')'); + if (!s || s[1] != ' ' || s[2] == 'Z' || s[2] == 'X') return 0; + for (int field = 2; s && field < 22; field++) s = strchr(s + 1, ' '); + long start = s ? atol(s + 1) : -1; + return !(start >= 0 && child_start >= 0 && start > child_start); +} + +// A handed-off program's parent is zygote, which the guest cannot see: a launcher that watches its +// parent through /proc/ took it for gone at once. getppid() answers with the process that +// forked it (DDH_TABLE's parent) while that one lives, and init once it is gone, as after the +// kernel's reparenting. /proc//stat keeps the real parent (see docs, "Tried and dropped"). +pid_t getppid(void) { + pid_t real = (pid_t)syscall(SYS_getppid); + const char *worker = getenv("DDH_WORKER_PID"), *spec = getenv("DDH_TABLE"); + if (!worker || !spec || (pid_t)atoi(worker) != getpid()) return real; + // fd:slot:parent:child + const char *p = strchr(spec, ':'); + p = p ? strchr(p + 1, ':') : NULL; + pid_t parent = p ? (pid_t)atoi(p + 1) : 0; + if (parent <= 0) return real; + long child = g_ddh_report && g_ddh_report_slot >= 0 ? (long)g_ddh_report->e[g_ddh_report_slot].child_start : -1; + return ddh_parent_lives(parent, child) != 0 ? parent : 1; +} + +static char g_ddh_group_entry[96]; +static int g_ddh_parent_entry; + +static int ddh_open_groups(int create) { + char dir[PATH_MAX]; + const char *real_dir = rewrite_path(DDH_GROUPS, dir, sizeof(dir)); + if (create) call_orig_syscall(SYS_mkdirat, (unsigned long)AT_FDCWD, (unsigned long)real_dir, 0755, 0, 0, 0); + return (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real_dir, + O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0); +} + +// Also P, "START PARENT ANCHOR": the process that forked this program's child, the parent it +// has in place of the worker's (see ddh_signal_reaper_tree()), and the worker's program that process +// descends from (DDH_ANCHOR), for when it is gone: Wine starts a process through a fork that exits. +static void ddh_register_group(void) { + if (getpid() != g_ddh_worker) return; + int dir = ddh_open_groups(1); + if (dir < 0) return; + long start = ddh_start_time(getpid()); + char name[96], text[96]; + const char *group = getenv("DDH_PGID"); + if (group) { + snprintf(name, sizeof(name), "%d.%d.%ld", atoi(group), (int)getpid(), start); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)dir, (unsigned long)name, O_WRONLY | O_CREAT | O_CLOEXEC, 0644, 0, 0); + if (fd >= 0) { + syscall(SYS_close, fd); + snprintf(g_ddh_group_entry, sizeof(g_ddh_group_entry), "%s", name); + } + } + if (g_ddh_report_parent > 0) { + snprintf(name, sizeof(name), "P%d", (int)getpid()); + // with their start times: a pid followed later may have been reused by then + // the start times the request recorded (DDH_PSTART, DDH_ASTART): one read now could be a + // reused pid's, the forking process having exited meanwhile + const char *anchor_env = getenv("DDH_ANCHOR"), *pstart = getenv("DDH_PSTART"), *astart = getenv("DDH_ASTART"); + pid_t anchor = anchor_env ? (pid_t)atoi(anchor_env) : g_ddh_report_parent; + int len = snprintf(text, sizeof(text), "%ld %d %d %ld %ld\n", start, (int)g_ddh_report_parent, (int)anchor, + pstart ? atol(pstart) : ddh_start_time(g_ddh_report_parent), + astart ? atol(astart) : ddh_start_time(anchor)); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)dir, (unsigned long)name, + O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644, 0, 0); + if (fd >= 0) { + call_orig_syscall(SYS_write, (unsigned long)fd, (unsigned long)text, (unsigned long)len, 0, 0, 0); + syscall(SYS_close, fd); + g_ddh_parent_entry = 1; + } + } + syscall(SYS_close, dir); +} + +static void ddh_unregister_group(void) { + if ((!g_ddh_group_entry[0] && !g_ddh_parent_entry) || getpid() != g_ddh_worker) return; + int dir = ddh_open_groups(0); + if (dir < 0) return; + if (g_ddh_group_entry[0]) call_orig_syscall(SYS_unlinkat, (unsigned long)dir, (unsigned long)g_ddh_group_entry, 0, 0, 0, 0); + if (g_ddh_parent_entry) { + char name[24]; + snprintf(name, sizeof(name), "P%d", (int)getpid()); + call_orig_syscall(SYS_unlinkat, (unsigned long)dir, (unsigned long)name, 0, 0, 0, 0); + } + syscall(SYS_close, dir); + g_ddh_group_entry[0] = 0; + g_ddh_parent_entry = 0; +} + +// The process that forked pid's child (or, gone, the worker's program it descended from), when pid +// is a handed-off program; else 0. +static pid_t ddh_logical_parent(pid_t pid) { + char path[PATH_MAX], text[96]; + const char *real_dir = rewrite_path(DDH_GROUPS, path, sizeof(path)); + if (real_dir != path) snprintf(path, sizeof(path), "%s", real_dir); + size_t used = strlen(path); + if (used + 16 >= sizeof(path)) return 0; + snprintf(path + used, sizeof(path) - used, "/P%d", (int)pid); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)text, sizeof(text) - 1, 0, 0, 0); + syscall(SYS_close, fd); + if (n <= 0) return 0; + text[n] = 0; + long start = 0, parent_start = -1, anchor_start = -1; + int parent = 0, anchor = 0; + if (sscanf(text, "%ld %d %d %ld %ld", &start, &parent, &anchor, &parent_start, &anchor_start) < 5 || + ddh_start_time(pid) != start) + return 0; + // -1: it was gone already when the program started (Wine forks through one that exits at once) + if (parent > 1 && parent_start >= 0 && ddh_start_time(parent) == parent_start) return (pid_t)parent; + if (anchor > 1 && anchor_start >= 0 && ddh_start_time(anchor) == anchor_start) return (pid_t)anchor; + return 0; +} + +// Signals the groups of the programs standing for group; returns how many took it. +static int ddh_signal_stand_ins(pid_t group, int sig, pid_t done) { + char dir[PATH_MAX]; + const char *real_dir = rewrite_path(DDH_GROUPS, dir, sizeof(dir)); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + char prefix[24], entries[4096]; + int plen = snprintf(prefix, sizeof(prefix), "%d.", (int)group); + int sent = 0; + long n; + while ((n = syscall(SYS_getdents64, fd, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (strncmp(name, prefix, (size_t)plen) != 0) continue; + int real = 0; + long start = 0; + if (sscanf(name + plen, "%d.%ld", &real, &start) != 2 || real <= 1) continue; + if (ddh_start_time(real) != start) { + call_orig_syscall(SYS_unlinkat, (unsigned long)fd, (unsigned long)name, 0, 0, 0, 0); // gone, or its pid reused + continue; + } + if (real == done || ddh_app_group(real)) continue; + if (syscall(SYS_kill, -real, sig) == 0) sent++; + } + } + syscall(SYS_close, fd); + return sent; +} + +static int ddh_kill_group(pid_t pid, int sig) { + pid_t group = pid == 0 ? ddh_logical_pgrp() : -pid; + pid_t own = pid == 0 ? getpgrp() : -pid; + // The caller's own group last: the signal may end the caller. + long ret = -1; + int err = ESRCH; + if (group != own && !ddh_app_group(group) && syscall(SYS_kill, -group, sig) == 0) ret = 0; + if (ddh_signal_stand_ins(group, sig, own) > 0) ret = 0; + if (syscall(SYS_kill, pid, sig) == 0) ret = 0; + else err = errno; + if (ret != 0) errno = err; + return (int)ret; +} + +// The kernel's parent of pid, from /proc//stat; 0 when unknown. +static pid_t ddh_proc_parent(pid_t pid) { + char path[48], stat[512]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + stat[n] = 0; + char *p = strrchr(stat, ')'); + return p && p[1] == ' ' && p[2] && p[3] == ' ' ? (pid_t)atoi(p + 4) : 0; +} + +// Steam's "reaper SteamLaunch AppId=N -- ...", which runs a game's launch. +static int ddh_is_steam_reaper(pid_t pid) { + char path[48], cmd[128]; + snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, cmd, sizeof(cmd) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + cmd[n] = 0; + size_t first = strlen(cmd); + return (size_t)n > first + 1 && strcmp(ddh_base(cmd), "reaper") == 0 && strcmp(cmd + first + 1, "SteamLaunch") == 0; +} + +static int ddh_descends_from(pid_t pid, pid_t ancestor) { + for (int depth = 0; pid > 1 && depth < 64; depth++) { + if (pid == ancestor) return 1; + pid_t up = ddh_logical_parent(pid); + pid = up > 0 ? up : ddh_proc_parent(pid); + } + return 0; +} + +// Steam ends a game by signalling its launch's reaper, which ends every process under it; the +// handed-off ones are not under it, so they (and the groups they lead) get the signal here. All are +// found before any is signalled: one that exits takes its place in the chain of parents with it. +// SIGINT goes as SIGTERM: Wine takes SIGINT for a console's Ctrl+C, which windowed programs ignore. +static void ddh_signal_reaper_tree(pid_t reaper, int sig) { + int dir = ddh_open_groups(0); + if (dir < 0) return; + pid_t found[256]; + int count = 0; + char entries[4096]; + long n; + while ((n = syscall(SYS_getdents64, dir, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (name[0] != 'P' || name[1] < '1' || name[1] > '9') continue; + pid_t pid = (pid_t)atoi(name + 1); + if (count < 256 && ddh_logical_parent(pid) > 0 && ddh_descends_from(pid, reaper)) found[count++] = pid; + } + } + syscall(SYS_close, dir); + for (int i = 0; i < count; i++) syscall(SYS_kill, -found[i], sig == SIGINT ? SIGTERM : sig); +} + +int killpg(int pgrp, int sig) { + if (pgrp < 0) { + errno = EINVAL; + return -1; + } + return kill(-pgrp, sig); +} + +int kill(pid_t pid, int sig) { + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) && pid > 0) { + // A child still handing its program off: the signal is for the program, which the forked + // child (stopped or killed by it) could no longer hand off or account for. Up to 3 s for the + // app's answer; a cold worker start takes well under one. + struct ddh_entry *claim = ddh_claiming(pid); + for (int i = 0; claim && i < 300 && __atomic_load_n(&claim->state, __ATOMIC_ACQUIRE) == DDH_CLAIMED; i++) { + struct timespec ts = {0, 10 * 1000 * 1000}; + nanosleep(&ts, NULL); + } + struct ddh_entry *e = ddh_find(pid); + if (e && __atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_HANDED) pid = e->real; + } + // -1 is every process this one may signal, the app's own among them + if (sig != 0 && (pid == -1 || (pid <= 0 && ddh_app_group(pid == 0 ? getpgrp() : -pid)))) { + errno = EPERM; + return -1; + } + if (pid < -1 || pid == 0) { + if (sig != 0 && getenv("DD_HANDOFF_DEBUG")) { + char line[96]; + int len = snprintf(line, sizeof(line), "ddnatv handoff: %d kill group %d (stands for %d), %d\n", (int)getpid(), + pid == 0 ? (int)getpgrp() : (int)-pid, pid == 0 ? (int)ddh_logical_pgrp() : (int)-pid, sig); + if (len > 0) ddh_log(getenv("DD_HANDOFF_DEBUG"), line, (size_t)len); + } + return ddh_kill_group(pid, sig); + } + if (pid > 1 && (sig == SIGINT || sig == SIGTERM || sig == SIGKILL || sig == SIGHUP) && ddh_is_steam_reaper(pid)) + ddh_signal_reaper_tree(pid, sig); + if (sig != 0 && getenv("DD_HANDOFF_DEBUG")) { + char line[160], comm[32] = "?"; + int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/comm", O_RDONLY | O_CLOEXEC); + if (fd >= 0) { + long n = syscall(SYS_read, fd, comm, sizeof(comm) - 1); + if (n > 0) comm[n - 1] = 0; + syscall(SYS_close, fd); + } + int len = snprintf(line, sizeof(line), "ddnatv handoff: %d (%s) kill(%d, %d)\n", (int)getpid(), comm, (int)pid, sig); + if (len > 0) ddh_log(getenv("DD_HANDOFF_DEBUG"), line, (size_t)len); + } + return (int)syscall(SYS_kill, pid, sig); +} diff --git a/tools/nativeguest/hook/kept.c b/tools/nativeguest/hook/kept.c new file mode 100644 index 0000000000..a25b3813d4 --- /dev/null +++ b/tools/nativeguest/hook/kept.c @@ -0,0 +1,225 @@ +// Part of libddnatv-hook.so, included by ddnatv-hook.c before privileged.c, and of the bionic +// runtime's exec shim (tools/bionic-runtime/handoff.c): the descriptors close(), close_range() and +// closefrom() leave open. + +// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of +// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it +// translates more code: a program that closes every descriptor it did not open (sshd at start, +// 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 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; + +// A thread that split its descriptor table from the others' (close_range() with +// CLOSE_RANGE_UNSHARE) goes on with a copy of the list made at the split, which only it reads and +// changes: the shared list keeps describing the other threads' table, so a kept fd this thread's +// program takes over (a dup2() onto the parent's pidfd) stays kept there. A child it forks takes the +// copy over as its list (kept_forked()). +static __thread int t_kept_split; +static __thread int t_kept_fds[DDNATV_MAX_KEPT_FDS]; +static __thread int t_kept_count; +// In a process forked from such a thread: numbers published for the shared table (the handoff table's) +// may name other files here, or none. +static int g_kept_split; + +static int kept_snapshot(int *out) { + if (t_kept_split) { + for (int i = 0; i < t_kept_count; i++) out[i] = t_kept_fds[i]; + return t_kept_count; + } + 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); } + +// Before anything takes g_kept_lock: a fork() in another thread then waits for it to be let go. +static void kept_register_once(void) { + static pthread_once_t once = PTHREAD_ONCE_INIT; + pthread_once(&once, kept_register_fork); +} + +// 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) { + kept_register_once(); + 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 kept_any(void) { + return t_kept_split ? t_kept_count : __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED); +} + +// The process's threads (/proc/self/stat), or 0 when it cannot be read. +static int kept_threads(void) { + char buf[512]; + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc/self/stat", + O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)buf, sizeof(buf) - 1, 0, 0, 0); + call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0); + if (n <= 0) return 0; + buf[n] = 0; + char *p = strrchr(buf, ')'); + // after the name: state, then 16 fields to num_threads + for (int field = 0; p && field < 18; field++) p = strchr(p + 1, ' '); + return p ? atoi(p + 1) : 0; +} + +// The calling thread's table split by split() (0, or -1 with errno), with the list copied for it in +// the same step: no keep or let-go of another thread falls between the copy and the split. A process +// with one thread keeps one table (the system copies only a shared one), and so one list. Threads that +// a thread with a table of its own starts later share that table but not its copy: not followed. +static int kept_split(int (*split)(void)) { + if (t_kept_split) return split(); + kept_register_once(); + uint64_t all = ~0ull, mask = 0; + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0); + pthread_mutex_lock(&g_kept_lock); + int shared = kept_threads() != 1; + int r = split(); + int saved = errno; + if (r == 0 && shared) { + int n = g_kept_fd_count; + for (int i = 0; i < n; i++) t_kept_fds[i] = g_kept_fds[i]; + t_kept_count = n; + t_kept_split = 1; + } + pthread_mutex_unlock(&g_kept_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0); + errno = saved; + return r; +} + +// In a forked child, whose only thread is the one that forked: a split thread's table is the child's. +static void kept_forked(void) { + if (!t_kept_split) return; + for (int i = 0; i < t_kept_count; i++) g_kept_fds[i] = t_kept_fds[i]; + g_kept_fd_count = t_kept_count; + t_kept_split = 0; + g_kept_split = 1; +} + +static int is_kept_fd(int fd) { + 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, + int (*fn)(unsigned int, unsigned int, void *), void *arg) { + unsigned int from = first; + for (int i = 0; i < nkept && from <= last; i++) { + if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue; + unsigned int k = (unsigned int)kept[i]; + if (k > from) { + int r = fn(from, k - 1, arg); + if (r != 0) return r; + } + if (k == last) return 0; + from = k + 1; + } + return from <= last ? fn(from, last, arg) : 0; +} diff --git a/tools/nativeguest/hook/net.c b/tools/nativeguest/hook/net.c index 69260a4243..de2459b74b 100644 --- a/tools/nativeguest/hook/net.c +++ b/tools/nativeguest/hook/net.c @@ -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 (kept_any() > 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; } diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index a7aa885dd2..2a4a4dc2e1 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -4,41 +4,6 @@ // Calls an app may not make (chown, mknod, capabilities, prctl, landlock, seccomp, namespaces, // close_range) and the generic syscall() entry point. -// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of -// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it -// translates more code: a program that closes every descriptor it did not open (sshd at start, -// 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 -static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending -static int g_kept_fd_count = 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; - } - return 0; -} - -// 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, - int (*fn)(unsigned int, unsigned int, void *), void *arg) { - unsigned int from = first; - for (int i = 0; i < nkept && from <= last; i++) { - if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue; - unsigned int k = (unsigned int)kept[i]; - if (k > from) { - int r = fn(from, k - 1, arg); - if (r != 0) return r; - } - if (k == last) return 0; - from = k + 1; - } - return from <= last ? fn(from, last, arg) : 0; -} - #ifndef DDNATV_HOST_TEST // ndk_translation's file is "/memfd:child"; any memory file counts in a process whose executable is @@ -438,20 +403,67 @@ 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); } +// The system call itself on the one number no fd has (close_range_all() would emulate a missing call +// by closing fds) +static int close_range_unshare(void) { + static long (*raw_syscall)(long, ...) = NULL; + if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall"); + if (!raw_syscall) { + errno = ENOSYS; + return -1; + } + return raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) == 0 ? 0 : -1; +} + +static int close_range_kept(unsigned int first, unsigned int last, int flags) { + // The table is unshared first, once, even when every fd in the range is kept, and this thread + // goes on with its own copy of the kept list (kept_split()). Without the system call, it is + // emulated where nothing is kept, and refused otherwise. + if (flags & CLOSE_RANGE_UNSHARE) { + if (kept_split(close_range_unshare) == 0) flags &= ~CLOSE_RANGE_UNSHARE; + else if (errno != ENOSYS || kept_any() > 0) return -1; + } + // 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); + 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 diff --git a/tools/phantomlab/.gitignore b/tools/phantomlab/.gitignore new file mode 100644 index 0000000000..567609b123 --- /dev/null +++ b/tools/phantomlab/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/tools/phantomlab/AndroidManifest.xml b/tools/phantomlab/AndroidManifest.xml new file mode 100644 index 0000000000..a554bfdda4 --- /dev/null +++ b/tools/phantomlab/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/phantomlab/build.sh b/tools/phantomlab/build.sh new file mode 100644 index 0000000000..a7afcfaa9a --- /dev/null +++ b/tools/phantomlab/build.sh @@ -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" diff --git a/tools/phantomlab/jni/exe.c b/tools/phantomlab/jni/exe.c new file mode 100644 index 0000000000..a87d2a4ede --- /dev/null +++ b/tools/phantomlab/jni/exe.c @@ -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 +#include +#include +#include +#include + +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; +} diff --git a/tools/phantomlab/jni/lab.c b/tools/phantomlab/jni/lab.c new file mode 100644 index 0000000000..811de3facd --- /dev/null +++ b/tools/phantomlab/jni/lab.c @@ -0,0 +1,422 @@ +// Native half of phantomlab: forks sleepers, execs in place, and probes what a process may do. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 : ""); +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java new file mode 100644 index 0000000000..1b10f9e777 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class Iso extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java b/tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java new file mode 100644 index 0000000000..f0ecde6e3a --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class IsoPlain extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java b/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java new file mode 100644 index 0000000000..8987b6cb08 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java @@ -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; + } +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java new file mode 100644 index 0000000000..c65950fa67 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java @@ -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 binders = new HashMap<>(); + private static final Map> pending = new HashMap<>(); + private static final Map 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 sent = new ArrayList<>(); + final List 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 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 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 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 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:, 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; + } +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Native.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Native.java new file mode 100644 index 0000000000..be733615fc --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Native.java @@ -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); +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java new file mode 100644 index 0000000000..2bd3e4145f --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java @@ -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) { + } +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java new file mode 100644 index 0000000000..7bd3578bc8 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class Proc extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W0.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W0.java new file mode 100644 index 0000000000..05fad74dcd --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W0.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W0 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W1.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W1.java new file mode 100644 index 0000000000..8c6e6bf414 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W1.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W1 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W2.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W2.java new file mode 100644 index 0000000000..49e1917e28 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W2.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W2 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W3.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W3.java new file mode 100644 index 0000000000..c9f3aa59c1 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W3.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W3 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W4.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W4.java new file mode 100644 index 0000000000..bfcf489921 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W4.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W4 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W5.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W5.java new file mode 100644 index 0000000000..cf9898db66 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W5.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W5 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W6.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W6.java new file mode 100644 index 0000000000..85999fab6c --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W6.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W6 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W7.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W7.java new file mode 100644 index 0000000000..c9b7dfbe2a --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W7.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W7 extends LabService {} diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index 72931860b7..0e055df0a2 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -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"])) diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py new file mode 100644 index 0000000000..bf4d0e2586 --- /dev/null +++ b/tools/tests/test_native_hook_handoff.py @@ -0,0 +1,2285 @@ +import errno +import fcntl +import json +import os +import select +import shutil +import signal +import socket +import struct +import subprocess +import sys +import tempfile +import termios +import threading +import time +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +CLD_EXITED = 1 + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +# fork() and exec argv[1] with "3", without the hook: prints the exit status it got +EXEC_PROBE = r""" +#include +#include +#include + +int main(int argc, char **argv) { + pid_t pid = fork(); + if (pid == 0) { + execl(argv[1], "target", "3", (char *)NULL); + _exit(127); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid) return 1; + printf("%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + +PARENT = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern char **environ; + +static int gate[2] = {-1, -1}; + +static void open_gate(int sig) { + (void)sig; + if (write(gate[1], "1", 1) != 1) _exit(125); +} + +// nothread: a second thread forks the child; __WNOTHREAD waits see only their own thread's children +static char *nothread_arg; +static int nothread_wrap; +static pthread_mutex_t nothread_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t nothread_cond = PTHREAD_COND_INITIALIZER; +static int nothread_step; +static pid_t nothread_child; + +static void nothread_await(int step) { + pthread_mutex_lock(¬hread_lock); + while (nothread_step < step) pthread_cond_wait(¬hread_cond, ¬hread_lock); + pthread_mutex_unlock(¬hread_lock); +} + +static void nothread_go(int step) { + pthread_mutex_lock(¬hread_lock); + nothread_step = step; + pthread_cond_broadcast(¬hread_cond); + pthread_mutex_unlock(¬hread_lock); +} + +static void *nothread_forker(void *unused) { + (void)unused; + pid_t pid = fork(); + if (pid == 0) { + if (nothread_wrap) execl("/bin/wrap", "wrap", "/bin/target", "target", nothread_arg, (char *)NULL); + execl("/bin/target", "target", nothread_arg, (char *)NULL); + _exit(127); + } + if (pid < 0) _exit(121); + nothread_child = pid; + usleep(1500000); // the program has exited by now + nothread_go(1); + nothread_await(2); + int status = 0; + pid_t r = waitpid(pid, &status, __WNOTHREAD); + printf("own\t%d\n", r == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return NULL; +} + +// laterecord: a program this thread spawns (not listed: glibc's posix_spawn(), recorded by the +// parent) is recorded only once the hook's test gate opens, by when it is gone and a later child of +// the main thread has its pid, handed off and its forked child reaped +static int late_done[2], late_hold[2], late_gate; + +static void *late_spawner(void *unused) { + (void)unused; + char gate[32]; + snprintf(gate, sizeof(gate), "%d %d", late_gate, (int)syscall(SYS_gettid)); + setenv("DDH_TEST_RECORD_GATE", gate, 1); + pid_t pid = 0; + char *args[] = {"wrap", NULL}; // exits at once: nothing to wrap + int err = posix_spawn(&pid, "/bin/wrap", NULL, NULL, args, environ); + if (write(late_done[1], &err, sizeof(err)) != sizeof(err)) _exit(123); // recorded + char c; + if (read(late_hold[0], &c, 1) != 1) _exit(124); // alive while the main thread's wait looks + return NULL; +} + +// Whether the hook's table (at any number here) has child's entry claimed: its handoff is with the app +static int claimed(pid_t child) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[4]; // child, real, parent, state + if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && head[3] == 3) + return 1; + } + } + return 0; +} + +// live 1: the late record is made while the later child is still handing its program off (the fake +// spawner holds its reply), so the start time it reads is that child's. live 2: made once the later +// child has recorded itself, before it execs and starts its handoff. +static int late_record(const char *arg, int live) { + int gate[2]; + if (pipe(gate) != 0 || pipe(late_done) != 0 || pipe(late_hold) != 0) return 1; + late_gate = gate[0]; + pthread_t spawner; + pthread_create(&spawner, NULL, late_spawner, NULL); + // the spawned program, reaped: the only child yet + pid_t first = 0; + int status = 0; + for (int i = 0; i < 3000 && (first = waitpid(-1, &status, WNOHANG)) <= 0; i++) usleep(10000); + if (first <= 0) return 1; + // the next fork gets the pid again + FILE *f = fopen("/proc/sys/kernel/ns_last_pid", "w"); + if (!f) return 1; + fprintf(f, "%d", (int)first - 1); + if (fclose(f) != 0) return 1; + int hold[2], at[2]; + if (live == 2 && (pipe(hold) != 0 || pipe(at) != 0)) return 1; + pid_t pid = fork(); + if (pid == 0) { + if (live == 2) { + // back from fork(), whose hook has recorded it: the parent's word to go on comes after the + // late record + char c = 1; + close(hold[1]); + if (write(at[1], &c, 1) != 1 || read(hold[0], &c, 1) != 1) _exit(126); + } + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + if (pid < 0) return 1; + printf("reused\t%d\n", pid == first); + int err = -1; + if (live == 1) { + int claim = 0; + for (int i = 0; i < 500 && !(claim = claimed(pid)); i++) usleep(10000); + printf("claimed\t%d\n", claim); + if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; + } + if (live == 2) { + char c; + struct pollfd p = {at[0], POLLIN, 0}; + int ready = poll(&p, 1, 10000) == 1 && read(at[0], &c, 1) == 1; + printf("recorded\t%d\n", ready); + if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; + close(hold[0]); + if (write(hold[1], "1", 1) != 1) return 1; + } + // its forked child exits once the program runs: reaped here, the program's exit left alone + char path[64]; + snprintf(path, sizeof(path), "/proc/%d", (int)pid); + for (int i = 0; i < 1000 && access(path, F_OK) == 0; i++) { + waitpid(-1, &status, WNOHANG); + usleep(10000); + } + printf("reaped\t%d\n", access(path, F_OK) != 0); + if (!live && (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err))) return 1; + printf("spawned\t%d\n", err); + printf("own\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WNOTHREAD) == 0); + kill(pid, SIGKILL); + printf("ended\t%d\n", waitpid(pid, &status, 0) == pid && WIFSIGNALED(status)); + if (write(late_hold[1], "1", 1) != 1) return 1; + pthread_join(spawner, NULL); + return 0; +} + +static void *gone_forker(void *unused) { + (void)unused; + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", nothread_arg, (char *)NULL); + _exit(127); + } + if (pid < 0) _exit(121); + nothread_child = pid; + return NULL; // the thread ends: its child goes to the main thread +} + +// nothreadnested: a signal's handler waits, with no __WNOTHREAD, while it interrupts the main +// thread's __WNOTHREAD wait; that wait still takes only the main thread's children afterwards +static void nested_wait(int sig) { + (void)sig; + int status = 0; + int saved = errno; + waitpid(4194303, &status, WNOHANG); // no such child: takes nothing + errno = saved; +} + +// prepclose: another thread's close_range(799, 801) has looked at the kept fds, none of them the +// table's yet, and waits on the hook's test gate while the first fork makes the table at 800 +static int prep_in[2], prep_out[2]; +static long prep_closed = -2; + +static void *prep_closer(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", prep_in[0], prep_out[1], (int)syscall(SYS_gettid)); + setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); + prep_closed = syscall(SYS_close_range, 799, 801, 0); + return NULL; +} + +static int prep_hold_ms = 0; // after the table's fd is kept: past the hook's wait for the close +static int prep_kept[2]; // the hook's word that it has kept the table's fd (DDH_TEST_TABLE_KEPT) +static int prep_acked; + +static void *prep_release(void *unused) { + (void)unused; + // once the first fork has made and kept the table's fd, while it waits for the close to end + struct pollfd p = {prep_kept[0], POLLIN, 0}; + char c; + prep_acked = poll(&p, 1, 10000) == 1 && read(prep_kept[0], &c, 1) == 1; + usleep(prep_hold_ms * 1000); + if (write(prep_in[1], "1", 1) != 1) _exit(122); + return NULL; +} + +// How many of the hook's tables are open here, at any numbers +static int tables_open(void) { + char path[32], target[64]; + int count = 0; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n > 0 && (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) == 0)) count++; + } + return count; +} + +static int table_open(void) { return tables_open() > 0; } + +// nowaitpeek: one thread's waitid(WNOWAIT) has seen the exit of a forked child that handed its +// program off (held there by the hook's wait gate) when another wait takes the program's exit and +// frees the entry; that look reports nothing, not the forked child's exit +static int nowait_in[2], nowait_out[2]; + +static void *nowait_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", nowait_in[0], nowait_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + siginfo_t si; + memset(&si, 0, sizeof(si)); + errno = 0; + int r = waitid(P_ALL, 0, &si, WEXITED | WNOWAIT); + printf("looked\t%d\n", r); + printf("echild\t%d\n", r == -1 && errno == ECHILD); + printf("lookedpid\t%d\n", r == 0 ? (int)si.si_pid : 0); + return NULL; +} + +// twowaits: one thread's wait has found the forked child (held there by the hook's test gate, for +// longer than any other wait would wait for it) when another thread's wait takes the program's exit; +// the child is reported once +static int two_in[2], two_out[2]; + +static void *first_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", two_in[0], two_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + int status = 0; + pid_t r = waitpid(-1, &status, 0); + printf("first\t%d\n", (int)r); + return NULL; +} + +static void *releaser(void *unused) { + (void)unused; + usleep(1500000); // the other wait is under way by now, and has had more than a second + if (write(two_in[1], "1", 1) != 1) _exit(122); + return NULL; +} + +// reapreuse: one thread's wait has reaped the first child's forked child and is held before it marks +// the entry (the hook's reap gate), while the first child is collected, its slot freed, and a second +// child takes the slot; that wait then reports the second child once, with its program's status +static int reuse_in[2], reuse_out[2]; + +static void *reuse_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", reuse_in[0], reuse_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_REAP_GATE", gate, 1); + int status = 0, reports = 0, last = 0, sig = -1; + pid_t r; + while ((r = waitpid(-1, &status, 0)) > 0) { + reports++; + last = r; + sig = WIFSIGNALED(status) ? WTERMSIG(status) : -1; + } + printf("reports\t%d\n", reports); + printf("last\t%d\n", last); + printf("lastsignal\t%d\n", sig); + return NULL; +} + +// stoppeek: one thread's wait for a child stopped while its handoff is with the app has seen the stop +// (held there by the hook's wait gate) when the child goes on, hands its program off and its forked +// child exits; that wait reports the program's exit, not the forked child's +static int peek_in[2], peek_out[2]; +static pid_t peek_child; + +static void *peek_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", peek_in[0], peek_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + int status = 0; + // the stop is gone by the time it takes the event: this one wait reports the program's end + pid_t r = waitpid(peek_child, &status, WUNTRACED); + printf("waited\t%d\n", r == peek_child); + printf("stopped\t%d\n", r == peek_child && WIFSTOPPED(status)); + printf("code\t%d\n", r == peek_child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return NULL; +} + +// Whether pid is a zombie here, its exit not taken (the kernel's word, no wait of any kind) +static int zombie(pid_t pid) { + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + size_t n = fread(stat, 1, sizeof(stat) - 1, f); + fclose(f); + stat[n] = 0; + char *end = strrchr(stat, ')'); + return end && end[1] == ' ' && end[2] == 'Z'; +} + +// A thread's state letter (R, S, Z...), or 0 +static char thread_state(pid_t tid) { + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)tid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + size_t n = fread(stat, 1, sizeof(stat) - 1, f); + fclose(f); + stat[n] = 0; + char *end = strrchr(stat, ')'); + return end && end[1] == ' ' ? end[2] : 0; +} + +// The state of the hook's table entry for child (any table here), or -1 when it has none: a forked +// child of this process when child is 0 (its pid in *found) +static int entry_state_of(pid_t child, pid_t *found) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[4]; // child, real, parent, state + if (pread(fd, head, sizeof(head), 64 + slot * 64) != (ssize_t)sizeof(head) || head[3] == 0) continue; + if (child ? head[0] == child : head[2] == getpid()) { + if (found) *found = head[0]; + return head[3]; + } + } + } + return -1; +} + +// Whether the app's report of child's program (status, child: 32 bytes into its entry) is in the table +static int reported(pid_t child) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[1], report[2]; + if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && + pread(fd, report, sizeof(report), 64 + slot * 64 + 32) == (ssize_t)sizeof(report) && report[1] == child) + return 1; + } + } + return 0; +} + +// nohangtwo: a handed-off child A whose program has exited while its forked child is held (the hook's +// test switch), and a child B that is ready: a WNOHANG wait reports B. kind 0: B ordinary, any child; +// 1: B handed off too (its program exited, its forked child free to go); 2: a wait for our group +// (waitpid(0)), with B ordinary and an exited child D in a group of its own, which it must not take. +static int nohang_two(const char *arg, int kind) { + int hold[2]; + if (pipe(hold) != 0) return 1; + char fd[16]; + snprintf(fd, sizeof(fd), "%d", hold[0]); + setenv("DDH_TEST_SHIM_HOLD", fd, 1); + pid_t a = fork(); + if (a == 0) { + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + if (a < 0) return 1; + unsetenv("DDH_TEST_SHIM_HOLD"); + // exited in the table (2), or handed off (1) with the app's report of its exit in: either is an exit + // the wait's look for exited entries reaches, not a claim (3) still under way + int done = 0; + for (int i = 0; i < 1000 && !done; i++) { + int st = entry_state_of(a, NULL); + done = st == 2 || (st == 1 && reported(a)); + if (!done) usleep(10000); + } + printf("aexited\t%d\n", done); + pid_t d = 0; + if (kind == 2) { + d = fork(); + if (d == 0) { + setpgid(0, 0); + _exit(6); + } + if (d < 0) return 1; + } + pid_t b = fork(); + if (b == 0) { + if (kind == 1) { + execl("/bin/target", "target", "5", (char *)NULL); + _exit(127); + } + _exit(5); + } + if (b < 0) return 1; + int ready = 0; + for (int i = 0; i < 1000 && !ready; i++) { + int st = kind == 1 ? entry_state_of(b, NULL) : 0; + // a handed-off B: its exit in the table and its forked child exited, so nothing holds it back + ready = zombie(b) && (kind != 1 || st == 2 || (st == 1 && reported(b))) && (!d || zombie(d)); + if (!ready) usleep(10000); + } + printf("bwaitable\t%d\n", ready); + char path[32]; + snprintf(path, sizeof(path), "/proc/%d", (int)a); + printf("aheld\t%d\n", access(path, F_OK) == 0 && !zombie(a)); + pid_t which = kind == 2 ? 0 : -1; + int status = 0; + pid_t r = waitpid(which, &status, WNOHANG); + printf("first\t%d\n", r == b); + printf("firstexit\t%d\n", r == b && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (write(hold[1], "1", 1) != 1) return 1; + r = waitpid(which, &status, 0); + printf("second\t%d\n", r == a); + printf("exit\t%d\n", r == a && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (d) { + r = waitpid(d, &status, WNOHANG); + printf("other\t%d\n", r == d && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + } + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; +} + +// reapbeforerecord: a thread forks a listed child and is held before its fork is recorded (the hook's +// record gate); meanwhile another thread's blocking wait reaps the child's forked child and must go +// on waiting for the program, not drop it when the record is made +static int rbr_gate[2]; +static pid_t rbr_pid; // all three read before the join of their writer: atomic +static pid_t rbr_got = -2; +static int rbr_status; + +static void *rbr_forker(void *arg) { + char gate[32]; + snprintf(gate, sizeof(gate), "%d %d", rbr_gate[0], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_RECORD_GATE", gate, 1); + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", (const char *)arg, (char *)NULL); + _exit(127); + } + __atomic_store_n(&rbr_pid, pid, __ATOMIC_RELEASE); + return NULL; +} + +static void *rbr_waiter(void *unused) { + (void)unused; + int status = 0; + pid_t r = waitpid(-1, &status, 0); + rbr_status = status; + __atomic_store_n(&rbr_got, r, __ATOMIC_RELEASE); + return NULL; +} + +static int reap_before_record(const char *arg) { + if (pipe(rbr_gate) != 0) return 1; + pthread_t forker, waiter; + pthread_create(&forker, NULL, rbr_forker, (void *)arg); + pid_t child = 0; + int st = -1; + for (int i = 0; i < 1000 && (st = entry_state_of(0, &child)) != 1; i++) usleep(10000); + int exited = 0; + for (int i = 0; st == 1 && child > 0 && i < 500 && !(exited = zombie(child)); i++) usleep(10000); + int handed = st == 1 && child > 0 && exited; + printf("handed\t%d\n", handed); + if (!handed) { + // no handed-off child to go on with: the forker let go, and nothing signalled + if (write(rbr_gate[1], "1", 1) != 1) return 1; + pthread_join(forker, NULL); + return 0; + } + pthread_create(&waiter, NULL, rbr_waiter, NULL); + char path[32]; + snprintf(path, sizeof(path), "/proc/%d", (int)child); + int reaped = 0; + for (int i = 0; i < 500 && !(reaped = access(path, F_OK) != 0); i++) usleep(10000); + printf("shimreaped\t%d\n", reaped); + printf("unrecorded\t%d\n", __atomic_load_n(&rbr_pid, __ATOMIC_ACQUIRE) == 0); + if (write(rbr_gate[1], "1", 1) != 1) return 1; + pthread_join(forker, NULL); + printf("forked\t%d\n", rbr_pid == child); + usleep(500000); + printf("waiting\t%d\n", __atomic_load_n(&rbr_got, __ATOMIC_ACQUIRE) == -2); + kill(child, SIGTERM); + pthread_join(waiter, NULL); + printf("got\t%d\n", rbr_got == child); + printf("signal\t%d\n", rbr_got == child && WIFSIGNALED(rbr_status) ? WTERMSIG(rbr_status) : -1); + return 0; +} + +// waitidblocked: the child holds before its exec until the parent's waitid(P_PID) has been seen blocked +// (its thread asleep) with no entry claimed yet, so the wait begins before the handoff exists +static siginfo_t wb_info; // read only after the join +static int wb_done = -2; // these two polled meanwhile: atomic +static pid_t wb_tid; +static pid_t wb_child; + +static void *wb_waiter(void *unused) { + (void)unused; + memset(&wb_info, 0, sizeof(wb_info)); + __atomic_store_n(&wb_tid, (pid_t)syscall(SYS_gettid), __ATOMIC_RELEASE); + int r = waitid(P_PID, (id_t)wb_child, &wb_info, WEXITED); + __atomic_store_n(&wb_done, r, __ATOMIC_RELEASE); + return NULL; +} + +static int waitid_blocked(const char *arg) { + int go[2]; + if (pipe(go) != 0) return 1; + wb_child = fork(); + if (wb_child == 0) { + char c; + close(go[1]); + if (read(go[0], &c, 1) != 1) _exit(126); + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + if (wb_child < 0) return 1; + close(go[0]); + pthread_t waiter; + pthread_create(&waiter, NULL, wb_waiter, NULL); + int asleep = 0; + for (int i = 0; i < 500 && asleep < 10; i++) { + usleep(20000); + pid_t tid = __atomic_load_n(&wb_tid, __ATOMIC_ACQUIRE); + asleep = tid && __atomic_load_n(&wb_done, __ATOMIC_ACQUIRE) == -2 && thread_state(tid) == 'S' ? asleep + 1 : 0; + } + printf("blocked\t%d\n", asleep >= 10); + printf("unclaimed\t%d\n", entry_state_of(wb_child, NULL) < 0); + if (write(go[1], "1", 1) != 1) return 1; + pthread_join(waiter, NULL); + printf("same\t%d\n", wb_done == 0 && wb_info.si_pid == wb_child); + printf("code\t%d\n", wb_info.si_code); + printf("exit\t%d\n", wb_info.si_status); + int status = 0; + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; +} + +static void *bystander(void *unused) { + (void)unused; + int status = 0; + printf("bystander\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + return NULL; +} + +// nothreadheir: the main thread and the forking one both end; the kernel gives the child to the +// group's first live thread, the heir (created first), and not to the bystander +static void *heir(void *unused) { + (void)unused; + nothread_await(2); + int status = 0; + pid_t r = waitpid(nothread_child, &status, __WNOTHREAD); + printf("own\t%d\n", r == nothread_child); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return NULL; +} + +static void *late_bystander(void *unused) { + (void)unused; + nothread_await(1); + // both waits only once the main thread has ended (its task a zombie) + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)getpid()); + int ended = 0; + for (int i = 0; i < 500 && !ended; i++) { + FILE *f = fopen(path, "r"); + size_t n = f ? fread(stat, 1, sizeof(stat) - 1, f) : 0; + if (f) fclose(f); + stat[n] = 0; + char *s = strrchr(stat, ')'); + ended = f && s && s[1] == ' ' && (s[2] == 'Z' || s[2] == 'X'); + if (!ended) usleep(10000); + } + printf("mainended\t%d\n", ended); + int status = 0; + printf("bystander\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + nothread_go(2); + return NULL; +} + +int main(int argc, char **argv) { + setvbuf(stdout, NULL, _IONBF, 0); // what it got to, also when it does not finish + pid_t pid; + if (strcmp(argv[1], "nothreadheir") == 0) { + nothread_arg = argv[2]; + pthread_t first, forker, other; + pthread_create(&first, NULL, heir, NULL); + pthread_create(&forker, NULL, gone_forker, NULL); + pthread_join(forker, NULL); + pthread_create(&other, NULL, late_bystander, NULL); + usleep(1500000); // the program has exited by now + nothread_go(1); + pthread_exit(NULL); // the main thread ends too; the others finish the process + } + if (strcmp(argv[1], "nohangtwo") == 0) return nohang_two(argv[2], 0); + if (strcmp(argv[1], "nohangtwohanded") == 0) return nohang_two(argv[2], 1); + if (strcmp(argv[1], "nohangtwogroup") == 0) return nohang_two(argv[2], 2); + if (strcmp(argv[1], "reapbeforerecord") == 0) return reap_before_record(argv[2]); + if (strcmp(argv[1], "waitidblocked") == 0) return waitid_blocked(argv[2]); + if (strcmp(argv[1], "laterecord") == 0) return late_record(argv[2], 0); + if (strcmp(argv[1], "laterecordlive") == 0) return late_record(argv[2], 1); + if (strcmp(argv[1], "laterecordearly") == 0) return late_record(argv[2], 2); + if (strcmp(argv[1], "nothreadgone") == 0) { + nothread_arg = argv[2]; + pthread_t forker; + pthread_create(&forker, NULL, gone_forker, NULL); + pthread_join(forker, NULL); + usleep(1500000); // the program has exited by now + // another thread than the one the child went to: not its child + pthread_t other; + pthread_create(&other, NULL, bystander, NULL); + pthread_join(other, NULL); + int status = 0; + pid_t r = waitpid(nothread_child, &status, __WNOTHREAD); + printf("own\t%d\n", r == nothread_child); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return 0; + } + if (strcmp(argv[1], "nothreadnested") == 0) { + // the main thread's own program runs on; the other thread's has exited by the time it waits + pid_t own = fork(); + if (own == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (own < 0) return 1; + nothread_arg = argv[2]; + pthread_t forker; + pthread_create(&forker, NULL, nothread_forker, NULL); + nothread_await(1); + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = nested_wait; // no SA_RESTART: the wait ends with EINTR after one more look + sigaction(SIGALRM, &sa, NULL); + alarm(1); + int status = 0; + errno = 0; + pid_t r = waitpid(-1, &status, __WNOTHREAD); + printf("outer\t%d\n", (int)r); + printf("eintr\t%d\n", r == -1 && errno == EINTR); + kill(own, SIGKILL); + printf("ownend\t%d\n", waitpid(own, &status, 0) == own && WIFSIGNALED(status)); + nothread_go(2); + pthread_join(forker, NULL); + return 0; + } + if (strcmp(argv[1], "nothread") == 0 || strcmp(argv[1], "nothreadwrap") == 0) { + nothread_arg = argv[2]; + nothread_wrap = argv[1][8] != 0; + pthread_t forker; + pthread_create(&forker, NULL, nothread_forker, NULL); + nothread_await(1); + int status = 0; + printf("other\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WNOTHREAD)); + printf("otherpid\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + printf("otherwait3\t%d\n", (int)wait3(&status, WNOHANG | __WNOTHREAD, NULL)); + nothread_go(2); + pthread_join(forker, NULL); + return 0; + } + if (strcmp(argv[1], "prepclose") == 0 || strcmp(argv[1], "prepcloselate") == 0) { + // late: the close goes on past the hook's wait for it, through its second try; a later fork + // makes the table then + int late = argv[1][9] != 0; + prep_hold_ms = late ? 1500 : 0; + if (pipe(prep_in) != 0 || pipe(prep_out) != 0 || pipe(prep_kept) != 0) return 1; + char kept[16]; + snprintf(kept, sizeof(kept), "%d", prep_kept[1]); + setenv("DDH_TEST_TABLE_KEPT", kept, 1); + pthread_t closer, release; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; // it has looked + pthread_create(&release, NULL, prep_release, NULL); + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (pid < 0) return 1; + pthread_join(release, NULL); + pthread_join(closer, NULL); + printf("ranged\t%ld\n", prep_closed); + int status = 0; + printf("same\t%d\n", waitpid(pid, &status, 0) == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + if (late) { + pid_t again = fork(); + if (again == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (again < 0) return 1; + printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + } + printf("acked\t%d\n", prep_acked); + printf("table\t%d\n", table_open()); + return 0; + } + if (strcmp(argv[1], "prepcloseheld") == 0) { + // the close stays under way through three forks, each of whose tries gives the table up: one + // table's fd at most is left for it, tried again, not another made each time + if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + pthread_t closer; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; + int status = 0; + for (int i = 0; i < 3; i++) { + pid_t quick = fork(); + if (quick == 0) _exit(0); + if (quick < 0) return 1; + waitpid(quick, &status, 0); + } + printf("tables\t%d\n", tables_open()); + if (write(prep_in[1], "1", 1) != 1) return 1; + pthread_join(closer, NULL); + // The close has closed the given-up table's 800 by now; a file of the program's own takes the + // number, as another thread's open could, and outlives the next try, which finds no table there. + char target[64]; + printf("freed800\t%d\n", readlink("/proc/self/fd/800", target, sizeof(target)) < 0); + int mine = open("/dev/null", O_RDONLY); + if (mine < 0 || dup2(mine, 800) != 800) return 1; + close(mine); + pid_t again = fork(); // the close is over: the table is made now + if (again == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (again < 0) return 1; + printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + printf("table\t%d\n", table_open()); + ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1); + if (n > 0) target[n] = 0; + printf("mine800\t%d\n", n > 0 && strcmp(target, "/dev/null") == 0); + return 0; + } + if (strcmp(argv[1], "nowaitpeek") == 0) { + if (pipe(nowait_in) != 0 || pipe(nowait_out) != 0) return 1; + pid_t child = fork(); + if (child == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (child < 0) return 1; + pthread_t waiter; + pthread_create(&waiter, NULL, nowait_waiter, NULL); + char c; + if (read(nowait_out[0], &c, 1) != 1) return 1; // it has seen the forked child's exit + kill(child, SIGTERM); + int status = 0; + printf("taken\t%d\n", waitpid(child, &status, 0) == child && WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM); + if (write(nowait_in[1], "1111", 4) != 4) return 1; + pthread_join(waiter, NULL); + printf("child\t%d\n", (int)child); + return 0; + } + if (strcmp(argv[1], "forkclose") == 0) { + // another thread's close_range() is under way (held on the test gate) when this forks a child, + // which then makes a table of its own for a child of its own: it waits for no close of its parent's + if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + pthread_t closer; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; + pid_t child = fork(); + if (child == 0) { + pid_t grandchild = fork(); + if (grandchild == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (grandchild < 0) _exit(123); + int status = 0; + if (waitpid(grandchild, &status, 0) != grandchild) _exit(124); + _exit(WIFEXITED(status) ? WEXITSTATUS(status) : 125); + } + if (child < 0) return 1; + int status = 0; + printf("child\t%d\n", waitpid(child, &status, 0) == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (write(prep_in[1], "1", 1) != 1) return 1; + pthread_join(closer, NULL); + return 0; + } + if (strcmp(argv[1], "reapreuse") == 0) { + if (pipe(reuse_in) != 0 || pipe(reuse_out) != 0) return 1; + pid_t first = fork(); + if (first == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (first < 0) return 1; + pthread_t waiter; + pthread_create(&waiter, NULL, reuse_waiter, NULL); + char c; + if (read(reuse_out[0], &c, 1) != 1) return 1; // it has reaped the first's forked child + kill(first, SIGTERM); + usleep(1000000); // the program's end is reported + int status = 0; + printf("first\t%d\n", waitpid(first, &status, 0) == first && WIFSIGNALED(status)); + pid_t second = fork(); + if (second == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (second < 0) { + if (write(reuse_in[1], "1111", 4) != 4) return 1; // the waiter let go before the fixture fails + return 1; + } + // handed off, its forked child exited (its exit not taken: the waiter is held) + int exited = 0; + for (int i = 0; i < 500 && !(exited = zombie(second)); i++) usleep(10000); + printf("secondexited\t%d\n", exited); + if (write(reuse_in[1], "1111", 4) != 4) return 1; // for this reap and any after it + usleep(500000); + kill(second, SIGTERM); + pthread_join(waiter, NULL); + printf("second\t%d\n", (int)second); + return 0; + } + if (strcmp(argv[1], "stoppeek") == 0) { + if (pipe(peek_in) != 0 || pipe(peek_out) != 0) return 1; + peek_child = fork(); + if (peek_child == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (peek_child < 0) return 1; + usleep(300000); // its handoff is with the app (the fake spawner holds its reply) + syscall(SYS_tgkill, peek_child, peek_child, SIGSTOP); + pthread_t waiter; + pthread_create(&waiter, NULL, peek_waiter, NULL); + char c; + if (read(peek_out[0], &c, 1) != 1) return 1; // it has seen an event: the gate says which + printf("peeked\t%d\n", c); + if (c != CLD_STOPPED) return 0; // not the stop, so not the ordering this is about: the test fails + syscall(SYS_tgkill, peek_child, peek_child, SIGCONT); + // the reply has come, the program runs, the forked child has exited (its exit still not taken) + int gone = 0; + for (int i = 0; i < 500 && !(gone = zombie(peek_child)); i++) usleep(10000); + printf("shimexited\t%d\n", gone); + if (write(peek_in[1], "11111111", 8) != 8) return 1; // for each look + pthread_join(waiter, NULL); + return 0; + } + // waitidpid: the child holds before its exec until the parent's wait has begun + if (strcmp(argv[1], "waitidpid") == 0 && pipe(gate) != 0) return 1; + if (strcmp(argv[1], "spawn") == 0) { + // as Python's subprocess does since 3.13, with its close_fds as a file action + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_addclosefrom_np(&actions, 3); + char *args[] = {"target", argv[2], NULL}; + int err = posix_spawn(&pid, argc > 3 ? argv[3] : "/bin/target", &actions, NULL, args, environ); + printf("spawned\t%d\n", err); + if (err) return 0; + } else if ((pid = fork()) == 0) { + if (strcmp(argv[1], "closefds") == 0) { + // as Python's subprocess does before exec; an ordinary fd shows that it closed them + int probe = open("/dev/null", O_RDONLY); + printf("closerange\t%ld\n", (long)syscall(SYS_close_range, 3, ~0U, 0)); + printf("closed\t%d\n", probe >= 3 && fcntl(probe, F_GETFD) < 0); + fflush(stdout); + } + if (strcmp(argv[1], "group") == 0) setpgid(0, 0); + if (gate[0] >= 0) { + char c; + close(gate[1]); + if (read(gate[0], &c, 1) != 1) _exit(126); + } + if (strcmp(argv[1], "manyargs") == 0) { + // argv[3] after 32 others, as a long env-wrapped launch has it + char *args[37] = {"target", argv[2]}; + for (int i = 2; i < 34; i++) args[i] = "x"; + args[34] = argv[3]; + args[35] = NULL; + execv("/bin/target", args); + _exit(127); + } + execl(argc > 3 ? argv[3] : "/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (pid < 0) return 1; + int status = 0; + if (strcmp(argv[1], "waitidpid") == 0) { + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = open_gate; + sa.sa_flags = SA_RESTART; + sigaction(SIGALRM, &sa, NULL); + alarm(1); + siginfo_t si; + memset(&si, 0, sizeof(si)); + int r = waitid(P_PID, pid, &si, WEXITED); + printf("same\t%d\n", r == 0 && si.si_pid == pid); + printf("code\t%d\n", si.si_code); + printf("exit\t%d\n", si.si_status); + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; + } + int all = strcmp(argv[1], "waitidall") == 0 ? __WALL : 0; + if (strcmp(argv[1], "waitid") == 0 || all) { + // at once, before the child has claimed its handoff, and for stops too (and with __WALL) + siginfo_t si; + errno = 0; + printf("pid0\t%d\n", waitid(P_PID, 0, &si, WEXITED) < 0 && errno == EINVAL); + memset(&si, 0, sizeof(si)); + int r = waitid(P_ALL, 0, &si, WEXITED | WSTOPPED | all); + printf("same\t%d\n", r == 0 && si.si_pid == pid); + printf("code\t%d\n", si.si_code); + printf("exit\t%d\n", si.si_status); + printf("uid\t%d\n", (int)si.si_uid); + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; + } + if (strcmp(argv[1], "twowaits") == 0) { + if (pipe(two_in) != 0 || pipe(two_out) != 0) return 1; + pthread_t first, release; + pthread_create(&first, NULL, first_waiter, NULL); + char c; + if (read(two_out[0], &c, 1) != 1) return 1; // the first wait has reaped the forked child + kill(pid, SIGTERM); // the program's: it ends, and its exit is ready + usleep(1000000); + pthread_create(&release, NULL, releaser, NULL); + pid_t r = -1; + for (int i = 0; i < 300 && (r = waitpid(-1, &status, WNOHANG)) == 0; i++) usleep(10000); + printf("second\t%d\n", (int)r); + printf("signal\t%d\n", r == pid && WIFSIGNALED(status) ? WTERMSIG(status) : -1); + pthread_join(release, NULL); + pthread_join(first, NULL); + printf("child\t%d\n", (int)pid); + return 0; + } + if (strcmp(argv[1], "stopclaim") == 0) { + // stopped while its handoff is with the app (the fake spawner holds its reply), then continued: by + // tgkill(), as a group's stop reaches it, where kill() would hold the signal for the program + usleep(300000); + syscall(SYS_tgkill, pid, pid, SIGSTOP); + printf("stopped\t%d\n", waitpid(pid, &status, WUNTRACED) == pid && WIFSTOPPED(status)); + usleep(1500000); // the reply has come meanwhile + syscall(SYS_tgkill, pid, pid, SIGCONT); + } + if (strcmp(argv[1], "badopts") == 0) { + usleep(1500000); // the program has exited by now + // refused (WNOWAIT is waitid()'s) or selecting no forked child (__WCLONE alone): the exit stays + errno = 0; + printf("nowait\t%d\n", (int)wait4(-1, &status, WNOHANG | WNOWAIT, NULL) == -1 && errno == EINVAL); + printf("clone\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WCLONE) != pid); + printf("cloneall\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WCLONE) != pid); + errno = 0; + printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH); + } + int group = strcmp(argv[1], "group") == 0; + if (group) { + setpgid(pid, pid); + usleep(300000); + // the child is in a group of its own: not ours + printf("ours\t%d\n", (int)waitpid(0, &status, WNOHANG)); + } + if (strcmp(argv[1], "kill") == 0) { + printf("nohang\t%d\n", (int)waitpid(pid, &status, WNOHANG)); + usleep(300000); + printf("kill\t%d\n", kill(pid, SIGTERM)); + } + pid_t r = waitpid(group ? -pid : pid, &status, 0); + printf("same\t%d\n", r == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + if (WIFSIGNALED(status)) printf("signal\t%d\n", WTERMSIG(status)); + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; +} +""" + +TARGET = r""" +#include +#include +#include + +int main(int argc, char **argv) { + if (strcmp(argv[1], "sleep") == 0) for (;;) pause(); + return atoi(argv[1]); +} +""" + +# A worker's program that puts files where the hook keeps its parent's pidfd: it gets the numbers, the +# hook makes no descriptor for it, and its parent stays known +DUPOVER = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static int is(int fd, const char *what) { + char path[64], target[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0) return 0; + target[n] = 0; + return strcmp(target, what) == 0; +} + +static unsigned long fds(void) { // a sum over the open fds, the listing's own left out + DIR *d = opendir("/proc/self/fd"); + unsigned long sum = 0; + struct dirent *e; + while (d && (e = readdir(d))) { + if (e->d_name[0] == '.' || atoi(e->d_name) == dirfd(d)) continue; + sum = sum * 31 + (unsigned long)atoi(e->d_name) + 1; + } + if (d) closedir(d); + return sum; +} + +int main(void) { + printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); + int file = open("/dev/null", O_WRONLY); + unsigned long before = fds(); + dup2(file, 900); + printf("nonew\t%d\n", fds() == before); + printf("taken\t%d\n", is(900, "/dev/null")); + printf("moved\t%d\n", (int)getppid()); + dup2(file, 901); // the spare too: no pidfd left, /proc answers + printf("again\t%d\n", (int)getppid()); + long closed = syscall(SYS_close_range, 3, ~0U, 0); + printf("closerange\t%ld\n", closed); + printf("fileclosed\t%d\n", fcntl(file, F_GETFD) == -1); + printf("closed\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program with its table at fd 1000 (kept, as 900 and 901 are): a dup2() onto the pidfd +# lets go of 900 while another thread's close_range(899, 2000) is between its parts, held there by the +# hook's test gate. The kept fds above 900 stay open. +DUPRACE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static int in[2], out[2]; +static long closed = -2; + +static int is(int fd, const char *what) { + char path[64], target[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0) return 0; + target[n] = 0; + return strncmp(target, what, strlen(what)) == 0; +} + +static void *closer(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", in[0], out[1], (int)syscall(SYS_gettid)); + setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); + closed = syscall(SYS_close_range, 899, 2000, 0); + return NULL; +} + +int main(void) { + printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]") && is(1000, "/memfd:")); + int file = open("/dev/null", O_WRONLY); + if (dup2(file, 950) != 950) return 1; // an ordinary fd in the range, which it closes + if (pipe(in) != 0 || pipe(out) != 0) return 1; + pthread_t thread; + pthread_create(&thread, NULL, closer, NULL); + char c; + if (read(out[0], &c, 1) != 1) return 1; // between the parts + dup2(file, 900); + if (write(in[1], "111", 3) != 3) return 1; // one for each part + pthread_join(thread, NULL); + printf("ranged\t%ld\n", closed); + printf("ordinary\t%d\n", fcntl(950, F_GETFD) == -1); + printf("spare\t%d\n", is(901, "anon_inode:[pidfd]")); + printf("table\t%d\n", is(1000, "/memfd:")); + printf("parent\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program where one thread gives itself a table of its own (close_range() with +# CLOSE_RANGE_UNSHARE) and takes the parent's pidfd number over with dup2(), then closes it there. +# The first thread's table still holds the pidfd, which its close() leaves open. +SPLIT = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +#ifndef CLOSE_RANGE_UNSHARE +#define CLOSE_RANGE_UNSHARE (1U << 1) +#endif + +static int split_closed, own_closed; + +static int is(int fd, const char *what) { + char path[64], target[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0) return 0; + target[n] = 0; + return strcmp(target, what) == 0; +} + +static void *splitter(void *file) { + long r = syscall(SYS_close_range, 950, 950, CLOSE_RANGE_UNSHARE); + split_closed = r == 0 && fcntl(950, F_GETFD) == -1; + dup2(*(int *)file, 900); + close(900); + own_closed = fcntl(900, F_GETFD) == -1; + return NULL; +} + +int main(void) { + printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); + int file = open("/dev/null", O_WRONLY); + if (dup2(file, 950) != 950) return 1; + pthread_t thread; + pthread_create(&thread, NULL, splitter, &file); + pthread_join(thread, NULL); + printf("split\t%d\n", split_closed); + printf("own\t%d\n", own_closed); + printf("shared\t%d\n", is(950, "/dev/null")); + close(900); + printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); + printf("parent\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program that checks its parent through the hook's pidfd (kept at 900) when it has one. +# Built with NOFDS, it first takes every free descriptor, so that /proc cannot be read: the answer can +# then only come from the pidfd, which needs no new one (and /proc's failure counts as alive). +PIDFDPPID = r""" +#include +#include +#include +#include +#include + +int main(void) { + char target[64]; + ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); + target[n > 0 ? n : 0] = 0; + printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); + fflush(stdout); +#ifdef NOFDS + struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open + setrlimit(RLIMIT_NOFILE, &lim); + while (open("/dev/null", O_RDONLY) >= 0) {} + printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); +#endif + printf("parent\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program that says whether it has the hook's pidfd of its parent (kept at 900) and exits +# with 9 at once. Built with NOFDS, it first takes every free descriptor (/proc then cannot be read). +EXIT9 = r""" +#include +#include +#include +#include +#include + +int main(void) { + char target[64]; + ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); + target[n > 0 ? n : 0] = 0; + printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); +#ifdef NOFDS + struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open + setrlimit(RLIMIT_NOFILE, &lim); + while (open("/dev/null", O_RDONLY) >= 0) {} + printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); +#endif + fflush(stdout); + return 9; +} +""" + +# An unlisted program that execs the next one, as env and shell wrappers do +WRAP = r""" +#include + +int main(int argc, char **argv) { + if (argc < 3) return 2; + execv(argv[1], argv + 2); // wrap PATH ARGV0 ARGS... + return 127; +} +""" + + +class FakeSpawner(threading.Thread): + """Stands in for the app's spawn socket: runs the program and reports its exit into the table.""" + + def __init__(self, name, prefix, root, reports=True, delay=0): + super().__init__(daemon=True) + self.delay = delay # seconds before the reply: the forked child waits with its entry claimed + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.bind("\0" + name) + self.sock.listen(4) + self.prefix = prefix + self.root = root + self.reports = reports # False: as an app that died with its worker, no exit report + self.requests = [] + # The programs it ran, as pidfds: ended with the test whatever becomes of them, and never another + # process given a pid of theirs once they have been reaped. A program it could not have one for + # is never run (failures says so); none is started once the ending has begun (closed). + self.pidfds = [] + self.failures = [] + self.closed = False + self.lock = threading.Lock() + + def run(self): + while True: + try: + conn, _ = self.sock.accept() + except OSError: + return + header = self.read(conn, 4) + payload = self.read(conn, struct.unpack(">I", header)[0]) if header else b"" + if not payload: + conn.close() + continue + request = json.loads(payload) + fds = [] + while len(fds) < len(request["fds"]) + 1: + data, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"]) + fds.extend(chunk) + if not data: + break # the client went away between chunks + if len(fds) < len(request["fds"]) + 1: + for fd in fds: + os.close(fd) + conn.close() + continue + self.requests.append(request) + table = fds[request["table"]] + program = str(self.root) + request["file"] + if self.delay: + threading.Event().wait(self.delay) + # As a worker does: a process whose pid goes back first, which runs the program only + # once the hook takes it on with "go" + with self.lock: + pid, pidfd = -1, None + if not self.closed: + gate_r, gate_w = os.pipe() + pid = os.fork() + if pid == 0: + os.close(gate_w) + if os.read(gate_r, 1) == b"1": + argv = list(self.prefix) + [program] + request["argv"][1:] + os.execv(argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0]), argv) + os._exit(127) + os.close(gate_r) + try: + pidfd = os.pidfd_open(pid) + self.pidfds.append(pidfd) + except (AttributeError, OSError) as error: + self.failures.append("no pidfd for a worker: %s" % error) + went = False + try: + if pidfd is not None: + conn.sendall(b"pid %d\n" % pid) + went = not request.get("ack") or self.read(conn, 3) == b"go\n" + if went and request.get("ack"): + conn.sendall(b"ok\n") # the app's last word, before the worker may run it + if went: + os.write(gate_w, b"1") + except OSError: + went = False # the fixture went away mid-handshake + finally: + for fd in fds: + if fd != table: + os.close(fd) + conn.close() + if pid > 0: + os.close(gate_w) # a worker not told to go ends at once + if not went: + if pid > 0: + os.waitpid(pid, 0) + os.close(table) + continue + threading.Thread(target=self.report if self.reports else self.reap, args=(pid, table, request), daemon=True).start() + + @staticmethod + def read(conn, size): + data = b"" + while len(data) < size: + more = conn.recv(size - len(data)) + if not more: + return b"" # the client went away + data += more + return data + + @staticmethod + def reap(pid, table, request): + os.waitpid(pid, 0) + os.close(table) + + @staticmethod + def report(pid, table, request): + code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) + status = (-code) & 0x7F if code < 0 else (code & 0xFF) << 8 + # as GuestWorkers.reportExit: one write of the status and the child it is for; the hook + # moves the entry to exited itself + entry = 64 + request["slot"] * 64 + os.pwrite(table, struct.pack(" out 2> err": the controlling terminal on none of its standard fds + result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="hidden") + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_near_the_limit_a_job_reading_dev_null_is_handed_off(self): + # "cmd &" from a shell without job control: the foreground group, stdin /dev/null + result, requests, out = self.run_parent("wait", "7", handoff="other", pressure=0, as_shell=True, terminal="null") + self.assertEqual(1, len(requests), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_near_the_limit_the_steam_client_is_not(self): + steam = self.root / "bin/steam" + if not steam.exists(): + shutil.copy(self.root / "bin/target", steam) + result, requests, out = self.run_parent("wait", "3", "/bin/steam", handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_near_the_limit_a_quick_tool_is_not(self): + # sed, grep, sort...: a few milliseconds of work, not an app process of their own + sed = self.root / "bin/sed" + if not sed.exists(): + shutil.copy(self.root / "bin/target", sed) + result, requests, out = self.run_parent("wait", "3", "/bin/sed", handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_near_the_limit_a_quick_tool_named_only_in_an_argument_is_handed_off(self): + # only the program itself counts: "target ... sed" is not sed + result, requests, out = self.run_parent("manyargs", "7", "sed", handoff="other", pressure=0, as_shell=True) + self.assertEqual(1, len(requests), out.stderr) + + def test_near_the_limit_a_launch_naming_steam_in_any_argument_is_not(self): + # as "env ... /path/Steam/steamrtarm64/steam", with the path after 32 other arguments + result, requests, out = self.run_parent("manyargs", "3", "/root/.local/share/Steam/steamrtarm64/steam", + handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_a_wait_of_another_thread_with_wnothread_does_not_take_the_program(self): + result, requests, out = self.run_parent("nothread", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("other"), out.stdout) + self.assertEqual("-1", result.get("otherpid"), out.stdout) + self.assertEqual("-1", result.get("otherwait3"), out.stdout) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_table_given_up_again_and_again_costs_one_fd(self): + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc)") + result, requests, out = self.run_parent("prepcloseheld", "5", extra_env={"DDH_TEST_LATE_TABLE": "1"}) + self.assertEqual("1", result.get("tables"), out.stdout + out.stderr) + # the given-up table's number, closed by the close and then the program's own file, stays its + self.assertEqual("1", result.get("freed800"), out.stdout) + self.assertEqual("1", result.get("mine800"), out.stdout) + self.assertEqual("5", result.get("again"), out.stdout) + self.assertEqual("1", result.get("table"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + + def test_a_waitid_nowait_reports_no_child_whose_entry_went_meanwhile(self): + result, requests, out = self.run_parent("nowaitpeek", "sleep") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("taken"), out.stdout + out.stderr) + self.assertEqual("1", result.get("echild"), out.stdout) + self.assertEqual("0", result.get("lookedpid"), out.stdout) + + def test_a_forked_child_waits_for_no_close_of_its_parents(self): + # no table in the parent (a close held across its tries), so the child makes one + result, requests, out = self.run_parent("forkclose", "3", extra_env={"DDH_TEST_LATE_TABLE": "1"}) + self.assertEqual(1, len(requests), out.stdout + out.stderr) + self.assertEqual("3", result.get("child"), out.stdout) + + def test_a_late_mark_of_a_reused_slot_leaves_the_new_child_once(self): + result, requests, out = self.run_parent("reapreuse", "sleep") + self.assertEqual(2, len(requests), out.stderr) + # the second child took the first's slot, and had handed off before the late mark came + self.assertEqual(requests[0]["slot"], requests[1]["slot"], requests) + self.assertEqual("1", result.get("first"), out.stdout + out.stderr) + self.assertEqual("1", result.get("secondexited"), out.stdout) + self.assertEqual("1", result.get("reports"), out.stdout) + self.assertEqual(result.get("second"), result.get("last"), out.stdout) + self.assertEqual(str(signal.SIGTERM.value), result.get("lastsignal"), out.stdout) + + def test_a_stop_seen_before_the_child_hands_off_reports_its_program(self): + result, requests, out = self.run_parent("stoppeek", "6", delay=1.0) + self.assertEqual(str(os.CLD_STOPPED), result.get("peeked"), out.stdout + out.stderr) # the look saw the stop + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("shimexited"), out.stdout + out.stderr) + # the one wait that saw the stop reports the program's end, not a stop and not the forked child's + self.assertEqual("1", result.get("waited"), out.stdout) + self.assertEqual("0", result.get("stopped"), out.stdout) + self.assertEqual("6", result.get("code"), out.stdout) + + def test_two_waits_report_a_handed_off_child_once(self): + result, requests, out = self.run_parent("twowaits", "sleep") + self.assertEqual(1, len(requests), out.stderr) + child = result.get("child") + self.assertEqual(child, result.get("second"), out.stdout) + self.assertEqual(str(signal.SIGTERM.value), result.get("signal"), out.stdout) + self.assertEqual("-1", result.get("first"), out.stdout) + + def test_a_stop_while_the_handoff_is_claimed_keeps_the_claim(self): + result, requests, out = self.run_parent("stopclaim", "6", delay=1.0) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("stopped"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("6", result.get("exit"), out.stdout) + + def test_a_wnothread_wait_a_handler_interrupts_keeps_to_its_thread(self): + result, requests, out = self.run_parent("nothreadnested", "7") + self.assertEqual(2, len(requests), out.stderr) + self.assertEqual("1", result.get("eintr"), out.stdout) + self.assertEqual("1", result.get("ownend"), out.stdout) + # the other thread's child is still its own + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_wait_with_options_wait4_refuses_or_clone_only_leaves_the_exit(self): + result, requests, out = self.run_parent("badopts", "5") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("nowait"), out.stdout) + self.assertEqual("1", result.get("clone"), out.stdout) + self.assertEqual("1", result.get("cloneall"), out.stdout) + self.assertEqual("1", result.get("intmin"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("5", result.get("exit"), out.stdout) + + def test_a_posix_spawn_of_a_file_with_only_the_elf_magic_fails_as_it_would(self): + stub = self.root / "bin/stub" + stub.write_bytes(b"\x7fELF") + stub.chmod(0o755) + result, requests, out = self.run_parent("spawn", "6", "/bin/stub", handoff="stub") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual([], requests) + self.assertEqual(str(errno.ENOEXEC), result.get("spawned"), out.stdout) + self.assertNotIn("exit", result, out.stdout) + self.assertNotIn("signal", result, out.stdout) + + def test_wnothread_child_goes_to_the_first_live_thread(self): + # The forking thread and the main one both ended. Which thread the kernel gives the child to + # (qemu-user has a thread of its own first) is what the same program shows without the hook. + result, requests, out = self.run_parent("nothreadheir", "7") + plain, _, plain_out = self.run_parent("nothreadheir", "7", hook=False) + # the waits ran only after the main thread had ended, in both runs + self.assertEqual("1", result.get("mainended"), out.stdout) + self.assertEqual("1", plain.get("mainended"), plain_out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual(plain.get("bystander"), result.get("bystander"), (out.stdout, plain_out.stdout)) + self.assertEqual(plain.get("own"), result.get("own"), (out.stdout, plain_out.stdout)) + if result.get("own") == "1": + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_wnothread_takes_a_child_whose_thread_ended(self): + # the kernel gives it to the main thread: another thread's wait does not take it + result, requests, out = self.run_parent("nothreadgone", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("bystander"), out.stdout) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_late_record_of_a_spawned_child_keeps_a_handoffs_owner(self): + self.late_record() + + def test_a_late_record_keeps_an_owner_whose_start_was_not_read(self): + # the fork's child could not read its own start time: its record has none to be told by + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}) + + def test_a_late_record_reading_the_new_childs_start_keeps_its_owner(self): + # made while the later child, which could not read its own start, still hands its program off + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="live") + + def test_a_late_record_before_the_new_child_execs_keeps_its_owner(self): + # made once the later child, which could not read its own start, has recorded itself and + # before it execs: no handoff of it yet to tell by + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="early") + + def late_record(self, env=None, live=None): + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so nothing can be spawned") + # the pid has to be given again, which only a pid namespace of the test's own allows + if not os.environ.get("DDH_TEST_PIDNS"): + unshare = shutil.which("unshare") + if not unshare or subprocess.run([unshare, "-Urpf", "--mount-proc", "true"], capture_output=True).returncode: + self.skipTest("no user and pid namespace for this test") + # this module by the name it was loaded as, from the repository's root or this directory + here, top = Path(__file__).resolve().parent, Path(__file__).resolve().parents[2] + path = os.pathsep.join([str(here), str(top)] + ([os.environ["PYTHONPATH"]] if os.environ.get("PYTHONPATH") else [])) + out = subprocess.run([unshare, "-Urpf", "--mount-proc", sys.executable, "-m", "unittest", self.id()], + env={**os.environ, "DDH_TEST_PIDNS": "1", "PYTHONPATH": path}, cwd=top, + capture_output=True, text=True, timeout=300) + self.assertEqual(0, out.returncode, out.stderr) + self.assertNotIn("skipped", out.stderr, out.stderr) + return + result, requests, out = self.run_parent("laterecord" + (live or ""), "sleep", extra_env=env, + delay=1.0 if live == "live" else 0) + self.assertEqual("1", result.get("reused"), out.stdout + out.stderr) + if live == "live": + self.assertEqual("1", result.get("claimed"), out.stdout) + if live == "early": + self.assertEqual("1", result.get("recorded"), out.stdout) + self.assertEqual("0", result.get("spawned"), out.stdout) + self.assertEqual("1", result.get("reaped"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("1", result.get("ended"), out.stdout) + + def test_wnothread_takes_a_program_started_through_a_wrapper(self): + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so the wrapper cannot run") + # the hook names its own path inside the guest's root for the programs it execs + rooted = self.root / str(self.hook).lstrip("/") + rooted.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(self.hook, rooted) + result, requests, out = self.run_parent("nothreadwrap", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("other"), out.stdout) + self.assertEqual("-1", result.get("otherpid"), out.stdout) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_waitid_for_a_pid_begun_before_its_claim_reports_the_program(self): + result, requests, out = self.run_parent("waitidpid", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual(str(CLD_EXITED), result.get("code"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def test_near_the_limit_a_terminals_foreground_job_is_not(self): + result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal=True) + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def ppid_in_worker(self, parent): + # as a worker's own program: DDH_WORKER_PID is its pid, DDH_TABLE names the process that forked it + tmp = Path(self.tmp.name) + probe = tmp / "ppid" + if not probe.exists(): + (tmp / "ppid.c").write_text('#include \n#include \nint main(void) { printf("%d", (int)getppid()); return 0; }\n') + subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "ppid.c")], check=True) + env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)} + if parent is not None: + env["DDH_TABLE"] = "3:0:%d:0" % parent + settings = " ".join("-E %s=%s" % item for item in env.items()) if self.prefix else \ + " ".join("%s=%s" % item for item in env.items()) + worker = "-E DDH_WORKER_PID=$$" if self.prefix else "DDH_WORKER_PID=$$" + runner = " ".join(self.prefix) + " " + settings + " " + worker if self.prefix else "env " + settings + " " + worker + out = subprocess.run(["sh", "-c", "exec %s %s" % (runner, probe)], capture_output=True, text=True, timeout=60) + return out.stdout.strip() + + def test_a_handed_off_programs_parent_is_the_process_that_forked_it(self): + forker = subprocess.Popen(["sleep", "60"]) + self.addCleanup(forker.wait) + self.addCleanup(forker.kill) + self.assertEqual(str(forker.pid), self.ppid_in_worker(forker.pid)) + + def test_a_handed_off_program_whose_forking_process_is_gone_has_init_as_parent(self): + self.assertEqual("1", self.ppid_in_worker(4194303)) + + def test_a_handed_off_program_whose_forking_process_exited_unreaped_has_init_as_parent(self): + forker = subprocess.Popen(["true"]) + self.addCleanup(forker.wait) + stat = Path("/proc/%d/stat" % forker.pid) + pause = threading.Event() + for _ in range(100): + if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": + break + pause.wait(0.05) + # exited and not reaped (Popen reaps only in wait() or poll()) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + self.assertEqual("1", self.ppid_in_worker(forker.pid)) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + + def test_through_its_pidfd_a_handed_off_programs_live_parent_is_its_parent(self): + parent, result, out = self.run_worker_program("pidfdlive", PIDFDPPID) + self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) + self.assertEqual(str(parent), result.get("parent"), out.stdout) + + def test_through_its_pidfd_a_handed_off_programs_unreaped_parent_is_gone(self): + forker = subprocess.Popen(["true"]) + self.addCleanup(forker.wait) + stat = Path("/proc/%d/stat" % forker.pid) + pause = threading.Event() + for _ in range(100): + if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": + break + pause.wait(0.05) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + # a pidfd opens for an exited parent that is not reaped, and reads as exited; /proc cannot be + # read meanwhile (no free fd), where a failure counts as alive: only the pidfd gives init + _, result, out = self.run_worker_program("pidfdzombie", "#define NOFDS 1\n" + PIDFDPPID, parent=forker.pid) + self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) + self.assertEqual("1", result.get("nofds"), out.stdout) + self.assertEqual("1", result.get("parent"), out.stdout) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + + def test_without_a_pidfd_a_handed_off_programs_gone_parent_is_init(self): + # no process has the pid, so no pidfd: /proc answers + _, result, out = self.run_worker_program("pidfdgone", PIDFDPPID, parent=4194303) + self.assertEqual("0", result.get("pidfd"), out.stdout + out.stderr) + self.assertEqual("1", result.get("parent"), out.stdout) + + def test_wnohang_reports_a_ready_child_while_a_handoffs_forked_child_runs(self): + result, requests, out = self.run_parent("nohangtwo", "3") + self.assertEqual(1, len(requests), out.stderr) + # the state this is about: the program's exit in the table, its forked child alive, the other ready + self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) + self.assertEqual("1", result.get("bwaitable"), out.stdout) + self.assertEqual("1", result.get("aheld"), out.stdout) + self.assertEqual("1", result.get("first"), out.stdout) + self.assertEqual("5", result.get("firstexit"), out.stdout) + self.assertEqual("1", result.get("second"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def test_wnohang_reports_a_ready_handoff_while_another_ones_forked_child_runs(self): + result, requests, out = self.run_parent("nohangtwohanded", "3") + self.assertEqual(2, len(requests), out.stderr) + self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) + self.assertEqual("1", result.get("bwaitable"), out.stdout) + self.assertEqual("1", result.get("aheld"), out.stdout) + self.assertEqual("1", result.get("first"), out.stdout) + self.assertEqual("5", result.get("firstexit"), out.stdout) + self.assertEqual("1", result.get("second"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def test_wnohang_for_the_group_reports_its_ready_child_while_a_forked_child_runs(self): + result, requests, out = self.run_parent("nohangtwogroup", "3") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) + self.assertEqual("1", result.get("bwaitable"), out.stdout) + self.assertEqual("1", result.get("aheld"), out.stdout) + # the group's ready child, not the exited one of another group + self.assertEqual("1", result.get("first"), out.stdout) + self.assertEqual("5", result.get("firstexit"), out.stdout) + self.assertEqual("1", result.get("second"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) + self.assertEqual("6", result.get("other"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def start_worker_exit(self, name, parent, state, nofds=False, child_start=1 << 62): + # A worker's program that exits with 9 at once, its entry (slot 0) given parent and state, as + # the parent's check of a gone worker leaves it while it holds it (TAKEN). With nofds it first + # takes every free descriptor, so that /proc cannot be read when it exits. A child_start before + # the parent's start leaves it without the parent's pidfd. Returns the run and the table. + tmp = Path(self.tmp.name) + probe = tmp / name + (tmp / (name + ".c")).write_text(("#define NOFDS 1\n" if nofds else "") + EXIT9) + subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / (name + ".c"))], check=True) + table = os.memfd_create("ddh-test-table", 0) + self.addCleanup(os.close, table) + os.ftruncate(table, 64 + 1024 * 64) + os.pwrite(table, struct.pack("/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