From bbb4d11bf0dc21b4b208654ef7ca00f57a520b28 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:44:11 -0500 Subject: [PATCH] feat(session): run the session root, its jobs and the gamescope chain outside the child-process count --- .../main/java/com/droiddeck/launcher/App.kt | 2 + .../audio/DirectAudioRelayComponent.java | 2 +- .../droiddeck/launcher/core/HostProcess.kt | 64 +++++ .../launcher/core/SessionLogCapture.kt | 17 +- .../launcher/runtime/GuestWorkers.kt | 116 ++++++-- .../launcher/session/SessionFiles.kt | 1 + .../launcher/session/SessionService.kt | 10 +- .../usr/local/bin/droiddeck-log-writer | 8 + .../overlay/usr/local/bin/droiddeck-session | 55 +++- tools/nativeguest/hook/exec.c | 2 + tools/nativeguest/hook/handoff.c | 257 ++++++++++++++++-- tools/nativeguest/hook/privileged.c | 7 +- tools/tests/test_native_hook_handoff.py | 8 +- 13 files changed, 478 insertions(+), 71 deletions(-) create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 85f2b2e738..f91157dd41 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -22,6 +22,8 @@ class App : Application() { 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/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt index d4a2cdc66d..49f077686a 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,66 @@ 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) + if (context == null || argv.isEmpty()) 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 + val input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY) + var reader: ParcelFileDescriptor? = null + val 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) + } + val pid = 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)) + } + input.close() + 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/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 index ec7373af4a..0f45e0b624 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -51,31 +51,45 @@ open class GuestWorker : Service() { private fun exec(argv: Array, env: Array, fds: List, targets: IntArray) { try { - keepBinderOpen() + val top = targets.maxOrNull() ?: 2 + val binderTop = keepBinderOpen(maxOf(BINDER_FDS, top + 1)) // 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) } } + 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) } - Os.execve(argv[0], argv, env) + // 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). + Os.execve(argv[0], argv, env.filterNot { it.startsWith("DDH_WORKER_PID=") }.toTypedArray() + + "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, above the numbers the program's fds go to. */ - private fun keepBinderOpen() { + /** + * Binder fds stay open across the exec, at [from] or above, where no fd of the program goes. + * Returns the highest fd used. + */ + private fun keepBinderOpen(from: Int): Int { + var highest = from - 1 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) - kept.add(fd) - Os.fcntlInt(fd.fileDescriptor, OsConstants.F_DUPFD, BINDER_FDS) + // 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 + highest = maxOf(highest, Os.fcntlInt(copy.fileDescriptor, OsConstants.F_DUPFD, from)) + copy.close() } + return highest } companion object { @@ -185,13 +199,17 @@ object GuestWorkers { GuestWorker63::class.java, ) - private class Slot(val index: Int, val connection: ServiceConnection) { + private class Slot(val index: Int, val connection: ServiceConnection, val guest: Boolean) { @Volatile var pid = -1 } private val slots = arrayOfNulls(classes.size) @Volatile private var server: Thread? = null + /** The app, once [attach] or [serve] ran in its main process; null before. */ + @Volatile var context: Context? = null + private set + fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid() /** @@ -204,7 +222,11 @@ object GuestWorkers { /** 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 { + 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. */ + private fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, + guest: Boolean, onExit: (Int) -> Unit): Int { val app = context.applicationContext val connected = CountDownLatch(1) var service: IBinder? = null @@ -225,7 +247,7 @@ object GuestWorkers { override fun onBindingDied(name: ComponentName) = release(app, index, onExit) } - slot = Slot(index, connection) + slot = Slot(index, connection, guest) slots[index] = slot } val intent = Intent(app, classes[slot.index]) @@ -277,17 +299,26 @@ object GuestWorkers { return -1 } - /** Kills every worker's program; for session teardown. */ - fun stopAll() { - val pids = synchronized(slots) { slots.mapNotNull { it?.pid?.takeIf { pid -> pid > 0 } } } + /** The pids of the session's guest programs running in workers. */ + fun guestPids(): List = synchronized(slots) { slots.mapNotNull { s -> s?.takeIf { it.guest }?.pid?.takeIf { it > 0 } } } + + /** Ends the session's guest programs that are still running; for session teardown. */ + fun stopGuests() { + val pids = guestPids() + 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 + } + fun serve(context: Context) { val app = context.applicationContext + this.context = app synchronized(this) { if (server != null) return server = Thread({ @@ -299,7 +330,13 @@ object GuestWorkers { } while (true) { val client = runCatching { socket.accept() }.getOrNull() ?: continue - Thread({ handle(app, client) }, "guest-spawn").start() + Thread({ + try { + handle(app, client) + } catch (e: Throwable) { + Log.w(TAG, "spawn request failed", e) + } + }, "guest-spawn").start() } }, "guest-spawn-server").apply { isDaemon = true; start() } } @@ -310,26 +347,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 received = client.ancillaryFileDescriptors.orEmpty() - val fds = received.map { ParcelFileDescriptor.dup(it) } - received.forEach { runCatching { Os.close(it) } } val request = JSONObject(String(payload)) + val fds = ArrayList() + fun take() { + val received = client.ancillaryFileDescriptors.orEmpty() + received.forEach { fds.add(ParcelFileDescriptor.dup(it)) } + received.forEach { runCatching { Os.close(it) } } + } + 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) { + if (input.read() < 0) throw java.io.EOFException("fds ended at ${fds.size} of $total") + take() + } + } else { + take() + } 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) 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 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) - val programFds = fds.filterIndexed { i, _ -> i != tableIndex } + 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" + } val root = env["DDNATV_ROOT"]?.let(::File) val out = client.outputStream if (root == null || argv.isEmpty()) { @@ -346,14 +408,18 @@ object GuestWorkers { } 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("umask")) env["DDH_UMASK"] = request.getLong("umask").toString() val exited = CountDownLatch(1) var status = -1 - val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, numbers) { code -> + val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true) { code -> status = code if (table != null && slot >= 0) reportExit(table, slot, code, parent) exited.countDown() } - programFds.forEach { runCatching { it.close() } } + programFds.filter { it !== table }.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() @@ -371,7 +437,11 @@ object GuestWorkers { 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.pread(table.fileDescriptor, word, entry + 12) + if (word.getInt(0) == 2) return@runCatching // the program wrote its own status + word.clear() + // An exit Android has no record of is reported as a failure, not as a signal. + Os.pwrite(table.fileDescriptor, word.putInt(0, if (status < 0) 1 shl 8 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) } 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 b58a97b29d..f9f7c4dfde 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,7 @@ object SessionFiles { "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/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 53948bdad1..825bf28ae1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -862,10 +862,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 "") @@ -1526,8 +1526,9 @@ class SessionService : Service() { private fun teardown(prootPid: Int, expectedStartTime: Long? = null) { fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime if (!stillSameProcess()) return - if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopAll() - val tree = descendants(prootPid) + // 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() 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) @@ -1544,6 +1545,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() } private fun clearCachedApps() { 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 97d0e5f935..544aaa621c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -30,12 +30,30 @@ dd_spawn() { "$@" & dd_spawned=$! } +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:python3:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver} + 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 @@ -49,8 +67,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)" @@ -635,6 +657,9 @@ 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. + 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 @@ -796,7 +821,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 @@ -1141,7 +1166,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 @@ -1150,7 +1175,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 @@ -1242,7 +1268,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 @@ -1321,8 +1347,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'; } @@ -1481,7 +1508,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 @@ -1505,7 +1532,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 @@ -1706,7 +1734,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= @@ -1884,7 +1912,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: /' diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 3fc92586db..bb33f270f8 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -660,7 +660,9 @@ 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(1); pid_t pid = orig_fork(); + if (pid == 0) ddh_drop_worker_binder(); // 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); diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index c56e5e485b..9195489eb5 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -51,16 +51,30 @@ static const char *ddh_env(char *const envp[], const char *name) { } // In the parent, before fork(): the table the children write to. -static void ddh_prepare(void) { - if (g_ddh || !getenv("DD_SPAWN")) return; +static void ddh_prepare_failed(const char *step) { + if (!getenv("DD_HANDOFF_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) syscall(SYS_write, 2, line, (size_t)len); +} + +// The table the children write to: at start when DD_SPAWN is set, else at the first fork() (a +// shell that exports DD_SPAWN itself has no sign of it in its own environment). +static void ddh_prepare(int any) { + if (g_ddh || (!any && !getenv("DD_SPAWN"))) return; int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); - if (fd < 0) return; + if (fd < 0) { + ddh_prepare_failed("memfd_create"); + return; + } if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { + ddh_prepare_failed("ftruncate"); close(fd); return; } void *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; } @@ -94,10 +108,129 @@ static void ddh_find_parent_table(void) { } } +// 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; + +static void ddh_unkeep(int fd) { + for (int i = 0; i < g_kept_fd_count; i++) { + if (g_kept_fds[i] != fd) continue; + memmove(&g_kept_fds[i], &g_kept_fds[i + 1], (size_t)(g_kept_fd_count - i - 1) * sizeof(int)); + g_kept_fd_count--; + return; + } +} + +static void ddh_keep(int fd) { + if (g_kept_fd_count >= DDNATV_MAX_KEPT_FDS || is_kept_fd(fd)) return; + int i = g_kept_fd_count; + while (i > 0 && g_kept_fds[i - 1] > fd) { + g_kept_fds[i] = g_kept_fds[i - 1]; + i--; + } + g_kept_fds[i] = fd; + g_kept_fd_count++; +} + +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_kept_from_cloexec = 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]; + for (int fd = 3; fd < 4096 && g_ddh_nbinder < 8; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); + if (len <= 0) continue; + target[len] = 0; + if (strstr(target, "binder")) g_ddh_binder[g_ddh_nbinder++] = fd; + } + 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]); + if (g_ddh_nbinder > 0) g_kept_from_cloexec = 1; + } + ddh_drop_worker_binder(); +} + +// In the program a worker runs for a handed-off child (DDH_TABLE "FD:SLOT:PARENT"): 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() (a signal, _exit()). +static struct ddh_table *g_ddh_report; +static int g_ddh_report_slot = -1; +static pid_t g_ddh_report_parent; + +static void ddh_report_exit(int status, void *unused) { + (void)unused; + if (!g_ddh_report || getpid() != g_ddh_worker) return; + struct ddh_entry *e = &g_ddh_report->e[g_ddh_report_slot]; + e->status = (status & 0xff) << 8; + __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); + if (g_ddh_report_parent > 0) syscall(SYS_kill, g_ddh_report_parent, SIGCHLD); +} + +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; + if (sscanf(spec, "%d:%d:%d", &fd, &slot, &parent) != 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; + on_exit(ddh_report_exit, NULL); +} + +// In a program a worker started: the state its forked parent had, sent along with the exec. +static void ddh_apply_inherited(void) { + 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; + if (getrlimit(RLIMIT_NOFILE, &lim) == 0) { + rlim_t want = (rlim_t)strtoull(nofile, NULL, 10); + 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"); + } +} + __attribute__((constructor)) static void ddh_init(void) { - if (!getenv("DD_SPAWN")) return; + ddh_apply_inherited(); + ddh_find_worker_binder(); + ddh_setup_report(); ddh_find_parent_table(); - ddh_prepare(); + ddh_prepare(0); } static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) { @@ -182,6 +315,7 @@ static void ddh_putarray(struct ddh_buf *b, char *const v[]) { } #define DDH_MAX_FDS 240 +#define DDH_FDS_PER_CHUNK 60 // The fds the program would have inherited: every open fd without FD_CLOEXEC. static int ddh_open_fds(int *fds, int max) { @@ -207,6 +341,15 @@ static int ddh_open_fds(int *fds, int max) { if (fd == dir) 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 (strstr(target, "binder")) continue; + } if (n == max) { syscall(SYS_close, dir); return -1; @@ -272,18 +415,33 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] table = g_ddh_up; table_fd = g_ddh_up_fd; } else { - ddh_debug(envp, "not a child its parent can track:", filename); + 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):", + g_ddh != NULL, (int)g_ddh_owner, g_ddh_up != NULL, g_ddh_up ? g_ddh_up->pad[0] : 0, (int)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 || access(filename, X_OK) != 0) return; + if (!sock || !list) return; + if (access(filename, X_OK) != 0) { + ddh_debug(envp, "not executable here:", 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); char shebang[256]; const char *interp = NULL; + // "python3 SCRIPT" and "sh SCRIPT" are matched by the script's name too + const char *script = argv && argv[0] && argv[1] && argv[1][0] != '-' ? ddh_base(argv[1]) : 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; + !(script && ddh_listed(list, script, argv)) && + !((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv))) { + ddh_debug(envp, "not listed:", filename); + return; + } int fds[DDH_MAX_FDS + 1]; int nfds = ddh_open_fds(fds, DDH_MAX_FDS); @@ -302,6 +460,17 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] pid_t me = getpid(), parent = getppid(); char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof(cwd))) strcpy(cwd, "/"); + // 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); struct ddh_buf b = {0}; for (int pass = 0; pass < 2; pass++) { @@ -319,7 +488,9 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] if (i) ddh_put(&b, ",", 1); ddh_putint(&b, fds[i]); } - ddh_puts(&b, "],\"table\":"); + 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); @@ -327,6 +498,12 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] 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, ",\"umask\":"); + ddh_putint(&b, (long)mask); ddh_puts(&b, "}"); if (pass == 0) { b.cap = b.len + 4; @@ -349,16 +526,30 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] 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)) { + 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) { @@ -541,10 +732,38 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { return 0; } +// 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; +} + 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; } + // -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 (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) syscall(SYS_write, 2, line, (size_t)len); + } return (int)syscall(SYS_kill, pid, sig); } diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7abb578071..ba702d8271 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -10,9 +10,12 @@ // closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when // the hook starts survive close(), close_range() and closefrom(); phones that run ARM code // themselves have none. -#define DDNATV_MAX_KEPT_FDS 4 +#define DDNATV_MAX_KEPT_FDS 12 static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending static int g_kept_fd_count = 0; +// 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_kept_from_cloexec = 0; static int is_kept_fd(int fd) { for (int i = 0; i < g_kept_fd_count; i++) { @@ -448,7 +451,7 @@ static int close_range_part(unsigned int first, unsigned int last, void *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)) { + if (g_kept_fd_count > 0 && (!(flags & CLOSE_RANGE_CLOEXEC) || g_kept_from_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); diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index e477eb4539..ff2339b9e7 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -71,12 +71,18 @@ class FakeSpawner(threading.Thread): conn, _ = self.sock.accept() except OSError: return - header, fds, _, _ = socket.recv_fds(conn, 4, 256) + header = b"" + while len(header) < 4: + header += conn.recv(4 - len(header)) length = struct.unpack(">I", header)[0] payload = b"" while len(payload) < length: payload += conn.recv(length - len(payload)) request = json.loads(payload) + fds = [] + while len(fds) < len(request["fds"]) + 1: + _, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"]) + fds.extend(chunk) self.requests.append(request) table = fds[request["table"]] program = str(self.root) + request["file"]