fix(session): confirm the hook before the worker runs, prefer a late report and free a reused pid

This commit is contained in:
Kurt Himebauch committed 2026-11-27 23:01:58 -05:00
1 parent 7c10d1fa85
commit 144a85114e
4 files changed
+92 -23

No files matched your search

@@ -53,15 +53,17 @@ open class GuestWorker : Service() {
// poll() with a timeout counts as network I/O to StrictMode on the main thread
android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX)
val committed = runCatching {
fun byte(): Int {
fun byte(timeout: Int): Int {
val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() }
val ready = Os.poll(arrayOf(poll), GO_TIMEOUT_MS)
val ready = Os.poll(arrayOf(poll), timeout)
return (if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1)
.also { why = "poll $ready revents ${poll.revents} read $it" }
}
// The commit, an answer, and the app's word that it has the answer: the app may
// have stopped waiting for it (and started the program another way) meanwhile.
byte() == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 && byte() == 1
// That last word comes, or the app closes its end (a byte or EOF): no timeout,
// which could drop a launch the app has already reported as started.
byte(GO_TIMEOUT_MS) == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 && byte(-1) == 1
}.getOrElse { why = it.toString(); false }
go.close()
if (committed) exec(argv, env, fds, targets, fillBinderFd)
@@ -314,9 +316,11 @@ object GuestWorkers {
/**
* [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.
* [confirmed] runs once the worker has taken it on, just before it is told to run it; false, and it does not.
*/
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }): Int {
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
confirmed: () -> 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
@@ -351,6 +355,8 @@ 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
go[0].close()
val pid = reply.readInt()
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
// would not find them.
@@ -371,9 +377,11 @@ object GuestWorkers {
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1)
val answer = StructPollfd().apply { fd = go[1].fileDescriptor; events = OsConstants.POLLIN.toShort() }
// then the word to run it: given only here, once its answer is in, so that a worker whose
// answer came too late never runs a program this call reports as not started
// 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).
val accepted = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 &&
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
if (!accepted) {
Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on")
slot.started = false
@@ -646,11 +654,19 @@ object GuestWorkers {
// 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 ->
// the hook's last word, sent once the worker has taken the program on and before it runs it
var confirmedToHook = false
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, onExit = { code ->
status = code
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
exited.countDown()
}) { started ->
}, confirmed = {
!ack || runCatching {
out.write("ok\n".toByteArray())
out.flush()
confirmedToHook = true
}.isSuccess
}, commit = { started ->
worker = started
if (!ack) return@start true
runCatching {
@@ -668,16 +684,16 @@ object GuestWorkers {
}
ended && line.toString() == "go"
}.getOrDefault(false)
}
})
handedOver = true
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
if (pid <= 0) table?.let { runCatching { it.close() } }
if (!answered) {
out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
out.flush()
} else {
// The hook's last word: the worker runs it, or nothing does and the hook runs it itself
runCatching { out.write(if (pid > 0) "ok\n".toByteArray() else "error not started\n".toByteArray()); out.flush() }
} else if (!confirmedToHook) {
// nothing runs it in a worker: the hook runs it itself
runCatching { out.write("error not started\n".toByteArray()); out.flush() }
}
if (pid > 0 && wait) {
exited.await()
+9 -1
View File
@@ -665,6 +665,8 @@ pid_t fork(void) {
if (pid == 0) {
ddh_drop_worker_binder();
ddh_forked();
} else if (pid > 0) {
ddh_child_created(pid);
}
// A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its
// execve() is a real one (only read in the usual case, so no page is copied for it)
@@ -1255,7 +1257,13 @@ int posix_spawn(pid_t *pid, const char *path,
int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ);
if (ret != -1) return ret;
}
return ddnatv_posix_spawn(pid, path, file_actions, attr, argv, envp, 0);
pid_t child = 0;
int ret = ddnatv_posix_spawn(&child, path, file_actions, attr, argv, envp, 0);
if (ret == 0) {
ddh_child_created(child);
if (pid) *pid = child;
}
return ret;
}
int posix_spawnp(pid_t *pid, const char *file,
+35 -4
View File
@@ -747,8 +747,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename
static void ddh_try(const char *filename, char *const argv[], char *const envp[]) {
struct ddh_table *table;
int table_fd;
if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) && getpid() != g_ddh_owner) {
table = g_ddh;
// one look: the fields are read only once the table is seen published
struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE);
pid_t own_owner = own ? g_ddh_owner : 0;
if (own && getpid() != own_owner) {
table = own;
table_fd = g_ddh_fd;
} else if (g_ddh_up && getppid() == g_ddh_up->pad[0]) {
table = g_ddh_up;
@@ -757,7 +760,7 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[]
if (ddh_env(envp, "DD_HANDOFF_DEBUG")) {
char why[160];
snprintf(why, sizeof(why), "not a child its parent can track (table %d owner %d up %d up-owner %d ppid %d):",
g_ddh != NULL, (int)g_ddh_owner, g_ddh_up != NULL, g_ddh_up ? g_ddh_up->pad[0] : 0, (int)getppid());
own != NULL, (int)own_owner, g_ddh_up != NULL, g_ddh_up ? g_ddh_up->pad[0] : 0, (int)getppid());
ddh_debug(envp, why, filename);
}
return;
@@ -1020,6 +1023,25 @@ static int ddh_selects(const struct ddh_entry *e, pid_t pid) {
return e->pad[1] == (pid == 0 ? getpgrp() : -pid);
}
static void ddh_release(struct ddh_entry *e, int *status);
// A new child of ours got pid: an entry still naming it (its forked child reaped early, as the
// wait above does, so the pid was free again) stands for a program the pid no longer reaches. The
// real child owns the pid from now on: kill() and wait() go to it, and that program's exit is
// dropped. Only after the pid space has wrapped around while that program runs.
static void ddh_child_created(pid_t pid) {
struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE);
if (!t || pid <= 0) return;
pid_t me = getpid();
for (int i = 0; i < DDH_SLOTS; i++) {
struct ddh_entry *e = &t->e[i];
int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE);
if ((st != DDH_HANDED && st != DDH_EXITED) || e->parent != me || e->child != pid || !e->reaped) continue;
if (__atomic_compare_exchange_n(&e->state, &st, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED))
ddh_release(e, NULL);
}
}
// Takes e's exit for a wait for pid, checked again once taken: between finding e and taking it,
// another waiter may have released the slot and a later child of ours (or one of another group)
// have exited in it.
@@ -1091,7 +1113,9 @@ static void ddh_check_gone(void) {
}
// Only this side moves HANDED to EXITED; a status the program wrote itself is kept.
int32_t none = DDH_NO_STATUS;
__atomic_compare_exchange_n(&e->status, &none, status, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
if (__atomic_compare_exchange_n(&e->status, &none, status, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED) &&
report[1] != e->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);
}
@@ -1099,6 +1123,13 @@ static void ddh_check_gone(void) {
static void ddh_release(struct ddh_entry *e, int *status) {
if (status) *status = e->status;
if (status && e->pad[0] == -1) {
// SIGKILL was the timeout's guess (no report then): the app's report, if it has come since
int32_t report[2];
uint64_t both = __atomic_load_n((uint64_t *)e->app, __ATOMIC_ACQUIRE);
memcpy(report, &both, sizeof(report));
if (report[1] != 0 && report[1] == e->child) *status = report[0];
}
memset(e, 0, offsetof(struct ddh_entry, state));
e->status = 0;
e->reaped = 0;
+20 -6
View File
@@ -88,13 +88,14 @@ int main(int argc, char **argv) {
class FakeSpawner(threading.Thread):
"""Stands in for the app's spawn socket: runs the program and reports its exit into the table."""
def __init__(self, name, prefix, root):
def __init__(self, name, prefix, root, reports=True):
super().__init__(daemon=True)
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.bind("\0" + name)
self.sock.listen(4)
self.prefix = prefix
self.root = root
self.reports = reports # False: as an app that died with its worker, no exit report
self.requests = []
def run(self):
@@ -140,16 +141,16 @@ class FakeSpawner(threading.Thread):
if fd != table:
os.close(fd)
if went:
os.write(gate_w, b"1")
if request.get("ack"):
conn.sendall(b"ok\n") # the app's last word, once the worker runs it
conn.sendall(b"ok\n") # the app's last word, before the worker may run it
os.write(gate_w, b"1")
conn.close()
os.close(gate_w)
if not went:
os.waitpid(pid, 0)
os.close(table)
continue
threading.Thread(target=self.report, args=(pid, table, request), daemon=True).start()
threading.Thread(target=self.report if self.reports else self.reap, args=(pid, table, request), daemon=True).start()
@staticmethod
def read(conn, size):
@@ -161,6 +162,11 @@ class FakeSpawner(threading.Thread):
data += more
return data
@staticmethod
def reap(pid, table, request):
os.waitpid(pid, 0)
os.close(table)
@staticmethod
def report(pid, table, request):
code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
@@ -195,9 +201,9 @@ class NativeHookHandoffTest(unittest.TestCase):
def tearDownClass(cls):
cls.tmp.cleanup()
def run_parent(self, *argv, handoff="target", hook=True):
def run_parent(self, *argv, handoff="target", hook=True, reports=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 = FakeSpawner(name, self.prefix or [], self.root, reports)
spawner.start()
self.addCleanup(spawner.sock.close)
hook_env = {"DDNATV_ROOT": str(self.root), "DD_SPAWN": name, "DD_HANDOFF": handoff}
@@ -213,6 +219,14 @@ class NativeHookHandoffTest(unittest.TestCase):
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
return result, spawner.requests, out
def test_a_program_gone_without_any_report_is_reported_killed(self):
# its worker is gone and nobody reports how it ended (the app died with it): SIGKILL, after
# the grace the app's report would have had
result, requests, out = self.run_parent("wait", "7", reports=False)
self.assertEqual(1, len(requests), out.stderr)
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual(str(int(signal.SIGKILL)), result.get("signal"), out.stdout)
def test_the_parent_waits_for_the_handed_off_program(self):
result, requests, out = self.run_parent("wait", "7")
self.assertEqual(1, len(requests), out.stderr)