Compare commits

..
Author SHA1 Message Date
5cd6fe8864 feat(session): run the session outside Android's child-process count (#3338)
* docs: research Android's child-process limit without developer options

* docs: confirm the child-process gaps on the Thor

* feat(session): start long-lived daemons in uncounted worker processes

* feat(nativeguest): hand long-lived programs to uncounted worker processes

* test(session): run the session bus block with dd_spawn

* test(nativeguest): cover the exec handoff's wait and kill

* feat(session): run the session root, its jobs and the gamescope chain outside the child-process count

* feat(setup): the child-process limit no longer blocks Steam while the session runs in workers

* feat(audio): run PulseAudio outside the child-process count

* feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive

* fix(nativeguest): let Steam end a handed-off game and keep process-group signals

* perf(session): exec a worker as soon as its reply is in and keep two bound ahead; fix review findings

* fix(nativeguest): address review findings in handoff waits, signals and spawn errors

* fix(session): commit each worker launch explicitly and keep workers with the session that asked

* fix(session): let a worker wait for its launch commit on the main thread

* fix(session): confirm handoffs, honour wait selectors and stop spawns at teardown

* fix(session): one owner per handoff exit, worker launch answers and spawn edge cases

* fix(session): send a working directory outside the program's root by its real path

* fix(session): recheck a taken exit's child and commit a launch only on a whole go line

* fix(session): three-step launch, tagged exit reports and lock-free popen and system children

* test(native): popen test shell is static, as the other hook fixtures

* test(native): run the popen test program with a clean environment

* test(native): skip the popen test where a spawn child cannot exec aarch64

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

* fix(session): tell a reused pid's old entry by start time, not the reaped flag

* fix(session): silent failed launches, bounded spawn requests and held check-gone writes

* test(native): check the unlisted child's status only where a child can exec aarch64

* fix(session): every exit-only waitid goes through the handoff wait

* fix(handoff): exact waitid events, safe exit timer, bounded request receipt

* feat(handoff): hand off shell children near Android's process limit

* fix(agent): tag handed-off game windows outside the reaper

* fix(handoff): a handed-off program's getppid() is its forking process

* fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports

* fix(handoff): getppid() gives init for an exited or replaced parent

* fix(handoff): keep __WALL waitid calls on the handoff path

* test(handoff): require a zombie parent in the unreaped-parent case

* fix(handoff): honor __WNOTHREAD and check every argument for Steam

* fix(handoff): stop waiting on a held entry once its parent has exited

* fix(handoff): __WNOTHREAD on waits for a pid, flags on every shim reap

* fix(handoff): keep the forking thread of each child in the parent

* fix(handoff): a wait that finds no child rechecks live handoffs

* fix(handoff): keep a child's forking thread until its end is taken

* fix(handoff): the thread selector applies to claims in progress too

* fix(handoff): controlling-terminal check via /dev/tty, owned records only

* fix(handoff): a child whose forking thread ended is any thread's

* fix(handoff): a parent /proc cannot read is checked with kill(), then given up

* fix(handoff): one-word fork records, changed only by compare-and-swap

* fix(handoff): watch the forking parent through a pidfd opened at start

* fix(handoff): fork records by pid, a gone thread's children go to the main one

* fix(handoff): keep the parent pidfd through dup2 and check it before use

* fix(handoff): no handoff without fork records, unknown thread state keeps the owner

* fix(handoff): undo a pidfd move when dup fails, recheck it after the poll

* fix(handoff): fresh fork records in a forked child, heir is the first live thread

* fix(handoff): one lock over a pidfd move, its dup and the undo

* fix(handoff): liveness check under the pidfd lock, forget only a reaped pid's record

* fix(handoff): lock only dups onto the pidfd, with signals blocked

* fix(handoff): fork record generations, no pidfd restore after a failed move

* fix(handoff): every dup in a pidfd process locks, fork prep blocks signals

* test(semaphores): tell a child hung in qemu-user from a guest deadlock

* fix(handoff): fork records matched by the child's start time, never removed

* test(semaphores): count only reaped children, only futex waits as emulator stalls

* fix(handoff): a known-start bit in fork records

* fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept

* fix(handoff): a fork record stays only for the pid's current process

* fix(handoff): keep a pending child's fork record when an older fork records late

* fix(handoff): an unknown-start fork record never replaces a pending one

* fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits

* test(handoff): find the module in the namespace run under discover too

* fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd

* test(handoff): require ENOEXEC for an ELF stub; skip the namespace run without binfmt

* fix(hook): change the kept fd list under a sequence lock; readers take a copy

* fix(handoff): one report per handed-off child; stops keep a claim; nested waits keep their selector

* fix(hook): a table made at runtime outlives closes begun before it; unknown-start fork records kept

* fix(handoff): waits look before they reap, so a handed-off fork's child is never reported

* fix(hook): settle waits out earlier epochs; unknown-start fork records kept for any handoff under way

* fix(handoff): generation-checked reap marks, stops taken as stops, close counts reset in a fork

* fix(handoff): one given-up table at most, whole stop codes and rusage, WNOWAIT exits rechecked

* fix(handoff): requests name their session; stops of handed-off programs reported; cancellable look

* fix(handoff): table setup not cancellable; test spawner never runs what it cannot end

* fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup

* docs(phantom): job-control jobs stay counted; listed programs report no stops

* fix(handoff): a listed program a shell runs as a job-control job stays counted

* refactor(hook): kept descriptors in their own part, a handoff matched by another program

The descriptors close(), close_range() and closefrom() leave open move from
privileged.c to hook/kept.c (unchanged), so the bionic runtime's exec shim can
build the handoff with them. ddh_try_as() matches DD_HANDOFF against one
program and sends another: the bionic shim sends "/system/bin/linker64 PROGRAM
ARGS" and lists it by PROGRAM. ddh_try() is ddh_try_as() with both the same.

* feat(bionic): hand the bionic runtime's Wine programs to the app's workers

The glibc session's hook never sees DroidDeck-Bionic's processes (Wine on
Android's libc), so a bionic game's Wine programs all stayed counted under the
worker running the tool's launch.sh. The handoff is now built into the
runtime's exec shim (tools/bionic-runtime/handoff.c, part of libexecshim.so):

- hook/handoff.c and hook/kept.c with what the native hook's other parts do
  around them: fork(), close(), close_range(), dup2(), dup3(), and exit() for
  the on_exit() bionic lacks
- bionic's execv(), execvp(), execl*() reach the execve system call inside
  libc, past execshim's execve(); Wine starts its preloader with execv(), so
  the shim defines them on top of its execve()
- a linker64 start is listed by its program
- the app starts a handed-off program from the glibc root's bash, which cannot
  load the runtime's LD_PRELOAD/LD_LIBRARY_PATH: they go as arguments of
  /system/bin/env, which puts them back for the program
- launch.sh keeps DD_SPAWN, DD_SPAWN_SESSION, DD_HANDOFF*, DDH_* and
  DDNATV_ROOT, and its /proc/N/environ reads no longer print "Permission
  denied" for idle workers (2>/dev/null before the redirect)

Pocket FIT, DroidDeck-Bionic 14.1-r67 with this shim and launcher, handoff on:
counted during Brawlhalla 25 -> 17, DiRT Showdown 24-27 -> 16, whole run
28 -> 19-20; with Android's limit on no DroidDeck process and no other app's
process was killed (before: Discord, BatteryLog helpers); DiRT 75 fps either
way. docs/phantom-processes.md: "The bionic runtime".

* fix(bionic): hand off only starts that would succeed here; bionic's execvp fallbacks

Review follow-ups on the bionic runtime's handoff (tools/bionic-runtime/handoff.c):

- A start is handed to a worker only when it would get past execve() in this process: the file is a
  regular executable outside the app's data (Android refuses execve() there), and for a linker64 start
  the program it loads is a readable regular file. A start that failed in the worker failed where the
  caller could not see it, so Wine never tried its next candidate. The hook's own check looked at
  /system/bin/env, not the program.
- A start whose argv[0] is not its file stays here: env starts FILE with FILE as argv[0]. linker64 and
  interpreter starts are unaffected (their argv[0] is the file). An empty argv stays here too.
- Nothing is built for the handoff without DD_SPAWN and DD_HANDOFF.
- execvp()/execvpe()/execlp() follow bionic's: an unset PATH is libc's default, an empty PATH or entry
  is the current directory, and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh.
- close_range() refuses first > last and unknown flags before it splits the range or unshares the table.
- The debug line reads the table's owner only once the table is seen published.

* fix(bionic): hand off app-data starts only where SELinux lets them run; bare names stay here

Follow-up to 7d95564f7 (review, and a Pocket FIT test of its pack):

- 7d95564f7 kept every start of a file in the app's data here. Wine's preloader is one (a static ELF,
  so execshim.c cannot make it a linker64 start), and where SELinux is permissive, as on AYANEO's
  firmware, it runs: Wine then never reached its loader, and its programs ran here, counted again
  (Pocket FIT: Brawlhalla 26-28 counted vs 16-17 before). Where SELinux enforces, Android refuses the
  exec, here and in a worker alike, and Wine falls back to its loader, which goes as a linker64 start.
  Such a start is now handed off when /sys/fs/selinux/enforce reads 0, and stays here otherwise
  (also when the setting cannot be read).
- The program a start would run is checked with the hook's own ddh_startable() (an ELF the kernel
  loads with its interpreter there, or a script with its interpreter): for a linker64 start, the
  program it loads.
- A file name without '/' stays here: env would look it up in PATH, the exec here in the caller's
  working directory.
- execvpe() skips a PATH entry whose candidate exceeds PATH_MAX (ENAMETOOLONG) instead of copying
  it onto the stack.

* fix(handoff): spawn blocks signals and cancellation across the fork; root flag stored under the stop lock

* fix(handoff): a thread that unshares its fd table keeps its own copy of the kept fds

* fix(handoff): register the kept list's fork handlers before a split takes its lock

* test(handoff): cover WNOHANG with a held forked child, early reaps, blocked waitid and pidfd parents; keep the counted-process exception in translations

* test(handoff): exited-entry precondition, atomic checkpoints, a pidfd-only zombie check; validate the shim hold fd

* test(handoff): WNOHANG with two handed-off children and for a group; a program's exit while its entry is held

* test(handoff): a held exit with no free fd, with and without the parent's pidfd

* test(handoff): held-exit tests require the program's own exit status

* test(handoff): time held exits from the run, and only once the program is at its exit

* perf(handoff): keep the asker's priority, quick tools local, workers bound ahead of a game (#3582)

Three fixes that bring handoff-on speed to within 1-2 % of handoff off
(AIO D3D11 same session: 3196 -> 3520 fps, 1 % low 444 -> 637) with the
same counted processes (benchmark mean 18.5, peak 23):

- A handed-off program keeps its asker's priority. Workers are bound
  from the top app with BIND_IMPORTANT, so Android boosts their main
  thread to THREAD_PRIORITY_TOP_APP_BOOST (-10); the program the worker
  execs inherited it. The asker's nice value is sent with the request and
  set before execve, and a watcher resets it if Android boosts it again.
- Quick script tools (awk, sed, grep, cat, ...) stay where they are when
  the count is near the limit. Sent to a worker, the forked child waits
  (counted) while a worker starts; run locally it is counted for a few ms.
- Workers are bound ahead when a Steam game is queued (16 for 20 s), so
  Wine's services do not wait on zygote forks at game start.

