Commit Graph
15 Commits
Author SHA1 Message Date
2d25fb91c5 Run Easy Anti-Cheat and BattlEye games on x86-64 DroidDeck-Proton under FEX (#3641)
* FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers

* Guest hook: route raw execve/execveat through the exec wrapper and pass self-sent SIGSYS to the program

A program that execs with syscall(SYS_execveat, ...) bypassed the environment the
guest needs, so re-executing /proc/self/exe died in the loader. /proc/self/exe now
maps to the real program on exec as it already does on open.

A SIGSYS the program queues itself, or one from a filter for another architecture,
went to the Android-filter emulation instead of the program's handler.

* FEX: list only guest mappings in /proc/<pid>/maps on hosts below 47 address bits

Credit the anti-cheat emulation source in the patch header.

* Preloads: leave poll, ppoll and select buffers untouched when no emulated device is open

A bad user pointer now reaches the kernel and returns EFAULT instead of crashing the caller inside the wrapper.

* Emulate only host-architecture seccomp traps in the guest hook; report the calling thread's seccomp mode in FEX's /proc/self/status

A SIGSYS carrying another architecture's seccomp siginfo now takes its default action when the program has no handler, so a process whose emulated filter traps a syscall while SIGSYS is blocked or ignored dies as on Linux.

* FEX: read the host status file through the raw openat syscall

* README: credit StonkGuy's FEX anti-cheat emulation

* FEX: open the host status file with a direct system call so preloads cannot rewrite it

* FEX: hand a traced program's ptrace state across exec

* Credit StonkGuy in the FEX anti-cheat patches and README

Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com>

* FEX: open guest paths with the raw openat system call so host preloads cannot replace the file

* FEX: serve emulated proc files by the requested path when the host returns a memfd

* FEX: map fixed guest memory above a small host address space

Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>

* FEX: serve decoder reads from fixed guest memory above the host limit

* Run games with anti-cheat files on an x86-64 DroidDeck-Proton under FEX

The Proton launchers look for Easy Anti-Cheat or BattlEye bridge files in
the game folder and, when an x86-64 DroidDeck-Proton and the matching Proton
runtime are installed, hand the launch to that Proton under FEX with the
game's own prefix. Picking the x86-64 tool directly also runs it under FEX.
DROIDDECK_ANTICHEAT=off keeps a game on ARM64.

* Keep x86-64 DroidDeck-Proton builds out of the ARM64 tool list

* droiddeck-fex: take the runtime from an adopted tool's original manifest

* FEX: show the guest command line when the argument area cannot be remapped

* FEX: describe the container's procfs in emulated mount tables

* FEX: order the anti-cheat series after the guest stack patch from main

* Test the container procfs view of FEX's emulated mount tables

* Docs: describe the anti-cheat signal mask fix and the container procfs view

* README: match the StonkGuy credit to the renumbered FEX patches

* Keep anti-cheat games on a tool the user chose instead of moving them to x86-64

* test(game-env): build the adopted-tool wrapper through extra_wrapper_sh

* Check anti-cheat runtime bridges, apply component choices under FEX and honour MAP_FIXED_NOREPLACE above the host limit

* Check the driver query is answered before each wrapper's call sites

* Keep x86-64 Proton builds out of the automatic default tool

* Keep high guest mappings intact when a fixed map or unmap fails

Check room in the region table, splits included, before a fixed map or
unmap removes anything, return the host munmap error without touching
the table entry, and keep write-protecting low shared aliases of
executable ranges that sit above the host address limit.

* Keep a requested x86-64 default and accept linked anti-cheat runtimes

A request for the current automatic x86-64 default now marks it as the
app's choice, so the next settle no longer moves it back to ARM64.
Anti-cheat runtime discovery follows a symlinked runtime directory.

* Route anti-cheat games to x86-64 Proton only on a capable FEX

The FEX build now lists its patches in share/fex-emu/.droiddeck-patches.
Anti-cheat routing needs the fixed guest memory patch in that list and
otherwise keeps the launch on ARM64, as an older FEX cannot map the
anti-cheat helper buffer above the host address limit. Installing a FEX
build without the list removes a list left by an earlier build.

* Update FEX before deciding anti-cheat routing

A device on an older FEX build never went through droiddeck-fex on the
ARM64 path, so the catalog FEX was never installed and the gate kept
anti-cheat games on ARM64 forever. dd_anticheat now runs the new
droiddeck-fex update action first, which installs the catalog build
under the same lock and retry window as other FEX launches.

* Leave MAP_FIXED_NOREPLACE above the host limit to the host

Wine finds the top of the address space with MAP_FIXED_NOREPLACE probes.
Claiming those probes above a 39-bit host limit made Wine place its stacks
in relocated memory, and every wineserver request then failed with EFAULT
because the iovec buffers it passes to writev are nested pointers that are
not translated. Only MAP_FIXED requests are relocated again, so the probes
see the real host limit while fixed mappings above it keep working.

* Translate only pointer syscall arguments into high guest memory

Pointer arguments are now picked from a per-syscall layout table, so
scalar values such as a truncate length are never rewritten. Sized
buffers must map to one contiguous host range or the call fails with
EFAULT, and new host backings are placed next to their guest
neighbours so adjacent mappings stay contiguous. readv, writev and the
preadv/pwritev family, sendmsg and recvmsg get a host-side copy of
their iovec and msghdr with translated bases, leaving the guest copies
untouched. Code invalidation for kernel writes maps the host buffer
back to its guest address, and an unmap checks the table before it
changes any host mapping.

* Claim high guest memory only with LSE atomics and invalidate every code alias

High guest mappings are claimed only when the JIT emits LSE atomics, and
exclusive load/store instructions are never single-stepped, so an atomic
on high memory cannot spin. A store into high code invalidates every
mirror of the written page through the tracked mapping. madvise and
mprotect on high memory apply to each region at its own host address.

* Reject wrapping lengths and drop stale code on discarded high memory

A nonzero length that wraps when page-aligned now fails madvise with
EINVAL and mprotect with ENOMEM, as on Linux. Discarding advice on
high memory invalidates translated code for the range whenever advice
reached any region.

* Add an end-to-end probe for guest memory above the host address limit

* Emulate exclusive pairs on high guest memory and release failed host unmaps later

* Size counted guest buffers by element and keep exclusive access within guest protection

poll, ppoll, epoll waits, mmsg calls and select bitmaps now translate the whole array their count describes, so a buffer that crosses into an unrelated host range fails with EFAULT and oversized counts cannot wrap. High regions remember their protection through mprotect, splitting at the range edges, and exclusive stores to read-only pages or loads from inaccessible pages reach the guest as a fault instead of being emulated.

* Refuse a high unmap when failed host unmaps could not all be retained

UnmapLocked counts the overlapping regions before it changes anything and returns ENOMEM when the retired list could not hold all of them, so a host range is never dropped from tracking while still mapped.

* Serve memory trim requests while syscall user dispatch blocks

A thread that runs with syscall user dispatch on and its selector set to
block (as x86-64 Wine does while in Windows code) took the trim signal
with the selector still blocking. Every raw syscall the handler made was
then dispatched to the program's SIGSYS handler, which either deadlocked
the thread or killed the process when SIGSYS was blocked, so the session
saw it as a deaf process and the game stalled during loading.

Track the selector each thread registers through prctl, allow syscalls
for the length of the handler and restore the selector before returning.

* Allow syscalls for a forwarded prctl while dispatch blocks

The prctl wrapper issues its syscall from the preload's own text, so a
thread whose selector blocks got SIGSYS where the plain libc call would
have been dispatched the same way by the caller's own rules. Allow
syscalls for the forwarded call and restore the selector afterwards.

The dispatch test now waits until the selector blocks before it sends
the trim request, and checks a prctl call made while it blocks.

* Merge high regions after protection changes and translate message batches

Protect now merges neighbouring high regions whose guest and host
ranges touch and whose protection and code state match, so toggling
page protections no longer fills the region table.

Exclusive loads on high memory accept write-only pages and exclusive
stores need only PROT_WRITE, matching x86-64 where writable pages are
readable.

sendmmsg and recvmmsg translate the name, control and io vectors of
every message in the batch, return msg_len for each processed message
and the received header fields for recvmmsg.

Counted arrays passed to getgroups, setgroups, semop, semtimedop,
io_submit, io_getevents, io_pgetevents, move_pages, futex_waitv and
listmount are now checked to stay within one host range. The unused
ToHost helper is removed.

* Translate fixed-size, string and in-array guest pointers in high memory

Give every syscall pointer without a length a fixed x86-64 size, a
length read through another argument, or a terminator scan for strings,
so spans crossing separately backed regions are refused before the
kernel sees them. Size message queue buffers as the type word plus
msgsz. Translate io_submit control blocks and their buffers, including
vectored reads and writes, through bounded host copies, restore the
guest words afterwards, and report guest iocb addresses back from
io_getevents. Translate move_pages page lists for the calling process
and futex_waitv addresses. Merge new mappings with matching neighbours.

* Size high-memory syscall spans by kernel widths and embedded sizes

Read counts with the width the kernel uses for each argument, so int
and unsigned int counts ignore the upper register bits and negative
counts reach the handler. Size capability data by its header version,
perf and scheduler attributes, file handles and mount requests by their
own size fields, and landlock rules by rule type. Keep the translated
prefix of a message batch, read headers that span separate backings one
by one, write results back through the current guest mapping, and stop
counting messages whose length cannot be stored. Revisit an entry moved
into an earlier slot while merging regions. Give newer syscalls
fallback numbers in the test harness.

* Send translated message batches one message at a time

Submit sendmmsg batches that need scratch headers one message per call,
storing each length before the next message goes out, so a length that
cannot be stored stops the batch where Linux would. Skip the name length
when no name was given and store flags before the control length. Check
the whole fixed file-handle header even when its size is invalid. Hand
capget and capset a private header so the checked data size matches the
version the kernel reads, and return a rewritten version to the guest.
Patch and restore AIO control blocks under the mapping lock and restore
only the block that was patched.

* Harden high-memory aio, capability and message batch write-backs

Restore patched aio buffers through /proc/self/mem when the control block
became read-only and keep the scratch vectors alive if that fails too,
fault capability calls whose header write-back fails, stop send batches
after a short message, and pin the batch socket with a private dup.

* Pin batch sockets, fall back to whole batches and reconcile pending aio restores

Follow-up message sends and the first dispatch share one duplicated
socket. When it cannot be duplicated, the whole translated batch goes
to the kernel in one call and lengths are written back up to the first
one that cannot be stored. Short sends compare against the iovec
lengths given to the kernel. Unrestorable aio_buf edits, including
unreadable control blocks, keep their storage in a bounded list that
later submissions reconcile.

* Stop message batches at unreadable vectors, send singly without a spare descriptor and reserve aio restore slots

A message whose iovec snapshot cannot be taken ends the prepared batch
instead of being sent with an unknown length; when it is the first
message the kernel handles the original array natively. When the
batch socket cannot be duplicated, messages still go one at a time on
the original descriptor with each length written before the next send.
Pending aio restore slots are reserved under the pending mutex before
the first guest edit and released or handed to the pending record, so
concurrent submissions cannot exceed the bound. Tests use a real
socket pair, injected descriptor exhaustion and concurrent
reservations.

* Send only the first message of a batch when the socket cannot be pinned

* Replay high-memory faults over the whole access and reconcile aio restores on unmap

* Keep high-memory traps ordered, fault-exact and locked against unmap

Protect, Map and low mmap/munmap/mremap/mprotect reconcile pending aio
restores at once, and io_submit reconciles them even when no high region
is mapped. Ordered loads and stores split across backings are emulated
between full fences instead of being byte-copied through the trampoline;
atomics and exclusives are still refused. Gather and scatter use
fault-safe copies, and a failing piece is re-faulted at the guest
instruction through a probe load, with SIGBUS redelivered the same way.
The VMA lock is held from planning until the scatter finishes, so unmap
and protect cannot race a resumed access. Sign-extending loads are no
longer classified as writes.

* Defer user signals while guest high memory mappings are held

Only the trampoline breakpoint completes a replay, user-sent SIGSEGV,
SIGBUS and SIGTRAP raised while the mapping lock is held are requeued
after it is released, and stranded control block words are restored
when their page turns readable again. The harness now runs under a
timeout.

* Rebase the FEX patch series onto FEX-2612

* FEX: restore stranded aio words before readable protection, report failures

Restore every pending aio word in the range before a readable guest
protection is applied, on both the high and low paths, and fail the guest
mprotect with the old protection kept when a word cannot be restored or its
window cannot be closed. Ignore user-sent SIGSEGV/SIGBUS after deferral,
read the cleared syscall info when resuming with guest GPRs and on restore,
and check exclusive acquisition from a separate thread in the harness.

* FEX: submit aio control blocks through private host copies

Stop editing guest IOCBs in place when aio_buf needs translation. io_submit
now hands the kernel a host copy of each such control block, maps
io_event.obj back to the guest pointer when the completion is reaped,
redirects io_cancel by guest pointer and context to the copy, and frees
copies on reap, on io_destroy, or when the kernel did not accept them.
The guest control block is never patched and its protection is never
touched, so the pending restore records, the protection windows and the
restore hooks in mmap, munmap, mremap and mprotect are removed with their
tests.

* fex: keep aio keys, cancels and reaped events native for copied control blocks

Guest aio_key is no longer cleared before dispatch: the slot is probed with a
same-value write and only the first n accepted copies get key 0 after the host
io_submit returns n. io_cancel redirects to a copy only when the guest block is
readable and its key is 0, so unreadable blocks fault in the kernel as before.
io_getevents and io_pgetevents reap into emulator storage, translate and
release copies there, then copy the events out, returning -EFAULT if that
fails. A successful io_setup clears the ring header magic so userspace ring
reapers fall back to io_getevents, where copies are translated and released.

* fex: leave aio rejections, keys and unwritable event buffers to the kernel

A copied control block whose key slot is read-only is now passed to the
kernel as the guest's own block at the end of the list, so the kernel reports
its native fd, eventfd or key error. After io_submit, guest keys follow the
private copies through the first rejected position, and they are stored
through a fresh translation of the guest address, skipped when it no longer
maps. io_getevents and io_pgetevents probe the guest event buffer and reap at
most its writable prefix, handing an unwritable buffer to the kernel so
completions are not consumed.

* Kept AIO completions and key stores stable against sibling remaps

Wrapped event buffers go to the kernel unchanged. Direct reaps report guest
control blocks and release copies only after the store lands. Guest stores and
reads hold the mapping lock across translation and copy. Completions whose
copy-out fails are stashed per context and delivered first on the next reap,
and dropped on io_destroy.

* fex: stage every AIO reap and keep stashed completions recoverable

Hold the guest mapping for every high address, restore the caller's
signal mask after thread-context holds, replace the fixed event stash
with a per-context table that reserves space before dispatch, stage
all reaps so control block identities are translated before copy-out,
keep collecting ready completions once the stash meets min_nr, and
restash events on every error except an interrupted delivery or a
destroyed context.

* fex: own AIO recovery storage before dispatch and bind it to the context lifetime

Allocate the recovery node with the event buffer before the kernel
consumes completions and hand the buffer itself to the stash when
copy-out fails, so settling never allocates. Track each context by a
generation that io_setup advances, so a destroy that finishes after a
replacement context reuses the ring address only releases the old
context's copies and stash. Drop the reservation cap so blocking reaps
keep their min_nr.

* fex: publish AIO contexts from private storage, keep their generation, wake blocked reapers for stashed completions

* fex: wait for AIO events in bounded slices instead of wake markers, roll back setup by its own generation, fault unreadable io_setup output

Blocked reapers wait in the kernel for at most 20 ms at a time and take stashed completions between waits until the guest minimum or timeout is met, so no eventfd or io_submit notification is needed. Deferred signals end the wait like EINTR. io_setup rollback uses the generation BeginContext installed, and an unreadable context output returns -EFAULT before dispatch.

---------

Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com>
Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>
2026-12-05 02:26:42 -05:00
Kurt Himebauch 20df8b1858 fix(nativeguest): reap the zombies session processes adopt as subreapers and never wait for (#3610) 2026-12-02 20:31:58 -05:00
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
The412Banner aaa9fb129c fix(nativeguest): programs on a mount kept at its host path start as guest programs (#3211) 2026-11-29 23:58:32 -05:00
Kurt Himebauch c0abf31a6b fix(native): start popen() and system() shells with posix_spawn (#3357) 2026-11-27 23:02:08 -05:00
MaxsTechReview 9be131cf6d fix(native): a trailing slash after a program keeps the hook's exe name like the kernel (#3171) 2026-11-24 18:24:41 -05:00
MaxsTechReview 14b130500f fix(desktop): a program started through a directory link knows its real path (#3158)
* fix(desktop): a program started through a directory link knows its real path

* fix(desktop): a missing or non-directory component still fails the lookup
2026-11-24 16:23:06 -05:00
MaxsTechReview fbeefc9c9a fix(desktop): programs started by name run scripts without a shebang line (#3155) 2026-11-24 15:33:49 -05:00
MaxsTechReview e709e1c454 fix(desktop): Go programs see the session's identity and paths (#3154)
* fix(desktop): Go programs see the session's identity and paths

Static Go programs now get the session's root identity from getuid and its
relatives, and set*id calls succeed, as C and x86 programs already do. The
added code also takes over Go's second raw system call function (and its
golang.org/x/sys copy), which getuid goes through.

Go programs that link the C library (snapd, gocryptfs, ipp-usb) get the same
code: their Go note is found past the other notes, and the code fits before
a data segment that does not start on a page boundary. snap now reaches the
session's snapd and installs snaps.

* fix(desktop): read every Go note and retry Go programs after a failed scan
2026-11-24 14:07:01 -05:00
MaxsTechReview e349d2544e fix(nativeguest): a script interpreter reached through a bind runs as a guest program (#3112)
* fix(nativeguest): a script interpreter reached through a bind runs as a guest program

A Flatpak runtime binds its own /usr outside the sandbox root, so the hook
took #!/usr/bin/bash there for an Android program and handed it to the
kernel, which failed with "bad interpreter". An interpreter whose guest
path is a bind now starts like any guest program.

* Native hook: keep Android interpreters a bind reaches on the host

* Native hook: match the root of an interpreter on a folder boundary
2026-11-23 23:42:04 -05:00
MaxsTechReview 823f70320f fix(nativeguest): x86-64 path calls, SIGSYS handlers and re-execs stay inside the rootfs hook (#3074)
* fix(nativeguest): x86-64 path system calls and SIGSYS handlers stay inside the rootfs hook

FEX passed most guest path system calls to the kernel with an inline svc, so the
native path hook never mapped them, and it mirrored guest SIGSYS handlers with a
raw rt_sigaction that replaced the hook's own handler, after which the next
blocked system call killed the program. Path calls now go through libc's
syscall(), which the hook maps (guarded until the hook is initialised so an early
allocator cannot deadlock), and a SIGSYS handler set through syscall() is
recorded and chained like one set through sigaction().

* fix(ddexec): a program that re-execs itself keeps the rootfs hook

A re-exec through /proc/self/exe starts the program through the guest
ld.so again but left out the hook, so the child saw host paths. Steam's
reaper then recorded host install folders, and Battle.net games moved to
a mapped drive the Library could not resolve. The re-exec now preloads
the hook of the root the same way the first start does.
2026-11-23 11:11:10 -05:00
The412Bannerandmaxjivi05 bf7f7ecda7 fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs (#3054)
* fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs

* fix(nativeguest): keep the existing ld.so start comments

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-23 10:40:16 -05:00
Kurt Himebauch dc98b6b96a feat: target Android 14 so Play Protect installs DroidDeck without a warning (#2683)
* fix(proot): ship proot in the APK and run it from the native library directory

* fix(native): start rootfs programs through an APK-shipped exec loader where data files may not be executed

* fix(audio): start PulseAudio through the system linker where data files may not be executed

* feat: target Android 14 (SDK 34) so Play Protect installs DroidDeck without a warning

* fix: ask for all-files access on Android 11+, reject unloadable ELFs before exec, keep checking the proot pack

* fix: hand host scripts to the kernel, skip startup launch while all-files Settings is open

* fix: run proot from its add-on pack through Android's linker, so the APK carries no proot

* fix: declare high sampling rate sensors for controller gyro at target 34

* fix: offer the rootfs proot fallback only where Android lets proot exec its loader

* test: install the runtime's proot pack in GameFileSync fixtures
2026-11-16 09:35:16 -05:00
Kurt Himebauch 2848484a99 feat: fuck proot and proots mama (#2300)
* feat: experimental native userland that runs the Linux side without proot

* fix(native): keep the visible name of link2symlink binaries

* fix(ci): run the native hook build through bash

* fix(native): address review findings in the hook and the ctl fallback

* fix(ctl): use the broadcast fallback only when content is missing

* fix(native): survive Android's seccomp filter in ld.so, libc and posix_spawn children

* docs(native): how to test under Android's seccomp filter

* fix(session): hide an unlistable /sys/bus/pci/devices so libpci does not abort Chromium's GPU init

* fix(native): nested syscall() redirects no longer loop with libblsession's openat2

* fix(native): controllers reach Steam and the install-script evaluator no longer blocks game moves

* fix(native): write the hook's NUL character literals as escapes

* fix(native): proot fast path turns off and greys out while running without proot

* fix(native): D-Bus logins work and Xwayland still admits root once peers read as root

* fix(native): scripts on session mounts outside the rootfs run with the rootfs shell

* fix(native): games on the SD card library start in their own folder

* fix(native): Wine drive links proot made point at their real places

* fix(native): at-calls, uid lookups and relative programs follow the session's mounts

* fix(native): close-from in spawned programs covers what is open at the spawn

* fix(native): service names resolve and the DNS fallback answers what was asked

* build(native): the hook is built with its Go support and tracked by the preload recipe

* fix(native): drive links into identity mounts stay, and relink and seccomp patch failures are logged

* fix(native): seccomp-sim's filter holds every allowed call

* fix(ctl): the broadcast fallback only stands in for a missing content command

* fix(native): pre-2.33 glibc stat calls present owners as root too

* fix(native): res_init and res_ninit call glibc, so Steam's store resolves names

* fix(ci): a preload lock older than a new output rebuilds that group, and generated headers are not hashed

* fix(native): a second seccomp patch run leaves other system calls alone

* fix(native): the terminal and bottom desktop keep proot's environment in a native session

* fix(native): any number of session mounts, and openat2 relative to a mounted folder

* fix(agent): a native command's stdin is written beside its timeout

* fix(ctl): native rejects --env without = and timeouts outside 0-600 s

* fix(native): the resolver fallback has the network's IPv6 servers, and lookups keep the fallback's validation errors

* fix(native): a spawn whose dup2 source close-from closed fails with EBADF

* fix(native): __getcwd_chk checks its buffer, and seccomp-sim -a takes only call numbers

* feat(native): guests see the session hostname from uname and gethostname

* feat(native): the terminal and bottom desktop run without proot

* fix(components): an origin APK without a newer preload output still proves the rest

* fix(native): seccomp-sim -a rejects empty fields

* fix(native): gethostbyname no longer answers failed lookups with Ubuntu and Debian addresses

* feat(native): store installers, root helpers, Comet and Xodus run without proot

* fix(native): the hook finds libraries, preloads and itself through a sandbox's mounts, and ldconfig -C makes its cache

* feat(native): Flatpak sandboxes run without proot, and apply_extra runs without a runtime

* fix(native): remove, glob and nftw take guest paths, and links in a mount are followed as the guest sees them

* fix(native): Flatpak sandboxes get the session's mounts, their libraries' RUNPATHs, and no rootfs-only settings

* fix(native): gethostbyname asks the network's DNS servers, nftw of / gives single slashes, and the library path fits mapped directories

* fix(native): a native process starts in its working directory's real place

* fix(native): the library path given to ld.so holds whole directories only

* fix(native): Wine drive links keep their guest paths, so proot finds the library after a native session

* fix(native): droiddeckctl native prepares the rootfs with the setting off

* fix(native): a SysV segment stays while any process has it attached

* fix(native): DNS lookups ask the network's own servers before public ones

* fix(native): a program's own seccomp traps reach its own SIGSYS handler

* feat(native): run native sessions under a device's own app seccomp filter for testing

* fix(native): SysV attaches and collection take a lock, a failed mark fails the attach, and collection closes its directory

* fix(native): shmat fails when it cannot take the segment lock

* fix(native): the SysV segment lock is retried when a signal interrupts it

* fix(native): process tools see the session's processes as root's

* fix(native): native processes are named after their program, not ld.so

* fix(native): a session's helpers keep the mode the session started in

* fix(native): a keyed SysV segment stays until IPC_RMID

* fix(native): a rootfs link to an absolute guest path is followed in the guest, so Wine finds its z: drive

* fix(native): a sandbox whose loader can't be patched runs under proot

* fix(native): creating a private SysV segment also collects stale ones

* fix(native): a session stopped during startup forgets its mode

* fix(xbox): a native backend is authorized by its process ancestry

* fix(native): Wine's drive links are followed in the guest from any prefix

* fix(native): only the startup that owns the running session publishes its mode

* fix(native): a SysV segment stays until IPC_RMID even after its maker ends

* fix(native): a sandbox mount nested in another mount gets its own place

* fix(native): a sandbox whose mount places can't be made runs under proot
2026-11-11 09:13:17 -05:00