From 1e022e2430f3dce9283c0dcbc19d5076d8d467b7 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Fri, 27 Nov 2026 10:11:27 -0500
Subject: [PATCH] feat(session): start long-lived daemons in uncounted worker
processes
---
app/src/main/AndroidManifest.xml | 24 ++
.../main/java/com/droiddeck/launcher/App.kt | 2 +
.../launcher/runtime/GuestWorkers.kt | 271 ++++++++++++++++++
.../launcher/session/SessionFiles.kt | 1 +
.../launcher/session/SessionService.kt | 5 +
docs/phantom-processes.md | 35 ++-
.../overlay/usr/local/bin/droiddeck-session | 28 +-
.../overlay/usr/local/bin/droiddeck-spawn | 86 ++++++
8 files changed, 442 insertions(+), 10 deletions(-)
create mode 100644 app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt
create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 55b75d36df..388ac51cc0 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -414,5 +414,29 @@
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..85f2b2e738 100644
--- a/app/src/main/java/com/droiddeck/launcher/App.kt
+++ b/app/src/main/java/com/droiddeck/launcher/App.kt
@@ -20,6 +20,8 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
+ if (android.os.Build.VERSION.SDK_INT >= 28 &&
+ com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
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..d58662e276
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt
@@ -0,0 +1,271 @@
+package com.droiddeck.launcher.runtime
+
+import android.app.ActivityManager
+import android.app.Service
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.ServiceConnection
+import android.net.LocalServerSocket
+import android.net.LocalSocket
+import android.os.Binder
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import android.os.Parcel
+import android.os.ParcelFileDescriptor
+import android.os.Process
+import android.system.ErrnoException
+import android.system.Os
+import android.system.OsConstants
+import android.util.Log
+import org.json.JSONObject
+import java.io.DataInputStream
+import java.io.File
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+/**
+ * A guest program run as the main process of its own Android process.
+ *
+ * Android counts the processes in an app process's cgroup against its child-process limit, but not
+ * the app processes themselves. The worker execs the program in place; its binder fd stays open
+ * across the exec, so the system keeps the process as a live service process. The program's own
+ * children are still counted. See docs/phantom-processes.md.
+ */
+open class GuestWorker : Service() {
+ private val binder = object : Binder() {
+ override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
+ if (code != RUN) return super.onTransact(code, data, reply, flags)
+ val argv = data.createStringArray() ?: return false
+ val env = data.createStringArray() ?: return false
+ val stdio = List(data.readInt()) { data.readFileDescriptor() }
+ reply?.writeInt(Process.myPid())
+ Handler(Looper.getMainLooper()).postDelayed({ exec(argv, env, stdio) }, EXEC_DELAY_MS)
+ return true
+ }
+ }
+
+ override fun onBind(intent: Intent): IBinder = binder
+
+ private fun exec(argv: Array, env: Array, stdio: List) {
+ try {
+ stdio.forEachIndexed { fd, pfd -> if (pfd != null) Os.dup2(pfd.fileDescriptor, fd) }
+ keepBinderOpen()
+ Os.execve(argv[0], argv, env)
+ } catch (e: ErrnoException) {
+ Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
+ }
+ Process.killProcess(Process.myPid())
+ }
+
+ private fun keepBinderOpen() {
+ File("/proc/self/fd").listFiles()?.forEach { link ->
+ val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
+ if (!target.contains("binder")) return@forEach
+ val fd = ParcelFileDescriptor.adoptFd(link.name.toIntOrNull() ?: return@forEach)
+ Os.fcntlInt(fd.fileDescriptor, OsConstants.F_SETFD, 0)
+ kept.add(fd)
+ }
+ }
+
+ companion object {
+ const val RUN = IBinder.FIRST_CALL_TRANSACTION
+ private const val EXEC_DELAY_MS = 100L
+ private const val TAG = "GuestWorker"
+ private val kept = ArrayList()
+
+ fun isWorkerProcess(context: Context, process: String?): Boolean =
+ process != null && process.startsWith(context.packageName + ":g") &&
+ process.substring(context.packageName.length + 2).all { it.isDigit() }
+ }
+}
+
+class GuestWorker0 : GuestWorker()
+class GuestWorker1 : GuestWorker()
+class GuestWorker2 : GuestWorker()
+class GuestWorker3 : GuestWorker()
+class GuestWorker4 : GuestWorker()
+class GuestWorker5 : GuestWorker()
+class GuestWorker6 : GuestWorker()
+class GuestWorker7 : GuestWorker()
+class GuestWorker8 : GuestWorker()
+class GuestWorker9 : GuestWorker()
+class GuestWorker10 : GuestWorker()
+class GuestWorker11 : GuestWorker()
+class GuestWorker12 : GuestWorker()
+class GuestWorker13 : GuestWorker()
+class GuestWorker14 : GuestWorker()
+class GuestWorker15 : GuestWorker()
+class GuestWorker16 : GuestWorker()
+class GuestWorker17 : GuestWorker()
+class GuestWorker18 : GuestWorker()
+class GuestWorker19 : GuestWorker()
+class GuestWorker20 : GuestWorker()
+class GuestWorker21 : GuestWorker()
+class GuestWorker22 : GuestWorker()
+class GuestWorker23 : GuestWorker()
+
+/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
+object GuestWorkers {
+ private const val TAG = "GuestWorkers"
+ private val classes: List> = listOf(
+ GuestWorker0::class.java, GuestWorker1::class.java, GuestWorker2::class.java, GuestWorker3::class.java,
+ GuestWorker4::class.java, GuestWorker5::class.java, GuestWorker6::class.java, GuestWorker7::class.java,
+ GuestWorker8::class.java, GuestWorker9::class.java, GuestWorker10::class.java, GuestWorker11::class.java,
+ GuestWorker12::class.java, GuestWorker13::class.java, GuestWorker14::class.java, GuestWorker15::class.java,
+ GuestWorker16::class.java, GuestWorker17::class.java, GuestWorker18::class.java, GuestWorker19::class.java,
+ GuestWorker20::class.java, GuestWorker21::class.java, GuestWorker22::class.java, GuestWorker23::class.java,
+ )
+
+ private class Slot(val index: Int, val connection: ServiceConnection) {
+ @Volatile var pid = -1
+ }
+
+ private val slots = arrayOfNulls(classes.size)
+ @Volatile private var server: Thread? = null
+
+ fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid()
+
+ /**
+ * Runs [argv] (a host command line) as the main process of a free worker with [env] and the
+ * fds in [stdio] as its 0, 1 and 2. Returns its pid, or -1. Blocks: not for the main thread.
+ * [onExit] runs once the process is gone.
+ */
+ fun start(context: Context, argv: List, env: List, stdio: List, onExit: (Int) -> Unit): Int {
+ val app = context.applicationContext
+ val connected = CountDownLatch(1)
+ var service: IBinder? = null
+ val slot: Slot
+ synchronized(slots) {
+ val index = slots.indexOfFirst { it == null }
+ if (index < 0) {
+ Log.w(TAG, "all ${slots.size} workers are busy")
+ return -1
+ }
+ val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName, binder: IBinder) {
+ service = binder
+ connected.countDown()
+ }
+
+ override fun onServiceDisconnected(name: ComponentName) = release(app, index, onExit)
+
+ override fun onBindingDied(name: ComponentName) = release(app, index, onExit)
+ }
+ slot = Slot(index, connection)
+ slots[index] = slot
+ }
+ val intent = Intent(app, classes[slot.index])
+ if (!app.bindService(intent, slot.connection, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT) ||
+ !connected.await(10, TimeUnit.SECONDS)) {
+ Log.w(TAG, "worker ${slot.index} did not start")
+ release(app, slot.index, null)
+ return -1
+ }
+ val data = Parcel.obtain()
+ val reply = Parcel.obtain()
+ try {
+ data.writeStringArray(argv.toTypedArray())
+ data.writeStringArray(env.toTypedArray())
+ data.writeInt(stdio.size)
+ stdio.forEach { data.writeFileDescriptor(it.fileDescriptor) }
+ service!!.transact(GuestWorker.RUN, data, reply, 0)
+ slot.pid = reply.readInt()
+ } catch (e: Exception) {
+ Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
+ release(app, slot.index, null)
+ return -1
+ } finally {
+ data.recycle()
+ reply.recycle()
+ }
+ Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
+ return slot.pid
+ }
+
+ private fun release(app: Context, index: Int, onExit: ((Int) -> Unit)?) {
+ val slot = synchronized(slots) { slots[index]?.also { slots[index] = null } } ?: return
+ runCatching { app.unbindService(slot.connection) }
+ if (onExit != null) Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start()
+ }
+
+ private fun exitStatus(app: Context, pid: Int): Int {
+ if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1
+ val am = app.getSystemService(ActivityManager::class.java)
+ repeat(20) {
+ am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let { return it.status }
+ Thread.sleep(50)
+ }
+ return -1
+ }
+
+ /** Kills every worker's program; for session teardown. */
+ fun stopAll() {
+ val pids = synchronized(slots) { slots.mapNotNull { it?.pid?.takeIf { pid -> pid > 0 } } }
+ pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
+ Thread.sleep(500)
+ pids.forEach { Process.killProcess(it) }
+ }
+
+ /** Listens for `droiddeck-spawn` requests from the session's guests. */
+ fun serve(context: Context) {
+ val app = context.applicationContext
+ synchronized(this) {
+ if (server != null) return
+ server = Thread({
+ val socket = try {
+ LocalServerSocket(socketName(app))
+ } catch (e: Exception) {
+ Log.e(TAG, "no spawn socket", e)
+ return@Thread
+ }
+ while (true) {
+ val client = runCatching { socket.accept() }.getOrNull() ?: continue
+ Thread({ handle(app, client) }, "guest-spawn").start()
+ }
+ }, "guest-spawn-server").apply { isDaemon = true; start() }
+ }
+ }
+
+ private fun handle(app: Context, client: LocalSocket) {
+ client.use {
+ if (client.peerCredentials.uid != Process.myUid()) return
+ val input = DataInputStream(client.inputStream)
+ val payload = ByteArray(input.readInt()).also { input.readFully(it) }
+ val fds = client.ancillaryFileDescriptors.orEmpty().map { ParcelFileDescriptor.dup(it) }
+ client.ancillaryFileDescriptors?.forEach { runCatching { Os.close(it) } }
+ val request = JSONObject(String(payload))
+ val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } }
+ val envObject = request.getJSONObject("env")
+ val env = LinkedHashMap()
+ envObject.keys().forEach { env[it] = envObject.getString(it) }
+ val cwd = request.optString("cwd", "/")
+ val wait = request.optBoolean("wait", false)
+ val root = env["DDNATV_ROOT"]?.let(::File)
+ val out = client.outputStream
+ if (root == null || argv.isEmpty()) {
+ out.write("error no guest root or program\n".toByteArray())
+ return
+ }
+ val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile }
+ val script = "cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\""
+ val command = NativeGuest.command(root, shell, listOf("-c", script, "droiddeck-spawn", cwd) + argv)
+ env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path
+ val exited = CountDownLatch(1)
+ var status = -1
+ val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, fds) { code ->
+ status = code
+ exited.countDown()
+ }
+ fds.forEach { runCatching { it.close() } }
+ out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
+ out.flush()
+ if (pid > 0 && wait) {
+ exited.await()
+ out.write("exit $status\n".toByteArray())
+ out.flush()
+ }
+ }
+ }
+}
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 aa240b6ed0..b58a97b29d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
@@ -129,6 +129,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
+ "usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
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 f3acf30ba1..53948bdad1 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -701,6 +701,10 @@ class SessionService : Service() {
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
+ if (com.droiddeck.launcher.runtime.NativeGuest.enabled(this)) {
+ com.droiddeck.launcher.runtime.GuestWorkers.serve(this)
+ guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
+ }
// Proton builds up to 11.12 report X11 text fields under this name.
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
@@ -1522,6 +1526,7 @@ class SessionService : Service() {
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
if (!stillSameProcess()) return
+ if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopAll()
val tree = descendants(prootPid)
if (!stillSameProcess()) return
saveWineRegistries(tree)
diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md
index 8ae2ce4d88..5f980b7385 100644
--- a/docs/phantom-processes.md
+++ b/docs/phantom-processes.md
@@ -33,10 +33,11 @@ Source: `frameworks/base/services/core/java/com/android/server/am/PhantomProcess
`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 (least important first), then youngest first, and the surplus is
- killed (`SIGKILL` and `killProcessGroup`). As the foreground app, other apps' phantoms go first,
- so the practical budget is our own 32. The newest process (often the game just launched) is the
- first of ours to go.
+ 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**.
@@ -180,6 +181,32 @@ main process of one worker (Gap 2): full app privileges, direct GPU, normal sign
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).
+
### C. Plan
1. ~~Verify both gaps on the Thor (Android 13, 5.15)~~ done; still to do on one stock Android 14+
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
index 83777ced29..35af03a324 100755
--- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
@@ -14,6 +14,22 @@ export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
+# Starts a long-lived program in its own Android process, which Android does not count against
+# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
+# Its pid is in $dd_spawned either way.
+dd_spawn() {
+ dd_spawned=
+ if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ] && [ -x /usr/local/bin/droiddeck-spawn ]; then
+ local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$
+ if /usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@"; then
+ dd_spawned=$(cat "$f" 2>/dev/null)
+ rm -f "$f"
+ [ -n "$dd_spawned" ] && return 0
+ fi
+ fi
+ "$@" &
+ dd_spawned=$!
+}
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
[ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_STEAM_EXIT_FILE"
@@ -628,7 +644,7 @@ reap_orphans() {
}
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
- /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
+ dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
fi
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
@@ -1384,8 +1400,8 @@ case $mode in
fi
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
write_system_bus_config
- dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
- system_bus=$!
+ dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile
+ system_bus=$dd_spawned
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
sleep 0.1
@@ -1393,8 +1409,8 @@ case $mode in
if [ -S /run/dbus/system_bus_socket ]; then
echo "== network: system bus up, NetworkManager stand-in running"
rm -f "$DD_LAUNCH_DIR/steam-sleep-ready"
- droiddeck-login1 --with-netmanager &
- login_manager=$!
+ dd_spawn droiddeck-login1 --with-netmanager
+ login_manager=$dd_spawned
for ((_i = 0; _i < 50; _i++)); do
[ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break
kill -0 "$login_manager" 2>/dev/null || break
@@ -1418,7 +1434,7 @@ case $mode in
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
_dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
rm -f "$_dd_bus"
- dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile &
+ dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile
for _ in $(seq 1 50); do
[ -S "$_dd_bus" ] && break
nap 0.1
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..1b4123d9cd
--- /dev/null
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+"""Starts a program as the main process of its own Android process, outside the session's cgroup.
+
+usage: droiddeck-spawn [--wait] [--pid-file FILE] [--] PROGRAM [ARGS...]
+
+Android counts the session's processes against its child-process limit; a program started this
+way is not counted (its own children are). It gets this process's environment, working directory
+and stdin/stdout/stderr, and is not a child of the caller: the pid printed on stdout (or written to
+FILE) is the one to signal. Without --wait this returns once the program has started; with --wait
+it waits for it and exits with its status. Where the app offers no spawner, the program is started as a normal child.
+"""
+import array
+import json
+import os
+import socket
+import struct
+import sys
+
+
+def report(pid, pid_file):
+ if pid_file:
+ with open(pid_file, "w") as f:
+ f.write("%s\n" % pid)
+ else:
+ print(pid, flush=True)
+
+
+def fallback(argv, wait, pid_file):
+ pid = os.fork()
+ if pid == 0:
+ try:
+ os.execvp(argv[0], argv)
+ except OSError as e:
+ print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr)
+ os._exit(127)
+ report(pid, pid_file)
+ if wait:
+ return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
+ return 0
+
+
+def main():
+ args = sys.argv[1:]
+ wait = False
+ pid_file = None
+ while args and args[0].startswith("--"):
+ flag = args.pop(0)
+ if flag == "--":
+ break
+ if flag == "--wait":
+ wait = True
+ elif flag == "--pid-file" and args:
+ pid_file = args.pop(0)
+ else:
+ print(__doc__.strip(), file=sys.stderr)
+ return 2
+ if not args:
+ print(__doc__.strip(), file=sys.stderr)
+ return 2
+ name = os.environ.get("DD_SPAWN")
+ if not name:
+ return fallback(args, wait, pid_file)
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ s.connect("\0" + name)
+ except OSError:
+ return fallback(args, wait, pid_file)
+ payload = json.dumps({"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}).encode()
+ s.sendmsg([struct.pack(">I", len(payload)), payload],
+ [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))])
+ reply = s.makefile("r")
+ first = reply.readline().split()
+ if len(first) != 2 or first[0] != "pid":
+ print("droiddeck-spawn: %s; starting %s as a child" % (" ".join(first[1:]) or "no answer", args[0]),
+ file=sys.stderr)
+ return fallback(args, wait, pid_file)
+ report(first[1], pid_file)
+ if not wait:
+ return 0
+ done = reply.readline().split()
+ status = int(done[1]) if len(done) == 2 and done[0] == "exit" else 1
+ return status if 0 <= status < 256 else 128 + (status & 0x7f)
+
+
+if __name__ == "__main__":
+ sys.exit(main())