---------

Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
2026-12-02 14:02:55 -05:00
Kurt Himebauch 186bae8f3e feat(native): run the desktop, its apps and shells as an ordinary user instead of fake root (#3587)
* feat(native): run the desktop, its apps and shells as an ordinary user instead of fake root

* fix(native): a script's interpreter takes DDNATV_BECOME, so sudo runs scripts as root

* fix(desktop): keep the Plasma start line the pipewire tests slice the script at
2026-12-02 13:50:06 -05:00
Kurt Himebauch 3bb22dc92b fix(native): terminals use the ioctls Android allows on an app's pseudo-terminal (#3585)
* fix(native): terminals use the ioctls Android allows on an app's pseudo-terminal

* fix(native): leave a terminal request alone when its register is read before the high half
2026-12-02 13:47:59 -05:00
LunaDL f3f410059d Feat:Add separate orientation settings for Steam and desktop sessions (#3567)
* Add per-session orientation preferences

* Apply orientation preference for active session

* Use session-specific orientation for output following

* Test independent session orientation preferences

* Map run sessions to Steam orientation preference

* Add separate Steam and desktop orientation controls

* Cover session mode orientation mapping

* Persist in-session orientation by session mode

* Refresh inherited orientation settings after global change

* Resolve window and portrait orientation by session mode

* Use session orientation for output sizing and window behavior

* Test mode-specific window and portrait orientation

* Refresh session orientation choices on resume

* Refresh session orientation choices on resume

* Use Compose lifecycle owner import

* Trigger CI
2026-12-02 12:29:52 -05:00
MaxsTechReview 6e7908ed81 fix(display): copy the game and the window above it in one GPU submit (#3583)
* fix(display): copy the game and the window above it in one GPU submit

When a game's frames go on the layer-copy path and a window sits above
the game, each scene copied the game frame and then the window above it
with two separate submits and two CPU waits. Each wait queued behind
the game's own GPU work, so a GPU-bound game lost on-screen frames to
the second wait.

Record both copies in one command buffer, merge their release fences,
and wait once per scene. The zero-copy path and the single-layer copy
path are unchanged.

* Check overlay eligibility against the frame's own game geometry and keep both release waits when a fence merge fails
2026-12-02 12:12:08 -05:00
LunaDL 9ca6fa064e fix(bionic): the WSI layer uses its normal bypass check, and zero-copy fallbacks log their reason (#3487)
The Bionic launcher no longer forces the WSI layer's XWayland bypass; the layer runs its normal eligibility check, cached for 100 ms. The compositor logs, rate-limited, why a frame or layer candidate leaves the zero-copy path: no registered gralloc buffer, a failed direct present, or a rejected candidate draw.

Tested on a 60 Hz Adreno handheld with the forced bypass on and off and with two driver versions: every run stayed on the zero-copy path at about 60 fps.
2026-12-02 04:04:53 -05:00
MaxsTechReview aab15f3146 fix(display): copy zero-copy frames that carry no acquire fence (#3427)
When a frame's acquire fence cannot be exported from its dma-buf, the frame takes the layer-copy path instead of reaching the display unfenced. Fixes #3410.
2026-12-02 03:29:48 -05:00
117 changed files with 10261 additions and 259 deletions

No files matched your search

+64
View File
@@ -417,5 +417,69 @@
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
tools:node="remove" />
</service>
<service android:name=".runtime.GuestWorker0" android:exported="false" android:process=":g0" />
<service android:name=".runtime.GuestWorker1" android:exported="false" android:process=":g1" />
<service android:name=".runtime.GuestWorker2" android:exported="false" android:process=":g2" />
<service android:name=".runtime.GuestWorker3" android:exported="false" android:process=":g3" />
<service android:name=".runtime.GuestWorker4" android:exported="false" android:process=":g4" />
<service android:name=".runtime.GuestWorker5" android:exported="false" android:process=":g5" />
<service android:name=".runtime.GuestWorker6" android:exported="false" android:process=":g6" />
<service android:name=".runtime.GuestWorker7" android:exported="false" android:process=":g7" />
<service android:name=".runtime.GuestWorker8" android:exported="false" android:process=":g8" />
<service android:name=".runtime.GuestWorker9" android:exported="false" android:process=":g9" />
<service android:name=".runtime.GuestWorker10" android:exported="false" android:process=":g10" />
<service android:name=".runtime.GuestWorker11" android:exported="false" android:process=":g11" />
<service android:name=".runtime.GuestWorker12" android:exported="false" android:process=":g12" />
<service android:name=".runtime.GuestWorker13" android:exported="false" android:process=":g13" />
<service android:name=".runtime.GuestWorker14" android:exported="false" android:process=":g14" />
<service android:name=".runtime.GuestWorker15" android:exported="false" android:process=":g15" />
<service android:name=".runtime.GuestWorker16" android:exported="false" android:process=":g16" />
<service android:name=".runtime.GuestWorker17" android:exported="false" android:process=":g17" />
<service android:name=".runtime.GuestWorker18" android:exported="false" android:process=":g18" />
<service android:name=".runtime.GuestWorker19" android:exported="false" android:process=":g19" />
<service android:name=".runtime.GuestWorker20" android:exported="false" android:process=":g20" />
<service android:name=".runtime.GuestWorker21" android:exported="false" android:process=":g21" />
<service android:name=".runtime.GuestWorker22" android:exported="false" android:process=":g22" />
<service android:name=".runtime.GuestWorker23" android:exported="false" android:process=":g23" />
<service android:name=".runtime.GuestWorker24" android:exported="false" android:process=":g24" />
<service android:name=".runtime.GuestWorker25" android:exported="false" android:process=":g25" />
<service android:name=".runtime.GuestWorker26" android:exported="false" android:process=":g26" />
<service android:name=".runtime.GuestWorker27" android:exported="false" android:process=":g27" />
<service android:name=".runtime.GuestWorker28" android:exported="false" android:process=":g28" />
<service android:name=".runtime.GuestWorker29" android:exported="false" android:process=":g29" />
<service android:name=".runtime.GuestWorker30" android:exported="false" android:process=":g30" />
<service android:name=".runtime.GuestWorker31" android:exported="false" android:process=":g31" />
<service android:name=".runtime.GuestWorker32" android:exported="false" android:process=":g32" />
<service android:name=".runtime.GuestWorker33" android:exported="false" android:process=":g33" />
<service android:name=".runtime.GuestWorker34" android:exported="false" android:process=":g34" />
<service android:name=".runtime.GuestWorker35" android:exported="false" android:process=":g35" />
<service android:name=".runtime.GuestWorker36" android:exported="false" android:process=":g36" />
<service android:name=".runtime.GuestWorker37" android:exported="false" android:process=":g37" />
<service android:name=".runtime.GuestWorker38" android:exported="false" android:process=":g38" />
<service android:name=".runtime.GuestWorker39" android:exported="false" android:process=":g39" />
<service android:name=".runtime.GuestWorker40" android:exported="false" android:process=":g40" />
<service android:name=".runtime.GuestWorker41" android:exported="false" android:process=":g41" />
<service android:name=".runtime.GuestWorker42" android:exported="false" android:process=":g42" />
<service android:name=".runtime.GuestWorker43" android:exported="false" android:process=":g43" />
<service android:name=".runtime.GuestWorker44" android:exported="false" android:process=":g44" />
<service android:name=".runtime.GuestWorker45" android:exported="false" android:process=":g45" />
<service android:name=".runtime.GuestWorker46" android:exported="false" android:process=":g46" />
<service android:name=".runtime.GuestWorker47" android:exported="false" android:process=":g47" />
<service android:name=".runtime.GuestWorker48" android:exported="false" android:process=":g48" />
<service android:name=".runtime.GuestWorker49" android:exported="false" android:process=":g49" />
<service android:name=".runtime.GuestWorker50" android:exported="false" android:process=":g50" />
<service android:name=".runtime.GuestWorker51" android:exported="false" android:process=":g51" />
<service android:name=".runtime.GuestWorker52" android:exported="false" android:process=":g52" />
<service android:name=".runtime.GuestWorker53" android:exported="false" android:process=":g53" />
<service android:name=".runtime.GuestWorker54" android:exported="false" android:process=":g54" />
<service android:name=".runtime.GuestWorker55" android:exported="false" android:process=":g55" />
<service android:name=".runtime.GuestWorker56" android:exported="false" android:process=":g56" />
<service android:name=".runtime.GuestWorker57" android:exported="false" android:process=":g57" />
<service android:name=".runtime.GuestWorker58" android:exported="false" android:process=":g58" />
<service android:name=".runtime.GuestWorker59" android:exported="false" android:process=":g59" />
<service android:name=".runtime.GuestWorker60" android:exported="false" android:process=":g60" />
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
</application>
</manifest>
@@ -205,15 +205,19 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else if (dmabuf_fd >= 0) {
} else {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead",
strerror(errno));
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
}
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
}
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
s ? droiddeck_surface_color(s) : NULL, ab->format);
+223 -16
View File
@@ -2272,6 +2272,69 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
struct draw_list { struct vkp_draw *d; int n, cap; };
#define ZERO_COPY_FALLBACK_SIGNATURES 32u
enum zero_copy_fallback_reason {
ZERO_COPY_NO_SURFACE_BUFFER = 1,
ZERO_COPY_NO_GRALLOC_AHB = 2,
ZERO_COPY_AHB_PRESENT_FAILED = 3
};
struct zero_copy_fallback_signature {
uint32_t reason, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct zero_copy_fallback_signature g_zero_copy_fallbacks[ZERO_COPY_FALLBACK_SIGNATURES];
static uint32_t g_zero_copy_fallback_count;
static int g_zero_copy_fallback_limit_logged;
static int zero_copy_fallback_should_log(const struct dmabuf_buffer *b, uint32_t reason) {
const struct zero_copy_fallback_signature key = {
.reason = reason, .format = b ? b->format : 0,
.stride = b && b->n_planes ? b->stride[0] : 0,
.offset = b && b->n_planes ? b->offset[0] : 0,
.width = b ? b->width : 0, .height = b ? b->height : 0,
.modifier = b ? b->modifier : 0};
for (uint32_t i = 0; i < g_zero_copy_fallback_count; i++) {
const struct zero_copy_fallback_signature *seen = &g_zero_copy_fallbacks[i];
if (seen->reason == key.reason && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_zero_copy_fallback_count >= ZERO_COPY_FALLBACK_SIGNATURES) {
if (!g_zero_copy_fallback_limit_logged) {
g_zero_copy_fallback_limit_logged = 1;
droiddeck_log("layer", "zero-copy: further fallback diagnostics suppressed after %u distinct buffer signatures",
ZERO_COPY_FALLBACK_SIGNATURES);
}
return 0;
}
g_zero_copy_fallbacks[g_zero_copy_fallback_count++] = key;
return 1;
}
static void note_zero_copy_fallback(struct surface *s, const struct dmabuf_buffer *b, uint32_t reason,
int scene_w, int scene_h, int present_result) {
if (!zero_copy_fallback_should_log(b, reason)) return;
char name[160] = "unknown surface";
if (s) describe(s, name, sizeof(name));
if (reason == ZERO_COPY_NO_SURFACE_BUFFER) {
droiddeck_log("layer", "zero-copy: layer candidate %s has no associated Wayland surface buffer; using the layer-copy path",
name);
} else {
droiddeck_log("layer", "zero-copy: %s buffer %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx %s; "
"scene %dx%d will use the layer-copy path (direct-present result %d)",
name, b->format & 0xff, (b->format >> 8) & 0xff, (b->format >> 16) & 0xff,
(b->format >> 24) & 0xff, b->width, b->height,
b->n_planes ? b->stride[0] : 0, b->n_planes ? b->offset[0] : 0,
(unsigned long long)b->modifier,
reason == ZERO_COPY_NO_GRALLOC_AHB
? "has no registered gralloc AHardwareBuffer"
: "has a registered gralloc AHardwareBuffer but direct presentation failed",
scene_w, scene_h, present_result);
}
}
static int add_cursor(struct draw_list *dl, int scene_w);
static struct vkp_image *surface_image(struct surface *s) {
@@ -2391,17 +2454,53 @@ static int black_fill_below(const struct draw_list *dl, int n) {
return 1;
}
#define LAYER_CANDIDATE_DIAGNOSTICS 32u
static unsigned g_layer_candidate_diag_count;
static int g_layer_candidate_diag_limit;
static void note_layer_candidate_skip(const struct vkp_draw *d, int index, int reason,
int scene_w, int scene_h) {
static int seen[LAYER_CANDIDATE_DIAGNOSTICS][8];
const int key[8] = {index, reason, scene_w, scene_h, d->dx, d->dy, d->dw, d->dh};
for (unsigned i = 0; i < g_layer_candidate_diag_count; i++)
if (!memcmp(seen[i], key, sizeof(key))) return;
if (g_layer_candidate_diag_count >= LAYER_CANDIDATE_DIAGNOSTICS) {
if (!g_layer_candidate_diag_limit++) droiddeck_log("layer", "zero-copy: further candidate-rejection details suppressed after %u signatures",
LAYER_CANDIDATE_DIAGNOSTICS);
return;
}
memcpy(seen[g_layer_candidate_diag_count++], key, sizeof(key));
const char *why = reason == 1 ? "translucent draw" :
reason == 2 ? "image is not DMA-BUF" :
reason == 3 ? "source rectangle is outside/invalid" :
reason == 4 ? "draw rectangle is outside scene or invalid" :
"not fullscreen and no black backing below";
droiddeck_log("layer", "zero-copy: candidate draw %d rejected: %s; scene %dx%d, dst %dx%d at %d,%d, src %.2f,%.2f %.2fx%.2f, image %dx%d",
index, why, scene_w, scene_h, d->dw, d->dh, d->dx, d->dy,
d->sx, d->sy, d->sw, d->sh, vkp_image_width(d->img), vkp_image_height(d->img));
}
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
const struct vkp_draw *d = &dl->d[i];
if (d->blend) continue;
if (!vkp_image_is_dmabuf(d->img)) continue;
if (d->blend) { note_layer_candidate_skip(d, i, 1, scene_w, scene_h); continue; }
if (!vkp_image_is_dmabuf(d->img)) { note_layer_candidate_skip(d, i, 2, scene_w, scene_h); continue; }
if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f ||
d->sx + d->sw >= vkp_image_width(d->img) + 1.0f ||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue;
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) {
note_layer_candidate_skip(d, i, 3, scene_w, scene_h);
continue;
}
if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i;
if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w ||
d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue;
d->dy + d->dh > scene_h) {
note_layer_candidate_skip(d, i, 4, scene_w, scene_h);
continue;
}
if (!black_fill_below(dl, i)) {
note_layer_candidate_skip(d, i, 5, scene_w, scene_h);
continue;
}
return i;
}
return -1;
@@ -2422,6 +2521,56 @@ static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h
vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : "");
}
static struct surface *surface_for_image(const struct vkp_image *img);
static void note_layer_candidate_rejected(const struct draw_list *dl, int scene_w, int scene_h) {
static int seen[32][14];
static unsigned seen_count;
static int limit_logged;
static time_t window_start;
struct timespec now_ts;
const struct vkp_draw *a = dl->n > 0 ? &dl->d[dl->n - 1] : NULL;
const struct vkp_draw *b = dl->n > 1 ? &dl->d[dl->n - 2] : NULL;
struct surface *sa = a ? surface_for_image(a->img) : NULL;
struct surface *sb = b ? surface_for_image(b->img) : NULL;
const int signature[14] = {
dl->n, scene_w, scene_h,
a ? a->dw : 0, a ? a->dh : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a ? vkp_image_is_dmabuf(a->img) : 0, a ? a->blend : 0, sa && sa->dmabuf_buf ? 1 : 0,
b ? b->dw : 0, b ? b->dh : 0, b ? vkp_image_is_dmabuf(b->img) : 0, sb && sb->dmabuf_buf ? 1 : 0
};
clock_gettime(CLOCK_MONOTONIC, &now_ts);
if (!window_start || now_ts.tv_sec - window_start >= 30) {
seen_count = 0;
limit_logged = 0;
window_start = now_ts.tv_sec;
}
for (unsigned i = 0; i < seen_count; i++)
if (!memcmp(signature, seen[i], sizeof(signature))) return;
if (seen_count >= 32) {
if (!limit_logged++) droiddeck_log("layer", "zero-copy: further fullscreen-candidate rejection details suppressed after 32 signatures in 30 seconds");
return;
}
memcpy(seen[seen_count++], signature, sizeof(signature));
char below[48];
if (b)
snprintf(below, sizeof(below), "%s %dx%d",
vkp_image_is_dmabuf(b->img) ? "DMA-BUF" : "non-DMA-BUF", b->dw, b->dh);
else
snprintf(below, sizeof(below), "none");
droiddeck_log("layer", "zero-copy: no eligible fullscreen DMA-BUF layer candidate: scene %dx%d, %d draws; "
"top draw %dx%d at %d,%d image %dx%d %s%s surface=%s dmabuf=%s; "
"draw below %s",
scene_w, scene_h, dl->n, a ? a->dw : 0, a ? a->dh : 0, a ? a->dx : 0, a ? a->dy : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a && vkp_image_is_dmabuf(a->img) ? "DMA-BUF" : "non-DMA-BUF",
a && a->blend ? " blended" : "",
sa ? "associated" : "unassociated",
sa && sa->dmabuf_buf ? "yes" : "no",
below);
}
static struct surface *surface_for_image(const struct vkp_image *img) {
struct surface *s;
wl_list_for_each(s, &g_surfaces, link)
@@ -2430,16 +2579,56 @@ static struct surface *surface_for_image(const struct vkp_image *img) {
}
static struct surface *ahb_layer_only_candidate(int scene_w, int scene_h) {
static struct {
const struct surface *surface;
int reason, scene_w, scene_h, w, h, buf_w, buf_h, x, y, src_set, dst_set, children;
} seen[32];
static unsigned seen_count;
static int limit_logged;
struct surface *s;
int w, h;
int w = 0, h = 0, reason = 0;
if (wl_list_empty(&g_toplevels)) return NULL;
s = wl_container_of(g_toplevels.prev, s, toplevel_link);
if (!s->dmabuf_buf || s->dmabuf_buf->img || !ahb_swapchain_has_ahb(s->dmabuf_buf)) return NULL;
if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) return NULL;
if (!wl_list_empty(&s->children)) return NULL;
if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) return NULL;
if (!s->dmabuf_buf) reason = 1;
else if (s->dmabuf_buf->img) reason = 2;
else if (!ahb_swapchain_has_ahb(s->dmabuf_buf)) reason = 3;
else if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) reason = 4;
else if (!wl_list_empty(&s->children)) reason = 5;
else if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) reason = 6;
surface_size(s, &w, &h);
if (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h) return NULL;
if (!reason && (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h)) reason = 7;
if (reason) {
int found = 0;
for (unsigned i = 0; i < seen_count; i++) {
if (seen[i].surface == s && seen[i].reason == reason && seen[i].scene_w == scene_w &&
seen[i].scene_h == scene_h && seen[i].w == w && seen[i].h == h &&
seen[i].buf_w == s->buf_w && seen[i].buf_h == s->buf_h && seen[i].x == s->x &&
seen[i].y == s->y && seen[i].src_set == s->src_set && seen[i].dst_set == s->dst_set &&
seen[i].children == !wl_list_empty(&s->children)) { found = 1; break; }
}
if (!found && seen_count < 32) {
seen[seen_count].surface = s; seen[seen_count].reason = reason;
seen[seen_count].scene_w = scene_w; seen[seen_count].scene_h = scene_h;
seen[seen_count].w = w; seen[seen_count].h = h; seen[seen_count].buf_w = s->buf_w; seen[seen_count].buf_h = s->buf_h;
seen[seen_count].x = s->x; seen[seen_count].y = s->y; seen[seen_count].src_set = s->src_set;
seen[seen_count].dst_set = s->dst_set; seen[seen_count].children = !wl_list_empty(&s->children);
seen_count++;
const char *why = reason == 1 ? "no DMA-BUF buffer" :
reason == 2 ? "buffer is already importable by Vulkan" :
reason == 3 ? "no registered gralloc AHardwareBuffer" :
reason == 4 ? "surface is positioned/cropped/scaled" :
reason == 5 ? "surface has child surfaces" :
reason == 6 ? "hidden shell surface" : "surface or buffer dimensions differ from scene";
char name[160]; describe(s, name, sizeof(name));
droiddeck_log("layer", "zero-copy: AHardwareBuffer-only candidate rejected: %s; %s, scene %dx%d, surface %dx%d at %d,%d, buffer %dx%d, crop=%d destination=%d children=%d",
why, name, scene_w, scene_h, w, h, s->x, s->y, s->buf_w, s->buf_h,
s->src_set, s->dst_set, !wl_list_empty(&s->children));
} else if (!found && !limit_logged) {
limit_logged = 1;
droiddeck_log("layer", "zero-copy: further AHardwareBuffer-only candidate diagnostics suppressed after 32 signatures");
}
return NULL;
}
return s;
}
@@ -2882,7 +3071,10 @@ static void render_scene(void) {
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL;
if (li < 0) ls = layer_only;
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on);
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) {
if (!cursor_on && !bfi) note_layer_candidate_rejected(&dl, w, h);
note_copy_scene(&dl, w, h, cursor_on);
}
if (cardboard) ls = NULL;
if (cursor_on) ls = NULL;
if (bfi) ls = NULL;
@@ -2910,15 +3102,30 @@ static void render_scene(void) {
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (!fg_pass && generated >= 0 && !fx_on && !framegen && r != 0) {
if (!ls || !ls->dmabuf_buf)
note_zero_copy_fallback(ls, NULL, ZERO_COPY_NO_SURFACE_BUFFER, w, h, r);
else if (!ahb_swapchain_has_ahb(ls->dmabuf_buf))
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_NO_GRALLOC_AHB, w, h, r);
else
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_AHB_PRESENT_FAILED, w, h, r);
}
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
else settle_unwaited();
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
int ov = 0, ov_done = 0;
if (!fg_pass && generated >= 0 && r != 0 && li >= 0) {
if (fx_on) {
r = sc_layer_present_pass(&dl.d[li], 1, w, h);
} else {
r = sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL,
over == 1 ? &dl.d[li + 1] : NULL, &ov);
ov_done = 1;
}
}
if (r == 0) {
if (ls) ls->drawn = 1;
int go[8], ov = 0;
if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
int go[8];
if (!ov_done && over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
if (ov <= 0) sc_layer_hide_overlay();
if (ov < 0) {
@@ -62,8 +62,40 @@ struct entry {
static struct wl_list g_entries;
static struct wl_event_loop *g_loop;
static uint64_t g_next_id = 1;
static int g_refused_logged;
static int g_ubwc_promised;
#define DISPLAY_BUFFER_MISMATCH_SIGNATURES 64u
struct display_buffer_mismatch_signature {
uint32_t kind, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct display_buffer_mismatch_signature g_mismatch_signatures[DISPLAY_BUFFER_MISMATCH_SIGNATURES];
static uint32_t g_mismatch_signature_count;
static int g_mismatch_limit_logged;
static int mismatch_should_log(const struct dmabuf_buffer *b, uint32_t kind) {
const struct display_buffer_mismatch_signature key = {
.kind = kind, .format = b->format, .stride = b->stride[0], .offset = b->offset[0],
.width = b->width, .height = b->height, .modifier = b->modifier};
for (uint32_t i = 0; i < g_mismatch_signature_count; i++) {
const struct display_buffer_mismatch_signature *seen = &g_mismatch_signatures[i];
if (seen->kind == key.kind && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_mismatch_signature_count >= DISPLAY_BUFFER_MISMATCH_SIGNATURES) {
if (!g_mismatch_limit_logged) {
g_mismatch_limit_logged = 1;
droiddeck_log("layer", "display buffers: further mismatch diagnostics suppressed after %u distinct buffer signatures",
DISPLAY_BUFFER_MISMATCH_SIGNATURES);
}
return 0;
}
g_mismatch_signatures[g_mismatch_signature_count++] = key;
return 1;
}
static int g_ubwc_probed[2];
static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) {
@@ -238,16 +270,51 @@ static void handle_alloc(struct peer *p, const struct display_buffers_request *q
} else {
if (ahb) AHardwareBuffer_release(ahb);
fd = -1;
if (sized && wanted && (compressed || !g_refused_logged)) {
g_refused_logged = 1;
droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u "
"%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at "
"%llu, %llu bytes): %s", (int)p->pid, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size,
(unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0),
(unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size),
compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path");
static struct {
pid_t pid;
uint32_t width, height, format, stride, offset, reason;
uint64_t size, modifier;
} refused[32];
static unsigned refused_count;
static int refused_limit_logged;
uint32_t reason = !sized ? 1u : !sane ? 2u : !wanted ? 3u :
!ahb_swapchain_advertised() ? 4u :
p->count >= DISPLAY_BUFFERS_MAX_PER_CLIENT ? 5u : 6u;
int seen = 0;
for (unsigned i = 0; i < refused_count; i++) {
if (refused[i].pid == p->pid && refused[i].width == q->width && refused[i].height == q->height &&
refused[i].format == q->format && refused[i].stride == q->stride && refused[i].offset == q->offset &&
refused[i].size == q->size && refused[i].modifier == q->modifier && refused[i].reason == reason) {
seen = 1;
break;
}
}
if (!seen && refused_count < 32) {
refused[refused_count].pid = p->pid;
refused[refused_count].width = q->width;
refused[refused_count].height = q->height;
refused[refused_count].format = q->format;
refused[refused_count].stride = q->stride;
refused[refused_count].offset = q->offset;
refused[refused_count].size = q->size;
refused[refused_count].modifier = q->modifier;
refused[refused_count].reason = reason;
refused_count++;
const char *why = reason == 1 ? "invalid dimensions, format, or stride" :
reason == 2 ? "size/offset/layout sanity check failed" :
reason == 3 ? "zero-copy or UBWC offering is disabled" :
reason == 4 ? "AHardwareBuffer swapchain is not advertised" :
reason == 5 ? "per-client allocation limit reached" :
"gralloc allocation/fd/size validation failed";
droiddeck_log(compressed ? "error" : "layer",
"display buffers: allocation refused for pid %d: %s; request %ux%u %c%c%c%c %s stride=%u offset=%u size=%llu modifier=0x%llx (client has %d allocations)",
(int)p->pid, why, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset,
(unsigned long long)q->size, (unsigned long long)q->modifier, p->count);
} else if (!seen && !refused_limit_logged) {
refused_limit_logged = 1;
droiddeck_log("layer", "display buffers: further allocation-refusal diagnostics suppressed after 32 signatures");
}
}
if (reply(p, &r, fd) != 0 && e) entry_free(e);
@@ -299,9 +366,18 @@ static int on_listen(int fd, uint32_t mask, void *data) {
}
void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) {
static int invalid_logged;
struct stat st;
struct entry *e;
if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return;
if (!g_loop || wl_list_empty(&g_entries)) return;
if (b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) {
if (!invalid_logged) {
invalid_logged = 1;
droiddeck_log("layer", "display buffers: cannot associate %s's DMA-BUF with gralloc (plane count %u; expected one plane at offset 0, or fstat failed)",
droiddeck_client_name(c), b->n_planes);
}
return;
}
wl_list_for_each(e, &g_entries, link) {
if (e->dev != st.st_dev || e->ino != st.st_ino) continue;
AHardwareBuffer_Desc d;
@@ -311,11 +387,27 @@ void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, stru
(uint32_t)b->height == e->height
: (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) &&
e->stride == b->stride[0];
if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height)
const uint32_t expected_format = ahb_format_of(b->format, e->modifier);
const int dimensions = b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height;
if (laid_out && e->format == expected_format && dimensions) {
ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier);
} else if (mismatch_should_log(b, 2)) {
droiddeck_log("layer", "display buffers: gralloc DMA-BUF identity matched but layout was rejected for %s: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; gralloc %ux%u stride %u format 0x%x, expected format 0x%x (layout %s, dimensions %s)",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier,
e->width, e->height, e->stride, e->format, expected_format,
laid_out ? "ok" : "mismatch", dimensions ? "ok" : "mismatch");
}
return;
}
if (mismatch_should_log(b, 1)) {
droiddeck_log("layer", "display buffers: no registered gralloc allocation matches %s's DMA-BUF identity: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; imported normally, copy path only",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier);
}
}
void display_buffers_init(struct wl_display *display) {
+58 -14
View File
@@ -187,6 +187,8 @@ struct layer {
static struct layer g_layers[SC_LAYER_COUNT];
static void apply_frame_rate(ASurfaceTransaction *tx, struct layer *l);
static void coverage_text(const struct layer *l, char *out, size_t n);
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd);
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent);
static int g_layers_ready;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_pending_cb;
@@ -721,9 +723,15 @@ static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct v
static ARect g_game_src, g_game_dst;
static int g_game_geo_known;
static void note_game_geometry(const int r[8]) {
g_game_src = (ARect){r[0], r[1], r[2], r[3]};
g_game_dst = (ARect){r[4], r[5], r[6], r[7]};
g_game_geo_known = 1;
}
static void apply_geometry(ASurfaceTransaction *tx, struct layer *l, const int r[8]) {
ARect srcR = {r[0], r[1], r[2], r[3]}, dstR = {r[4], r[5], r[6], r[7]};
if (l == &g_layers[SC_LAYER_GAME]) { g_game_src = srcR; g_game_dst = dstR; g_game_geo_known = 1; }
if (l == &g_layers[SC_LAYER_GAME]) note_game_geometry(r);
if (!l->geo_valid || memcmp(&srcR, &l->geo_src, sizeof(srcR)) || memcmp(&dstR, &l->geo_dst, sizeof(dstR))) {
api.setGeometry(tx, l->sc, &srcR, &dstR, 0 );
l->geo_src = srcR; l->geo_dst = dstR; l->geo_valid = 1;
@@ -998,19 +1006,40 @@ unavailable:
}
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color) {
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown) {
struct layer *l = layer_of(SC_LAYER_GAME);
*over_shown = 0;
if (!src || ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
int r[8];
int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r);
if (g < 0) return -1;
if (g == 0) { sc_layer_hide(); return 0; }
int og[8];
if (over && !vkp_map_draw(over, og)) over = NULL;
if (g == 0) {
sc_layer_hide();
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
struct vkp_blit blits[2] = {{.src = src, .wait_fd = -1}, {.src = over ? over->img : NULL, .wait_fd = -1}};
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &blits[0].wait_fd);
if (idx < 0) {
log_drop(l);
if (g_alloc_failed) return -1;
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
blits[0].dst = l->slots[idx].img;
struct layer *ol = layer_of(SC_LAYER_OVERLAY);
int over_idx = -1;
if (over) {
note_game_geometry(r);
const int taken = overlay_slot(ol, over->img, &over_idx, &blits[1].wait_fd);
*over_shown = taken < 0 ? -1 : 1;
if (taken > 0) blits[1].dst = ol->slots[over_idx].img;
}
if (vkp_blit_images(blits, over_idx >= 0 ? 2 : 1) != 0) return -1;
if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
if (!l->first_logged) {
@@ -1020,6 +1049,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
pool_kind(l->pool_modifier), l->pool_n);
}
vkp_signal_first_frame();
if (over_idx >= 0 && overlay_shown(ol, over_idx, og, over->blend) != 0) *over_shown = -1;
return 0;
}
@@ -1209,17 +1239,19 @@ int sc_layer_overlay_affordable(void) {
return ok;
}
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!src || !geo) return -1;
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd) {
*wait_fd = -1;
if (!src) return -1;
if (!sc_layer_overlay_affordable()) return -1;
if (ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
if (sw <= 0 || sh <= 0) return -1;
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
*idx = take_free_slot(l, sw, sh, AHB_RGBA8, wait_fd);
if (*idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
return 1;
}
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent) {
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
l->first_logged = 1;
@@ -1228,6 +1260,18 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
return 0;
}
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!geo) return -1;
int idx;
struct vkp_blit blit = {.src = src, .wait_fd = -1};
const int taken = overlay_slot(l, src, &idx, &blit.wait_fd);
if (taken <= 0) return taken;
blit.dst = l->slots[idx].img;
if (vkp_blit_images(&blit, 1) != 0) return -1;
return overlay_shown(l, idx, geo, translucent);
}
static int hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return 0;
ASurfaceTransaction *tx = api.txCreate();
+1 -1
View File
@@ -22,7 +22,7 @@ void sc_layer_hdr_symbols(char *out, size_t size);
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color);
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown);
int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h);
int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf,
+62 -27
View File
@@ -20,6 +20,8 @@
#include <unistd.h>
#include <errno.h>
#include <poll.h>
#include <linux/sync_file.h>
#include <sys/ioctl.h>
#include <time.h>
#include <pthread.h>
#include <stdarg.h>
@@ -3162,8 +3164,38 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la
0, 0, NULL, 0, NULL, 1, &release);
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) {
static int merge_wait_fds(int a, int b) {
if (a < 0) return b;
if (b < 0) return a;
struct sync_merge_data m = {.name = "droiddeck-layer-copy", .fd2 = b};
if (ioctl(a, SYNC_IOC_MERGE, &m) == 0) {
close(a);
close(b);
return m.fence;
}
struct pollfd p = {.fd = b, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(b);
if (r != 0) return a;
p.fd = a;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(a);
return -2;
}
int vkp_blit_images(const struct vkp_blit *blits, int n) {
int wait_fd = -1;
for (int i = 0; i < n; i++) {
if (wait_fd == -2) { if (blits[i].wait_fd >= 0) close(blits[i].wait_fd); continue; }
wait_fd = merge_wait_fds(wait_fd, blits[i].wait_fd);
}
int valid = n > 0 && wait_fd != -2;
for (int i = 0; valid && i < n; i++) {
const struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
if (!src || src->blit_dst || !dst || !dst->blit_dst) valid = 0;
}
if (!valid || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -3176,32 +3208,35 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
for (int i = 0; i < n; i++) {
struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -105,7 +105,11 @@ int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n
int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh);
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
struct vkp_blit {
struct vkp_image *src, *dst;
int wait_fd;
};
int vkp_blit_images(const struct vkp_blit *blits, int n);
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
int vkp_update_map(int scene_w, int scene_h);
int vkp_map_draw(const struct vkp_draw *d, int out[8]);
@@ -20,6 +20,10 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
if (android.os.Build.VERSION.SDK_INT >= 28 &&
com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return
if (android.os.Build.VERSION.SDK_INT >= 28 && Application.getProcessName() == packageName)
com.droiddeck.launcher.runtime.GuestWorkers.attach(this)
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
@@ -192,6 +192,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
@@ -3049,7 +3050,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3066,6 +3067,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
@@ -3384,6 +3386,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
@@ -1951,7 +1951,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
SessionPrefs.setOrientation(this@SessionActivity, value)
when (SessionState.mode) {
SessionService.MODE_STEAM, SessionService.MODE_RUN ->
SessionPrefs.setOrientation(this@SessionActivity, "steam", value)
SessionService.MODE_DESKTOP ->
SessionPrefs.setOrientation(this@SessionActivity, "desktop", value)
else -> SessionPrefs.setOrientation(this@SessionActivity, value)
}
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
@@ -2730,7 +2736,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this)
sessionOrientation = SessionPrefs.orientation(this, SessionState.mode)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
@@ -3062,7 +3068,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this, SessionState.mode)
private fun applyFollowChoice() {
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
@@ -3071,7 +3077,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp, SessionState.mode)
if (requestedOrientation != wanted) requestedOrientation = wanted
}
@@ -3134,13 +3140,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this, SessionState.mode) && !controlsBelowWanted()
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), portraitOutput())
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this, SessionState.mode)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
@@ -89,7 +89,7 @@ public class DirectAudioRelayComponent extends SessionPart {
}
}
final java.io.PrintWriter log = out;
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
pid = HostProcess.startUncounted(command.toString(), env.toArray(new String[0]),
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
@@ -186,13 +186,16 @@ public class PulseAudioComponent extends SessionPart {
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
// The daemon closes every fd at start but this one; in a worker process it is the binder
// fd whose closing Android takes for the process's death.
env.add("PULSE_PASSED_FD=" + com.droiddeck.launcher.runtime.GuestWorker.BINDER_FD_TOKEN);
String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so"))
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
start(generation);
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.core
import android.os.ParcelFileDescriptor
import android.util.Log
import java.io.File
import java.util.function.Consumer
@@ -7,6 +8,9 @@ import java.util.function.Consumer
object HostProcess {
private const val TAG = "HostProcess"
private const val LINKER = "/system/bin/linker64"
// sh -c WORKER_CD sh DIR NAME=VALUE... -- PROGRAM ARGS...
private const val WORKER_CD = "cd \"\$1\" || exit 126; shift; " +
"while [ \$# -gt 0 ] && [ \"\$1\" != -- ]; do export \"\$1\"; shift; done; shift; exec \"\$@\""
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
@JvmStatic
@@ -65,6 +69,77 @@ object HostProcess {
}
}
/**
* As [start], but the program runs as the main process of one of the app's worker processes,
* which Android does not count against the app's child processes (docs/phantom-processes.md).
* Falls back to [start] when no worker is available. The exit status is the program's exit
* code, or 128 plus the signal that ended it, as Process.waitFor() reports it.
*/
@JvmStatic
@JvmOverloads
fun startUncounted(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?,
outputFile: File? = null, onOutputComplete: Runnable? = null): Int {
val context = com.droiddeck.launcher.runtime.GuestWorkers.context
val argv = split(command)
// 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())
env?.forEach { line ->
val eq = line.indexOf('=')
if (eq > 0) environment[line.substring(0, eq)] = line.substring(eq + 1)
}
val assignments = environment.map { (k, v) -> "$k=$v" }
// A worker cannot chdir before its exec, so Android's shell does it. The shell starts with an
// environment of its own (the program's LD_PRELOAD of glibc libraries would stop it loading)
// and exports the program's before the exec.
val launch = if (dir != null) {
listOf("/system/bin/sh", "-c", WORKER_CD, "sh", dir.path) + assignments + listOf("--") + argv
} else argv
val workerEnv = if (dir != null) listOf("PATH=/system/bin") else assignments
var input: ParcelFileDescriptor? = null
var reader: ParcelFileDescriptor? = null
var output: ParcelFileDescriptor? = null
val pid = try {
input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY)
output = when {
onLine != null -> ParcelFileDescriptor.createPipe().let { reader = it[0]; it[1] }
outputFile != null -> ParcelFileDescriptor.open(outputFile,
ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND)
else -> ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_WRITE_ONLY)
}
com.droiddeck.launcher.runtime.GuestWorkers.start(context, launch, workerEnv, listOf(input, output, output)) { status ->
onExit?.accept(if (status < 0) -1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f))
}
} catch (e: Exception) {
Log.w(TAG, "no worker for ${argv.first()}", e)
-1
} finally {
runCatching { input?.close() }
runCatching { output?.close() }
}
if (pid <= 0) {
reader?.close()
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
Log.i(TAG, "started pid $pid outside the child-process count: ${argv.first()} (${argv.size - 1} arguments)")
reader?.let { pipe ->
Thread({
try {
ParcelFileDescriptor.AutoCloseInputStream(pipe).bufferedReader().useLines { lines ->
lines.forEach { onLine?.accept(it) }
}
} catch (e: Exception) {
} finally {
onOutputComplete?.run()
}
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
}
return pid
}
@JvmStatic
fun pidOf(process: Process): Int = try {
val field = process.javaClass.getDeclaredField("pid")
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.R
enum class PhantomProcessStatus {
NOT_APPLICABLE,
/** The limit is on, but the session keeps its programs out of Android's count (GuestWorkers). */
UNCOUNTED,
DISABLED,
ENABLED,
UNSET,
@@ -57,6 +59,12 @@ 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.limitHandled(context))
PhantomProcessStatus.UNCOUNTED else status
}
private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
val global = try {
@@ -101,7 +109,8 @@ object PhantomProcessLimit {
fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED &&
status != PhantomProcessStatus.UNCOUNTED
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
@@ -109,6 +118,7 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required
PhantomProcessStatus.UNCOUNTED -> R.string.phantom_title_uncounted
})
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -116,6 +126,7 @@ object PhantomProcessLimit {
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
PhantomProcessStatus.UNCOUNTED -> context.getString(R.string.phantom_instructions_uncounted)
}
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -132,5 +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 (most of the session's programs run in uncounted worker processes)"
}
}
@@ -28,17 +28,18 @@ object SessionLogCapture {
out.flush()
writer = out
this.target = target
pid = HostProcess.start(
pid = HostProcess.startUncounted(
command(Process.myPid(), sinceMillis),
null, target.parentFile, null,
) { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
onLine = { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
}
}
}
}
},
)
if (pid == -1) {
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
out.flush()
@@ -243,7 +243,7 @@ object Library {
if (runCatching { SteamGrid.sync(context, targets) }.getOrDefault(false)) steam = steamGames(context, strictRead, arch)
val claimed = claimedFolders(steam)
val own = list.filter { g ->
g.steamAppId != null || !g.steamProgram || claimed.isEmpty() ||
g.steamAppId != null || claimed.isEmpty() ||
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
}
@@ -38,6 +38,11 @@ object ElfSeccompPatch {
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
var pos = start
while (pos + 4 <= end) {
if (patchTermiosRequest(buffer, pos, end)) {
patched++
pos += 4
continue
}
val replacement = when (buffer.getInt(pos)) {
MOV_X8_SET_ROBUST_LIST -> NOP
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
@@ -65,6 +70,40 @@ object ElfSeccompPatch {
return patched
}
/**
* glibc 2.42 and later read and set a terminal with TCGETS2 and TCSETS2/W2/F2, which Android's
* SELinux policy refuses on an app's pseudo-terminal slaves (EACCES): isatty() was false in every
* Konsole, ssh and tmux session, so bash had no prompt or job control and stdout was not line
* buffered. TCGETS and TCSETS* carry the same struct without its two speed fields, which glibc
* then takes from c_cflag. A site is `movz xN, #lo` then `movk xN, #hi, lsl #16`; the movz gets
* the old request and the movk becomes a no-op.
*/
private fun patchTermiosRequest(buffer: ByteBuffer, pos: Int, end: Int): Boolean {
val movz = buffer.getInt(pos)
if ((movz and 0x7fe00000) != 0x52800000) return false
val low = (movz ushr 5) and 0xffff
if (low !in 0x542a..0x542d) return false
val register = movz and 0x1f
var next = pos + 4
while (next < minOf(end, pos + 4 + 4 * 4)) {
val movk = buffer.getInt(next)
if ((movk and 0x7fe00000) == 0x72a00000 && (movk and 0x1f) == register) {
val request = when ((movk ushr 5) and 0xffff) {
0x802c -> if (low == 0x542a) 0x5401 else return false
0x402c -> if (low != 0x542a) 0x5402 + (low - 0x542b) else return false
else -> return false
}
buffer.putInt(pos, (movz and 0x1f.inv() and (0xffff shl 5).inv()) or (request shl 5) or register)
buffer.putInt(next, NOP)
return true
}
// Anything between that might read or write the register would see the old low half
if (intArrayOf(0, 5, 10, 16).any { (movk ushr it) and 0x1f == register }) return false
next += 4
}
return false
}
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
fun patchFile(path: File): Int {
val target = path.canonicalFile
@@ -0,0 +1,894 @@
package com.droiddeck.launcher.runtime
import android.app.ActivityManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Parcel
import android.os.ParcelFileDescriptor
import android.os.Process
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import android.system.StructPollfd
import android.util.Log
import org.json.JSONObject
import java.io.DataInputStream
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* A guest program run as the main process of its own Android process.
*
* Android counts the processes in an app process's cgroup against its child-process limit, but not
* the app processes themselves. The worker execs the program in place; its binder fd stays open
* across the exec, so the system keeps the process as a live service process. The program's own
* children are still counted. See docs/phantom-processes.md.
*/
open class GuestWorker : Service() {
private val binder = object : Binder() {
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (code != RUN) return super.onTransact(code, data, reply, flags)
val argv = data.createStringArray() ?: return false
val env = data.createStringArray() ?: return false
val fds = List(data.readInt()) { data.readFileDescriptor() }
val targets = data.createIntArray() ?: IntArray(fds.size) { it }
val fillBinderFd = data.readInt() != 0
val go = data.readFileDescriptor()
val nice = data.readInt()
reply?.writeInt(Process.myPid())
Handler(Looper.getMainLooper()).post {
// 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.
var why = ""
// 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(timeout: Int): Int {
val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() }
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.
// 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, nice)
else {
Log.w(TAG, "launch not committed ($why): not running ${argv.firstOrNull()}")
Process.killProcess(Process.myPid())
}
}
return true
}
}
override fun onBind(intent: Intent): IBinder = binder
private fun exec(argv: Array<String>, env: Array<String>, fds: List<ParcelFileDescriptor?>, targets: IntArray, fillBinderFd: Boolean,
nice: Int) {
try {
val top = targets.maxOrNull() ?: 2
val (binderTop, binderFd) = keepBinderOpen(maxOf(BINDER_FDS, top + 1))
// Out of the way first, so that placing one fd cannot overwrite another not yet placed.
val above = maxOf(MOVED_FDS, top + 1, binderTop + 1)
val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, above) } }
moved.forEachIndexed { i, fd ->
if (fd == null || i >= targets.size) return@forEachIndexed
val source = ParcelFileDescriptor.adoptFd(fd).also { kept.add(it) }.fileDescriptor
Os.dup2(source, targets[i])
Os.fcntlInt(source, OsConstants.F_SETFD, OsConstants.FD_CLOEXEC)
}
// 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). 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")
// Android raised this thread to THREAD_PRIORITY_TOP_APP_BOOST (a service the top app binds with
// BIND_IMPORTANT is scheduled as the top app); the program and its threads would keep it and
// run ahead of the game. They get the asker's priority instead, as a forked child would.
runCatching { Process.setThreadPriority(nice) }
Os.execve(argv[0], argv.map(fill).toTypedArray(),
env.filterNot { it.startsWith("DDH_WORKER_PID=") }.map(fill).toTypedArray() + mask +
"DDH_WORKER_PID=${Process.myPid()}")
} catch (e: ErrnoException) {
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
}
Process.killProcess(Process.myPid())
}
/**
* Binder fds stay open across the exec, at [from] or above, where no fd of the program goes.
* Returns the highest fd used and the one on /dev/binder, whose closing Android takes for
* the death of this process.
*/
private fun keepBinderOpen(from: Int): Pair<Int, Int> {
var highest = from - 1
var binder = -1
File("/proc/self/fd").listFiles()?.forEach { link ->
val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
if (target !in BINDER_DEVICES && !target.startsWith("/dev/binderfs/")) return@forEach
// A copy, not adoptFd(): some of these fds are owned (fdsan) by a ParcelFileDescriptor.
val copy = runCatching { ParcelFileDescriptor.fromFd(link.name.toIntOrNull() ?: return@forEach) }.getOrNull()
?: return@forEach
val kept = Os.fcntlInt(copy.fileDescriptor, OsConstants.F_DUPFD, from)
highest = maxOf(highest, kept)
if (target.substringAfterLast('/') == "binder") binder = kept
copy.close()
}
return highest to binder
}
companion object {
const val RUN = IBinder.FIRST_CALL_TRANSACTION
/** 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@"
// Longer than the app may wait for the hook's "go" (GuestWorkers.ACK_TIMEOUT_MS) before it commits
private const val GO_TIMEOUT_MS = 15000
private val BINDER_DEVICES = setOf("/dev/binder", "/dev/hwbinder", "/dev/vndbinder")
private const val BINDER_FDS = 900
private const val MOVED_FDS = 1200
private const val TAG = "GuestWorker"
private val kept = ArrayList<ParcelFileDescriptor>()
fun isWorkerProcess(context: Context, process: String?): Boolean =
process != null && process.startsWith(context.packageName + ":g") &&
process.substring(context.packageName.length + 2).all { it.isDigit() }
}
}
class GuestWorker0 : GuestWorker()
class GuestWorker1 : GuestWorker()
class GuestWorker2 : GuestWorker()
class GuestWorker3 : GuestWorker()
class GuestWorker4 : GuestWorker()
class GuestWorker5 : GuestWorker()
class GuestWorker6 : GuestWorker()
class GuestWorker7 : GuestWorker()
class GuestWorker8 : GuestWorker()
class GuestWorker9 : GuestWorker()
class GuestWorker10 : GuestWorker()
class GuestWorker11 : GuestWorker()
class GuestWorker12 : GuestWorker()
class GuestWorker13 : GuestWorker()
class GuestWorker14 : GuestWorker()
class GuestWorker15 : GuestWorker()
class GuestWorker16 : GuestWorker()
class GuestWorker17 : GuestWorker()
class GuestWorker18 : GuestWorker()
class GuestWorker19 : GuestWorker()
class GuestWorker20 : GuestWorker()
class GuestWorker21 : GuestWorker()
class GuestWorker22 : GuestWorker()
class GuestWorker23 : GuestWorker()
class GuestWorker24 : GuestWorker()
class GuestWorker25 : GuestWorker()
class GuestWorker26 : GuestWorker()
class GuestWorker27 : GuestWorker()
class GuestWorker28 : GuestWorker()
class GuestWorker29 : GuestWorker()
class GuestWorker30 : GuestWorker()
class GuestWorker31 : GuestWorker()
class GuestWorker32 : GuestWorker()
class GuestWorker33 : GuestWorker()
class GuestWorker34 : GuestWorker()
class GuestWorker35 : GuestWorker()
class GuestWorker36 : GuestWorker()
class GuestWorker37 : GuestWorker()
class GuestWorker38 : GuestWorker()
class GuestWorker39 : GuestWorker()
class GuestWorker40 : GuestWorker()
class GuestWorker41 : GuestWorker()
class GuestWorker42 : GuestWorker()
class GuestWorker43 : GuestWorker()
class GuestWorker44 : GuestWorker()
class GuestWorker45 : GuestWorker()
class GuestWorker46 : GuestWorker()
class GuestWorker47 : GuestWorker()
class GuestWorker48 : GuestWorker()
class GuestWorker49 : GuestWorker()
class GuestWorker50 : GuestWorker()
class GuestWorker51 : GuestWorker()
class GuestWorker52 : GuestWorker()
class GuestWorker53 : GuestWorker()
class GuestWorker54 : GuestWorker()
class GuestWorker55 : GuestWorker()
class GuestWorker56 : GuestWorker()
class GuestWorker57 : GuestWorker()
class GuestWorker58 : GuestWorker()
class GuestWorker59 : GuestWorker()
class GuestWorker60 : GuestWorker()
class GuestWorker61 : GuestWorker()
class GuestWorker62 : GuestWorker()
class GuestWorker63 : GuestWorker()
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
object GuestWorkers {
private const val TAG = "GuestWorkers"
private val classes: List<Class<out GuestWorker>> = listOf(
GuestWorker0::class.java, GuestWorker1::class.java, GuestWorker2::class.java,
GuestWorker3::class.java, GuestWorker4::class.java, GuestWorker5::class.java,
GuestWorker6::class.java, GuestWorker7::class.java, GuestWorker8::class.java,
GuestWorker9::class.java, GuestWorker10::class.java, GuestWorker11::class.java,
GuestWorker12::class.java, GuestWorker13::class.java, GuestWorker14::class.java,
GuestWorker15::class.java, GuestWorker16::class.java, GuestWorker17::class.java,
GuestWorker18::class.java, GuestWorker19::class.java, GuestWorker20::class.java,
GuestWorker21::class.java, GuestWorker22::class.java, GuestWorker23::class.java,
GuestWorker24::class.java, GuestWorker25::class.java, GuestWorker26::class.java,
GuestWorker27::class.java, GuestWorker28::class.java, GuestWorker29::class.java,
GuestWorker30::class.java, GuestWorker31::class.java, GuestWorker32::class.java,
GuestWorker33::class.java, GuestWorker34::class.java, GuestWorker35::class.java,
GuestWorker36::class.java, GuestWorker37::class.java, GuestWorker38::class.java,
GuestWorker39::class.java, GuestWorker40::class.java, GuestWorker41::class.java,
GuestWorker42::class.java, GuestWorker43::class.java, GuestWorker44::class.java,
GuestWorker45::class.java, GuestWorker46::class.java, GuestWorker47::class.java,
GuestWorker48::class.java, GuestWorker49::class.java, GuestWorker50::class.java,
GuestWorker51::class.java, GuestWorker52::class.java, GuestWorker53::class.java,
GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java,
GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java,
GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java,
GuestWorker63::class.java,
)
private class Slot(val index: Int) {
lateinit var connection: ServiceConnection
val connected = CountDownLatch(1)
@Volatile var service: IBinder? = null
@Volatile var pid = -1
@Volatile var guest = false
/** The session it runs a program for ([serve]'s number). */
@Volatile var session = 0
@Volatile var onExit: ((Int) -> Unit)? = null
/** The priority it runs its program at: the asker's (a guest, or the app thread that started it). */
@Volatile var nice = 0
/** 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<Slot>(classes.size)
// Workers bound ahead of need while a session runs: a zygote fork and the bind take about
// 60-100 ms, which every program the session starts would otherwise wait for.
private val warm = ArrayDeque<Slot>()
@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
// Held for a launch's last word and for marking a session stopped
private val authorizing = Any()
private val warming = java.util.concurrent.atomic.AtomicBoolean(false)
private const val WARM_WORKERS = 2
// A game's start hands off a burst of programs (Wine's services, the agent's checks) within a few
// seconds: bound ahead while the client starts it, not forked while the game draws its first frames.
private const val LAUNCH_WORKERS = 16
private const val LAUNCH_MS = 20_000L
@Volatile private var launchUntil = 0L
private val launches = java.util.concurrent.atomic.AtomicInteger()
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
// Android sets a worker's main thread to THREAD_PRIORITY_TOP_APP_BOOST again each time the app returns to the top
private const val TOP_APP_BOOST = -10
private const val PRIORITY_CHECK_MS = 2000L
@Volatile private var keeper: Thread? = null
/** The app, once [attach] or [serve] ran in its main process; null before. */
@Volatile var context: Context? = null
private set
/** Whether the session runs its programs in workers: the native userland, and not turned off. */
fun enabled(context: Context): Boolean =
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()
/**
* Runs [argv] (a host command line) as the main process of a free worker with [env] and the
* fds in [stdio] as its 0, 1 and 2. Returns its pid, or -1. Blocks: not for the main thread.
* [onExit] runs once the process is gone.
*/
fun start(context: Context, argv: List<String>, env: List<String>, stdio: List<ParcelFileDescriptor>, onExit: (Int) -> Unit): Int =
start(context, argv, env, stdio, IntArray(stdio.size) { it }, onExit)
/** As [start], with the fds in [fds] placed at the numbers in [targets]. */
fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, 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.
* [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.
* [owner]: the session asking (the one a guest's request names), else the latest.
*/
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 },
confirmed: () -> Boolean = { true }, owner: Int = session,
nice: Int = Process.getThreadPriority(Process.myTid())): Int {
val app = context.applicationContext
if (guest && owner <= stopped) {
Log.w(TAG, (if (owner == 0) "a request naming no session" else "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 {
Log.w(TAG, "no worker started for ${argv.firstOrNull()}")
return -1
}
slot.guest = guest
slot.session = owner
slot.onExit = onExit
slot.nice = nice
// during a game's start the pool drains instead: its refill would fork while the game starts
if (android.os.SystemClock.elapsedRealtime() >= launchUntil) refill(app)
// The worker execs once a byte comes through this socket: 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).
// It answers with a byte of its own: without that it gave up waiting, and nothing runs.
var go: Array<ParcelFileDescriptor>? = null
var data: Parcel? = Parcel.obtain()
val reply = Parcel.obtain()
try {
go = ParcelFileDescriptor.createSocketPair()
data!!.writeStringArray(argv.toTypedArray())
data.writeStringArray(env.toTypedArray())
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)
data.writeInt(nice)
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
// 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
// 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
}
// 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.launching = true } }
}
if (!live) {
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)
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. [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).
// The word and a teardown's start exclude each other: a launch is authorized before stopGuests()
// marks the session stopped, and is then stopped with the pids it takes (guestPids lists a
// launching slot), or never.
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
val accepted = answered && synchronized(authorizing) {
!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")
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()
reply.recycle()
go?.forEach { runCatching { it.close() } }
}
Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
return slot.pid
}
/** Binds a free worker; its [Slot.connected] opens once it is up. Null when all are in use. */
private fun bind(app: Context): Slot? {
val slot = synchronized(slots) {
val index = slots.indexOfFirst { it == null }
if (index < 0) {
Log.w(TAG, "all ${slots.size} workers are busy")
return null
}
Slot(index).also { slots[index] = it }
}
slot.connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
slot.service = binder
slot.connected.countDown()
}
override fun onServiceDisconnected(name: ComponentName) = release(app, slot)
override fun onBindingDied(name: ComponentName) = release(app, slot)
}
// 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.
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
}
return slot
}
private fun takeWarm(): Slot? = synchronized(slots) {
while (warm.isNotEmpty()) {
val slot = warm.removeFirst()
if (slots[slot.index] === slot && slot.service?.isBinderAlive == true) return slot
}
null
}
/** Brings the warm workers back up to [warmTarget], one at a time, off the caller's thread. */
private fun refill(app: Context) {
if (warmTarget == 0 || !warming.compareAndSet(false, true)) return
Thread({
try {
while (true) {
val missing = warmTarget - synchronized(slots) { warm.size }
if (missing <= 0) break
// all at once: the zygote forks them in parallel
val fresh = (1..missing).mapNotNull { bind(app) }
if (fresh.isEmpty()) break
for (slot in fresh) {
if (!slot.connected.await(10, TimeUnit.SECONDS)) {
release(app, slot)
continue
}
// 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 {
warming.set(false)
}
}, "guest-worker-warm").apply { isDaemon = true; start() }
}
/** A game is about to start: [LAUNCH_WORKERS] bound ahead, back to [WARM_WORKERS] once it is up. */
fun expectLaunch(context: Context) {
val app = context.applicationContext
val raised = synchronized(slots) { (warmTarget > 0).also { if (it) warmTarget = LAUNCH_WORKERS } }
if (!raised) return
launchUntil = android.os.SystemClock.elapsedRealtime() + LAUNCH_MS
val launch = launches.incrementAndGet()
refill(app)
Thread({
try {
Thread.sleep(LAUNCH_MS)
} catch (_: InterruptedException) {
return@Thread
}
if (launches.get() != launch) return@Thread
val extra = synchronized(slots) {
if (warmTarget != LAUNCH_WORKERS) emptyList()
else {
warmTarget = WARM_WORKERS
List((warm.size - WARM_WORKERS).coerceAtLeast(0)) { warm.removeLast() }
}
}
extra.forEach { release(app, it) }
refill(app)
}, "guest-worker-launch").apply { isDaemon = true; start() }
}
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) }
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. */
private fun exitStatus(app: Context, pid: Int): Int {
if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1
val am = app.getSystemService(ActivityManager::class.java)
var recorded = false
repeat(20) {
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let {
recorded = true
// an exit code only when the process exited itself; a signal number otherwise (a native crash)
if (it.reason == android.app.ApplicationExitInfo.REASON_EXIT_SELF) return (it.status and 0xff) shl 8
if (it.status in 1..64) return it.status and 0x7f
// Android records the death first and the zygote's status later (as UNKNOWN, 0, then
// EXIT_SELF): a reason without a status may still be completed
if (it.reason != android.app.ApplicationExitInfo.REASON_UNKNOWN) return OsConstants.SIGKILL
}
Thread.sleep(50)
}
// killed by Android with no signal recorded, not a clean exit
return if (recorded) OsConstants.SIGKILL else -1
}
/** The pids of session [of]'s guest programs running in workers. */
fun guestPids(of: Int = session): List<Int> =
synchronized(slots) { slots.mapNotNull { s -> s?.takeIf { it.guest && it.session == of }?.pid?.takeIf { it > 0 } } }
/** Ends session [of]'s guest programs that are still running, and, for the latest session, the warm workers. */
fun stopGuests(of: Int = session) {
// the check and the reset together: a new session's serve() may be under way
val drained = synchronized(authorizing) {
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) } }
val pids = guestPids(of)
if (pids.isEmpty()) return
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
Thread.sleep(500)
pids.forEach { Process.killProcess(it) }
}
/** Listens for `droiddeck-spawn` requests from the session's guests. */
fun attach(context: Context) {
this.context = context.applicationContext
}
/** Puts a running program's main thread back to its asker's priority after Android boosted it (once started, never stops). */
private fun keepPriorities() {
synchronized(this) {
if (keeper != null) return
keeper = Thread({
while (true) {
try {
Thread.sleep(PRIORITY_CHECK_MS)
} catch (_: InterruptedException) {
return@Thread
}
val running = synchronized(slots) {
slots.filterNotNull().filter { it.started && it.pid > 0 && it.nice != TOP_APP_BOOST }
}
for (s in running) runCatching {
if (Process.getThreadPriority(s.pid) == TOP_APP_BOOST) Process.setThreadPriority(s.pid, s.nice)
}
}
}, "guest-worker-priority").apply { isDaemon = true; start() }
}
}
/** Starts a session's use of the workers (and the spawn socket, once); returns its number. */
fun serve(context: Context): Int {
val app = context.applicationContext
this.context = app
val number = synchronized(slots) { warmTarget = WARM_WORKERS; ++session }
refill(app)
keepPriorities()
synchronized(this) {
if (server != null) return number
server = Thread({
val socket = try {
LocalServerSocket(socketName(app))
} catch (e: Exception) {
Log.e(TAG, "no spawn socket", e)
synchronized(this) { server = null }
return@Thread
}
while (true) {
val client = runCatching { socket.accept() }.getOrNull()
if (client == null) {
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) { receiving.decrementAndGet() }
} catch (e: Throwable) {
Log.w(TAG, "spawn request failed", e)
}
}, "guest-spawn").start()
}
}, "guest-spawn-server").apply { isDaemon = true; start() }
}
return number
}
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
// The whole request and its fds within this, however slowly they come (the wait for a
// program's exit is not): each read gets what is left of it
val deadline = android.os.SystemClock.elapsedRealtime() + RECEIVE_TIMEOUT_MS
fun left() {
val ms = deadline - android.os.SystemClock.elapsedRealtime()
if (ms <= 0) throw java.net.SocketTimeoutException("spawn request not received in time")
client.soTimeout = ms.toInt()
}
val input = DataInputStream(client.inputStream)
val fds = ArrayList<ParcelFileDescriptor>()
fun take() {
val received = client.ancillaryFileDescriptors.orEmpty()
try {
received.forEach { fds.add(ParcelFileDescriptor.dup(it)) }
} finally {
received.forEach { runCatching { Os.close(it) } }
}
}
// fds can come with any read, the request's own bytes too: each read's are taken at once
fun fill(bytes: ByteArray) {
var got = 0
while (got < bytes.size) {
left()
val n = input.read(bytes, got, bytes.size - got)
take()
if (n < 0) throw java.io.EOFException("spawn request ended at $got of ${bytes.size} bytes")
got += n
}
}
// Until start() has them: closed on every way out before that, from the first byte on
var handedOver = false
try {
val length = ByteArray(4).also { fill(it) }.let { java.nio.ByteBuffer.wrap(it).int }
if (length !in 1..MAX_REQUEST_BYTES) {
Log.w(TAG, "spawn request of $length bytes refused")
return
}
val payload = ByteArray(length).also { fill(it) }
val request = JSONObject(String(payload))
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)
while (fds.size < total) {
left()
if (input.read() < 0) throw java.io.EOFException("fds ended at ${fds.size} of $total")
take()
}
} else {
take()
}
received()
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) } }
request.optJSONArray("envlist")?.let { a ->
for (i in 0 until a.length()) a.getString(i).split('=', limit = 2).let { if (it.size == 2) env[it[0]] = it[1] }
}
// What the hook told the program that asked (it may run in a worker itself) is not this one's
env.keys.removeAll { it.startsWith("DDH_") }
val cwd = request.optString("cwd", "/")
val wait = request.optBoolean("wait", false)
// A path without a slash names a file in the cwd, as execve() takes it, not one on PATH
val file = request.optString("file", "").let { if (it.isNotEmpty() && '/' !in it) "./$it" else it }
// The handoff table (the hook's) comes last among the fds; the rest go to these numbers.
val tableIndex = request.optInt("table", -1)
val numbers = request.optJSONArray("fds")?.let { a -> IntArray(a.length()) { a.getInt(it) } } ?: IntArray(3) { it }
val table = fds.getOrNull(tableIndex)?.takeIf { pfd ->
runCatching { Os.readlink("/proc/self/fd/${pfd.fd}") }.getOrNull()?.contains("ddnatv-handoff") == true
}
val slot = request.optInt("slot", -1)
val parent = request.optInt("parent", -1)
var programFds = fds.filterIndexed { i, _ -> i != tableIndex }
var targets = numbers
if (table != null && slot >= 0) {
// The program reports its own exit status into the table (hook/handoff.c)
val tableFd = (numbers.maxOrNull() ?: 2) + 1
programFds = programFds + table
targets = numbers + tableFd
env["DDH_TABLE"] = "$tableFd:$slot:$parent:${request.optInt("child", -1)}"
}
val root = env["DDNATV_ROOT"]?.let(::File)
val out = client.outputStream
if (root == null || argv.isEmpty()) {
out.write("error no guest root or program\n".toByteArray())
return
}
val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile }
val args = if (file.isNotEmpty()) {
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", "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
// The hook restores these in the program (tools/nativeguest/hook/handoff.c).
if (request.has("sigign")) env["DDH_SIGIGN"] = request.getLong("sigign").toString()
if (request.has("nofile")) {
env["DDH_NOFILE"] = request.getLong("nofile").toString() +
(if (request.has("nofilemax")) ":" + request.getLong("nofilemax") else "")
}
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()
// 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
// 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
// the hook's last word, sent once the worker has taken the program on and before it runs it
var confirmedToHook = false
// The session whose guest asks, not the latest: a new session can start (serve()) while an
// older one's guests are still sending, and that older one's teardown must find its programs.
// A request that names none is refused (start() runs nothing for session 0): the hook and
// droiddeck-spawn always name it, and which session's it is cannot be told otherwise.
val owner = request.optInt("session", 0).coerceAtLeast(0)
// The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit
val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT)
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code ->
status = code
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
exited.countDown()
}, confirmed = {
!ack || runCatching {
out.write("ok\n".toByteArray())
out.flush()
confirmedToHook = true
}.isSuccess
}, commit = { started ->
worker = started
if (!ack) return@start true
runCatching {
out.write("pid $started\n".toByteArray())
out.flush()
answered = true
client.soTimeout = ACK_TIMEOUT_MS
// the whole line: a hook whose write stopped short treats it as failed and runs the program itself
val line = StringBuilder()
var ended = false
while (!ended) {
val c = input.read()
if (c < 0) break
if (c == '\n'.code) ended = true else line.append(c.toChar())
}
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 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()
// droiddeck-spawn exits with this: an exit code, or 128 plus the signal
val code = if (status < 0) 1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f)
out.write("exit $code\n".toByteArray())
out.flush()
}
} finally {
if (!handedOver) fds.forEach { runCatching { it.close() } }
}
}
}
// Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 64-byte
// entries of int32 child, real, parent, state, ..., and at 32 the app's report: int32 status, child.
// The report is one 8-byte write tagged with the child it is for; only the hook changes an
// entry's state, so a report that lands after the entry went to another child is ignored there.
private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int, child: Int, worker: Int) {
runCatching {
val entry = 64L + slot * 64L
val head = java.nio.ByteBuffer.allocate(16).order(java.nio.ByteOrder.nativeOrder())
Os.pread(table.fileDescriptor, head, entry)
val real = head.getInt(4)
val state = head.getInt(12)
// Also while the hook holds the entry (TAKEN) or has already guessed its end (EXITED):
// the report is for this child only, and wins over the timeout's guess (ddh_status)
if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || state !in 1..4)
return@runCatching
// An exit Android has no record of is reported as a failure, not as a signal.
val report = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.nativeOrder())
.putInt(0, if (status < 0) 1 shl 8 else status).putInt(4, child)
Os.pwrite(table.fileDescriptor, report, entry + 32)
if (parent > 0) Process.sendSignal(parent, OsConstants.SIGCHLD)
}.onFailure { Log.w(TAG, "could not report an exit to the guest's parent", it) }
runCatching { table.close() }
}
}
@@ -130,6 +130,8 @@ object SessionFiles {
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
@@ -154,6 +156,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
@@ -358,6 +361,7 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeSessionBusPolicy(etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
@@ -880,6 +884,24 @@ object SessionFiles {
}
}
/**
* A session bus admits only its owner, and with droiddeck-user (the native hook's ordinary
* user) a root process and a user's share the bus while the kernel sees one Android uid.
*/
private fun writeSessionBusPolicy(etc: File) {
val xml = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy context="default">
<allow user="*"/>
</policy>
</busconfig>
"""
val conf = File(etc, "dbus-1/session.d/droiddeck-users.conf")
conf.parentFile?.mkdirs()
if (!FileUtils.writeString(conf, xml)) Log.e(TAG, "could not write the session bus policy")
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -63,6 +63,24 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun orientation(context: Context, mode: String?): Int {
val key = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
} ?: return orientation(context)
val stored = prefs(context).getInt(key, Int.MIN_VALUE)
return if (stored == Int.MIN_VALUE) orientation(context)
else stored.takeIf { value -> orientationOptions.any { it.first == value } } ?: orientation(context)
}
fun setOrientation(context: Context, mode: String, orientation: Int) {
require(mode == "steam" || mode == "desktop")
require(orientationOptions.any { it.first == orientation })
val key = if (mode == "steam") "orientation.steam" else "orientation.desktop"
prefs(context).edit().putInt(key, orientation).apply()
}
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
@@ -75,11 +93,19 @@ object SessionPrefs {
prefs(context).edit().putInt("orientation", orientation).apply()
}
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int, mode: String? = null): Int {
val modeKey = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
}
val preferences = prefs(context)
if (modeKey != null && preferences.contains(modeKey)) return orientation(context, mode)
return if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !preferences.contains("orientation"))
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
}
fun portrait(context: Context): Boolean = when (orientation(context)) {
fun portrait(context: Context, mode: String? = null): Boolean = when (orientation(context, mode)) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
ActivityInfo.SCREEN_ORIENTATION_USER ->
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
@@ -1111,10 +1137,20 @@ object SessionPrefs {
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
fun setDesktopAsUser(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
@@ -661,7 +661,7 @@ class SessionService : Service() {
Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output")
}
if (SessionState.followScreen || size.first < size.second ||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
SessionPrefs.orientation(this, SessionState.mode) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
guest.add("DD_FOLLOW_OUTPUT=1")
if (SessionState.hdr) {
guest.add("DD_HDR=1")
@@ -705,10 +705,25 @@ class SessionService : Service() {
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
}
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)) {
// Under the lock a stop takes its number with: a stop either comes first (and this session
// starts no workers) or owns them
ownWorkers = synchronized(stopLock) {
if (gen != sessionGen || !SessionState.running) 0
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
}
if (ownWorkers > 0) {
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
guest.add("DD_SPAWN_SESSION=$ownWorkers")
}
}
// Proton builds up to 11.12 report X11 text fields under this name.
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop")
if (SessionPrefs.desktopAsUser(this)) guest.add("DD_DESKTOP_USER=1")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1")
@@ -863,10 +878,10 @@ class SessionService : Service() {
watchLaunchRequests(sessionRoot)
watchSyncWanted(root)
EsyncPacks.fetchInBackground(this, root)
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = SessionEvents.step("guest-launch") { HostProcess.startUncounted(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
return@startUncounted
}
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
@@ -882,10 +897,19 @@ class SessionService : Service() {
syncWatcher = null
}
abandonStart(gen, sessionDir, started)
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
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
// Under the lock Stop clears it with, and only while this session still runs: a Stop since the
// check above has cleared it already, and this would set it again for no running session.
val uncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running)
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = uncounted
}
if (pid > 1) {
raiseTracer(pid, gen)
SessionEvents.guestStarted(pid)
@@ -1535,10 +1559,15 @@ class SessionService : Service() {
return binds
}
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
// The workers' session number of the session running now (GuestWorkers.serve)
@Volatile private var guestWorkerSession = 0
private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
if (!stillSameProcess()) return
val tree = descendants(prootPid)
// The session's programs that run in worker processes are not descendants of its root.
val workers = if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workerSession) else emptyList()
val tree = descendants(prootPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) }
if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15)
@@ -1555,6 +1584,7 @@ class SessionService : Service() {
killed++
}
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession)
}
private fun clearCachedApps() {
@@ -1729,6 +1759,7 @@ class SessionService : Service() {
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
Log.i(TAG, "queued Steam game $gameId for the running client")
com.droiddeck.launcher.runtime.GuestWorkers.expectLaunch(this)
}
private fun watchGameExit(
@@ -2325,12 +2356,16 @@ class SessionService : Service() {
return
}
completeNativeSleep()
var workers = 0
val (ended, endedArch) = synchronized(stopLock) {
if (gen != null && gen != sessionGen) return
// as it is when running is cleared: startup registers its workers under this lock too
workers = guestWorkerSession
cancelQueuedSteamGame()
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))
@@ -2391,7 +2426,8 @@ class SessionService : Service() {
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
if (prootPid > 1) teardown(prootPid, workerSession = workers)
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
killGuestLeftovers(ended)
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
@@ -2400,6 +2436,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()
@@ -1,6 +1,9 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import android.os.Build
@@ -50,6 +53,7 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -152,6 +156,19 @@ internal fun SetupPanel(
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) }
var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, ctx) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) }
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
@@ -398,7 +415,8 @@ internal fun SetupPanel(
listOfNotNull(
gpu.displayName(ctx),
s.installed?.let { stringResource(R.string.setup_ready_runtime, it) },
stringResource(R.string.setup_ready_limit_off).takeIf { !limitBlocks },
stringResource(R.string.setup_ready_limit_off)
.takeIf { !limitBlocks && s.phantomProcessStatus != PhantomProcessStatus.UNCOUNTED },
s.offlineAccount?.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.setup_ready_signed_in, it) },
).joinToString(" · "),
open = showChecks, onDetails = { showChecks = !showChecks },
@@ -516,7 +534,27 @@ internal fun SetupPanel(
ChoiceRow(
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.orientation, onPick = a.onOrientation,
s.orientation, onPick = { value ->
a.onOrientation(value)
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
},
)
ChoiceRow(
host, "orientation-steam", stringResource(R.string.setup_session_orientation) + " (Steam)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
steamOrientation, onPick = { value ->
steamOrientation = value
SessionPrefs.setOrientation(ctx, "steam", value)
},
)
ChoiceRow(
host, "orientation-desktop", stringResource(R.string.setup_session_orientation) + " (Desktop)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
desktopOrientation, onPick = { value ->
desktopOrientation = value
SessionPrefs.setOrientation(ctx, "desktop", value)
},
)
ToggleRow(
host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
@@ -49,6 +49,7 @@ fun PerformancePage(
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
@@ -67,6 +68,7 @@ fun PerformancePage(
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
@@ -194,6 +196,12 @@ fun PerformancePage(
modifier = Modifier.width(220.dp).focusGlide(),
)
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
if (phantomWarning != null) {
Spacer(Modifier.height(16.dp))
@@ -89,6 +89,7 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"),
SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")),
+5
View File
@@ -654,6 +654,9 @@
<string name="perf_hostname">اسم المضيف</string>
<string name="perf_hostname_hint">الاسم الذي يراه Steam لهذا الجهاز. اتركه خاليًا للاستعادة إلى %1$s.</string>
<string name="perf_hostname_invalid">أحرف وأرقام وشرطات داخلية فقط، حتى 63 حرفًا.</string>
<string name="perf_desktop_as_user">تشغيل سطح المكتب كمستخدم</string>
<string name="perf_desktop_as_user_hint">يعمل سطح المكتب وتطبيقاته وطرفياته كمستخدم عادي باسم deck بدلًا من root، للتطبيقات التي ترفض root. يظل sudo يعمل. يسري على سطح المكتب التالي.</string>
<string name="perf_desktop_as_user_needs_native">يتطلب التشغيل دون proot.</string>
<string name="perf_phantom_warning">Android مهيَّأ لإنهاء هذه الجلسة</string>
<string name="driver_installed">مثبّت</string>
<string name="driver_available">متاح للتنزيل</string>
@@ -2551,6 +2554,8 @@
<string name="phantom_instructions_fix">%1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى.</string>
<string name="phantom_instructions_off">يمكن بدء جلسات Steam.</string>
<string name="phantom_instructions_not_applicable">لا يستخدم إصدار Android هذا هذا الحدّ.</string>
<string name="phantom_title_uncounted">يتولى DroidDeck حد العمليات الفرعية</string>
<string name="phantom_instructions_uncounted">يشغّل DroidDeck معظم برامج الجلسة في عمليات لا يحتسبها Android، ما يبقي الجلسة دون الحد بكثير، لذا يمكن إبقاء خيارات المطوّرين متوقفة. ما زال Steam وبعض أدواته المساعدة محتسبة.</string>
<string name="phantom_fix_toggle">فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك.</string>
<string name="phantom_fix_no_toggle">لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز.</string>
<string name="upd_block_no_apk">لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck.</string>
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario común deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
@@ -2543,6 +2546,8 @@
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
<string name="phantom_instructions_uncounted">DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones de desarrollador pueden quedar desactivadas. Steam y algunos de sus procesos auxiliares todavía cuentan.</string>
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Име на хоста</string>
<string name="perf_hostname_hint">Името, което Steam вижда за това устройство. Оставено празно възстановява %1$s.</string>
<string name="perf_hostname_invalid">Само букви, цифри и тирета по средата, до 63 знака.</string>
<string name="perf_desktop_as_user">Работният плот работи като потребител</string>
<string name="perf_desktop_as_user_hint">Работният плот, приложенията и терминалите му работят като обикновения потребител deck вместо root, за приложения, които отказват root. sudo продължава да работи. Важи за следващия работен плот.</string>
<string name="perf_desktop_as_user_needs_native">Изисква Работа без proot.</string>
<string name="perf_phantom_warning">Android е настроен да прекратява тази сесия</string>
<string name="driver_installed">Инсталиран</string>
<string name="driver_available">Налично за изтегляне</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Ако това не е възможно, свържи устройството с компютър с ADB и изпълни командата отдолу. Върни се тук и провери отново.</string>
<string name="phantom_instructions_off">Сесиите на Steam могат да стартират.</string>
<string name="phantom_instructions_not_applicable">Тази версия на Android не използва това ограничение.</string>
<string name="phantom_title_uncounted">DroidDeck се справя с ограничението за дъщерни процеси</string>
<string name="phantom_instructions_uncounted">DroidDeck изпълнява повечето програми на сесията в процеси, които Android не отчита, така че сесията остава далеч под лимита и опциите за програмисти могат да останат изключени. Steam и някои от помощните му процеси все още се отчитат.</string>
<string name="phantom_fix_toggle">Включи „Деактивиране на ограниченията за дъщерните процеси“ в Опции за програмисти и остави Опции за програмисти включени след това.</string>
<string name="phantom_fix_no_toggle">Тази версия на Android няма превключвател за това. Използвай безжично отстраняване на грешки, за да го промениш от това устройство.</string>
<string name="upd_block_no_apk">Тази версия няма изтегляне за това копие на DroidDeck.</string>
+5
View File
@@ -650,6 +650,9 @@
<string name="perf_hostname">Název hostitele</string>
<string name="perf_hostname_hint">Název, který Steam vidí pro toto zařízení. Prázdné obnoví %1$s.</string>
<string name="perf_hostname_invalid">Pouze písmena, číslice a vnitřní pomlčky, až 63 znaků.</string>
<string name="perf_desktop_as_user">Plocha běží jako uživatel</string>
<string name="perf_desktop_as_user_hint">Plocha, její aplikace a terminály běží jako běžný uživatel deck místo root, kvůli aplikacím, které root odmítají. sudo dál funguje. Projeví se u příští plochy.</string>
<string name="perf_desktop_as_user_needs_native">Vyžaduje Spouštět bez proot.</string>
<string name="perf_phantom_warning">Android je nastaven tak, aby tuto relaci ukončil</string>
<string name="driver_installed">Nainstalováno</string>
<string name="driver_available">K dispozici ke stažení</string>
@@ -2499,6 +2502,8 @@
<string name="phantom_instructions_fix">%1$s Pokud to není možné, připojte toto zařízení k počítači s ADB a spusťte příkaz níže. Vraťte se sem a zkontrolujte to znovu.</string>
<string name="phantom_instructions_off">Relace Steamu se mohou spouštět.</string>
<string name="phantom_instructions_not_applicable">Tato verze Androidu tento limit nepoužívá.</string>
<string name="phantom_title_uncounted">Limit podřízených procesů řeší DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck spouští většinu programů relace v procesech, které Android nezapočítává, takže relace zůstává hluboko pod limitem a možnosti pro vývojáře mohou zůstat vypnuté. Steam a některé jeho pomocné procesy se stále započítávají.</string>
<string name="phantom_fix_toggle">Zapněte „Deaktivace omezení podřízených procesů“ v Možnostech pro vývojáře a pak je nechte zapnuté.</string>
<string name="phantom_fix_no_toggle">Tato verze Androidu pro to nemá přepínač. Použijte bezdrátové ladění a změňte to z tohoto zařízení.</string>
<string name="upd_block_no_apk">Toto sestavení nemá stažení pro tuto kopii DroidDecku.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Værtsnavn</string>
<string name="perf_hostname_hint">Navnet Steam ser for denne enhed. Tomt gendanner %1$s.</string>
<string name="perf_hostname_invalid">Kun bogstaver, tal og bindestreger i midten, op til 63 tegn.</string>
<string name="perf_desktop_as_user">Skrivebordet kører som bruger</string>
<string name="perf_desktop_as_user_hint">Skrivebordet, dets apps og terminaler kører som den almindelige bruger deck i stedet for root, til apps der afviser root. sudo virker stadig. Gælder fra næste skrivebord.</string>
<string name="perf_desktop_as_user_needs_native">Kræver Kør uden proot.</string>
<string name="perf_phantom_warning">Android er sat til at lukke denne session</string>
<string name="driver_installed">Installeret</string>
<string name="driver_available">Tilgængelig til download</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Hvis det ikke er muligt, så forbind enheden til en computer med ADB, og køre kommandoen nedenfor. Kom tilbage hertil, og tjek igen.</string>
<string name="phantom_instructions_off">Steam-sessioner kan starte.</string>
<string name="phantom_instructions_not_applicable">Denne Android-version bruger ikke denne grænse.</string>
<string name="phantom_title_uncounted">DroidDeck håndterer grænsen for underprocesser</string>
<string name="phantom_instructions_uncounted">DroidDeck kører de fleste af sessionens programmer i processer, som Android ikke tæller med, så sessionen holder sig et godt stykke under grænsen, og Indstillinger for udviklere kan forblive slået fra. Steam og nogle af dets hjælpeprocesser tæller stadig med.</string>
<string name="phantom_fix_toggle">Tænd „Deaktiver begrænsningerne for underprocesser“ i Udvikleremuligheder, og lad Udvikleremuligheder være tændt bagefter.</string>
<string name="phantom_fix_no_toggle">Denne Android-version har ingen kontakt til det. Brug Trådløs fejlretning til at ændre det fra denne enhed.</string>
<string name="upd_block_no_apk">Denne version har ingen download til denne kopi af DroidDeck.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Hostname</string>
<string name="perf_hostname_hint">Der Name, den Steam für dieses Gerät sieht. Leer lassen stellt %1$s wieder her.</string>
<string name="perf_hostname_invalid">Nur Buchstaben, Ziffern und innere Bindestriche, bis zu 63 Zeichen.</string>
<string name="perf_desktop_as_user">Desktop läuft als Benutzer</string>
<string name="perf_desktop_as_user_hint">Der Desktop, seine Apps und Terminals laufen als normaler Benutzer deck statt als root, für Apps, die root ablehnen. sudo funktioniert weiterhin. Gilt ab dem nächsten Desktop.</string>
<string name="perf_desktop_as_user_needs_native">Erfordert Ohne proot ausführen.</string>
<string name="perf_phantom_warning">Android ist so eingestellt, dass es diese Sitzung beendet</string>
<string name="driver_installed">Installiert</string>
<string name="driver_available">Zum Download verfügbar</string>
@@ -2439,6 +2442,8 @@
<string name="phantom_instructions_fix">%1$s Falls das nicht möglich ist, verbinde dieses Gerät per ADB mit einem Computer und führe den Befehl unten aus. Kehre dann hierher zurück und prüfe erneut.</string>
<string name="phantom_instructions_off">Steam-Sitzungen können starten.</string>
<string name="phantom_instructions_not_applicable">Diese Android-Version nutzt dieses Limit nicht.</string>
<string name="phantom_title_uncounted">Limit für untergeordnete Prozesse übernimmt DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck führt die meisten Programme der Sitzung in Prozessen aus, die Android nicht mitzählt. So bleibt die Sitzung deutlich unter dem Limit, und die Entwickleroptionen können ausgeschaltet bleiben. Steam und einige seiner Hilfsprozesse zählen weiterhin mit.</string>
<string name="phantom_fix_toggle">Aktiviere „Beschränkungen für Unterprozesse deaktivieren“ in den Entwickleroptionen und lass die Entwickleroptionen danach aktiviert.</string>
<string name="phantom_fix_no_toggle">Diese Android-Version hat dafür keinen Schalter. Nutze Debugging über WLAN, um es auf diesem Gerät zu ändern.</string>
<string name="upd_block_no_apk">Dieser Build hat keinen Download für diese DroidDeck-Installation.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Όνομα κεντρικού υπολογιστή</string>
<string name="perf_hostname_hint">Το όνομα που βλέπει το Steam για αυτή τη συσκευή. Αν το αφήσετε κενό, επανέρχεται σε %1$s.</string>
<string name="perf_hostname_invalid">Μόνο γράμματα, ψηφία και εσωτερικές παύλες, έως 63 χαρακτήρες.</string>
<string name="perf_desktop_as_user">Η επιφάνεια εργασίας εκτελείται ως χρήστης</string>
<string name="perf_desktop_as_user_hint">Η επιφάνεια εργασίας, οι εφαρμογές και τα τερματικά της εκτελούνται ως ο απλός χρήστης deck αντί για root, για εφαρμογές που αρνούνται το root. Το sudo εξακολουθεί να λειτουργεί. Ισχύει από την επόμενη επιφάνεια εργασίας.</string>
<string name="perf_desktop_as_user_needs_native">Απαιτεί Εκτέλεση χωρίς proot.</string>
<string name="perf_phantom_warning">Το Android είναι ρυθμισμένο να διακόπτει αυτή τη συνεδρία</string>
<string name="driver_installed">Εγκατεστημένο</string>
<string name="driver_available">Διαθέσιμο για λήψη</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Αν αυτό δεν είναι δυνατό, συνδέστε αυτή τη συσκευή σε έναν υπολογιστή με ADB και εκτελέστε την παρακάτω εντολή. Επιστρέψτε εδώ και ελέγξτε ξανά.</string>
<string name="phantom_instructions_off">Οι συνεδρίες Steam μπορούν να ξεκινήσουν.</string>
<string name="phantom_instructions_not_applicable">Αυτή η έκδοση Android δεν χρησιμοποιεί αυτό το όριο.</string>
<string name="phantom_title_uncounted">Το DroidDeck χειρίζεται το όριο θυγατρικών διεργασιών</string>
<string name="phantom_instructions_uncounted">Το DroidDeck εκτελεί τα περισσότερα προγράμματα της συνεδρίας σε διεργασίες που το Android δεν μετράει, ώστε η συνεδρία να μένει πολύ κάτω από το όριο και οι Επιλογές για προγραμματιστές να μπορούν να μείνουν απενεργοποιημένες. Το Steam και ορισμένες βοηθητικές διεργασίες του εξακολουθούν να μετράνε.</string>
<string name="phantom_fix_toggle">Ενεργοποιήστε την «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες» στις Επιλογές προγραμματιστή και αφήστε τις Επιλογές προγραμματιστή ενεργές μετά.</string>
<string name="phantom_fix_no_toggle">Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό. Χρησιμοποιήστε τον ασύρματο εντοπισμό σφαλμάτων για να το αλλάξετε από αυτή τη συσκευή.</string>
<string name="upd_block_no_apk">Αυτή η έκδοση δεν έχει λήψη για αυτό το αντίγραφο του DroidDeck.</string>
+5
View File
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario normal deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
@@ -2473,6 +2476,8 @@
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a un ordenador con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
<string name="phantom_instructions_uncounted">DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones para desarrolladores pueden seguir desactivadas. Steam y algunos de sus procesos auxiliares siguen contando.</string>
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Isäntänimi</string>
<string name="perf_hostname_hint">Nimi, jonka Steam näkee tälle laitteelle. Tyhjä palauttaa arvon %1$s.</string>
<string name="perf_hostname_invalid">Vain kirjaimia, numeroita ja sisäisiä yhdysmerkkejä, enintään 63 merkkiä.</string>
<string name="perf_desktop_as_user">Työpöytä toimii käyttäjänä</string>
<string name="perf_desktop_as_user_hint">Työpöytä, sen sovellukset ja päätteet toimivat tavallisena käyttäjänä deck rootin sijaan, rootin torjuvia sovelluksia varten. sudo toimii edelleen. Koskee seuraavaa työpöytää.</string>
<string name="perf_desktop_as_user_needs_native">Vaatii Suorita ilman prootia.</string>
<string name="perf_phantom_warning">Android on asetettu lopettamaan tämä istunto</string>
<string name="driver_installed">Asennettu</string>
<string name="driver_available">Ladattavissa</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Jos se ei ole mahdollista, yhdistä tämä laite tietokoneeseen ADB:llä ja suorita alla oleva komento. Palaa tähän ja tarkista uudelleen.</string>
<string name="phantom_instructions_off">Steam-istunnot voivat käynnistyä.</string>
<string name="phantom_instructions_not_applicable">Tämä Android-versio ei käytä tätä rajaa.</string>
<string name="phantom_title_uncounted">DroidDeck hoitaa aliprosessirajoituksen</string>
<string name="phantom_instructions_uncounted">DroidDeck ajaa useimmat istunnon ohjelmat prosesseissa, joita Android ei laske, joten istunto pysyy reilusti rajan alapuolella ja kehittäjäasetukset voivat pysyä pois päältä. Steam ja osa sen apuprosesseista lasketaan edelleen.</string>
<string name="phantom_fix_toggle">Ota käyttöön ”Poista käytöstä alatason prosessirajoitukset” Kehittäjäasetuksissa, ja pidä Kehittäjäasetukset päällä sen jälkeen.</string>
<string name="phantom_fix_no_toggle">Tässä Android-versiossa ei ole kytkintä sille. Käytä langatonta virheenkorjausta muuttaaksesi sitä tältä laitteelta.</string>
<string name="upd_block_no_apk">Tälle versiolle ei ole latausta tähän DroidDeck-kopioon.</string>
+5
View File
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nom d\'hôte</string>
<string name="perf_hostname_hint">Le nom sous lequel Steam voit cet appareil. Laisser vide pour restaurer %1$s.</string>
<string name="perf_hostname_invalid">Ne peut contenir que des lettres, des chiffres et des tirets au milieu, jusqu\'à 63 caractères.</string>
<string name="perf_desktop_as_user">Le bureau s’exécute en tant qu’utilisateur</string>
<string name="perf_desktop_as_user_hint">Le bureau, ses applications et ses terminaux s’exécutent en tant qu’utilisateur ordinaire deck au lieu de root, pour les applications qui refusent root. sudo fonctionne toujours. S’applique au prochain bureau.</string>
<string name="perf_desktop_as_user_needs_native">Nécessite Exécuter sans proot.</string>
<string name="perf_phantom_warning">Android est configuré pour terminer cette session</string>
<string name="driver_installed">Installé</string>
<string name="driver_available">Téléchargeable</string>
@@ -2472,6 +2475,8 @@
<string name="phantom_instructions_fix">%1$s Si ce n\'est pas possible, connectez cet appareil à un ordinateur avec ADB et exécutez la commande ci-dessous. Revenez ensuite ici et vérifiez à nouveau.</string>
<string name="phantom_instructions_off">Les sessions Steam peuvent démarrer.</string>
<string name="phantom_instructions_not_applicable">Cette version d\'Android n\'utilise pas cette limite.</string>
<string name="phantom_title_uncounted">Limite de processus enfants gérée par DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck exécute la plupart des programmes de la session dans des processus qu’Android ne compte pas, ce qui maintient la session bien en dessous de la limite : les options pour les développeurs peuvent rester désactivées. Steam et certains de ses processus auxiliaires sont toujours comptés.</string>
<string name="phantom_fix_toggle">Activez « Désactiver les limites pour les processus enfant » dans les options pour les développeurs, puis laissez les options pour les développeurs activées.</string>
<string name="phantom_fix_no_toggle">Cette version d\'Android ne dispose pas de cet interrupteur. Utilisez le débogage sans fil pour le modifier depuis cet appareil.</string>
<string name="upd_block_no_apk">Cette version ne propose aucun téléchargement pour cette copie de DroidDeck.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">होस्ट नाम</string>
<string name="perf_hostname_hint">वह नाम जो Steam इस डिवाइस के लिए देखता है। खाली छोड़ने पर %1$s वापस आ जाता है।</string>
<string name="perf_hostname_invalid">सिर्फ़ अक्षर, अंक और बीच के हाइफ़न, 63 वर्णों तक।</string>
<string name="perf_desktop_as_user">डेस्कटॉप उपयोगकर्ता के रूप में चलता है</string>
<string name="perf_desktop_as_user_hint">डेस्कटॉप, उसके ऐप और टर्मिनल root के बजाय सामान्य उपयोगकर्ता deck के रूप में चलते हैं, उन ऐप के लिए जो root को अस्वीकार करते हैं। sudo फिर भी काम करता है। अगले डेस्कटॉप पर लागू होता है।</string>
<string name="perf_desktop_as_user_needs_native">proot के बिना चलाएँ आवश्यक है।</string>
<string name="perf_phantom_warning">Android इस सेशन को बंद करने के लिए सेट है</string>
<string name="driver_installed">इंस्टॉल है</string>
<string name="driver_available">डाउनलोड के लिए उपलब्ध</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s अगर यह संभव नहीं है, तो इस डिवाइस को ADB वाले कंप्यूटर से कनेक्ट करें और नीचे दिया कमांड चलाएं। यहां वापस आएं और फिर से जांचें।</string>
<string name="phantom_instructions_off">Steam सेशन शुरू हो सकते हैं।</string>
<string name="phantom_instructions_not_applicable">यह Android वर्शन इस सीमा का उपयोग नहीं करता।</string>
<string name="phantom_title_uncounted">चाइल्ड-प्रोसेस सीमा DroidDeck संभालता है</string>
<string name="phantom_instructions_uncounted">DroidDeck सत्र के ज़्यादातर प्रोग्राम उन प्रोसेस में चलाता है जिन्हें Android नहीं गिनता, जिससे सत्र सीमा से काफ़ी नीचे रहता है, इसलिए डेवलपर विकल्प बंद रह सकते हैं। Steam और उसके कुछ सहायक प्रोसेस अब भी गिने जाते हैं।</string>
<string name="phantom_fix_toggle">डेवलपर विकल्प में “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें, और बाद में डेवलपर विकल्प चालू रहने दें।</string>
<string name="phantom_fix_no_toggle">इस Android वर्शन में इसके लिए कोई स्विच नहीं है। इसे इस डिवाइस से बदलने के लिए वायरलेस डीबगिंग इस्तेमाल करें।</string>
<string name="upd_block_no_apk">इस बिल्ड में DroidDeck की इस कॉपी के लिए कोई डाउनलोड नहीं है।</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Hosztnév</string>
<string name="perf_hostname_hint">A név, amelyet a Steam ehhez az eszközhöz lát. Üresen hagyva visszaállítja: %1$s.</string>
<string name="perf_hostname_invalid">Csak betűk, számok és belső kötőjelek, legfeljebb 63 karakter.</string>
<string name="perf_desktop_as_user">Az asztal felhasználóként fut</string>
<string name="perf_desktop_as_user_hint">Az asztal, az alkalmazásai és a termináljai root helyett a deck nevű átlagos felhasználóként futnak, a root-ot elutasító alkalmazások miatt. A sudo továbbra is működik. A következő asztaltól érvényes.</string>
<string name="perf_desktop_as_user_needs_native">A Futtatás proot nélkül szükséges hozzá.</string>
<string name="perf_phantom_warning">Az Android be van állítva, hogy kilője ezt a munkamenetet</string>
<string name="driver_installed">Telepítve</string>
<string name="driver_available">Letölthető</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Ha ez nem lehetséges, csatlakoztassa ezt az eszközt egy ADB-vel rendelkező számítógéphez, és futtassa az alábbi parancsot. Térjen vissza ide, és ellenőrizze újra.</string>
<string name="phantom_instructions_off">A Steam-munkamenetek elindulhatnak.</string>
<string name="phantom_instructions_not_applicable">Ez az Android-verzió nem használja ezt a korlátot.</string>
<string name="phantom_title_uncounted">A gyermekfolyamat-korlátot a DroidDeck kezeli</string>
<string name="phantom_instructions_uncounted">A DroidDeck a munkamenet legtöbb programját olyan folyamatokban futtatja, amelyeket az Android nem számol bele, így a munkamenet jóval a korlát alatt marad, és a fejlesztői beállítások kikapcsolva maradhatnak. A Steam és néhány segédfolyamata továbbra is beleszámít.</string>
<string name="phantom_fix_toggle">Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget a Fejlesztői beállításokban, és utána hagyja bekapcsolva a Fejlesztői beállításokat.</string>
<string name="phantom_fix_no_toggle">Ehhez az Android-verzióhoz nincs kapcsoló. Használja a vezeték nélküli hibakeresést a módosításához erről az eszközről.</string>
<string name="upd_block_no_apk">Ehhez a buildhez nincs letöltés a DroidDeck ezen másolatához.</string>
+5
View File
@@ -644,6 +644,9 @@
<string name="perf_hostname">Nama host</string>
<string name="perf_hostname_hint">Nama yang dilihat Steam untuk perangkat ini. Kosongkan untuk memulihkan %1$s.</string>
<string name="perf_hostname_invalid">Hanya huruf, angka, dan tanda hubung di tengah, hingga 63 karakter.</string>
<string name="perf_desktop_as_user">Desktop berjalan sebagai pengguna</string>
<string name="perf_desktop_as_user_hint">Desktop, aplikasi, dan terminalnya berjalan sebagai pengguna biasa deck, bukan root, untuk aplikasi yang menolak root. sudo tetap berfungsi. Berlaku untuk desktop berikutnya.</string>
<string name="perf_desktop_as_user_needs_native">Memerlukan Jalankan tanpa proot.</string>
<string name="perf_phantom_warning">Android diatur untuk menghentikan sesi ini</string>
<string name="driver_installed">Terinstal</string>
<string name="driver_available">Tersedia untuk diunduh</string>
@@ -2422,6 +2425,8 @@
<string name="phantom_instructions_fix">%1$s Jika itu tidak memungkinkan, sambungkan perangkat ini ke komputer dengan ADB dan jalankan perintah di bawah. Kembali ke sini dan periksa lagi.</string>
<string name="phantom_instructions_off">Sesi Steam dapat dimulai.</string>
<string name="phantom_instructions_not_applicable">Versi Android ini tidak menggunakan batas ini.</string>
<string name="phantom_title_uncounted">Batas proses anak ditangani DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck menjalankan sebagian besar program sesi dalam proses yang tidak dihitung Android, sehingga sesi tetap jauh di bawah batas dan Opsi developer bisa tetap nonaktif. Steam dan beberapa proses pembantunya masih dihitung.</string>
<string name="phantom_fix_toggle">Aktifkan “Nonaktifkan batasan proses turunan” di Opsi developer, dan biarkan Opsi developer tetap aktif setelahnya.</string>
<string name="phantom_fix_no_toggle">Versi Android ini tidak memiliki sakelar untuk itu. Gunakan Debugging nirkabel untuk mengubahnya dari perangkat ini.</string>
<string name="upd_block_no_apk">Build ini tidak memiliki unduhan untuk salinan DroidDeck ini.</string>
+5
View File
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nome host</string>
<string name="perf_hostname_hint">Il nome con cui Steam vede questo dispositivo. Se vuoto, torna a %1$s.</string>
<string name="perf_hostname_invalid">Solo lettere, cifre e trattini interni, fino a 63 caratteri.</string>
<string name="perf_desktop_as_user">Il desktop viene eseguito come utente</string>
<string name="perf_desktop_as_user_hint">Il desktop, le sue app e i suoi terminali vengono eseguiti come utente normale deck invece che come root, per le app che rifiutano root. sudo funziona comunque. Si applica al prossimo desktop.</string>
<string name="perf_desktop_as_user_needs_native">Richiede Esegui senza proot.</string>
<string name="perf_phantom_warning">Android è impostato per terminare questa sessione</string>
<string name="driver_installed">Installati</string>
<string name="driver_available">Disponibili per il download</string>
@@ -2464,6 +2467,8 @@
<string name="phantom_instructions_fix">%1$s Se non è possibile, collega questo dispositivo a un computer con ADB ed esegui il comando qui sotto. Poi torna qui e ricontrolla.</string>
<string name="phantom_instructions_off">Le sessioni Steam possono avviarsi.</string>
<string name="phantom_instructions_not_applicable">Questa versione di Android non usa questo limite.</string>
<string name="phantom_title_uncounted">Limite dei processi figli gestito da DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck esegue la maggior parte dei programmi della sessione in processi che Android non conteggia, così la sessione resta ben al di sotto del limite e le Opzioni sviluppatore possono restare disattivate. Steam e alcuni dei suoi processi di supporto vengono ancora conteggiati.</string>
<string name="phantom_fix_toggle">Attiva “Disattiva limitazioni per i processi secondari” in Opzioni sviluppatore e poi lascia attive le Opzioni sviluppatore.</string>
<string name="phantom_fix_no_toggle">Questa versione di Android non ha un interruttore per farlo. Usa il debug wireless per cambiarlo da questo dispositivo.</string>
<string name="upd_block_no_apk">Questa build non ha un download per questa copia di DroidDeck.</string>
+5
View File
@@ -644,6 +644,9 @@
<string name="perf_hostname">ホスト名</string>
<string name="perf_hostname_hint">Steamがこのデバイスを認識する名前。空にすると%1$sに戻ります。</string>
<string name="perf_hostname_invalid">英数字と中間のハイフンのみ使用でき、最大63文字です。</string>
<string name="perf_desktop_as_user">デスクトップをユーザーとして実行</string>
<string name="perf_desktop_as_user_hint">デスクトップとそのアプリやターミナルを root ではなく一般ユーザー deck として実行します。root を拒否するアプリ向けです。sudo は引き続き使えます。次回のデスクトップから適用されます。</string>
<string name="perf_desktop_as_user_needs_native">proot なしで実行が必要です。</string>
<string name="perf_phantom_warning">Androidがこのセッションを終了するように設定されています</string>
<string name="driver_installed">インストール済み</string>
<string name="driver_available">ダウンロード可能</string>
@@ -2422,6 +2425,8 @@
<string name="phantom_instructions_fix">%1$s それができない場合は、このデバイスをADBが使えるPCに接続し、以下のコマンドを実行してください。その後ここに戻って再確認してください。</string>
<string name="phantom_instructions_off">Steamセッションを開始できます。</string>
<string name="phantom_instructions_not_applicable">このAndroidバージョンではこの制限は使用されません。</string>
<string name="phantom_title_uncounted">子プロセスの制限は DroidDeck が対処します</string>
<string name="phantom_instructions_uncounted">DroidDeck はセッションのほとんどのプログラムを Android が数えないプロセスで実行するため、セッションは上限を大きく下回り、開発者向けオプションはオフのままでかまいません。Steam とその補助プロセスの一部は引き続き数えられます。</string>
<string name="phantom_fix_toggle">開発者向けオプションで「子プロセスの制限を無効化」をオンにし、その後も開発者向けオプションをオンのままにしてください。</string>
<string name="phantom_fix_no_toggle">このAndroidバージョンにはこのスイッチがありません。ワイヤレスデバッグを使って、このデバイスから変更してください。</string>
<string name="upd_block_no_apk">このビルドには、このDroidDeckコピー用のダウンロードがありません。</string>
+5
View File
@@ -644,6 +644,9 @@
<string name="perf_hostname">호스트 이름</string>
<string name="perf_hostname_hint">Steam이 이 기기를 인식하는 이름입니다. 비워 두면 %1$s(으)로 복원됩니다.</string>
<string name="perf_hostname_invalid">영문, 숫자 및 중간 하이픈만 사용할 수 있으며 최대 63자입니다.</string>
<string name="perf_desktop_as_user">데스크톱을 사용자로 실행</string>
<string name="perf_desktop_as_user_hint">데스크톱과 앱, 터미널이 root 대신 일반 사용자 deck으로 실행됩니다. root를 거부하는 앱을 위한 설정입니다. sudo는 계속 사용할 수 있습니다. 다음 데스크톱부터 적용됩니다.</string>
<string name="perf_desktop_as_user_needs_native">proot 없이 실행이 필요합니다.</string>
<string name="perf_phantom_warning">Android가 이 세션을 종료하도록 설정했습니다</string>
<string name="driver_installed">설치됨</string>
<string name="driver_available">다운로드 가능</string>
@@ -2422,6 +2425,8 @@
<string name="phantom_instructions_fix">%1$s 이 방법을 사용할 수 없으면 이 기기를 ADB가 설치된 PC에 연결하고 아래 명령을 실행하세요. 그런 다음 여기로 돌아와 다시 확인하세요.</string>
<string name="phantom_instructions_off">Steam 세션을 시작할 수 있습니다.</string>
<string name="phantom_instructions_not_applicable">이 Android 버전에서는 이 제한을 사용하지 않습니다.</string>
<string name="phantom_title_uncounted">하위 프로세스 제한은 DroidDeck이 처리합니다</string>
<string name="phantom_instructions_uncounted">DroidDeck은 세션 프로그램 대부분을 Android가 세지 않는 프로세스에서 실행하므로 세션이 한도보다 훨씬 낮게 유지되어 개발자 옵션을 꺼 둔 채로 두어도 됩니다. Steam과 일부 보조 프로세스는 여전히 집계됩니다.</string>
<string name="phantom_fix_toggle">개발자 옵션에서 “하위 프로세스 제한 사용 중지”를 켜고, 이후에도 개발자 옵션을 켜 둔 상태로 유지하세요.</string>
<string name="phantom_fix_no_toggle">이 Android 버전에는 해당 스위치가 없습니다. 무선 디버깅을 사용하여 이 기기에서 변경하세요.</string>
<string name="upd_block_no_apk">이 빌드에는 이 DroidDeck 복사본용 다운로드가 없습니다.</string>
+5
View File
@@ -644,6 +644,9 @@
<string name="perf_hostname">Nama hos</string>
<string name="perf_hostname_hint">Nama yang dilihat Steam untuk peranti ini. Kosongkan untuk memulihkan %1$s.</string>
<string name="perf_hostname_invalid">Huruf, digit dan tanda sempang dalaman sahaja, sehingga 63 aksara.</string>
<string name="perf_desktop_as_user">Desktop berjalan sebagai pengguna</string>
<string name="perf_desktop_as_user_hint">Desktop, aplnya dan terminalnya berjalan sebagai pengguna biasa deck dan bukan root, untuk apl yang menolak root. sudo masih berfungsi. Berkuat kuasa pada desktop seterusnya.</string>
<string name="perf_desktop_as_user_needs_native">Memerlukan Jalankan tanpa proot.</string>
<string name="perf_phantom_warning">Android ditetapkan untuk menamatkan sesi ini</string>
<string name="driver_installed">Dipasang</string>
<string name="driver_available">Tersedia untuk dimuat turun</string>
@@ -2422,6 +2425,8 @@
<string name="phantom_instructions_fix">%1$s Jika itu tidak boleh, sambungkan peranti ini ke komputer dengan ADB dan jalankan arahan di bawah. Kembali ke sini dan semak semula.</string>
<string name="phantom_instructions_off">Sesi Steam boleh dimulakan.</string>
<string name="phantom_instructions_not_applicable">Versi Android ini tidak menggunakan had ini.</string>
<string name="phantom_title_uncounted">Had proses anak dikendalikan oleh DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck menjalankan kebanyakan program sesi dalam proses yang tidak dikira oleh Android, jadi sesi kekal jauh di bawah had dan Pilihan pembangun boleh kekal dimatikan. Steam dan sesetengah proses pembantunya masih dikira.</string>
<string name="phantom_fix_toggle">Hidupkan “Lumpuhkan sekatan proses anak” dalam Pilihan pembangun, dan biarkan Pilihan pembangun hidup selepas itu.</string>
<string name="phantom_fix_no_toggle">Versi Android ini tidak mempunyai suis untuknya. Gunakan Debugging Wayarles untuk menukarnya daripada peranti ini.</string>
<string name="upd_block_no_apk">Binaan ini tidak mempunyai muat turun untuk salinan DroidDeck ini.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Vertsnavn</string>
<string name="perf_hostname_hint">Navnet Steam ser for denne enheten. Tomt gjenoppretter %1$s.</string>
<string name="perf_hostname_invalid">Bare bokstaver, tall og bindestreker inni navnet, opptil 63 tegn.</string>
<string name="perf_desktop_as_user">Skrivebordet kjører som bruker</string>
<string name="perf_desktop_as_user_hint">Skrivebordet, appene og terminalene kjører som den vanlige brukeren deck i stedet for root, for apper som avviser root. sudo virker fortsatt. Gjelder fra neste skrivebord.</string>
<string name="perf_desktop_as_user_needs_native">Krever Kjør uten proot.</string>
<string name="perf_phantom_warning">Android er satt til å avslutte denne sesjonen</string>
<string name="driver_installed">Installert</string>
<string name="driver_available">Tilgjengelig for nedlasting</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Hvis det ikke er mulig, koble denne enheten til en datamaskin med ADB og kjør kommandoen under. Kom tilbake hit og kontroller igjen.</string>
<string name="phantom_instructions_off">Steam-sesjoner kan starte.</string>
<string name="phantom_instructions_not_applicable">Denne Android-versjonen bruker ikke denne grensen.</string>
<string name="phantom_title_uncounted">DroidDeck håndterer grensen for underprosesser</string>
<string name="phantom_instructions_uncounted">DroidDeck kjører de fleste programmene i økten i prosesser som Android ikke teller med, så økten holder seg godt under grensen og utvikleralternativer kan forbli av. Steam og noen av hjelpeprosessene dens telles fortsatt.</string>
<string name="phantom_fix_toggle">Slå på «Slå av begrensninger for underordnede prosesser» i Utvikleralternativer, og la Utvikleralternativer stå på etterpå.</string>
<string name="phantom_fix_no_toggle">Denne Android-versjonen har ingen bryter for det. Bruk trådløs feilsøking for å endre det fra denne enheten.</string>
<string name="upd_block_no_apk">Denne builden har ingen nedlasting for denne kopien av DroidDeck.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Hostnaam</string>
<string name="perf_hostname_hint">De naam die Steam voor dit apparaat ziet. Leeg herstelt %1$s.</string>
<string name="perf_hostname_invalid">Alleen letters, cijfers en koppeltekens binnen de naam, tot 63 tekens.</string>
<string name="perf_desktop_as_user">Bureaublad draait als gebruiker</string>
<string name="perf_desktop_as_user_hint">Het bureaublad, de apps en terminals draaien als de gewone gebruiker deck in plaats van root, voor apps die root weigeren. sudo werkt nog steeds. Geldt vanaf het volgende bureaublad.</string>
<string name="perf_desktop_as_user_needs_native">Vereist Uitvoeren zonder proot.</string>
<string name="perf_phantom_warning">Android is ingesteld om deze sessie te sluiten</string>
<string name="driver_installed">Geïnstalleerd</string>
<string name="driver_available">Beschikbaar om te downloaden</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Als dat niet mogelijk is, sluit dit apparaat aan op een computer met ADB en voer de onderstaande opdracht uit. Kom hierna terug en controleer opnieuw.</string>
<string name="phantom_instructions_off">Steam-sessies kunnen starten.</string>
<string name="phantom_instructions_not_applicable">Deze Android-versie gebruikt deze limiet niet.</string>
<string name="phantom_title_uncounted">Limiet voor onderliggende processen geregeld door DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck voert de meeste programma\'s van de sessie uit in processen die Android niet meetelt, zodat de sessie ruim onder de limiet blijft en Ontwikkelaarsopties uit kunnen blijven. Steam en enkele van zijn hulpprocessen tellen nog wel mee.</string>
<string name="phantom_fix_toggle">Schakel “Beperkingen voor onderliggende processen uitzetten” in bij Ontwikkelaarsopties en laat Ontwikkelaarsopties daarna aan staan.</string>
<string name="phantom_fix_no_toggle">Deze Android-versie heeft hier geen schakelaar voor. Gebruik draadloze foutopsporing om dit vanaf dit apparaat te wijzigen.</string>
<string name="upd_block_no_apk">Deze build heeft geen download voor dit exemplaar van DroidDeck.</string>
+5
View File
@@ -650,6 +650,9 @@
<string name="perf_hostname">Nazwa hosta</string>
<string name="perf_hostname_hint">Nazwa tego urządzenia widoczna dla Steam. Puste pole przywraca %1$s.</string>
<string name="perf_hostname_invalid">Tylko litery, cyfry i łączniki w środku, do 63 znaków.</string>
<string name="perf_desktop_as_user">Pulpit działa jako użytkownik</string>
<string name="perf_desktop_as_user_hint">Pulpit, jego aplikacje i terminale działają jako zwykły użytkownik deck zamiast root, dla aplikacji, które odrzucają root. sudo nadal działa. Obowiązuje od następnego pulpitu.</string>
<string name="perf_desktop_as_user_needs_native">Wymaga Uruchamiaj bez proot.</string>
<string name="perf_phantom_warning">Android jest ustawiony tak, że zamknie tę sesję</string>
<string name="driver_installed">Zainstalowane</string>
<string name="driver_available">Do pobrania</string>
@@ -2499,6 +2502,8 @@
<string name="phantom_instructions_fix">%1$s Jeśli to niemożliwe, podłącz to urządzenie do komputera z ADB i uruchom poniższe polecenie. Wróć tutaj i sprawdź ponownie.</string>
<string name="phantom_instructions_off">Sesje Steam mogą się uruchamiać.</string>
<string name="phantom_instructions_not_applicable">Ta wersja systemu Android nie używa tego limitu.</string>
<string name="phantom_title_uncounted">Limitem procesów podrzędnych zajmuje się DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck uruchamia większość programów sesji w procesach, których Android nie liczy, dzięki czemu sesja pozostaje znacznie poniżej limitu, a Opcje programisty mogą pozostać wyłączone. Steam i niektóre jego procesy pomocnicze nadal są liczone.</string>
<string name="phantom_fix_toggle">Włącz „Wyłącz ograniczenia procesów podrzędnych aplikacji” w Opcjach programisty i nie wyłączaj potem Opcji programisty.</string>
<string name="phantom_fix_no_toggle">Ta wersja systemu Android nie ma dla niego przełącznika. Użyj debugowania bezprzewodowego, aby zmienić go z tego urządzenia.</string>
<string name="upd_block_no_apk">Ta wersja nie ma pliku do pobrania dla tej kopii DroidDeck.</string>
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nome do anfitrião</string>
<string name="perf_hostname_hint">O nome com que o Steam vê este dispositivo. Em branco, repõe %1$s.</string>
<string name="perf_hostname_invalid">Apenas letras, algarismos e hífenes interiores, até 63 carateres.</string>
<string name="perf_desktop_as_user">O ambiente de trabalho corre como utilizador</string>
<string name="perf_desktop_as_user_hint">O ambiente de trabalho, as suas apps e terminais correm como o utilizador comum deck em vez de root, para apps que recusam root. O sudo continua a funcionar. Aplica-se ao próximo ambiente de trabalho.</string>
<string name="perf_desktop_as_user_needs_native">Requer Executar sem proot.</string>
<string name="perf_phantom_warning">O Android está configurado para terminar esta sessão</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponível para transferir</string>
@@ -2479,6 +2482,8 @@
<string name="phantom_instructions_fix">%1$s Se não for possível, ligue este dispositivo a um computador com ADB e execute o comando abaixo. Volte aqui e verifique novamente.</string>
<string name="phantom_instructions_off">As sessões Steam podem ser iniciadas.</string>
<string name="phantom_instructions_not_applicable">Esta versão do Android não usa este limite.</string>
<string name="phantom_title_uncounted">Limite de processos filhos gerido pelo DroidDeck</string>
<string name="phantom_instructions_uncounted">O DroidDeck executa a maioria dos programas da sessão em processos que o Android não conta, o que mantém a sessão bem abaixo do limite, por isso as Opções de programador podem continuar desativadas. O Steam e alguns dos seus processos auxiliares continuam a contar.</string>
<string name="phantom_fix_toggle">Ative «Desativar restrições de processos secundários» nas Opções de programador e mantenha as Opções de programador ativadas depois.</string>
<string name="phantom_fix_no_toggle">Esta versão do Android não tem um interruptor para isto. Use a depuração sem fios para o alterar a partir deste dispositivo.</string>
<string name="upd_block_no_apk">Esta versão não tem transferência para esta cópia do DroidDeck.</string>
+5
View File
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nome do host</string>
<string name="perf_hostname_hint">O nome que a Steam vê para este dispositivo. Em branco, volta a ser %1$s.</string>
<string name="perf_hostname_invalid">Só letras, dígitos e hifens internos, até 63 caracteres.</string>
<string name="perf_desktop_as_user">A área de trabalho roda como usuário</string>
<string name="perf_desktop_as_user_hint">A área de trabalho, seus apps e terminais rodam como o usuário comum deck em vez de root, para apps que recusam root. O sudo continua funcionando. Vale a partir da próxima área de trabalho.</string>
<string name="perf_desktop_as_user_needs_native">Requer Executar sem proot.</string>
<string name="perf_phantom_warning">O Android está configurado para encerrar esta sessão</string>
<string name="driver_installed">Instalados</string>
<string name="driver_available">Disponíveis para download</string>
@@ -2487,6 +2490,8 @@
<string name="phantom_instructions_fix">%1$s Se não for possível, conecte este dispositivo a um computador com ADB e execute o comando abaixo. Depois volte aqui e verifique de novo.</string>
<string name="phantom_instructions_off">As sessões do Steam podem ser iniciadas.</string>
<string name="phantom_instructions_not_applicable">Esta versão do Android não usa esse limite.</string>
<string name="phantom_title_uncounted">Limite de processos filhos gerenciado pelo DroidDeck</string>
<string name="phantom_instructions_uncounted">O DroidDeck executa a maioria dos programas da sessão em processos que o Android não conta, o que mantém a sessão bem abaixo do limite, então as Opções do desenvolvedor podem continuar desativadas. O Steam e alguns dos seus processos auxiliares ainda contam.</string>
<string name="phantom_fix_toggle">Ative “Desativar restrições de processos filhos” nas Opções do desenvolvedor e mantenha as Opções do desenvolvedor ativadas depois.</string>
<string name="phantom_fix_no_toggle">Esta versão do Android não tem uma chave para isso. Use a depuração por Wi-Fi para alterar pelo próprio dispositivo.</string>
<string name="upd_block_no_apk">Esta versão não tem download para esta cópia do DroidDeck.</string>
+5
View File
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nume de host</string>
<string name="perf_hostname_hint">Numele pe care Steam îl vede pentru acest dispozitiv. Gol restaurează %1$s.</string>
<string name="perf_hostname_invalid">Doar litere, cifre și liniuțe interioare, până la 63 de caractere.</string>
<string name="perf_desktop_as_user">Desktopul rulează ca utilizator</string>
<string name="perf_desktop_as_user_hint">Desktopul, aplicațiile și terminalele sale rulează ca utilizatorul obișnuit deck în loc de root, pentru aplicațiile care refuză root. sudo funcționează în continuare. Se aplică la următorul desktop.</string>
<string name="perf_desktop_as_user_needs_native">Necesită Rulează fără proot.</string>
<string name="perf_phantom_warning">Android este setat să închidă această sesiune</string>
<string name="driver_installed">Instalat</string>
<string name="driver_available">Disponibil pentru descărcare</string>
@@ -2473,6 +2476,8 @@
<string name="phantom_instructions_fix">%1$s Dacă nu este posibil, conectează acest dispozitiv la un computer cu ADB și rulează comanda de mai jos. Revino aici și verifică din nou.</string>
<string name="phantom_instructions_off">Sesiunile Steam pot porni.</string>
<string name="phantom_instructions_not_applicable">Această versiune de Android nu folosește această limită.</string>
<string name="phantom_title_uncounted">Limita proceselor copil este gestionată de DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck rulează majoritatea programelor sesiunii în procese pe care Android nu le numără, astfel încât sesiunea rămâne mult sub limită, iar Opțiunile pentru dezvoltatori pot rămâne dezactivate. Steam și unele dintre procesele sale auxiliare sunt încă numărate.</string>
<string name="phantom_fix_toggle">Activează „Dezactivează restricțiile pentru procese secundare” în Opțiunile pentru dezvoltatori, și lasă Opțiunile pentru dezvoltatori activate după aceea.</string>
<string name="phantom_fix_no_toggle">Această versiune de Android nu are un comutator pentru asta. Folosește Depanarea wireless pentru a o schimba de pe acest dispozitiv.</string>
<string name="upd_block_no_apk">Această versiune nu are o descărcare pentru această copie de DroidDeck.</string>
+5
View File
@@ -650,6 +650,9 @@
<string name="perf_hostname">Имя хоста</string>
<string name="perf_hostname_hint">Имя, под которым Steam видит это устройство. Оставьте пустым, чтобы вернуть %1$s.</string>
<string name="perf_hostname_invalid">Только буквы, цифры и дефисы посередине, до 63 символов.</string>
<string name="perf_desktop_as_user">Рабочий стол от имени пользователя</string>
<string name="perf_desktop_as_user_hint">Рабочий стол, его приложения и терминалы работают от имени обычного пользователя deck вместо root — для приложений, которые отказываются работать от root. sudo по-прежнему работает. Применяется к следующему запуску рабочего стола.</string>
<string name="perf_desktop_as_user_needs_native">Требуется «Запуск без proot».</string>
<string name="perf_phantom_warning">Android настроен на завершение этой сессии</string>
<string name="driver_installed">Установлен</string>
<string name="driver_available">Доступен для скачивания</string>
@@ -2500,6 +2503,8 @@
<string name="phantom_instructions_fix">%1$s Если это невозможно, подключите устройство к компьютеру с ADB и выполните команду ниже. Затем вернитесь сюда и проверьте снова.</string>
<string name="phantom_instructions_off">Сессии Steam могут запускаться.</string>
<string name="phantom_instructions_not_applicable">Эта версия Android не использует это ограничение.</string>
<string name="phantom_title_uncounted">Ограничение дочерних процессов обходит DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck запускает большинство программ сеанса в процессах, которые Android не учитывает, поэтому сеанс остаётся намного ниже лимита и параметры разработчика можно не включать. Steam и некоторые его вспомогательные процессы по-прежнему учитываются.</string>
<string name="phantom_fix_toggle">Включите «Отключить ограничения для дочерних процессов» в разделе «Для разработчиков» и оставьте этот раздел включенным.</string>
<string name="phantom_fix_no_toggle">В этой версии Android нет такого переключателя. Измените настройку с этого устройства через отладку по Wi-Fi.</string>
<string name="upd_block_no_apk">В этой сборке нет загрузки для этой копии DroidDeck.</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Värdnamn</string>
<string name="perf_hostname_hint">Namnet Steam ser för den här enheten. Lämna tomt för att återställa till %1$s.</string>
<string name="perf_hostname_invalid">Endast bokstäver, siffror och bindestreck inuti, upp till 63 tecken.</string>
<string name="perf_desktop_as_user">Skrivbordet körs som användare</string>
<string name="perf_desktop_as_user_hint">Skrivbordet, dess appar och terminaler körs som den vanliga användaren deck i stället för root, för appar som vägrar root. sudo fungerar fortfarande. Gäller från nästa skrivbord.</string>
<string name="perf_desktop_as_user_needs_native">Kräver Kör utan proot.</string>
<string name="perf_phantom_warning">Android är inställt på att avsluta den här sessionen</string>
<string name="driver_installed">Installerad</string>
<string name="driver_available">Tillgänglig att ladda ned</string>
@@ -2447,6 +2450,8 @@
<string name="phantom_instructions_fix">%1$s Om det inte är möjligt ansluter du den här enheten till en dator med ADB och kör kommandot nedan. Kom tillbaka hit och kontrollera igen.</string>
<string name="phantom_instructions_off">Steam-sessioner kan starta.</string>
<string name="phantom_instructions_not_applicable">Den här Android-versionen använder inte den här gränsen.</string>
<string name="phantom_title_uncounted">DroidDeck hanterar gränsen för underprocesser</string>
<string name="phantom_instructions_uncounted">DroidDeck kör de flesta av sessionens program i processer som Android inte räknar, så sessionen håller sig långt under gränsen och Utvecklaralternativ kan vara avstängda. Steam och några av dess hjälpprocesser räknas fortfarande.</string>
<string name="phantom_fix_toggle">Slå på ”Inaktivera begränsningar på underordnade processer” i Utvecklaralternativ, och låt Utvecklaralternativ vara kvar på efteråt.</string>
<string name="phantom_fix_no_toggle">Den här Android-versionen har ingen växel för det. Använd trådlös felsökning för att ändra det från den här enheten.</string>
<string name="upd_block_no_apk">Den här versionen har ingen nedladdning för den här kopian av DroidDeck.</string>
+5
View File
@@ -644,6 +644,9 @@
<string name="perf_hostname">ชื่อโฮสต์</string>
<string name="perf_hostname_hint">ชื่อที่ Steam มองเห็นสำหรับอุปกรณ์นี้ เว้นว่างไว้เพื่อคืนค่าเป็น %1$s</string>
<string name="perf_hostname_invalid">ใช้ได้เฉพาะตัวอักษร ตัวเลข และยัติภังค์ตรงกลาง ไม่เกิน 63 ตัวอักษร</string>
<string name="perf_desktop_as_user">เดสก์ท็อปทำงานในฐานะผู้ใช้</string>
<string name="perf_desktop_as_user_hint">เดสก์ท็อป แอป และเทอร์มินัลจะทำงานในฐานะผู้ใช้ทั่วไป deck แทน root สำหรับแอปที่ไม่ยอมทำงานด้วย root sudo ยังใช้งานได้ มีผลกับเดสก์ท็อปครั้งถัดไป</string>
<string name="perf_desktop_as_user_needs_native">ต้องเปิด เรียกใช้โดยไม่มี proot</string>
<string name="perf_phantom_warning">Android ถูกตั้งให้ปิดเซสชันนี้</string>
<string name="driver_installed">ติดตั้งแล้ว</string>
<string name="driver_available">พร้อมดาวน์โหลด</string>
@@ -2422,6 +2425,8 @@
<string name="phantom_instructions_fix">%1$s หากทำไม่ได้ ให้เชื่อมต่ออุปกรณ์นี้กับคอมพิวเตอร์ที่มี ADB แล้วรันคำสั่งด้านล่าง กลับมาที่นี่แล้วตรวจสอบอีกครั้ง</string>
<string name="phantom_instructions_off">เซสชัน Steam สามารถเริ่มได้</string>
<string name="phantom_instructions_not_applicable">Android รุ่นนี้ไม่ใช้ขีดจำกัดนี้</string>
<string name="phantom_title_uncounted">DroidDeck จัดการขีดจำกัดโปรเซสลูกให้</string>
<string name="phantom_instructions_uncounted">DroidDeck เรียกใช้โปรแกรมส่วนใหญ่ของเซสชันในโปรเซสที่ Android ไม่นับ เซสชันจึงต่ำกว่าขีดจำกัดมาก และปิดตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ไว้ได้ Steam และโปรเซสตัวช่วยบางตัวของ Steam ยังคงถูกนับ</string>
<string name="phantom_fix_toggle">เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” ในตัวเลือกสำหรับนักพัฒนา และเปิดตัวเลือกสำหรับนักพัฒนาไว้ต่อไปหลังจากนั้น</string>
<string name="phantom_fix_no_toggle">Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ใช้ Wireless debugging เพื่อเปลี่ยนค่าจากอุปกรณ์นี้</string>
<string name="upd_block_no_apk">บิลด์นี้ไม่มีให้ดาวน์โหลดสำหรับสำเนานี้ของ DroidDeck</string>
+5
View File
@@ -646,6 +646,9 @@
<string name="perf_hostname">Ana bilgisayar adı</string>
<string name="perf_hostname_hint">Steam\'in bu cihaz için gördüğü ad. Boş bırakılırsa %1$s geri yüklenir.</string>
<string name="perf_hostname_invalid">Yalnızca harf, rakam ve arada kısa çizgi; en fazla 63 karakter.</string>
<string name="perf_desktop_as_user">Masaüstü kullanıcı olarak çalışır</string>
<string name="perf_desktop_as_user_hint">Masaüstü, uygulamaları ve terminalleri root yerine sıradan kullanıcı deck olarak çalışır; root’u reddeden uygulamalar içindir. sudo çalışmaya devam eder. Bir sonraki masaüstünde geçerli olur.</string>
<string name="perf_desktop_as_user_needs_native">proot olmadan çalıştır gerekir.</string>
<string name="perf_phantom_warning">Android bu oturumu sonlandıracak şekilde ayarlı</string>
<string name="driver_installed">Yüklü</string>
<string name="driver_available">İndirilebilir</string>
@@ -2439,6 +2442,8 @@
<string name="phantom_instructions_fix">%1$s Bu mümkün değilse bu cihazı ADB\'li bir bilgisayara bağlayıp aşağıdaki komutu çalıştırın. Buraya dönüp yeniden kontrol edin.</string>
<string name="phantom_instructions_off">Steam oturumları başlayabilir.</string>
<string name="phantom_instructions_not_applicable">Bu Android sürümü bu sınırı kullanmaz.</string>
<string name="phantom_title_uncounted">Alt işlem sınırını DroidDeck yönetiyor</string>
<string name="phantom_instructions_uncounted">DroidDeck oturumun programlarının çoğunu Android\'in saymadığı işlemlerde çalıştırır; böylece oturum sınırın çok altında kalır ve Geliştirici seçenekleri kapalı kalabilir. Steam ve bazı yardımcı işlemleri hâlâ sayılır.</string>
<string name="phantom_fix_toggle">Geliştirici seçenekleri\'nde “Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açın ve sonrasında Geliştirici seçeneklerini açık tutun.</string>
<string name="phantom_fix_no_toggle">Bu Android sürümünde bunun için bir anahtar yok. Bu cihazdan değiştirmek için Kablosuz hata ayıklamayı kullanın.</string>
<string name="upd_block_no_apk">Bu derlemede bu DroidDeck kopyası için bir indirme yok.</string>
+5
View File
@@ -650,6 +650,9 @@
<string name="perf_hostname">Ім’я хоста</string>
<string name="perf_hostname_hint">Ім’я, яке Steam бачить для цього пристрою. Порожнє значення відновлює %1$s.</string>
<string name="perf_hostname_invalid">Лише літери, цифри та дефіси всередині, до 63 символів.</string>
<string name="perf_desktop_as_user">Робочий стіл від імені користувача</string>
<string name="perf_desktop_as_user_hint">Робочий стіл, його застосунки й термінали працюють від імені звичайного користувача deck замість root — для застосунків, які відмовляються працювати від root. sudo і далі працює. Застосовується до наступного запуску робочого столу.</string>
<string name="perf_desktop_as_user_needs_native">Потрібен «Запуск без proot».</string>
<string name="perf_phantom_warning">Android налаштовано завершувати цей сеанс</string>
<string name="driver_installed">Встановлено</string>
<string name="driver_available">Доступно для завантаження</string>
@@ -2499,6 +2502,8 @@
<string name="phantom_instructions_fix">%1$s Якщо це неможливо, підключіть цей пристрій до комп’ютера з ADB і виконайте команду нижче. Потім поверніться сюди і перевірте ще раз.</string>
<string name="phantom_instructions_off">Сеанси Steam можуть запускатися.</string>
<string name="phantom_instructions_not_applicable">Ця версія Android не використовує це обмеження.</string>
<string name="phantom_title_uncounted">Обмеження дочірніх процесів обходить DroidDeck</string>
<string name="phantom_instructions_uncounted">DroidDeck запускає більшість програм сеансу в процесах, які Android не враховує, тож сеанс залишається значно нижче ліміту і параметри розробника можна не вмикати. Steam і деякі його допоміжні процеси все ще враховуються.</string>
<string name="phantom_fix_toggle">Увімкніть «Вимкнути обмеження для дочірніх процесів» у розділі «Параметри розробника» і залишіть «Параметри розробника» увімкненими після цього.</string>
<string name="phantom_fix_no_toggle">У цій версії Android немає перемикача для цього. Змініть це з цього пристрою за допомогою бездротового налагодження.</string>
<string name="upd_block_no_apk">У цій збірці немає завантаження для цієї копії DroidDeck.</string>
+5
View File
@@ -644,6 +644,9 @@
<string name="perf_hostname">Tên máy chủ</string>
<string name="perf_hostname_hint">Tên mà Steam thấy cho thiết bị này. Để trống để khôi phục %1$s.</string>
<string name="perf_hostname_invalid">Chỉ chữ, số và gạch ngang ở giữa, tối đa 63 ký tự.</string>
<string name="perf_desktop_as_user">Màn hình nền chạy dưới dạng người dùng</string>
<string name="perf_desktop_as_user_hint">Màn hình nền, các ứng dụng và terminal của nó chạy dưới người dùng thường deck thay vì root, cho các ứng dụng từ chối root. sudo vẫn hoạt động. Áp dụng cho lần mở màn hình nền tiếp theo.</string>
<string name="perf_desktop_as_user_needs_native">Cần bật Chạy không cần proot.</string>
<string name="perf_phantom_warning">Android được đặt để tắt phiên này</string>
<string name="driver_installed">Đã cài</string>
<string name="driver_available">Có thể tải</string>
@@ -2422,6 +2425,8 @@
<string name="phantom_instructions_fix">%1$s Nếu không thể, hãy kết nối thiết bị này với một máy tính có ADB và chạy lệnh dưới đây. Quay lại đây và kiểm tra lại.</string>
<string name="phantom_instructions_off">Phiên Steam có thể khởi động.</string>
<string name="phantom_instructions_not_applicable">Phiên bản Android này không dùng giới hạn này.</string>
<string name="phantom_title_uncounted">DroidDeck xử lý giới hạn tiến trình con</string>
<string name="phantom_instructions_uncounted">DroidDeck chạy hầu hết các chương trình của phiên trong những tiến trình mà Android không tính, nên phiên luôn ở dưới giới hạn khá xa và có thể để tắt Tùy chọn cho nhà phát triển. Steam và một số tiến trình phụ trợ của nó vẫn được tính.</string>
<string name="phantom_fix_toggle">Bật “Tắt các mục hạn chế đối với tiến trình con” trong Developer options, và giữ Developer options luôn mở sau đó.</string>
<string name="phantom_fix_no_toggle">Phiên bản Android này không có công tắc cho việc đó. Dùng Gỡ lỗi qua mạng không dây để đổi nó từ thiết bị này.</string>
<string name="upd_block_no_apk">Bản build này không có tệp tải cho bản DroidDeck này.</string>
@@ -644,6 +644,9 @@
<string name="perf_hostname">主机名</string>
<string name="perf_hostname_hint">Steam 看到的本设备名称。留空恢复为 %1$s。</string>
<string name="perf_hostname_invalid">仅限字母、数字,连字符只能位于中间,最多 63 个字符。</string>
<string name="perf_desktop_as_user">桌面以普通用户运行</string>
<string name="perf_desktop_as_user_hint">桌面及其应用和终端以普通用户 deck 而非 root 运行,适用于拒绝以 root 运行的应用。sudo 仍可使用。下次启动桌面时生效。</string>
<string name="perf_desktop_as_user_needs_native">需要开启“不使用 proot 运行”。</string>
<string name="perf_phantom_warning">Android 将会终止此会话</string>
<string name="driver_installed">已安装</string>
<string name="driver_available">可下载</string>
@@ -2499,6 +2502,8 @@
<string name="phantom_instructions_fix">%1$s 如果无法做到,请将此设备连接到装有 ADB 的电脑并运行下方命令,然后返回此处重新检查。</string>
<string name="phantom_instructions_off">可以启动 Steam 会话了。</string>
<string name="phantom_instructions_not_applicable">此 Android 版本不使用该限制。</string>
<string name="phantom_title_uncounted">子进程限制由 DroidDeck 处理</string>
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不计数的进程中运行大部分会话程序,使会话远低于上限,因此开发者选项可以保持关闭。Steam 及其部分辅助进程仍会被计数。</string>
<string name="phantom_fix_toggle">在开发者选项中打开“停止限制子进程”,之后请保持开发者选项开启。</string>
<string name="phantom_fix_no_toggle">此 Android 版本没有该开关。请使用无线调试在此设备上更改。</string>
<string name="upd_block_no_apk">此构建没有适用于此 DroidDeck 副本的下载。</string>
@@ -644,6 +644,9 @@
<string name="perf_hostname">主機名稱</string>
<string name="perf_hostname_hint">Steam 看到的此裝置名稱。留空則還原為 %1$s。</string>
<string name="perf_hostname_invalid">只可使用字母、數字和中間的連字號,最多 63 個字元。</string>
<string name="perf_desktop_as_user">桌面以普通用戶執行</string>
<string name="perf_desktop_as_user_hint">桌面及其應用程式和終端機會以普通用戶 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。</string>
<string name="perf_desktop_as_user_needs_native">需要開啟「不使用 proot 執行」。</string>
<string name="perf_phantom_warning">Android 已設定為終止此會話</string>
<string name="driver_installed">已安裝</string>
<string name="driver_available">可供下載</string>
@@ -2419,6 +2422,8 @@
<string name="phantom_instructions_fix">%1$s 如無法這樣做,請將此裝置連接到已安裝 ADB 的電腦,並執行以下指令,然後返回這裡再檢查一次。</string>
<string name="phantom_instructions_off">可以啟動 Steam 會話。</string>
<string name="phantom_instructions_not_applicable">此 Android 版本不使用此限制。</string>
<string name="phantom_title_uncounted">子程序限制由 DroidDeck 處理</string>
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。</string>
<string name="phantom_fix_toggle">在開發人員選項中開啟「停用對子處理過程的限制」,之後請保持開發人員選項開啟。</string>
<string name="phantom_fix_no_toggle">此 Android 版本沒有此開關。請使用無線偵錯,直接在此裝置上更改。</string>
<string name="upd_block_no_apk">此版本沒有適用於此 DroidDeck 版本的下載。</string>
@@ -644,6 +644,9 @@
<string name="perf_hostname">主機名稱</string>
<string name="perf_hostname_hint">Steam 看到的此裝置名稱。留空可還原為 %1$s。</string>
<string name="perf_hostname_invalid">只能包含字母、數字和中間的連字號,最多 63 個字元。</string>
<string name="perf_desktop_as_user">桌面以一般使用者執行</string>
<string name="perf_desktop_as_user_hint">桌面及其應用程式和終端機會以一般使用者 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。</string>
<string name="perf_desktop_as_user_needs_native">需要開啟「不使用 proot 執行」。</string>
<string name="perf_phantom_warning">Android 已設定為結束此工作階段</string>
<string name="driver_installed">已安裝</string>
<string name="driver_available">可下載</string>
@@ -2419,6 +2422,8 @@
<string name="phantom_instructions_fix">%1$s 如果無法這麼做,請將此裝置連接到裝有 ADB 的電腦並執行下方指令,然後返回這裡重新檢查。</string>
<string name="phantom_instructions_off">可以啟動 Steam 工作階段。</string>
<string name="phantom_instructions_not_applicable">此 Android 版本不使用這項限制。</string>
<string name="phantom_title_uncounted">子程序限制由 DroidDeck 處理</string>
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。</string>
<string name="phantom_fix_toggle">在開發人員選項中開啟「停止限制子程序」,之後請保持開發人員選項開啟。</string>
<string name="phantom_fix_no_toggle">此 Android 版本沒有這個開關。請使用無線偵錯,直接在此裝置上變更。</string>
<string name="upd_block_no_apk">此組建版本沒有適用於此 DroidDeck 複本的下載檔案。</string>
+5
View File
@@ -678,6 +678,9 @@
<string name="perf_hostname">Host name</string>
<string name="perf_hostname_hint">The name Steam sees for this device. Blank restores %1$s.</string>
<string name="perf_hostname_invalid">Letters, digits and inner hyphens only, up to 63 characters.</string>
<string name="perf_desktop_as_user">Desktop runs as a user</string>
<string name="perf_desktop_as_user_hint">The desktop, its apps and its terminals run as the ordinary user deck instead of root, for apps that refuse root. sudo still works. Applies to the next desktop.</string>
<string name="perf_desktop_as_user_needs_native">Needs Run without proot.</string>
<string name="perf_phantom_warning">Android is set to kill this session</string>
<string name="driver_installed">Installed</string>
<string name="driver_available">Available to download</string>
@@ -2765,6 +2768,8 @@
<string name="phantom_instructions_fix">%1$s If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again.</string>
<string name="phantom_instructions_off">Steam sessions can start.</string>
<string name="phantom_instructions_not_applicable">This Android version does not use this limit.</string>
<string name="phantom_title_uncounted">Child-process limit handled by DroidDeck</string>
<string name="phantom_instructions_uncounted">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.</string>
<string name="phantom_fix_toggle">Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards.</string>
<string name="phantom_fix_no_toggle">This Android version has no switch for it. Use Wireless debugging to change it from this device.</string>
<string name="upd_block_no_apk">This build has no download for this copy of DroidDeck.</string>
@@ -81,4 +81,10 @@ class PhantomProcessLimitTest {
assertFalse(PhantomProcessLimit.hasDeveloperToggle(33))
assertTrue(PhantomProcessLimit.hasDeveloperToggle(34))
}
@Test
fun theLimitOnDoesNotBlockSteamWhenTheSessionStaysOutOfItsCount() {
assertFalse(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.UNCOUNTED))
assertTrue(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.ENABLED))
}
}
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -50,20 +49,4 @@ class LibraryArchTest {
val second = AddedGames.Game(other, "Other", File(other, "Other.exe"), "/g/Other.exe", "/g", 0x81234567L, (0x81234567L shl 32) or 0x02000000L, emptyList())
assertEquals(listOf("Example" to "internal", "Other" to Library.ADDED), Library.launchableGames(app, added = listOf(added, second), arch = "arm64").map { it.name to it.library })
}
@Test fun anotherProgramPickedInASteamGamesFolderIsListedBesideTheSteamGame() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setSteamClientArch(app, "arm64")
val apps = File(SessionPrefs.steamRoot(app, "arm64"), "steamapps").apply { mkdirs() }
val folder = File(apps, "common/Example").apply { mkdirs() }
val main = File(folder, "Example.exe").apply { writeBytes(ByteArray(16)) }
val launcher = File(folder, "ModLauncher.exe").apply { writeBytes(ByteArray(16)) }
File(apps, "appmanifest_42.acf").writeText("\"AppState\"\n{\n\t\"appid\"\t\t\"42\"\n\t\"name\"\t\t\"Example\"\n\t\"StateFlags\"\t\t\"4\"\n\t\"installdir\"\t\t\"Example\"\n}\n")
fun listed() = Library.launchableGames(app, arch = "arm64").map { it.library to it.gameFiles }
assertTrue(AddedGames.addExe(app, launcher) is AddedGames.AddResult.Added)
assertEquals(listOf("internal" to folder, Library.ADDED to folder), listed())
assertTrue(AddedGames.addExe(app, main) is AddedGames.AddResult.Switched)
assertEquals(listOf("internal" to folder), listed())
}
}
@@ -44,6 +44,40 @@ class ElfSeccompPatchTest {
}
}
@Test
fun terminalRequestsUseTheOnesAndroidAllowsOnAPseudoTerminal() {
// glibc 2.43's tcsetattr: TCSETS2 into x0, TCGETS2 into x1, with an unrelated instruction between
val data = elfWith(
0xd28a8560.toInt(), 0x910123e2.toInt(), 0xf2a80580.toInt(),
0xd28a8541.toInt(), 0x93407ea0.toInt(), 0xf2b00581.toInt(),
0x528a85a3.toInt(), 0x72a80583.toInt(),
)
assertEquals(3, ElfSeccompPatch.patch(data))
val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
val nop = 0xd503201f.toInt()
assertEquals(0xd28a8040.toInt(), b.getInt(0x100)) // mov x0, #0x5402 (TCSETS)
assertEquals(nop, b.getInt(0x108))
assertEquals(0xd28a8021.toInt(), b.getInt(0x10c)) // mov x1, #0x5401 (TCGETS)
assertEquals(nop, b.getInt(0x114))
assertEquals(0x528a8083.toInt(), b.getInt(0x118)) // mov w3, #0x5404 (TCSETSF)
assertEquals(nop, b.getInt(0x11c))
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun aLookalikeConstantIsLeftAlone() {
// 0x542a with another high half, and one whose high half goes to another register
val data = elfWith(0xd28a8541.toInt(), 0xf2a00021.toInt(), 0xd28a8541.toInt(), 0xf2b00582.toInt())
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun aSiteWhoseRegisterIsReadBeforeTheHighHalfIsLeftAlone() {
// movz x1, #0x542a; add x2, x1, #1; movk x1, #0x802c, lsl #16; movk x2, #0x402c, lsl #16
val data = elfWith(0xd28a8541.toInt(), 0x91000422.toInt(), 0xf2b00581.toInt(), 0xf2a80582.toInt())
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun otherSystemCallsAreLeftAlone() {
val svc = 0xd4000001.toInt()
@@ -80,6 +80,24 @@ class OrientationTest {
assertFalse(SessionPrefs.portrait(landscape))
}
@Test fun modeOrientationControlsWindowFollowAndPortraitResolution() {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM))
SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_USER)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, false, 400, SessionService.MODE_RUN))
val config = android.content.res.Configuration(context.resources.configuration)
config.orientation = android.content.res.Configuration.ORIENTATION_PORTRAIT
val portrait = context.createConfigurationContext(config)
config.orientation = android.content.res.Configuration.ORIENTATION_LANDSCAPE
val landscape = context.createConfigurationContext(config)
assertTrue(SessionPrefs.portrait(portrait, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.portrait(landscape, SessionService.MODE_STEAM))
assertTrue(SessionPrefs.portrait(landscape, SessionService.MODE_DESKTOP))
}
@Test fun invalidLauncherOrientationFallsBackAndInvalidChoicePreservesPreference() {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", 999).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context))
@@ -88,4 +106,20 @@ class OrientationTest {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context))
}
@Test fun steamAndDesktopOrientationsAreIndependentAndFallBackToLegacyChoice() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "steam"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "desktop"))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
SessionPrefs.setOrientation(context, "desktop", ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, "steam"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_STEAM))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_RUN))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, "desktop"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_DESKTOP))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.orientation(context))
}
}
+569
View File
@@ -0,0 +1,569 @@
# Android's child-process limit without developer options
Research log for removing DroidDeck's requirement to turn off "Restrict child processes" (or run
`settings put global settings_enable_monitor_phantom_procs false` over wireless ADB). The goal:
Android must not kill a Steam session for having too many Linux processes, and the user must not
need developer options.
Status: **working on the AYN Thor (Android 13).** With Android's limit on and no developer option,
a Steam session with a game running keeps 12 processes in the app's counted cgroups (63 without
this work), and Android killed nothing in minutes of forced scans. DroidDeck's Setup reports the
limit as handled and no longer blocks Steam. Both counting gaps below are in identical code on
Android 12 through 16; a stock Android 14+ phone is still to be tested. The experiments are in
`tools/phantomlab` (see the end).
## How Android counts and kills
Source: `frameworks/base/services/core/java/com/android/server/am/PhantomProcessList.java`
(android12-release to android16-release and main; the parts below are unchanged across them).
1. **What is counted.** For every app process AMS knows (`mPidsSelfLocked`),
`lookForPhantomProcessesLocked(app)` reads
`/sys/fs/cgroup/uid_<app.info.uid>/pid_<pid>/cgroup.procs` (`/acct/...` on cgroup v1). Every
pid listed there other than the app process itself is a "phantom process". `cgroup.procs`
lists thread-group ids, so threads never count.
2. **What is skipped.**
- `if (app.appZygote || app.isKilled() || app.isKilledByAm()) return;`. `appZygote` is true
for uids in `FIRST_APP_ZYGOTE_ISOLATED_UID..LAST_APP_ZYGOTE_ISOLATED_UID` (90000–98999),
i.e. every process forked from an app zygote (`ProcessRecord` constructor).
- A pid that is itself an app process (`mPidsSelfLocked.get(pid) != null`).
- A pid whose `/proc/<pid>/cmdline` cannot be opened, whose uid cannot be read, or for which
`pidfd_open` fails. These only happen once the process is gone (an empty cmdline reads as
`""`, not `null`, so it is still counted).
3. **When.** Only after AMS refreshes CPU stats (`AppProfiler.updateCpuStatsNow` →
`updateProcessCpuStatesLocked`), at most every 5 s (`MONITOR_CPU_MIN_TIME`), and only when
something asks for it: activity and process lifecycle events, mostly. Also from
`setProcessGroupForPhantomProcessOfApp` when an app changes scheduling group. A new phantom
schedules `trimPhantomProcessesIfNecessary`.
4. **The kill.** When the device-wide total exceeds `max_phantom_processes` (32), phantoms are
sorted by their app's oom adj (most important first), then youngest first, and the surplus is
killed from the end of that list (`SIGKILL` and `killProcessGroup`): the least important app's
oldest processes go first. As the foreground app, other apps' phantoms go first, so the
practical budget is our own 32, and of ours the **oldest** die first: the session's PipeWire,
D-Bus and Steam itself, not the game that pushed the count over.
5. **The second killer.** `ActivityManagerService.updatePhantomProcessCpuTimeLPr`: when the app is
at `PROCESS_STATE_HOME` or below (backgrounded, no foreground service) and a phantom used
"excessive" CPU, `killPhantomProcessGroupLocked` kills every phantom of that app **and the app**.
`settings_enable_monitor_phantom_procs=false` (the developer option) switches off both on Android
12L and later; Android 12 does not have the setting, and there only the `device_config` limit below
applies. Raising
`max_phantom_processes` through `device_config` (shell only) avoids only the first: the
excessive-CPU check still runs while monitoring is on.
Today an idle Steam session is about 30 processes and a session with a game about 45 (#566, #575).
## Gap 1: an isolated process's children are never counted
Two independent reasons, either of which is enough:
- **Wrong cgroup path.** The path is built from `app.info.uid`, the *package's* uid (10148 here),
but an isolated process runs as its own uid (99000+ for `android:isolatedProcess`, 90000+ from an
app zygote) and its cgroup is `uid_<isolated uid>/pid_<pid>`. The lookup finds nothing
(`FileNotFoundException`, logged only with `DEBUG_PROCESSES`) and the process is skipped.
- **App zygote skip.** Processes forked from an app zygote (`android:useAppZygote="true"`) are
skipped outright by the `app.appZygote` check, by design ("doesn't have its own acct entry").
This one survives even if Google fixes the path.
Measured with `max_phantom_processes=4` and monitoring on, children killed by Android:
| Where the children were forked | Children | Thor (Android 13) | Emulator (Android 15) |
|---|---|---|---|
| Main app process (control) | 10 | 6 ("Trimming phantom processes") | 6 |
| plain `isolatedProcess` service (uid 99000+) | 10 | 0 | 0 |
| `isolatedProcess` + `useAppZygote` service (uid 90000) | 40 | 0 | 0 |
`cgroup.procs` of `/sys/fs/cgroup/uid_90000/pid_<service>` held all 41 pids the whole time; the
phantom list (`dumpsys activity processes`, "All Active App Child Processes") only ever showed the
main process's children. With the limit at 4, the Thor also trimmed another app's `logcat` child,
as expected for the device-wide count.
## Gap 2: a process that execs in place is an app process, not a phantom
An `android:process` service process can `execve()` a Linux program in place. If it first clears
`FD_CLOEXEC` on its binder fd, the binder node stays alive, so AMS never sees the process die. The
pid stays in `mPidsSelfLocked` and is never counted. Its own children are counted as usual.
Same results on the Thor and the emulator:
| Worker `:wN` | Result |
|---|---|
| exec `/system/bin/sleep`, binder fd closed by exec (control) | "has died" at once; AMS restarts the service |
| exec `/system/bin/sleep`, binder fd kept | stays `fg`/`(service)` while bound; survives a density change, `am send-trim-memory`, Home/back cycles |
| exec `sh` forking 6 `sleep`s, binder fd kept | `sh` not counted; its 6 children counted (2 trimmed at limit 4) |
| guest exits (killed) | AMS logs "has died" and removes the cgroup, as for any app process |
Calls AMS makes into the process after the exec fail cleanly: the kernel logs
`binder_alloc_buf, no vma` and AMS gets `DeadObjectException` ("Failed for dead process.
ClientTransactionItem=ConfigurationChangeItem", "Remote exception" for trim). Nothing kills the
process for it. It is frozen like any cached process when the app goes to the background without a
foreground service.
## What else was tried
| Idea | Result |
|---|---|
| Move a process to another cgroup (`cgroup.procs` of root, of `uid_N`) | `EACCES`: dirs are `system:system 0775` and SELinux denies `cgroup_v2` writes to apps |
| Make a sub-cgroup under our `pid_N` (children of a sub-cgroup are not in its `cgroup.procs`) | `EACCES` |
| `clone3(CLONE_INTO_CGROUP)` | apps cannot open `/sys/fs/cgroup` (SELinux `read` denied) |
| `unshare(CLONE_NEWUSER)` / `CLONE_NEWCGROUP` | `EINVAL` (no user namespaces in GKI) / `EPERM` |
| Empty `/proc/<pid>/cmdline` | read as `""`, still counted; changing it needs `PR_SET_MM` (`CAP_SYS_RESOURCE`) |
| Run "processes" as threads (`CLONE_THREAD`) | only with a shared address space; Steam, Chromium and Wine rely on real processes |
| More `android:process` services hosting the tree | each process's children are still phantoms; only the process itself is free (Gap 2) |
| Rely on kill order | we are the foreground app, so our own newest processes die first |
## What an isolated process can do
Measured from both isolated variants (domain `isolated_app`) against the normal app
(`untrusted_app`), with fds created by the app and passed over binder:
| | app | isolated |
|---|---|---|
| `fork` | ✅ | ✅ (children uncounted) |
| `execve` of an executable in the APK's lib dir (as `libddexec.so`) | ✅ | ✅ |
| `execve` of `/system/bin/*` | ✅ | ✅ |
| create `AF_INET` socket | ✅ | ❌ `EACCES` |
| `connect`/`send`/`recv` on a TCP or UDP socket the app created | ✅ | ✅ (policy: "network sockets received over IPC") |
| read/write a passed unix stream socket / pipe | ✅ | ✅ |
| `open()` an app data file by path | ✅ | ❌ `ENOENT` (not mounted) |
| read/write/`mmap` a passed app data file | ✅ | ✅ |
| `mmap(PROT_EXEC)` of a passed app data file | ✅ | ❌ `EACCES` |
| receive a passed directory fd | ✅ | ❌ (binder refuses the transaction) |
| `mmap(PROT_EXEC)` of a memfd, anonymous RWX (JIT) | ✅ | ✅ |
| GPU device (`/dev/kgsl-3d0`, `/dev/mali0`) | ✅ | ❌ (`neverallow`, also for passed fds) |
| signal or read `/proc` of the app's processes | ✅ | ❌ (`EPERM`, `EACCES`) |
This table is the emulator (stock, enforcing policy). **The Thor's ROM runs `isolated_app`
permissive** (every isolated denial logs `permissive=1`; `untrusted_app` is enforcing): there an
isolated process could also create inet sockets and open `/dev/kgsl-3d0`. That is an AYN quirk and
must not be relied on; design for the enforcing column.
Isolated processes can talk to each other through abstract unix sockets. Everything else in the
app's world (files, sockets to the app's servers, the GPU) has to be brokered through fds.
## Routes
### A. An isolated tier for everything that does not touch the GPU
Run a session's GPU-free processes inside one app-zygote isolated service; their whole fork tree is
invisible. Needed:
- **Loader:** `libddexec.so` already starts programs without the kernel loading them; it would take
its ELF from an inherited fd and copy segments into anonymous or memfd memory, since isolated
processes cannot map app files executable. A broker can hand out one sealed memfd per library so
pages stay shared.
- **File broker:** the native hook already funnels path calls through `rewrite_path`; in the
isolated tier those calls become requests to a broker in the app, which opens the file and returns
the fd. Directories cannot be passed, so `opendir`/`getdents` are served from listings.
Raw syscalls (Wine's preloader, FEX internals) need a seccomp `SIGSYS` trap, which the hook
already uses for Android's own filter.
- **Sockets:** `socket(AF_INET*)` → broker-created socket; then the process connects itself.
Unix sockets between isolated processes become abstract sockets; connections to servers in the
app (compositor, PipeWire, VkBridge) are connected by the broker.
- **No signals across the boundary:** a process and everything it signals or ptraces must be on the
same side. Wine's processes all depend on `wineserver` signalling them, so Wine stays with the game.
- **GPU:** only through a remoting layer such as VkBridge (already used on Mali), never directly.
Candidates for the tier: the Steam client and its web helper's renderer/utility processes (with
the web helper's GPU work remoted or in software), the session scripts, D-Bus services, PipeWire
helpers, Python daemons. A cross-tier launch (Steam starting the game's `reaper`) runs through the
broker, with a small stand-in process left in the tier for Steam to wait on. Stand-ins are free
there.
### B. Exec-in-place workers for long-lived processes
Declare a pool of `android:process` services (`:g0`…`:g95`). Each long-lived program runs as the
main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc`
(same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits:
- A worker is a zygote fork (~100 ms); a pre-started pool removes the wait.
- Only the worker's main process is free; its children count. So each long-lived program must be
started in its own worker, not forked by its parent.
- Programs the app or the session script start and do not wait on (Xwayland, D-Bus, PipeWire,
helpers, `wineserver -p`) can move with a `droiddeck-spawn` client and no other change.
- A program another guest forks and waits on (Wine's processes, Steam's children) needs the hook to
hand the exec to a worker and translate the pid for the parent: `wait4`, `kill`, `/proc/<pid>`,
`SIGCHLD`. All app processes share zygote's session (sid 0, pgid of zygote), so `setpgid` and
process-group signals across workers are possible.
- Relies on AMS never pinging a process; today it only sends oneway calls that fail harmlessly.
### Measured on the Thor: a real session
An idle Steam session (Big Picture at the library, Decky on, 0.7.11 / main `b08d8e8e1`) holds
**48 counted processes** in the app's cgroup, well past 32 before any game starts:
9 bash, 6 python3, 5 dbus-daemon (with the portals and at-spi under the session bus), 4 Decky
PluginLoader, 4 steamwebhelper, 2 Xwayland, gamescope and its reaper, PipeWire and WirePlumber,
Steam, the clipboard bridge, and the app's own logcat, PulseAudio and audio relay.
Prototype of B on this branch (`runtime/GuestWorkers.kt`, `droiddeck-spawn`, `dd_spawn` in the
session script; `DD_SPAWN_DAEMONS=0` turns it off): 24 `:gN` worker services, a spawn socket in the
app, and the session script starting the clipboard bridge, the system bus, login1 and the session
bus through it. Result:
- Each of the four runs as its own app process (`/sys/fs/cgroup/uid_<app>/pid_<worker>` with one
process). login1's sleep handshake, NetworkManager (state 70, full connectivity) and the Steam
library all work.
- Counted processes: **45** instead of 48. The session bus took its 9 activated children with it, so
they are still counted, under its worker.
So starting top-level daemons in workers is not enough. What is left is the processes other
programs start. Of the 47 counted processes in that session, **40 are exec'd programs** and only 7
are forks without an exec (the session script's `( … ) &` subshells). A handoff inside the native
hook, at `execve()` in a forked child, could move all 40, leaving about 7 counted at idle. That needs
the pid translation described in B (the parent keeps the forked pid; `wait4`, `kill`, `SIGCHLD` and
`/proc/<pid>` go to the worker's process).
### Handoff in the native hook (prototype, on this branch)
`tools/nativeguest/hook/handoff.c`. At `execve()` in a forked child, a program named in
`DD_HANDOFF` is sent to the app's spawn socket instead of exec'd: the request carries argv, the
environment, the working directory and every inheritable fd with its number, and a worker execs
the program with those fds in place. The child records "my pid is now worker pid P" in a memfd
table its parent created, and exits. In the parent, `wait4`/`waitpid`/`wait`/`wait3`/`waitid` and
`kill` treat the forked pid as P until P exits. P's hook writes its exit status into the table; for
a program that ends without `exit()` (a signal) the app writes a report tagged with the child it is
for (from `ApplicationExitInfo`), which the parent's hook takes once P is gone, and sends the parent
`SIGCHLD`. Only the hook moves an entry to "exited", by compare-and-swap. A launch takes three
answers: the hook's "go" once it has P's pid, the worker's answer to the app's commit, and the
app's "ok" once the worker runs the program; without any of them the program runs locally instead,
never twice. The child's side is
vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
- **Scripts:** the list also matches the `#!` interpreter (`python3` for `droiddeck-agent`).
- **Exec chains:** a forked child that first execs a wrapper (`env`, `taskset`, a shell script,
Wine re-executing itself through `wine-preloader`) keeps its parent's table fd across the exec,
so the wrapper's own exec can still be handed off.
- **Not handed off:** Steam and the web helper's browser process (gamescope finds a window's app by
walking its process's parents) and its utility processes (the client refuses its transport —
"no transport is available" — from processes that are not its children). The web helper's
renderers hand off fine.
- **Game windows outside the reaper:** gamescope finds a window's app by walking its process up to
Steam's `reaper`, which a handed-off Wine process is not under. Proton sets `STEAM_GAME` itself
from `SteamGameId`, but a store game's is a 64-bit id and is not set: Splinter Cell (Ubisoft)
ran without ever taking focus. The agent now tags such a window from its process's `SteamAppId`
also on the arm64 client.
- One-shot programs cost a worker start (~100 ms) each, so the list names long-lived programs only
(`xprop+-spy`: `name+prefix` matches only when an argument starts with prefix).
- **Near the limit, a shell's children too.** Once 20 of the app's processes are counted (the hook
counts them in `/proc`: this uid's processes in an app process's cgroup other than that process),
a child of `bash`, `sh`, `dash`, `zsh`, `ksh`, `fish`, `make` or `xargs` is handed off even when
it is not listed. Those parents wait with `wait()`, which the hook answers; Qt's `QProcess` and
other parents that watch a child by pidfd or `/proc` would see the forked child end at once, so
their children stay. A job in the foreground of its controlling terminal (`TIOCGPGRP` on
`/dev/tty`, whatever its standard fds are: `cmd | less`, `less < file`) stays too: a handed-off
program has no controlling terminal, so `/dev/tty`, ^C and job control would miss it. A job a
shell with job control runs (any process group other than the shell's, `cmd &` in an interactive
terminal, each member of its pipeline) stays as well: the shell waits for its stops and continues,
which happen to a handed-off program's worker and never reach that wait. A job started with `&`
from a shell without job control (a script, `bash -c`) runs in the shell's group reading
`/dev/null`, and goes. Steam's client and launch chain (`steam`, its
web helper, `droiddeck-steam-x64`, `reaper`, `steam-launch-wrapper`, `pw-audio-namespace`,
gamescope, anything under `Steam/`) never go this way. In the desktop
session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at
61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and
at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a
`make -j` and its compilers), the D-Bus daemon's activation helpers (forks that never exec) and
the desktop's own programs started by KDE's launchers.
Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's
`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`.
Measured on the Thor, same session and game as above:
| | counted children, idle | counted, Bully (Proton) running |
|---|---|---|
| main, no handoff | 48 | 63 |
| handoff | **26** | **29** |
With the handoff on, Bully reached its menu at 30 fps, kept focus, and Steam's library, Decky, the
portals, NetworkManager/login1 and the agent all worked.
Then Android's own limit was switched back on (`settings_enable_monitor_phantom_procs=true`,
default limit 32) with the game running, and a scan was forced every 20 s for 3 minutes
(`dumpsys meminfo` refreshes the CPU stats the scan runs on; process starts and activity changes do
too, irregularly):
| | Android listed | killed | session |
|---|---|---|---|
| no handoff (`DD_SPAWN_DAEMONS=0`, same build) | 63 | **33**, oldest first: the session's bash, Python daemons, D-Bus, Xwayland, Steam, PipeWire, gamescope's reaper | FAILED |
| handoff | 27–29 (device-wide) | **0** in 9 scans | game running throughout |
### Taken further: the session itself in workers
A second round moved most of what was still counted:
- **The app's own processes:** `HostProcess.startUncounted` runs a host command in a worker with the
same contract as `HostProcess.start` (output lines, exit code, working directory). The session
root, the app log's logcat, PulseAudio and the DirectAudio relay use it. A worker cannot `chdir`
before its exec, so Android's `sh` does it from an environment of its own and exports the
program's (`env -i` cannot be used: the APK's library path contains `==`).
- **PulseAudio** closes every inherited fd at start, the worker's binder fd included, and Android
then killed the worker as dead (the SIGKILL came from system_server's `ActivityManager` thread,
seen with the `signal_generate` ftrace event, which shell can enable on the Thor). The daemon
spares the fd named in `PULSE_PASSED_FD`; the worker replaces `@DDH_WORKER_BINDER_FD@` in a
program's arguments and environment with its `/dev/binder` fd number, so PulseAudio is given it.
Started as a normal child the token reads as fd 0, which the daemon ignores.
- **The script's long-lived subshells:** `dd_job FUNCTION` runs a function in a new `bash` that first
loads the shell's variables, functions and options from a state file, so it is an exec'd program
the hook can hand off (`bash+dd-job`). `$!`, `kill` and `wait` keep working. The zRAM scanner,
the property watcher, Decky's supervisor and the request/timer loop use it.
- **The log pipeline** is `droiddeck-log-writer`, a script of its own instead of a `{ gnudd; cat; }`
subshell.
- **gamescope, its reaper and the inner `droiddeck-session steam`** are handed off. Steam, its web
helper's browser process and its utility processes still are not (see above).
Things this needed, found the hard way:
- **The binder fd is the worker's life.** It sits above every fd number the program gets; programs
that close all inherited fds (gamescope) are kept from closing it (the hook's kept fds, also
against `CLOSE_RANGE_CLOEXEC`); children never send it along with a handoff; and the hook closes
copies in every other process (`DDH_WORKER_PID`), so a worker's exit is seen when its program
exits. A worker that lost its binder fd was killed by Android within milliseconds.
- **A session of its own (`setsid`) for every worker.** All app processes are in zygote's process
group, so a program signalling its group reached the app itself (the hook also refuses
`kill(0)`/`kill(-pgid)` into zygote's group, and `kill(-1)`). `reap_orphans` in the session
script stands down when its parent is zygote.
- **Nested handoffs** (a program in a worker handing off its own child): inherited `DDH_*`
variables are dropped from each request.
- **Requests carry up to 240 fds,** in chunks of 60 (`LocalSocket` reads at most 64 per read), after
the request itself; the spawn server catches everything per connection (an uncaught exception there
took the whole app down once).
- **The table is made at a process's first fork,** not only when `DD_SPAWN` is in its environment at
start: a shell that exports it has no sign of it in its own environment.
- **Exit status:** the program's hook records it with `on_exit` or in `_exit()` into the parent's
table; the app's `ApplicationExitInfo` is only the fallback (signals). A program inherits its
forked parent's ignored signals, open-files limit and umask (`DDH_SIGIGN`, `DDH_NOFILE`,
`DDH_UMASK`).
Measured on the Thor, Bully under Proton, Android's limit on (default 32), a scan forced every 20 s:
| | counted, idle | counted, in game | killed in 3 min |
|---|---|---|---|
| main (no handoff) | 48 | 63 | 33, session failed |
| first round | 26 | 29 | 0 |
| second round | 9 | 14 | 0 |
| **third round** | **7–9** | **12** | **0** in 2 min, game kept focus |
Still counted at idle: `run_gamescope`'s subshell, Steam, its web helper's browser and
two or three utility processes, the session bus's activation babysitter and Decky's
multiprocessing child (forks without an exec). In game, also Steam's launch chain (`sh`,
`pw-audio-namespace`, `reaper`) and the `wineserver` daemon (a fork of its first process, which
lingers in its worker; see below).
### Third round
- **PulseAudio in a worker** (above).
- **`posix_spawn()`:** Python 3.13+ (`subprocess`, even with `close_fds`) and GLib's `g_spawn` start
programs with `posix_spawn()`, whose child makes the exec system call itself, past the hook. A
listed program is now spawned with `fork()` and the hook's `execve()`; the hook replays glibc's
file actions and attributes in the child, and a close-on-exec pipe returns an exec error as
`posix_spawn()`'s result. Proton's Wine and at-spi's bus came out of the count this way.
- **The table fd survives a child that closes every inherited fd** (Python's `subprocess` before
exec): it sits at fd 800 or above and is one of the hook's kept fds. Reopening it from
`/proc/<owner>/fd` does not work on Android (EACCES). A nonce in the table's header tells it from
a file a program put at that number (inode numbers are rewritten by the hardlink emulation).
- **The exit status comes from the program itself.** The worker first runs a `bash` that `cd`s and
execs the program; that `bash` closed the `DDH_TABLE` fd as someone else's table, so the
program after it could never report, and statuses came from `ApplicationExitInfo`, late or
unknown. The `DDH_TABLE` fd is now kept through that exec, and `_exit()` reports as `exit()` does.
- **Daemons:** Android kills every process in a worker's cgroup when the worker's own process ends
(`libprocessgroup: Successfully killed process cgroup`). `wineserver` forks the server and leaves
with `_exit(0)`, so the server died with it and Wine stopped with "the wine server failed to run".
A handed-off program's process now reports its status and then stays, with no fds but the
binder's and all signals blocked, until no other process is left in its cgroup (found through
`/proc/<pid>/cgroup`, as `cgroup.procs` is not readable). It does so only when it is
single-threaded at exit, and never for the processes the app starts itself (the session root),
whose exit the app waits for.
- **`reap_orphans`** in the session script killed every process whose parent was zygote (all the
app's workers, the session root among them) when the inner `droiddeck-session` ended in a
worker: the guest cannot see zygote in `/proc`. It now stands down when `DDH_WORKER_PID` is
its own pid.
- **`DD_HANDOFF_DEBUG=/path`** appends the hook's trace to a file. On stderr it broke Steam's
login, and the trace from a game's processes went to a pipe nobody read.
- **Finding the sender of a SIGKILL:** shell can enable the `signal/signal_generate` ftrace event
on the Thor (`/sys/kernel/tracing`), which names the sending thread; Perfetto recorded nothing
there.
- **Ending a game from Steam** (`SteamClient.Apps.TerminateApp`, the overlay's Exit game) left Wine
running since the first round: Steam sends SIGINT to the launch's `reaper` and its parent, and the
reaper ends what is under it, which handed-off programs are not. Each handed-off program now
lists itself as `P<pid>` with the process that forked its child and, for when that process is
gone (Wine starts a process through a fork that exits at once), the worker's program it descended
from. A signal to `reaper SteamLaunch` from a hooked process also goes, as SIGTERM for SIGINT
(Wine takes SIGINT for a console's Ctrl+C), to the groups of every listed program under that
reaper, all found before any is signalled.
- **Process groups:** a handed-off program runs in a session of its own, outside the group its
forked parent's child was in. It lists itself as `GROUP.PID.START` for that group (`DDH_PGID`,
also for the processes it forks), and the hook's `kill(-GROUP)`, `kill(0)` and `killpg()` also
signal the groups those programs lead.
- **Tried and dropped:** handing off Steam's launch chain (`sh`, `steam-launch-wrapper`, `reaper`):
the client tracks the process it forked, which then exits at once, and called the game closed.
Showing a handed-off program's forking process as its parent in `/proc/<pid>/stat` and `status`
left Steam's UI at "Loading library data": the client checks the parents of the processes on its
IPC connections with `lsof -F R`. Only the program's own `getppid()` answers with that process
(while it lives, then 1): the GOG launch leases the game folder for as long as the launcher, its
parent, runs, and took zygote, which the guest cannot see, for a launcher already gone. And
`posix_spawn()` emulation must make only
system calls in its child (no hook wrapper takes a lock there): one Steam fork hung on a lock
another thread held.
Quitting the game (also from Steam), stopping the session (no worker is left) and starting
again all work. Started from the front end with the limit on, Setup shows "Child-process limit
handled by DroidDeck" and Steam starts.
### The bionic runtime
DroidDeck-Bionic runs Wine on Android's libc, outside the glibc root, so the native hook never sees
its processes: with the handoff on, a bionic game's Wine programs (the game, `services.exe`,
`winedevice.exe`, `plugplay.exe`, `svchost.exe`, `lsass.exe`, `explorer.exe`, `rpcss.exe`) all stayed
under the worker that runs the tool's `launch.sh` and were counted. The same handoff is built into
the runtime's exec shim (`tools/bionic-runtime/handoff.c`, part of `libexecshim.so`, which every Wine
process preloads): it includes `hook/handoff.c` and `hook/kept.c` (the descriptors `close()` and
`close_range()` leave open, moved out of `privileged.c` for this) and adds what the native hook's
other parts do around them (`fork()`, `close()`, `close_range()`, `dup2()`, `dup3()`, and `exit()` for
the `on_exit()` bionic lacks). What differs on bionic:
- **bionic's `execv()`, `execvp()` and `execl*()`** make the execve system call inside libc, past an
interposed `execve()`. Wine starts its preloader with `execv()`, so the shim defines them on top
of its `execve()`.
- **A start through the system linker** (`/system/bin/linker64 PROGRAM ARGS`, which the shim makes
of a dynamic program in app data, and which Wine sometimes makes itself) is listed by PROGRAM
(`ddh_try_as()` matches one program and sends another).
- **The app starts a handed-off program from the glibc root's `bash`** (GuestWorkers), which cannot
load the runtime's `LD_PRELOAD` and `LD_LIBRARY_PATH` (bionic libraries: "libdl.so: cannot open
shared object file"). The request carries those two as arguments of `/system/bin/env` instead,
which `bash` execs and which puts them back for the program; the worker's main process is the
program all the same.
- `launch.sh` keeps `DD_SPAWN`, `DD_SPAWN_SESSION`, `DD_HANDOFF*`, `DDH_*` and `DDNATV_ROOT` (it drops
the glibc guest's environment otherwise). The "can't open /proc/N/environ: Permission denied"
lines its prefix checks printed came from idle workers (zygote forks, not dumpable), not from
handed-off programs, which are readable; the redirect is now quiet.
Measured on an AYANEO Pocket FIT (Snapdragon G3 Gen 3, Adreno 750, Android 14), DroidDeck-Bionic 14.1-r67 with this shim and
launcher, handoff on, max counted in the app's cgroups:
| | Brawlhalla | DiRT Showdown | whole run | other apps' processes trimmed (limit on) |
|---|---|---|---|---|
| bionic, before | 25 | 24–27 | 28 | yes (Discord, a logcat, BatteryLog's `su`) |
| bionic, with the shim | 17 | 16 | 19–20 | none |
| DroidDeck-Proton 11-14.2 | 12–13 | 12–15 | 15–17 | none |
DiRT's benchmark held 75 fps average either way; quit through Steam, stop and restart worked with
Android's limit on, with no DroidDeck process killed. Still counted on bionic: what `launch.sh`
itself starts (the game's first Wine process, `gstag`, the wait loop's `sleep`), since Android's
`sh` has no hook, and `wineserver`'s daemon fork.
### Cost
Measured on the Thor, Bully under Proton, the handoff on (`childProcessHandoff`) against off, two
sessions each:
| | off | on, first | on, now |
|---|---|---|---|
| one program started, `fork`+`exec` of `/usr/bin/true` | 37–39 ms | 197 ms | 80 ms |
| `start steam` to READY | 14.0–14.2 s | 20.0–20.2 s | 18.2–18.5 s |
| `launch` to the game's focus | 10.1 s | 14.7–14.8 s | 11.6–11.7 s |
| in game: frames, CPU of the app's uid, `system_server` | 29.9 fps, 1.02–1.05 s/s, 21 ms/s | 29.8 fps, 1.11 s/s, 21–27 ms/s | 29.8–29.9 fps, 1.10–1.11 s/s, 22 ms/s |
| memory of the app's processes (RSS) | 3.57–3.62 GB | 3.42–3.50 GB | 3.49–3.66 GB |
Running costs nothing measurable; starting things does. A handed-off program costs a worker: a
zygote fork, its runtime (40–50 ms of CPU) and the bind, and the worker waited 100 ms before its
exec so as not to cut off its reply. Now the app closes a pipe once it has the reply and the worker
execs then, and two workers are kept bound ahead of need while a session runs (12 MB of PSS each);
four did no better. Starting a session takes about 10 more CPU-seconds (51 s against 41 s for the
app's uid), and the last 4 s come from the session script's own steps running beside the
handed-off daemons. With only the hook's handoffs off (`DD_SPAWN_DAEMONS=0`), READY came at
14.1 s: the app's own workers (the session root, PulseAudio, logcat) cost nothing there.
**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`, with
Setup > Developer > Debugging tools on; see `docs/agent-control.md`) brings back
the old behavior and the old requirement.
### C. Plan
1. ~~Verify both gaps on the Thor~~ done; still to do on a stock Android 14+ phone (enforcing
SELinux, unlike the Thor) and on a Mali device.
2. ~~B for the processes DroidDeck and the session script start themselves~~ done.
3. ~~B inside the hook, with pid translation~~ done.
4. ~~The session root, its jobs, the log pipeline, the gamescope chain~~ done: 9 idle, 14 in game.
Third round (PulseAudio, `posix_spawn`, daemons): 7–9 idle, 12 in game.
5. ~~Setup no longer requires the developer option while the session runs in workers~~ done.
6. Open:
- ~~PulseAudio in a worker~~ done;
- ~~`posix_spawn()` and daemons in workers~~ done;
- `/proc/<pid>/stat` showing the virtual parent, so that Steam and its web helper can be handed
off too;
- ~~pre-started workers, so that a handoff costs no zygote fork~~ done: two are kept bound;
- ~~more games and configurations~~ done on the Thor with the stock limit on, no kills in any:
Bully on GE-Proton, Proton Experimental ARM64 and DroidDeck-Proton 11 (11–14 counted), Bomb
Rush Cyberfunk (14), MGSV Ground Zeroes (13), Sekiro (13), zero-copy off (11), the x86-64
Steam client under FEX (14, against 55 without the handoff), Splinter Cell through Ubisoft
Connect (14, against 65), Star Wars: Galaxy of Heroes (EA, 14), 9 Years of Shadows (GOG, 14),
run mode with 40 background jobs (1), the desktop at rest (17–20) and
with a terminal's 40 background jobs (20). PRoot sessions keep the old behavior and still need
the developer option: with the limit on, Android killed 30 of their processes and the session
failed;
- Wine-heavy launchers and anti-cheat;
- a settings switch for `childProcessHandoff`.
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
broker and keeps the GPU outside.
## Robustness
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
zygote isolated services so either one is enough.
- Gap 2 depends on AMS not probing liveness. A future check (a ping, or watching a pidfd for the
binder) would end it; the session would then fall back to counted processes, which is today's
behavior.
- OEM ROMs with their own process managers (MIUI/HyperOS, ColorOS) are outside this.
- A listed program's stops and continues (`kill -STOP`, `SIGCONT`) reach its worker, not a wait in
its parent: `waitpid(…, WUNTRACED)` and `WCONTINUED` report none for it. Listed programs are the
session's own (Steam, Wine, game helpers), whose parents start them without job control; one a
shell runs as a job-control job (`wine game.exe &` in an interactive terminal) stays counted, as
any such job does, so its shell gets its stops. Reading
the worker's state from `/proc` instead was tried and dropped: a stop and a continue can both
fall between two reads.
## phantomlab
`tools/phantomlab` is a standalone test app (package `com.droiddeck.phantomlab`, no Gradle). It
forks sleepers from the main process, a plain isolated service, an app-zygote isolated service and
eight `:wN` workers, execs in place, and probes what a process may do.
The limit of 4 below is device-wide: a trim while it is set can kill other apps' child processes,
which restoring the setting does not bring back. Use a test device or an emulator with nothing else
running, and note the current values first, to put them back afterwards:
```
adb shell settings get global settings_enable_monitor_phantom_procs
adb shell device_config get activity_manager max_phantom_processes
adb shell device_config get_sync_disabled_for_tests
```
Android 12 and some Android 13 builds have no `get_sync_disabled_for_tests`; there `adb shell
device_config is_sync_disabled_for_tests` answers only true or false, so it cannot tell `persistent`
from `until_reboot`. Note `none` when it says false. When it says true, sync is already off: skip
the `set_sync_disabled_for_tests persistent` step below, which keeps whichever mode it was, and
leave the mode alone when you restore the rest.
```
tools/phantomlab/build.sh # build/phantomlab.apk, debug-signed
adb install -r tools/phantomlab/build/phantomlab.apk
adb shell device_config set_sync_disabled_for_tests persistent
adb shell device_config put activity_manager max_phantom_processes 4
adb shell settings put global settings_enable_monitor_phantom_procs true
adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso:a --ei n 40
adb shell "am start -n com.droiddeck.phantomlab/.Main --es cmd exec --es target w0 --ei keep 1 --es argv '/system/bin/sleep|100000'"
adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd probe --es target iso:a --es what self,memfd_exec,exec,fds,escape,libexec --es fds tcp,udp,unix,file:probe.txt
adb logcat -s PLAB ActivityManager | grep -i 'PLAB\|Trimming'
```
Targets: `main`, `proc` (`:proc`), `isoplain`, `iso:<name>` (one app-zygote instance per name),
`w0`…`w7`. Android scans only on CPU-stat refreshes, so switch apps a few times (5 s apart) before
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 end the lab's
sleepers with `adb shell am force-stop com.droiddeck.phantomlab`.
+1
View File
@@ -32,6 +32,7 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
| Controller | Settings › Controller (`droiddeck://settings/controller`) | gamepad, buttons, mapping, profile, remap |
| Smart glasses | Settings › Smart glasses (`droiddeck://settings/glasses`) | xreal, viture, vr, ar |
| Theme | Settings › Launcher (`droiddeck://settings/launcher`) | color, dark |
+1 -1
View File
@@ -184,7 +184,7 @@ echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-taggi
"$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \
-ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" "$HERE/handoff.c" -ldl -o "$PACK/preload/libexecshim.so"
"$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so"
"$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag"
"$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag"
+5
View File
@@ -25,6 +25,9 @@ typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t;
#define LINKER "/system/bin/linker64"
// handoff.c: returns unless the exec was handed to one of the app's worker processes
void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]);
enum kind { PASS, VIA_LINKER, VIA_INTERP };
// What starting `path` needs; for scripts, the interpreter and its optional argument.
@@ -205,6 +208,8 @@ int execve(const char *path, char *const argv[], char *const envp[]) {
char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes)
const char *file = path;
char **args = rewrite(path, argv, &file, storage);
// the app may run it in a worker instead (handoff.c): matched by the program, sent as the start below
ddh_bionic_exec(file, args ? args : argv, envp, path, argv);
int ret = real(file, args ? args : argv, envp);
int saved = errno;
free(args);
+415
View File
@@ -0,0 +1,415 @@
// handoff: part of libexecshim.so, preloaded into the bionic Wine processes. The native hook's exec
// handoff (tools/nativeguest/hook/handoff.c, docs/phantom-processes.md) built for bionic: a program a
// Wine process forks and execs runs as the main process of one of the app's worker processes instead of
// as a child Android counts against its limit. The glibc session's hook cannot reach these processes
// (they run on Android's libc), so without this every Wine process of a bionic game was counted.
//
// What the native hook does around the handoff and this file does too: fork() records the child for
// its parent's table, close(), close_range(), dup2() and dup3() leave the table and the worker's binder
// fds alone (hook/kept.c), and execve() offers the exec to the app before it runs (execshim.c calls
// ddh_bionic_exec() with the start it is about to make: "/system/bin/linker64 PROGRAM ARGS" for a
// program in the app's data, matched against DD_HANDOFF by PROGRAM). wait*(), kill() and _exit() are
// the handoff's own (hook/handoff.c). Nothing here acts without DD_SPAWN and DD_HANDOFF in the
// environment (tools/bionic-runtime/tool/launch.sh keeps them).
#define _GNU_SOURCE
#include <dlfcn.h>
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/wait.h>
// bionic has no thread cancellation: nothing can cancel the table's setup
#ifndef PTHREAD_CANCEL_ENABLE
#define PTHREAD_CANCEL_ENABLE 0
#define PTHREAD_CANCEL_DISABLE 1
static int pthread_setcancelstate(int state, int *old) {
(void)state;
if (old) *old = PTHREAD_CANCEL_ENABLE;
return 0;
}
#endif
#ifndef CLOSE_RANGE_UNSHARE
#define CLOSE_RANGE_UNSHARE (1U << 1)
#endif
#ifndef CLOSE_RANGE_CLOEXEC
#define CLOSE_RANGE_CLOEXEC (1U << 2)
#endif
#ifndef __NR_close_range
#define __NR_close_range 436
#endif
#include <sys/sysmacros.h>
static void pthread_testcancel(void) {}
int close_range(unsigned int first, unsigned int last, int flags);
// bionic has no on_exit(): the handoff reports a program's exit status from it (exit() runs it).
// atexit() handlers get no status, so exit() below notes it first; a return from main() reaches
// exit() inside libc and reports 0.
static void (*g_on_exit_fn)(int, void *);
static void *g_on_exit_arg;
static int g_exit_status;
static void run_on_exit(void) {
if (g_on_exit_fn) g_on_exit_fn(g_exit_status, g_on_exit_arg);
}
static int on_exit(void (*fn)(int, void *), void *arg) {
g_on_exit_fn = fn;
g_on_exit_arg = arg;
return atexit(run_on_exit);
}
// The native hook's names for the plain system call and for a guest path: here there is no guest root.
static long call_orig_syscall(long nr, unsigned long a, unsigned long b, unsigned long c, unsigned long d,
unsigned long e, unsigned long f) {
return syscall(nr, a, b, c, d, e, f);
}
static const char *rewrite_path(const char *path, char *out, size_t size) {
(void)out;
(void)size;
return path;
}
#include "../nativeguest/hook/kept.c"
#include "../nativeguest/hook/handoff.c"
void exit(int status) {
g_exit_status = status;
void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, "exit");
if (real) real(status);
syscall(SYS_exit_group, status);
__builtin_unreachable();
}
static int ddh_is_linker(const char *path) {
const char *base = path ? strrchr(path, '/') : NULL;
return base && strcmp(base + 1, "linker64") == 0;
}
static int ddh_regular(const char *path, int mode) {
struct stat st;
return path && stat(path, &st) == 0 && S_ISREG(st.st_mode) && access(path, mode) == 0;
}
// Android refuses execve() of a file in the app's data unless SELinux is permissive (execshim.c makes the
// dynamic ones linker64 starts). An unreadable setting counts as enforcing.
static int ddh_selinux_permissive(void) {
char c = 0;
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC, 0);
if (fd < 0) return 0;
long n = syscall(SYS_read, fd, &c, 1);
syscall(SYS_close, fd);
return n == 1 && c == '0';
}
// A handed-off start that fails fails in the worker, where the caller cannot see it and try its next
// candidate (Wine tries its preloader, then its loader), so only a start that would succeed here goes.
static int ddh_bionic_startable(const char *file, char *const args[]) {
char real[PATH_MAX];
// env takes an argument with '=' for a variable, and looks a name without '/' up in PATH
if (!file || strchr(file, '=') || !strchr(file, '/')) return 0;
if (!ddh_regular(file, X_OK) || !realpath(file, real)) return 0;
if (ddh_is_linker(real))
return args && args[0] && args[1] && args[1][0] != '-' && ddh_regular(args[1], R_OK) && ddh_startable(args[1]);
if (strncmp(real, "/data/", 6) == 0 && !ddh_selinux_permissive()) return 0;
// env starts FILE with FILE as argv[0]
return args && args[0] && strcmp(args[0], file) == 0 && ddh_startable(file);
}
void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]) {
if (ddh_env(envp, "DD_HANDOFF_DEBUG")) {
char why[200];
struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE);
snprintf(why, sizeof(why), "bionic exec (spawn %d list %d table %d owner %d up %d ppid %d) of", ddh_env(envp, "DD_SPAWN") != NULL,
ddh_env(envp, "DD_HANDOFF") != NULL, own != NULL, own ? (int)g_ddh_owner : 0, g_ddh_up != NULL, (int)getppid());
ddh_debug(envp, why, path ? path : "(null)");
}
if (!ddh_env(envp, "DD_SPAWN") || !ddh_env(envp, "DD_HANDOFF")) return;
if (!ddh_bionic_startable(file, args)) {
ddh_debug(envp, "bionic exec stays here (not startable as a handoff):", path ? path : "(null)");
return;
}
// Wine's own starts through the system linker ("/system/bin/linker64 PROGRAM ARGS") are listed by PROGRAM
const char *match = path;
char *const *match_argv = argv;
if (ddh_is_linker(path) && argv && argv[0] && argv[1]) {
match = argv[1];
match_argv = argv + 1;
}
// The app starts a handed-off program from the glibc root's shell (GuestWorkers), which cannot load this
// runtime's LD_PRELOAD and LD_LIBRARY_PATH (bionic libraries). The request carries them as arguments of
// Android's env instead, which the shell execs and which puts them back for the program: the worker's main
// process ends up as the program all the same. Stack only (this may run in a vfork child).
int nargs = 0, nenv = 0;
while (args[nargs]) nargs++;
while (envp && envp[nenv]) nenv++;
// env, up to two loader variables, FILE, args[1..], NULL (nargs >= 1: ddh_bionic_startable)
char *wrapped[nargs + 4];
char *trimmed[nenv + 1];
int w = 0, t = 0;
wrapped[w++] = (char *)"/system/bin/env";
for (int i = 0; i < nenv; i++) {
if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0 || strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) {
if (w < 3) wrapped[w++] = envp[i];
} else {
trimmed[t++] = envp[i];
}
}
trimmed[t] = NULL;
// env runs the program by the path its first argument gives: the start's file, then the rest of its argv
wrapped[w++] = (char *)file;
for (int i = 1; i < nargs; i++) wrapped[w++] = args[i];
wrapped[w] = NULL;
ddh_try_as("/system/bin/env", wrapped, trimmed, match, match_argv);
ddh_debug(envp, "bionic exec stays here:", path ? path : "(null)");
}
// bionic's exec functions call the execve system call stub inside libc, past execshim.c's execve(): Wine
// starts its programs with execv() (its preloader) and execvp(), so these go through execve() here.
extern char **environ;
int execv(const char *path, char *const argv[]) { return execve(path, argv, environ); }
// bionic's execvpe(), through execve() here: an unset PATH is libc's default (Android 14's; an empty one, and an empty
// entry, are the current directory), and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh.
#define DDH_DEFPATH "/product/bin:/apex/com.android.runtime/bin:/apex/com.android.art/bin:/system_ext/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin"
static int exec_as_script(const char *file, char *const argv[], char *const envp[]) {
int n = 0;
while (argv && argv[n]) n++;
char *script[(n > 0 ? n : 1) + 2];
int s = 0;
script[s++] = (char *)"sh";
script[s++] = (char *)file;
for (int i = 1; i < n; i++) script[s++] = argv[i];
script[s] = NULL;
return execve("/system/bin/sh", script, envp);
}
int execvpe(const char *file, char *const argv[], char *const envp[]) {
if (!file || !*file) {
errno = ENOENT;
return -1;
}
if (strchr(file, '/')) {
execve(file, argv, envp);
return errno == ENOEXEC ? exec_as_script(file, argv, envp) : -1;
}
const char *dirs = getenv("PATH");
if (!dirs) dirs = DDH_DEFPATH;
int saw_eacces = 0;
size_t flen = strlen(file);
for (const char *p = dirs;;) {
const char *end = strchr(p, ':');
size_t len = end ? (size_t)(end - p) : strlen(p);
const char *dir = len ? p : ".";
if (!len) len = 1;
char full[PATH_MAX];
if (len + flen + 2 > sizeof(full)) {
errno = ENAMETOOLONG;
} else {
memcpy(full, dir, len);
full[len] = '/';
memcpy(full + len + 1, file, flen + 1);
execve(full, argv, envp);
}
switch (errno) {
case EISDIR:
case ELOOP:
case ENAMETOOLONG:
case ENOENT:
case ENOTDIR:
break;
case ENOEXEC:
return exec_as_script(full, argv, envp);
case EACCES:
saw_eacces = 1;
break;
default:
return -1;
}
if (!end) break;
p = end + 1;
}
if (saw_eacces) errno = EACCES;
return -1;
}
int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); }
// execl(), execlp(), execle(): the list as an argv on the stack
#define EXECL_ARGV(first, ap, n) \
do { \
va_list count_ap; \
va_copy(count_ap, ap); \
n = first ? 1 : 0; \
if (first) \
while (va_arg(count_ap, const char *)) n++; \
va_end(count_ap); \
} while (0)
int execl(const char *path, const char *arg0, ...) {
va_list ap;
va_start(ap, arg0);
int n;
EXECL_ARGV(arg0, ap, n);
char *argv[n + 1];
argv[0] = (char *)arg0;
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
argv[n] = NULL;
va_end(ap);
return execve(path, argv, environ);
}
int execlp(const char *file, const char *arg0, ...) {
va_list ap;
va_start(ap, arg0);
int n;
EXECL_ARGV(arg0, ap, n);
char *argv[n + 1];
argv[0] = (char *)arg0;
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
argv[n] = NULL;
va_end(ap);
return execvp(file, argv);
}
int execle(const char *path, const char *arg0, ...) {
va_list ap;
va_start(ap, arg0);
int n;
EXECL_ARGV(arg0, ap, n);
char *argv[n + 1];
argv[0] = (char *)arg0;
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
argv[n] = NULL;
if (arg0) (void)va_arg(ap, char *); // the list's NULL
char *const *envp = va_arg(ap, char *const *);
va_end(ap);
return execve(path, argv, envp);
}
pid_t fork(void) {
static pid_t (*orig_fork)(void) = NULL;
if (!orig_fork) orig_fork = (pid_t (*)(void))dlsym(RTLD_NEXT, "fork");
if (!orig_fork) {
errno = ENOSYS;
return -1;
}
ddh_prepare();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
return pid;
}
int close(int fd) {
static int (*orig_close)(int) = NULL;
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
uint64_t ticket = kept_close_begin();
if (kept_any() > 0 && is_kept_fd(fd)) {
kept_close_end(ticket);
return 0;
}
int r = orig_close ? orig_close(fd) : (errno = ENOSYS, -1);
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
static int dup_moved(int (*dup_fn)(int, int, int), int oldfd, int newfd, int flags) {
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = dup_fn(oldfd, newfd, flags);
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
int saved = errno;
ddh_parent_pidfd_unlock(locked);
errno = saved;
return ret;
}
static int (*g_orig_dup2)(int, int);
static int (*g_orig_dup3)(int, int, int);
static int call_dup2(int oldfd, int newfd, int flags) {
(void)flags;
return g_orig_dup2 ? g_orig_dup2(oldfd, newfd) : (errno = ENOSYS, -1);
}
static int call_dup3(int oldfd, int newfd, int flags) {
return g_orig_dup3 ? g_orig_dup3(oldfd, newfd, flags) : (errno = ENOSYS, -1);
}
int dup2(int oldfd, int newfd) {
if (!g_orig_dup2) g_orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
return dup_moved(call_dup2, oldfd, newfd, 0);
}
int dup3(int oldfd, int newfd, int flags) {
if (!g_orig_dup3) g_orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
return dup_moved(call_dup3, oldfd, newfd, flags);
}
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
return (int)syscall(__NR_close_range, first, last, *(int *)flags);
}
static int close_range_unshare(void) {
return (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE);
}
int close_range(unsigned int first, unsigned int last, int flags) {
// what the kernel refuses, refused before the range is split or the table unshared
if (first > last || (flags & ~(int)(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))) {
errno = EINVAL;
return -1;
}
uint64_t ticket = kept_close_begin();
int r = 0;
// The table is unshared first, once, and this thread goes on with its own copy of the kept list
// (kept_split())
if (flags & CLOSE_RANGE_UNSHARE) {
r = kept_split(close_range_unshare);
flags &= ~(int)CLOSE_RANGE_UNSHARE;
}
if (r == 0) {
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
r = count == 0 ? close_range_part(first, last, &flags)
: for_each_range_without(first, last, kept, count, close_range_part, &flags);
}
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
// The native hook's own uses of these (exec.c) have no counterpart here
__attribute__((unused)) static void *const glibc_only[] = {(void *)ddh_try, (void *)ddh_spawn_wanted};
+10 -5
View File
@@ -52,6 +52,10 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
DROIDDECK_GUEST_ROOT) ;;
VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;;
# The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the
# glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs
# in one): the first Wine process's hook knows the worker's binder fds are not its own.
DD_SPAWN|DD_SPAWN_SESSION|DD_HANDOFF|DD_HANDOFF_DEBUG|DD_HANDOFF_PRESSURE|DDH_*|DDNATV_ROOT) ;;
*) unset "$v" 2>/dev/null ;;
esac
done
@@ -86,7 +90,8 @@ RTD=$APP/.wayland-rt
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=0
echo "WSI forced XWayland bypass disabled (GAMESCOPE_WSI_FORCE_BYPASS=$GAMESCOPE_WSI_FORCE_BYPASS)"
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
# Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor),
@@ -258,7 +263,7 @@ prepare_prefix() {
prefix_busy() { # a process of this prefix is running
for p in /proc/[0-9]*; do
[ "${p#/proc/}" = "$$" ] && continue
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
done
return 1
}
@@ -273,7 +278,7 @@ programs_left() { # a program of this prefix is still running, apart from Wine's
""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe|\
winemenubuilder|wineboot.exe|tabtip.exe) continue ;;
esac
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
done
return 1
}
@@ -282,7 +287,7 @@ stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game
wineserver_ -k 2>/dev/null
sleep 1
for p in /proc/[0-9]*; do
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue
[ "${p#/proc/}" = "$$" ] && continue
echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)"
kill -9 "${p#/proc/}" 2>/dev/null
@@ -426,7 +431,7 @@ comm=$(echo "$name" | cut -c1-15)
game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name)
for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do
p=${p%/comm}
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}"
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}"
done
}
# The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game
+6 -1
View File
@@ -233,7 +233,12 @@ return_gaming=/run/droiddeck/return-gaming
mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
as_user=
if [ "${DD_DESKTOP_USER:-}" = 1 ] && [ -n "${DDNATV_ROOT:-}" ]; then
as_user=/usr/local/bin/droiddeck-user
echo "== droiddeck-desktop: Plasma runs as an ordinary user"
fi
$as_user dbus-run-session -- startplasma-wayland
rc=$?
/usr/local/bin/droiddeck-pipewire stop
echo "== droiddeck-desktop: Plasma ended ($rc)"
@@ -284,8 +284,10 @@ def sandboxed_apps(proc=Path("/proc")):
def window_steam_app(win, flatpaks, proc=Path("/proc")):
match = STEAM_APP_CLASS.match(win.get("class") or "")
if match:
return match.group(1) if os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64" else None
if match and os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64":
return match.group(1)
# Gamescope finds the app of a window whose process runs under Steam's reaper. A game the
# session runs in a worker process (GuestWorkers) is not under it, whatever its class.
pid = win.get("pid")
if pid:
if under_reaper(pid, proc):
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
# Appends stdin to a session log up to a byte cap, then reads and drops the rest, so that the session
# writing into it never gets SIGPIPE. A program of its own, rather than a subshell of the session, so
# that the native hook can start it outside the app's counted child processes.
# usage: droiddeck-log-writer FILE CAP_BYTES
dd=$(command -v gnudd || echo dd)
"$dd" of="$1" oflag=append conv=notrunc iflag=count_bytes count="$2" bs=65536 status=none
exec cat >/dev/null
@@ -14,6 +14,59 @@ export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
# Starts a long-lived program in its own Android process, which Android does not count against
# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
# Its pid is in $dd_spawned either way, 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.$$ 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
# hook can hand to its own process (DD_HANDOFF "bash+dd-job"). $! is its pid, as for ( ... ) &.
dd_job() {
local state
if [ -n "${DD_HANDOFF:-}" ] && state=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/.dd-job.XXXXXX" 2>/dev/null); then
{
declare -p | grep -Ev '^declare -[a-zA-Z]*r|^declare -[-a-zA-Z]* (BASH[A-Z_]*|FUNCNAME|GROUPS|DIRSTACK|PIPESTATUS|COPROC|LINENO|_)='
declare -f
shopt -p
set +o
} > "$state" 2>/dev/null
/bin/bash -c 'source "$1" 2>/dev/null; rm -f "$1"; shift; "$@"' dd-job "$state" "$@" &
else
"$@" &
fi
}
# Long-lived programs the session's guests start run in their own processes too
# (tools/nativeguest/hook/handoff.c). Not Steam, its web helper's browser process (gamescope finds a
# window's app by walking its process's parents) or its utility processes (the client only accepts
# its transport from its own children).
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
else
unset DD_HANDOFF
fi
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
[ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_STEAM_EXIT_FILE"
@@ -24,8 +77,12 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
if [ "$(stat -c %s "$DD_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
mv -f "$DD_LOG" "$DD_LOG.1"
fi
dd=$(command -v gnudd || echo dd)
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
if [ -x /usr/local/bin/droiddeck-log-writer ]; then
exec > >(exec /usr/local/bin/droiddeck-log-writer "$DD_LOG" "${DD_LOG_CAP:-268435456}") 2>&1
else
dd=$(command -v gnudd || echo dd)
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
fi
echo "== droiddeck-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
@@ -618,6 +675,11 @@ dd_stretch_game_screen() {
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
reap_orphans() {
local round p stat pid left
# Started by the app as an Android process of its own: its parent is zygote, whose other
# children are the app's processes. The guest may not see zygote in /proc; a worker's own
# program has DDH_WORKER_PID.
[ "${DDH_WORKER_PID:-}" = "$$" ] && return 0
case "$(tr -d '\0' < "/proc/$PPID/cmdline" 2>/dev/null)" in ''|zygote*) return 0 ;; esac
for round in 1 2 3 4 5; do
left=
for p in /proc/[0-9]*; do
@@ -636,7 +698,7 @@ reap_orphans() {
}
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
fi
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
@@ -779,7 +841,7 @@ case $mode in
fi
if [ "${DD_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
(
_dd_job_zram() {
dd_zram_scan() {
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0
@@ -1124,7 +1186,7 @@ case $mode in
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
while kill -0 $$ 2>/dev/null; do
while kill -0 "$dd_session_pid" 2>/dev/null; do
dd_memory_tick
if [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
@@ -1133,7 +1195,8 @@ case $mode in
nap 5
fi
done
) &
}
dd_job _dd_job_zram
fi
if [ "${DD_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] \
&& [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
@@ -1226,7 +1289,7 @@ case $mode in
) &
fi
fi
[ -z "${DD_DESKTOP:-}" ] && (
_dd_job_properties() {
stretch=0 restore=0
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
@@ -1305,8 +1368,9 @@ case $mode in
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
;;
esac
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
) &
done < <(exec xprop -spy -root "${atoms[@]}" 2>/dev/null)
}
[ -n "${DD_DESKTOP:-}" ] || dd_job _dd_job_properties
steam_hold_launch() {
local game=$1 shortcut= waited=0 status=0
_dd_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
@@ -1393,8 +1457,8 @@ case $mode in
fi
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
system_bus=$!
dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile
system_bus=$dd_spawned
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
sleep 0.1
@@ -1402,8 +1466,8 @@ case $mode in
if [ -S /run/dbus/system_bus_socket ]; then
echo "== network: system bus up, NetworkManager stand-in running"
rm -f "$DD_LAUNCH_DIR/steam-sleep-ready"
droiddeck-login1 --with-netmanager &
login_manager=$!
dd_spawn droiddeck-login1 --with-netmanager
login_manager=$dd_spawned
for ((_i = 0; _i < 50; _i++)); do
[ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break
kill -0 "$login_manager" 2>/dev/null || break
@@ -1427,7 +1491,7 @@ case $mode in
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
_dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
rm -f "$_dd_bus"
dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile &
dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile
for _ in $(seq 1 50); do
[ -S "$_dd_bus" ] && break
nap 0.1
@@ -1465,7 +1529,7 @@ case $mode in
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then
(
_dd_job_decky() {
decky_child=
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
trap decky_stop TERM INT HUP
@@ -1489,7 +1553,8 @@ case $mode in
echo "== Decky: loader exited with status $decky_status; restart $((decky_exits + 1))/5 in ${decky_delay}s"
sleep "$decky_delay"
done
) &
}
dd_job _dd_job_decky
decky_supervisor=$!
echo "== Decky: session supervisor started ($decky_arch)"
else
@@ -1690,7 +1755,7 @@ case $mode in
rm -f "$DD_LAUNCH_DIR/steam-stop" "$DD_LAUNCH_DIR/steam-game" "$DD_LAUNCH_DIR/steam-game.tmp"
requests=1
fi
(
_dd_job_requests() {
tick=0
beat=0
library_job=
@@ -1868,7 +1933,8 @@ case $mode in
fi
fi
done
) &
}
dd_job _dd_job_requests
stop_watcher=$!
if [ "${DD_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then
LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /'
@@ -2022,6 +2088,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"
@@ -2031,6 +2098,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
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Starts a program as the main process of its own Android process, outside the session's cgroup.
usage: droiddeck-spawn [--wait] [--pid-file FILE] [--] PROGRAM [ARGS...]
Android counts the session's processes against its child-process limit; a program started this
way is not counted (its own children are). It gets this process's environment, working directory
and stdin/stdout/stderr, and is not a child of the caller: the pid printed on stdout (or written to
FILE) is the one to signal. Without --wait this returns once the program has started; with --wait
it waits for it and exits with its status. Where the app offers no spawner, the program is started as a normal child.
"""
import array
import json
import os
import re
import socket
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):
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):
pid = os.fork()
if pid == 0:
try:
os.execvp(argv[0], argv)
except OSError as e:
print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr)
os._exit(127)
reported = report(pid, pid_file)
if wait:
return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
return 0 if reported else STARTED_UNREPORTED
def main():
args = sys.argv[1:]
wait = False
pid_file = None
while args and args[0].startswith("--"):
flag = args.pop(0)
if flag == "--":
break
if flag == "--wait":
wait = True
elif flag == "--pid-file" and args:
pid_file = args.pop(0)
else:
print(__doc__.strip(), file=sys.stderr)
return 2
if not args:
print(__doc__.strip(), file=sys.stderr)
return 2
name = os.environ.get("DD_SPAWN")
if not name:
return fallback(args, wait, pid_file)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
s.connect("\0" + name)
except OSError:
return fallback(args, wait, pid_file)
request = {"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}
# the session it belongs to, as SessionService writes it (a positive decimal); anything else is
# left out, and the app then runs nothing for it
session = os.environ.get("DD_SPAWN_SESSION", "")
if re.fullmatch(r"[1-9][0-9]{0,8}", session):
request["session"] = int(session)
payload = json.dumps(request).encode()
s.sendmsg([struct.pack(">I", len(payload)), payload],
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))])
reply = s.makefile("r")
first = reply.readline().split()
if len(first) != 2 or first[0] != "pid":
print("droiddeck-spawn: %s; starting %s as a child" % (" ".join(first[1:]) or "no answer", args[0]),
file=sys.stderr)
return fallback(args, wait, pid_file)
reported = report(first[1], pid_file)
if not wait:
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)
if __name__ == "__main__":
sys.exit(main())
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Runs COMMAND, or a shell, as an ordinary user ("deck", the app's own Android user) instead of
# root, for programs that refuse root or check who owns their files. Everything started from it
# stays that user; sudo and su still give root, and exit goes back.
case ${1:-} in
-h|--help) echo "usage: droiddeck-user [COMMAND [ARG...]]"; exit 0 ;;
esac
if [ -z "${DDNATV_ROOT:-}" ]; then
echo "droiddeck-user: needs the native userland (Settings > Performance > Run without proot)" >&2
exit 1
fi
export DDNATV_BECOME=app USER=deck LOGNAME=deck
[ $# -gt 0 ] && exec "$@"
[ -t 2 ] && echo "Programs here run as an ordinary user (deck), not root. sudo still works; exit goes back." >&2
exec "${SHELL:-/bin/bash}"
+14
View File
@@ -17,6 +17,20 @@ same length: the code compares environment names by length) and extended with:
Build: `tools/nativeguest/build.sh out.so` with an aarch64 glibc cross compiler.
## Root or an ordinary user
Every program sees itself as root by default, which apt, dpkg and the session expect.
`DDNATV_USER=app` in a process's environment makes it, and everything it starts, the app's own
Android user instead, named `deck` (home `/root`): its ids, its files' owners, `/proc/*/status` and
peer credentials are the kernel's, and it may not change its ids. `DDNATV_BECOME=root` or `=app` in
a started program's environment switches that program and its children; the hook drops both
variables and puts `DDNATV_USER=app` first in the environment, where a peer's mode is read from
`/proc/<pid>/environ`. A set-user-ID program owned by the app (shown as root's) starts as root.
`droiddeck-user [COMMAND]` starts a shell or command that way, `sudo` and `su` return to root, and
Performance > "Desktop runs as a user" starts the whole Plasma session as `deck`. Statically linked
Go programs are patched once on disk and still see root.
## Testing under Android's seccomp filter
Some devices (eng builds, `setenforce 0` ROMs) run apps with no seccomp filter, so a hook that
+2
View File
@@ -77,11 +77,13 @@
#include "hook/files.c"
#include "hook/fileops.c"
#include "hook/identity.c"
#include "hook/kept.c"
#include "hook/privileged.c"
#include "hook/env.c"
#include "hook/exec_probe.c"
#include "hook/static_programs.c"
#include "hook/go_programs.c"
#include "hook/handoff.c"
#include "hook/exec.c"
#include "hook/net.c"
#include "hook/sockets.c"
+17 -1
View File
@@ -99,6 +99,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
int has_exec_loader = 0;
int has_preload_list = 0;
const char *preload_value = NULL;
const char *become = NULL;
while (envp && envp[count]) {
const char *e = envp[count];
switch (e[0]) {
@@ -127,6 +128,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
else if (strncmp(e, "DDNATV_HOSTNAME=", 16) == 0) has_hostname = 1;
else if (strncmp(e, "DDNATV_LINK_ROOT=", 17) == 0) has_link_root = 1;
else if (strncmp(e, "DDNATV_EXEC=", 12) == 0) has_exec_loader = 1;
else if (strncmp(e, "DDNATV_BECOME=", 14) == 0) become = e + 14;
else if (strncmp(e, "DPKG_DEB_THREADS_MAX=", 21) == 0) has_threads_max = 1;
else if (strncmp(e, "DEBIAN_FRONTEND=", 16) == 0) has_frontend = 1;
else if (strncmp(e, "DEBCONF_FRONTEND=", 17) == 0) has_debconf_frontend = 1;
@@ -138,9 +140,23 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
count++;
}
char **new_env = calloc(count + 25, sizeof(char *));
char **new_env = calloc(count + 26, sizeof(char *));
int dst = 0;
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
// says, unless DDNATV_BECOME asks for one, or the program is set-user-ID root's (the app's files
// are root's), as the kernel would start it. First in the block, where a peer looks (sockets.c).
int as_app = app_user_mode();
if (become) as_app = strcmp(become, "app") == 0;
else if (as_app && real_exe && real_exe[0] == '/') {
struct stat st;
if (real_fstatat(AT_FDCWD, real_exe, &st, 0) == 0 && S_ISREG(st.st_mode) && (st.st_mode & S_ISUID)
&& st.st_uid == app_uid_now()) as_app = 0;
}
if (as_app) new_env[dst++] = strdup("DDNATV_USER=app");
for (int i = 0; i < count; i++) {
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
continue;
}
if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
// ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every
// program loads (DDNATV_PRELOAD) come first
+235 -6
View File
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ENOSYS;
return -1;
}
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
// like the kernel would pass it; routing below uses the absolute form.
@@ -538,11 +539,9 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ELOOP;
ret = -1;
} else {
char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL);
ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
errno = saved_errno;
// The interpreter's exec prepares the environment, as posix_spawn's does: done here
// too, it dropped DDNATV_BECOME before the interpreter could take it (sudo SCRIPT)
ret = ddnatv_execve(rewritten_interp, new_argv, envp, depth + 1);
}
free(new_argv);
return ret;
@@ -660,7 +659,17 @@ 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();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
// 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)
if (pid == 0 && __atomic_load_n(&g_exec_rehearsal, __ATOMIC_RELAXED)) __atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELAXED);
@@ -1067,6 +1076,215 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
static int apply_closefrom(posix_spawn_file_actions_t *actions);
// glibc's file actions (posix/spawn_int.h, unchanged since 2.35)
struct ddh_spawn_action {
enum { DDH_DO_CLOSE, DDH_DO_DUP2, DDH_DO_OPEN, DDH_DO_CHDIR, DDH_DO_FCHDIR, DDH_DO_CLOSEFROM, DDH_DO_TCSETPGRP } tag;
union {
struct { int fd; } close_action;
struct { int fd; int newfd; } dup2_action;
struct { int fd; char *path; int oflag; mode_t mode; } open_action;
struct { char *path; } chdir_action;
struct { int fd; } fchdir_action;
struct { int from; } closefrom_action;
struct { int fd; } setpgrp_action;
} action;
};
#ifndef POSIX_SPAWN_SETSID
#define POSIX_SPAWN_SETSID 0x80
#endif
static int ddh_spawn_errno(long ret) {
return ret < 0 ? errno : 0;
}
static int ddh_spawn_close_part(unsigned int first, unsigned int last, void *unused) {
(void)unused;
return (int)call_orig_syscall(SYS_close_range, first, last, 0, 0, 0, 0);
}
// What glibc's spawn child does before its exec (posix/spawni.c), as an errno. Its fd and
// directory work is done with system calls, not the hook's wrappers: those take locks that another
// thread of the parent may have held at fork() (Steam has many threads).
static int ddh_spawn_child_setup(const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr) {
short flags = 0;
if (attr) posix_spawnattr_getflags(attr, &flags);
if (flags & POSIX_SPAWN_SETSIGDEF) {
sigset_t def;
posix_spawnattr_getsigdefault(attr, &def);
for (int sig = 1; sig < _NSIG; sig++) {
if (sigismember(&def, sig) == 1) signal(sig, SIG_DFL);
}
}
if ((flags & POSIX_SPAWN_SETSID) && setsid() < 0) return errno;
if (flags & POSIX_SPAWN_SETPGROUP) {
pid_t group = 0;
posix_spawnattr_getpgroup(attr, &group);
if (setpgid(0, group) != 0) return errno;
}
if (flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)) {
struct sched_param param;
posix_spawnattr_getschedparam(attr, &param);
int policy = 0;
posix_spawnattr_getschedpolicy(attr, &policy);
int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, &param) : sched_setparam(0, &param);
if (r == -1) return errno;
}
const struct ddh_spawn_action *a = fa ? (const struct ddh_spawn_action *)fa->__actions : NULL;
char path[PATH_MAX];
int err;
for (int i = 0; a && i < fa->__used; i++) {
switch (a[i].tag) {
case DDH_DO_CLOSE:
// the handoff table and the worker's binder stay open (kept fds)
if (!is_kept_fd(a[i].action.close_action.fd))
call_orig_syscall(SYS_close, (unsigned long)a[i].action.close_action.fd, 0, 0, 0, 0, 0);
break;
case DDH_DO_OPEN: {
const char *real = rewrite_path(a[i].action.open_action.path, path, sizeof(path));
// as glibc: the target goes first, so a full fd table still has room for the open
if (!is_kept_fd(a[i].action.open_action.fd))
call_orig_syscall(SYS_close, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0, 0);
long fd = call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
(unsigned long)a[i].action.open_action.oflag, a[i].action.open_action.mode, 0, 0);
if (fd < 0) return errno;
if (fd != a[i].action.open_action.fd) {
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)fd, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0))))
return err;
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
}
break;
}
case DDH_DO_DUP2: {
int from = a[i].action.dup2_action.fd, to = a[i].action.dup2_action.newfd;
if (from == to) {
long fdflags = call_orig_syscall(SYS_fcntl, (unsigned long)from, F_GETFD, 0, 0, 0, 0);
if (fdflags < 0) return errno;
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fcntl, (unsigned long)from, F_SETFD, (unsigned long)(fdflags & ~FD_CLOEXEC), 0, 0, 0))))
return err;
} else if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)from, (unsigned long)to, 0, 0, 0, 0)))) {
return err;
}
break;
}
case DDH_DO_CHDIR: {
const char *real = rewrite_path_follow(a[i].action.chdir_action.path, path, sizeof(path));
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_chdir, (unsigned long)real, 0, 0, 0, 0, 0)))) return err;
break;
}
case DDH_DO_FCHDIR:
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fchdir, (unsigned long)a[i].action.fchdir_action.fd, 0, 0, 0, 0, 0))))
return err;
break;
case DDH_DO_CLOSEFROM:
for_each_range_without((unsigned int)a[i].action.closefrom_action.from, ~0U, g_kept_fds, g_kept_fd_count,
ddh_spawn_close_part, NULL);
break;
case DDH_DO_TCSETPGRP:
if (tcsetpgrp(a[i].action.setpgrp_action.fd, getpgrp()) != 0) return errno;
break;
}
}
if (flags & POSIX_SPAWN_SETSIGMASK) {
sigset_t mask;
posix_spawnattr_getsigmask(attr, &mask);
sigprocmask(SIG_SETMASK, &mask, NULL);
}
return 0;
}
// posix_spawn() as fork() and execve(), so that ddh_try() sees the exec. -1 when it cannot be.
static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
if (fa) {
const struct ddh_spawn_action *a = (const struct ddh_spawn_action *)fa->__actions;
// A terminal action stays with glibc, which blocks signals around the file actions: here a
// SIGTTOU could stop the child at tcsetpgrp() with the parent waiting on its report.
for (int i = 0; i < fa->__used; i++) {
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;
// Not cancelled while the child is being started (its report is read, and its failure reaped):
// the pid would be lost with the child still running, and the report's fd left open.
int cancel = PTHREAD_CANCEL_ENABLE;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel);
int report[2];
if (pipe2(report, O_CLOEXEC) != 0) {
pthread_setcancelstate(cancel, NULL);
return -1;
}
// Every signal blocked from the fork to the exec, as glibc's posix_spawn() does: a signal to the
// group during a file action (an open of a FIFO that blocks) would otherwise run the caller's
// handler, or end the child, before the program is started. The child gets back the caller's mask,
// or the one the attributes ask for, just before its exec.
sigset_t all, caller;
sigfillset(&all);
pthread_sigmask(SIG_SETMASK, &all, &caller);
pid_t child = fork();
if (child < 0) {
int err = errno;
pthread_sigmask(SIG_SETMASK, &caller, NULL);
close(report[0]);
close(report[1]);
pthread_setcancelstate(cancel, NULL);
return err;
}
if (child > 0) pthread_sigmask(SIG_SETMASK, &caller, NULL);
if (child == 0) {
call_orig_syscall(SYS_close, (unsigned long)report[0], 0, 0, 0, 0, 0);
// Out of the file actions' way: high, and one of the fds they leave open (closefrom(3) is common)
int to_parent = (int)call_orig_syscall(SYS_fcntl, (unsigned long)report[1], F_DUPFD_CLOEXEC, 1000, 0, 0, 0);
if (to_parent >= 0) {
call_orig_syscall(SYS_close, (unsigned long)report[1], 0, 0, 0, 0, 0);
ddh_keep(to_parent);
} else {
to_parent = report[1];
}
int err = ddh_spawn_child_setup(fa, attr);
if (!err) {
// A signal still pending when the mask is restored must not run a handler copied from the
// caller: caught signals go back to their default, ignored ones stay ignored (exec keeps
// them), and SIGSYS keeps the hook's handler.
for (int sig = 1; sig < _NSIG; sig++) {
struct sigaction old;
if (sig == SIGSYS || sig == SIGKILL || sig == SIGSTOP) continue;
if (sigaction(sig, NULL, &old) != 0) continue;
if (old.sa_handler == SIG_IGN || old.sa_handler == SIG_DFL) continue;
struct sigaction def = {0};
def.sa_handler = SIG_DFL;
sigaction(sig, &def, NULL);
}
short flags = 0;
if (attr) posix_spawnattr_getflags(attr, &flags);
if (!(flags & POSIX_SPAWN_SETSIGMASK)) sigprocmask(SIG_SETMASK, &caller, NULL);
execve(path, argv, envp);
err = errno;
}
syscall(SYS_write, to_parent, &err, sizeof(err));
_exit(127);
}
close(report[1]);
int err = 0;
ssize_t n;
do n = read(report[0], &err, sizeof(err));
while (n < 0 && errno == EINTR);
close(report[0]);
if (n == (ssize_t)sizeof(err)) {
while (waitpid(child, NULL, 0) < 0 && errno == EINTR) {
}
pthread_setcancelstate(cancel, NULL);
return err;
}
if (pid) *pid = child;
pthread_setcancelstate(cancel, NULL);
return 0;
}
int posix_spawn(pid_t *pid, const char *path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp,
@@ -1076,7 +1294,18 @@ int posix_spawn(pid_t *pid, const char *path,
if (bad) return bad;
}
posix_spawnattr_t sanitized;
return ddnatv_posix_spawn(pid, path, file_actions, spawn_attr_for_android(attrp, &sanitized), argv, envp, 0);
const posix_spawnattr_t *attr = spawn_attr_for_android(attrp, &sanitized);
if (ddh_spawn_wanted(path, argv, envp ? envp : environ)) {
int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ);
if (ret != -1) return ret;
}
pid_t child = 0;
int ret = ddnatv_posix_spawn(&child, path, file_actions, attr, argv, envp, 0);
if (ret == 0) {
ddh_child_created(child, 0);
if (pid) *pid = child;
}
return ret;
}
int posix_spawnp(pid_t *pid, const char *file,
+1 -1
View File
@@ -155,7 +155,7 @@ static void proc_status_root_ids(char *text, size_t len, const char *field, unsi
// The status file with the app's ids as root's, in a memory file; -2 when `path` is no such file
// or is opened for writing.
static int open_proc_status(const char *path, int flags) {
if ((flags & O_ACCMODE) != O_RDONLY || !is_proc_status_path(path) || !reader_compares_process_ids()) return -2;
if ((flags & O_ACCMODE) != O_RDONLY || app_user_mode() || !is_proc_status_path(path) || !reader_compares_process_ids()) return -2;
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return -1;
char text[16384];
File diff suppressed because it is too large. Load diff
+48
View File
@@ -445,6 +445,49 @@ static void load_app_ids(void) {
__atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED);
}
// DDNATV_USER=app: this process and what it starts run as the app's own user, an ordinary user
// ("deck"), instead of root. Its ids, its files' owners and its peers' ids are then the kernel's,
// so programs that refuse root (Firefox, Chromium, makepkg) or compare owners need no exception.
// DDNATV_BECOME in a started program's environment ("root" for sudo, "app" for droiddeck-user)
// changes the user for that program and everything it starts (env.c).
static int g_user_mode = -1;
static int app_user_mode(void) {
int mode = __atomic_load_n(&g_user_mode, __ATOMIC_RELAXED);
if (mode < 0) {
const char *value = getenv("DDNATV_USER");
mode = value && strcmp(value, "app") == 0;
__atomic_store_n(&g_user_mode, mode, __ATOMIC_RELAXED);
}
return mode;
}
static uid_t app_uid_now(void) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
return __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
}
static gid_t app_gid_now(void) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
return __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
}
// What the process calls its own user and group: root's, or the app's in app user mode
static uid_t presented_uid(void) { return app_user_mode() ? app_uid_now() : 0; }
static gid_t presented_gid(void) { return app_user_mode() ? app_gid_now() : 0; }
// Whether a set*id() call may set these ids (-1 leaves one as it is): root may set any; an ordinary
// user only the one it has, as there is no other to have
static int may_set_ids(int group, uint32_t a, uint32_t b, uint32_t c) {
if (!app_user_mode()) return 1;
uint32_t own = group ? (uint32_t)app_gid_now() : (uint32_t)app_uid_now();
uint32_t ids[3] = {a, b, c};
for (int i = 0; i < 3; i++) {
if (ids[i] != UINT32_MAX && ids[i] != own) return 0;
}
return 1;
}
#define ANDROID_MEDIA_RW_GID ((gid_t)1023)
static void present_owner_as_root(uid_t *uid, gid_t *gid) {
@@ -452,6 +495,11 @@ static void present_owner_as_root(uid_t *uid, gid_t *gid) {
uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
if (app_uid == (uid_t)-1) return;
if (app_user_mode()) {
// Shared storage is the user's, as it is root's otherwise
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = app_uid;
return;
}
if (uid && *uid == app_uid) *uid = 0;
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = 0;
if (gid && *gid == app_gid) *gid = 0;
+100 -15
View File
@@ -5,20 +5,28 @@
#ifndef DDNATV_HOST_TEST
// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions
uid_t getuid(void) { return 0; }
uid_t geteuid(void) { return 0; }
gid_t getgid(void) { return 0; }
gid_t getegid(void) { return 0; }
// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions. In app user
// mode (hardlinks.c) the ids are the app's and may only be "changed" to themselves, as the kernel
// allows an ordinary user; Android's seccomp filter refuses the real calls to apps.
uid_t getuid(void) { return presented_uid(); }
uid_t geteuid(void) { return presented_uid(); }
gid_t getgid(void) { return presented_gid(); }
gid_t getegid(void) { return presented_gid(); }
int setuid(uid_t uid) { (void)uid; return 0; }
int seteuid(uid_t uid) { (void)uid; return 0; }
int setgid(gid_t gid) { (void)gid; return 0; }
int setegid(gid_t gid) { (void)gid; return 0; }
int setreuid(uid_t ruid, uid_t euid) { (void)ruid; (void)euid; return 0; }
int setregid(gid_t rgid, gid_t egid) { (void)rgid; (void)egid; return 0; }
int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (void)suid; return 0; }
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; }
static int set_own_ids(int group, uint32_t a, uint32_t b, uint32_t c) {
if (may_set_ids(group, a, b, c)) return 0;
errno = EPERM;
return -1;
}
int setuid(uid_t uid) { return set_own_ids(0, uid, -1, -1); }
int seteuid(uid_t uid) { return set_own_ids(0, uid, -1, -1); }
int setgid(gid_t gid) { return set_own_ids(1, gid, -1, -1); }
int setegid(gid_t gid) { return set_own_ids(1, gid, -1, -1); }
int setreuid(uid_t ruid, uid_t euid) { return set_own_ids(0, ruid, euid, -1); }
int setregid(gid_t rgid, gid_t egid) { return set_own_ids(1, rgid, egid, -1); }
int setresuid(uid_t ruid, uid_t euid, uid_t suid) { return set_own_ids(0, ruid, euid, suid); }
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { return set_own_ids(1, rgid, egid, sgid); }
int getgroups(int size, gid_t list[]) {
if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1;
@@ -32,8 +40,14 @@ int __getgroups_chk(int size, gid_t list[], size_t listlen) {
if (size > 0 && (size_t)size * sizeof(gid_t) > listlen) __chk_fail();
return getgroups(size, list);
}
int setgroups(size_t size, const gid_t *list) { (void)size; (void)list; return 0; }
int initgroups(const char *user, gid_t group) { (void)user; (void)group; return 0; }
int setgroups(size_t size, const gid_t *list) {
(void)size;
(void)list;
if (!app_user_mode()) return 0;
errno = EPERM;
return -1;
}
int initgroups(const char *user, gid_t group) { (void)user; return setgroups(1, &group); }
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups) {
(void)user;
@@ -658,12 +672,60 @@ struct spwd *getspnam(const char *name) {
}
#endif /* !DDNATV_HOST_TEST */
// In app user mode the app's ids are an ordinary user, "deck", whose home is root's (where the
// session keeps everything). The rootfs lists the app's uid as root's for proot, so these come first.
#define DDNATV_APP_USER "deck"
static int app_user_passwd(const char *name, uid_t uid, int by_name, struct passwd *pwd, char *buf, size_t buflen) {
if (!app_user_mode()) return ENOENT;
if (by_name ? (!name || strcmp(name, DDNATV_APP_USER) != 0) : uid != app_uid_now()) return ENOENT;
static const char *const fields[] = {DDNATV_APP_USER, "x", "DroidDeck", "/root", "/bin/bash"};
size_t need = 0;
for (size_t i = 0; i < 5; i++) need += strlen(fields[i]) + 1;
if (!pwd || !buf || need > buflen) return ERANGE;
char *out[5];
char *cursor = buf;
for (size_t i = 0; i < 5; i++) {
size_t len = strlen(fields[i]) + 1;
memcpy(cursor, fields[i], len);
out[i] = cursor;
cursor += len;
}
pwd->pw_name = out[0];
pwd->pw_passwd = out[1];
pwd->pw_gecos = out[2];
pwd->pw_dir = out[3];
pwd->pw_shell = out[4];
pwd->pw_uid = app_uid_now();
pwd->pw_gid = app_gid_now();
return 0;
}
static int app_user_group(const char *name, gid_t gid, int by_name, struct group *grp, char *buf, size_t buflen) {
if (!app_user_mode()) return ENOENT;
if (by_name ? (!name || strcmp(name, DDNATV_APP_USER) != 0) : gid != app_gid_now()) return ENOENT;
size_t ptrs = 2 * sizeof(char *);
if (!grp || !buf || ptrs + sizeof(DDNATV_APP_USER) + 2 > buflen) return ERANGE;
char **members = (char **)buf;
char *cursor = buf + ptrs;
memcpy(cursor, DDNATV_APP_USER, sizeof(DDNATV_APP_USER));
grp->gr_name = cursor;
cursor += sizeof(DDNATV_APP_USER);
memcpy(cursor, "x", 2);
grp->gr_passwd = cursor;
members[0] = NULL;
grp->gr_mem = members;
grp->gr_gid = app_gid_now();
return 0;
}
static struct group s_grp_storage;
static char s_grp_buf[2048];
static struct passwd s_pwd_storage;
static char s_pwd_buf[2048];
struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) {
if (app_user_group(NULL, gid, 0, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf)) == 0) return &s_grp_storage;
#ifndef DDNATV_HOST_TEST
static struct group *(*orig_getgrgid)(gid_t) = NULL;
if (!orig_getgrgid) orig_getgrgid = (struct group *(*)(gid_t))dlsym(RTLD_NEXT, "getgrgid");
@@ -677,6 +739,7 @@ struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) {
}
struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) {
if (app_user_group(name, 0, 1, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf)) == 0) return &s_grp_storage;
#ifndef DDNATV_HOST_TEST
static struct group *(*orig_getgrnam)(const char *) = NULL;
if (!orig_getgrnam) orig_getgrnam = (struct group *(*)(const char *))dlsym(RTLD_NEXT, "getgrnam");
@@ -690,6 +753,11 @@ struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) {
}
int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t buflen, struct group **result) {
int own = app_user_group(NULL, gid, 0, grp, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? grp : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getgrgid_r)(gid_t, struct group *, char *, size_t, struct group **) = NULL;
if (!orig_getgrgid_r) orig_getgrgid_r = (int (*)(gid_t, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrgid_r");
@@ -714,6 +782,11 @@ int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t b
}
int DDNATV_NSS_SYM(getgrnam_r)(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result) {
int own = app_user_group(name, 0, 1, grp, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? grp : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getgrnam_r)(const char *, struct group *, char *, size_t, struct group **) = NULL;
if (!orig_getgrnam_r) orig_getgrnam_r = (int (*)(const char *, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrnam_r");
@@ -756,6 +829,7 @@ static struct passwd *present_privsep_user_as_root(struct passwd *pwd) {
}
struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) {
if (app_user_passwd(NULL, uid, 0, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf)) == 0) return &s_pwd_storage;
#ifndef DDNATV_HOST_TEST
static struct passwd *(*orig_getpwuid)(uid_t) = NULL;
if (!orig_getpwuid) orig_getpwuid = (struct passwd *(*)(uid_t))dlsym(RTLD_NEXT, "getpwuid");
@@ -769,6 +843,7 @@ struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) {
}
struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) {
if (app_user_passwd(name, 0, 1, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf)) == 0) return &s_pwd_storage;
#ifndef DDNATV_HOST_TEST
static struct passwd *(*orig_getpwnam)(const char *) = NULL;
if (!orig_getpwnam) orig_getpwnam = (struct passwd *(*)(const char *))dlsym(RTLD_NEXT, "getpwnam");
@@ -782,6 +857,11 @@ struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) {
}
int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) {
int own = app_user_passwd(NULL, uid, 0, pwd, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? pwd : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getpwuid_r)(uid_t, struct passwd *, char *, size_t, struct passwd **) = NULL;
if (!orig_getpwuid_r) orig_getpwuid_r = (int (*)(uid_t, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwuid_r");
@@ -810,6 +890,11 @@ int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t
}
int DDNATV_NSS_SYM(getpwnam_r)(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) {
int own = app_user_passwd(name, 0, 1, pwd, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? pwd : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getpwnam_r)(const char *, struct passwd *, char *, size_t, struct passwd **) = NULL;
if (!orig_getpwnam_r) orig_getpwnam_r = (int (*)(const char *, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwnam_r");
+225
View File
@@ -0,0 +1,225 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c before privileged.c, and of the bionic
// runtime's exec shim (tools/bionic-runtime/handoff.c): the descriptors close(), close_range() and
// closefrom() leave open.
// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of
// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it
// translates more code: a program that closes every descriptor it did not open (sshd at start,
// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when
// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code
// themselves have none.
#define DDNATV_MAX_KEPT_FDS 12
static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending
static int g_kept_fd_count = 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;
// The list can change while the program runs (hook/handoff.c keeps and lets go of its own fds): odd
// while a change is under way, which kept_change_begin() and kept_change_end() bracket. Readers take
// a whole copy (kept_snapshot()), so that another thread's close() or close_range() never works
// from a list half moved, which could close a kept fd.
static unsigned g_kept_seq;
static pthread_mutex_t g_kept_lock = PTHREAD_MUTEX_INITIALIZER;
static __thread uint64_t t_kept_mask;
// A thread that split its descriptor table from the others' (close_range() with
// CLOSE_RANGE_UNSHARE) goes on with a copy of the list made at the split, which only it reads and
// changes: the shared list keeps describing the other threads' table, so a kept fd this thread's
// program takes over (a dup2() onto the parent's pidfd) stays kept there. A child it forks takes the
// copy over as its list (kept_forked()).
static __thread int t_kept_split;
static __thread int t_kept_fds[DDNATV_MAX_KEPT_FDS];
static __thread int t_kept_count;
// In a process forked from such a thread: numbers published for the shared table (the handoff table's)
// may name other files here, or none.
static int g_kept_split;
static int kept_snapshot(int *out) {
if (t_kept_split) {
for (int i = 0; i < t_kept_count; i++) out[i] = t_kept_fds[i];
return t_kept_count;
}
for (;;) {
unsigned seq = __atomic_load_n(&g_kept_seq, __ATOMIC_ACQUIRE);
if (seq & 1) continue;
int n = __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED);
if (n > DDNATV_MAX_KEPT_FDS) n = DDNATV_MAX_KEPT_FDS;
for (int i = 0; i < n; i++) out[i] = __atomic_load_n(&g_kept_fds[i], __ATOMIC_RELAXED);
__atomic_thread_fence(__ATOMIC_ACQUIRE);
if (__atomic_load_n(&g_kept_seq, __ATOMIC_RELAXED) == seq) return n;
}
}
static void kept_fork_prepare(void) { pthread_mutex_lock(&g_kept_lock); }
static void kept_fork_done(void) { pthread_mutex_unlock(&g_kept_lock); }
static void kept_register_fork(void) { pthread_atfork(kept_fork_prepare, kept_fork_done, kept_fork_done); }
// Before anything takes g_kept_lock: a fork() in another thread then waits for it to be let go.
static void kept_register_once(void) {
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, kept_register_fork);
}
// Every signal blocked meanwhile, so that no handler on this thread reads the list half changed (it
// would wait for the change forever) or changes it too; a fork() waits for the change to end, so a
// child never starts with one under way.
static void kept_change_begin(void) {
kept_register_once();
uint64_t all = ~0ull;
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&t_kept_mask, 8, 0, 0);
pthread_mutex_lock(&g_kept_lock);
__atomic_store_n(&g_kept_seq, g_kept_seq + 1, __ATOMIC_RELAXED);
__atomic_thread_fence(__ATOMIC_RELEASE);
}
static void kept_change_end(void) {
__atomic_store_n(&g_kept_seq, g_kept_seq + 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&g_kept_lock);
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&t_kept_mask, 0, 8, 0, 0);
}
static int kept_any(void) {
return t_kept_split ? t_kept_count : __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED);
}
// The process's threads (/proc/self/stat), or 0 when it cannot be read.
static int kept_threads(void) {
char buf[512];
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc/self/stat",
O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)buf, sizeof(buf) - 1, 0, 0, 0);
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
if (n <= 0) return 0;
buf[n] = 0;
char *p = strrchr(buf, ')');
// after the name: state, then 16 fields to num_threads
for (int field = 0; p && field < 18; field++) p = strchr(p + 1, ' ');
return p ? atoi(p + 1) : 0;
}
// The calling thread's table split by split() (0, or -1 with errno), with the list copied for it in
// the same step: no keep or let-go of another thread falls between the copy and the split. A process
// with one thread keeps one table (the system copies only a shared one), and so one list. Threads that
// a thread with a table of its own starts later share that table but not its copy: not followed.
static int kept_split(int (*split)(void)) {
if (t_kept_split) return split();
kept_register_once();
uint64_t all = ~0ull, mask = 0;
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0);
pthread_mutex_lock(&g_kept_lock);
int shared = kept_threads() != 1;
int r = split();
int saved = errno;
if (r == 0 && shared) {
int n = g_kept_fd_count;
for (int i = 0; i < n; i++) t_kept_fds[i] = g_kept_fds[i];
t_kept_count = n;
t_kept_split = 1;
}
pthread_mutex_unlock(&g_kept_lock);
call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0);
errno = saved;
return r;
}
// In a forked child, whose only thread is the one that forked: a split thread's table is the child's.
static void kept_forked(void) {
if (!t_kept_split) return;
for (int i = 0; i < t_kept_count; i++) g_kept_fds[i] = t_kept_fds[i];
g_kept_fd_count = t_kept_count;
t_kept_split = 0;
g_kept_split = 1;
}
static int is_kept_fd(int fd) {
int kept[DDNATV_MAX_KEPT_FDS];
int n = kept_snapshot(kept);
for (int i = 0; i < n; i++) {
if (kept[i] == fd) return 1;
}
return 0;
}
// Closes under way (close(), close_range()), counted by the epoch they began in: one that looked at
// the list before a fd was added to it may still close that fd. A thread that makes and keeps a fd
// while others run (hook/handoff.c's table) moves the epoch on afterwards, waits for the closes of
// the one before (kept_settle()), and only then trusts the fd to be its own still.
static unsigned g_close_epoch;
// Per epoch, generation << 32 | count, one word: every change is one compare-and-swap, so a fork from
// a handler that interrupted a close's begin or end never splits one in two. A forked child moves the
// generation on and starts from none (kept_close_forked()): an end whose generation is gone counts
// nothing, and a begin whose swap failed takes the child's.
static uint64_t g_closers[2];
static void kept_close_end(uint64_t ticket);
// The close's ticket: generation << 1 | epoch
static uint64_t kept_close_begin(void) {
for (;;) {
unsigned epoch = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1;
uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST);
if (!__atomic_compare_exchange_n(&g_closers[epoch], &word, word + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
continue;
uint64_t ticket = (word >> 32) << 1 | epoch;
if ((__atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1) == epoch) return ticket;
kept_close_end(ticket); // the epoch moved on meanwhile: counted in the new one instead
}
}
static void kept_close_end(uint64_t ticket) {
unsigned epoch = (unsigned)(ticket & 1);
uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST);
while ((word >> 32) == (ticket >> 1) && (word & 0xffffffffu) != 0 &&
!__atomic_compare_exchange_n(&g_closers[epoch], &word, word - 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
}
}
// In a forked child: the closes the parent's threads were making are not the child's to wait for.
// (The forking thread's own, a close a handler interrupted to fork, then goes uncounted.)
static void kept_close_forked(void) {
for (int epoch = 0; epoch < 2; epoch++) {
uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST);
__atomic_store_n(&g_closers[epoch], ((word >> 32) + 1) << 32, __ATOMIC_SEQ_CST);
}
}
static int kept_drained(unsigned epoch) {
for (int i = 0; i < 1000; i++) {
if ((__atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST) & 0xffffffffu) == 0) return 1;
struct timespec pause = {0, 1000 * 1000};
nanosleep(&pause, NULL);
}
return 0;
}
// 1 once every close that began before now has ended; 0 after a second without (one interrupted by
// a signal whose handler is the caller, say): then nothing it made since can be trusted. The epoch
// moves on only once the closes of the one before it are over too, so the two counts never mix one
// that is still under way from an earlier settle that gave up with the current one.
static int kept_settle(void) {
unsigned current = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1;
if (!kept_drained(current ^ 1)) return 0;
unsigned old = __atomic_fetch_add(&g_close_epoch, 1, __ATOMIC_SEQ_CST) & 1;
return kept_drained(old);
}
// Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending);
// the first nonzero answer of fn is returned, else 0.
static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept,
int (*fn)(unsigned int, unsigned int, void *), void *arg) {
unsigned int from = first;
for (int i = 0; i < nkept && from <= last; i++) {
if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue;
unsigned int k = (unsigned int)kept[i];
if (k > from) {
int r = fn(from, k - 1, arg);
if (r != 0) return r;
}
if (k == last) return 0;
from = k + 1;
}
return from <= last ? fn(from, last, arg) : 0;
}
+26 -2
View File
@@ -240,22 +240,38 @@ static void clear_dns_redirect(int fd) {
int close(int fd) {
static int (*orig_close)(int) = NULL;
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
uint64_t ticket = kept_close_begin();
// The ARM translator's memory file (privileged.c): left open, as if it were closed
if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0;
if (kept_any() > 0 && is_kept_fd(fd)) {
kept_close_end(ticket);
return 0;
}
clear_dns_redirect(fd);
set_chosen_port_fd(fd, 0);
forget_proc_root_fd(fd);
return orig_close ? orig_close(fd) : -1;
int r = orig_close ? orig_close(fd) : -1;
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
int dup2(int oldfd, int newfd) {
static int (*orig_dup2)(int, int) = NULL;
if (!orig_dup2) orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
// the bookkeeping's own locks before the pidfd's: its holder waits on nothing else
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
int saved = errno;
ddh_parent_pidfd_unlock(locked);
errno = saved;
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
return ret;
}
@@ -263,11 +279,19 @@ int dup2(int oldfd, int newfd) {
int dup3(int oldfd, int newfd, int flags) {
static int (*orig_dup3)(int, int, int) = NULL;
if (!orig_dup3) orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
int pidfd_from = -1, locked = 0;
if (oldfd != newfd) {
// the bookkeeping's own locks before the pidfd's: its holder waits on nothing else
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
locked = ddh_parent_pidfd_lock(newfd);
pidfd_from = ddh_parent_pidfd_moves(newfd);
}
int ret = orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
int saved = errno;
ddh_parent_pidfd_unlock(locked);
errno = saved;
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
return ret;
}
+79 -67
View File
@@ -4,41 +4,6 @@
// Calls an app may not make (chown, mknod, capabilities, prctl, landlock, seccomp, namespaces,
// close_range) and the generic syscall() entry point.
// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of
// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it
// translates more code: a program that closes every descriptor it did not open (sshd at start,
// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when
// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code
// themselves have none.
#define DDNATV_MAX_KEPT_FDS 4
static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending
static int g_kept_fd_count = 0;
static int is_kept_fd(int fd) {
for (int i = 0; i < g_kept_fd_count; i++) {
if (g_kept_fds[i] == fd) return 1;
}
return 0;
}
// Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending);
// the first nonzero answer of fn is returned, else 0.
static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept,
int (*fn)(unsigned int, unsigned int, void *), void *arg) {
unsigned int from = first;
for (int i = 0; i < nkept && from <= last; i++) {
if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue;
unsigned int k = (unsigned int)kept[i];
if (k > from) {
int r = fn(from, k - 1, arg);
if (r != 0) return r;
}
if (k == last) return 0;
from = k + 1;
}
return from <= last ? fn(from, last, arg) : 0;
}
#ifndef DDNATV_HOST_TEST
// ndk_translation's file is "/memfd:child"; any memory file counts in a process whose executable is
@@ -438,20 +403,67 @@ int setns(int fd, int nstype) {
#ifndef CLOSE_RANGE_CLOEXEC
#define CLOSE_RANGE_CLOEXEC (1U << 2)
#endif
#ifndef CLOSE_RANGE_UNSHARE
#define CLOSE_RANGE_UNSHARE (1U << 1)
#endif
static int close_range_all(unsigned int first, unsigned int last, int flags);
// Tests only ("IN OUT TID"): before each part it closes, once it has looked at the kept fds, thread
// TID's close_range() writes a byte to OUT and waits for one on IN, as a thread descheduled there
// would.
static void close_range_test_gate(void) {
const char *gate = getenv("DDNATV_TEST_CLOSE_RANGE_GATE");
int in, out, tid;
if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return;
int saved = errno;
char c = 1;
syscall(SYS_write, out, &c, 1);
while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {}
errno = saved;
}
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
close_range_test_gate();
return close_range_all(first, last, *(int *)flags);
}
// The system call itself on the one number no fd has (close_range_all() would emulate a missing call
// by closing fds)
static int close_range_unshare(void) {
static long (*raw_syscall)(long, ...) = NULL;
if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (!raw_syscall) {
errno = ENOSYS;
return -1;
}
return raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) == 0 ? 0 : -1;
}
static int close_range_kept(unsigned int first, unsigned int last, int flags) {
// The table is unshared first, once, even when every fd in the range is kept, and this thread
// goes on with its own copy of the kept list (kept_split()). Without the system call, it is
// emulated where nothing is kept, and refused otherwise.
if (flags & CLOSE_RANGE_UNSHARE) {
if (kept_split(close_range_unshare) == 0) flags &= ~CLOSE_RANGE_UNSHARE;
else if (errno != ENOSYS || kept_any() > 0) return -1;
}
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
if (kept_count == 0) return close_range_part(first, last, &flags);
return for_each_range_without(first, last, kept, kept_count, close_range_part, &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)) {
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);
uint64_t ticket = kept_close_begin();
int r = close_range_kept(first, last, flags);
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
// glibc's closefrom() makes the close_range system call itself, past the function above
@@ -529,7 +541,7 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long
static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) {
long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0);
if (rc == 0) *real = *effective = *saved = 0;
if (rc == 0 && !app_user_mode()) *real = *effective = *saved = 0;
return rc;
}
@@ -821,82 +833,82 @@ long syscall(long number, ...) {
#endif
#if defined(__NR_setresuid)
if (number == __NR_setresuid) return 0;
if (number == __NR_setresuid) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3);
#endif
#if defined(__NR_setresuid32)
if (number == __NR_setresuid32) return 0;
if (number == __NR_setresuid32) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3);
#endif
#if defined(__NR_setresgid)
if (number == __NR_setresgid) return 0;
if (number == __NR_setresgid) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3);
#endif
#if defined(__NR_setresgid32)
if (number == __NR_setresgid32) return 0;
if (number == __NR_setresgid32) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3);
#endif
#if defined(__NR_setuid)
if (number == __NR_setuid) return 0;
if (number == __NR_setuid) return (long)setuid((uid_t)arg1);
#endif
#if defined(__NR_setuid32)
if (number == __NR_setuid32) return 0;
if (number == __NR_setuid32) return (long)setuid((uid_t)arg1);
#endif
#if defined(__NR_setgid)
if (number == __NR_setgid) return 0;
if (number == __NR_setgid) return (long)setgid((gid_t)arg1);
#endif
#if defined(__NR_setgid32)
if (number == __NR_setgid32) return 0;
if (number == __NR_setgid32) return (long)setgid((gid_t)arg1);
#endif
#if defined(__NR_setreuid)
if (number == __NR_setreuid) return 0;
if (number == __NR_setreuid) return (long)setreuid((uid_t)arg1, (uid_t)arg2);
#endif
#if defined(__NR_setreuid32)
if (number == __NR_setreuid32) return 0;
if (number == __NR_setreuid32) return (long)setreuid((uid_t)arg1, (uid_t)arg2);
#endif
#if defined(__NR_setregid)
if (number == __NR_setregid) return 0;
if (number == __NR_setregid) return (long)setregid((gid_t)arg1, (gid_t)arg2);
#endif
#if defined(__NR_setregid32)
if (number == __NR_setregid32) return 0;
if (number == __NR_setregid32) return (long)setregid((gid_t)arg1, (gid_t)arg2);
#endif
#if defined(__NR_setgroups)
if (number == __NR_setgroups) return 0;
if (number == __NR_setgroups) return (long)setgroups((size_t)arg1, (const gid_t *)arg2);
#endif
#if defined(__NR_setgroups32)
if (number == __NR_setgroups32) return 0;
if (number == __NR_setgroups32) return (long)setgroups((size_t)arg1, (const gid_t *)arg2);
#endif
#if defined(__NR_setfsuid)
if (number == __NR_setfsuid) return 0;
if (number == __NR_setfsuid) return (long)presented_uid();
#endif
#if defined(__NR_setfsuid32)
if (number == __NR_setfsuid32) return 0;
if (number == __NR_setfsuid32) return (long)presented_uid();
#endif
#if defined(__NR_setfsgid)
if (number == __NR_setfsgid) return 0;
if (number == __NR_setfsgid) return (long)presented_gid();
#endif
#if defined(__NR_setfsgid32)
if (number == __NR_setfsgid32) return 0;
if (number == __NR_setfsgid32) return (long)presented_gid();
#endif
#if defined(__NR_getuid)
if (number == __NR_getuid) return 0;
if (number == __NR_getuid) return (long)presented_uid();
#endif
#if defined(__NR_getuid32)
if (number == __NR_getuid32) return 0;
if (number == __NR_getuid32) return (long)presented_uid();
#endif
#if defined(__NR_geteuid)
if (number == __NR_geteuid) return 0;
if (number == __NR_geteuid) return (long)presented_uid();
#endif
#if defined(__NR_geteuid32)
if (number == __NR_geteuid32) return 0;
if (number == __NR_geteuid32) return (long)presented_uid();
#endif
#if defined(__NR_getgid)
if (number == __NR_getgid) return 0;
if (number == __NR_getgid) return (long)presented_gid();
#endif
#if defined(__NR_getgid32)
if (number == __NR_getgid32) return 0;
if (number == __NR_getgid32) return (long)presented_gid();
#endif
#if defined(__NR_getegid)
if (number == __NR_getegid) return 0;
if (number == __NR_getegid) return (long)presented_gid();
#endif
#if defined(__NR_getegid32)
if (number == __NR_getegid32) return 0;
if (number == __NR_getegid32) return (long)presented_gid();
#endif
#if defined(__NR_getresuid)
if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
+2
View File
@@ -36,6 +36,8 @@ static void init_ddnatv_hook(void) {
}
}
}
// The SIGSYS handler answers id calls with these and cannot look them up itself
if (app_user_mode()) load_app_ids();
ddnatv_load_binds(getenv("DDNATV_BINDS"), getenv("DDNATV_BINDS_KERNEL"));
const char *mount_table = getenv("DDNATV_MOUNTINFO");
if (mount_table && mount_table[0] == '/' && strlen(mount_table) < sizeof(g_mount_table))
+24
View File
@@ -33,6 +33,27 @@ static void remember_app_sigsys(const struct sigaction *act, struct sigaction *o
}
}
#if defined(__aarch64__)
// An id change the filter refused: root's succeed, an ordinary user's only to the ids it has (as in
// identity.c). setfsuid() and setfsgid() return the id they had.
static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_val) {
if (!app_user_mode()) return ret_val;
uint32_t a = (uint32_t)regs[0], b = (uint32_t)regs[1], c = (uint32_t)regs[2];
switch (nr) {
case 146: return may_set_ids(0, a, UINT32_MAX, UINT32_MAX) ? 0 : -EPERM; // setuid
case 144: return may_set_ids(1, a, UINT32_MAX, UINT32_MAX) ? 0 : -EPERM; // setgid
case 145: return may_set_ids(0, a, b, UINT32_MAX) ? 0 : -EPERM; // setreuid
case 143: return may_set_ids(1, a, b, UINT32_MAX) ? 0 : -EPERM; // setregid
case 147: return may_set_ids(0, a, b, c) ? 0 : -EPERM; // setresuid
case 149: return may_set_ids(1, a, b, c) ? 0 : -EPERM; // setresgid
case 151: return (long)app_uid_now(); // setfsuid
case 152: return (long)app_gid_now(); // setfsgid
case 159: return -EPERM; // setgroups
default: return ret_val;
}
}
#endif
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
if (!ctx || !info) return;
@@ -57,6 +78,9 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
int sys_nr = info->si_syscall;
long ret_val = is_sigsys_synthetic_success_syscall(sys_nr) ? 0 : -ENOSYS;
#if defined(__aarch64__)
ret_val = sigsys_id_change(sys_nr, uctx->uc_mcontext.regs, ret_val);
#endif
#if defined(__aarch64__)
uctx->uc_mcontext.regs[0] = (uint64_t)ret_val;
+24 -2
View File
@@ -234,9 +234,31 @@ ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) {
return orig_sendmsg ? orig_sendmsg(sockfd, msg, flags) : -1;
}
// Whether process pid runs as the app's user (DDNATV_USER=app, which env.c puts first in the
// environment of every program it starts that way)
static int peer_runs_as_app(pid_t pid) {
if (pid <= 0) return 0;
if (pid == getpid()) return app_user_mode();
char path[48];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
int fd = (int)call_orig_syscall(__NR_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
// Servers that pass credentials get them with every message, so only the first entry is read
static const char k_var[] = "DDNATV_USER=app";
char buf[sizeof(k_var)];
long n = call_orig_syscall(__NR_read, fd, (unsigned long)buf, sizeof(buf), 0, 0, 0);
call_orig_syscall(__NR_close, fd, 0, 0, 0, 0, 0);
return n == (long)sizeof(buf) && memcmp(buf, k_var, sizeof(buf)) == 0;
}
// The app's ids are root's for a peer that runs as root, and its own for one that runs as the
// app's user, whichever this process is: a server compares them with what the peer says it is.
static void present_peer_as_root(struct ucred *cred) {
if (cred->uid == (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0)) cred->uid = 0;
if (cred->gid == (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0)) cred->gid = 0;
uid_t app_uid = (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0);
gid_t app_gid = (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0);
if ((cred->uid != app_uid && cred->gid != app_gid) || peer_runs_as_app(cred->pid)) return;
if (cred->uid == app_uid) cred->uid = 0;
if (cred->gid == app_gid) cred->gid = 0;
}
// A server compares a peer's credentials with the user the peer claims, which is getuid()'s 0
+1
View File
@@ -0,0 +1 @@
build/
+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.droiddeck.phantomlab">
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="PhantomLab"
android:extractNativeLibs="true"
android:zygotePreloadName="com.droiddeck.phantomlab.Preload">
<activity android:name=".Main" android:exported="true" android:launchMode="singleTask"
android:configChanges="density|orientation|screenSize|screenLayout|smallestScreenSize|uiMode|keyboard|keyboardHidden|navigation|fontScale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Iso" android:exported="false"
android:isolatedProcess="true" android:useAppZygote="true" />
<service android:name=".IsoPlain" android:exported="false"
android:isolatedProcess="true" />
<service android:name=".Proc" android:exported="false" android:process=":proc" />
<service android:name=".W0" android:exported="false" android:process=":w0" />
<service android:name=".W1" android:exported="false" android:process=":w1" />
<service android:name=".W2" android:exported="false" android:process=":w2" />
<service android:name=".W3" android:exported="false" android:process=":w3" />
<service android:name=".W4" android:exported="false" android:process=":w4" />
<service android:name=".W5" android:exported="false" android:process=":w5" />
<service android:name=".W6" android:exported="false" android:process=":w6" />
<service android:name=".W7" android:exported="false" android:process=":w7" />
</application>
</manifest>
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Builds phantomlab.apk without Gradle: javac, d8, aapt2, the NDK's clang, apksigner (debug key).
# usage: tools/phantomlab/build.sh [out.apk] (ANDROID_SDK_ROOT or ANDROID_HOME must be set)
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
sdk=${ANDROID_SDK_ROOT:-${ANDROID_HOME:?set ANDROID_SDK_ROOT}}
bt=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1)
platform=$(ls -d "$sdk"/platforms/android-* | sort -V | tail -1)
ndk=${ANDROID_NDK_ROOT:-$(ls -d "$sdk"/ndk/* | sort -V | tail -1)}
out=${1:-$here/build/phantomlab.apk}
work=$here/build
exe=""
case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) exe=".exe" ;; esac
bat=""
[ -n "$exe" ] && bat=".bat"
rm -rf "$work/classes" "$work/dex" "$work/lib" "$work/unsigned.apk"
mkdir -p "$work/classes" "$work/dex"
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
case $abi in arm64-v8a) triple=aarch64-linux-android29 ;; x86_64) triple=x86_64-linux-android29 ;; esac
mkdir -p "$work/lib/$abi"
"$host/bin/clang$exe" --target=$triple -shared -fPIC -O2 -Wall -o "$work/lib/$abi/liblab.so" "$here/jni/lab.c" -llog
"$host/bin/clang$exe" --target=$triple -fPIE -pie -O2 -Wall -o "$work/lib/$abi/libplabexe.so" "$here/jni/exe.c"
done
"$bt/aapt2$exe" link -o "$work/unsigned.apk" -I "$platform/android.jar" --manifest "$here/AndroidManifest.xml"
python3 - "$work" <<'EOF'
import os, sys, zipfile
work = sys.argv[1]
with zipfile.ZipFile(os.path.join(work, "unsigned.apk"), "a", zipfile.ZIP_DEFLATED) as z:
z.write(os.path.join(work, "dex", "classes.dex"), "classes.dex")
for abi in os.listdir(os.path.join(work, "lib")):
for so in ("liblab.so", "libplabexe.so"):
z.write(os.path.join(work, "lib", abi, so), "lib/%s/%s" % (abi, so))
EOF
key=$work/debug.keystore
[ -f "$key" ] || keytool -genkeypair -keystore "$key" -storepass android -keypass android -alias lab \
-keyalg RSA -keysize 2048 -validity 10000 -dname "CN=phantomlab" >/dev/null 2>&1
"$bt/zipalign$exe" -f -p 4 "$work/unsigned.apk" "$work/aligned.apk"
"$bt/apksigner$bat" sign --ks "$key" --ks-pass pass:android --out "$out" "$work/aligned.apk"
echo "$out"
+24
View File
@@ -0,0 +1,24 @@
// 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 <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
char buf[128] = "";
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);
if (fd >= 0) {
ssize_t m = read(fd, ctx, sizeof(ctx) - 1);
if (m > 0) ctx[m] = 0;
close(fd);
}
dprintf(2, "plabexe uid=%d ctx=%s fd3=%s\n", getuid(), ctx, n > 0 ? buf : "none");
return 7;
}
+422
View File
@@ -0,0 +1,422 @@
// Native half of phantomlab: forks sleepers, execs in place, and probes what a process may do.
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#include <android/log.h>
#define TAG "PLAB"
JNIEXPORT jint JNICALL Java_com_droiddeck_phantomlab_Native_spawn(JNIEnv *env, jclass cls, jint n) {
int made = 0;
for (int i = 0; i < n; i++) {
pid_t pid = fork();
if (pid == 0) {
for (;;) pause();
}
if (pid > 0) made++;
}
return made;
}
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 0;
int count = 0;
struct dirent *e;
char path[64], target[256];
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);
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len <= 0) continue;
target[len] = 0;
if (strstr(target, "binder")) {
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) {
int n = (*env)->GetArrayLength(env, jargv);
char **argv = calloc(n + 1, sizeof(char *));
for (int i = 0; i < n; i++) {
jstring s = (*env)->GetObjectArrayElement(env, jargv, i);
const char *c = (*env)->GetStringUTFChars(env, s, NULL);
argv[i] = strdup(c);
}
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;
static size_t report_len, report_cap;
static void out(const char *fmt, ...) {
char line[1024];
va_list ap;
va_start(ap, fmt);
int len = vsnprintf(line, sizeof(line), fmt, ap);
va_end(ap);
if (len < 0) return;
if (len >= (int)sizeof(line)) len = sizeof(line) - 1;
if (report_len + len + 2 > report_cap) {
report_cap = (report_len + len + 2) * 2;
report = realloc(report, report_cap);
}
memcpy(report + report_len, line, len);
report_len += len;
report[report_len++] = '\n';
report[report_len] = 0;
}
static void read_small(const char *path, char *buf, size_t size) {
buf[0] = 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
snprintf(buf, size, "<%s>", strerror(errno));
return;
}
ssize_t n = read(fd, buf, size - 1);
close(fd);
if (n < 0) n = 0;
buf[n] = 0;
for (ssize_t i = 0; i < n; i++) if (buf[i] == '\n' || buf[i] == 0) buf[i] = ' ';
}
#if defined(__aarch64__)
static const unsigned char ret42[] = {0x40, 0x05, 0x80, 0x52, 0xc0, 0x03, 0x5f, 0xd6};
#else
static const unsigned char ret42[] = {0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3};
#endif
static int call_code(void *code) {
__builtin___clear_cache((char *)code, (char *)code + sizeof(ret42));
return ((int (*)(void))code)();
}
static void probe_memfd_exec(void) {
int fd = syscall(SYS_memfd_create, "lab", 0);
if (fd < 0) {
out("memfd_exec: memfd_create %s", strerror(errno));
return;
}
write(fd, ret42, sizeof(ret42));
void *p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) out("memfd_exec: mmap exec %s", strerror(errno));
else out("memfd_exec: ran, returned %d", call_code(p));
close(fd);
}
static void probe_anon_exec(void) {
void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memcpy(p, ret42, sizeof(ret42));
if (mprotect(p, 4096, PROT_READ | PROT_EXEC) != 0) out("anon_exec: mprotect %s", strerror(errno));
else out("anon_exec: ran, returned %d", call_code(p));
}
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);
_exit(100 + errno);
}
int status = 0;
waitpid(pid, &status, 0);
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", 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];
ssize_t n;
while (src >= 0 && (n = read(src, buf, sizeof(buf))) > 0) write(mfd, buf, n);
if (src >= 0) close(src);
char *targv[] = {"true", NULL};
st = run_child(targv, mfd);
out("execveat memfd(toybox true): %s", exec_result(st, st == 0 ? "ok" : "status"));
close(mfd);
}
static void probe_fd(int i, int fd) {
struct stat st;
if (fstat(fd, &st) != 0) {
out("fd%d: fstat %s", i, strerror(errno));
return;
}
char target[256] = "";
char path[64];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len > 0) target[len] = 0;
if (S_ISSOCK(st.st_mode)) {
int type = 0, family = 0;
socklen_t sl = sizeof(type);
getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &sl);
struct sockaddr_storage ss;
socklen_t al = sizeof(ss);
getsockname(fd, (struct sockaddr *)&ss, &al);
family = ss.ss_family;
if (family == AF_INET && type == SOCK_STREAM) {
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);
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
out("fd%d udp: connect %s", i, r == 0 ? "ok" : strerror(errno));
} else {
char buf[64] = "";
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));
}
return;
}
if (S_ISDIR(st.st_mode)) {
int f = openat(fd, "probe.txt", O_RDONLY);
out("fd%d dir %s: openat child %s", i, target, f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
return;
}
char buf[64] = "";
ssize_t r = pread(fd, buf, sizeof(buf) - 1, 0);
if (r > 0) buf[r - 1] = 0;
out("fd%d file %s: read %s", i, target, r >= 0 ? buf : strerror(errno));
void *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
out("fd%d mmap read: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
if (p != MAP_FAILED) munmap(p, 4096);
p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
out("fd%d mmap exec: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
if (p != MAP_FAILED) munmap(p, 4096);
char *argv[] = {"x", NULL};
int st2 = run_child(argv, fd);
out("fd%d execveat: %s", i, exec_result(st2, "ran"));
}
static void probe_self(void) {
char buf[512];
out("uid=%d gid=%d pid=%d ppid=%d", getuid(), getgid(), getpid(), getppid());
read_small("/proc/self/attr/current", buf, sizeof(buf));
out("selinux: %s", buf);
read_small("/proc/self/cgroup", buf, sizeof(buf));
out("cgroup: %s", buf);
int s = socket(AF_INET, SOCK_STREAM, 0);
out("socket(AF_INET): %s", s >= 0 ? "ok" : strerror(errno));
if (s >= 0) close(s);
s = socket(AF_UNIX, SOCK_STREAM, 0);
out("socket(AF_UNIX): %s", s >= 0 ? "ok" : strerror(errno));
if (s >= 0) close(s);
int f = open("/data/data/com.droiddeck.phantomlab/files/probe.txt", O_RDONLY);
out("open app data by path: %s", f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
const char *gpus[] = {"/dev/kgsl-3d0", "/dev/mali0", "/dev/dri/renderD128", NULL};
for (int i = 0; gpus[i]; i++) {
if (access(gpus[i], F_OK) != 0) continue;
f = open(gpus[i], O_RDWR);
out("open %s: %s", gpus[i], f >= 0 ? "ok" : strerror(errno));
if (f >= 0) close(f);
}
}
static void probe_pid(const char *spec) {
int pid = atoi(spec);
char path[64], buf[256];
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
read_small(path, buf, sizeof(buf));
out("read /proc/%d/cmdline: %s", pid, buf);
out("kill(%d, 0): %s", pid, kill(pid, 0) == 0 ? "ok" : strerror(errno));
out("kill(%d, SIGCONT): %s", pid, kill(pid, SIGCONT) == 0 ? "ok" : strerror(errno));
}
static void try_write(const char *path, const char *value) {
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) {
out("write %s: open %s", path, strerror(errno));
return;
}
ssize_t n = write(fd, value, strlen(value));
out("write %s: %s", path, n >= 0 ? "ok" : strerror(errno));
close(fd);
}
// Every way a process could leave the cgroup Android counts it in.
static void probe_escape(void) {
char own[256], pid[32], path[300];
read_small("/proc/self/cgroup", own, sizeof(own));
char *v2 = strstr(own, "0::");
char dir[200] = "";
if (v2) sscanf(v2 + 3, "%199s", dir);
snprintf(pid, sizeof(pid), "%d", getpid());
try_write("/sys/fs/cgroup/cgroup.procs", pid);
char parent[200];
snprintf(parent, sizeof(parent), "%s", dir);
char *slash = strrchr(parent, '/');
if (slash) *slash = 0;
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/cgroup.procs", parent);
try_write(path, pid);
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/lab", dir);
out("mkdir %s: %s", path, mkdir(path, 0755) == 0 ? "ok" : strerror(errno));
int r = syscall(SYS_unshare, 0x10000000 /* CLONE_NEWUSER */);
out("unshare(CLONE_NEWUSER): %s", r == 0 ? "ok" : strerror(errno));
r = syscall(SYS_unshare, 0x02000000 /* CLONE_NEWCGROUP */);
out("unshare(CLONE_NEWCGROUP): %s", r == 0 ? "ok" : strerror(errno));
int cg = open("/sys/fs/cgroup", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (cg < 0) {
out("open /sys/fs/cgroup: %s", strerror(errno));
} else {
struct {
unsigned long long flags, pidfd, child_tid, parent_tid, exit_signal, stack, stack_size, tls, set_tid,
set_tid_size, cgroup;
} args = {.flags = 0x200000000ULL /* CLONE_INTO_CGROUP */, .exit_signal = SIGCHLD, .cgroup = (unsigned)cg};
long child = syscall(435 /* clone3 */, &args, sizeof(args));
if (child == 0) _exit(0);
if (child > 0) waitpid(child, NULL, 0);
out("clone3(CLONE_INTO_CGROUP, root): %s", child > 0 ? "ok" : strerror(errno));
close(cg);
}
}
// Runs path with fd as its fd 3 and its stderr captured.
static void probe_libexec(const char *path, int fd) {
int pipefd[2];
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);
char *argv[] = {(char *)path, NULL};
execv(path, argv);
dprintf(2, "execv: %s", strerror(errno));
_exit(127);
}
close(pipefd[1]);
char buf[512] = "";
ssize_t n = read(pipefd[0], buf, sizeof(buf) - 1);
if (n > 0) buf[n] = 0;
char *nl = strchr(buf, '\n');
if (nl) *nl = 0;
close(pipefd[0]);
int status = 0;
waitpid(pid, &status, 0);
out("exec %s: status %d, said \"%s\"", path, WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status), buf);
}
JNIEXPORT jstring JNICALL Java_com_droiddeck_phantomlab_Native_probe(JNIEnv *env, jclass cls, jstring jwhat, jintArray jfds) {
report_len = 0;
if (report) report[0] = 0;
const char *what = jwhat ? (*env)->GetStringUTFChars(env, jwhat, NULL) : "self";
int n = (*env)->GetArrayLength(env, jfds);
jint *fds = (*env)->GetIntArrayElements(env, jfds, NULL);
char spec[1024];
snprintf(spec, sizeof(spec), "%s", what);
char *save = NULL;
for (char *tok = strtok_r(spec, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
if (!strcmp(tok, "self")) probe_self();
else if (!strcmp(tok, "memfd_exec")) probe_memfd_exec();
else if (!strcmp(tok, "anon_exec")) probe_anon_exec();
else if (!strcmp(tok, "exec")) probe_exec();
else if (!strcmp(tok, "fds")) for (int i = 0; i < n; i++) probe_fd(i, fds[i]);
else if (!strncmp(tok, "pid=", 4)) probe_pid(tok + 4);
else if (!strcmp(tok, "escape")) probe_escape();
else if (!strncmp(tok, "libexec=", 8)) probe_libexec(tok + 8, n > 0 ? fds[0] : -1);
}
(*env)->ReleaseIntArrayElements(env, jfds, fds, 0);
return (*env)->NewStringUTF(env, report ? report : "");
}
@@ -0,0 +1,3 @@
package com.droiddeck.phantomlab;
public class Iso extends LabService {}
@@ -0,0 +1,3 @@
package com.droiddeck.phantomlab;
public class IsoPlain extends LabService {}
@@ -0,0 +1,91 @@
package com.droiddeck.phantomlab;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.util.Log;
import java.io.IOException;
public class LabService extends Service {
static final int SPAWN = 1;
static final int PROBE = 2;
static final int EXEC = 3;
static final int WHO = 4;
private final Handler handler = new Handler(Looper.getMainLooper());
private final Binder binder = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
switch (code) {
case SPAWN: {
int n = data.readInt();
reply.writeInt(Native.spawn(n));
return true;
}
case PROBE: {
String what = data.readString().replace("libexec",
"libexec=" + getApplicationInfo().nativeLibraryDir + "/libplabexe.so");
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: {
final String[] argv = data.createStringArray();
final boolean keep = data.readInt() != 0;
Log.i(Main.TAG, "pid " + Process.myPid() + " execs " + String.join(" ", argv) + " keepBinder=" + keep);
handler.postDelayed(() -> Native.execInPlace(argv, keep), 500);
reply.writeInt(Process.myPid());
return true;
}
case WHO:
reply.writeString("pid=" + Process.myPid() + " uid=" + Process.myUid()
+ " isolated=" + Process.isIsolated());
return true;
default:
return false;
}
}
};
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);
}
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i(Main.TAG, getClass().getSimpleName() + " bound in pid " + Process.myPid() + " uid " + Process.myUid());
return binder;
}
}
@@ -0,0 +1,333 @@
package com.droiddeck.phantomlab;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
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
* Results go to logcat under the PLAB tag.
*/
public class Main extends Activity {
static final String TAG = "PLAB";
private static final Map<String, IBinder> binders = new HashMap<>();
private static final Map<String, List<Task>> pending = new HashMap<>();
private static final Map<String, ServiceConnection> connections = new HashMap<>();
private static final ExecutorService worker = Executors.newSingleThreadExecutor();
private TextView text;
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<ParcelFileDescriptor> sent = new ArrayList<>();
final List<FileDescriptor> 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) {
super.onCreate(state);
text = new TextView(this);
setContentView(text);
log("main pid " + Process.myPid() + " uid " + Process.myUid());
handle(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handle(intent);
}
private void log(String s) {
Log.i(TAG, s);
runOnUiThread(() -> text.append(s + "\n"));
}
private static Class<?> serviceClass(String target) {
String base = target.contains(":") ? target.substring(0, target.indexOf(':')) : target;
switch (base) {
case "iso": return Iso.class;
case "isoplain": return IsoPlain.class;
case "proc": return Proc.class;
default:
if (base.startsWith("w")) {
try {
return Class.forName("com.droiddeck.phantomlab.W" + base.substring(1));
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(target);
}
}
throw new IllegalArgumentException(target);
}
}
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<Task> q = pending.get(target);
if (q == null) {
q = new ArrayList<>();
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<Task> ops = pending.remove(target);
if (ops != null) for (Task t : ops) t.run(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
log("DISCONNECTED " + target);
binders.remove(target);
}
@Override
public void onBindingDied(ComponentName name) {
log("BINDING DIED " + target);
if (connections.get(target) != this) return;
List<Task> ops = pending.remove(target);
unbind(target);
if (ops != null) {
pending.put(target, ops);
bind(target);
}
}
};
connections.put(target, conn);
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);
}
}
private void unbind(String target) {
ServiceConnection c = connections.remove(target);
binders.remove(target);
List<Task> 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();
binder.transact(code, data, reply, 0);
return reply;
}
private void handle(Intent intent) {
String cmd = intent.getStringExtra("cmd");
if (cmd == null) return;
String target = intent.getStringExtra("target");
try {
switch (cmd) {
case "spawn": {
int n = intent.getIntExtra("n", 10);
if ("main".equals(target)) {
log("main spawned " + Native.spawn(n));
return;
}
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, "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, "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");
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": {
unbind(target);
log("unbound " + target);
return;
}
default:
log("unknown cmd " + cmd);
}
} catch (Exception e) {
log(cmd + " failed " + e);
}
}
/** fds: comma separated list of tcp, udp, file:<name>, unix, memfd. */
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));
}
}
} catch (Exception e) {
try {
fds.close();
} catch (IOException ignored) {
}
throw e;
}
return fds;
}
}
@@ -0,0 +1,16 @@
package com.droiddeck.phantomlab;
final class Native {
static {
System.loadLibrary("lab");
}
/** Forks n children that sleep until killed; returns how many were started. */
static native int spawn(int n);
/** execve(argv) in this process; with keepBinder, the binder fds stay open across it. */
static native void execInPlace(String[] argv, boolean keepBinder);
/** Runs the capability probes named in what, using the given fds; returns a report. */
static native String probe(String what, int[] fds);
}
@@ -0,0 +1,10 @@
package com.droiddeck.phantomlab;
import android.app.ZygotePreload;
import android.content.pm.ApplicationInfo;
public class Preload implements ZygotePreload {
@Override
public void doPreload(ApplicationInfo appInfo) {
}
}
@@ -0,0 +1,3 @@
package com.droiddeck.phantomlab;
public class Proc extends LabService {}
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more