mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
fix(session): commit each worker launch explicitly and keep workers with the session that asked
This commit is contained in:
1 parent
924ad4e9a3
commit
4e2bfa5cdc
4 files changed
+79
-37
No files matched your search
@@ -45,14 +45,15 @@ open class GuestWorker : Service() {
|
||||
val go = data.readFileDescriptor()
|
||||
reply?.writeInt(Process.myPid())
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
// The app closes its end once it has the reply: an exec before then would end
|
||||
// this process with the reply undelivered.
|
||||
runCatching {
|
||||
// The app writes a byte once it has the reply and has taken the launch on: an exec
|
||||
// before then would end this process with the reply undelivered, and with none (the
|
||||
// app gave up and starts the program another way) the program must not run here.
|
||||
val committed = runCatching {
|
||||
val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() }
|
||||
Os.poll(arrayOf(poll), GO_TIMEOUT_MS)
|
||||
}
|
||||
Os.poll(arrayOf(poll), GO_TIMEOUT_MS) > 0 && Os.read(go.fileDescriptor, ByteArray(1), 0, 1) == 1
|
||||
}.getOrDefault(false)
|
||||
go.close()
|
||||
exec(argv, env, fds, targets)
|
||||
if (committed) exec(argv, env, fds, targets) else Process.killProcess(Process.myPid())
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -274,6 +275,8 @@ object GuestWorkers {
|
||||
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
|
||||
guest: Boolean, onExit: (Int) -> Unit): 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
|
||||
val slot = takeWarm() ?: bind(app)?.takeIf { fresh ->
|
||||
fresh.connected.await(10, TimeUnit.SECONDS).also { if (!it) release(app, fresh) }
|
||||
} ?: run {
|
||||
@@ -281,11 +284,12 @@ object GuestWorkers {
|
||||
return -1
|
||||
}
|
||||
slot.guest = guest
|
||||
slot.session = session
|
||||
slot.session = owner
|
||||
slot.onExit = onExit
|
||||
refill(app)
|
||||
// The worker execs once this pipe closes: after the reply has reached us, so that its exec
|
||||
// does not cut the reply off, and after the slot is marked started.
|
||||
// The worker execs once a byte comes through this pipe: after the reply has reached us, so
|
||||
// that its exec does not cut the reply off, and after the slot is marked started. Closed
|
||||
// without one, the worker ends without running the program (the caller starts it another way).
|
||||
var go: Array<ParcelFileDescriptor>? = null
|
||||
val data = Parcel.obtain()
|
||||
val reply = Parcel.obtain()
|
||||
@@ -306,6 +310,7 @@ object GuestWorkers {
|
||||
Log.w(TAG, "worker ${slot.index} ended before running ${argv.firstOrNull()}")
|
||||
return -1
|
||||
}
|
||||
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
|
||||
release(app, slot)
|
||||
@@ -341,8 +346,11 @@ object GuestWorkers {
|
||||
}
|
||||
// Callbacks off the main thread: start() waits for onServiceConnected, and a caller holding a
|
||||
// lock the main thread is waiting for (PulseAudio's launch) would otherwise wait out the timeout.
|
||||
if (!app.bindService(Intent(app, classes[slot.index]), Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT,
|
||||
connections, slot.connection)) {
|
||||
val bound = runCatching {
|
||||
app.bindService(Intent(app, classes[slot.index]), Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT,
|
||||
connections, slot.connection)
|
||||
}.onFailure { Log.w(TAG, "worker ${slot.index} could not be bound", it) }.getOrDefault(false)
|
||||
if (!bound) {
|
||||
release(app, slot)
|
||||
return null
|
||||
}
|
||||
@@ -373,8 +381,11 @@ object GuestWorkers {
|
||||
release(app, slot)
|
||||
continue
|
||||
}
|
||||
synchronized(slots) { if (slots[slot.index] === slot && warmTarget > 0) warm.addLast(slot) }
|
||||
if (warmTarget == 0) release(app, slot)
|
||||
// decided once, under the lock: kept warm, or released
|
||||
val kept = synchronized(slots) {
|
||||
(slots[slot.index] === slot && warmTarget > 0).also { if (it) warm.addLast(slot) }
|
||||
}
|
||||
if (!kept) release(app, slot)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -403,7 +414,7 @@ object GuestWorkers {
|
||||
// an exit code only when the process exited itself; a signal number otherwise (a native crash)
|
||||
return if (it.reason == android.app.ApplicationExitInfo.REASON_EXIT_SELF) (it.status and 0xff) shl 8
|
||||
else if (it.status in 1..64) it.status and 0x7f
|
||||
else (it.status and 0xff) shl 8
|
||||
else OsConstants.SIGKILL // killed by Android with no signal recorded, not a clean exit
|
||||
}
|
||||
Thread.sleep(50)
|
||||
}
|
||||
@@ -416,10 +427,11 @@ object GuestWorkers {
|
||||
|
||||
/** Ends session [of]'s guest programs that are still running, and, for the latest session, the warm workers. */
|
||||
fun stopGuests(of: Int = session) {
|
||||
if (of == session) {
|
||||
warmTarget = 0
|
||||
context?.let { app -> synchronized(slots) { warm.toList().also { warm.clear() } }.forEach { release(app, it) } }
|
||||
// the check and the reset together: a new session's serve() may be under way
|
||||
val drained = synchronized(slots) {
|
||||
if (of != session) emptyList() else { warmTarget = 0; warm.toList().also { warm.clear() } }
|
||||
}
|
||||
context?.let { app -> drained.forEach { release(app, it) } }
|
||||
val pids = guestPids(of)
|
||||
if (pids.isEmpty()) return
|
||||
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
|
||||
@@ -436,8 +448,7 @@ object GuestWorkers {
|
||||
fun serve(context: Context): Int {
|
||||
val app = context.applicationContext
|
||||
this.context = app
|
||||
val number = ++session
|
||||
warmTarget = WARM_WORKERS
|
||||
val number = synchronized(slots) { warmTarget = WARM_WORKERS; ++session }
|
||||
refill(app)
|
||||
synchronized(this) {
|
||||
if (server != null) return number
|
||||
@@ -477,9 +488,15 @@ object GuestWorkers {
|
||||
val fds = ArrayList<ParcelFileDescriptor>()
|
||||
fun take() {
|
||||
val received = client.ancillaryFileDescriptors.orEmpty()
|
||||
received.forEach { fds.add(ParcelFileDescriptor.dup(it)) }
|
||||
received.forEach { runCatching { Os.close(it) } }
|
||||
try {
|
||||
received.forEach { fds.add(ParcelFileDescriptor.dup(it)) }
|
||||
} finally {
|
||||
received.forEach { runCatching { Os.close(it) } }
|
||||
}
|
||||
}
|
||||
// Until start() has them: closed on every way out before that, from the first chunk on
|
||||
var handedOver = false
|
||||
try {
|
||||
if (request.has("fdchunks")) {
|
||||
// The hook sends its fds after the request, a chunk with each byte (hook/handoff.c)
|
||||
val total = (request.optJSONArray("fds")?.length() ?: 0) + (if (request.has("table")) 1 else 0)
|
||||
@@ -490,9 +507,6 @@ object GuestWorkers {
|
||||
} else {
|
||||
take()
|
||||
}
|
||||
// Until start() has them: closed on every way out before that
|
||||
var handedOver = false
|
||||
try {
|
||||
val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } }
|
||||
val env = LinkedHashMap<String, String>()
|
||||
request.optJSONObject("env")?.let { o -> o.keys().forEach { env[it] = o.getString(it) } }
|
||||
@@ -543,6 +557,8 @@ object GuestWorkers {
|
||||
if (request.has("umask")) env["DDH_UMASK"] = request.getLong("umask").toString()
|
||||
if (request.has("pgid")) env["DDH_PGID"] = request.getLong("pgid").toString()
|
||||
if (request.has("anchor")) env["DDH_ANCHOR"] = request.getLong("anchor").toString()
|
||||
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()
|
||||
val child = request.optInt("child", -1)
|
||||
val exited = CountDownLatch(1)
|
||||
|
||||
@@ -701,8 +701,11 @@ class SessionService : Service() {
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
|
||||
// this session's worker number: the shared field may be a newer session's by the time it is used
|
||||
var ownWorkers = 0
|
||||
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
|
||||
guestWorkerSession = com.droiddeck.launcher.runtime.GuestWorkers.serve(this)
|
||||
ownWorkers = com.droiddeck.launcher.runtime.GuestWorkers.serve(this)
|
||||
guestWorkerSession = ownWorkers
|
||||
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
|
||||
}
|
||||
// Proton builds up to 11.12 report X11 text fields under this name.
|
||||
@@ -881,8 +884,9 @@ class SessionService : Service() {
|
||||
syncWatcher = null
|
||||
}
|
||||
abandonStart(gen, sessionDir, started)
|
||||
val workers = guestWorkerSession
|
||||
val workers = ownWorkers
|
||||
if (pid > 1) Thread({ teardown(pid, workerSession = workers) }, "session-teardown").start()
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
|
||||
return
|
||||
}
|
||||
sessionPid = pid
|
||||
@@ -2406,6 +2410,7 @@ class SessionService : Service() {
|
||||
} else {
|
||||
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
|
||||
Thread({
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
|
||||
@@ -400,7 +400,8 @@ handed-off daemons. With only the hook's handoffs off (`DD_SPAWN_DAEMONS=0`), RE
|
||||
**In the app:** `PhantomProcessStatus.UNCOUNTED` is reported when the limit is on but the session
|
||||
runs in workers (`GuestWorkers.enabled`: the native userland, Android 11+, and the
|
||||
`childProcessHandoff` session preference, on by default). It does not block Steam. Turning the
|
||||
preference off (`droiddeckctl prefs set session childProcessHandoff false --type bool`) brings back
|
||||
preference off (`droiddeckctl prefs set session childProcessHandoff false --type bool`, with
|
||||
Setup > Developer > Debugging tools on; see `docs/agent-control.md`) brings back
|
||||
the old behavior and the old requirement.
|
||||
|
||||
### C. Plan
|
||||
@@ -466,4 +467,5 @@ Targets: `main`, `proc` (`:proc`), `isoplain`, `iso:<name>` (one app-zygote inst
|
||||
reading the phantom list. Restore the noted values afterwards: `adb shell device_config put
|
||||
activity_manager max_phantom_processes <value>` (or `adb shell device_config delete activity_manager
|
||||
max_phantom_processes` if it was null), `adb shell device_config set_sync_disabled_for_tests <mode>`
|
||||
and `adb shell settings put global settings_enable_monitor_phantom_procs <value>`.
|
||||
and `adb shell settings put global settings_enable_monitor_phantom_procs <value>`, and end the lab's
|
||||
sleepers with `adb shell am force-stop com.droiddeck.phantomlab`.
|
||||
@@ -59,7 +59,8 @@ static void ddh_log(const char *setting, const char *line, size_t len) {
|
||||
syscall(SYS_write, 2, line, len);
|
||||
return;
|
||||
}
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, setting, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644);
|
||||
// non-blocking: a FIFO with no reader must not hold up the call being traced (a kill())
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, setting, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NONBLOCK, 0644);
|
||||
if (fd < 0) return;
|
||||
syscall(SYS_write, fd, line, len);
|
||||
syscall(SYS_close, fd);
|
||||
@@ -339,6 +340,7 @@ static void ddh_linger(int flush) {
|
||||
static void ddh_register_group(void);
|
||||
static void ddh_unregister_group(void);
|
||||
static pid_t ddh_logical_pgrp(void);
|
||||
static long ddh_start_time(pid_t pid);
|
||||
|
||||
// From exit() (on_exit, arg 1) or _exit() (arg NULL) in a worker's own process.
|
||||
// Only a handed-off child lingers: the app waits for the death of the programs it starts itself
|
||||
@@ -487,7 +489,7 @@ static void ddh_putint(struct ddh_buf *b, long v) {
|
||||
char tmp[24];
|
||||
int i = sizeof(tmp);
|
||||
int neg = v < 0;
|
||||
unsigned long u = neg ? (unsigned long)-v : (unsigned long)v;
|
||||
unsigned long u = neg ? 0UL - (unsigned long)v : (unsigned long)v; // no overflow for LONG_MIN
|
||||
do {
|
||||
tmp[--i] = (char)('0' + u % 10);
|
||||
u /= 10;
|
||||
@@ -715,6 +717,8 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[]
|
||||
mode_t mask = umask(0);
|
||||
umask(mask);
|
||||
sigset_t blocked;
|
||||
pid_t anchor = getenv("DDH_WORKER_PID") ? (pid_t)atoi(getenv("DDH_WORKER_PID")) : parent;
|
||||
long parent_start = ddh_start_time(parent), anchor_start = ddh_start_time(anchor);
|
||||
unsigned long blocked_bits = 0;
|
||||
if (sigprocmask(SIG_BLOCK, NULL, &blocked) == 0) {
|
||||
for (int sig = 1; sig <= 64 && sig < NSIG; sig++) {
|
||||
@@ -759,7 +763,12 @@ static void ddh_try(const char *filename, char *const argv[], char *const envp[]
|
||||
ddh_puts(&b, ",\"sigmask\":");
|
||||
ddh_putint(&b, (long)blocked_bits);
|
||||
ddh_puts(&b, ",\"anchor\":");
|
||||
ddh_putint(&b, getenv("DDH_WORKER_PID") ? (long)atoi(getenv("DDH_WORKER_PID")) : (long)parent);
|
||||
ddh_putint(&b, (long)anchor);
|
||||
// their start times now, while both are surely the ones meant (see ddh_logical_parent)
|
||||
ddh_puts(&b, ",\"pstart\":");
|
||||
ddh_putint(&b, parent_start);
|
||||
ddh_puts(&b, ",\"astart\":");
|
||||
ddh_putint(&b, anchor_start);
|
||||
ddh_puts(&b, "}");
|
||||
if (pass == 0) {
|
||||
b.cap = b.len + 4;
|
||||
@@ -911,6 +920,13 @@ static ddh_wait4_f ddh_real_wait4(void) {
|
||||
|
||||
// A wait interrupted by a signal: as the real call, which a handler installed with SA_RESTART restarts.
|
||||
// The app's and the program's SIGCHLD are the usual ones.
|
||||
// The forked child of an entry whose program has exited: 1 once reaped (or already gone), 0 when it is
|
||||
// still exiting and WNOHANG was asked for, or the wait was interrupted.
|
||||
static int ddh_reap_shim(ddh_wait4_f real, pid_t child, int options) {
|
||||
pid_t r = real(child, NULL, options & WNOHANG, NULL);
|
||||
return r == child || (r < 0 && errno == ECHILD);
|
||||
}
|
||||
|
||||
static int ddh_nap(void) {
|
||||
struct timespec ts = {0, 20 * 1000 * 1000};
|
||||
if (nanosleep(&ts, NULL) == 0) return 0;
|
||||
@@ -934,9 +950,9 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) {
|
||||
if (pid > 0 && e) {
|
||||
if (!e->reaped && real(pid, NULL, WNOHANG, NULL) == pid) e->reaped = 1;
|
||||
if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_EXITED) {
|
||||
// the forked child is between its last write and its exit: reap it now, or a later
|
||||
// wait() would report its pid a second time
|
||||
if (!e->reaped) real(pid, NULL, 0, NULL);
|
||||
// the forked child is between its last write and its exit: reap it first, or a later
|
||||
// wait() would report its pid a second time (not blocking for WNOHANG: then later)
|
||||
if (!e->reaped && !ddh_reap_shim(real, pid, options)) return (options & WNOHANG) ? 0 : -1;
|
||||
if (ru) memset(ru, 0, sizeof(*ru));
|
||||
ddh_release(e, status);
|
||||
return pid;
|
||||
@@ -947,7 +963,7 @@ static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) {
|
||||
}
|
||||
if (pid <= 0 && (e = ddh_exited())) {
|
||||
pid_t child = e->child;
|
||||
if (!e->reaped) real(child, NULL, 0, NULL);
|
||||
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;
|
||||
@@ -1077,10 +1093,13 @@ static void ddh_register_group(void) {
|
||||
if (g_ddh_report_parent > 0) {
|
||||
snprintf(name, sizeof(name), "P%d", (int)getpid());
|
||||
// with their start times: a pid followed later may have been reused by then
|
||||
const char *anchor_env = getenv("DDH_ANCHOR");
|
||||
// the start times the request recorded (DDH_PSTART, DDH_ASTART): one read now could be a
|
||||
// reused pid's, the forking process having exited meanwhile
|
||||
const char *anchor_env = getenv("DDH_ANCHOR"), *pstart = getenv("DDH_PSTART"), *astart = getenv("DDH_ASTART");
|
||||
pid_t anchor = anchor_env ? (pid_t)atoi(anchor_env) : g_ddh_report_parent;
|
||||
int len = snprintf(text, sizeof(text), "%ld %d %d %ld %ld\n", start, (int)g_ddh_report_parent, (int)anchor,
|
||||
ddh_start_time(g_ddh_report_parent), ddh_start_time(anchor));
|
||||
pstart ? atol(pstart) : ddh_start_time(g_ddh_report_parent),
|
||||
astart ? atol(astart) : ddh_start_time(anchor));
|
||||
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)dir, (unsigned long)name,
|
||||
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644, 0, 0);
|
||||
if (fd >= 0) {
|
||||
|
||||
Reference in new issue
Block a user