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 81553e49dc..366665a522 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -258,6 +258,10 @@ object GuestWorkers { @Volatile var onExit: ((Int) -> Unit)? = null /** Set once its program was handed over: only then does its end count as the program's. */ @Volatile var started = false + /** Between the pid and the last word of a launch (under the slots lock): its end is held back. */ + var launching = false + /** It ended while launching: reported once the launch turns out to have run, never otherwise. */ + var endedLaunching = false } private val slots = arrayOfNulls(classes.size) @@ -273,6 +277,11 @@ object GuestWorkers { private const val WARM_WORKERS = 2 private const val ACK_TIMEOUT_MS = 5000 private const val ANSWER_TIMEOUT_MS = 5000 + private const val RECEIVE_TIMEOUT_MS = 10000 + // argv and the environment of one exec, with room: Linux caps them at a quarter of the stack + private const val MAX_REQUEST_BYTES = 8 shl 20 + private const val MAX_RECEIVING = 32 + private val receiving = java.util.concurrent.atomic.AtomicInteger() private val connections = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "guest-worker-binder").apply { isDaemon = true } } @Volatile private var server: Thread? = null @@ -343,11 +352,11 @@ object GuestWorkers { // without one, the worker ends without running the program (the caller starts it another way). // It answers with a byte of its own: without that it gave up waiting, and nothing runs. var go: Array? = null - val data = Parcel.obtain() + var data: Parcel? = Parcel.obtain() val reply = Parcel.obtain() try { go = ParcelFileDescriptor.createSocketPair() - data.writeStringArray(argv.toTypedArray()) + data!!.writeStringArray(argv.toTypedArray()) data.writeStringArray(env.toTypedArray()) data.writeInt(fds.size) fds.forEach { data.writeFileDescriptor(it.fileDescriptor) } @@ -355,7 +364,10 @@ object GuestWorkers { data.writeInt(if (guest) 0 else 1) data.writeFileDescriptor(go[0].fileDescriptor) slot.service!!.transact(GuestWorker.RUN, data, reply, 0) - // The worker has its own copy: with ours closed, a worker that gave up leaves no reader + // The worker has its own copy: with ours closed (and the request's, which holds one too), + // a worker that gave up leaves no reader + data.recycle() + data = null go[0].close() val pid = reply.readInt() // Once a session's teardown has begun (stopGuests), none of its programs may start: it @@ -366,8 +378,9 @@ object GuestWorkers { release(app, slot) return -1 } + // launching, not started yet: an end before the last word is reported only if the launch ran val live = synchronized(slots) { - (slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.started = true } } + (slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.launching = true } } } if (!live) { Log.w(TAG, "worker ${slot.index} ended, or its session is stopping, before running ${argv.firstOrNull()}") @@ -380,20 +393,29 @@ object GuestWorkers { // answer came too late never runs a program this call reports as not started. [confirmed] // goes first: a caller that hears nothing runs the program itself, so it must have heard // before the worker may run it (an app dying in between loses the program, not doubles it). + // A teardown that began meanwhile has the pid already (guestPids lists a launching slot), so + // a launch that goes on from here is still stopped with the session. val accepted = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 && - confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + !stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + val endedRunning = synchronized(slots) { + slot.launching = false + if (accepted && !slot.endedLaunching) slot.started = true + accepted && slot.endedLaunching + } if (!accepted) { Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on") - slot.started = false release(app, slot) return -1 } + // it ran and was already gone by now: its end, once + if (endedRunning) reportEnd(app, slot) } catch (e: Exception) { Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e) + synchronized(slots) { slot.launching = false } release(app, slot) return -1 } finally { - data.recycle() + data?.recycle() reply.recycle() go?.forEach { runCatching { it.close() } } } @@ -472,14 +494,20 @@ object GuestWorkers { } private fun release(app: Context, slot: Slot) { + var report = false val removed = synchronized(slots) { warm.remove(slot) + if (slot.launching) slot.endedLaunching = true else report = slot.started (slots[slot.index] === slot).also { if (it) slots[slot.index] = null } } if (!removed) return runCatching { app.unbindService(slot.connection) } - val onExit = slot.onExit - if (slot.started && onExit != null) Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start() + if (report) reportEnd(app, slot) + } + + private fun reportEnd(app: Context, slot: Slot) { + val onExit = slot.onExit ?: return + Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start() } /** The worker's exit as a wait status (exit code << 8, or the signal), -1 when unknown. */ @@ -549,9 +577,16 @@ object GuestWorkers { Thread.sleep(100) // out of fds, for one: do not spin continue } + // A bounded number of requests still coming in: a stalled sender holds a thread + if (receiving.incrementAndGet() > MAX_RECEIVING) { + receiving.decrementAndGet() + Log.w(TAG, "$MAX_RECEIVING spawn requests are still coming in: refusing another") + runCatching { client.close() } + continue + } Thread({ try { - handle(app, client) + handle(app, client) { receiving.decrementAndGet() } } catch (e: Throwable) { Log.w(TAG, "spawn request failed", e) } @@ -562,11 +597,28 @@ object GuestWorkers { return number } - private fun handle(app: Context, client: LocalSocket) { + private fun handle(app: Context, client: LocalSocket, received: () -> Unit) { + var receiving = true + val done = { if (receiving) { receiving = false; received() } } + try { + handleRequest(app, client, done) + } finally { + done() + } + } + + private fun handleRequest(app: Context, client: LocalSocket, received: () -> Unit) { client.use { if (client.peerCredentials.uid != Process.myUid()) return + // Each read of the request and its fds within this (the wait for a program's exit is not) + client.soTimeout = RECEIVE_TIMEOUT_MS val input = DataInputStream(client.inputStream) - val payload = ByteArray(input.readInt()).also { input.readFully(it) } + val length = input.readInt() + if (length !in 1..MAX_REQUEST_BYTES) { + Log.w(TAG, "spawn request of $length bytes refused") + return + } + val payload = ByteArray(length).also { input.readFully(it) } val request = JSONObject(String(payload)) val fds = ArrayList() fun take() { @@ -590,6 +642,7 @@ object GuestWorkers { } else { take() } + received() val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } } val env = LinkedHashMap() request.optJSONObject("env")?.let { o -> o.keys().forEach { env[it] = o.getString(it) } } diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 009ae2b044..897c61a361 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -1201,6 +1201,11 @@ static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file if ((unsigned)a[i].tag >= DDH_DO_TCSETPGRP) return -1; } } + // A scheduling policy or priority would apply to this child, not to the worker that runs the program + short spawn_flags = 0; + if (attr && posix_spawnattr_getflags(attr, &spawn_flags) == 0 && + (spawn_flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM))) + return -1; int report[2]; if (pipe2(report, O_CLOEXEC) != 0) return -1; pid_t child = fork(); diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index bf3fe1c178..79d9337a46 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -701,6 +701,31 @@ static int ddh_startable(const char *path) { return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(p, real, sizeof(real)), X_OK, 0, 0, 0) == 0; } +// Whether s is valid UTF-8: the app reads the request as UTF-8, and any other byte would reach the +// program changed (a file name in Latin-1, say), where a local exec passes it on as it is. +static int ddh_utf8(const char *s) { + const unsigned char *p = (const unsigned char *)s; + while (*p) { + int n = *p < 0x80 ? 0 : (*p & 0xe0) == 0xc0 ? 1 : (*p & 0xf0) == 0xe0 ? 2 : (*p & 0xf8) == 0xf0 ? 3 : -1; + if (n < 0 || (n == 1 && *p < 0xc2) || (n == 3 && *p > 0xf4)) return 0; + unsigned int cp = n == 0 ? *p : *p & (0x3f >> n); + for (int i = 1; i <= n; i++) { + if ((p[i] & 0xc0) != 0x80) return 0; + cp = (cp << 6) | (p[i] & 0x3f); + } + if ((n == 2 && (cp < 0x800 || (cp >= 0xd800 && cp <= 0xdfff))) || (n == 3 && (cp < 0x10000 || cp > 0x10ffff))) return 0; + p += n + 1; + } + return 1; +} + +static int ddh_all_utf8(char *const v[]) { + for (int i = 0; v && v[i]; i++) { + if (!ddh_utf8(v[i])) return 0; + } + return 1; +} + static int ddh_program_listed(const char *list, const char *filename, char *const argv[]) { char shebang[256]; const char *interp; @@ -787,6 +812,10 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] ddh_debug(envp, "would not start:", filename); return; } + if (!ddh_utf8(filename) || !ddh_all_utf8(argv) || !ddh_all_utf8(envp)) { + ddh_debug(envp, "not all UTF-8:", filename); + return; + } int fds[DDH_MAX_FDS + 1]; int nfds = ddh_open_fds(fds, DDH_MAX_FDS, table_fd); @@ -838,6 +867,11 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[] snprintf(why, sizeof(why), "kernel name for the working directory (errno %d):", err); ddh_debug(envp, why, cwd); } + if (!ddh_utf8(cwd)) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + ddh_debug(envp, "working directory not UTF-8:", cwd); + return; + } // What the program would have inherited here and a worker does not have: ignored signals, the // open-files limit, the umask (ddh_apply_inherited() restores them in the program). unsigned long ignored = 0; @@ -1066,7 +1100,7 @@ static int ddh_any_live(pid_t pid) { for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &g_ddh->e[i]; int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); - if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->parent == me && ddh_selects(e, pid)) return 1; + if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN || st == DDH_CLAIMED) && e->parent == me && ddh_selects(e, pid)) return 1; } return 0; } @@ -1102,12 +1136,13 @@ static void ddh_check_gone(void) { for (int i = 0; i < DDH_SLOTS; i++) { struct ddh_entry *e = &t->e[i]; if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_HANDED || e->parent != me) continue; + pid_t child = e->child; if (syscall(SYS_kill, e->real, 0) == 0 || errno != ESRCH) continue; int32_t report[2]; uint64_t both = __atomic_load_n((uint64_t *)e->app, __ATOMIC_ACQUIRE); memcpy(report, &both, sizeof(report)); int32_t status = SIGKILL; - if (report[1] == e->child && report[1] != 0) { + if (report[1] == child && report[1] != 0) { status = report[0]; } else { // The app looks the status up for up to a second after the worker's death: wait longer. @@ -1119,13 +1154,20 @@ static void ddh_check_gone(void) { } if (now.tv_sec + 1 - e->pad[0] < 3) continue; } - // Only this side moves HANDED to EXITED; a status the program wrote itself is kept. + // Only this side moves HANDED to EXITED, the entry held meanwhile and still the child looked at: + // a waiter may have finished with it and a new handoff taken the slot since the look above. + int expected = DDH_HANDED; + if (!__atomic_compare_exchange_n(&e->state, &expected, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) continue; + if (e->child != child || e->parent != me) { + __atomic_store_n(&e->state, DDH_HANDED, __ATOMIC_RELEASE); + continue; + } + // a status the program wrote itself is kept int32_t none = DDH_NO_STATUS; if (__atomic_compare_exchange_n(&e->status, &none, status, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED) && - report[1] != e->child) + report[1] != child) e->pad[0] = -1; // the timeout's guess: an app report that comes before the exit is taken wins (ddh_release) - int expected = DDH_HANDED; - __atomic_compare_exchange_n(&e->state, &expected, DDH_EXITED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); } } @@ -1224,11 +1266,13 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { pid_t child = e->child; if (!e->reaped && !ddh_reap_shim(real, child, options)) { ddh_untake(e); - return (options & WNOHANG) ? 0 : -1; + if (!(options & WNOHANG)) return -1; + // its forked child is still exiting: another child may be ready now (below) + } else { + if (ru) memset(ru, 0, sizeof(*ru)); + ddh_release(e, status); + return child; } - if (ru) memset(ru, 0, sizeof(*ru)); - ddh_release(e, status); - return child; } int live = pid <= 0 && ddh_any_live(pid); int wstatus = 0; @@ -1272,7 +1316,7 @@ int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { // 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 (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || - (idtype == P_PID ? !ddh_find(which) : !ddh_any_live(which))) + (idtype == P_PID ? !ddh_find(which) && !ddh_claiming(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; diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 628d601817..bf782ea266 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -301,6 +301,7 @@ class NativeHookHandoffTest(unittest.TestCase): result, requests, out = self.run_parent("wait", "3", handoff="other") self.assertEqual([], requests) self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) if __name__ == "__main__":