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 e3f11ead46..d3a03036a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt @@ -81,7 +81,9 @@ object HostProcess { outputFile: File? = null, onOutputComplete: Runnable? = null): Int { val context = com.droiddeck.launcher.runtime.GuestWorkers.context val argv = split(command) - if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context)) { + // A missing working directory fails the launch (start() returns -1 for it), not the program + if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context) || + (dir != null && !dir.isDirectory)) { return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete) } val environment = LinkedHashMap(System.getenv()) diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt index 7a6e0a6707..5bcc716d1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -60,7 +60,7 @@ object PhantomProcessLimit { fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus { if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE val status = readSetting(context, sdk) - return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.enabled(context)) + return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.limitHandled(context)) PhantomProcessStatus.UNCOUNTED else status } @@ -143,6 +143,6 @@ object PhantomProcessLimit { PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)" PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)" PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12" - PhantomProcessStatus.UNCOUNTED -> "on, not needed (the session's programs run in uncounted worker processes)" + PhantomProcessStatus.UNCOUNTED -> "on, not needed (most of the session's programs run in uncounted worker processes)" } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index d51f536c09..501ec8792c 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -42,6 +42,7 @@ open class GuestWorker : Service() { val env = data.createStringArray() ?: return false val fds = List(data.readInt()) { data.readFileDescriptor() } val targets = data.createIntArray() ?: IntArray(fds.size) { it } + val fillBinderFd = data.readInt() != 0 val go = data.readFileDescriptor() reply?.writeInt(Process.myPid()) Handler(Looper.getMainLooper()).post { @@ -59,7 +60,7 @@ open class GuestWorker : Service() { got == 1 }.getOrElse { why = it.toString(); false } go.close() - if (committed) exec(argv, env, fds, targets) + if (committed) exec(argv, env, fds, targets, fillBinderFd) else { Log.w(TAG, "launch not committed ($why): not running ${argv.firstOrNull()}") Process.killProcess(Process.myPid()) @@ -71,7 +72,7 @@ open class GuestWorker : Service() { override fun onBind(intent: Intent): IBinder = binder - private fun exec(argv: Array, env: Array, fds: List, targets: IntArray) { + private fun exec(argv: Array, env: Array, fds: List, targets: IntArray, fillBinderFd: Boolean) { try { val top = targets.maxOrNull() ?: 2 val (binderTop, binderFd) = keepBinderOpen(maxOf(BINDER_FDS, top + 1)) @@ -87,8 +88,14 @@ open class GuestWorker : Service() { // 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). - val fill = { arg: String -> arg.replace(BINDER_FD_TOKEN, binderFd.toString()) } + // The native hook closes the binder fds in every other process (hook/handoff.c). Only an + // app launch asks for the number (a whole argument or variable value), never a guest's. + val fill = { arg: String -> + if (!fillBinderFd) arg + else if (arg == BINDER_FD_TOKEN) binderFd.toString() + else if (arg.endsWith("=$BINDER_FD_TOKEN")) arg.removeSuffix(BINDER_FD_TOKEN) + binderFd + else arg + } // This thread blocks SIGQUIT, SIGUSR1 and SIGPIPE (Android's runtime), and an exec keeps // that: the program's hook sets DDH_SIGMASK instead (none blocked, unless the request says). val mask = if (env.any { it.startsWith("DDH_SIGMASK=") }) emptyList() else listOf("DDH_SIGMASK=0") @@ -125,7 +132,7 @@ open class GuestWorker : Service() { companion object { const val RUN = IBinder.FIRST_CALL_TRANSACTION - /** In a program's arguments or environment, replaced by the number of its kept binder fd. */ + /** An argument, or a variable's whole value, in an app launch: replaced by the number of its kept binder fd. */ const val BINDER_FD_TOKEN = "@DDH_WORKER_BINDER_FD@" private const val GO_TIMEOUT_MS = 2000 private val BINDER_DEVICES = setOf("/dev/binder", "/dev/hwbinder", "/dev/vndbinder") @@ -253,8 +260,11 @@ object GuestWorkers { @Volatile private var warmTarget = 0 // Numbers the sessions: an old session's teardown can still be running when the next one starts. @Volatile private var session = 0 + // The latest session whose teardown has begun + @Volatile private var stopped = 0 private val warming = java.util.concurrent.atomic.AtomicBoolean(false) private const val WARM_WORKERS = 2 + private const val ACK_TIMEOUT_MS = 5000 private val connections = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "guest-worker-binder").apply { isDaemon = true } } @Volatile private var server: Thread? = null @@ -267,6 +277,20 @@ object GuestWorkers { android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) && NativeGuest.enabled(context) + /** How the running session's root was started: in a worker (true) or counted (false); null with none running. */ + @Volatile var sessionRootUncounted: Boolean? = null + + /** + * Whether Android's child-process limit is out of the session's way: as the running session + * started (a proot session, or one whose root fell back to a counted start, is not), else as + * the next one would start. + */ + fun limitHandled(context: Context): Boolean = + sessionRootUncounted ?: (NativeGuest.sessionMode != false && enabled(context)) + + /** Whether pid is a program running in one of the workers. */ + fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } } + fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid() /** @@ -281,12 +305,19 @@ object GuestWorkers { fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, onExit: (Int) -> Unit): Int = start(context, argv, env, fds, targets, false, onExit) - /** [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends. */ + /** + * [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends. + * [commit] runs with the pid before the worker may run the program; false, and it does not. + */ private fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, - guest: Boolean, onExit: (Int) -> Unit): Int { + guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }): Int { val app = context.applicationContext // The session asking: a cold bind can take long enough for it to stop and another to start val owner = session + if (guest && owner <= stopped) { + Log.w(TAG, "session $owner is stopping: not starting ${argv.firstOrNull()}") + return -1 + } val slot = takeWarm() ?: bind(app)?.takeIf { fresh -> fresh.connected.await(10, TimeUnit.SECONDS).also { if (!it) release(app, fresh) } } ?: run { @@ -310,14 +341,24 @@ object GuestWorkers { data.writeInt(fds.size) fds.forEach { data.writeFileDescriptor(it.fileDescriptor) } data.writeIntArray(targets) + data.writeInt(if (guest) 0 else 1) data.writeFileDescriptor(go[0].fileDescriptor) slot.service!!.transact(GuestWorker.RUN, data, reply, 0) val pid = reply.readInt() + // Once a session's teardown has begun (stopGuests), none of its programs may start: it + // would not find them. + val stopping = { guest && owner <= stopped } + if (stopping() || !commit(pid)) { + Log.w(TAG, "worker ${slot.index}: ${argv.firstOrNull()} was not taken on") + release(app, slot) + return -1 + } val live = synchronized(slots) { - (slots[slot.index] === slot).also { if (it) { slot.pid = pid; slot.started = true } } + (slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.started = true } } } if (!live) { - Log.w(TAG, "worker ${slot.index} ended before running ${argv.firstOrNull()}") + Log.w(TAG, "worker ${slot.index} ended, or its session is stopping, before running ${argv.firstOrNull()}") + release(app, slot) return -1 } Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) @@ -439,6 +480,7 @@ object GuestWorkers { fun stopGuests(of: Int = session) { // the check and the reset together: a new session's serve() may be under way val drained = synchronized(slots) { + stopped = maxOf(stopped, of) if (of != session) emptyList() else { warmTarget = 0; warm.toList().also { warm.clear() } } } context?.let { app -> drained.forEach { release(app, it) } } @@ -544,7 +586,7 @@ object GuestWorkers { val tableFd = (numbers.maxOrNull() ?: 2) + 1 programFds = programFds + table targets = numbers + tableFd - env["DDH_TABLE"] = "$tableFd:$slot:$parent" + env["DDH_TABLE"] = "$tableFd:$slot:$parent:${request.optInt("child", -1)}" } val root = env["DDNATV_ROOT"]?.let(::File) val out = client.outputStream @@ -554,10 +596,10 @@ object GuestWorkers { } val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile } val args = if (file.isNotEmpty()) { - listOf("-c", "cd -- \"\$1\" 2>/dev/null; a=\$2; f=\$3; shift 3; exec -a \"\$a\" \"\$f\" \"\$@\"", + listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; a=\$2; f=\$3; shift 3; exec -a \"\$a\" \"\$f\" \"\$@\"", "droiddeck-spawn", cwd, argv[0], file) + argv.drop(1) } else { - listOf("-c", "cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"", "droiddeck-spawn", cwd) + argv + listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"", "droiddeck-spawn", cwd) + argv } val command = NativeGuest.command(root, shell, args) env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path @@ -570,21 +612,45 @@ object GuestWorkers { if (request.has("pstart")) env["DDH_PSTART"] = request.getLong("pstart").toString() if (request.has("astart")) env["DDH_ASTART"] = request.getLong("astart").toString() env["DDH_SIGMASK"] = request.optLong("sigmask", 0L).toString() + // The shell above: the hook restores nothing there (bash changes its own signal mask), + // only in the program it execs, which no longer has this. + env["DDH_WRAPPER"] = "1" val child = request.optInt("child", -1) val exited = CountDownLatch(1) var status = -1 var worker = -1 - val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true) { code -> + // The hook answers the pid with "go" (ack): without it (it died, or gave up and runs the + // program itself) the worker must not run it too. + val ack = request.optBoolean("ack", false) + var answered = false + 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, child, worker) exited.countDown() + }) { started -> + worker = started + if (!ack) return@start true + runCatching { + out.write("pid $started\n".toByteArray()) + out.flush() + answered = true + client.soTimeout = ACK_TIMEOUT_MS + val line = StringBuilder() + while (true) { + val c = input.read() + if (c < 0 || c == '\n'.code) break + line.append(c.toChar()) + } + line.toString() == "go" + }.getOrDefault(false) } - worker = pid handedOver = true 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() + if (!answered) { + out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray()) + out.flush() + } if (pid > 0 && wait) { exited.await() // droiddeck-spawn exits with this: an exit code, or 128 plus the signal 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 275e3ae5e3..33a6b726db 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -890,6 +890,7 @@ class SessionService : Service() { return } sessionPid = pid + com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid) if (pid > 1) { raiseTracer(pid, gen) SessionEvents.guestStarted(pid) @@ -2340,6 +2341,7 @@ class SessionService : Service() { gameExitWatchToken++ // also when startup stopped before the guest ran com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null + com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null if (!SessionState.running) return if (relaunch) SessionState.confirmRelaunchStop() SessionEvents.record("guest.exited", mapOf("status" to status)) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index efe05f1257..cd0072dbea 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2743,7 +2743,7 @@ Steam sessions can start. This Android version does not use this limit. Child-process limit handled by DroidDeck - DroidDeck runs the session\'s programs in processes Android does not count, so Developer options can stay off. + DroidDeck runs most of the session\'s programs in processes Android does not count, which keeps the session well under the limit, so Developer options can stay off. Steam and some of its helpers still count. Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards. This Android version has no switch for it. Use Wireless debugging to change it from this device. This build has no download for this copy of DroidDeck. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 6972e9d955..fa82399544 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -16,20 +16,30 @@ 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. +# Its pid is in $dd_spawned either way, and the ones not started as jobs in $dd_daemons, which +# the session stops as it ends. +dd_daemons= dd_spawn() { dd_spawned= if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ] && [ -x /usr/local/bin/droiddeck-spawn ]; then - local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$ - 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 + local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$ rc=0 + /usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@" || rc=$? + dd_spawned=$(cat "$f" 2>/dev/null) + rm -f "$f" + if [ "$rc" = 0 ] && [ -n "$dd_spawned" ]; then + dd_daemons="$dd_daemons $dd_spawned" + return 0 fi + # started, but its pid is unknown: not a second time + [ "$rc" = 3 ] && { dd_spawned=; return 0; } fi "$@" & dd_spawned=$! } +dd_stop_daemons() { + [ -n "$dd_daemons" ] && kill $dd_daemons 2>/dev/null + dd_daemons= +} dd_session_pid=$$ # Runs function $1 (with its arguments) in the background in a new bash that first loads this shell's # variables, functions and options: a background subshell, but an exec'd program, which the native @@ -2069,6 +2079,7 @@ case $mode in wait "$decky_supervisor" 2>/dev/null || true echo "== Decky: session supervisor stopped" fi + dd_stop_daemons _dd_jobs=$(jobs -p) [ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null echo "== steam: the client on the desktop has exited" @@ -2078,6 +2089,7 @@ case $mode in wait "$decky_supervisor" 2>/dev/null || true echo "== Decky: session supervisor stopped" fi + dd_stop_daemons _dd_jobs=$(jobs -p) [ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null reap_orphans diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn index 1b4123d9cd..55c13280a3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn @@ -17,12 +17,22 @@ import struct import sys +# Exit status when the program started but its pid could not be reported: the caller must not +# start it again. +STARTED_UNREPORTED = 3 + + def report(pid, pid_file): - if pid_file: - with open(pid_file, "w") as f: - f.write("%s\n" % pid) - else: - print(pid, flush=True) + try: + if pid_file: + with open(pid_file, "w") as f: + f.write("%s\n" % pid) + else: + print(pid, flush=True) + return True + except OSError as e: + print("droiddeck-spawn: started pid %s but could not report it: %s" % (pid, e), file=sys.stderr) + return False def fallback(argv, wait, pid_file): @@ -33,10 +43,10 @@ def fallback(argv, wait, pid_file): except OSError as e: print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr) os._exit(127) - report(pid, pid_file) + reported = report(pid, pid_file) if wait: return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) - return 0 + return 0 if reported else STARTED_UNREPORTED def main(): @@ -74,9 +84,9 @@ def main(): 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) + reported = report(first[1], pid_file) if not wait: - return 0 + return 0 if reported else STARTED_UNREPORTED done = reply.readline().split() status = int(done[1]) if len(done) == 2 and done[0] == "exit" else 1 return status if 0 <= status < 256 else 128 + (status & 0x7f) diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index dfbe927b71..462636efc0 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -660,7 +660,7 @@ 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); + ddh_prepare(); 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 diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index faf5ca192c..8caf45ee7a 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -83,24 +83,33 @@ static int ddh_is_binder(const char *target) { strcmp(target, "/dev/vndbinder") == 0 || strncmp(target, "/dev/binderfs/", 14) == 0; } -// 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; +// The table the children write to, in a process of a session that hands programs off (DD_SPAWN). +// One thread makes it; a fork() while another thread is making it goes without (its child runs here). +static void ddh_prepare(void) { + static int busy; + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN")) return; + if (__atomic_exchange_n(&busy, 1, __ATOMIC_ACQ_REL)) return; + if (g_ddh) { + __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); + return; + } int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); if (fd < 0) { ddh_prepare_failed("memfd_create"); + __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); return; } if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { ddh_prepare_failed("ftruncate"); close(fd); + __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); return; } - void *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + struct ddh_table *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { ddh_prepare_failed("mmap"); close(fd); + __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); return; } // Out of the way of the numbers programs redirect, and kept open when a child closes every @@ -111,16 +120,17 @@ static void ddh_prepare(int any) { fd = high; } ddh_keep(fd); - g_ddh = p; - g_ddh->magic = DDH_MAGIC; - g_ddh->pad[0] = getpid(); + p->magic = DDH_MAGIC; + p->pad[0] = getpid(); // A nonce that tells this table's fd from any other (inode numbers are rewritten by the hardlink emulation) - if (syscall(SYS_getrandom, &g_ddh->pad[1], 2 * sizeof(int32_t), 0) != 2 * (long)sizeof(int32_t)) { - g_ddh->pad[1] = (int32_t)time(NULL); - g_ddh->pad[2] = (int32_t)(intptr_t)p; + if (syscall(SYS_getrandom, &p->pad[1], 2 * sizeof(int32_t), 0) != 2 * (long)sizeof(int32_t)) { + p->pad[1] = (int32_t)time(NULL); + p->pad[2] = (int32_t)(intptr_t)p; } g_ddh_fd = fd; g_ddh_owner = getpid(); + __atomic_store_n(&g_ddh, p, __ATOMIC_RELEASE); + __atomic_store_n(&busy, 0, __ATOMIC_RELEASE); } // Whether fd is still this table: a program may have put a file of its own at that number. @@ -130,6 +140,30 @@ static int ddh_is_table(int fd, const struct ddh_table *t) { return head[0] == t->magic && head[1] == t->pad[0] && head[2] == t->pad[1] && head[3] == t->pad[2]; } +// The open fds from 3 on, ascending (as /proc lists them): how many, at most max; -1 without /proc. +static int ddh_list_fds(int *fds, int max) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + int n = 0; + char buf[4096]; + long got; + while ((got = syscall(SYS_getdents64, dir, buf, sizeof(buf))) > 0) { + for (long off = 0; off < got;) { + unsigned short reclen; + memcpy(&reclen, buf + off + 16, sizeof(reclen)); + const char *name = buf + off + 19; + off += reclen ? reclen : got; + if (name[0] < '0' || name[0] > '9') continue; + int fd = atoi(name); + if (fd >= 3 && fd != dir && n < max) fds[n++] = fd; + } + } + syscall(SYS_close, dir); + return n; +} + +#define DDH_LISTED_FDS 2048 + // A table inherited across exec: the parent's if its owner is still our parent, else closed. static void ddh_find_parent_table(void) { char path[64], target[64]; @@ -138,7 +172,10 @@ static void ddh_find_parent_table(void) { int report = -1; const char *spec = getenv("DDH_TABLE"); if (spec && getenv("DDH_WORKER_PID") && atoi(getenv("DDH_WORKER_PID")) == getpid()) report = atoi(spec); - for (int fd = 3; fd < 1024; fd++) { + static int open_fds[DDH_LISTED_FDS]; + int count = ddh_list_fds(open_fds, DDH_LISTED_FDS); + for (int i = 0; i < count; i++) { + int fd = open_fds[i]; if (fd == report) { ddh_keep(fd); continue; @@ -195,7 +232,7 @@ static void ddh_drop_worker_binder(void) { syscall(SYS_close, g_ddh_binder[i]); } g_ddh_nbinder = 0; - g_kept_from_cloexec = 0; + g_cloexec_kept_count = 0; } static void ddh_find_worker_binder(void) { @@ -203,27 +240,33 @@ static void ddh_find_worker_binder(void) { 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); + static int open_fds[DDH_LISTED_FDS]; + int count = ddh_list_fds(open_fds, DDH_LISTED_FDS); + for (int i = 0; i < count && g_ddh_nbinder < 8; i++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", open_fds[i]); long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); if (len <= 0) continue; target[len] = 0; - if (ddh_is_binder(target)) g_ddh_binder[g_ddh_nbinder++] = fd; + if (ddh_is_binder(target)) g_ddh_binder[g_ddh_nbinder++] = open_fds[i]; } if (getpid() == g_ddh_worker) { // The program closing every fd it did not open (gamescope does) would end the worker. - for (int i = 0; i < g_ddh_nbinder; i++) ddh_keep(g_ddh_binder[i]); - if (g_ddh_nbinder > 0) g_kept_from_cloexec = 1; + for (int i = 0; i < g_ddh_nbinder; i++) { + ddh_keep(g_ddh_binder[i]); + g_cloexec_kept_fds[i] = g_ddh_binder[i]; + } + g_cloexec_kept_count = g_ddh_nbinder; } ddh_drop_worker_binder(); } -// In the program a worker runs for a handed-off child (DDH_TABLE "FD:SLOT:PARENT"): its exit status -// goes into the parent's table here; the app reports it from Android's exit record only when the -// program never got to exit() or _exit() (a signal). +// In the program a worker runs for a handed-off child (DDH_TABLE "FD:SLOT:PARENT:CHILD"): its exit +// status goes into the parent's table here; the app reports it from Android's exit record only when +// the program never got to exit() or _exit() (a signal). static struct ddh_table *g_ddh_report; static int g_ddh_report_slot = -1; static pid_t g_ddh_report_parent; +static pid_t g_ddh_report_child; // The line of /proc/PID/cgroup that names the app's per-process cgroup ("...:/uid_U/pid_P"). static int ddh_cgroup_line(pid_t pid, const char *want, char *out, size_t size) { @@ -350,9 +393,15 @@ static void ddh_report_exit(int status, void *from_exit) { // exit() flushes stdio after its on_exit() handlers: before the parent can see the exit here if (from_exit) fflush(NULL); struct ddh_entry *e = &g_ddh_report->e[g_ddh_report_slot]; - 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); + // Still this program's entry: the parent frees it when the forked child dies before handing off + // (and a later child may have it by now). + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_HANDED || st == DDH_CLAIMED) && e->parent == g_ddh_report_parent && + (g_ddh_report_child <= 0 || e->child == g_ddh_report_child)) { + 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); + } ddh_linger(from_exit != NULL); ddh_unregister_group(); } @@ -379,19 +428,23 @@ void _Exit(int status) { static void ddh_setup_report(void) { const char *spec = getenv("DDH_TABLE"); if (!spec || g_ddh_worker != getpid()) return; - int fd = -1, slot = -1, parent = 0; - if (sscanf(spec, "%d:%d:%d", &fd, &slot, &parent) != 3 || slot < 0 || slot >= DDH_SLOTS) return; + int fd = -1, slot = -1, parent = 0, child = 0; + if (sscanf(spec, "%d:%d:%d:%d", &fd, &slot, &parent, &child) < 3 || slot < 0 || slot >= DDH_SLOTS) return; struct ddh_table *t = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (t == MAP_FAILED || t->magic != DDH_MAGIC) return; g_ddh_report = t; g_ddh_report_slot = slot; g_ddh_report_parent = parent; + g_ddh_report_child = child; on_exit(ddh_report_exit, (void *)1); ddh_register_group(); } -// In a program a worker started: the state its forked parent had, sent along with the exec. +// In a program a worker started: the state its forked parent had, sent along with the exec. Not in +// the app's shell that execs it (DDH_WRAPPER): bash changes its signal mask (it unblocks SIGCHLD), +// and its exec keeps bash's. static void ddh_apply_inherited(void) { + if (getenv("DDH_WRAPPER")) return; const char *ign = getenv("DDH_SIGIGN"); if (ign) { unsigned long mask = strtoul(ign, NULL, 10); @@ -440,7 +493,7 @@ __attribute__((constructor)) static void ddh_init(void) { ddh_find_worker_binder(); ddh_setup_report(); ddh_find_parent_table(); - ddh_prepare(0); + ddh_prepare(); } static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) { @@ -527,8 +580,8 @@ 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) { +// The fds the program would have inherited: every open fd without FD_CLOEXEC, but skip (the table). +static int ddh_open_fds(int *fds, int max, int skip) { int n = 0; int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (dir < 0) return -1; @@ -548,7 +601,7 @@ static int ddh_open_fds(int *fds, int max) { 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; + if (fd == dir || fd == skip) continue; int flags = (int)syscall(SYS_fcntl, fd, F_GETFD); if (flags < 0 || (flags & FD_CLOEXEC)) continue; // A worker's binder fd, inherited from the worker this process runs in: it keeps that @@ -609,6 +662,28 @@ static const char *ddh_interpreter(const char *path, char *buf, size_t size) { return name; } +// Whether an exec of path would get as far as the program: an ELF file, or a script whose "#!" +// interpreter is there to run. Anything else fails in the exec, which must happen here then, so that +// the caller (posix_spawn() above all) gets its error rather than a worker's exit status. +static int ddh_startable(const char *path) { + char real[PATH_MAX], head[256]; + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(path, real, sizeof(real)), + O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)head, sizeof(head) - 1, 0, 0, 0); + syscall(SYS_close, fd); + if (n >= 4 && memcmp(head, "\177ELF", 4) == 0) return 1; + if (n < 3 || head[0] != '#' || head[1] != '!') return 0; + head[n] = 0; + char *p = head + 2; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\n' && *end != '\r') end++; + *end = 0; + if (*p != '/') return 0; + return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(p, real, sizeof(real)), X_OK, 0, 0, 0) == 0; +} + static int ddh_program_listed(const char *list, const char *filename, char *const argv[]) { char shebang[256]; const char *interp; @@ -682,9 +757,13 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] ddh_debug(envp, "not listed:", filename); return; } + if (!ddh_startable(filename)) { + ddh_debug(envp, "would not start:", filename); + return; + } int fds[DDH_MAX_FDS + 1]; - int nfds = ddh_open_fds(fds, DDH_MAX_FDS); + int nfds = ddh_open_fds(fds, DDH_MAX_FDS, table_fd); if (nfds < 0) return; int slot = -1; @@ -703,6 +782,7 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] e->child = me; e->parent = parent; e->real = 0; + e->pad[1] = getpgrp(); // the group waitpid(0) and waitpid(-GROUP) pick it by 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 @@ -769,7 +849,8 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] ddh_putint(&b, parent_start); ddh_puts(&b, ",\"astart\":"); ddh_putint(&b, anchor_start); - ddh_puts(&b, "}"); + // the worker runs the program only once this side has its pid (the "go" below) + ddh_puts(&b, ",\"ack\":true}"); if (pass == 0) { b.cap = b.len + 4; b.p = mmap(NULL, b.cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); @@ -825,6 +906,8 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] } reply[got] = 0; if (strncmp(reply, "pid ", 4) == 0) pid = atol(reply + 4); + // Without it the app does not let the worker run the program, and it runs here. + if (pid > 0 && syscall(SYS_sendto, s, "go\n", 3, MSG_NOSIGNAL, NULL, 0) != 3) pid = -1; } } } @@ -858,23 +941,41 @@ static struct ddh_entry *ddh_find(pid_t child) { return NULL; } -static int ddh_any_live(void) { +// Whether a wait for pid (-1: any child, 0: one in our group, -G: one in group G) takes e's child. +static int ddh_selects(const struct ddh_entry *e, pid_t pid) { + if (pid > 0) return e->child == pid; + if (pid == -1) return 1; + return e->pad[1] == (pid == 0 ? getpgrp() : -pid); +} + +static int ddh_any_live(pid_t pid) { 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; + if ((st == DDH_HANDED || st == DDH_EXITED) && e->parent == me && ddh_selects(e, pid)) return 1; } return 0; } -static struct ddh_entry *ddh_exited(void) { +static struct ddh_entry *ddh_exited(pid_t pid) { 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; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_EXITED && e->parent == me && ddh_selects(e, pid)) return e; + } + return NULL; +} + +// The entry of child while it is still handing its program off (its request is with the app). +static struct ddh_entry *ddh_claiming(pid_t child) { + if (!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]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_CLAIMED && e->parent == me && e->child == child) return e; } return NULL; } @@ -907,6 +1008,7 @@ static void ddh_release(struct ddh_entry *e, int *status) { e->status = 0; e->reaped = 0; e->pad[0] = 0; + e->pad[1] = 0; __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); } @@ -927,14 +1029,25 @@ static int ddh_reap_shim(ddh_wait4_f real, pid_t child, int options) { return r == child || (r < 0 && errno == ECHILD); } +// 20 ms, or -1 (EINTR) when a signal's handler interrupted it. The read of a timerfd restarts, as a +// wait does, after a handler installed with SA_RESTART; nanosleep() never does. static int ddh_nap(void) { - struct timespec ts = {0, 20 * 1000 * 1000}; - if (nanosleep(&ts, NULL) == 0) return 0; - struct sigaction sa; - if (errno == EINTR && sigaction(SIGCHLD, NULL, &sa) == 0 && - (sa.sa_handler == SIG_DFL || sa.sa_handler == SIG_IGN || (sa.sa_flags & SA_RESTART))) + int fd = (int)syscall(SYS_timerfd_create, CLOCK_MONOTONIC, O_CLOEXEC); + if (fd < 0) { + struct timespec ts = {0, 20 * 1000 * 1000}; + nanosleep(&ts, NULL); return 0; - return -1; + } + struct itimerspec when = {{0, 0}, {0, 20 * 1000 * 1000}}; + uint64_t ticks; + long r = syscall(SYS_timerfd_settime, fd, 0, &when, NULL) == 0 ? syscall(SYS_read, fd, &ticks, sizeof(ticks)) : 0; + int err = errno; + syscall(SYS_close, fd); + if (r < 0 && err == EINTR) { + errno = EINTR; + return -1; + } + return 0; } static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { @@ -944,6 +1057,9 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { return -1; } if (!g_ddh) return real(pid, status, options, ru); + // After a nap a signal interrupted, one more look before EINTR: the signal may be the SIGCHLD + // that reports an exit. + int interrupted = 0; for (;;) { ddh_check_gone(); struct ddh_entry *e = pid > 0 ? ddh_find(pid) : NULL; @@ -958,17 +1074,18 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { return pid; } if (options & WNOHANG) return 0; - if (ddh_nap() != 0) return -1; + if (interrupted) return -1; + interrupted = ddh_nap() != 0; continue; } - if (pid <= 0 && (e = ddh_exited())) { + if (pid <= 0 && (e = ddh_exited(pid))) { pid_t child = e->child; if (!e->reaped && !ddh_reap_shim(real, child, options)) return (options & WNOHANG) ? 0 : -1; if (ru) memset(ru, 0, sizeof(*ru)); ddh_release(e, status); return child; } - int live = pid <= 0 && ddh_any_live(); + int live = pid <= 0 && ddh_any_live(pid); int wstatus = 0; pid_t r = real(pid, &wstatus, live ? options | WNOHANG : options, ru); if (r > 0) { @@ -977,13 +1094,19 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { h->reaped = 1; // the forked child that handed its program off continue; } + // A forked child that died while handing its program off (a signal): its entry is done. + if (!h && (h = ddh_claiming(r))) ddh_release(h, NULL); 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; + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; } } @@ -1001,12 +1124,14 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { return -1; } // An ordinary child asked for by pid: the real call, with all its options (stops, WNOWAIT). - if (!g_ddh || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL) || !ddh_any_live() || - (idtype == P_PID && !ddh_find((pid_t)id))) + // As a waitpid() selector: a pid, -1 for any child, 0 for our group, -G for group G + pid_t which = idtype == P_PID ? (pid_t)id : idtype == P_PGID ? (id == 0 ? 0 : -(pid_t)id) : -1; + if (!g_ddh || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || + (idtype == P_PID ? !ddh_find(which) : !ddh_any_live(which))) 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); + pid_t r = ddh_wait(which, &status, options & WNOHANG, NULL); if (r < 0) return -1; if (info) { memset(info, 0, sizeof(*info)); @@ -1271,6 +1396,14 @@ int killpg(int pgrp, int sig) { int kill(pid_t pid, int sig) { if (g_ddh && pid > 0) { + // A child still handing its program off: the signal is for the program, which the forked + // child (stopped or killed by it) could no longer hand off or account for. Up to 3 s for the + // app's answer; a cold worker start takes well under one. + struct ddh_entry *claim = ddh_claiming(pid); + for (int i = 0; claim && i < 300 && __atomic_load_n(&claim->state, __ATOMIC_ACQUIRE) == DDH_CLAIMED; i++) { + struct timespec ts = {0, 10 * 1000 * 1000}; + nanosleep(&ts, NULL); + } struct ddh_entry *e = ddh_find(pid); if (e && __atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_HANDED) pid = e->real; } diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index ba702d8271..b40afa1127 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -13,9 +13,10 @@ #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; +// Of those, the ones also kept from close-on-exec: a worker process's binder fds (hook/handoff.c), +// which must outlive the program's own execs. +static int g_cloexec_kept_fds[8]; // ascending +static int g_cloexec_kept_count = 0; static int is_kept_fd(int fd) { for (int i = 0; i < g_kept_fd_count; i++) { @@ -451,7 +452,10 @@ 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) || g_kept_from_cloexec)) { + if (flags & CLOSE_RANGE_CLOEXEC) { + if (g_cloexec_kept_count > 0) + return for_each_range_without(first, last, g_cloexec_kept_fds, g_cloexec_kept_count, close_range_part, &flags); + } else if (g_kept_fd_count > 0) { 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/phantomlab/build.sh b/tools/phantomlab/build.sh index 9f766128fe..a7afcfaa9a 100644 --- a/tools/phantomlab/build.sh +++ b/tools/phantomlab/build.sh @@ -17,8 +17,12 @@ bat="" rm -rf "$work/classes" "$work/dex" "$work/lib" "$work/unsigned.apk" mkdir -p "$work/classes" "$work/dex" -javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" $(find "$here/src" -name '*.java') 2>&1 | grep -v "^warning\|^Note:" || true -"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" $(find "$work/classes" -name '*.class') +sources=() +while IFS= read -r -d '' f; do sources+=("$f"); done < <(find "$here/src" -name '*.java' -print0) +javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" "${sources[@]}" 2>&1 | { grep -v "^warning\|^Note:" || true; } +classes=() +while IFS= read -r -d '' f; do classes+=("$f"); done < <(find "$work/classes" -name '*.class' -print0) +"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" "${classes[@]}" host=$(ls -d "$ndk"/toolchains/llvm/prebuilt/* | head -1) for abi in arm64-v8a x86_64; do diff --git a/tools/phantomlab/jni/exe.c b/tools/phantomlab/jni/exe.c index c3bee8003f..a87d2a4ede 100644 --- a/tools/phantomlab/jni/exe.c +++ b/tools/phantomlab/jni/exe.c @@ -1,13 +1,16 @@ // libplabexe.so: an executable shipped as a "library" so the APK's lib directory holds it. // Reports its identity and reads fd 3 when it is open, then exits with status 7. #include +#include #include #include #include int main(int argc, char **argv) { char buf[128] = ""; - ssize_t n = read(3, buf, sizeof(buf) - 1); + ssize_t n = -1; + struct pollfd p = {.fd = 3, .events = POLLIN}; + if (poll(&p, 1, 500) > 0 && (p.revents & (POLLIN | POLLHUP))) n = read(3, buf, sizeof(buf) - 1); if (n > 0) buf[n] = 0; char ctx[128] = ""; int fd = open("/proc/self/attr/current", O_RDONLY); diff --git a/tools/phantomlab/jni/lab.c b/tools/phantomlab/jni/lab.c index 58c026f772..811de3facd 100644 --- a/tools/phantomlab/jni/lab.c +++ b/tools/phantomlab/jni/lab.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -33,12 +34,17 @@ JNIEXPORT jint JNICALL Java_com_droiddeck_phantomlab_Native_spawn(JNIEnv *env, j return made; } -static void keep_binder_fds(void) { +struct kept_fd { + int fd, flags; +}; + +static int keep_binder_fds(struct kept_fd *kept, int max) { DIR *d = opendir("/proc/self/fd"); - if (!d) return; + if (!d) return 0; + int count = 0; struct dirent *e; char path[64], target[256]; - while ((e = readdir(d)) != NULL) { + while ((e = readdir(d)) != NULL && count < max) { int fd = atoi(e->d_name); if (fd <= 2) continue; snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); @@ -46,11 +52,16 @@ static void keep_binder_fds(void) { if (len <= 0) continue; target[len] = 0; if (strstr(target, "binder")) { - fcntl(fd, F_SETFD, 0); + int flags = fcntl(fd, F_GETFD); + if (flags < 0 || fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) != 0) continue; + kept[count].fd = fd; + kept[count].flags = flags; + count++; __android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target); } } closedir(d); + return count; } JNIEXPORT void JNICALL Java_com_droiddeck_phantomlab_Native_execInPlace(JNIEnv *env, jclass cls, jobjectArray jargv, jboolean keep) { @@ -61,9 +72,11 @@ JNIEXPORT void JNICALL Java_com_droiddeck_phantomlab_Native_execInPlace(JNIEnv * const char *c = (*env)->GetStringUTFChars(env, s, NULL); argv[i] = strdup(c); } - if (keep) keep_binder_fds(); + struct kept_fd kept[16]; + int kept_count = keep ? keep_binder_fds(kept, 16) : 0; execv(argv[0], argv); __android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno)); + for (int i = 0; i < kept_count; i++) fcntl(kept[i].fd, F_SETFD, kept[i].flags); } static char *report; @@ -134,6 +147,10 @@ static void probe_anon_exec(void) { static int run_child(char *const argv[], int execfd) { pid_t pid = fork(); + if (pid < 0) { + out("fork: %s", strerror(errno)); + return -1; + } if (pid == 0) { if (execfd >= 0) syscall(SYS_execveat, execfd, "", argv, environ, AT_EMPTY_PATH); else execv(argv[0], argv); @@ -144,10 +161,59 @@ static int run_child(char *const argv[], int execfd) { return WIFEXITED(status) ? WEXITSTATUS(status) : 1000 + WTERMSIG(status); } +static const char *exec_result(int st, const char *ran) { + if (st < 0) return "not run"; + return st >= 100 && st < 1000 ? strerror(st - 100) : ran; +} + +static int wait_fd(int fd, short events) { + struct pollfd p = {.fd = fd, .events = events}; + int r = poll(&p, 1, 2000); + if (r == 0) errno = ETIMEDOUT; + return r > 0 ? 0 : -1; +} + +static void probe_tcp(int i, int fd) { + struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)}; + inet_pton(AF_INET, "1.1.1.1", &a.sin_addr); + int fl = fcntl(fd, F_GETFL); + if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) != 0) { + out("fd%d tcp: fcntl %s", i, strerror(errno)); + return; + } + int r = connect(fd, (struct sockaddr *)&a, sizeof(a)); + if (r != 0 && errno == EINPROGRESS) { + int err = 0; + socklen_t el = sizeof(err); + if (wait_fd(fd, POLLOUT) == 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) == 0) { + r = err ? -1 : 0; + errno = err; + } else { + r = -1; + } + } + if (r != 0) { + out("fd%d tcp: connect %s", i, strerror(errno)); + } else { + const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n"; + if (wait_fd(fd, POLLOUT) != 0 || write(fd, req, strlen(req)) < 0) { + out("fd%d tcp: connected, write %s", i, strerror(errno)); + } else { + char resp[64] = ""; + ssize_t n = wait_fd(fd, POLLIN) == 0 ? read(fd, resp, sizeof(resp) - 1) : -1; + if (n > 0) resp[n] = 0; + char *nl = strchr(resp, '\r'); + if (nl) *nl = 0; + out("fd%d tcp: connected, got \"%s\"", i, n > 0 ? resp : strerror(errno)); + } + } + fcntl(fd, F_SETFL, fl); +} + static void probe_exec(void) { char *argv[] = {"/system/bin/true", NULL}; int st = run_child(argv, -1); - out("execve /system/bin/true: %s", st == 0 ? "ok" : (st >= 100 && st < 1000 ? strerror(st - 100) : "status")); + out("execve /system/bin/true: %s", exec_result(st, st == 0 ? "ok" : "status")); int src = open("/system/bin/toybox", O_RDONLY); int mfd = syscall(SYS_memfd_create, "toybox", 0); char buf[65536]; @@ -156,7 +222,7 @@ static void probe_exec(void) { if (src >= 0) close(src); char *targv[] = {"true", NULL}; st = run_child(targv, mfd); - out("execveat memfd(toybox true): %s", st == 0 ? "ok" : (st >= 100 && st < 1000 ? strerror(st - 100) : "status")); + out("execveat memfd(toybox true): %s", exec_result(st, st == 0 ? "ok" : "status")); close(mfd); } @@ -180,20 +246,7 @@ static void probe_fd(int i, int fd) { getsockname(fd, (struct sockaddr *)&ss, &al); family = ss.ss_family; if (family == AF_INET && type == SOCK_STREAM) { - struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)}; - inet_pton(AF_INET, "1.1.1.1", &a.sin_addr); - if (connect(fd, (struct sockaddr *)&a, sizeof(a)) != 0) { - out("fd%d tcp: connect %s", i, strerror(errno)); - return; - } - const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n"; - write(fd, req, strlen(req)); - char resp[64] = ""; - ssize_t r = read(fd, resp, sizeof(resp) - 1); - if (r > 0) resp[r] = 0; - char *nl = strchr(resp, '\r'); - if (nl) *nl = 0; - out("fd%d tcp: connected, got \"%s\"", i, r > 0 ? resp : strerror(errno)); + probe_tcp(i, fd); } else if (family == AF_INET && type == SOCK_DGRAM) { struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(53)}; inet_pton(AF_INET, "1.1.1.1", &a.sin_addr); @@ -201,7 +254,7 @@ static void probe_fd(int i, int fd) { out("fd%d udp: connect %s", i, r == 0 ? "ok" : strerror(errno)); } else { char buf[64] = ""; - ssize_t r = read(fd, buf, sizeof(buf) - 1); + ssize_t r = wait_fd(fd, POLLIN) == 0 ? read(fd, buf, sizeof(buf) - 1) : -1; if (r > 0) buf[r - 1] = 0; out("fd%d unix(family %d): read %s", i, family, r > 0 ? buf : strerror(errno)); } @@ -225,7 +278,7 @@ static void probe_fd(int i, int fd) { if (p != MAP_FAILED) munmap(p, 4096); char *argv[] = {"x", NULL}; int st2 = run_child(argv, fd); - out("fd%d execveat: %s", i, st2 >= 100 && st2 < 1000 ? strerror(st2 - 100) : "ran"); + out("fd%d execveat: %s", i, exec_result(st2, "ran")); } static void probe_self(void) { @@ -314,8 +367,17 @@ static void probe_escape(void) { // Runs path with fd as its fd 3 and its stderr captured. static void probe_libexec(const char *path, int fd) { int pipefd[2]; - pipe(pipefd); + if (pipe(pipefd) != 0) { + out("exec %s: pipe %s", path, strerror(errno)); + return; + } pid_t pid = fork(); + if (pid < 0) { + out("exec %s: fork %s", path, strerror(errno)); + close(pipefd[0]); + close(pipefd[1]); + return; + } if (pid == 0) { dup2(pipefd[1], 2); if (fd >= 0) dup2(fd, 3); diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java b/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java index c6bfdb918d..8987b6cb08 100644 --- a/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java @@ -11,6 +11,8 @@ import android.os.ParcelFileDescriptor; import android.os.Process; import android.util.Log; +import java.io.IOException; + public class LabService extends Service { static final int SPAWN = 1; static final int PROBE = 2; @@ -31,8 +33,14 @@ public class LabService extends Service { case PROBE: { String what = data.readString().replace("libexec", "libexec=" + getApplicationInfo().nativeLibraryDir + "/libplabexe.so"); - int[] fds = readFds(data); - reply.writeString(Native.probe(what, fds)); + ParcelFileDescriptor[] pfds = readFds(data); + try { + int[] fds = new int[pfds.length]; + for (int i = 0; i < fds.length; i++) fds[i] = pfds[i] == null ? -1 : pfds[i].getFd(); + reply.writeString(Native.probe(what, fds)); + } finally { + closeAll(pfds); + } return true; } case EXEC: { @@ -53,14 +61,26 @@ public class LabService extends Service { } }; - private static int[] readFds(Parcel data) { - int n = data.readInt(); - int[] fds = new int[n]; - for (int i = 0; i < n; i++) { - ParcelFileDescriptor pfd = data.readFileDescriptor(); - fds[i] = pfd == null ? -1 : pfd.detachFd(); + private static ParcelFileDescriptor[] readFds(Parcel data) { + ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[data.readInt()]; + try { + for (int i = 0; i < pfds.length; i++) pfds[i] = data.readFileDescriptor(); + } catch (RuntimeException e) { + closeAll(pfds); + throw e; + } + return pfds; + } + + private static void closeAll(ParcelFileDescriptor[] pfds) { + for (ParcelFileDescriptor pfd : pfds) { + if (pfd == null) continue; + try { + pfd.close(); + } catch (IOException e) { + Log.w(Main.TAG, "close fd failed " + e); + } } - return fds; } @Override diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java index a9fcf43406..c65950fa67 100644 --- a/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java @@ -10,18 +10,24 @@ import android.os.IBinder; import android.os.Parcel; import android.os.ParcelFileDescriptor; import android.os.Process; +import android.os.RemoteException; +import android.system.ErrnoException; import android.system.Os; import android.system.OsConstants; import android.util.Log; import android.widget.TextView; +import java.io.Closeable; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** * Drive with: am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso --ei n 40 @@ -31,10 +37,81 @@ public class Main extends Activity { static final String TAG = "PLAB"; private static final Map binders = new HashMap<>(); - private static final Map> pending = new HashMap<>(); + private static final Map> pending = new HashMap<>(); private static final Map connections = new HashMap<>(); + private static final ExecutorService worker = Executors.newSingleThreadExecutor(); private TextView text; - private static final List keep = new ArrayList<>(); + + private interface Op { + void run(IBinder binder) throws Exception; + } + + private final class Task { + final String target; + final String name; + final Op op; + final Closeable owned; + + Task(String target, String name, Op op, Closeable owned) { + this.target = target; + this.name = name; + this.op = op; + this.owned = owned; + } + + void run(IBinder binder) { + worker.execute(() -> { + try { + op.run(binder); + } catch (Exception e) { + log(target + " " + name + " failed " + e); + } finally { + release(); + } + }); + } + + void cancel() { + log(target + " " + name + " cancelled"); + release(); + } + + private void release() { + if (owned == null) return; + try { + owned.close(); + } catch (IOException e) { + log(target + " " + name + " close failed " + e); + } + } + } + + private static final class ProbeFds implements Closeable { + final List sent = new ArrayList<>(); + final List owned = new ArrayList<>(); + + @Override + public void close() throws IOException { + IOException failure = null; + for (ParcelFileDescriptor p : sent) { + try { + p.close(); + } catch (IOException e) { + failure = e; + } + } + for (FileDescriptor fd : owned) { + try { + Os.close(fd); + } catch (ErrnoException e) { + failure = new IOException(e); + } + } + sent.clear(); + owned.clear(); + if (failure != null) throw failure; + } + } @Override protected void onCreate(Bundle state) { @@ -53,7 +130,7 @@ public class Main extends Activity { private void log(String s) { Log.i(TAG, s); - text.append(s + "\n"); + runOnUiThread(() -> text.append(s + "\n")); } private static Class serviceClass(String target) { @@ -74,26 +151,30 @@ public class Main extends Activity { } } - private void withBinder(String target, Runnable op) { - if (binders.containsKey(target)) { - op.run(); + private void withBinder(String target, String name, Op op, Closeable owned) { + Task task = new Task(target, name, op, owned); + IBinder binder = binders.get(target); + if (binder != null) { + task.run(binder); return; } - List q = pending.get(target); - if (q != null) { - q.add(op); - return; + List q = pending.get(target); + if (q == null) { + q = new ArrayList<>(); + pending.put(target, q); } - q = new ArrayList<>(); - q.add(op); - pending.put(target, q); + q.add(task); + if (!connections.containsKey(target)) bind(target); + } + + private void bind(String target) { ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { log("connected " + target); binders.put(target, service); - List ops = pending.remove(target); - if (ops != null) for (Runnable r : ops) r.run(); + List ops = pending.remove(target); + if (ops != null) for (Task t : ops) t.run(service); } @Override @@ -105,23 +186,47 @@ public class Main extends Activity { @Override public void onBindingDied(ComponentName name) { log("BINDING DIED " + target); + if (connections.get(target) != this) return; + List ops = pending.remove(target); + unbind(target); + if (ops != null) { + pending.put(target, ops); + bind(target); + } } }; connections.put(target, conn); - Intent intent = new Intent(this, serviceClass(target)); - int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT; - boolean ok; - if (target.contains(":")) { - ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn); - } else { - ok = getApplicationContext().bindService(intent, conn, flags); + boolean ok = false; + try { + Intent intent = new Intent(this, serviceClass(target)); + int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT; + if (target.contains(":")) { + ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn); + } else { + ok = getApplicationContext().bindService(intent, conn, flags); + } + } finally { + log("bind " + target + " -> " + ok); + if (!ok) unbind(target); } - log("bind " + target + " -> " + ok); } - private Parcel call(String target, int code, Parcel data) throws Exception { + private void unbind(String target) { + ServiceConnection c = connections.remove(target); + binders.remove(target); + List q = pending.remove(target); + if (q != null) for (Task t : q) t.cancel(); + if (c == null) return; + try { + getApplicationContext().unbindService(c); + } catch (IllegalArgumentException e) { + log("unbind " + target + " " + e); + } + } + + private static Parcel call(IBinder binder, int code, Parcel data) throws RemoteException { Parcel reply = Parcel.obtain(); - binders.get(target).transact(code, data, reply, 0); + binder.transact(code, data, reply, 0); return reply; } @@ -137,61 +242,41 @@ public class Main extends Activity { log("main spawned " + Native.spawn(n)); return; } - withBinder(target, () -> { - try { - Parcel d = Parcel.obtain(); - d.writeInt(n); - log(target + " spawned " + call(target, LabService.SPAWN, d).readInt()); - } catch (Exception e) { - log(target + " spawn failed " + e); - } - }); + withBinder(target, "spawn", b -> { + Parcel d = Parcel.obtain(); + d.writeInt(n); + log(target + " spawned " + call(b, LabService.SPAWN, d).readInt()); + }, null); return; } case "who": - withBinder(target, () -> { - try { - log(target + " " + call(target, LabService.WHO, Parcel.obtain()).readString()); - } catch (Exception e) { - log(target + " who failed " + e); - } - }); + withBinder(target, "who", b -> log(target + " " + call(b, LabService.WHO, Parcel.obtain()).readString()), null); return; case "exec": { String[] argv = intent.getStringExtra("argv").split("\\|"); boolean keepBinder = intent.getIntExtra("keep", 1) != 0; - withBinder(target, () -> { - try { - Parcel d = Parcel.obtain(); - d.writeStringArray(argv); - d.writeInt(keepBinder ? 1 : 0); - log(target + " exec in pid " + call(target, LabService.EXEC, d).readInt()); - } catch (Exception e) { - log(target + " exec failed " + e); - } - }); + withBinder(target, "exec", b -> { + Parcel d = Parcel.obtain(); + d.writeStringArray(argv); + d.writeInt(keepBinder ? 1 : 0); + log(target + " exec in pid " + call(b, LabService.EXEC, d).readInt()); + }, null); return; } case "probe": { String what = intent.getStringExtra("what"); - List fds = probeFds(intent.getStringExtra("fds")); - withBinder(target, () -> { - try { - Parcel d = Parcel.obtain(); - d.writeString(what); - d.writeInt(fds.size()); - for (ParcelFileDescriptor p : fds) d.writeFileDescriptor(p.getFileDescriptor()); - for (String line : call(target, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line); - } catch (Exception e) { - log(target + " probe failed " + e); - } - }); + ProbeFds fds = probeFds(intent.getStringExtra("fds")); + withBinder(target, "probe", b -> { + Parcel d = Parcel.obtain(); + d.writeString(what); + d.writeInt(fds.sent.size()); + for (ParcelFileDescriptor p : fds.sent) d.writeFileDescriptor(p.getFileDescriptor()); + for (String line : call(b, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line); + }, fds); return; } case "unbind": { - ServiceConnection c = connections.remove(target); - binders.remove(target); - if (c != null) getApplicationContext().unbindService(c); + unbind(target); log("unbound " + target); return; } @@ -204,36 +289,45 @@ public class Main extends Activity { } /** fds: comma separated list of tcp, udp, file:, unix, memfd. */ - private List probeFds(String spec) throws Exception { - List out = new ArrayList<>(); - if (spec == null || spec.isEmpty()) return out; - for (String s : spec.split(",")) { - if (s.equals("tcp") || s.equals("udp")) { - FileDescriptor fd = Os.socket(OsConstants.AF_INET, - s.equals("tcp") ? OsConstants.SOCK_STREAM : OsConstants.SOCK_DGRAM, 0); - keep.add(fd); - out.add(ParcelFileDescriptor.dup(fd)); - } else if (s.equals("unix")) { - FileDescriptor a = new FileDescriptor(); - FileDescriptor b = new FileDescriptor(); - Os.socketpair(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0, a, b); - Os.write(a, "hello from main\n".getBytes(), 0, 16); - keep.add(a); - out.add(ParcelFileDescriptor.dup(b)); - } else if (s.startsWith("file:")) { - File f = new File(getFilesDir(), s.substring(5)); - if (!f.exists()) { - try (FileOutputStream o = new FileOutputStream(f)) { - o.write("data file contents\n".getBytes()); + private ProbeFds probeFds(String spec) throws Exception { + ProbeFds fds = new ProbeFds(); + if (spec == null || spec.isEmpty()) return fds; + try { + for (String s : spec.split(",")) { + if (s.equals("tcp") || s.equals("udp")) { + FileDescriptor fd = Os.socket(OsConstants.AF_INET, + s.equals("tcp") ? OsConstants.SOCK_STREAM : OsConstants.SOCK_DGRAM, 0); + fds.owned.add(fd); + fds.sent.add(ParcelFileDescriptor.dup(fd)); + } else if (s.equals("unix")) { + FileDescriptor a = new FileDescriptor(); + FileDescriptor b = new FileDescriptor(); + Os.socketpair(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0, a, b); + fds.owned.add(a); + fds.owned.add(b); + Os.write(a, "hello from main\n".getBytes(), 0, 16); + fds.sent.add(ParcelFileDescriptor.dup(b)); + } else if (s.startsWith("file:")) { + File f = new File(getFilesDir(), s.substring(5)); + if (!f.exists()) { + try (FileOutputStream o = new FileOutputStream(f)) { + o.write("data file contents\n".getBytes()); + } } + fds.sent.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE)); + } else if (s.startsWith("path:")) { + fds.sent.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY)); + } else if (s.equals("dir")) { + fds.sent.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY)); } - out.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE)); - } else if (s.startsWith("path:")) { - out.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY)); - } else if (s.equals("dir")) { - out.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY)); } + } catch (Exception e) { + try { + fds.close(); + } catch (IOException ignored) { + } + throw e; } - return out; + return fds; } } diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 3758ce2e6a..bb954eda38 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -16,6 +16,7 @@ HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" PARENT = r""" #define _GNU_SOURCE +#include #include #include #include @@ -38,18 +39,31 @@ int main(int argc, char **argv) { printf("spawned\t%d\n", err); if (err) return 0; } else if ((pid = fork()) == 0) { - // as Python's subprocess does before exec - if (strcmp(argv[1], "closefds") == 0) syscall(SYS_close_range, 3, ~0U, 0); + if (strcmp(argv[1], "closefds") == 0) { + // as Python's subprocess does before exec; an ordinary fd shows that it closed them + int probe = open("/dev/null", O_RDONLY); + printf("closerange\t%ld\n", (long)syscall(SYS_close_range, 3, ~0U, 0)); + printf("closed\t%d\n", probe >= 3 && fcntl(probe, F_GETFD) < 0); + fflush(stdout); + } + if (strcmp(argv[1], "group") == 0) setpgid(0, 0); execl("/bin/target", "target", argv[2], (char *)NULL); _exit(127); } int status = 0; + int group = strcmp(argv[1], "group") == 0; + if (group) { + setpgid(pid, pid); + usleep(300000); + // the child is in a group of its own: not ours + printf("ours\t%d\n", (int)waitpid(0, &status, WNOHANG)); + } if (strcmp(argv[1], "kill") == 0) { printf("nohang\t%d\n", (int)waitpid(pid, &status, WNOHANG)); usleep(300000); printf("kill\t%d\n", kill(pid, SIGTERM)); } - pid_t r = waitpid(pid, &status, 0); + pid_t r = waitpid(group ? -pid : pid, &status, 0); printf("same\t%d\n", r == pid); if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); if (WIFSIGNALED(status)) printf("signal\t%d\n", WTERMSIG(status)); @@ -96,17 +110,31 @@ class FakeSpawner(threading.Thread): request = json.loads(payload) fds = [] while len(fds) < len(request["fds"]) + 1: - _, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"]) + data, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"]) fds.extend(chunk) + if not data: + break # the client went away between chunks + if len(fds) < len(request["fds"]) + 1: + for fd in fds: + os.close(fd) + conn.close() + continue self.requests.append(request) table = fds[request["table"]] program = str(self.root) + request["file"] proc = subprocess.Popen(list(self.prefix) + [program] + request["argv"][1:]) conn.sendall(b"pid %d\n" % proc.pid) + # the hook takes the program on with "go"; without it the program must not run + went = not request.get("ack") or self.read(conn, 3) == b"go\n" conn.close() for fd in fds: if fd != table: os.close(fd) + if not went: + proc.kill() + proc.wait() + os.close(table) + continue threading.Thread(target=self.report, args=(proc, table, request), daemon=True).start() @staticmethod @@ -152,13 +180,14 @@ class NativeHookHandoffTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def run_parent(self, *argv, handoff="target"): - name = "dd-handoff-test-%d-%s-%s" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff) + def run_parent(self, *argv, handoff="target", hook=True): + name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook) spawner = FakeSpawner(name, self.prefix or [], self.root) spawner.start() self.addCleanup(spawner.sock.close) - hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook), "DD_SPAWN": name, - "DD_HANDOFF": handoff} + hook_env = {"DDNATV_ROOT": str(self.root), "DD_SPAWN": name, "DD_HANDOFF": handoff} + if hook: + hook_env["LD_PRELOAD"] = str(self.hook) env = {k: v for k, v in os.environ.items() if k not in hook_env} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] @@ -180,6 +209,9 @@ class NativeHookHandoffTest(unittest.TestCase): def test_a_child_that_closed_its_inherited_fds_is_handed_off(self): result, requests, out = self.run_parent("closefds", "5") + if result.get("closerange") != "0": + self.skipTest("close_range does not work here: %s" % result.get("closerange")) + self.assertEqual("1", result.get("closed"), out.stdout) self.assertEqual(1, len(requests), out.stderr) self.assertEqual("1", result.get("same"), out.stdout) self.assertEqual("5", result.get("exit"), out.stdout) @@ -194,9 +226,35 @@ class NativeHookHandoffTest(unittest.TestCase): def test_a_posix_spawn_of_a_missing_program_fails_as_it_would(self): # posix_spawn() returns the exec's error, even with closefrom(3) among the file actions - result, requests, out = self.run_parent("spawn", "6", "/bin/missing") + result, requests, out = self.run_parent("spawn", "6", "/bin/missing", handoff="missing") self.assertEqual([], requests) self.assertEqual(str(errno.ENOENT), result.get("spawned"), out.stdout) + self.assertNotIn("exit", result, out.stdout) + self.assertNotIn("signal", result, out.stdout) + + def test_a_posix_spawn_of_a_missing_program_not_listed_is_unchanged(self): + # As without the hook: ENOENT natively; qemu-user, which runs glibc's vfork-style spawn child + # as a separate process, gets 0 and an exit status of 127. + result, requests, out = self.run_parent("spawn", "6", "/bin/missing", handoff="other") + plain, _, plain_out = self.run_parent("spawn", "6", "/bin/missing", handoff="other", hook=False) + self.assertEqual([], requests) + self.assertEqual(plain.get("spawned"), result.get("spawned"), out.stdout + plain_out.stdout) + self.assertEqual(plain.get("exit"), result.get("exit"), out.stdout + plain_out.stdout) + + def test_a_posix_spawn_of_a_script_without_its_interpreter_fails_as_it_would(self): + script = self.root / "bin/orphan" + script.write_text("#!/bin/no-such-interpreter\n") + script.chmod(0o755) + result, requests, out = self.run_parent("spawn", "6", "/bin/orphan", handoff="orphan") + self.assertEqual([], requests) + self.assertEqual(str(errno.ENOENT), result.get("spawned"), out.stdout) + + def test_a_wait_for_a_group_takes_only_that_groups_children(self): + result, requests, out = self.run_parent("group", "4") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("ours"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("4", result.get("exit"), out.stdout) def test_kill_reaches_the_program_and_its_signal_is_reported(self): result, requests, out = self.run_parent("kill", "sleep")