diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 388ac51cc0..ce4bd796df 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -438,5 +438,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index d58662e276..ec7373af4a 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -39,19 +39,27 @@ open class GuestWorker : Service() { if (code != RUN) return super.onTransact(code, data, reply, flags) val argv = data.createStringArray() ?: return false val env = data.createStringArray() ?: return false - val stdio = List(data.readInt()) { data.readFileDescriptor() } + val fds = List(data.readInt()) { data.readFileDescriptor() } + val targets = data.createIntArray() ?: IntArray(fds.size) { it } reply?.writeInt(Process.myPid()) - Handler(Looper.getMainLooper()).postDelayed({ exec(argv, env, stdio) }, EXEC_DELAY_MS) + Handler(Looper.getMainLooper()).postDelayed({ exec(argv, env, fds, targets) }, EXEC_DELAY_MS) return true } } override fun onBind(intent: Intent): IBinder = binder - private fun exec(argv: Array, env: Array, stdio: List) { + private fun exec(argv: Array, env: Array, fds: List, targets: IntArray) { try { - stdio.forEachIndexed { fd, pfd -> if (pfd != null) Os.dup2(pfd.fileDescriptor, fd) } keepBinderOpen() + // Out of the way first, so that placing one fd cannot overwrite another not yet placed. + val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, MOVED_FDS) } } + 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) + } Os.execve(argv[0], argv, env) } catch (e: ErrnoException) { Log.e(TAG, "could not exec ${argv.firstOrNull()}", e) @@ -59,19 +67,22 @@ open class GuestWorker : Service() { Process.killProcess(Process.myPid()) } + /** Binder fds stay open across the exec, above the numbers the program's fds go to. */ private fun keepBinderOpen() { File("/proc/self/fd").listFiles()?.forEach { link -> val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach if (!target.contains("binder")) return@forEach val fd = ParcelFileDescriptor.adoptFd(link.name.toIntOrNull() ?: return@forEach) - Os.fcntlInt(fd.fileDescriptor, OsConstants.F_SETFD, 0) kept.add(fd) + Os.fcntlInt(fd.fileDescriptor, OsConstants.F_DUPFD, BINDER_FDS) } } companion object { const val RUN = IBinder.FIRST_CALL_TRANSACTION private const val EXEC_DELAY_MS = 100L + private const val BINDER_FDS = 900 + private const val MOVED_FDS = 1200 private const val TAG = "GuestWorker" private val kept = ArrayList() @@ -105,17 +116,73 @@ 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, + 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, val connection: ServiceConnection) { @@ -132,7 +199,12 @@ object GuestWorkers { * 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 { + 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 { val app = context.applicationContext val connected = CountDownLatch(1) var service: IBinder? = null @@ -168,8 +240,9 @@ object GuestWorkers { try { data.writeStringArray(argv.toTypedArray()) data.writeStringArray(env.toTypedArray()) - data.writeInt(stdio.size) - stdio.forEach { data.writeFileDescriptor(it.fileDescriptor) } + data.writeInt(fds.size) + fds.forEach { data.writeFileDescriptor(it.fileDescriptor) } + data.writeIntArray(targets) service!!.transact(GuestWorker.RUN, data, reply, 0) slot.pid = reply.readInt() } catch (e: Exception) { @@ -190,11 +263,15 @@ object GuestWorkers { if (onExit != null) 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) repeat(20) { - am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let { return it.status } + am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let { + return if (it.reason == android.app.ApplicationExitInfo.REASON_SIGNALED) it.status and 0x7f + else (it.status and 0xff) shl 8 + } Thread.sleep(50) } return -1 @@ -233,32 +310,51 @@ object GuestWorkers { if (client.peerCredentials.uid != Process.myUid()) return val input = DataInputStream(client.inputStream) val payload = ByteArray(input.readInt()).also { input.readFully(it) } - val fds = client.ancillaryFileDescriptors.orEmpty().map { ParcelFileDescriptor.dup(it) } - client.ancillaryFileDescriptors?.forEach { runCatching { Os.close(it) } } + val received = client.ancillaryFileDescriptors.orEmpty() + val fds = received.map { ParcelFileDescriptor.dup(it) } + received.forEach { runCatching { Os.close(it) } } val request = JSONObject(String(payload)) val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } } - val envObject = request.getJSONObject("env") val env = LinkedHashMap() - envObject.keys().forEach { env[it] = envObject.getString(it) } + 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] } + } val cwd = request.optString("cwd", "/") val wait = request.optBoolean("wait", false) + val file = request.optString("file", "") + // 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) + val slot = request.optInt("slot", -1) + val parent = request.optInt("parent", -1) + val programFds = fds.filterIndexed { i, _ -> i != tableIndex } 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()) + fds.forEach { runCatching { it.close() } } return } val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile } - val script = "cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"" - val command = NativeGuest.command(root, shell, listOf("-c", script, "droiddeck-spawn", cwd) + argv) + val args = if (file.isNotEmpty()) { + listOf("-c", "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", "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 val exited = CountDownLatch(1) var status = -1 - val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, fds) { code -> + val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, numbers) { code -> status = code + if (table != null && slot >= 0) reportExit(table, slot, code, parent) exited.countDown() } - fds.forEach { runCatching { it.close() } } + programFds.forEach { runCatching { it.close() } } + if (pid <= 0) table?.let { runCatching { it.close() } } out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray()) out.flush() if (pid > 0 && wait) { @@ -268,4 +364,17 @@ object GuestWorkers { } } } + + // Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 32-byte + // entries of int32 child, real, parent, state, status, ... + private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int) { + runCatching { + val entry = 64L + slot * 32L + val word = java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.nativeOrder()) + Os.pwrite(table.fileDescriptor, word.putInt(0, if (status < 0) 9 else status).also { it.rewind() }, entry + 16) + Os.pwrite(table.fileDescriptor, word.putInt(0, 2).also { it.rewind() }, entry + 12) + 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/docs/phantom-processes.md b/docs/phantom-processes.md index 5f980b7385..d80efece8a 100644 --- a/docs/phantom-processes.md +++ b/docs/phantom-processes.md @@ -207,16 +207,70 @@ hook, at `execve()` in a forked child, could move all 40, leaving about 7 counte 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; the app writes P's exit status (from +`ApplicationExitInfo`) into the table and sends the parent `SIGCHLD`. 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. +- 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). + +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 +scans were forced by switching apps: Android listed **28** child processes device-wide and killed +**none**; the game and its Wine processes were still running afterwards. + +Still counted with a game running: the session script's 9 bash subshells, gamescope with its two +Xwayland servers, its reaper and an autolaunched D-Bus, Steam with its web helper browser and two +utility processes, Steam's launch chain (`sh`, `pw-audio-namespace`, `reaper`), and the app's own +logcat, PulseAudio and audio relay. The app's three can use `GuestWorkers.start` directly, and the +autolaunched bus goes away once gamescope sees the session bus address. + ### C. Plan 1. ~~Verify both gaps on the Thor (Android 13, 5.15)~~ done; still to do on one stock Android 14+ phone with an enforcing `isolated_app`. -2. B for the processes DroidDeck and the session script start themselves (no pid translation). - Measure the session's count. -3. A for the Steam client tree if 2 is not enough. Only GPU, Wine and game processes then stay in - the counted cgroup, about 15 with a game running. -4. Keep the developer-option check as a fallback until the count with a game running stays well - under 32 on every supported device, then turn it into a warning. +2. ~~B for the processes DroidDeck and the session script start themselves~~ done (45 of 48). +3. ~~B inside the hook, with pid translation~~ prototype done: 26 idle, 29 with a game, no kills + with Android's limit on. +4. To finish B: + - the app's own logcat, PulseAudio and audio relay through `GuestWorkers.start`; + - fewer session-script subshells, or start them with `dd_spawn bash -c`; + - the autolaunched D-Bus under gamescope; + - Xwayland, if gamescope keeps working without them as its children; + - `/proc//stat` showing the virtual parent, so Steam, its web helper and the launch chain + can be handed off too; + - a pre-started worker or two, so a handoff costs no zygote fork. +5. Then the session can stop requiring the developer option where the in-game count stays well + under 32. Keep the check as a warning and fall back to counted processes if a worker cannot + start. +6. 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 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 35af03a324..97d0e5f935 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -30,6 +30,15 @@ dd_spawn() { "$@" & dd_spawned=$! } +# 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:python3: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" diff --git a/tools/nativeguest/ddnatv-hook.c b/tools/nativeguest/ddnatv-hook.c index 4070f55c85..0ca43b0bbf 100644 --- a/tools/nativeguest/ddnatv-hook.c +++ b/tools/nativeguest/ddnatv-hook.c @@ -82,6 +82,7 @@ #include "hook/exec_probe.c" #include "hook/static_programs.c" #include "hook/go_programs.c" +#include "hook/handoff.c" #include "hook/exec.c" #include "hook/net.c" #include "hook/sockets.c" diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index b4249eb06c..3fc92586db 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) 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. diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c new file mode 100644 index 0000000000..c56e5e485b --- /dev/null +++ b/tools/nativeguest/hook/handoff.c @@ -0,0 +1,550 @@ +// 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; the app +// writes its exit status into the table and sends the parent SIGCHLD. +// +// Only programs named in DD_HANDOFF (basenames separated by ':', or "*") are handed off. The child's +// side runs where vfork() children run too, so it allocates nothing and writes no globals. + +#define DDH_SLOTS 1024 +#define DDH_FREE 0 +#define DDH_CLAIMED 3 +#define DDH_HANDED 1 +#define DDH_EXITED 2 +#define DDH_MAGIC 0x6464686f + +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, written by the app + int32_t reaped; // the parent has reaped the forked child itself + int32_t pad[2]; +}; + +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 +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; +} + +// In the parent, before fork(): the table the children write to. +static void ddh_prepare(void) { + if (g_ddh || !getenv("DD_SPAWN")) return; + int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); + if (fd < 0) return; + if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { + close(fd); + return; + } + void *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + close(fd); + return; + } + g_ddh = p; + g_ddh->magic = DDH_MAGIC; + g_ddh->pad[0] = getpid(); + g_ddh_fd = fd; + g_ddh_owner = getpid(); +} + +// 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 = getppid(); + for (int fd = 3; fd < 1024; fd++) { + 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); + continue; + } + if (t != MAP_FAILED) munmap(t, sizeof(struct ddh_table)); + syscall(SYS_close, fd); + } +} + +__attribute__((constructor)) static void ddh_init(void) { + if (!getenv("DD_SPAWN")) return; + ddh_find_parent_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 + n <= b->cap) memcpy(b->p + b->len, s, n); + 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 ? (unsigned long)-v : (unsigned long)v; + 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 + +// The fds the program would have inherited: every open fd without FD_CLOEXEC. +static int ddh_open_fds(int *fds, int max) { + 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) continue; + int flags = (int)syscall(SYS_fcntl, fd, F_GETFD); + if (flags < 0 || (flags & FD_CLOEXEC)) 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. +static const char *ddh_interpreter(const char *path, char *buf, size_t size) { + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return NULL; + long n = read(fd, buf, size - 1); + 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; +} + +// 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) { + if (!ddh_env(envp, "DD_HANDOFF_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; + syscall(SYS_write, 2, line, b.len); +} + +static void ddh_try(const char *filename, char *const argv[], char *const envp[]) { + struct ddh_table *table; + int table_fd; + if (g_ddh && getpid() != g_ddh_owner) { + table = g_ddh; + table_fd = g_ddh_fd; + } else if (g_ddh_up && getppid() == g_ddh_up->pad[0]) { + table = g_ddh_up; + table_fd = g_ddh_up_fd; + } else { + ddh_debug(envp, "not a child its parent can track:", filename); + return; + } + const char *sock = ddh_env(envp, "DD_SPAWN"); + const char *list = ddh_env(envp, "DD_HANDOFF"); + if (!sock || !list || access(filename, X_OK) != 0) return; + // Whatever this exec becomes can still hand off its own exec (a wrapper, a script). + syscall(SYS_fcntl, table_fd, F_SETFD, 0); + char shebang[256]; + const char *interp = NULL; + if (!ddh_listed(list, ddh_base(filename), argv) && !(argv && ddh_listed(list, ddh_base(argv[0]), argv)) && + !((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv))) return; + + int fds[DDH_MAX_FDS + 1]; + int nfds = ddh_open_fds(fds, DDH_MAX_FDS); + 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]; + pid_t me = getpid(), parent = getppid(); + char cwd[PATH_MAX]; + if (!getcwd(cwd, sizeof(cwd))) strcpy(cwd, "/"); + + 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, "],\"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, "}"); + 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}; + struct iovec iov[2] = {{header, 4}, {b.p, b.len}}; + char control[CMSG_SPACE(sizeof(int) * (DDH_MAX_FDS + 1))]; + struct msghdr msg = {.msg_iov = iov, .msg_iovlen = 2, .msg_control = control, + .msg_controllen = CMSG_SPACE(sizeof(int) * (nfds + 1))}; + struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); + cm->cmsg_level = SOL_SOCKET; + cm->cmsg_type = SCM_RIGHTS; + cm->cmsg_len = CMSG_LEN(sizeof(int) * (nfds + 1)); + memcpy(CMSG_DATA(cm), fds, sizeof(int) * (nfds + 1)); + if (syscall(SYS_sendmsg, s, &msg, MSG_NOSIGNAL) == (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 || reply[got] == '\n') break; + got++; + } + reply[got] = 0; + if (strncmp(reply, "pid ", 4) == 0) pid = atol(reply + 4); + } + } + } + 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); + syscall(SYS_exit_group, 0); +} + +// ---- the parent's side ----------------------------------------------------------------------- + +static struct ddh_entry *ddh_find(pid_t child) { + if (!g_ddh || 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) && e->parent == me && e->child == child) return e; + } + return NULL; +} + +static int ddh_any_live(void) { + if (!g_ddh) 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) && e->parent == me) return 1; + } + return 0; +} + +static struct ddh_entry *ddh_exited(void) { + if (!g_ddh) 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_EXITED && e->parent == me) return e; + } + return NULL; +} + +// A worker that is gone with no status from the app (it crashed with the app): reported as killed. +static void ddh_check_gone(void) { + if (!g_ddh) return; + 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_HANDED || e->parent != me) continue; + if (syscall(SYS_kill, e->real, 0) == 0 || errno != ESRCH) continue; + if (e->pad[0] == 0) { + e->pad[0] = 1; // give the app time to write the status + continue; + } + if (++e->pad[0] > 50) { + e->status = SIGKILL; + __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); + } + } +} + +static void ddh_release(struct ddh_entry *e, int *status) { + if (status) *status = e->status; + memset(e, 0, offsetof(struct ddh_entry, state)); + e->status = 0; + e->reaped = 0; + e->pad[0] = 0; + __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; +} + +static int ddh_nap(void) { + struct timespec ts = {0, 20 * 1000 * 1000}; + return nanosleep(&ts, NULL); +} + +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; + } + if (!g_ddh) return real(pid, status, options, ru); + for (;;) { + ddh_check_gone(); + struct ddh_entry *e = pid > 0 ? ddh_find(pid) : NULL; + if (pid > 0 && e) { + if (!e->reaped && real(pid, NULL, WNOHANG, NULL) == pid) e->reaped = 1; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_EXITED) { + if (ru) memset(ru, 0, sizeof(*ru)); + ddh_release(e, status); + return pid; + } + if (options & WNOHANG) return 0; + if (ddh_nap() != 0) return -1; + continue; + } + if (pid <= 0 && (e = ddh_exited())) { + pid_t child = e->child; + if (!e->reaped && real(child, NULL, WNOHANG, NULL) == child) e->reaped = 1; + if (ru) memset(ru, 0, sizeof(*ru)); + ddh_release(e, status); + return child; + } + int live = pid <= 0 && ddh_any_live(); + int wstatus = 0; + pid_t r = real(pid, &wstatus, live ? options | WNOHANG : options, ru); + if (r > 0) { + struct ddh_entry *h = ddh_find(r); + if (h && !h->reaped) { + h->reaped = 1; // the forked child that handed its program off + continue; + } + if (status) *status = wstatus; + return r; + } + if (!live) return r; + if (r < 0 && errno != ECHILD) return r; + if (options & WNOHANG) return 0; + if (ddh_nap() != 0) return -1; + } +} + +pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru) { return ddh_wait(pid, status, options, ru); } +pid_t waitpid(pid_t pid, int *status, int options) { return ddh_wait(pid, status, options, NULL); } +pid_t wait(int *status) { return ddh_wait(-1, status, 0, NULL); } +pid_t wait3(int *status, int options, struct rusage *ru) { return ddh_wait(-1, status, options, ru); } + +int 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; + } + if (!g_ddh || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL) || !ddh_any_live()) + return real(idtype, id, info, options); + // Only exits are asked for here: answer through ddh_wait and describe the result as waitid does. + int status = 0; + pid_t r = ddh_wait(idtype == P_PID ? (pid_t)id : -1, &status, options & WNOHANG, NULL); + if (r < 0) return -1; + if (info) { + memset(info, 0, sizeof(*info)); + if (r > 0) { + info->si_signo = SIGCHLD; + info->si_pid = r; + info->si_code = WIFEXITED(status) ? CLD_EXITED : CLD_KILLED; + info->si_status = WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status); + } + } + return 0; +} + +int kill(pid_t pid, int sig) { + if (g_ddh && pid > 0) { + struct ddh_entry *e = ddh_find(pid); + if (e && __atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_HANDED) pid = e->real; + } + return (int)syscall(SYS_kill, pid, sig); +}