Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 8f639a08eb Keep recovery for outstanding restores after a loss, keep losses across a rollback, and leave the paused state idle when no attempt is due 2026-12-05 06:22:44 -05:00
Kurt Himebauch 82f806ad84 Stop the owner's worker and hold the helper inside its phase before the mid-I/O kill tests kill it 2026-12-05 06:22:43 -05:00
Kurt Himebauch 7771a87695 Keep lost guests failed, count zombies and adopted spills as lost, check every thread's tracer, and pace automatic resumes 2026-12-05 06:03:00 -05:00
Kurt Himebauch 3419391940 Test that only the kernel's exit kill ends a spilled owner, and that no owner thread runs after its helper dies mid-spill or mid-read-back 2026-12-05 06:03:00 -05:00
Kurt Himebauch c46bb72631 Retry held sessions with paced resumes, settle rollbacks and late answers, and end read-backs without a marker 2026-12-05 05:38:02 -05:00
Kurt Himebauch 0cd42b7217 Kill a spilled owner whose helper exits still tracing it, and check stale spill requests leave no acknowledgement 2026-12-05 05:38:01 -05:00
Kurt Himebauch f68a78c577 Keep the frozen clock, a pending rollback and late spills tracked when a resume cannot finish 2026-12-05 05:16:03 -05:00
Kurt Himebauch 6638a7dac8 Keep intercepted signals, discard checks and owner exit in the spill helper, and answer a cancelled spill 2026-12-05 05:16:03 -05:00
Kurt Himebauch c6333350ae Drop a spill request that reaches the handler after the resume it was asked before 2026-12-05 04:34:25 -05:00
Kurt Himebauch fbf1788647 Keep a spill without an acknowledgement asked, so a failed resume count still fails 2026-12-05 04:21:28 -05:00
Kurt Himebauch 48f587bb41 Wait only on spills whose handler started, and read back a late zram fallback 2026-12-05 04:15:28 -05:00
Kurt Himebauch 088e9994a0 Merge remote-tracking branch 'origin/main' into frozen-session-disk-spill 2026-12-05 04:08:34 -05:00
Kurt Himebauch 29350f1bd5 Fail the spill test when its readers do not go quiet before the measurement 2026-12-05 03:53:09 -05:00
Kurt Himebauch 498a3a653a Wait on resume for a spill that had not answered when the spill wait ended 2026-12-05 03:52:32 -05:00
Kurt Himebauch 644f8e655f Release zram fallbacks on resume and count late restores before another spill 2026-12-05 03:33:08 -05:00
Kurt Himebauch 7ad52166a2 Keep unanswered spills and unfinished restores tracked until a resume can release them 2026-12-05 03:02:57 -05:00
MaxsTechReview 872c5e1834 fix(native): reopen refused memfds and answer links in the form they are named (#3734)
* fix(native): reopen refused memfds and answer links in the form they are named

Android's app policy refuses the open permission on memory files, so a
read-only reopen of an own memfd through /proc/self/fd/N,
/proc/thread-self/fd/N, /proc/<own pid or thread>/fd/N or /dev/fd/N
failed with EACCES while read, write and mmap of the descriptor still
worked. The hook now answers such a refused read-only open with a new
memfd holding the same bytes, name, mode and seals. Writable opens,
other processes' descriptors and regular files stay refused. FEX routes
guest openat through libc syscall(), so x86 guests get the same answer.

readlink() stripped the rootfs prefix from every target, so a link
stored with a real target (Proton's s: drive) read as /root/... while
getcwd(), /proc/self/fd and /proc/self/maps give the real path, and a
path resolved through the link no longer matched the working directory.
A link named by its real rootfs path, and /proc/<pid>/cwd, now keep the
real target, as realpath() of a real path does; guest and relative names
keep the guest form.

* fix(native): keep the memfd copy read-only, leave openat2 errors native, keep guest form for remapped link names

The copy that answers a refused read-only memfd reopen is now sealed
against writes and resizing, so it cannot be written through as a
read-only descriptor could not. openat2 reads its open_how only after
the kernel refused the open with EACCES, so an unreadable pointer gets
the kernel's EFAULT. readlinkat and fstatat keep the guest form for a
relative name the hook remapped to a real path; only a name the caller
supplied in real form keeps the real target.

* fix(native): pin the memfd being copied and refuse copies that cannot match it

* Copy a refused memfd only when the path and the descriptor name one file
2026-12-05 02:54:50 -05:00
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
MaxsTechReview 56213d74b3 fix(ubuntu): drop the Mesa patches Ubuntu's Mesa 26.2 now ships and rebase the rest (#3736) 2026-12-05 01:59:21 -05:00
The412Bannerandmaxjivi05 9c6fafec4c fix(hook): end readlink answers so Steam's install scripts run without proot (#3386)
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-12-05 00:52:52 -05:00
LunaDL f06c37e279 Feat: Add per-game scaling filter (#3726) 2026-12-05 00:47:58 -05:00
Kurt Himebauch f17406effc Bind a spill to the resume count it was asked under and report a resume only once memory is back 2026-12-04 22:49:06 -05:00
Kurt Himebauch b072cedd16 Fix black bottom-screen Mirror with HDR enabled (#3710)
* Keep Mirror frames readable with HDR enabled

* Exercise mirror capture messages in the native host queue test

* Preserve the HDR display fallback while Mirror is open
2026-12-04 14:01:37 -05:00
Kurt Himebauch ad6bb159d3 Write a sleeping session's memory to storage instead of zram 2026-12-04 12:53:14 -05:00
104 changed files with 16578 additions and 302 deletions

No files matched your search

+1
View File
@@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0021 with his authorship, patches 0022 to 0029 build on it, and his `eac-tests` regression suite verifies them.
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
+24 -10
View File
@@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16;
static constexpr int kWatchedBits = sizeof(unsigned long) * 8;
static std::atomic<unsigned long> watched_fds[kWatchedFds / kWatchedBits];
static std::atomic<bool> watched_beyond{false};
static std::atomic<int> watched_count{0};
static void watch_fd(int fd) {
if (fd < 0) return;
if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release);
else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release);
if (fd >= kWatchedFds) {
watched_beyond.store(true, std::memory_order_release);
return;
}
const unsigned long bit = 1UL << (fd % kWatchedBits);
if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit))
watched_count.fetch_add(1, std::memory_order_acq_rel);
}
static void unwatch_fd(int fd) {
if (fd >= 0 && fd < kWatchedFds)
watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release);
if (fd < 0 || fd >= kWatchedFds) return;
const unsigned long bit = 1UL << (fd % kWatchedBits);
if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit)
watched_count.fetch_sub(1, std::memory_order_acq_rel);
}
static bool any_watched() {
return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire);
}
static bool watched(int fd) {
@@ -4269,7 +4281,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
nfds_t first = 0;
nfds_t first = any_watched() ? 0 : nfds;
while (first < nfds && !watched(fds[first].fd)) first++;
bool has_fake_fds = false;
std::vector<struct pollfd> real_fds;
@@ -4372,12 +4384,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask) {
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
errno = EINVAL;
return -1;
}
for (nfds_t i = 0; i < nfds; ++i) {
for (nfds_t i = 0; any_watched() && i < nfds; ++i) {
if (!is_fake_input_fd(fds[i].fd)) continue;
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
errno = EINVAL;
return -1;
}
if (!sigmask)
return poll_fake(fds, nfds, static_cast<int>(timespec_to_ms(timeout)), nullptr);
sigset_t all_signals, original_mask;
@@ -4410,6 +4422,8 @@ EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *t
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
if (!any_watched())
return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1;
fd_set original_readfds;
fd_set original_writefds;
+20 -4
View File
@@ -343,6 +343,7 @@ volatile int g_hide_shell;
volatile int g_zero_copy;
static int g_zero_copy_paused;
static int g_mirror_capture;
extern volatile int g_display_buffer_driver;
extern void droiddeck_on_overlay_planes(int planes);
static int g_overlay_planes_told = -1;
@@ -2961,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
static int said = -1, said_tm = -1;
static const char *said_why;
const int tm = route != 0 && !droiddeck_color_output();
if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return;
if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return;
int was = said;
said = route; said_why = hs->why; said_tm = tm;
char name[160] = "the HDR game";
@@ -2978,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
"BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white());
break;
case 2:
if (g_mirror_capture) {
droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name);
break;
}
if (tm)
droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to "
"SDR and presented through an SDR screen swapchain", name);
@@ -3198,6 +3203,11 @@ static void render_scene(void) {
const int cardboard = vkp_cardboard_active();
struct hdr_scene hs;
int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs);
/* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */
if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {
hdr_route = 2;
hs.why = "Mirror needs the screen swapchain";
}
const char *hdr_copy = NULL;
if (droiddeck_color_hdr_open()) {
hdr_note_route(hdr_route, &hs);
@@ -3263,16 +3273,16 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
if (hdr_route == 0 && !g_mirror_capture && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
tell_overlay_planes();
const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer();
const int fg_layer = framegen && !g_mirror_capture && hdr_route == 0 && framegen_fits_layer();
g_framegen_layer = fg_layer;
int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int li = (g_zero_copy && !g_mirror_capture && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; }
@@ -5002,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name
struct wl_display *droiddeck_get_display(void) { return g_display; }
void droiddeck_request_redraw(void) { schedule_render(); }
void droiddeck_set_mirror_capture(int on) {
if (g_mirror_capture == on) return;
g_mirror_capture = on;
schedule_render();
}
struct wl_resource *droiddeck_ime_target(void) {
struct surface *s;
if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource;
@@ -11,7 +11,7 @@
#include "ahb_swapchain.h"
#include "droiddeck_color.h"
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD, HOST_MIRROR_CAPTURE };
struct host_msg {
enum host_kind kind;
@@ -91,6 +91,9 @@ void droiddeck_host_text_delete(int before, int after) {
void droiddeck_host_zero_copy(int on, int live) {
host_post(HOST_ZERO_COPY, NULL, 0, on, live);
}
void droiddeck_host_mirror_capture(int on) {
host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0);
}
void droiddeck_host_hdr_output(int on) {
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
}
@@ -271,6 +274,9 @@ static int on_wake(int fd, uint32_t mask, void *data) {
case HOST_ZERO_COPY:
ahb_swapchain_set_mode(m->a, m->b);
break;
case HOST_MIRROR_CAPTURE:
droiddeck_set_mirror_capture(m->a);
break;
case HOST_HDR_OUTPUT:
droiddeck_color_set_output(m->a);
break;
@@ -29,6 +29,8 @@ void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
void droiddeck_host_text_delete(int before, int after);
void droiddeck_host_zero_copy(int on, int live);
void droiddeck_host_mirror_capture(int on);
void droiddeck_set_mirror_capture(int on);
void droiddeck_host_hdr_output(int on);
void droiddeck_host_key(int evdev, int state);
void droiddeck_host_select_game_field(int copy);
@@ -461,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *
__android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : "");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) {
droiddeck_host_mirror_capture(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) {
g_display_buffer_driver = on ? 1 : 0;
@@ -661,6 +661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var effects by mutableStateOf(ScreenEffects.OFF)
private var observedScreenEffectsProfileId by mutableStateOf<String?>(null)
private var screenEffectsTarget by mutableStateOf(SCREEN_EFFECTS_TARGET_AUTO)
private var screenEffectsProfileRevision by mutableIntStateOf(0)
private var cardboard by mutableStateOf(Cardboard.OFF)
private var headTracker: HeadTracker? = null
private var steamVrStatus by mutableStateOf<SteamVr.Status?>(null)
@@ -1641,8 +1642,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
effects = effects,
screenEffectsTarget = screenEffectsTarget,
screenEffectsTargets = screenEffectsTargetOptions(),
screenEffectsCanDelete = screenEffectsProfileIdForTarget(screenEffectsTarget)?.let {
SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it)
screenEffectsCanDelete = screenEffectsProfileRevision.let {
screenEffectsProfileIdForTarget(screenEffectsTarget)?.let {
SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) ||
SessionPrefs.hasScreenEffectsUpscalerOverride(this@SessionActivity, it)
}
} == true,
cardboard = cardboard,
cardboardSensor = hasRotationSensor,
@@ -1748,6 +1752,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
val profileId = screenEffectsProfileIdForTarget(target)
SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m)
screenEffectsProfileRevision++
if (target == screenEffectsTarget) {
upscaler = m
@@ -1783,6 +1788,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
val profileId = screenEffectsProfileIdForTarget(target)
SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m)
screenEffectsProfileRevision++
if (target == screenEffectsTarget) {
upscaler = m
if (screenEffectsUpscalerTargetAppliesToLiveOutput(target)) {
@@ -1829,7 +1835,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val profileId = screenEffectsProfileIdForTarget(editorTarget)
SessionPrefs.setScreenEffects(this@SessionActivity, profileId, e)
effects = e
if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) e.push(upscaler)
if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) {
val upscalerAppliesToLiveOutput =
screenEffectsUpscalerTargetAppliesToLiveOutput(editorTarget)
val liveUpscaler = if (upscalerAppliesToLiveOutput) {
SessionPrefs.screenEffectsUpscaler(
this@SessionActivity,
screenEffectsProfileIdForTarget(editorTarget)
)
} else {
SessionPrefs.screenEffectsUpscaler(
this@SessionActivity,
currentScreenEffectsProfileId()
)
}
e.push(liveUpscaler)
}
}
}
},
@@ -2648,10 +2669,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val targetUpscaler = SessionPrefs.screenEffectsUpscaler(this, profileId)
effects = targetEffects
upscaler = targetUpscaler
val upscalerAppliesToLiveOutput = screenEffectsUpscalerTargetAppliesToLiveOutput(target)
val liveUpscaler = if (upscalerAppliesToLiveOutput) {
targetUpscaler
} else {
SessionPrefs.screenEffectsUpscaler(this, currentScreenEffectsProfileId())
}
if (upscalerAppliesToLiveOutput) {
WaylandCompositor.nativeSetUpscaler(liveUpscaler)
}
if (screenEffectsTargetAppliesToLiveOutput(target)) {
WaylandCompositor.nativeSetUpscaler(targetUpscaler)
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, targetUpscaler)?.name)
targetEffects.push(targetUpscaler)
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, liveUpscaler)?.name)
targetEffects.push(liveUpscaler)
} else if (upscalerAppliesToLiveOutput) {
val liveEffects = SessionPrefs.screenEffects(this, currentScreenEffectsProfileId())
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(liveEffects, liveUpscaler)?.name)
}
}
@@ -2664,6 +2696,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun resetScreenEffectsTarget(target: String) {
if (target != screenEffectsTarget) return
SessionPrefs.resetScreenEffectsProfile(this, screenEffectsProfileIdForTarget(target))
screenEffectsProfileRevision++
syncScreenEffectsTarget(target)
}
@@ -2671,6 +2704,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (target != screenEffectsTarget) return
val profileId = screenEffectsProfileIdForTarget(target) ?: return
SessionPrefs.deleteScreenEffectsProfile(this, profileId)
screenEffectsProfileRevision++
syncScreenEffectsTarget(target)
}
@@ -6348,7 +6382,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun holdComposedOutput(hold: Boolean) {
val wasHeld = composedHolds > 0
composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0)
val held = composedHolds > 0
if (held == wasHeld) return
WaylandCompositor.nativeSetMirrorCapture(held)
// Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available.
if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
@@ -66,11 +66,14 @@ object ProtonExtras {
internal fun installedIn(dir: File, tool: Tool): List<String> =
dir.listFiles()
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) }
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && !x86_64Build(it) && usable(it) }
?.map { it.name }
?.sortedWith { a, b -> compareVersions(a, b) }
?: emptyList()
internal fun x86_64Build(dir: File): Boolean =
File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory
private fun usable(dir: File): Boolean {
val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false
val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false
@@ -972,6 +972,9 @@ object SessionPrefs {
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
/** A sleeping session writes its memory to storage instead of zram. */
fun diskSpill(context: Context): Boolean = prefs(context).getBoolean("diskSpill", false)
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
fun setValveProtonOnDemand(context: Context, on: Boolean) {
@@ -2011,24 +2014,84 @@ object SessionPrefs {
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
private const val GAME_UPSCALER_OVERRIDES_KEY = "upscaler.gameOverrides"
private fun gameUpscalerOverrides(context: Context): JSONObject = runCatching {
JSONObject(prefs(context).getString(GAME_UPSCALER_OVERRIDES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
private fun legacyScreenEffectsUpscaler(context: Context, profileId: String): Int? =
runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
val profile = profiles.optJSONObject(profileId)
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1).takeIf { it >= 0 }
} else null
}.getOrNull()?.let(::canonicalUpscaler)
private fun clearLegacyScreenEffectsUpscaler(context: Context, profileId: String) {
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrNull() ?: return
val profile = profiles.optJSONObject(profileId) ?: return
if (!profile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) return
profile.remove(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)
if (profile.length() == 0) profiles.remove(profileId)
sessionPrefs.edit().apply {
if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY)
else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString())
}.apply()
}
fun hasGameUpscalerOverride(context: Context, gameId: String): Boolean {
if (gameId.isBlank()) return false
val stored = gameUpscalerOverrides(context)
return (stored.has(gameId) && stored.optInt(gameId, -1) >= 0) ||
legacyScreenEffectsUpscaler(context, "game:$gameId") != null
}
fun setGameUpscaler(context: Context, gameId: String, mode: Int) {
if (gameId.isBlank()) return
val overrides = gameUpscalerOverrides(context)
overrides.put(gameId, canonicalUpscaler(mode))
prefs(context).edit().putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()).apply()
clearLegacyScreenEffectsUpscaler(context, "game:$gameId")
}
fun clearGameUpscaler(context: Context, gameId: String) {
if (gameId.isBlank()) return
val sessionPrefs = prefs(context)
val overrides = gameUpscalerOverrides(context)
if (overrides.has(gameId)) {
overrides.remove(gameId)
sessionPrefs.edit().apply {
if (overrides.length() == 0) remove(GAME_UPSCALER_OVERRIDES_KEY)
else putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString())
}.apply()
}
clearLegacyScreenEffectsUpscaler(context, "game:$gameId")
}
fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return false
return runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true
}.getOrDefault(false)
if (profileId.startsWith("game:")) {
return hasGameUpscalerOverride(context, profileId.removePrefix("game:"))
}
return legacyScreenEffectsUpscaler(context, profileId) != null
}
fun screenEffectsUpscaler(context: Context, profileId: String?): Int {
if (profileId.isNullOrBlank()) return upscaler(context)
val stored = runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
val profile = profiles.optJSONObject(profileId)
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1)
} else -1
}.getOrDefault(-1)
return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context)
if (profileId.startsWith("game:")) {
val gameId = profileId.removePrefix("game:")
val overrides = gameUpscalerOverrides(context)
if (overrides.has(gameId)) {
val stored = overrides.optInt(gameId, -1)
if (stored >= 0) return canonicalUpscaler(stored)
}
}
return legacyScreenEffectsUpscaler(context, profileId) ?: upscaler(context)
}
fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) {
@@ -2036,6 +2099,10 @@ object SessionPrefs {
setUpscaler(context, mode)
return
}
if (profileId.startsWith("game:")) {
setGameUpscaler(context, profileId.removePrefix("game:"), mode)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
@@ -2072,6 +2139,7 @@ object SessionPrefs {
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
if (profileId.startsWith("game:")) clearGameUpscaler(context, profileId.removePrefix("game:"))
if (!profiles.has(profileId)) return
profiles.remove(profileId)
sessionPrefs.edit().apply {
@@ -111,6 +111,8 @@ class SessionService : Service() {
private var suspendOperationPending = false
private var pipTask = false
private var suspendAttemptFailed = false
private val resumeRecovery = SuspendRecovery()
private val retryResume = Runnable { updateSuspendPolicy() }
private var freezePending = false
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
@@ -276,7 +278,7 @@ class SessionService : Service() {
}
ACTION_XR_ACTIVITY_VISIBLE -> {
xrActivityVisible = true
resumeSession(panelVisible = false)
resumeSession(panelVisible = false, restartRecovery = false)
return START_NOT_STICKY
}
ACTION_XR_ACTIVITY_HIDDEN -> {
@@ -380,6 +382,8 @@ class SessionService : Service() {
suspendOperationPending = false
freezePending = false
suspendAttemptFailed = false
resumeRecovery.reset()
mainHandler.removeCallbacks(retryResume)
suspendController = null
SessionState.micAvailable = false
SessionState.micEnabled = false
@@ -977,7 +981,7 @@ class SessionService : Service() {
SessionEvents.record("session.paged_out", mapOf(
"processes" to processes, "unacknowledged" to unacknowledged, "residentMb" to residentKb / 1024,
"swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024, "ms" to millis,
))
), sessionDir)
}
},
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
@@ -990,7 +994,27 @@ class SessionService : Service() {
SessionEvents.record("session.paged_in", mapOf(
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
"availableMb" to availableKb / 1024, "ms" to millis,
))
), sessionDir)
}
},
spilled = { processes, spilledKb, residentKb, millis ->
Log.i(TAG, "wrote $processes processes to storage in $millis ms: ${spilledKb / 1024} MB, " +
"resident ${residentKb / 1024} MB")
mainHandler.post {
SessionEvents.record("session.spilled", mapOf(
"processes" to processes, "spilledMb" to spilledKb / 1024, "residentMb" to residentKb / 1024,
"ms" to millis,
), sessionDir)
}
},
restored = { processes, unacknowledged, residentKb, millis ->
Log.i(TAG, "restored $processes processes ($unacknowledged unacknowledged) from storage in $millis ms: " +
"resident ${residentKb / 1024} MB")
mainHandler.post {
SessionEvents.record("session.restored", mapOf(
"processes" to processes, "unacknowledged" to unacknowledged,
"residentMb" to residentKb / 1024, "ms" to millis,
), sessionDir)
}
},
)
@@ -1761,7 +1785,7 @@ class SessionService : Service() {
return
}
if (SessionState.suspended) {
resumeSession()
resumeSession(restartRecovery = false)
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
return
}
@@ -1930,8 +1954,10 @@ class SessionService : Service() {
private fun steamGameRunning(gameId: String): Boolean =
SteamGameProcess.running(gameId)
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
private fun resumeSession(panelVisible: Boolean = true, restartRecovery: Boolean = true) {
if (SessionState.suspended && (restartRecovery || resumeRecovery.due(SystemClock.elapsedRealtime()))) {
SessionState.resumeRequested = true
}
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
@@ -1942,6 +1968,7 @@ class SessionService : Service() {
completeNativeSleep()
completeSteamSleep()
suspendAttemptFailed = false
if (restartRecovery) resumeRecovery.reset()
updateSuspendPolicy()
}
@@ -2160,7 +2187,12 @@ class SessionService : Service() {
controller.cancelFreeze()
}
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
// A session still held after a failed suspend or resume is released by paced resumes, whatever clears or
// sets the latch; only an explicit resume (resumeSession) restarts the pacing.
val held = SessionState.suspended && SessionState.resumeFailed && !shouldSuspend
if (!suspendOperationPending && resumeRecovery.holds(held, SystemClock.elapsedRealtime())) return
val recovering = suspendAttemptFailed && held
if (suspendOperationPending || (suspendAttemptFailed && !recovering) || shouldSuspend == SessionState.suspended) return
val gen = sessionGen
suspendOperationPending = true
SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf(
@@ -2175,9 +2207,9 @@ class SessionService : Service() {
freezeCancelled = false
val freezeSteamToken = steamSleepToken
val freezeNativeToken = nativeSleepToken
controller.freeze(
pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn,
) { success ->
val pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn
controller.freeze(pageOut = pageOut, spill = pageOut && SessionPrefs.diskSpill(this)) { success ->
val rollbackPending = !success && controller.rollbackPending
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
SessionState.suspending = false
@@ -2186,6 +2218,7 @@ class SessionService : Service() {
if (success) {
SessionState.suspended = true
SessionState.resumeFailed = false
resumeRecovery.reset()
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
@@ -2200,6 +2233,12 @@ class SessionService : Service() {
SessionState.manualPause = false
Log.w(TAG, "could not confirm that the session stopped")
}
// Some processes are still held: only a resume can release them.
if (rollbackPending) {
SessionState.suspended = true
SessionState.resumeFailed = true
Log.w(TAG, "could not return the session to running after the suspend failed")
}
}
updateSuspendPolicy()
}
@@ -2208,6 +2247,8 @@ class SessionService : Service() {
acquireLocks()
SessionState.resuming = true
controller.resume { success ->
// A loss with another spill still reading back is retried for that one; the loss is kept.
val lost = !success && controller.guestLost && !controller.restoreOutstanding
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
suspendOperationPending = false
@@ -2216,13 +2257,28 @@ class SessionService : Service() {
if (success) {
SessionState.suspended = false
SessionState.resumeFailed = false
suspendAttemptFailed = false
resumeRecovery.reset()
mainHandler.removeCallbacks(retryResume)
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
refreshNotification()
} else if (lost) {
// Everything was continued, but a game ended without its memory back: no retry restores
// it, and the failure stays reported.
SessionState.suspended = false
SessionState.resumeFailures++
SessionState.resumeFailed = true
resumeRecovery.reset()
mainHandler.removeCallbacks(retryResume)
SessionEvents.transition(SessionEvents.resumePhase(), "session.resume_lost_guest")
Log.w(TAG, "a game ended before its memory was read back from storage")
refreshNotification()
} else {
suspendAttemptFailed = true
SessionState.resumeFailures++
SessionState.resumeFailed = true
Log.w(TAG, "could not confirm that the session resumed")
resumeRecovery.failed(SystemClock.elapsedRealtime())?.let { mainHandler.postDelayed(retryResume, it) }
}
updateSuspendPolicy()
}
@@ -29,6 +29,8 @@ internal class SessionSuspendController(
{ _, _, _, _, _, _ -> },
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
private val spilled: (processes: Int, spilledKb: Long, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> },
private val restored: (processes: Int, unacknowledged: Int, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> },
) {
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
@@ -53,10 +55,34 @@ internal class SessionSuspendController(
private var frozen = emptyList<ProcessRecord>()
private var frozenSince: Long? = null
private var pagedOutTargets = emptyList<ProcessRecord>()
private var spilledTargets = emptyList<ProcessRecord>()
// Asked to spill and not yet released by a resume count they saw: acknowledged or not, each may park its process.
private var spillAsked = emptyList<ProcessRecord>()
private var counterUnpublished = false
// Spilled targets whose positive answer was taken (and its acknowledgement removed).
private var spillWritten = emptyList<ProcessRecord>()
// Taken into the restore wait by this resume: alive then, so one that ends without its memory back is lost.
private var adopted = emptyList<ProcessRecord>()
// Released by this attempt on a late answer of 0 or a cancellation: not lost if they end afterwards.
private var answeredLate = emptyList<ProcessRecord>()
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
// A spilled process ended without its memory back since the last suspend began: retrying cannot bring it
// back, so no later resume of this suspension reports success.
@Volatile var guestLost = false
private set
// Spilled processes still reading back, which a later resume waits for again.
@Volatile var restoreOutstanding = false
private set
// A failed freeze that could not return every process to running: only a resume releases them.
@Volatile var rollbackPending = false
private set
fun freeze(pageOut: Boolean = false, spill: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
submit({
guestLost = false
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
var complete = false
var interrupted = false
@@ -74,7 +100,7 @@ internal class SessionSuspendController(
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
}
}
if (pageOut) pageOut(records, root.pid, helpers)
if (pageOut) pageOut(records, root.pid, helpers, spill)
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
var previous: Map<TaskIdentity, Long>? = null
for (pass in 0 until FREEZE_MAX_PASSES) {
@@ -105,9 +131,14 @@ internal class SessionSuspendController(
frozen = records.values.toList()
if (complete && frozenSince == null) frozenSince = nowNanos()
if (!complete) {
if (restoreSafely(frozen)) frozen = emptyList()
// A spilled process is back only once its helper has read it back: until then a resume retries.
adopted = emptyList()
answeredLate = emptyList()
val running = startedAlive()
if (restoreSafely(frozen) && awaitRestored(running)) frozen = emptyList()
runAudio(resumeAudio)
}
rollbackPending = !complete && frozen.isNotEmpty()
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
@@ -122,12 +153,23 @@ internal class SessionSuspendController(
fun resume(completion: (Boolean) -> Unit) {
submit({
val records = frozen
advanceClock()
val advancedTo = advanceClock()
adopted = emptyList()
answeredLate = emptyList()
val running = startedAlive()
runAudio(resumeAudio)
val resumed = restoreSafely(records)
if (resumed) frozen = emptyList()
completion(resumed)
if (resumed) readBack()
if (resumed) {
frozen = emptyList()
rollbackPending = false
}
// nothing was continued: the guest clock owes the time from here to the next attempt
if (!resumed && counterUnpublished && advancedTo != null) frozenSince = advancedTo
// a spilled process runs again only once its helper has read its memory back
val restoredAll = resumed && awaitRestored(running)
restoreOutstanding = frozen.isNotEmpty() || spilledTargets.isNotEmpty()
completion(restoredAll && !guestLost)
if (resumed) readBack(waitForRestore = false)
}, { completion(false) })
}
@@ -135,7 +177,10 @@ internal class SessionSuspendController(
closing = true
submit({
advanceClock()
val running = startedAlive()
if (restoreSafely(frozen)) frozen = emptyList()
// the teardown asks the guests to exit, which a process still reading back cannot answer
if (frozen.isEmpty()) awaitRestored(running, whileClosing = true)
completion()
executor.shutdown()
}, completion)
@@ -149,22 +194,25 @@ internal class SessionSuspendController(
}
}
private fun advanceClock() {
val since = frozenSince ?: return
// Returns the moment the guest clock now accounts for, or null when no frozen interval was open.
private fun advanceClock(): Long? {
val since = frozenSince ?: return null
frozenSince = null
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
val now = nowNanos()
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return now
try {
mapClockControl(control)
RandomAccessFile(control, "rw").use { file ->
val bytes = ByteArray(Long.SIZE_BYTES)
file.readFully(bytes)
val shift = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).long.coerceAtLeast(0L) +
(nowNanos() - since).coerceAtLeast(0L)
(now - since).coerceAtLeast(0L)
file.seek(0L)
file.write(ByteBuffer.allocate(Long.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(shift).array())
}
} catch (_: IOException) {
}
return now
}
private fun runAudio(action: () -> Unit) {
@@ -275,13 +323,15 @@ internal class SessionSuspendController(
return tasks.takeIf { stopped && it.isNotEmpty() }
}
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>, spill: Boolean) {
val control = zramControl?.takeIf { it.isFile } ?: return
val hold = holdFile(control)
try {
hold.writeText(PAGE_OUT_REQUEST)
// A spill names the resume count it was asked under: any later count releases the helper, however
// late it starts reading.
hold.writeText(if (spill) "$SPILL_REQUEST ${resumeCount(control)}" else PAGE_OUT_REQUEST)
sleep(PAGE_OUT_POLL_MS)
pageOut(control, records, root, helpers)
if (spill) spill(control, records, root, helpers) else pageOut(control, records, root, helpers)
} catch (_: IOException) {
} finally {
hold.delete()
@@ -290,15 +340,208 @@ internal class SessionSuspendController(
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
private fun ackFile(control: File, kind: String, record: ProcessRecord) =
File(control.parentFile, "${control.name}.$kind.${record.pid}")
private fun preloaded(records: Collection<ProcessRecord>) = records.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
} catch (_: IOException) {
false
}
}
private fun readAck(ack: File): Long? = try {
ack.readText().trim().toLongOrNull()
} catch (_: IOException) {
null
}
// Each process parks its threads, writes its private memory to an unlinked file and stays parked until
// the resume counter changes; its acknowledgement is the kB it wrote, 0 when it paged out to zram instead.
private fun spill(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
// A restore that finished after the last resume stopped waiting is counted before its marker goes; one
// still reading is not asked to spill again.
val (done, still) = spilledTargets.partition { settled(control, it) }
release(control, done)
spilledTargets = still
val targets = preloaded(records.values).filterNot { it in spilledTargets }
if (targets.isEmpty()) return
targets.forEach { ackFile(control, "ack", it).delete(); ackFile(control, "restored", it).delete() }
val start = nowMillis()
spillAsked = (spillAsked + targets).distinct()
for (record in targets) send(record, SIGURG)
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < SPILL_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
waiting.removeAll { val ack = ackFile(control, "ack", it); readAck(ack) != null || (started && !ack.exists()) || isGone(it) }
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
var total = 0L
val acks = targets.associateWith { readAck(ackFile(control, "ack", it)) }
val written = targets.filter { record ->
val kb = acks[record]?.coerceAtLeast(0L) ?: 0L
total += kb
kb > 0L
}
// A process that answered 0 paged out to zram instead and has no spill to release. One whose handler
// started (its acknowledgement is there, still empty) may still be writing: it is waited for like a
// spilled one, its acknowledgement kept. One with no acknowledgement may have no handler, or one that has
// not got that far: it is not waited for, but stays asked, so a resume count that cannot be written still
// fails (a late spill waits for any count other than the one it was asked with).
val unanswered = targets.filter { acks[it] == null && ackFile(control, "ack", it).exists() && !isGone(it) }
spillAsked = spillAsked.filterNot { acks[it] == 0L || acks[it] == SPILL_CANCELLED }
spilledTargets = (spilledTargets + written + unanswered).distinct()
spillWritten = (spillWritten + written).distinct()
pagedOutTargets = (pagedOutTargets + targets.filter { acks[it] == 0L }).distinct()
targets.filterNot { it in unanswered }.forEach { ackFile(control, "ack", it).delete() }
spilled(written.size, total, memoryKb(targets).first, nowMillis() - start)
}
// Its memory is back, it paged out to zram after all (an answer of 0 that came late), a resume cancelled
// it before it wrote anything, or it is gone.
private fun settled(control: File, record: ProcessRecord): Boolean {
val ack = readAck(ackFile(control, "ack", record))
return readAck(ackFile(control, "restored", record)) != null || ack == 0L || ack == SPILL_CANCELLED ||
ended(record)
}
// Gone, or every thread has exited and only an unreaped zombie is left.
private fun ended(record: ProcessRecord): Boolean {
if (isGone(record)) return true
val tasks = File(procRoot, "${record.pid}/task").listFiles()?.filter { it.name.toIntOrNull() != null } ?: return false
return tasks.all { entry ->
try { readStat(File(entry, "stat"))[0].first().let { it == 'Z' || it == 'X' } } catch (_: IOException) { false }
}
}
// Settled targets stop being tracked; one that fell back to zram late is read back like any paged-out one.
private fun release(control: File, settledTargets: List<ProcessRecord>) {
val lateZram = settledTargets.filter { readAck(ackFile(control, "ack", it)) == 0L && !isGone(it) }
pagedOutTargets = (pagedOutTargets + lateZram).distinct()
spillAsked = spillAsked.filterNot { it in settledTargets }
spillWritten = spillWritten.filterNot { it in settledTargets }
settledTargets.forEach {
ackFile(control, "restored", it).delete()
ackFile(control, "ack", it).delete()
}
}
private fun resumeFile(control: File) = File(control.parentFile, "${control.name}.resume")
private fun resumeCount(control: File): Long = try {
resumeFile(control).takeIf { it.isFile }?.readText()?.trim()?.toLongOrNull() ?: 0L
} catch (_: IOException) {
0L
}
// False when a process asked to spill may not have seen the new count: it would stay stopped. The count is
// put in place whole, so a failed write leaves the one before.
private fun bumpResume(): Boolean {
val control = zramControl?.takeIf { it.isFile } ?: return spillAsked.isEmpty()
// A late answer of 0 or a cancellation already let its process go: it needs no count.
val answered = spillAsked.filter {
val ack = readAck(ackFile(control, "ack", it))
ack == 0L || ack == SPILL_CANCELLED
}
if (answered.isNotEmpty()) {
answeredLate = (answeredLate + answered).distinct()
spilledTargets = spilledTargets.filterNot { it in answered }
release(control, answered)
}
val counter = resumeFile(control)
val ok = try {
val next = resumeCount(control) + 1
val fresh = File(counter.parentFile, "${counter.name}.new")
fresh.writeText(next.toString())
java.nio.file.Files.move(fresh.toPath(), counter.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE)
resumeCount(control) == next
} catch (_: IOException) {
false
}
if (ok) spillAsked = emptyList()
return ok || spillAsked.isEmpty()
}
// True when every spilled process has its memory back (or was gone already). Ones still reading stay
// tracked, so a later resume waits for them again. One of [running] that ends without its memory back fails
// this resume.
private fun awaitRestored(running: Collection<ProcessRecord> = emptyList(), whileClosing: Boolean = false): Boolean {
val control = zramControl ?: return true
val targets = spilledTargets
val start = nowMillis()
val waiting = targets.toMutableList()
val untraced = HashMap<ProcessRecord, Long>()
val releasedWithoutMarker = HashSet<ProcessRecord>()
try {
while (targets.isNotEmpty() && (whileClosing || !closing) && nowMillis() - start < RESTORE_TIMEOUT_MS) {
waiting.removeAll {
settled(control, it) || detached(control, it, untraced).also { done -> if (done) releasedWithoutMarker += it }
}
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
}
val lost = (running + adopted).distinct().filterNot { it in answeredLate || it in releasedWithoutMarker }.filter { record ->
val ack = readAck(ackFile(control, "ack", record))
ended(record) && readAck(ackFile(control, "restored", record)) == null && ack != 0L && ack != SPILL_CANCELLED
}
adopted = emptyList()
answeredLate = emptyList()
if (lost.isNotEmpty()) guestLost = true
if (targets.isNotEmpty()) {
release(control, targets.filterNot { it in waiting })
spilledTargets = waiting.toList()
restored(targets.size, waiting.size, memoryKb(targets).first, nowMillis() - start)
}
return waiting.isEmpty() && lost.isEmpty()
}
// A process that wrote its spill is traced by its helper until the read-back ends; one that stays untraced
// and alive for a while has its memory back even if the helper could not write its marker (a helper that
// dies first has its owner killed).
private fun detached(control: File, record: ProcessRecord, untraced: MutableMap<ProcessRecord, Long>): Boolean {
if (record !in spillWritten && (readAck(ackFile(control, "ack", record)) ?: 0L) <= 0L) return false
// The helper detaches thread by thread, so every live thread must be out of its trace.
val current = try { readProcess(record.pid) } catch (_: IOException) { null }
if (current == null || current.started != record.started || ended(record) || anyThreadTraced(record)) {
untraced.remove(record)
return false
}
return nowMillis() - untraced.getOrPut(record) { nowMillis() } >= MARKER_GRACE_MS
}
private fun anyThreadTraced(record: ProcessRecord): Boolean {
val tasks = File(procRoot, "${record.pid}/task").listFiles() ?: return true
return tasks.any { entry ->
entry.name.toIntOrNull() != null && try {
File(entry, "status").useLines { lines ->
lines.firstOrNull { it.startsWith("TracerPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() != 0
}
} catch (_: IOException) {
false
File(entry, "stat").exists()
}
}
}
// Asked, started or written spills of processes alive now: one that ends without its memory back (or a 0 or
// cancelled answer) is lost.
private fun startedAlive(): List<ProcessRecord> {
val control = zramControl ?: return emptyList()
return (spilledTargets + spillAsked).distinct().filter {
val ack = readAck(ackFile(control, "ack", it))
ack != 0L && ack != SPILL_CANCELLED && !ended(it)
}
}
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = preloaded(records.values)
if (targets.isEmpty()) return
pagedOutTargets = (pagedOutTargets + targets).distinct()
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
@@ -325,7 +568,8 @@ internal class SessionSuspendController(
false
}
private fun readBack() {
private fun readBack(waitForRestore: Boolean = true) {
if (waitForRestore) awaitRestored()
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
val control = zramControl?.takeIf { it.isFile } ?: return
@@ -411,10 +655,12 @@ internal class SessionSuspendController(
private fun stopThreads(record: ProcessRecord) {
val current = try { readProcess(record.pid) } catch (_: Exception) { return }
if (current == null || current.started != record.started) return
// A spill helper's tracing stop ends when it detaches after reading back: the pending SIGSTOP holds then.
val helperHeld = record in spilledTargets
for (entry in File(procRoot, "${record.pid}/task").listFiles().orEmpty()) {
val tid = entry.name.toIntOrNull() ?: continue
val state = try { readStat(File(entry, "stat"))[0].first() } catch (_: IOException) { continue }
if (state == 'T' || state == 't' || state == 'Z' || state == 'X') continue
if (state == 'T' || (state == 't' && !helperHeld) || state == 'Z' || state == 'X') continue
try {
threadSignal(record.pid, tid, SIGSTOP)
} catch (_: Throwable) {
@@ -431,6 +677,10 @@ internal class SessionSuspendController(
Role.HELPER_CHILD -> 3
}
}
val asked = spillAsked
counterUnpublished = !bumpResume()
if (counterUnpublished) return false
adoptStartedSpills(asked)
for (record in ordered) send(record, SIGCONT)
val waiting = ordered.toMutableList()
repeat(RESTORE_CHECKS) { check ->
@@ -442,6 +692,15 @@ internal class SessionSuspendController(
return false
}
// A handler that started after the spill wait ended parks its process until it has read back, like one
// that answered in time.
private fun adoptStartedSpills(asked: List<ProcessRecord>) {
val control = zramControl ?: return
val started = asked.filter { it !in spilledTargets && ackFile(control, "ack", it).exists() && !ended(it) }
if (started.isNotEmpty()) spilledTargets = spilledTargets + started
adopted = started
}
private fun restoreSafely(records: List<ProcessRecord>): Boolean = try {
restore(records)
} catch (_: InterruptedException) {
@@ -460,10 +719,12 @@ internal class SessionSuspendController(
}
}
// A spilled process's threads stay in a tracing stop until its helper has read its memory back.
private fun isRunningOrGone(record: ProcessRecord): Boolean {
val current = try { readProcess(record.pid) } catch (_: Exception) { return false }
if (current == null || current.started != record.started) return true
if (current.state == 'T' || current.state == 't') return false
val spilled = record in spilledTargets
if (current.state == 'T' || (current.state == 't' && !spilled)) return false
return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry ->
entry.name.toIntOrNull() != null &&
try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false }
@@ -477,6 +738,11 @@ internal class SessionSuspendController(
const val PAGE_OUT_ACK = "1"
const val PAGE_OUT_REQUEST = "1"
const val READ_BACK_REQUEST = "0"
const val SPILL_REQUEST = "4"
const val SPILL_CANCELLED = -2L
const val SPILL_TIMEOUT_MS = 30_000L
const val RESTORE_TIMEOUT_MS = 30_000L
const val MARKER_GRACE_MS = 1_000L
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.session
// Paced resume retries for a session that is still held after a failed suspend or resume.
internal class SuspendRecovery(
private val maxAttempts: Int = 5,
private val firstDelayMs: Long = 5_000L,
) {
private var attempts = 0
private var nextAt = 0L
fun due(now: Long): Boolean = attempts < maxAttempts && now >= nextAt
// Whether a session that is still held must wait instead of starting another resume now.
fun holds(held: Boolean, now: Long): Boolean = held && !due(now)
// The delay before the next attempt is due, or null when no attempt is left.
fun failed(now: Long): Long? {
attempts++
if (attempts >= maxAttempts) return null
val delay = firstDelayMs shl (attempts - 1)
nextAt = now + delay
return delay
}
fun reset() {
attempts = 0
nextAt = 0L
}
}
@@ -881,6 +881,28 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it)
} ?: false)
}
val scalingFilterChoices = SessionPrefs.upscalerChoices(context)
var gameUpscaler by remember(frameGenProfileKey) {
mutableStateOf(frameGenProfileKey?.let {
SessionPrefs.screenEffectsUpscaler(context, "game:$it")
} ?: SessionPrefs.upscaler(context))
}
var gameUpscalerOverride by remember(frameGenProfileKey) {
mutableStateOf(frameGenProfileKey?.let { SessionPrefs.hasGameUpscalerOverride(context, it) } ?: false)
}
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, frameGenProfileKey) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
frameGenProfileKey?.let { key ->
gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key")
gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key)
}
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
@@ -914,6 +936,25 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
},
)
}
val scalingFilterMenuContent: @Composable () -> Unit = {
val key = frameGenProfileKey
if (key != null) ScalingFilterMenu(
mode = gameUpscaler,
options = scalingFilterChoices,
hasGameOverride = gameUpscalerOverride,
onPick = { mode ->
SessionPrefs.setGameUpscaler(context, key, mode)
gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key")
gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key)
},
onResetGame = {
SessionPrefs.clearGameUpscaler(context, key)
gameUpscaler = SessionPrefs.upscaler(context)
gameUpscalerOverride = false
},
gameName = game?.name,
)
}
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
@@ -938,6 +979,17 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
if (frameGenProfileKey != null) add { m ->
Box(m) {
SettingCard(
stringResource(R.string.display_filter),
scalingFilterChoices.firstOrNull { it.first == gameUpscaler }?.second ?: scalingFilterChoices.first().second,
"card:scaling-filter", Modifier.fillMaxSize(),
) {
host.open = if (host.open == "scaling-filter") null else "scaling-filter"
}
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
if (steamCard != null) add(steamCard)
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG }
@@ -972,6 +1024,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
frameGenMenuContent()
}
}
if (host.open == "scaling-filter") {
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
scalingFilterMenuContent()
}
}
}
}
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
@Composable
internal fun ScalingFilterMenu(
mode: Int,
options: List<Pair<Int, String>>,
hasGameOverride: Boolean,
onPick: (Int) -> Unit,
onResetGame: () -> Unit,
gameName: String? = null,
) {
val colors = MaterialTheme.colorScheme
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
val selectedLabel = options.firstOrNull { it.first == mode }?.second ?: mode.toString()
Text(
stringResource(
if (hasGameOverride) R.string.display_filter_game_profile else R.string.display_filter_default_profile,
if (hasGameOverride) gameName.orEmpty() else selectedLabel,
selectedLabel,
),
color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(bottom = 6.dp),
)
options.forEachIndexed { index, (option, label) ->
val selected = mode == option
val pick = { onPick(option) }
OutlinedButton(
onClick = pick,
modifier = Modifier.fillMaxWidth()
.padding(top = if (index == 0) 0.dp else 6.dp)
.controllerConfirm(onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
Text(
stringResource(R.string.display_filter_note),
color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp),
)
OutlinedButton(
onClick = onResetGame,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = onResetGame),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
}
@@ -333,6 +333,8 @@ public final class WaylandCompositor {
public static native void nativeSetZeroCopy(boolean on);
public static native void nativeSetMirrorCapture(boolean on);
public static native void nativeSetDisplayBufferDriver(boolean on);
public static native int nativeZeroCopyFrames();
+2
View File
@@ -4330,4 +4330,6 @@
<string name="glasses_shortcut_group">اختصار داخل اللعبة</string>
<string name="glasses_show_shortcut">إظهار اختصار النظارات الذكية</string>
<string name="glasses_show_shortcut_hint">إظهار زر النظارات الذكية العائم فوق اللعبة.</string>
<string name="display_filter_game_profile">استخدام ملف تعريف %1$s: %2$s</string>
<string name="display_filter_default_profile">استخدام الملف التعريفي الافتراضي: %1$s</string>
</resources>
@@ -4208,4 +4208,6 @@
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Пряк път в играта</string>
<string name="glasses_show_shortcut">Показване на прекия път за Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Показва плаващия бутон за Smart Glasses върху играта.</string>
<string name="display_filter_game_profile">Използва се профил %1$s: %2$s</string>
<string name="display_filter_default_profile">Използва се профилът по подразбиране: %1$s</string>
</resources>
+2
View File
@@ -4250,4 +4250,6 @@
<string name="glasses_shortcut_group">Zkratka ve hře</string>
<string name="glasses_show_shortcut">Zobrazit zkratku Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Zobrazit plovoucí tlačítko Smart Glasses nad hrou.</string>
<string name="display_filter_game_profile">Používá se profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Používá se výchozí profil: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Genvej i spillet</string>
<string name="glasses_show_shortcut">Vis Smart Glasses-genvej</string>
<string name="glasses_show_shortcut_hint">Vis den flydende Smart Glasses-knap oven på spillet.</string>
<string name="display_filter_game_profile">Bruger profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Bruger standardprofilen: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Ingame-Verknüpfung</string>
<string name="glasses_show_shortcut">Smart-Glasses-Verknüpfung anzeigen</string>
<string name="glasses_show_shortcut_hint">Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen.</string>
<string name="display_filter_game_profile">Profil %1$s wird verwendet: %2$s</string>
<string name="display_filter_default_profile">Standardprofil wird verwendet: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Συντόμευση μέσα στο παιχνίδι</string>
<string name="glasses_show_shortcut">Εμφάνιση συντόμευσης Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι.</string>
<string name="display_filter_game_profile">Χρήση προφίλ %1$s: %2$s</string>
<string name="display_filter_default_profile">Χρήση προεπιλεγμένου προφίλ: %1$s</string>
</resources>
+2
View File
@@ -4210,4 +4210,6 @@
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Pelin aikainen pikakuvake</string>
<string name="glasses_show_shortcut">Näytä Smart Glasses -pikakuvake</string>
<string name="glasses_show_shortcut_hint">Näytä pelin päällä kelluva Smart Glasses -painike.</string>
<string name="display_filter_game_profile">Käytössä profiili %1$s: %2$s</string>
<string name="display_filter_default_profile">Käytössä oletusprofiili: %1$s</string>
</resources>
+2
View File
@@ -4209,4 +4209,6 @@
<string name="glasses_shortcut_group">Raccourci en jeu</string>
<string name="glasses_show_shortcut">Afficher le raccourci Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Afficher le bouton flottant Smart Glasses par-dessus le jeu.</string>
<string name="display_filter_game_profile">Profil %1$s utilisé : %2$s</string>
<string name="display_filter_default_profile">Profil par défaut utilisé : %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">गेम में शॉर्टकट</string>
<string name="glasses_show_shortcut">Smart Glasses शॉर्टकट दिखाएँ</string>
<string name="glasses_show_shortcut_hint">गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ।</string>
<string name="display_filter_game_profile">%1$s प्रोफ़ाइल का उपयोग: %2$s</string>
<string name="display_filter_default_profile">डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Játékon belüli parancsikon</string>
<string name="glasses_show_shortcut">Smart Glasses parancsikon megjelenítése</string>
<string name="glasses_show_shortcut_hint">A játék fölött lebegő Smart Glasses gomb megjelenítése.</string>
<string name="display_filter_game_profile">Használt profil: %1$s – %2$s</string>
<string name="display_filter_default_profile">Alapértelmezett profil használata: %1$s</string>
</resources>
+2
View File
@@ -4140,4 +4140,6 @@
<string name="glasses_shortcut_group">Pintasan dalam game</string>
<string name="glasses_show_shortcut">Tampilkan pintasan Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Tampilkan tombol Smart Glasses mengambang di atas game.</string>
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Menggunakan profil default: %1$s</string>
</resources>
+2
View File
@@ -4209,4 +4209,6 @@
<string name="glasses_shortcut_group">Scorciatoia nel gioco</string>
<string name="glasses_show_shortcut">Mostra scorciatoia Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostra il pulsante mobile Smart Glasses sopra il gioco.</string>
<string name="display_filter_game_profile">Profilo %1$s in uso: %2$s</string>
<string name="display_filter_default_profile">Profilo predefinito in uso: %1$s</string>
</resources>
+2
View File
@@ -4140,4 +4140,6 @@
<string name="glasses_shortcut_group">ゲーム内ショートカット</string>
<string name="glasses_show_shortcut">Smart Glasses のショートカットを表示</string>
<string name="glasses_show_shortcut_hint">ゲーム画面上に Smart Glasses のフローティングボタンを表示します。</string>
<string name="display_filter_game_profile">%1$s プロファイルを使用中: %2$s</string>
<string name="display_filter_default_profile">デフォルトプロファイルを使用中: %1$s</string>
</resources>
+2
View File
@@ -4140,4 +4140,6 @@
<string name="glasses_shortcut_group">게임 내 바로가기</string>
<string name="glasses_show_shortcut">Smart Glasses 바로가기 표시</string>
<string name="glasses_show_shortcut_hint">게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다.</string>
<string name="display_filter_game_profile">%1$s 프로필 사용 중: %2$s</string>
<string name="display_filter_default_profile">기본 프로필 사용 중: %1$s</string>
</resources>
+2
View File
@@ -4140,4 +4140,6 @@
<string name="glasses_shortcut_group">Pintasan dalam permainan</string>
<string name="glasses_show_shortcut">Tunjukkan pintasan Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Tunjukkan butang Smart Glasses terapung di atas permainan.</string>
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Menggunakan profil lalai: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Snarvei i spillet</string>
<string name="glasses_show_shortcut">Vis Smart Glasses-snarvei</string>
<string name="glasses_show_shortcut_hint">Vis den flytende Smart Glasses-knappen over spillet.</string>
<string name="display_filter_game_profile">Bruker profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Bruker standardprofilen: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Snelkoppeling in game</string>
<string name="glasses_show_shortcut">Smart Glasses-snelkoppeling tonen</string>
<string name="glasses_show_shortcut_hint">Toon de zwevende Smart Glasses-knop boven het spel.</string>
<string name="display_filter_game_profile">Profiel %1$s in gebruik: %2$s</string>
<string name="display_filter_default_profile">Standaardprofiel in gebruik: %1$s</string>
</resources>
+2
View File
@@ -4250,4 +4250,6 @@
<string name="glasses_shortcut_group">Skrót w grze</string>
<string name="glasses_show_shortcut">Pokaż skrót Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Pokaż pływający przycisk Smart Glasses nad grą.</string>
<string name="display_filter_game_profile">Używany profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Używany profil domyślny: %1$s</string>
</resources>
@@ -4209,4 +4209,6 @@
<string name="glasses_shortcut_group">Atalho no jogo</string>
<string name="glasses_show_shortcut">Mostrar atalho do Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
<string name="display_filter_game_profile">Perfil %1$s em utilização: %2$s</string>
<string name="display_filter_default_profile">Perfil predefinido em utilização: %1$s</string>
</resources>
+2
View File
@@ -4217,4 +4217,6 @@
<string name="glasses_shortcut_group">Atalho durante o jogo</string>
<string name="glasses_show_shortcut">Mostrar atalho do Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
<string name="display_filter_game_profile">Perfil %1$s em uso: %2$s</string>
<string name="display_filter_default_profile">Perfil predefinido em uso: %1$s</string>
</resources>
+2
View File
@@ -4210,4 +4210,6 @@
<string name="glasses_shortcut_group">Comandă rapidă în joc</string>
<string name="glasses_show_shortcut">Afișează comanda rapidă Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Afișează butonul plutitor Smart Glasses peste joc.</string>
<string name="display_filter_game_profile">Se folosește profilul %1$s: %2$s</string>
<string name="display_filter_default_profile">Se folosește profilul implicit: %1$s</string>
</resources>
+2
View File
@@ -4251,4 +4251,6 @@
<string name="glasses_shortcut_group">Ярлык в игре</string>
<string name="glasses_show_shortcut">Показывать ярлык Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Показывать плавающую кнопку Smart Glasses поверх игры.</string>
<string name="display_filter_game_profile">Используется профиль %1$s: %2$s</string>
<string name="display_filter_default_profile">Используется профиль по умолчанию: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Genväg i spelet</string>
<string name="glasses_show_shortcut">Visa Smart Glasses-genväg</string>
<string name="glasses_show_shortcut_hint">Visa den flytande Smart Glasses-knappen ovanpå spelet.</string>
<string name="display_filter_game_profile">Använder profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Använder standardprofilen: %1$s</string>
</resources>
+2
View File
@@ -4140,4 +4140,6 @@
<string name="glasses_shortcut_group">ทางลัดในเกม</string>
<string name="glasses_show_shortcut">แสดงทางลัด Smart Glasses</string>
<string name="glasses_show_shortcut_hint">แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม</string>
<string name="display_filter_game_profile">ใช้โปรไฟล์ %1$s: %2$s</string>
<string name="display_filter_default_profile">ใช้โปรไฟล์เริ่มต้น: %1$s</string>
</resources>
+2
View File
@@ -4170,4 +4170,6 @@
<string name="glasses_shortcut_group">Oyun içi kısayol</string>
<string name="glasses_show_shortcut">Smart Glasses kısayolunu göster</string>
<string name="glasses_show_shortcut_hint">Oyun üzerinde yüzen Smart Glasses düğmesini göster.</string>
<string name="display_filter_game_profile">%1$s profili kullanılıyor: %2$s</string>
<string name="display_filter_default_profile">Varsayılan profil kullanılıyor: %1$s</string>
</resources>
+2
View File
@@ -4250,4 +4250,6 @@
<string name="glasses_shortcut_group">Ярлик у грі</string>
<string name="glasses_show_shortcut">Показувати ярлик Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Показувати плаваючу кнопку Smart Glasses поверх гри.</string>
<string name="display_filter_game_profile">Використовується профіль %1$s: %2$s</string>
<string name="display_filter_default_profile">Використовується профіль за замовчуванням: %1$s</string>
</resources>
+2
View File
@@ -4140,4 +4140,6 @@
<string name="glasses_shortcut_group">Lối tắt trong trò chơi</string>
<string name="glasses_show_shortcut">Hiển thị lối tắt Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Hiển thị nút Smart Glasses nổi phía trên trò chơi.</string>
<string name="display_filter_game_profile">Đang dùng hồ sơ %1$s: %2$s</string>
<string name="display_filter_default_profile">Đang dùng hồ sơ mặc định: %1$s</string>
</resources>
@@ -4138,4 +4138,6 @@
<string name="glasses_shortcut_group">游戏内快捷方式</string>
<string name="glasses_show_shortcut">显示 Smart Glasses 快捷方式</string>
<string name="glasses_show_shortcut_hint">在游戏画面上显示悬浮的 Smart Glasses 按钮。</string>
<string name="display_filter_game_profile">正在使用 %1$s 配置:%2$s</string>
<string name="display_filter_default_profile">正在使用默认配置:%1$s</string>
</resources>
@@ -4138,4 +4138,6 @@
<string name="glasses_shortcut_group">遊戲內捷徑</string>
<string name="glasses_show_shortcut">顯示 Smart Glasses 捷徑</string>
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
</resources>
@@ -4138,4 +4138,6 @@
<string name="glasses_shortcut_group">遊戲內捷徑</string>
<string name="glasses_show_shortcut">顯示 Smart Glasses 捷徑</string>
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
</resources>
+2
View File
@@ -2857,6 +2857,8 @@
<string name="display_filter_hint">Shared by Steam and Desktop.</string>
<string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string>
<string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string>
<string name="display_filter_game_profile">Using %1$s profile: %2$s</string>
<string name="display_filter_default_profile">Using Default profile: %1$s</string>
<string name="display_sharpness">Filter sharpness</string>
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
@@ -181,6 +181,17 @@ class ProtonExtrasTest {
assertEquals(emptyList<String>(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
}
@Test
fun x86_64BuildsAreNotTakenForTheArm64Tool() {
val tools = temp.newFolder("compatibilitytools.d")
for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-14.2-x86_64")) installTool(tools, name)
File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs()
File(tools, "DroidDeck-Proton 11-7.5/files/lib/wine/x86_64-unix").mkdirs()
File(tools, "DroidDeck-Proton 11-7.5/files/bin-arm64").mkdirs()
assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedIn(tools, tool("droiddeck")))
assertTrue(ProtonExtras.x86_64Build(File(tools, "DroidDeck-Proton-11-14.2-x86_64")))
}
@Test
fun interruptedBuildsAreNotReportedAsInstalled() {
val tools = temp.newFolder("compatibilitytools.d")
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionPrefsUpscalerTest {
private lateinit var context: Context
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun gameOverridesAreIsolatedAndFallBackToTheGlobalFilter() {
SessionPrefs.setUpscaler(context, 4)
SessionPrefs.setGameUpscaler(context, "12345", 7)
assertEquals(4, SessionPrefs.upscaler(context))
assertEquals(7, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
assertEquals(4, SessionPrefs.screenEffectsUpscaler(context, "game:54321"))
assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "54321"))
assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
}
@Test fun resettingGameOverrideRestoresTheGlobalFilter() {
SessionPrefs.setUpscaler(context, 3)
SessionPrefs.setGameUpscaler(context, "12345", 6)
SessionPrefs.clearGameUpscaler(context, "12345")
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
assertEquals(3, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
}
@Test fun screenEffectsUpscalerApiKeepsGameFiltersSeparateFromScreenEffects() {
SessionPrefs.setUpscaler(context, 4)
SessionPrefs.setScreenEffectsUpscaler(context, "game:12345", 8)
assertEquals(8, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
}
@Test fun legacyGameFilterOverridesRemainReadableAndCanBeReset() {
val profile = JSONObject().put("upscaler", 6)
val profiles = JSONObject().put("game:12345", profile)
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putString("screenEffects.profiles", profiles.toString()).commit()
assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
assertEquals(6, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
SessionPrefs.clearGameUpscaler(context, "12345")
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
assertEquals(2, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
}
@Test fun deletingGameScreenEffectsProfileClearsUpscalerOverrideEvenWithoutEffectsProfile() {
SessionPrefs.setGameUpscaler(context, "12345", 6)
SessionPrefs.deleteScreenEffectsProfile(context, "game:12345")
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
assertEquals(SessionPrefs.upscaler(context), SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
}
}
@@ -124,6 +124,450 @@ class SessionSuspendControllerTest {
assertEquals(1, fixture.pagedIn.size)
}
@Test fun aSpillWritesThePreloadedGuestsToStorageBeforeTheyStop() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
assertEquals(listOf<String?>("4 0"), fixture.held)
assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP })
assertEquals(listOf(1 to 4_000_000L), fixture.spills)
assertTrue(fixture.pagedOut.isEmpty())
assertTrue(fixture.game.threads.all { it.state == 't' })
assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists())
assertFalse(File(fixture.control.parentFile, ".dd-zram.hold").exists())
}
@Test fun resumeMovesTheCounterBeforeContinuingAndWaitsForTheRestore() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val before = fixture.signals.size
var called = false
fixture.controller.resume {
// success is reported once the guest has its memory back and has left its tracing stop
assertTrue(it)
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
called = true
}
assertTrue(called)
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
assertFalse(fixture.signals.drop(before).any { it.signal == URG })
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.pagedIn.isEmpty())
assertFalse(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").exists())
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf<String?>("1", "2"), fixture.resumeAtContinue)
assertEquals(2, fixture.restores.size)
}
@Test fun aRestoreThatOutlastsTheWaitIsWaitedForAgainByTheNextResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 60_000L
fixture.controller.resume { assertFalse(it) }
assertEquals(listOf(1 to 1), fixture.restores)
assertTrue(fixture.game.threads.all { it.state == 't' })
fixture.restoreDelayMs = 0L
var called = false
fixture.controller.resume {
assertTrue(it)
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
called = true
}
assertTrue(called)
assertEquals(listOf(1 to 1, 1 to 0), fixture.restores)
}
@Test fun aResumeCountThatCannotBeWrittenFailsWhileASpillHasNotAnswered() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertFalse(it) }
assertFalse(File(fixture.control.parentFile, ".dd-zram.resume").isFile)
}
@Test fun aSpillThatAnswersAfterTheWaitIsStillRestoredOnResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.spillSilent = false
fixture.advance(1_000L)
assertTrue(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").isFile)
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.pagedIn.isEmpty())
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aGuestWithoutTheSpillHandlerIsNotWaitedForOnResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.restores.isEmpty())
}
@Test fun aSpillThatStartsAfterTheWaitFailsAResumeCountThatCannotBeWritten() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertFalse(it) }
}
@Test fun aSpillThatStartsAfterTheWaitIsReleasedByTheNextCount() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.startLateSpill()
var called = false
fixture.controller.resume {
assertTrue(it)
assertEquals(listOf(1 to 0), fixture.restores)
assertEquals(4_000_000L, fixture.gameResident)
assertEquals(1, fixture.readBacks)
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' || thread.state == 'T' })
called = true
}
assertTrue(called)
}
@Test fun aLateSpillThatSeesTheNewCountIsCancelledWithoutAReadBack() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.lateSpillSeesTheCount = true
fixture.startLateSpill()
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(1 to 0), fixture.restores)
assertEquals(0, fixture.readBacks)
assertEquals(4_000_000L, fixture.gameResident)
assertTrue(fixture.pagedIn.isEmpty())
assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists())
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aHelperThatReadsBackBeforeTheContinueStillResumes() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 0L
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.releasedBeforeContinue)
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aLateSpillWithoutAnAcknowledgementFailsTheResumeUntilItsHelperLetsGo() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.ackFails = true
fixture.startLateSpill()
fixture.restoreDelayMs = 5_000L
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.game.threads.all { it.state == 't' })
fixture.advance(5_000L)
fixture.controller.resume { assertTrue(it) }
assertEquals(1, fixture.readBacks)
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aReadBackWhoseMarkerCouldNotBeWrittenEndsWhenTheHelperLetsGo() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.game.tracer = HELPER
fixture.sync()
fixture.markerFails = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val start = fixture.now
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.now - start < 5_000L)
fixture.controller.freeze { assertTrue(it) }
fixture.controller.resume { assertTrue(it) }
}
@Test fun aLateFallbackDoesNotNeedTheCountWritten() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.spillSilent = false
fixture.spillFallsBack = true
fixture.advance(1_000L)
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertTrue(it) }
assertEquals(1, fixture.pagedIn.size)
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aCancelledFreezeWhoseRestoreDoesNotFinishLeavesTheRollbackPending() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.restoreDelayMs = 60_000L
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertTrue(fixture.controller.rollbackPending)
assertEquals(listOf(1 to 1), fixture.restores)
fixture.afterSleep = null
fixture.restoreDelayMs = 0L
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.rollbackPending)
}
@Test fun aSpilledGuestThatEndsWhileReadingBackFailsTheResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 60_000L
fixture.afterSleep = {
if (fixture.signals.any { it.signal == CONT } && fixture.game.threads.first().started == 2000L) {
fixture.game.threads.first().started++
}
}
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
}
@Test fun aLossWithAnotherSpillStillReadingBackKeepsBothTheRetryAndTheFailure() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.addSecondSpiller()
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.readBackKills = true
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertTrue(fixture.controller.restoreOutstanding)
assertTrue(fixture.other.threads.all { it.state == 't' })
fixture.releaseSecondSpiller()
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertFalse(fixture.controller.restoreOutstanding)
fixture.controller.freeze { assertTrue(it) }
assertFalse(fixture.controller.guestLost)
}
@Test fun aGuestReleasedWithoutItsMarkerThatEndsLaterIsNotLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.addSecondSpiller()
fixture.game.tracer = HELPER
fixture.sync()
fixture.markerFails = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val start = fixture.now
fixture.afterSleep = {
if (fixture.now - start >= 3_000L && fixture.game.threads.first().started == 2000L) {
fixture.game.threads.first().started++
}
if (fixture.now - start >= 4_000L && fixture.otherHeld) fixture.releaseSecondSpiller()
}
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.guestLost)
}
@Test fun anAskedGuestThatStartsAndEndsBeforeItIsTakenIsLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.onAudioResume = {
File(fixture.control.parentFile, ".dd-zram.ack.$GAME").writeText("")
fixture.game.threads.first().started++
fixture.sync()
}
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
}
@Test fun aGuestLostInACancelledFreezesRollbackStaysLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.readBackKills = true
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
fixture.afterSleep = null
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertFalse(fixture.controller.restoreOutstanding)
}
@Test fun aSpillThatStartsDuringTheResumeAndIsLostFailsIt() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
// after the resume took its snapshot, before it publishes the count
fixture.onAudioResume = {
fixture.startLateSpill()
fixture.readBackKills = true
}
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
}
@Test fun aGuestThatFellBackLateAndEndedIsNotLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.onAudioResume = {
File(fixture.control.parentFile, ".dd-zram.ack.$GAME").writeText("0")
fixture.game.threads.forEach { it.state = 'Z' }
fixture.sync()
}
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.guestLost)
}
@Test fun aSpilledGuestKilledByAFailedReadBackIsLostWhileStillAZombie() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.game.tracer = HELPER
fixture.sync()
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.readBackKills = true
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertTrue(fixture.game.threads.all { it.state == 'Z' })
}
@Test fun theMarkerlessFallbackWaitsForEveryThreadToLeaveTheTrace() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.game.tracer = HELPER
fixture.sync()
fixture.markerFails = true
fixture.workerStaysTraced = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
var called = false
fixture.controller.resume {
assertTrue(it)
assertTrue(fixture.workerReleaseAt < 0)
called = true
}
assertTrue(called)
}
@Test fun aRefreezeStopsAGuestThatOnlyItsHelperStillHolds() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 60_000L
fixture.controller.resume { assertFalse(it) }
val before = fixture.signals.size
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
assertTrue(fixture.signals.drop(before).count { it.pid == GAME && it.signal == STOP } >= 17)
fixture.restoreDelayMs = 0L
fixture.advance(1_000L)
assertTrue(fixture.game.threads.all { it.state == 'T' })
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aResumeThatCannotPublishItsCountKeepsTheFrozenTimeOwed() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.clock.writeBytes(shift(0L))
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val frozenAt = fixture.now
val blocked = File(fixture.control.parentFile, ".dd-zram.resume.new").apply { mkdirs() }
fixture.now += 90_000L
fixture.controller.resume { assertFalse(it) }
blocked.delete()
fixture.now += 10_000L
val resumedAt = fixture.now
fixture.controller.resume { assertTrue(it) }
assertEquals((resumedAt - frozenAt) * 1_000_000L, shift(fixture.clock))
}
@Test fun aRollbackThatCannotPublishItsCountStaysPendingUntilAResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
val blocked = File(fixture.control.parentFile, ".dd-zram.resume.new").apply { mkdirs() }
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertTrue(fixture.controller.rollbackPending)
assertTrue(fixture.resumeAtContinue.isEmpty())
blocked.delete()
fixture.afterSleep = null
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.rollbackPending)
assertEquals(listOf(1 to 0), fixture.restores)
}
@Test fun aLateFallbackToZramIsReadBack() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.spillSilent = false
fixture.spillFallsBack = true
fixture.advance(1_000L)
fixture.controller.resume { assertTrue(it) }
assertEquals(1, fixture.pagedIn.size)
}
@Test fun aGuestThatFellBackToZramResumesWhenTheCountCannotBeWritten() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillFallsBack = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aRestoreThatFinishedLateDoesNotHoldBackTheNextResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 60_000L
fixture.controller.resume { assertFalse(it) }
fixture.restoreDelayMs = 0L
fixture.advance(1_000L)
fixture.advance(100L)
assertTrue(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").isFile)
fixture.spillFallsBack = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.controller.resume { assertTrue(it) }
}
@Test fun aGuestThatCouldNotSpillIsReadBackFromZram() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillFallsBack = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
assertEquals(listOf(0 to 0L), fixture.spills)
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(GAME), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
assertTrue(fixture.restores.isEmpty())
assertEquals(1, fixture.pagedIn.size)
}
@Test fun aSpillCutShortByACancelledFreezeIsStillRestored() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
assertEquals(listOf(1 to 0), fixture.restores)
}
@Test fun theMonitorIsHeldOffWhilePagingOutAndReadingBack() {
val fixture = fixture(17)
fixture.control.writeText("0")
@@ -485,7 +929,7 @@ class SessionSuspendControllerTest {
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
Fixture(temporary.newFolder(), temporary.newFolder(), count, executor)
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0, var tracer: Int? = null)
private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList<Task>)
private data class SentSignal(val pid: Int, val signal: Int)
@@ -493,6 +937,20 @@ class SessionSuspendControllerTest {
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') })
val groups = mutableListOf(root, game)
val other = Group(OTHER, ROOT, ROOT, mutableListOf(Task(OTHER, 4000, 'S')))
var otherHeld = false
fun addSecondSpiller() {
groups += other
sync()
}
fun releaseSecondSpiller() {
otherHeld = false
other.threads.forEach { it.state = 'S' }
File(control.parentFile, "${control.name}.restored.$OTHER").writeText("50")
sync()
}
val helpers = mutableListOf<Int>()
val signals = mutableListOf<SentSignal>()
val held = mutableListOf<String?>()
@@ -507,6 +965,7 @@ class SessionSuspendControllerTest {
var emptyGameTasks = false
var rootGone = false
var afterSleep: (() -> Unit)? = null
var onAudioResume: (() -> Unit)? = null
val control = File(tmp, ".dd-zram")
val clock = File(tmp, ".dd-clock")
var clockAtContinue: Long? = null
@@ -522,9 +981,32 @@ class SessionSuspendControllerTest {
var unacknowledged = -1
var handlerStalls = false
var handlerReplaced = false
var spillFallsBack = false
var spillSilent = false
var restoreDelayMs = RESTORE_DELAY_MS
val spills = mutableListOf<Pair<Int, Long>>()
val restores = mutableListOf<Pair<Int, Int>>()
val resumeAtContinue = mutableListOf<String?>()
var lateSpillSeesTheCount = false
var markerFails = false
var workerStaysTraced = false
var workerReleaseAt = -1L
var readBackKills = false
var readBacks = 0
val gameResident get() = gameResidentKb
private var spilling = false
private var spilledBase: String? = null
private var restoring = false
private var restoredPending = false
private var gameStopPending = false
private var countSeenAt = -1L
private var gameContinued = false
var releasedBeforeContinue = false
var ackFails = false
private val resume = File(tmp, ".dd-zram.resume")
private var continuing = false
val controller = SessionSuspendController(
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++; onAudioResume?.invoke() },
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
zramControl = control,
clockControl = clock,
@@ -535,12 +1017,15 @@ class SessionSuspendControllerTest {
this.unacknowledged = unacknowledged
},
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
spilled = { processes, spilledKb, _, _ -> spills += processes to spilledKb },
restored = { processes, unacknowledged, _, _ -> restores += processes to unacknowledged },
)
init { sync() }
private fun signal(pid: Int, signal: Int) {
signals += SentSignal(pid, signal)
helperStep()
val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null
if (signal == URG) held += request
val group = groups.first { it.pid == pid }
@@ -550,14 +1035,34 @@ class SessionSuspendControllerTest {
else group.threads.firstOrNull {
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
}?.state = 't'
} else if (signal == URG && pid == OTHER) {
// a second guest that spills at once and whose helper reads back only when the test lets it
if (request?.startsWith("4") == true) {
File(control.parentFile, "${control.name}.ack.$OTHER").writeText("1000")
otherHeld = true
other.threads.forEach { it.state = 't' }
}
} else if (signal == URG) {
if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
if (request?.startsWith("4") == true) {
if (!handlerReplaced) {
spilling = true
File(control.parentFile, "${control.name}.ack.$GAME").writeText("")
}
spilledBase = request.substringAfter(' ', "0").trim()
}
else if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
} else if (signal == CONT) {
if (pid == GAME) resumeAtContinue += resume.takeIf { it.isFile }?.readText()
if (clockAtContinue == null && clock.isFile) {
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
}
continuing = true
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
if (pid == GAME) gameStopPending = false
if (pid == GAME) gameContinued = true
// a spilled guest stays in its tracing stop until its helper has read the memory back
if (!(pid == GAME && (blockGameContinue || parked)) && !(pid == OTHER && otherHeld)) {
group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
}
sync()
}
@@ -565,14 +1070,88 @@ class SessionSuspendControllerTest {
private fun threadSignal(pid: Int, tid: Int, signal: Int) {
signals += SentSignal(pid, signal)
val task = groups.first { it.pid == pid }.threads.first { it.tid == tid }
// held by the helper's trace: the stop stays pending until the helper detaches
if (signal == STOP && pid == GAME && parked && task.state == 't') gameStopPending = true
if (signal == STOP && task.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && task == game.threads.last())) {
task.state = 't'
}
sync()
}
private val parked get() = spilling || restoring
private fun releaseGame() {
countSeenAt = -1L
game.threads.forEach { if (it.state != 'Z') it.state = if (gameStopPending) 'T' else 'S' }
}
fun advance(millis: Long) = sleep(millis)
// the handler takes the spill request only now, after the controller stopped waiting for it
fun startLateSpill() {
handlerReplaced = false
spilling = true
if (!ackFails) File(control.parentFile, "${control.name}.ack.$GAME").writeText("")
}
// The helper reads back as soon as it sees a new count, SIGCONT or not; it detaches first and publishes
// its marker on a later step.
private fun helperStep() {
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
if (restoredPending) {
restoredPending = false
if (!markerFails) File(control.parentFile, "${control.name}.restored.$GAME").writeText("120")
}
if (workerReleaseAt in 0..now) {
game.threads.last().tracer = null
workerReleaseAt = -1L
}
if (!restoring || count == spilledBase) return
if (countSeenAt < 0) {
countSeenAt = now
gameContinued = false
}
if (now - countSeenAt < restoreDelayMs) return
restoring = false
if (readBackKills) {
// the helper kills its owner on a failed read-back; nobody has reaped it yet
game.tracer = 0
game.threads.forEach { it.state = 'Z' }
countSeenAt = -1L
return
}
readBacks++
gameResidentKb = 4_000_000L
if (markerFails) game.tracer = 0
if (markerFails && workerStaysTraced) {
game.threads.last().tracer = HELPER
workerReleaseAt = now + 3_000L
}
if (!gameContinued) releasedBeforeContinue = true
releaseGame()
restoredPending = true
}
private fun sleep(millis: Long) {
now += millis
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
if (spilling && !spillSilent) {
spilling = false
val ack = File(control.parentFile, "${control.name}.ack.$GAME")
if (lateSpillSeesTheCount && count != spilledBase) {
ack.writeText("-2")
releaseGame()
} else if (spillFallsBack) {
gameSwapKb += gameResidentKb
gameResidentKb = 0L
ack.writeText("0")
} else {
if (!ackFails) ack.writeText(gameResidentKb.toString())
gameResidentKb = 0L
restoring = true
}
}
helperStep()
if (pagingOut && !handlerReplaced) {
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
}
@@ -591,7 +1170,7 @@ class SessionSuspendControllerTest {
gameResidentKb += moved
if (gameSwapKb == 0L) pagingIn = false
}
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
if (root.threads.first().state != 'T' && !continuing && !parked) game.threads.forEach {
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
}
afterSleep?.invoke()
@@ -611,7 +1190,7 @@ class SessionSuspendControllerTest {
"TracerPid: ${group.tracer}\n" +
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "",
)
if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
if (group == game || group == other) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
val taskDir = File(dir, "task")
if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue }
taskDir.mkdirs()
@@ -619,6 +1198,7 @@ class SessionSuspendControllerTest {
for (task in group.threads) {
val entry = File(taskDir, task.tid.toString()).apply { mkdirs() }
File(entry, "stat").writeText(stat(group, task))
File(entry, "status").writeText("TracerPid: ${task.tracer ?: group.tracer}\n")
}
}
}
@@ -661,5 +1241,8 @@ class SessionSuspendControllerTest {
const val STOP = 19
const val CONT = 18
const val URG = 23
const val RESTORE_DELAY_MS = 300L
const val HELPER = 300
const val OTHER = 400
}
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SuspendRecoveryTest {
@Test fun theFirstAttemptIsDueAtOnceAndLaterOnesBackOff() {
val recovery = SuspendRecovery(maxAttempts = 3, firstDelayMs = 1_000L)
assertTrue(recovery.due(0L))
assertEquals(1_000L, recovery.failed(0L))
assertFalse(recovery.due(999L))
assertTrue(recovery.due(1_000L))
assertEquals(2_000L, recovery.failed(1_000L))
assertFalse(recovery.due(2_999L))
assertTrue(recovery.due(3_000L))
}
// The service's loop: every policy pass (a 250 ms queued-launch poll, a display event or a scheduled retry)
// starts a resume unless the recovery holds it; a failed resume schedules the next pass.
private class Service(val recovery: SuspendRecovery = SuspendRecovery()) {
var now = 0L
var suspended = true
var counterWritable = false
var resumes = 0
val scheduled = sortedSetOf<Long>()
fun pass() {
if (!suspended || recovery.holds(true, now)) return
resumes++
if (counterWritable) {
suspended = false
recovery.reset()
scheduled.clear()
} else {
recovery.failed(now)?.let { scheduled += now + it }
}
}
// Only a scheduled retry or a poll runs a pass; time with neither runs nothing.
fun runUntil(end: Long, pollMs: Long? = null) {
while (true) {
val nextPoll = pollMs?.let { now - now % it + it } ?: Long.MAX_VALUE
val next = minOf(nextPoll, scheduled.firstOrNull() ?: Long.MAX_VALUE)
if (next > end) break
now = next
scheduled.remove(next)
pass()
}
now = end
}
}
@Test fun queuedLaunchPollsCannotExceedTheRetryBudget() {
val service = Service()
service.pass()
service.runUntil(600_000L, pollMs = 250L)
assertEquals(5, service.resumes)
assertTrue(service.suspended)
}
@Test fun aScheduledRetryResumesOnceTheCountCanBeWrittenWithoutAnotherEvent() {
val service = Service()
service.pass()
assertEquals(1, service.resumes)
assertEquals(listOf(5_000L), service.scheduled.toList())
service.counterWritable = true
service.runUntil(4_999L)
assertTrue(service.suspended)
service.runUntil(5_000L)
assertFalse(service.suspended)
assertEquals(2, service.resumes)
}
@Test fun nothingResumesWithoutAScheduledRetryOrAnEvent() {
val service = Service(SuspendRecovery(maxAttempts = 1))
service.pass()
assertTrue(service.scheduled.isEmpty())
service.counterWritable = true
service.runUntil(600_000L)
assertTrue(service.suspended)
assertEquals(1, service.resumes)
}
@Test fun attemptsAreBoundedUntilAResumeSucceeds() {
val recovery = SuspendRecovery(maxAttempts = 2, firstDelayMs = 1_000L)
recovery.failed(0L)
assertNull(recovery.failed(1_000L))
assertFalse(recovery.due(1_000_000L))
recovery.reset()
assertTrue(recovery.due(0L))
}
}
+54
View File
@@ -0,0 +1,54 @@
# Easy Anti-Cheat and BattlEye
On a Steam Deck, Proton loads Valve's anti-cheat runtimes (Proton EasyAntiCheat Runtime, app 1826330, and
Proton BattlEye Runtime, app 1161040). Their bridge libraries are x86 only, so the ARM64 DroidDeck-Proton
cannot load them. Games that need them run an x86-64 DroidDeck-Proton under FEX instead.
## Routing
The Proton launchers (`steam-compatibility`: the built-in DroidDeck-Proton launcher and the wrapper put around
every tool in `compatibilitytools.d`) check each `run` and `waitforexitandrun` before any ARM64 setup:
- **Condition.** The game folder (`STEAM_COMPAT_INSTALL_PATH`, three levels deep) holds one of
`EasyAntiCheat/Settings.json`, `easyanticheat_x64.so`, `BEClient_x64.so` or `BEService_x64.exe`. No
title, app ID or device list is involved.
- **Chosen tool.** Only launches through DroidDeck's own Proton (the built-in launcher or a `DroidDeck-Proton*`
folder) are moved. A game set to any other tool, such as GE-Proton, Bionic or Valve's Proton, in DroidDeck or
in Steam's Properties, runs on that tool and the launcher logs that it was chosen.
- **Tool.** The newest `compatibilitytools.d/DroidDeck-Proton*` whose layout is x86-64
(`files/lib/wine/x86_64-unix`, no `files/bin-arm64`).
- **Runtime.** `PROTON_EAC_RUNTIME` or `PROTON_BATTLEYE_RUNTIME` when it already points at a folder with the
bridge libraries, otherwise the runtime's folder in any Steam library.
- **Launch.** `droiddeck-fex proton <tool>/proton <verb> <args>`: FEX with the Steam Linux Runtime rootfs,
keeping the game's own `STEAM_COMPAT_DATA_PATH` prefix.
Without the x86-64 tool or the runtime files the launch stays on ARM64 and the launcher logs why.
`DROIDDECK_ANTICHEAT=off` in the game's launch options keeps it on ARM64. Picking the x86-64 tool for a
game in Steam always runs it under FEX.
## Why the x86-64 build needs its own Wine patches
Android kernels use 39-bit user address spaces. Easy Anti-Cheat's launcher maps fixed memory at
`0x7001_0000_0000`, which FEX serves from emulated guest pages (`tools/fex/patches/0027`). Exclusive load and store pairs on that
memory are emulated as a compare-and-swap, so hosts without LSE atomics work too. `tools/fex/probes/guest-high-memory.c`
checks loads, stores, atomics, iovec system calls, `madvise` and code written through a high alias. The x86-64 Wine
in DroidDeck-Proton carries `ntdll-fixed-allocations-above-host-address-limit.patch` (fixed mappings above
the host limit go to the emulator) and `ntdll-keep-libc-in-native-syscall-dispatch-range.patch` (the
re-armed syscall user dispatch range keeps libc native). Stock x86-64 Proton stops after "Hack native
syscalls" on the same game.
Easy Anti-Cheat's launcher attaches to the game with ptrace, stops it on a `rt_sigprocmask` call, runs its
own loader and restores the registers it saved at the stop. The call then returns `ENOSYS` without writing
the old mask, as it does on a desktop kernel. `ntdll-retry-blocking-signals-dropped-by-a-tracer.patch`
retries the block once when it fails, so Wine never restores an uninitialised mask that blocks `SIGSYS`.
## The container's procfs
Android mounts `/proc` with `hidepid=invisible,gid=3009`, and Easy Anti-Cheat refuses that mount with
launch error 261. Without root, user namespaces or PID namespaces, no procfs instance without those options
can be mounted. Every program in the container runs as the app's user and already sees all of the
container's processes, as it would in a PID-namespaced sandbox on a desktop, so FEX's emulated
`/proc/<pid>/mounts` and `/proc/<pid>/mountinfo` show the proc mount without `hidepid=`, `gid=` and
`subset=` (`tools/fex/patches/0029`). Only x86 programs under FEX see this view; every other line of the
table is the host's. Processes of other Android users stay hidden, as host processes do from a desktop
sandbox.
+16
View File
@@ -97,6 +97,22 @@ out, and resuming reads it back when available memory is at least twice what tho
have in swap at that moment and, after it, 1 GiB or a tenth of RAM, whichever is larger, stays
available.
## Writing a sleeping session to storage
With the `diskSpill` session pref on, the suspend for sleep writes each preloaded process's
private memory to storage instead of zram (request `4`). The preload's worker starts a helper
process that shares the process's memory, stops every other thread with ptrace (which also holds
threads that block every signal, as Mesa's queue threads do, and which `SIGCONT` does not undo),
writes readable private anonymous memory to an unlinked file next to the control file, drops it,
and answers the kB it wrote in `/tmp/.dd-zram.ack.<pid>`. Regions registered with userfaultfd,
locked or I/O memory and the preload's own memory stay. The app adds one to
`/tmp/.dd-zram.resume` before it continues any process; the helper then reads everything back
(through `/proc/<pid>/mem` where the pages are not writable), answers `/tmp/.dd-zram.restored.<pid>`
and lets the threads go. A process that cannot be traced answers `0` and pages out to zram instead.
On an AYN Thor with Bully at its menu, 30 processes wrote 1,227 MB in 2.1 seconds and read it
back in 1.3 seconds; system anonymous memory fell from 2.53 to 1.21 GB while asleep.
## Threads
When a worker can be started, page-out runs outside the game's threads. The preload's signal
+4 -3
View File
@@ -216,9 +216,10 @@ alone would then read as an installed client.
NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the
overlapping part of any alias that is already executable, so the first write faults and invalidates.
`FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch.
- `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
`install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
The guest libraries are external projects in the default build, which `install` already follows.
- `0007-cmake-install-code-without-depends` (`Fixed-upstream: FEX-2612`): CMake 4.5 rejects the
`DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with
host thunks stopped at configure. The guest libraries are external projects in the default build,
which `install` already follows.
- `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's
syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler
left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and
+5
View File
@@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
mkdir -p out/usr/local/share/fex-emu
for p in tools/fex/patches/*.patch; do
p=$(basename "$p" .patch)
echo "${p#*-}"
done > out/usr/local/share/fex-emu/.droiddeck-patches
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
@@ -1,3 +1,4 @@
Fixed-upstream: FEX-2612
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8976588..3ae54f4 100644
--- a/CMakeLists.txt
@@ -1,8 +1,8 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index b4c7b24..643185d 100644
index 345f4d834..085ff00a2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
auto Frame = Thread->CurrentFrame;
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
@@ -1,5 +1,5 @@
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
index 02bb6bf..2e72492 100644
index 02bb6bfef..2e724929f 100644
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
@@ -49,6 +49,11 @@ struct X86ContextBackup {
@@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644
// Arm64 doesn't have a red zone
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index 643185d..53179c4 100644
index 085ff00a2..5c79d1092 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
#endif
}
@@ -62,7 +62,7 @@ index 643185d..53179c4 100644
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
// We can end up getting a signal at any point in our host state
// Jump to a handler that saves all state so we can safely return
@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
}
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
@@ -82,7 +82,7 @@ index 643185d..53179c4 100644
}
uintptr_t NewSP = OldSP;
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
auto Frame = Thread->CurrentFrame;
@@ -90,7 +90,7 @@ index 643185d..53179c4 100644
// Ref count our faults
// We use this to track if it is safe to clear cache
@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
uint64_t NewGuestSP = OldGuestSP;
@@ -99,7 +99,7 @@ index 643185d..53179c4 100644
// altstack is only used if the signal handler was setup with SA_ONSTACK
if (GuestAction->sa_flags & SA_ONSTACK) {
@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp);
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
@@ -108,7 +108,7 @@ index 643185d..53179c4 100644
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
// We are already in the alt stack, the rest of the code will handle adjusting this
} else {
@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
}
}
@@ -149,7 +149,7 @@ index 643185d..53179c4 100644
// siginfo_t
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
// Our ref counting doesn't matter anymore
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
@@ -159,7 +159,7 @@ index 643185d..53179c4 100644
// Set the new PC
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
index dfcd4b0..e4a86a9 100644
index 0f45cf68d..408cddf71 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
@@ -1,7 +1,8 @@
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
index 1946dc946..9f04358c5 100644
--- a/FEXCore/Source/Interface/Core/Core.cpp
+++ b/FEXCore/Source/Interface/Core/Core.cpp
@@ -383,7 +383,11 @@
@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() {
}
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
@@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
index ae3ed51e4..c5e656d2c 100644
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
@@ -305,6 +305,9 @@
@@ -306,6 +306,9 @@ DEF_OP(Thunk) {
PushDynamicRegs(TMP1);
@@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
@@ -320,6 +323,8 @@
@@ -321,6 +324,8 @@ DEF_OP(Thunk) {
FillStaticRegs({
.NZCV = false,
});
@@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
DEF_OP(ValidateCode) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index 5c79d1092..e8e04b056 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -107,6 +107,10 @@
@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
#ifdef ARCHITECTURE_arm64
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
@@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
if (IgnoreMask & (1U << SRAIdxMap)) {
@@ -301,12 +305,10 @@
@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
if (Context->UContextLocation) {
auto Frame = Thread->CurrentFrame;
@@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
if (Is64BitMode) {
RestoreFrame_x64(Thread, Context, Frame, ucontext);
@@ -361,6 +363,9 @@
@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
Thread->CurrentFrame->InSyscallInfo = 0;
} else {
@@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
// This is likely to cause issues but in some cases it isn't fatal
// This can also happen if we have put a signal on hold, then we just reenabled the signal
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
index fa6260954..e5d92e7c5 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -131,7 +131,7 @@
@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
@@ -211,7 +211,7 @@
@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
// If the guest modified the RIP then we need to take special precautions here
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
@@ -290,7 +290,7 @@
@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -1,7 +1,8 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
index 9e6820bf6..43898e700 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
@@ -263,6 +263,8 @@
@@ -266,6 +266,8 @@ private:
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
@@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc
///< Setup the signal frame for x64.
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
index e5d92e7c5..38dc524f1 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -122,6 +122,32 @@
@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) {
}
}
@@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
@@ -202,6 +228,27 @@
@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
}
@@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
}
}
@@ -280,6 +327,17 @@
@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
@@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
}
}
@@ -359,6 +417,17 @@
@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
@@ -1,8 +1,8 @@
diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
index 2881ad9..abc84f3 100644
index dd2c18303..e7e88f8f2 100644
--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
+++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) {
@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) {
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName);
} else {
// Anonymous program.
@@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644
}
} else {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
index a7a432b..4a77d87 100644
index a7a432bbd..4a77d8716 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
From: maxjivi05 <maxjividen@gmail.com>
Subject: [PATCH] List only guest mappings in /proc/<pid>/maps on hosts below 47 address bits
Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index eb12945e4..65b0521c9 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -17,7 +17,11 @@ $end_info$
#include <FEXCore/Config/Config.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Core/CPUID.h>
+#include <FEXCore/Utils/Allocator.h>
#include <FEXCore/Utils/LogManager.h>
+#include <FEXCore/Utils/SignalScopeGuards.h>
+#include <FEXCore/fextl/unordered_map.h>
+#include <FEXCore/fextl/vector.h>
#include <FEXCore/fextl/fmt.h>
#include <FEXCore/fextl/string.h>
#include <FEXCore/fextl/sstream.h>
@@ -25,9 +29,13 @@ $end_info$
#include <git_version.h>
+#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
+#include <elf.h>
+#include <mutex>
+#include <shared_mutex>
#include <fcntl.h>
#include <filesystem>
#include <ostream>
@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
EmulatedFDManager::~EmulatedFDManager() {}
+static bool IsSelfProcPath(const char* Path) {
+ const char* P = Path + 6;
+ if (!isdigit(*P)) {
+ return true;
+ }
+ return strtol(P, nullptr, 10) == ::getpid();
+}
+
+static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::string, bool>& Seen) {
+ auto Known = Seen.find(Path);
+ if (Known != Seen.end()) {
+ return Known->second;
+ }
+ bool Host = false;
+ int FD = ::open(Path, O_RDONLY | O_CLOEXEC);
+ if (FD >= 0) {
+ Elf64_Ehdr Header {};
+ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast<ssize_t>(offsetof(Elf64_Ehdr, e_version)) &&
+ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) {
+#if defined(__aarch64__)
+ Host = Header.e_machine == EM_AARCH64;
+#else
+ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386;
+#endif
+ }
+ ::close(FD);
+ }
+ Seen.emplace(Path, Host);
+ return Host;
+}
+
static bool IsProcMapsPath(const char* Path) {
if (strncmp(Path, "/proc/", 6) != 0) {
return false;
@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
::close(HostFD);
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
+ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
+ const bool Self = IsSelfProcPath(pathname);
+ fextl::vector<std::pair<uint64_t, uint64_t>> GuestRanges;
+ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) {
+ auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(FEX::HLE::_SyscallHandler->VMATracking.Mutex);
+ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size());
+ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) {
+ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) {
+ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length);
+ } else {
+ GuestRanges.emplace_back(Base, Base + VMA.Length);
+ }
+ }
+ }
+ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) {
+ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start,
+ [](uint64_t Value, const std::pair<uint64_t, uint64_t>& Range) { return Value < Range.first; });
+ if (It != GuestRanges.begin() && std::prev(It)->second > Start) {
+ return true;
+ }
+ return It != GuestRanges.end() && It->first < End;
+ };
+ fextl::unordered_map<fextl::string, bool> ModuleArch;
fextl::string Out;
Out.reserve(In.size());
size_t Pos = 0;
while (Pos < In.size()) {
size_t Eol = In.find('\n', Pos);
const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1;
- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16);
- if (Start < X86_64TaskSizeMax) {
+ char* Cursor {};
+ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16);
+ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start;
+ bool Keep = Start < X86_64TaskSizeMax;
+ if (Keep && HostSharesGuestRange) {
+ if (Self) {
+ Keep = IsGuestRange(Start, Stop);
+ } else {
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
+ size_t Name = In.find_first_of("/[", Pos);
+ if (Name != fextl::string::npos && Name < LineEnd) {
+ fextl::string Path(In, Name, LineEnd - Name);
+ if (Path.starts_with("[anon:FEX")) {
+ Keep = false;
+ } else if (Path[0] == '/') {
+ Keep = !IsHostArchModule(Path.c_str(), ModuleArch);
+ }
+ }
+ }
+ }
+ if (Keep) {
Out.append(In, Pos, End - Pos);
}
Pos = End;
@@ -0,0 +1,53 @@
From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:21:23 -0500
Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
.../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++-
.../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index 65b0521c9..ce36b988b 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
Buf[Len] = '\0';
uint32_t SeccompMode = SECCOMP_MODE_DISABLED;
- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) {
+ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr;
+ if (!Thread) {
+ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject();
+ }
+ if (Thread) {
SeccompMode = Thread->SeccompMode;
}
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
index 0a46703ca..9c5f9f1c2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -290,6 +290,16 @@ public:
return &Threads;
}
+ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) {
+ std::lock_guard lk(ThreadCreationMutex);
+ for (auto* Thread : Threads) {
+ if (Thread->ThreadInfo.TID == TID) {
+ return Thread;
+ }
+ }
+ return nullptr;
+ }
+
private:
struct InvalidationStats {
explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread)
--
2.43.0
@@ -0,0 +1,105 @@
From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:25:20 -0500
Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system
call
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++
.../EmulatedFiles/EmulatedFiles.cpp | 3 +-
.../LinuxSyscalls/PtraceEmu.cpp | 3 +-
3 files changed, 34 insertions(+), 2 deletions(-)
diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
index dae3d3bcc..c0f3eb3ed 100644
--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
+++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
@@ -4,6 +4,7 @@
#include <FEXCore/Utils/LogManager.h>
#include <cstdint>
+#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
@@ -123,4 +124,33 @@ inline int32_t gettid() {
#endif
+#ifndef _WIN32
+inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) {
+#if defined(__aarch64__)
+ register long x0 asm("x0") = dirfd;
+ register long x1 asm("x1") = reinterpret_cast<long>(pathname);
+ register long x2 asm("x2") = flags;
+ register long x3 asm("x3") = 0;
+ register long x8 asm("x8") = SYS_openat;
+ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory");
+ if (x0 < 0) {
+ errno = static_cast<int>(-x0);
+ return -1;
+ }
+ return static_cast<int32_t>(x0);
+#elif defined(__x86_64__)
+ long ret;
+ register long r10 asm("r10") = 0;
+ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory");
+ if (ret < 0) {
+ errno = static_cast<int>(-ret);
+ return -1;
+ }
+ return static_cast<int32_t>(ret);
+#else
+ return static_cast<int32_t>(::syscall(SYS_openat, dirfd, pathname, flags));
+#endif
+}
+#endif
+
} // namespace FHU::Syscalls
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index ce36b988b..19bfc814f 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -14,6 +14,7 @@ $end_info$
#include "LinuxSyscalls/Syscalls.h"
#include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
+#include <FEXHeaderUtils/Syscalls.h>
#include <FEXCore/Config/Config.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Core/CPUID.h>
@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
char Buf[8192];
ssize_t Len = 0;
{
- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
+ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
if (HostFD >= 0) {
Len = ::read(HostFD, Buf, sizeof(Buf) - 1);
::close(HostFD);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
index ca4c86063..49ece24a3 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
@@ -3,6 +3,7 @@
#include "LinuxSyscalls/PtraceEmu.h"
#include "LinuxSyscalls/Syscalls.h"
+#include <FEXHeaderUtils/Syscalls.h>
#include <FEXCore/Core/CoreState.h>
#include <FEXCore/Core/X86Enums.h>
@@ -133,7 +134,7 @@ namespace {
}
bool HasHostTracer() {
- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
+ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return true;
}
--
2.43.0
@@ -0,0 +1,104 @@
From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:41:52 -0500
Subject: [PATCH] Hand the tracee's ptrace state across exec
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
.../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++-
1 file changed, 53 insertions(+), 1 deletion(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
index 49ece24a3..62acdb0da 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
@@ -266,6 +266,38 @@ namespace {
::close(fd);
}
+ bool AdoptionTried = false;
+
+ void AdoptSharedPage() {
+ if (AdoptionTried || Current != &StaticState || !IsMainThread()) {
+ return;
+ }
+ AdoptionTried = true;
+ const int fd = OpenSidecar("state", ::getpid(), O_RDWR);
+ if (fd < 0) {
+ return;
+ }
+ if (!HasHostTracer()) {
+ ::close(fd);
+ return;
+ }
+ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ ::close(fd);
+ if (Page == MAP_FAILED) {
+ return;
+ }
+ auto* S = static_cast<SharedState*>(Page);
+ if (S->Magic != SharedState::MagicValue) {
+ ::munmap(Page, 4096);
+ return;
+ }
+ S->Pending = 0;
+ S->DirtyMask = 0;
+ S->SignalNumber = 0;
+ S->FlushLen = 0;
+ Current = S;
+ }
+
struct Remote {
uint8_t* Mapped = nullptr;
uintptr_t StaticAddr = 0;
@@ -332,6 +364,22 @@ namespace {
return &Remotes.emplace(Pid, std::move(R)).first->second;
}
+ bool KeepAcrossExec(pid_t Pid) {
+ {
+ std::lock_guard lk(RemotesLock);
+ auto It = Remotes.find(Pid);
+ if (It != Remotes.end()) {
+ return It->second.Mapped != nullptr;
+ }
+ }
+ const int fd = OpenSidecar("state", Pid, O_RDONLY);
+ if (fd < 0) {
+ return false;
+ }
+ ::close(fd);
+ return true;
+ }
+
void Forget(pid_t Pid, bool Exited) {
std::lock_guard lk(RemotesLock);
auto It = Remotes.find(Pid);
@@ -470,10 +518,12 @@ namespace {
bool IsAttached() {
+ AdoptSharedPage();
return Current->Attached != 0;
}
bool WantsSyscallStops() {
+ AdoptSharedPage();
return Current->SyscallStops && IsMainThread();
}
@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) {
if ((St >> 16) == X86_PTRACE_EVENT_EXEC) {
CaptureExecPath(Pid);
- Forget(Pid, false);
+ if (!KeepAcrossExec(Pid)) {
+ Forget(Pid, false);
+ }
}
if (WSTOPSIG(St) == SIGSTOP) {
--
2.43.0
@@ -0,0 +1,78 @@
From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:58:13 -0500
Subject: [PATCH] Serve emulated proc files by the requested path when the host
returns a memfd
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
.../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++----
.../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +-
2 files changed, 8 insertions(+), 5 deletions(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
index 62b6a2d27..b76e96e58 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint
return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode);
}
-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
+bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) {
char Tmp[PATH_MAX + 1];
if (fd < 0) {
@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
// And try to open via EmuFD
auto EmuFd = EmuFD.Open(Tmp, flags, mode);
+ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) {
+ EmuFd = EmuFD.Open(RequestedPath, flags, mode);
+ }
if (EmuFd == -1) {
return false;
}
@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
fd = ::open(SelfPath, flags, mode);
}
- ReplaceEmuFd(fd, flags, mode);
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
} else {
fd = ::open(SelfPath, flags, mode);
}
@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
}
- ReplaceEmuFd(fd, flags, mode);
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
} else {
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
}
@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
}
- ReplaceEmuFd(fd, how->flags, how->mode);
+ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath);
} else {
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
}
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
index b11f096f7..a86539972 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
@@ -102,7 +102,7 @@ public:
fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const;
fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const;
- bool ReplaceEmuFd(int fd, int flags, uint32_t mode);
+ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath);
#if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED
void TrackFEXFD(int FD) noexcept {
--
2.43.0
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,58 @@
From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Thu, 3 Dec 2026 03:26:13 -0500
Subject: [PATCH] Show the guest command line when the argument area cannot be
remapped
Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP,
so /proc/pid/cmdline kept showing the FEX invocation instead of the
guest program and the argv rewrites it makes. For 64-bit guests whose
arguments fit, the guest argument strings now live in the original
argument area and argv points there, which needs no privilege.
---
Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
index b1a72d227..6d2157365 100644
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
@@ -874,13 +874,34 @@ public:
int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L);
if (r != 0) {
- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno);
+ int Error = errno;
+ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) {
+ return;
+ }
+ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error);
}
} else {
LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)");
}
}
+ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) {
+ struct prctl_mm_map map {};
+ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) {
+ return false;
+ }
+
+ auto HostArgs = reinterpret_cast<uint8_t*>(map.arg_start);
+ memmove(HostArgs, reinterpret_cast<const void*>(GuestArgStart), ArgSize);
+ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize);
+
+ auto ArgumentPointers = reinterpret_cast<uint64_t*>(StackPointer + sizeof(uint64_t));
+ for (size_t i = 0; i < ApplicationArgs.size(); ++i) {
+ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start;
+ }
+ return true;
+ }
+
// Setups the stack initial data (argv, envp, auxv)
void SetupStack() {
StackPointer += StackSize();
--
2.43.0
@@ -0,0 +1,310 @@
From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Thu, 3 Dec 2026 08:03:20 -0500
Subject: [PATCH] Describe the container's procfs in emulated mount tables
Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the
processes of other users. Every process of the container runs as the app's
user, so the container sees all of its own processes, as it would through a
procfs of its own in a PID namespace. The emulated /proc/<pid>/mounts and
mountinfo now list the proc mount without the host instance's access options
(hidepid, gid, subset). Every other mount is passed through unchanged.
---
.../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++-----
.../EmulatedFiles/EmulatedFiles.h | 1 +
2 files changed, 170 insertions(+), 61 deletions(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index 19bfc814f..85f1b3e15 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -37,6 +37,7 @@ $end_info$
#include <elf.h>
#include <mutex>
#include <shared_mutex>
+#include <string_view>
#include <fcntl.h>
#include <filesystem>
#include <ostream>
@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::strin
return Host;
}
+static bool ReadHostFile(const char* Path, fextl::string& Out) {
+ int HostFD = ::open(Path, O_RDONLY | O_CLOEXEC);
+ if (HostFD < 0) {
+ return false;
+ }
+ char Buf[65536];
+ for (;;) {
+ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
+ if (Len > 0) {
+ Out.append(Buf, Len);
+ } else if (Len == 0) {
+ break;
+ } else if (errno != EINTR) {
+ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno);
+ ::close(HostFD);
+ return false;
+ }
+ }
+ ::close(HostFD);
+ return true;
+}
+
+static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) {
+ int NewFD = GenTmpFD(pathname, flags);
+ if (NewFD < 0) {
+ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno);
+ return -1;
+ }
+ for (size_t Done = 0; Done < Data.size();) {
+ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done);
+ if (Wrote > 0) {
+ Done += Wrote;
+ } else if (Wrote < 0 && errno == EINTR) {
+ continue;
+ } else {
+ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno);
+ ::close(NewFD);
+ return -1;
+ }
+ }
+ if (::lseek(NewFD, 0, SEEK_SET) != 0) {
+ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno);
+ ::close(NewFD);
+ return -1;
+ }
+ SealTmpFD(NewFD);
+ return NewFD;
+}
+
+static const char* ProcFileOfPid(const char* Path) {
+ if (strncmp(Path, "/proc/", 6) != 0) {
+ return nullptr;
+ }
+ const char* P = Path + 6;
+ if (strncmp(P, "self/", 5) == 0) {
+ return P + 5;
+ }
+ if (strncmp(P, "thread-self/", 12) == 0) {
+ return P + 12;
+ }
+ if (!isdigit(*P)) {
+ return P;
+ }
+ while (isdigit(*P)) {
+ ++P;
+ }
+ if (*P++ != '/') {
+ return nullptr;
+ }
+ if (strncmp(P, "task/", 5) == 0) {
+ P += 5;
+ if (!isdigit(*P)) {
+ return nullptr;
+ }
+ while (isdigit(*P)) {
+ ++P;
+ }
+ if (*P++ != '/') {
+ return nullptr;
+ }
+ }
+ return P;
+}
+
+static bool IsProcMountTablePath(const char* Path) {
+ const char* File = ProcFileOfPid(Path);
+ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0);
+}
+
+static fextl::string ContainerProcOptions(std::string_view Options) {
+ fextl::string Out;
+ size_t Pos = 0;
+ while (Pos <= Options.size()) {
+ size_t Comma = Options.find(',', Pos);
+ if (Comma == std::string_view::npos) {
+ Comma = Options.size();
+ }
+ const std::string_view Option = Options.substr(Pos, Comma - Pos);
+ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) {
+ if (!Out.empty()) {
+ Out += ',';
+ }
+ Out.append(Option);
+ }
+ Pos = Comma + 1;
+ }
+ return Out;
+}
+
+static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {
+ fextl::vector<std::string_view> Fields;
+ size_t Pos = 0;
+ while (Pos < Line.size()) {
+ size_t Space = Line.find(' ', Pos);
+ if (Space == std::string_view::npos) {
+ Space = Line.size();
+ }
+ Fields.push_back(Line.substr(Pos, Space - Pos));
+ Pos = Space + 1;
+ }
+ size_t Type = 2;
+ if (MountInfo) {
+ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-"));
+ Type = static_cast<size_t>(Dash - Fields.begin()) + 1;
+ }
+ const size_t Options = MountInfo ? Type + 2 : Type + 1;
+ if (Options >= Fields.size() || Fields[Type] != "proc") {
+ return fextl::string(Line);
+ }
+ fextl::string Out;
+ for (size_t i = 0; i < Fields.size(); ++i) {
+ if (i) {
+ Out += ' ';
+ }
+ if (i == Options) {
+ Out += ContainerProcOptions(Fields[i]);
+ } else {
+ Out.append(Fields[i]);
+ }
+ }
+ return Out;
+}
+
static bool IsProcMapsPath(const char* Path) {
if (strncmp(Path, "/proc/", 6) != 0) {
return false;
@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
if (pathname && IsProcMapsPath(pathname)) {
return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode);
}
+ if (pathname && IsProcMountTablePath(pathname)) {
+ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);
+ }
return -1;
}
@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
}
int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
- int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC);
- if (HostFD < 0) {
- return -1;
- }
fextl::string In;
- char Buf[65536];
- for (;;) {
- const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
- if (Len > 0) {
- In.append(Buf, Len);
- } else if (Len == 0) {
- break;
- } else if (errno != EINTR) {
- LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno);
- ::close(HostFD);
- return -1;
- }
+ if (!ReadHostFile(pathname, In)) {
+ return -1;
}
- ::close(HostFD);
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
Pos = End;
}
- int NewFD = GenTmpFD(pathname, flags);
- if (NewFD < 0) {
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
+ return SealedFileOf(pathname, flags, Out);
+}
+
+int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
+ fextl::string In;
+ if (!ReadHostFile(pathname, In)) {
return -1;
}
- for (size_t Done = 0; Done < Out.size();) {
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
- if (Wrote > 0) {
- Done += Wrote;
- } else if (Wrote < 0 && errno == EINTR) {
- continue;
- } else {
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
- ::close(NewFD);
- return -1;
+ const char* File = ProcFileOfPid(pathname);
+ const bool MountInfo = File && strcmp(File, "mountinfo") == 0;
+ fextl::string Out;
+ Out.reserve(In.size());
+ size_t Pos = 0;
+ while (Pos < In.size()) {
+ size_t Eol = In.find('\n', Pos);
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
+ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
+ if (Eol != fextl::string::npos) {
+ Out += '\n';
}
+ Pos = LineEnd + 1;
}
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
- ::close(NewFD);
- return -1;
- }
- SealTmpFD(NewFD);
- return NewFD;
+ return SealedFileOf(pathname, flags, Out);
}
int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
Cursor = Eol + 1;
}
- int NewFD = GenTmpFD(pathname, flags);
- if (NewFD < 0) {
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
- return -1;
- }
- for (size_t Done = 0; Done < Out.size();) {
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
- if (Wrote > 0) {
- Done += Wrote;
- } else if (Wrote < 0 && errno == EINTR) {
- continue;
- } else {
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
- ::close(NewFD);
- return -1;
- }
- }
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
- ::close(NewFD);
- return -1;
- }
- SealTmpFD(NewFD);
- return NewFD;
+ return SealedFileOf(pathname, flags, Out);
}
int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
index b98ef4bda..b1ec241a7 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
@@ -35,6 +35,7 @@ private:
static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
+ static int32_t ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
const uint32_t ThreadsConfig;
};
+92
View File
@@ -0,0 +1,92 @@
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
#define HIGH ((uintptr_t)0x7e0000000000ULL)
#define ALIAS ((uintptr_t)0x7e0000100000ULL)
#define THREADS 4
#define ITERS 200000
static volatile uint64_t *counter;
static volatile uint64_t *cas;
static int fails;
static void check(const char *name, int ok) {
printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) fails++;
}
static void *worker(void *arg) {
(void)arg;
for (int i = 0; i < ITERS; i++) {
__atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST);
uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED);
while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {
}
}
return NULL;
}
int main(void) {
alarm(60);
uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (high == MAP_FAILED) {
printf("NOTCLAIMED errno=%d\n", errno);
return 0;
}
check("fixed-high-map", high == (uint8_t *)HIGH);
memset(high, 0x5a, 65536);
check("load-store", high[100] == 0x5a && high[65535] == 0x5a);
counter = (uint64_t *)(high + 64);
cas = (uint64_t *)(high + 128);
*counter = 0;
*cas = 0;
pthread_t t[THREADS];
for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL);
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
check("atomic-add", *counter == (uint64_t)THREADS * ITERS);
check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS);
int p[2];
check("pipe", pipe(p) == 0);
memcpy(high + 4096, "hello ", 6);
memcpy(high + 8192, "world", 5);
struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}};
ssize_t w = writev(p[1], out, 2);
memset(high + 12288, 0, 64);
struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}};
ssize_t r = w == 11 ? readv(p[0], in, 2) : -1;
check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0);
int wrote = write(p[1], "abcdef", 6) == 6;
check("write", wrote);
check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0);
high[30000] = 7;
check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0);
int fd = memfd_create("code", 0);
check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0);
static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3};
check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code);
uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS);
int (*fn)(void) = (int (*)(void))low;
int before = fn();
alias[1] = 2;
__atomic_thread_fence(__ATOMIC_SEQ_CST);
int after = fn();
printf("alias before=%d after=%d\n", before, after);
check("smc-through-high-alias", before == 1 && after == 2);
printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS");
return fails != 0;
}
@@ -664,7 +664,7 @@ def data_dir(env):
return DATA_DIR
def guest_environment(fex, env):
def guest_environment(fex, env, keep_compat=False):
result = dict(env)
data = data_dir(env)
for directory in (CONFIG_DIR, data, CACHE_DIR):
@@ -672,7 +672,7 @@ def guest_environment(fex, env):
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
result["FEX_APP_DATA_LOCATION"] = data + "/"
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
if result.get("STEAM_COMPAT_DATA_PATH"):
if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat:
short = data if data != DATA_DIR else "/tmp/fex"
os.makedirs(short, exist_ok=True)
result["STEAM_COMPAT_DATA_PATH"] = short
@@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder):
def required_runtime(program):
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
folder = os.path.dirname(program)
for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"):
match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "")
if match and match.group(1) in RUNTIMES:
return match.group(1)
return SNIPER_APPID
def resolve(program, env):
@@ -761,7 +764,7 @@ def resolve(program, env):
return shutil.which(program, path=env.get("PATH")) or program
def launch(command, env, mode, decide=None):
def launch(command, env, mode, decide=None, keep_compat=False):
program = resolve(command[0], env)
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
if not use:
@@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None):
fex = prepare(required_runtime(program))
if fex is None:
return 126
guest = guest_environment(fex, env)
guest = guest_environment(fex, env, keep_compat)
x86_64 = elf_arch(program) != "i386"
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
@@ -963,7 +966,7 @@ def parse_run(args):
def main(argv):
if not argv:
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status")
return 2
action, args = argv[0], list(argv[1:])
if action == "steam":
@@ -975,6 +978,10 @@ def main(argv):
if not command:
return 2
return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto"))
if action == "proton":
if len(args) < 2:
return 2
return launch(args, game_environment(dict(os.environ), args[2:] or args), "on", keep_compat=True)
if action == "run":
try:
mode, decide, command = parse_run(args)
@@ -996,6 +1003,10 @@ def main(argv):
return extract(args[0])
if action == "prepare":
return 0 if prepare() else 1
if action == "update":
with locked():
update_own_fex()
return 0
if action == "status":
with locked():
status = describe(fex_install(), runtime_platform(), graphics_platform())
@@ -29,10 +29,14 @@ fex_install() {
return 1
fi
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done > "$tmp/stale"
{
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done
f=usr/local/share/fex-emu/.droiddeck-patches
if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi
} > "$tmp/stale"
mkdir "$tmp/old"
while IFS= read -r f; do
f=${f#./}
@@ -318,12 +318,72 @@ dd_vacdiag() {
}
"""
DD_ANTICHEAT_SETUP = """
dd_anticheat_runtime() {
local current=$1 name=$2 bridge=$3 library
if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then
printf '%s' "$current"; return 0
fi
while IFS= read -r library; do
[ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue
printf '%s' "$library/steamapps/common/$name"; return 0
done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null)
return 1
}
dd_x86_64_proton() {
[ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ]
}
dd_anticheat() {
case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac
case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac
local game=${STEAM_COMPAT_INSTALL_PATH:-} found tool runtime
[ -d "$game" ] || return 0
found=$(find "$game" -maxdepth 3 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\
-o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print -quit 2>/dev/null)
[ -n "$found" ] || return 0
case ${DD_AC_TOOL:-DroidDeck-Proton} in
DroidDeck-Proton*) ;;
*)
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2
return 0
;;
esac
/usr/local/bin/droiddeck-fex update || true
if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2
return 0
fi
DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d"
done | sort -V | tail -n 1)
if [ -z "$tool" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2
return 0
fi
case ${found,,} in
*easyanticheat*) runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so) && export PROTON_EAC_RUNTIME="$runtime" ;;
*) runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so) && export PROTON_BATTLEYE_RUNTIME="$runtime" ;;
esac
if [ -z "$runtime" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2
return 0
fi
dd_game_cpus
declare -F dd_components >/dev/null && dd_components "$tool"
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@"
}
"""
# DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the
# newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set.
DD_BIONIC_PROOT_FALLBACK = """
if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then
dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue
v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d"
done | sort -V | tail -n 1 | cut -f 2-)
if [ -n "$dd_fallback" ]; then
@@ -461,6 +521,7 @@ for name in %s; do
[ -n "$depot" ] && break
done
if [ -n "$depot" ]; then
dd_anticheat "$@"
dd_components "$depot"
dd_directaudio "$depot" "$@"
dd_game_cpus
@@ -481,7 +542,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -516,6 +577,11 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
*) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;;
esac
fi
if dd_x86_64_proton "$here"; then
dd_game_cpus
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@"
fi
DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"
dd_components "$here"
dd_directaudio "$here" "$@"
dd_game_cpus
@@ -530,9 +596,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
@@ -1332,10 +1398,18 @@ def tool_catalog(steam_root, extras=None):
continue
extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry
for name, entry in sorted(extras.items()):
catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False))
tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False)
if x86_64_layout(os.path.join(tools, entry)):
tool["x86_64"] = True
catalog.append(tool)
return catalog
def x86_64_layout(path):
return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and
not os.path.isdir(os.path.join(path, "files", "bin-arm64")))
def built_from(name, catalog, runnable=None):
depot = VALVE_DEPOTS.get(name)
tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and
@@ -1474,7 +1548,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
def own_builds(tools):
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")]
def build_key(name):
@@ -1512,7 +1586,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app
wanted = requested_tool(request, catalog)
state["applied"] = seq
if wanted:
if wanted != state.get("default"):
if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any(
t["name"] == wanted and t.get("x86_64") for t in catalog)):
state.update(default=wanted, seq=now or now_ms(), source="app")
else:
print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % (
@@ -1709,7 +1784,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"):
automatic = state.get("source") not in ("app", "steam")
if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}:
default = newest or TOOL
state.update(default=default, seq=now_ms(), source="update")
elif settle and newest and default == TOOL and automatic:
default = newest
state.update(default=newest, seq=now_ms(), source="update")
state.pop("own_proton", None)
+2 -1
View File
@@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) {
__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0;
struct vdec *v = vd_find(fds[0].fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vd_lock);
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vd_lock);
+495 -10
View File
@@ -5,6 +5,7 @@
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -12,12 +13,17 @@
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#if defined(__i386__)
#include <asm/ldt.h>
#endif
#include <unistd.h>
#ifndef PR_SET_SYSCALL_USER_DISPATCH
#define PR_SET_SYSCALL_USER_DISPATCH 59
#endif
#ifndef MADV_PAGEOUT
#define MADV_PAGEOUT 21
#endif
@@ -36,7 +42,18 @@
#define ZR_INLINE_KB (32UL << 10)
#define ZR_INLINE_CHUNKS 512UL
#define ZR_FAILED (~0UL)
#define ZR_CANCELLED (-2L)
#define ZR_FUTEX_WAIT 0
#define ZR_PTRACE_DETACH 17
#define ZR_PTRACE_SEIZE 0x4206
#define ZR_PTRACE_INTERRUPT 0x4207
#define ZR_PTRACE_SETOPTIONS 0x4200
#define ZR_PTRACE_O_EXITKILL (1 << 20)
#define ZR_SPILL_CHUNK (8UL << 20)
#define ZR_SPILL_RUNS ((16UL << 20) / sizeof(struct zr_run))
#define ZR_SPILL_TIDS 8192
#define ZR_PARK_MS 3000
#define ZR_RESUME_POLL_MS 50
#define ZR_STACK (128UL << 10)
#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \
CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID)
@@ -202,6 +219,23 @@ static struct zr_slot {
static uint16_t zr_gen = 1;
static unsigned long zr_cursor;
static unsigned long zr_visits;
static struct zr_run {
unsigned long addr, len, off, writable;
} *zr_runs;
static char *zr_bounce;
static unsigned long zr_run_count;
static long zr_owner;
static long zr_reaper;
static int zr_seized;
static int zr_tids[ZR_SPILL_TIDS];
static signed char zr_stopped[ZR_SPILL_TIDS];
static unsigned char zr_signals[ZR_SPILL_TIDS];
static char *zr_helper_stack;
static int zr_helper_done;
static int zr_helper_discarded;
static int zr_helper_released;
static unsigned long zr_helper_spilled;
static unsigned long zr_baseline; // the resume count the spill was asked under
static int zr_prefix(const char *text, const char *prefix) {
while (*prefix)
@@ -209,6 +243,11 @@ static int zr_prefix(const char *text, const char *prefix) {
return 1;
}
// A named mapping never merges with the game's anonymous memory, so excluding it from a spill excludes only it.
static void zr_name(long addr, unsigned long len) {
zr_sys(SYS_prctl, 0x53564d41, 0, addr, len, "dd-zram");
}
static char *zr_find(char *text, char c, size_t n) {
for (; n > 0; n--, text++)
if (*text == c) return text;
@@ -217,11 +256,15 @@ static char *zr_find(char *text, char c, size_t n) {
static char zr_ctl[ZR_PATH] = ZR_CTL;
static char zr_hold[ZR_PATH + sizeof(".hold")];
static char zr_resume[ZR_PATH + sizeof(".resume")];
static int zr_open(const char *path) {
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
}
// The number after a request's mode: kB to trim, or for a spill the resume count it was asked under.
static unsigned long zr_request_arg;
static int zr_mode(unsigned long *want) {
char text[24];
long n = 0;
@@ -236,12 +279,13 @@ static int zr_mode(unsigned long *want) {
n = zr_sys(SYS_read, fd, text, sizeof(text));
zr_sys(SYS_close, fd);
}
if (n < 1 || text[0] < '0' || text[0] > '3') return -1;
if (n < 1 || text[0] < '0' || text[0] > '4') return -1;
unsigned long kb = 0;
for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++)
kb = kb * 10 + (unsigned long)(text[i] - '0');
zr_request_arg = kb;
*want = kb / (zr_page / 1024);
if (text[0] >= '2' && *want == 0) return -1;
if ((text[0] == '2' || text[0] == '3') && *want == 0) return -1;
return text[0] - '0';
}
@@ -416,42 +460,445 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
return done;
}
static void zr_ack(long value, int trim) {
const char *suffix = trim ? ".trim." : ".ack.";
char path[sizeof(zr_ctl) + sizeof(".trim.") + 20];
static void zr_ack(long value, const char *suffix) {
char path[sizeof(zr_ctl) + sizeof(".restored.") + 20];
char digits[20];
size_t n = 0, d = 0;
for (const char *p = zr_ctl; *p; p++) path[n++] = *p;
for (const char *p = suffix; *p; p++) path[n++] = *p;
long pid = zr_sys(SYS_getpid);
long pid = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
if (pid == 0) pid = zr_sys(SYS_getpid);
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
while (d > 0) path[n++] = digits[--d];
path[n] = 0;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) return;
n = 0;
if (value < -1) {
path[n++] = '-';
value = -value;
}
for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10);
for (n = 0; d > 0;) path[n++] = digits[--d];
while (d > 0) path[n++] = digits[--d];
if (n > 0) zr_sys(SYS_write, fd, path, n);
zr_sys(SYS_close, fd);
}
#if defined(__aarch64__)
static int zr_read_small(const char *path, char *text, long size) {
int fd = zr_open(path);
if (fd < 0) return 0;
long n;
do n = zr_sys(SYS_read, fd, text, size); while (n == -EINTR);
zr_sys(SYS_close, fd);
return n > 0 ? (int)n : 0;
}
static void zr_nap(int *word, int value, long ms) {
struct { long sec, nsec; } wait = {ms / 1000, ms % 1000 * 1000000};
zr_sys(SYS_futex, word, ZR_FUTEX_WAIT, value, &wait, NULL, 0);
}
static long zr_now_ms(void) {
struct { long sec, nsec; } now = {0, 0};
zr_sys(SYS_clock_gettime, CLOCK_MONOTONIC, &now);
return now.sec * 1000 + now.nsec / 1000000;
}
static size_t zr_digits(char *out, long value) {
char digits[20];
size_t d = 0, n = 0;
do digits[d++] = (char)('0' + value % 10); while ((value /= 10) > 0);
while (d > 0) out[n++] = digits[--d];
return n;
}
static int zr_seized_index(long tid) {
for (int i = 0; i < zr_seized; i++)
if (zr_tids[i] == tid) return i;
return -1;
}
// Seizes and interrupts the owner's threads it has not seized yet; returns how many it added, or -1.
static long zr_seize_new(void) {
char path[48] = "/proc/";
size_t n = 6 + zr_digits(path + 6, zr_owner);
for (const char *p = "/task"; *p; p++) path[n++] = *p;
path[n] = 0;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0);
if (fd < 0) return -1;
long added = 0, got;
while ((got = zr_sys(SYS_getdents64, fd, zr_maps, sizeof(zr_maps))) > 0) {
for (long at = 0; at < got;) {
unsigned short reclen = *(unsigned short *)(zr_maps + at + 16);
const char *name = zr_maps + at + 19;
at += reclen;
long tid = 0;
for (const char *p = name; *p >= '0' && *p <= '9'; p++) tid = tid * 10 + (*p - '0');
if (tid <= 0 || tid == zr_reaper || zr_seized_index(tid) >= 0) continue;
if (zr_seized == ZR_SPILL_TIDS) {
added = -1;
break;
}
long r = zr_sys(SYS_ptrace, ZR_PTRACE_SEIZE, tid, 0, 0);
if (r == -ESRCH) continue;
if (r < 0) {
added = -1;
break;
}
zr_tids[zr_seized] = (int)tid;
zr_signals[zr_seized] = 0;
zr_stopped[zr_seized++] = 0;
zr_sys(SYS_ptrace, ZR_PTRACE_INTERRUPT, tid, 0, 0);
added++;
}
if (added < 0) break;
}
zr_sys(SYS_close, fd);
return got < 0 ? -1 : added;
}
static void zr_detach_all(void) {
for (int i = 0; i < zr_seized; i++)
if (zr_stopped[i] >= 0) zr_sys(SYS_ptrace, ZR_PTRACE_DETACH, zr_tids[i], 0, zr_signals[i]);
zr_seized = 0;
}
// A thread stopped by ptrace stays stopped whatever its signal mask, and SIGCONT does not start it again:
// only the detach after the restore does.
static int zr_seize_all(void) {
zr_seized = 0;
long start = zr_now_ms(), added;
int idle = 0;
do {
added = zr_seize_new();
if (added < 0) return 0;
for (;;) {
int status, waiting = 0;
long tid;
while ((tid = zr_sys(SYS_wait4, -1, &status, __WALL | WNOHANG, NULL)) > 0) {
int i = zr_seized_index(tid);
if (i < 0) continue;
zr_stopped[i] = WIFSTOPPED(status) ? 1 : -1;
// A signal that reached the thread before the interrupt stops it in that signal's delivery, which a
// detach without the signal would drop.
if (WIFSTOPPED(status) && (status >> 16) == 0) zr_signals[i] = (unsigned char)WSTOPSIG(status);
}
for (int i = 0; i < zr_seized; i++) waiting += zr_stopped[i] == 0;
if (waiting == 0) break;
if (zr_now_ms() - start >= ZR_PARK_MS) return 0;
zr_nap(&idle, 0, 2);
}
} while (added > 0);
return 1;
}
// The spill must not drop the memory it runs on: the stacks, this file's state and the run index.
static int zr_own(unsigned long start, unsigned long end) {
const unsigned long marks[] = {
(unsigned long)zr_slots, (unsigned long)&zr_owner, (unsigned long)zr_maps, (unsigned long)zr_entries,
(unsigned long)zr_tids, (unsigned long)zr_stack, (unsigned long)zr_runs, (unsigned long)zr_helper_stack,
(unsigned long)zr_bounce,
};
for (unsigned long i = 0; i < sizeof(marks) / sizeof(marks[0]); i++)
if (marks[i] >= start && marks[i] < end) return 1;
return 0;
}
static int zr_flag(const char *flags, char a, char b) {
for (const char *p = flags; p[0] && p[1]; p++)
if (p[0] == a && p[1] == b && (p == flags || p[-1] == ' ') && (p[2] == ' ' || p[2] == 0 || p[2] == '\n'))
return 1;
return 0;
}
// Private anonymous memory that can be read, whatever else its protection allows now.
static int zr_spillable(const char *line, unsigned long *start, unsigned long *end, int *writable) {
const char *p = line;
*start = zr_hex(&p);
if (*p++ != '-') return 0;
*end = zr_hex(&p);
if (*p++ != ' ' || p[0] != 'r' || p[3] != 'p') return 0;
*writable = p[1] == 'w';
for (int field = 0; field < 4; field++) {
while (*p && *p != ' ') p++;
while (*p == ' ') p++;
}
return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[stack]") || zr_prefix(p, "[anon:");
}
static long zr_io(long call, int fd, unsigned long addr, unsigned long len, unsigned long off, int *direct) {
unsigned long done = 0;
while (done < len) {
unsigned long step = len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : len - done;
long n = zr_sys(call, fd, addr + done, step, off + done);
if (n == -EINTR) continue;
if (n == -EINVAL && *direct) {
long flags = zr_sys(SYS_fcntl, fd, F_GETFL);
if (flags < 0 || zr_sys(SYS_fcntl, fd, F_SETFL, flags & ~O_DIRECT) < 0) return -1;
*direct = 0;
continue;
}
if (n <= 0) return -1;
// f2fs on an encrypted volume may serve O_DIRECT through the page cache without saying so.
if (call == SYS_pwrite64) zr_sys(SYS_sync_file_range, fd, off + done, n, 7);
zr_sys(SYS_fadvise64, fd, off + done, n, 4);
done += (unsigned long)n;
}
return 0;
}
// Pages that cannot be written in place go back through /proc/<pid>/mem, which the tracer may write.
static int zr_restore_run(int fd, int mem, const struct zr_run *run, int *direct) {
if (run->writable) return (int)zr_io(SYS_pread64, fd, run->addr, run->len, run->off, direct);
for (unsigned long done = 0; done < run->len; done += ZR_SPILL_CHUNK) {
unsigned long step = run->len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : run->len - done;
if (mem < 0 || zr_io(SYS_pread64, fd, (unsigned long)zr_bounce, step, run->off + done, direct) < 0) return -1;
for (unsigned long put = 0; put < step;) {
long n = zr_sys(SYS_pwrite64, mem, zr_bounce + put, step - put, run->addr + done + put);
if (n == -EINTR) continue;
if (n <= 0) return -1;
put += (unsigned long)n;
}
}
return 0;
}
static unsigned long zr_spill_range(int pagemap, int fd, unsigned long start, unsigned long end, int writable,
unsigned long *off, int *direct, int *full) {
unsigned long spilled = 0;
for (unsigned long addr = start; addr < end && !*full;) {
unsigned long count = (end - addr) / zr_page;
if (count > ZR_BATCH) count = ZR_BATCH;
if (zr_sys(SYS_lseek, pagemap, (long)(addr / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return spilled;
long got = zr_sys(SYS_read, pagemap, zr_entries, count * sizeof(uint64_t));
if (got < (long)sizeof(uint64_t)) return spilled;
unsigned long pages = (unsigned long)got / sizeof(uint64_t);
for (unsigned long i = 0; i < pages && !*full;) {
if (!(zr_entries[i] & (ZR_PRESENT | ZR_SWAPPED))) {
i++;
continue;
}
unsigned long j = i;
while (j < pages && (zr_entries[j] & (ZR_PRESENT | ZR_SWAPPED))) j++;
unsigned long from = addr + i * zr_page, len = (j - i) * zr_page;
if (zr_run_count == ZR_SPILL_RUNS || zr_io(SYS_pwrite64, fd, from, len, *off, direct) < 0) {
*full = 1;
break;
}
zr_helper_discarded = 1;
if (zr_sys(SYS_madvise, from, len, MADV_DONTNEED) == 0) {
zr_runs[zr_run_count++] = (struct zr_run){from, len, *off, (unsigned long)writable};
*off += len;
spilled += len;
}
i = j;
}
addr += pages * zr_page;
}
return spilled;
}
static unsigned long zr_spill_all(int fd, int *direct) {
int smaps = zr_open("/proc/self/smaps");
int pagemap = zr_open("/proc/self/pagemap");
unsigned long spilled = 0, off = 0, s = 0, e = 0;
int take = 0, full = 0, writable = 0;
size_t have = 0;
while (smaps >= 0 && pagemap >= 0 && !full) {
long n = zr_sys(SYS_read, smaps, zr_maps + have, sizeof(zr_maps) - 1 - have);
if (n == -EINTR) continue;
if (n <= 0) break;
have += (size_t)n;
zr_maps[have] = 0;
char *line = zr_maps, *nl;
while (!full && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
*nl = 0;
if ((line[0] >= '0' && line[0] <= '9') || (line[0] >= 'a' && line[0] <= 'f')) {
take = zr_spillable(line, &s, &e, &writable) && e > s && !zr_own(s, e);
} else if (take && zr_prefix(line, "VmFlags:")) {
const char *flags = line + 8;
// Tagged memory (mt) stays: dropping its pages drops the tags, which reading the bytes back cannot restore.
if (!zr_flag(flags, 'u', 'm') && !zr_flag(flags, 'u', 'w') && !zr_flag(flags, 'l', 'o') &&
!zr_flag(flags, 'i', 'o') && !zr_flag(flags, 'p', 'f') && !zr_flag(flags, 'm', 't'))
spilled += zr_spill_range(pagemap, fd, s, e, writable, &off, direct, &full);
take = 0;
}
line = nl + 1;
}
have -= (size_t)(line - zr_maps);
for (size_t i = 0; i < have; i++) zr_maps[i] = line[i];
if (have == sizeof(zr_maps) - 1) have = 0;
}
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
if (smaps >= 0) zr_sys(SYS_close, smaps);
return spilled;
}
static int zr_spill_file(void) {
char path[sizeof(zr_ctl) + sizeof(".spill.") + 20];
char digits[20];
size_t n = 0, d = 0;
for (const char *p = zr_ctl; *p; p++) path[n++] = *p;
for (const char *p = ".spill."; *p; p++) path[n++] = *p;
long pid = zr_sys(SYS_getpid);
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
while (d > 0) path[n++] = digits[--d];
path[n] = 0;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_DIRECT, 0600);
if (fd >= 0 && zr_sys(SYS_unlinkat, AT_FDCWD, path, 0) < 0) {
zr_sys(SYS_close, fd);
return -1;
}
return fd;
}
// A count other than the request's; a marker that cannot be read is no resume.
static int zr_resumed(void) {
char now[24];
int got = zr_read_small(zr_resume, now, sizeof(now));
unsigned long count = 0;
int digits = 0;
for (int i = 0; i < got && now[i] >= '0' && now[i] <= '9'; i++, digits++) count = count * 10 + (unsigned long)(now[i] - '0');
return digits > 0 && count != zr_baseline;
}
// Runs in a process that shares the owner's memory, so it keeps running while every owner thread is stopped.
// Once pages are dropped, the owner must not outlive a helper that ends without detaching: the kernel kills
// every thread still traced when its tracer exits. Only a stopped tracee takes options, which all are here.
static int zr_exit_kill(void) {
for (int i = 0; i < zr_seized; i++) {
if (zr_stopped[i] <= 0) continue;
long r = zr_sys(SYS_ptrace, ZR_PTRACE_SETOPTIONS, zr_tids[i], 0, ZR_PTRACE_O_EXITKILL);
if (r < 0 && r != -ESRCH) return 0;
}
return 1;
}
static void zr_helper(void) {
zr_sys(SYS_prctl, PR_SET_NAME, "zr-spill");
if (!zr_seize_all() || zr_resumed() || !zr_exit_kill()) {
zr_detach_all();
return;
}
int fd = zr_spill_file();
if (fd < 0) {
zr_detach_all();
return;
}
int direct = 1, idle = 0;
zr_run_count = 0;
unsigned long spilled = zr_spill_all(fd, &direct);
zr_helper_spilled = spilled;
zr_helper_done = 1;
// nothing written (a full volume): the owner pages out to zram instead and acknowledges that
if (spilled > 0) {
zr_ack((long)(spilled / 1024), ".ack.");
while (!zr_resumed()) {
// reparented: the owner is gone and there is nothing to read back into
if (zr_sys(SYS_getppid) != zr_owner) {
zr_sys(SYS_close, fd);
return;
}
zr_nap(&idle, 0, ZR_RESUME_POLL_MS);
}
long start = zr_now_ms();
char path[48] = "/proc/";
size_t n = 6 + zr_digits(path + 6, zr_owner);
for (const char *p = "/mem"; *p; p++) path[n++] = *p;
path[n] = 0;
int mem = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CLOEXEC, 0);
int restored = 1;
for (unsigned long i = 0; i < zr_run_count; i++) {
if (zr_restore_run(fd, mem, &zr_runs[i], &direct) < 0) {
zr_sys(SYS_kill, zr_owner, SIGKILL);
restored = 0;
}
}
if (mem >= 0) zr_sys(SYS_close, mem);
zr_sys(SYS_close, fd);
zr_helper_released = restored;
zr_detach_all();
// after the detach, so a controller that sees the marker finds the process out of its tracing stop
if (restored) zr_ack(zr_now_ms() - start, ".restored.");
return;
}
zr_helper_released = 1;
zr_sys(SYS_close, fd);
zr_detach_all();
}
static void *zr_area(unsigned long len) {
long area = zr_sys(ZR_MMAP, 0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if ((unsigned long)area > -4096UL) return NULL;
zr_name(area, len);
return (void *)area;
}
static int zr_spill(void) {
if (zr_runs == NULL) zr_runs = zr_area(ZR_SPILL_RUNS * sizeof(struct zr_run));
if (zr_helper_stack == NULL) zr_helper_stack = zr_area(ZR_STACK);
if (zr_bounce == NULL) zr_bounce = zr_area(ZR_SPILL_CHUNK);
if (zr_runs == NULL || zr_helper_stack == NULL || zr_bounce == NULL) return 0;
zr_baseline = zr_request_arg;
zr_helper_done = 0;
zr_helper_spilled = 0;
zr_helper_discarded = 0;
zr_helper_released = 0;
zr_reaper = zr_sys(SYS_gettid);
__atomic_store_n(&zr_owner, zr_sys(SYS_getpid), __ATOMIC_RELEASE);
long child = zr_clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM, zr_helper_stack + ZR_STACK, NULL, NULL, NULL);
if (child > 0) {
int status;
while (zr_sys(SYS_wait4, child, &status, __WALL, NULL) == -EINTR) {
}
// A helper that ended between dropping pages and reading them back took them with it.
if (zr_helper_discarded && !zr_helper_released) zr_sys(SYS_kill, zr_sys(SYS_getpid), SIGKILL);
}
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
return child > 0 && zr_helper_done && zr_helper_spilled > 0;
}
#endif
static void zr_request(int worker) {
unsigned long want = 0;
int mode = zr_mode(&want);
if (mode < 0) return;
if (mode == 4) {
// A request that reaches this after the resume it was asked before has nothing left to do: the
// controller no longer waits for it, and holding the process now would stop it after the resume.
#if defined(__aarch64__)
zr_baseline = zr_request_arg;
if (zr_resumed()) return;
#endif
zr_ack(-1, ".ack.");
#if defined(__aarch64__)
if (worker && zr_spill()) return;
// it acknowledged the start, so the controller waits for a final answer
if (zr_resumed()) {
zr_ack(ZR_CANCELLED, ".ack.");
return;
}
#endif
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
zr_walk(1, 1, 0, 0);
zr_gen++;
zr_ack(0, ".ack.");
return;
}
if (!worker && want > ZR_INLINE_KB / (zr_page / 1024)) want = ZR_INLINE_KB / (zr_page / 1024);
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
if (mode > 0) zr_ack(-1, mode > 1);
if (mode > 0) zr_ack(-1, mode > 1 ? ".trim." : ".ack.");
if (mode < 2) {
zr_walk(mode, 1, 0, 0);
zr_gen++;
if (mode == 1) zr_ack(1, 0);
if (mode == 1) zr_ack(1, ".ack.");
return;
}
unsigned long from = zr_cursor;
unsigned long done = zr_walk(mode, want, from, ~0UL);
if (done < want && from > 0) done += zr_walk(mode, want - done, 0, from);
zr_ack((long)(done * (zr_page / 1024)), 1);
zr_ack((long)(done * (zr_page / 1024)), ".trim.");
}
static void zr_drain(int worker) {
@@ -463,6 +910,13 @@ static void zr_drain(int worker) {
}
void zr_thread(void) {
#if defined(__aarch64__)
long owner = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
if (owner != 0 && zr_sys(SYS_getpid) != owner) {
zr_helper();
return;
}
#endif
zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker");
zr_drain(1);
}
@@ -520,6 +974,7 @@ static int zr_start(void) {
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
if ((unsigned long)base > -4096UL) return 0;
zr_stack = (char *)base;
zr_name(base, ZR_STACK);
}
struct { long sec, nsec; } wait = {0, 5000000};
for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++)
@@ -538,16 +993,44 @@ static int zr_start(void) {
return 0;
}
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
int prctl(int option, ...) {
va_list ap;
va_start(ap, option);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
va_end(ap);
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
if (selector) *dispatch = selector;
if ((unsigned long)result > -4096UL) {
errno = (int)-result;
return -1;
}
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
return (int)result;
}
static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
int saved = errno;
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
errno = saved;
if (selector) *dispatch = selector;
}
static void zr_child(void) {
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
}
@@ -564,6 +1047,8 @@ static void zr_paths(void) {
size_t n = strlen(zr_ctl);
memcpy(zr_hold, zr_ctl, n);
memcpy(zr_hold + n, ".hold", sizeof(".hold"));
memcpy(zr_resume, zr_ctl, n);
memcpy(zr_resume + n, ".resume", sizeof(".resume"));
}
__attribute__((constructor)) static void zr_init(void) {
+1
View File
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ENOSYS;
return -1;
}
if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe;
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),
+4 -2
View File
@@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s
if (ret <= 0 || out == buf) return ret;
size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz;
memcpy(buf, out, n);
if (n < bufsiz) buf[n] = '\0';
return (ssize_t)n;
}
@@ -454,6 +455,7 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL;
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
const char *given = pathname;
DDNATV_AT_REMAP(dirfd, pathname);
// after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well
{
@@ -478,7 +480,7 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz);
}
return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz));
return copy_readlink_result(buf, bufsiz, out, postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, out, ret, outsiz));
}
// Fortified readlink variants used by dpkg / update-alternatives
@@ -776,7 +778,7 @@ char *realpath(const char *path, char *resolved_path) {
char pbuf[PATH_MAX];
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL;
if (res && g_ddnatv_root[0] != '\0') {
if (res && g_ddnatv_root[0] != '\0' && !is_rootfs_real_path(path)) {
size_t rlen = g_ddnatv_root_len;
if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) {
size_t rem_len = strlen(res + rlen);
+121 -5
View File
@@ -197,6 +197,116 @@ static int open_proc_status_at(int dirfd, const char *name, int flags) {
return open_proc_status(dir, flags);
}
static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6);
#ifndef F_SEAL_EXEC
#define F_SEAL_EXEC 0x0020
#endif
#ifndef MFD_EXEC
#define MFD_EXEC 0x0010U
#endif
static int own_fd_of_path(const char *path) {
if (!path) return -1;
const char *p;
if (strncmp(path, "/dev/fd/", 8) == 0) {
p = path + 8;
} else {
if (!is_proc_fd_link(path)) return -1;
const char *who = path + 6;
if (*who >= '0' && *who <= '9') {
long pid = 0;
while (*who >= '0' && *who <= '9') pid = pid * 10 + (*who++ - '0');
if (pid != (long)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0)) {
char task[48];
snprintf(task, sizeof(task), "/proc/self/task/%ld", pid);
if (call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)task, F_OK, 0, 0, 0) != 0) return -1;
}
}
p = strstr(path + 6, "/fd/") + 4;
}
if (*p < '0' || *p > '9') return -1;
long fd = 0;
while (*p >= '0' && *p <= '9') {
fd = fd * 10 + (*p++ - '0');
if (fd > INT_MAX) return -1;
}
return *p == '\0' ? (int)fd : -1;
}
static int copy_memfd_contents(int from, int to, off_t size) {
char chunk[32768];
off_t at = 0;
while (at < size) {
size_t want = (size_t)(size - at) < sizeof(chunk) ? (size_t)(size - at) : sizeof(chunk);
long got = call_orig_syscall(SYS_pread64, (unsigned long)from, (unsigned long)chunk, want, (unsigned long)at, 0, 0);
if (got < 0 && errno == EINTR) continue;
if (got <= 0) return -1;
long done = 0;
while (done < got) {
long put = call_orig_syscall(SYS_write, (unsigned long)to, (unsigned long)(chunk + done), (unsigned long)(got - done), 0, 0, 0);
if (put < 0 && errno == EINTR) continue;
if (put <= 0) return -1;
done += put;
}
at += got;
}
return 0;
}
static int copy_of_memfd(int src, int flags) {
char link[48], target[PATH_MAX];
snprintf(link, sizeof(link), "/proc/thread-self/fd/%d", src);
long n = call_orig_syscall(SYS_readlinkat, (unsigned long)AT_FDCWD, (unsigned long)link, (unsigned long)target, sizeof(target) - 1, 0, 0);
if (n <= 7 || strncmp(target, "/memfd:", 7) != 0) return -1;
target[n] = '\0';
char *name = target + 7;
size_t name_len = (size_t)n - 7;
if (name_len >= 10 && strcmp(name + name_len - 10, " (deleted)") == 0) name[name_len -= 10] = '\0';
if (name_len > 249) name[249] = '\0';
struct stat st;
if (call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) return -1;
long seals = call_orig_syscall(SYS_fcntl, (unsigned long)src, F_GET_SEALS, 0, 0, 0, 0);
if (seals < 0) return -1;
unsigned long mfd_flags = MFD_ALLOW_SEALING | ((flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
long copy = -1;
if (st.st_mode & 0111) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags | MFD_EXEC, 0, 0, 0, 0);
if (copy < 0) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags, 0, 0, 0, 0);
if (copy < 0) return -1;
int ok = copy_memfd_contents(src, (int)copy, st.st_size) == 0 &&
call_orig_syscall(SYS_lseek, (unsigned long)copy, 0, SEEK_SET, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fchmod, (unsigned long)copy, st.st_mode & 07777, 0, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fcntl, (unsigned long)copy, F_ADD_SEALS, (unsigned long)(seals | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK), 0, 0, 0) == 0;
if (!ok) {
call_orig_syscall(SYS_close, (unsigned long)copy, 0, 0, 0, 0, 0);
return -1;
}
return (int)copy;
}
static int reopen_denied_memfd(const char *path, int flags) {
if ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT | O_TRUNC | O_DIRECTORY | O_PATH))) return -1;
int named = own_fd_of_path(path);
if (named < 0) return -1;
long src = call_orig_syscall(SYS_fcntl, (unsigned long)named, F_DUPFD_CLOEXEC, 0, 0, 0, 0);
if (src < 0) return -1;
struct stat by_path, by_fd;
int same = call_orig_syscall(SYS_newfstatat, (unsigned long)AT_FDCWD, (unsigned long)path, (unsigned long)&by_path, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&by_fd, 0, 0, 0, 0) == 0 &&
by_path.st_dev == by_fd.st_dev && by_path.st_ino == by_fd.st_ino;
int copy = same ? copy_of_memfd((int)src, flags) : -1;
call_orig_syscall(SYS_close, (unsigned long)src, 0, 0, 0, 0, 0);
return copy;
}
static int open_or_reopen_memfd(int fd, const char *path, int flags) {
if (fd >= 0 || errno != EACCES) return fd;
int copy = reopen_denied_memfd(path, flags);
if (copy >= 0) return copy;
errno = EACCES;
return -1;
}
// Hook open
int open(const char *pathname, int flags, ...) {
static int (*orig_open)(const char *, int, ...) = NULL;
@@ -225,7 +335,7 @@ int open(const char *pathname, int flags, ...) {
forget_proc_root_fd(fd);
return fd;
}
int fd = orig_open(target, flags);
int fd = open_or_reopen_memfd(orig_open(target, flags), pathname, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
@@ -259,7 +369,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
forget_proc_root_fd(fd);
return fd;
}
int fd = orig_openat(dirfd, target, flags);
int fd = open_or_reopen_memfd(orig_openat(dirfd, target, flags), (pathname && pathname[0] == '/') ? pathname : NULL, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
@@ -304,6 +414,11 @@ static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, u
return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6);
}
static int openat2_or_reopen_memfd(int fd, const char *pathname, const struct ddnatv_open_how *how) {
if (fd >= 0 || errno != EACCES || pathname[0] != '/' || !how || how->resolve) return fd;
return open_or_reopen_memfd(fd, pathname, (int)how->flags);
}
// Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal).
// Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels
// without openat2, e.g. Android < 5.6) emulates with plain openat instead of
@@ -334,12 +449,12 @@ int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_openat2) {
int ret = orig_openat2(dirfd, target, how, usize);
if (ret >= 0 || errno != ENOSYS) return ret;
if (ret >= 0 || errno != ENOSYS) return openat2_or_reopen_memfd(ret, pathname, how);
}
#ifdef __NR_openat2
long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0);
if (sret >= 0 || errno != ENOSYS) {
return (int)sret;
return openat2_or_reopen_memfd((int)sret, pathname, how);
}
#endif
if (!how || usize < 16) {
@@ -646,6 +761,7 @@ int lstat(const char *pathname, struct stat *statbuf) {
int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
const char *given = pathname;
DDNATV_AT_REMAP(dirfd, pathname);
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? ((flags & AT_SYMLINK_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
@@ -665,7 +781,7 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1;
if (llen > 0) {
ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf));
ssize_t post_len = postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, link_buf, llen, sizeof(link_buf));
if (post_len > 0) {
statbuf->st_size = post_len;
}
+30 -2
View File
@@ -952,6 +952,30 @@ static int is_proc_fd_link(const char *path) {
return *p == '\0';
}
static int is_proc_cwd_link(const char *path) {
if (!path || strncmp(path, "/proc/", 6) != 0) return 0;
const char *p = path + 6;
if (strncmp(p, "self/", 5) == 0) {
p += 5;
} else if (strncmp(p, "thread-self/", 12) == 0) {
p += 12;
} else {
if (*p < '0' || *p > '9') return 0;
while (*p >= '0' && *p <= '9') p++;
if (*p != '/') return 0;
p++;
}
return strcmp(p, "cwd") == 0;
}
static int is_rootfs_real_path(const char *path) {
return path && g_ddnatv_root_len > 0 && is_path_prefix(path, g_ddnatv_root, g_ddnatv_root_len);
}
static int link_answers_in_kernel_form(const char *linkpath, const char *named) {
return is_proc_fd_link(linkpath) || is_proc_cwd_link(linkpath) || is_rootfs_real_path(named);
}
// The guest path of a folder that a session mount puts outside the rootfs, for what the kernel
// reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for
// Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit.
@@ -989,7 +1013,7 @@ static char *guest_path_of_allocated_mount_source(char *res) {
return grown;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
static ssize_t postprocess_named_readlink(const char *linkpath, const char *named, char *buf, ssize_t ret, size_t bufsiz) {
if (ret <= 0) return ret;
if ((size_t)ret < bufsiz) {
buf[ret] = '\0';
@@ -998,7 +1022,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL);
// 1. Strip g_ddnatv_root if target starts with it
if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) {
if (g_ddnatv_root_len > 0 && !link_answers_in_kernel_form(linkpath, named)) {
size_t rlen = g_ddnatv_root_len;
if ((size_t)ret >= rlen && memcmp(buf, g_ddnatv_root, rlen) == 0 &&
((size_t)ret == rlen || buf[rlen] == '/')) {
@@ -1053,6 +1077,10 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
return ret;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
return postprocess_named_readlink(linkpath, linkpath, buf, ret, bufsiz);
}
// Android's SELinux label, which the xattr hooks keep away from Ubuntu programs.
static const char k_selinux_xattr[] = "security.selinux";
+13
View File
@@ -668,6 +668,19 @@ long syscall(long number, ...) {
}
#endif
#ifdef __NR_execve
if (number == __NR_execve) {
return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3);
}
#endif
#ifdef __NR_execveat
if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' &&
(((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) {
return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4);
}
#endif
#ifdef __NR_clone3
if (number == __NR_clone3) {
errno = ENOSYS;
+1
View File
@@ -307,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
size_t len = strlen(out_path);
size_t copy_len = (len < bufsiz) ? len : bufsiz;
memcpy(buf, out_path, copy_len);
if (copy_len < bufsiz) buf[copy_len] = '\0';
return (ssize_t)copy_len;
}
+13 -6
View File
@@ -10,6 +10,12 @@
#define SYS_SECCOMP 1
#endif
#if defined(__aarch64__)
#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U
#else
#define DDNATV_HOST_AUDIT_ARCH 0x40000028U
#endif
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *);
// A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's
@@ -57,7 +63,13 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va
// 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;
if (info->si_code != SYS_SECCOMP) {
int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH;
if (!host_trap && g_app_sigsys_set) {
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
else g_app_sigsys.sa_handler(sig);
return;
}
if (!host_trap) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (real_sig) {
struct sigaction sa_dfl;
@@ -69,11 +81,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
raise(sig);
return;
}
if (info->si_errno != 0 && g_app_sigsys_set) {
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
else g_app_sigsys.sa_handler(sig);
return;
}
ucontext_t *uctx = (ucontext_t *)ctx;
int sys_nr = info->si_syscall;
+223
View File
@@ -0,0 +1,223 @@
import json
import os
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility")
SETUP = COMPAT["DD_ANTICHEAT_SETUP"]
class AntiCheatRoutingTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / "Steam"
self.common = self.steam / "steamapps" / "common"
self.tools = self.steam / "compatibilitytools.d"
self.game = self.common / "Some Game"
self.game.mkdir(parents=True)
self.tools.mkdir(parents=True)
self.record = self.root / "record.json"
self.fex = self.root / "droiddeck-fex"
self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; "
"[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n"
"python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], "
"\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, "
"open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n")
self.fex.chmod(0o755)
self.patches = self.root / "fex-patches"
self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n")
def tool(self, name, x86_64=True):
tool = self.tools / name
(tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True)
if not x86_64:
(tool / "files" / "bin-arm64").mkdir()
(tool / "proton").write_text("#!/bin/sh\n")
(tool / "proton").chmod(0o755)
return tool
def runtime(self, name, library):
folder = self.common / name / "v2" / "lib64"
folder.mkdir(parents=True)
(folder / library).write_text("")
return self.common / name
def file(self, relative):
path = self.game / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("{}")
def launch(self, verb="waitforexitandrun", extra=None):
script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace(
"/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + (
"dd_game_cpus() { :; }\n"
"verb=$1; shift\n"
"dd_anticheat \"$@\"\n"
"echo stayed\n")
env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches),
"STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)}
env.update(extra or {})
result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")],
env=env, capture_output=True, text=True, timeout=30)
routed = json.loads(self.record.read_text()) if self.record.exists() else None
return result, routed
def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
newest = self.tool("DroidDeck-Proton-11.0-10-x86_64")
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertNotIn("stayed", result.stdout)
self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")])
self.assertEqual(routed["eac"], str(runtime))
self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr)
def test_battleye_sets_its_own_runtime(self):
self.file("BattlEye/BEClient_x64.so")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
_, routed = self.launch()
self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None))
def test_a_runtime_already_set_with_files_is_kept(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
own = self.root / "own-eac"
(own / "v2").mkdir(parents=True)
(own / "v2" / "easyanticheat_x64.so").write_text("")
_, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)})
self.assertEqual(routed["eac"], str(own))
def test_games_without_anti_cheat_files_stay_on_arm64(self):
self.file("Data/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertEqual(result.stderr, "")
def test_without_an_x86_64_build_the_launch_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr)
def test_without_the_runtime_files_the_launch_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
(self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True)
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("its Proton runtime is not installed", result.stderr)
def test_the_user_can_turn_routing_off(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
def test_a_tool_the_user_chose_is_kept(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"):
result, routed = self.launch(extra={"DD_AC_TOOL": chosen})
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr)
def test_droiddeck_proton_builds_still_route(self):
self.file("EasyAntiCheat/Settings.json")
newest = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"):
self.record.unlink(missing_ok=True)
result, routed = self.launch(extra={"DD_AC_TOOL": own})
self.assertEqual(routed["argv"][1], str(newest / "proton"))
def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for patches in ("openat2-enosys-fallback\n", None):
if patches is None:
self.patches.unlink()
else:
self.patches.write_text(patches)
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr)
def test_an_older_fex_build_is_updated_before_routing(self):
self.file("EasyAntiCheat/Settings.json")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
self.patches.unlink()
result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"})
self.assertEqual(routed["argv"][1], str(tool / "proton"))
self.assertNotIn("cannot run anti-cheat", result.stderr)
self.assertTrue((self.root / "record.json.update").exists())
def test_games_without_anti_cheat_files_do_not_update_fex(self):
self.file("Data/Settings.json")
self.launch()
self.assertFalse((self.root / "record.json.update").exists())
def test_choices_are_kept_the_same_with_an_older_fex_build(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
self.patches.unlink()
result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"})
self.assertIsNone(routed)
self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr)
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
self.assertIsNone(routed)
self.assertEqual(result.stderr, "")
def test_the_fex_build_lists_its_patches(self):
build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text()
self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build)
names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")}
self.assertIn("fixed-guest-memory-above-host-address-limit", names)
def test_adopted_tools_pass_their_own_folder_name(self):
wrapper = COMPAT["extra_wrapper_sh"]("proton")
self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper)
self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"])
def test_other_verbs_are_left_alone(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch(verb="getcompatpath")
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self):
launcher = COMPAT["LAUNCHER_SH"]
self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"'))
wrapper = COMPAT["extra_wrapper_sh"]("proton")
self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback="))
self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"'))
self.assertIn('! dd_x86_64_proton "$d"', wrapper)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,38 @@
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src"
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
class BottomMirrorCompositionTest(unittest.TestCase):
def test_mirror_requests_composition_until_its_last_consumer_leaves(self):
panel = (APP / "ui/BottomMirrorPage.kt").read_text()
self.assertIn("actions.holdComposed(true)", panel)
self.assertIn("onDispose { actions.holdComposed(false) }", panel)
activity = (APP / "SessionActivity.kt").read_text()
hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0]
self.assertIn("if (held == wasHeld) return", hold)
self.assertIn("nativeSetMirrorCapture(held)", hold)
self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold)
self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity)
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity)
self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold)
self.assertNotIn("SessionPrefs.set", hold)
def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self):
jni = (NATIVE / "waylandcomp_jni.c").read_text()
self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni)
host = (NATIVE / "droiddeck_ext.c").read_text()
self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host)
compositor = (NATIVE / "compositor.c").read_text()
self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor)
self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor)
self.assertIn("if (un && g_zero_copy)", compositor)
self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor)
self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor)
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -1235,6 +1235,29 @@ class LaunchTest(FexTestCase):
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self):
proton = self.proton("4183110")
folder = proton.parent
os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig")
self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n')
self.assertEqual(FEX["required_runtime"](str(proton)), "4183110")
os.unlink(folder / "toolmanifest.vdf.droiddeck-orig")
self.assertEqual(FEX["required_runtime"](str(proton)), "1628350")
def test_proton_action_keeps_the_prefix_and_runs_under_fex(self):
self.fex_tool()
self.runtime()
proton = self.proton("1628350")
prefix = str(self.tmp / "compatdata" / "730")
env = {"STEAM_COMPAT_DATA_PATH": prefix}
with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated:
self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"])
command, guest = emulated.call_args[0][1], emulated.call_args[0][2]
self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"])
self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix)
self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix)
self.assertEqual(FEX["main"](["proton", str(proton)]), 2)
def test_native_programs_run_directly(self):
program = self.write(self.tmp / "native", elf(183), 0o755)
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
@@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False}
NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False}
X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64",
"valve": False, "x86_64": True}
def config_text(entries):
@@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase):
self.assertEqual(newest, "b")
self.assertEqual(gone, {OLD["name"]})
def test_an_x86_64_build_never_becomes_the_automatic_default(self):
default, mapping, state = self.run_default(
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"])
self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"]))
default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_an_automatic_x86_64_default_moves_back_to_arm64(self):
default, mapping, state = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86])
self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update"))
default, mapping, _ = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_an_x86_64_default_the_user_picked_is_kept(self):
for source in ("app", "steam"):
default, mapping, _ = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86])
self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]}))
def test_a_request_for_the_automatic_x86_64_default_keeps_it(self):
default, mapping, state = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])],
[VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]})
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86],
request={"seq": 2, "name": X86["name"]})
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
def test_x86_64_layouts_are_marked_in_the_catalog(self):
with tempfile.TemporaryDirectory() as tmp:
tools = Path(tmp) / "compatibilitytools.d"
for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)):
(tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
if arm:
(tools / entry / "files" / "bin-arm64").mkdir()
(tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("")
catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]}
self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64"))
self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"])
newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values()))
self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"])
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+22
View File
@@ -117,6 +117,28 @@ class FexInstallTest(unittest.TestCase):
self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text())
self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text())
def test_a_build_without_a_patch_list_drops_the_old_one(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertFalse(marker.exists())
def test_a_failed_install_keeps_the_old_patch_list(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("FAILED", self.install(installed_loads=False)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n", marker.read_text())
def test_a_build_with_a_patch_list_installs_it(self):
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").write_text("openat2-enosys-fallback\n")
shipped = Path(self.temp.name) / "pkg/usr/local/share/fex-emu"
shipped.mkdir(parents=True)
(shipped / ".droiddeck-patches").write_text("fixed-guest-memory-above-host-address-limit\n")
self.pack()
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n",
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").read_text())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
+157
View File
@@ -0,0 +1,157 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch"
EMULATED = "Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles"
HOST_MOUNTS = """/dev/block/dm-28 / ext4 ro,seclabel,relatime,discard 0 0
tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,size=5791196k,nr_inodes=1447799,mode=755 0 0
proc /proc proc rw,relatime,gid=3009,hidepid=invisible 0 0
sysfs /sys sysfs rw,seclabel,relatime 0 0
/dev/fuse /mnt/user/0/emulated fuse rw,lazytime,nosuid,nodev,noexec,noatime,user_id=0,group_id=0,allow_other 0 0
"""
HOST_MOUNTINFO = """9838 9837 254:28 / / ro,relatime master:1 - ext4 /dev/block/dm-28 ro,seclabel,discard
9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw,gid=3009,hidepid=invisible
9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw,hidepid=2,subset=pid
9871 9838 0:21 / /sys rw,relatime master:5 - sysfs sysfs rw,seclabel
"""
HARNESS = r"""
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
namespace fextl {
using string = std::string;
template<typename T> using vector = std::vector<T>;
}
HELPERS
static std::string Filter(const std::string& In, bool MountInfo) {
std::string Out;
size_t Pos = 0;
while (Pos < In.size()) {
size_t Eol = In.find('\n', Pos);
const size_t LineEnd = Eol == std::string::npos ? In.size() : Eol;
Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
if (Eol != std::string::npos) {
Out += '\n';
}
Pos = LineEnd + 1;
}
return Out;
}
int main(int argc, char** argv) {
if (argv[1][0] == 'p') {
for (int i = 2; i < argc; ++i) {
std::printf("%s\n", IsProcMountTablePath(argv[i]) ? "yes" : "no");
}
return 0;
}
std::string In;
char Buf[4096];
size_t Len;
while ((Len = std::fread(Buf, 1, sizeof(Buf), stdin)) > 0) {
In.append(Buf, Len);
}
std::fputs(Filter(In, argv[1][0] == 'i').c_str(), stdout);
return 0;
}
"""
def added():
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
def helpers():
body = added()
start = body.index("static const char* ProcFileOfPid(const char* Path) {")
end = body.index("static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {")
end = body.index("}", end) + 1
return "\n".join(body[start:end])
class FexProcMountTablesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.binary = None
compiler = shutil.which("g++") or shutil.which("clang++")
if compiler:
source = Path(cls.tmp.name) / "mounts.cpp"
source.write_text(HARNESS.replace("HELPERS", helpers()))
binary = Path(cls.tmp.name) / "mounts"
subprocess.run([compiler, "-std=c++20", "-O1", "-o", str(binary), str(source)], check=True)
cls.binary = binary
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_filter(self, mode, text):
if not self.binary:
self.skipTest("no C++ compiler")
return subprocess.run([str(self.binary), mode], input=text, capture_output=True, text=True, check=True).stdout
def matches(self, *paths):
if not self.binary:
self.skipTest("no C++ compiler")
out = subprocess.run([str(self.binary), "p", *paths], capture_output=True, text=True, check=True).stdout
return out.split()
def test_only_the_emulated_files_change(self):
files = re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)
self.assertEqual({EMULATED + ".cpp", EMULATED + ".h"}, set(files))
def test_mount_tables_are_routed_to_the_filter_on_open(self):
body = added()
self.assertIn(" if (pathname && IsProcMountTablePath(pathname)) {", body)
self.assertIn(" return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);", body)
def test_every_path_form_of_the_mount_tables_matches(self):
paths = ["/proc/mounts", "/proc/self/mounts", "/proc/thread-self/mounts", "/proc/self/mountinfo", "/proc/4242/mounts",
"/proc/4242/mountinfo", "/proc/4242/task/4243/mountinfo"]
self.assertEqual(["yes"] * len(paths), self.matches(*paths))
def test_other_proc_files_do_not_match(self):
paths = ["/proc/self/maps", "/proc/self/status", "/proc/self/mountstats", "/proc/4242/task/mounts", "/proc/self/mounts/x",
"/etc/mounts", "/proc/4242x/mounts"]
self.assertEqual(["no"] * len(paths), self.matches(*paths))
def test_only_the_proc_line_of_mounts_changes(self):
out = self.run_filter("m", HOST_MOUNTS).splitlines()
expected = HOST_MOUNTS.splitlines()
expected[2] = "proc /proc proc rw,relatime 0 0"
self.assertEqual(expected, out)
def test_only_proc_super_options_of_mountinfo_change(self):
out = self.run_filter("i", HOST_MOUNTINFO).splitlines()
expected = HOST_MOUNTINFO.splitlines()
expected[1] = "9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw"
expected[2] = "9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw"
self.assertEqual(expected, out)
def test_tables_without_proc_pass_through_unchanged(self):
text = "".join(line + "\n" for line in HOST_MOUNTS.splitlines() if " proc " not in line)
self.assertEqual(text, self.run_filter("m", text))
def test_malformed_lines_pass_through_unchanged(self):
text = "proc /proc proc\nno dash here proc rw\n\nproc\n"
self.assertEqual(text, self.run_filter("m", text))
self.assertEqual(text, self.run_filter("i", text))
def test_no_comments_are_added(self):
self.assertFalse([line for line in added() if line.strip().startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+49 -2
View File
@@ -8,14 +8,17 @@ from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
EMULATION = FEX / "patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch"
MCONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
PROBE = FEX / "probes/signal-register-update.c"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
def files(patch=PATCH):
sections = re.split(r"^diff --git a/(\S+) \S+\n", patch.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
@@ -96,6 +99,50 @@ class SignalRegisterUpdateTest(unittest.TestCase):
self.assertNotIn("Fixed-upstream", PATCH.read_text())
class ClearedSyscallInfoTest(unittest.TestCase):
SOURCE = "ArchHelpers::Context::SavedSyscallInfo(Context)"
def saved_info(self):
lines = [line[1:] for line in files(EMULATION)[MCONTEXT].splitlines() if line.startswith("+") and not line.startswith("+++")]
start = lines.index("template<typename Backup>")
end = lines.index("}", start)
return "\n".join(lines[start:end + 1])
def test_register_writeback_reads_the_same_saved_state_as_the_restore(self):
frames = files(EMULATION)[FRAMES]
self.assertIn("- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;", frames)
self.assertIn("+ const uint32_t Spilled = " + self.SOURCE + " & 0xFFFF;", frames)
delegator = added(files(EMULATION)[DELEGATOR])
self.assertIn("Thread->CurrentFrame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = Context->InSyscallInfo;", removed(files(EMULATION)[DELEGATOR]))
self.assertNotIn("Context->ClearedSyscallInfo :", "\n".join(delegator))
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "needs a C++ compiler")
def test_cleared_state_is_preferred_only_when_flagged(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
source = "\n".join([
"#include <cstdint>",
"#include <cstdio>",
"enum ContextFlags : uint32_t { CONTEXT_FLAG_INJIT = 1U << 0, CONTEXT_FLAG_SYSCALLINFO_CLEARED = 1U << 1 };",
"struct Backup { uint16_t InSyscallInfo; uint16_t ClearedSyscallInfo; uint32_t Flags; };",
self.saved_info(),
"int main() {",
" const Backup Thunk {0, 0xFFFF, CONTEXT_FLAG_SYSCALLINFO_CLEARED};",
" const Backup Jit {0x0F0F, 0x1234, CONTEXT_FLAG_INJIT};",
" const Backup Idle {0, 0x1234, 0};",
" std::printf(\"%x %x %x\\n\", SavedSyscallInfo(&Thunk), SavedSyscallInfo(&Jit), SavedSyscallInfo(&Idle));",
"}",
])
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "saved.cpp"
binary = Path(tmp) / "saved"
path.write_text(source)
subprocess.run([compiler, "-std=c++20", "-Wall", "-Werror", "-o", str(binary), str(path)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
self.assertEqual(output.split(), ["ffff", "f0f", "0"])
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalRegisterUpdateProbeTest(unittest.TestCase):
@classmethod
+7 -5
View File
@@ -2664,8 +2664,8 @@ class GameEnvironmentTest(unittest.TestCase):
def test_both_proton_wrappers_call_environment_launcher(self):
self.assertIn('dd_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["extra_wrapper_sh"]("proton"))
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
@@ -2673,9 +2673,11 @@ class GameEnvironmentTest(unittest.TestCase):
scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton"))
query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe"
probe = "/root/.local/share/Steam/steamapps/compatdata/0"
for script in scripts:
for script, here in zip(scripts, ("$depot", "$here")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("dd_components "))
answered = script.index('case "$verb:${1##*/}:')
self.assertLess(answered, script.index('dd_components "%s"' % here))
self.assertLess(answered, script.index('dd_anticheat "$@"'))
for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"),
([query.replace("64.exe", ".exe")], probe)):
result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True,
@@ -2744,7 +2746,7 @@ class GameEnvironmentTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
for name in ("libddsession.so", "libfakeinput.so"):
(Path(tmp) / name).write_bytes(b"")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
start = script.index("for fake in ")
block = script[start:script.index("\ndone\n", start) + 6].replace("/usr/local/lib/", tmp + "/")
for inherited, expected in (
@@ -0,0 +1,229 @@
import errno
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#define SIZE 100003
static unsigned long sum_of(int fd) {
unsigned long sum = 0;
unsigned char buf[4096];
ssize_t n;
long total = 0;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
for (ssize_t i = 0; i < n; i++) sum = sum * 31 + buf[i];
total += n;
}
return total == SIZE ? sum : 0;
}
static int open_by(const char *how, const char *path, int flags) {
if (strcmp(how, "open") == 0) return open(path, flags);
if (strcmp(how, "openat") == 0) return openat(AT_FDCWD, path, flags);
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, 0);
}
static void report(const char *label, int fd, int src) {
if (fd < 0) {
printf("%s\terr\t%d\n", label, errno);
return;
}
char link[64], target[256];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, target, sizeof(target) - 1);
target[n > 0 ? n : 0] = '\0';
char *deleted = strstr(target, " (deleted)");
if (deleted) *deleted = '\0';
struct stat a, b;
fstat(fd, &a);
fstat(src, &b);
unsigned long sum = sum_of(fd);
int write_errno = pwrite(fd, "x", 1, 0) < 0 ? errno : 0;
int grow_errno = ftruncate(fd, SIZE + 1) < 0 ? errno : 0;
printf("%s\tok\t%lu\t%d\t%s\t%d\t%ld\t%o\t%d\t%d\n", label, sum, fcntl(fd, F_GET_SEALS), target,
(fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (long)lseek(src, 0, SEEK_CUR), (unsigned)(a.st_mode & 07777),
write_errno != 0, grow_errno != 0);
close(fd);
}
int main(int argc, char **argv) {
int src = memfd_create("probe-module", MFD_ALLOW_SEALING);
unsigned char *data = malloc(SIZE);
for (long i = 0; i < SIZE; i++) data[i] = (unsigned char)(i * 7 + 3);
if (write(src, data, SIZE) != SIZE) return 3;
unsigned long want = 0;
for (long i = 0; i < SIZE; i++) want = want * 31 + data[i];
printf("want\t%lu\n", want);
fcntl(src, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
fchmod(src, 0);
char path[64];
const char *forms[] = {"self", "thread", "pid", "dev"};
const char *hows[] = {"open", "openat", "syscall"};
for (int f = 0; f < 4; f++) {
for (int h = 0; h < 3; h++) {
if (f == 0) snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (f == 1) snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", src);
if (f == 2) snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), src);
if (f == 3) snprintf(path, sizeof(path), "/dev/fd/%d", src);
char label[32];
snprintf(label, sizeof(label), "%s-%s", forms[f], hows[h]);
report(label, open_by(hows[h], path, O_RDONLY | O_CLOEXEC), src);
}
}
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
report("keep-cloexec-off", open(path, O_RDONLY), src);
report("write", open(path, O_RDWR), src);
int foreign = memfd_create("probe-foreign", 0);
fchmod(foreign, 0);
pid_t child = fork();
if (child < 0) return 6;
if (child == 0) {
pause();
_exit(0);
}
snprintf(path, sizeof(path), "/proc/%d/fd/%d", (int)child, foreign);
report("other-pid", open(path, O_RDONLY), src);
kill(child, SIGKILL);
waitpid(child, NULL, 0);
int plain = open(argv[1], O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (write(plain, "x", 1) != 1) return 4;
fchmod(plain, 0);
snprintf(path, sizeof(path), "/proc/self/fd/%d", plain);
report("plain-file", open(path, O_RDONLY | O_CLOEXEC), plain);
int open_mfd = memfd_create("probe-open", 0);
if (write(open_mfd, data, SIZE) != SIZE) return 5;
snprintf(path, sizeof(path), "/proc/self/fd/%d", open_mfd);
int again = open(path, O_RDONLY | O_CLOEXEC);
struct stat a, b;
fstat(again, &a);
fstat(open_mfd, &b);
printf("readable-memfd\t%d\n", again >= 0 && a.st_ino == b.st_ino);
unsigned long long how[3] = {O_RDONLY | O_CLOEXEC, 0, 0};
errno = 0;
long direct = syscall(437, AT_FDCWD, "/", how, sizeof(how));
printf("kernel-openat2\t%d\n", direct >= 0 || errno != ENOSYS);
int (*open2)(int, const char *, void *, size_t) = dlsym(RTLD_DEFAULT, "openat2");
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (open2 && argc > 2) {
errno = 0;
int refused = open2(AT_FDCWD, path, (void *)8, 24);
int refused_errno = errno;
printf("unreadable-how\t%d\t%d\n", refused, refused_errno);
}
return 0;
}
"""
class NativeHookMemfdReopenTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
if os.geteuid() == 0:
raise unittest.SkipTest("root ignores the file mode that stands in for the refused reopen")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
cls.plain = cls.root / "plain"
cls.bare = cls.run_probe(False)
cls.kernel_openat2 = cls.bare["kernel-openat2"] == ["1"]
cls.hooked = cls.run_probe(True, *(["how"] if cls.kernel_openat2 else []))
@classmethod
def tearDownClass(cls):
os.chmod(cls.plain, 0o600)
cls.tmp.cleanup()
@classmethod
def run_probe(cls, hook, *extra):
if cls.plain.exists():
os.chmod(cls.plain, 0o600)
hook_env = {"DDNATV_ROOT": str(cls.root), "LD_PRELOAD": str(cls.hook)} if hook else {}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if cls.prefix:
cmd = list(cls.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(cls.probe), str(cls.plain), *extra], env=env, capture_output=True, text=True, timeout=120)
if out.returncode != 0:
raise AssertionError(out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_the_refused_reopen_is_the_condition_without_the_hook(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-open"])
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-syscall"])
def test_a_refused_read_only_reopen_of_an_own_memfd_gets_its_bytes_and_seals(self):
want = self.hooked["want"][0]
for form in ("self", "thread", "pid", "dev"):
for how in ("open", "openat", "syscall"):
with self.subTest(form=form, how=how):
status, total, seals, name, cloexec, offset, mode, unwritable, fixed = self.hooked[f"{form}-{how}"]
self.assertEqual("ok", status)
self.assertEqual(want, total)
self.assertEqual(str(0x2 | 0x4 | 0x8), seals)
self.assertEqual("1", unwritable)
self.assertEqual("1", fixed)
self.assertEqual("/memfd:probe-module", name)
self.assertEqual("1", cloexec)
self.assertEqual("100003", offset)
self.assertEqual("0", mode)
def test_close_on_exec_follows_the_open_flags(self):
self.assertEqual("0", self.hooked["keep-cloexec-off"][4])
def test_an_unreadable_open_how_gets_the_kernel_error(self):
if not self.kernel_openat2:
self.skipTest("the runner has no openat2")
self.assertEqual(["-1", str(errno.EFAULT)], self.hooked["unreadable-how"])
def test_a_writable_reopen_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["write"])
def test_another_process_descriptor_is_not_copied(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["other-pid"])
self.assertEqual(["err", str(errno.EACCES)], self.hooked["other-pid"])
def test_a_refused_regular_file_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["plain-file"])
self.assertEqual(self.bare["plain-file"], self.hooked["plain-file"])
def test_a_memfd_the_kernel_reopens_is_the_same_file(self):
self.assertEqual(["1"], self.hooked["readable-memfd"])
self.assertEqual(["1"], self.bare["readable-memfd"])
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -19,6 +19,13 @@ int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
char buf[4096];
ssize_t n;
if (strncmp(argv[i], "fill:", 5) == 0 || strncmp(argv[i], "short:", 6) == 0) {
size_t size = argv[i][0] == 'f' ? sizeof(buf) : 256;
memset(buf, '/', sizeof(buf));
n = readlink(strchr(argv[i], ':') + 1, buf, size);
printf("%s\t%s\n", argv[i], n > 0 && (size_t)n < size && buf[n] == 0 ? "ends" : "runs on");
continue;
}
if (strncmp(argv[i], "at:", 3) == 0) {
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
n = dfd >= 0 ? readlinkat(dfd, "exe", buf, sizeof(buf) - 1) : -1;
@@ -57,6 +64,7 @@ class NativeHookProcExeTest(unittest.TestCase):
(cls.root / "usr/bin").mkdir(parents=True)
cls.kwin = cls.root / "usr/bin/kwin_wayland"
shutil.copy(tmp / "sleeper", cls.kwin)
(cls.root / "compositor").symlink_to("usr/bin/kwin_wayland")
cls.runtime = tmp / "runtime"
cls.runtime.mkdir()
cls.bound = cls.runtime / "chrome"
@@ -151,6 +159,14 @@ class NativeHookProcExeTest(unittest.TestCase):
link = f"/proc/{pid}/exe"
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
def test_the_own_program_answer_ends_where_the_name_ends(self):
key = "fill:/proc/self/exe"
self.assertEqual("ends", self.readlink(key)[key])
def test_a_link_read_into_a_short_buffer_ends_where_its_target_ends(self):
key = "short:/compositor"
self.assertEqual("ends", self.readlink(key)[key])
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
pid = self.start(loader=True)
link = f"/proc/{pid}/exe"
+87 -2
View File
@@ -45,6 +45,38 @@ int main(int argc, char **argv) {
}
"""
FORMS = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (chdir(argv[1]) != 0) return 2;
char buf[PATH_MAX];
printf("cwd\t%s\n", getcwd(buf, sizeof(buf)) ? buf : "");
ssize_t n = readlink("/proc/self/cwd", buf, sizeof(buf) - 1);
printf("proc-cwd\t%.*s\n", n > 0 ? (int)n : 0, buf);
n = readlink(argv[2], buf, sizeof(buf) - 1);
printf("relative\t%.*s\n", n > 0 ? (int)n : 0, buf);
char climbing[PATH_MAX];
snprintf(climbing, sizeof(climbing), "../../../../../../../../../../../../etc/alternatives/%s", argv[2]);
n = readlinkat(AT_FDCWD, climbing, buf, sizeof(buf) - 1);
printf("climbing-at\t%.*s\n", n > 0 ? (int)n : 0, buf);
struct stat st;
printf("climbing-size\t%ld\n", fstatat(AT_FDCWD, climbing, &st, AT_SYMLINK_NOFOLLOW) == 0 ? (long)st.st_size : -1L);
for (int i = 3; i < argc; i++) {
char *got = realpath(argv[i], NULL);
printf("realpath:%s\t%s\n", argv[i], got ? got : "");
free(got);
}
return 0;
}
"""
class NativeHookReadlinkTest(unittest.TestCase):
@classmethod
@@ -65,12 +97,20 @@ class NativeHookReadlinkTest(unittest.TestCase):
(cls.root / "bin/nano").write_text("")
os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor")
os.symlink("/bin/nano", cls.root / "etc/alternatives/guest")
(tmp / "forms.c").write_text(FORMS)
cls.forms = tmp / "forms"
subprocess.run([cls.cc, "-O1", "-o", str(cls.forms), str(tmp / "forms.c")], check=True)
cls.steam = cls.root / "root/.local/share/Steam"
(cls.steam / "steamapps/common/Game").mkdir(parents=True)
(cls.steam / "steamapps/common/Game/Game.exe").write_text("")
(cls.root / "root/pfx/dosdevices").mkdir(parents=True)
os.symlink(cls.steam, cls.root / "root/pfx/dosdevices/s:")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def read(self, link):
def run_hooked(self, argv):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
@@ -78,10 +118,16 @@ class NativeHookReadlinkTest(unittest.TestCase):
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120)
out = subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def read(self, link):
return self.run_hooked([str(self.probe), link])
def path_forms(self, cwd, relative_link, *paths):
return {key: value[0] for key, value in self.run_hooked([str(self.forms), cwd, relative_link, *paths]).items()}
def test_a_buffer_sized_from_lstat_gets_the_guest_target(self):
result = self.read("/etc/alternatives/editor")
self.assertEqual(["9", "/bin/nano"], result["sized"])
@@ -101,6 +147,45 @@ class NativeHookReadlinkTest(unittest.TestCase):
self.assertEqual(["-1", str(errno.EINVAL)], result["zero"])
self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"])
def test_a_link_named_by_its_real_path_keeps_a_real_target(self):
steam = str(self.steam)
result = self.read(str(self.root / "root/pfx/dosdevices/s:"))
self.assertEqual([str(len(steam)), steam], result["sized"])
self.assertEqual([str(len(steam)), steam], result["sized-at"])
self.assertEqual([str(len(steam)), steam], result["full"])
def test_a_link_named_by_its_guest_path_keeps_the_guest_target(self):
result = self.read("/root/pfx/dosdevices/s:")
self.assertEqual([str(len("/root/.local/share/Steam")), "/root/.local/share/Steam"], result["full"])
self.assertEqual(["9", "/bin/nano"], self.read("/etc/alternatives/editor")["sized"])
def test_a_link_the_hook_wrote_reads_in_the_form_it_is_named_in(self):
real = str(self.root / "bin/nano")
self.assertEqual([str(len(real)), real], self.read(str(self.root / "etc/alternatives/editor"))["sized"])
self.assertEqual(["9", "/bin/nano"], self.read(str(self.root / "etc/alternatives/guest"))["sized"])
def test_a_game_reached_through_a_drive_link_is_named_like_the_working_directory(self):
game = self.steam / "steamapps/common/Game"
through_drive = str(self.root / "root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe")
result = self.path_forms(str(game), "Game.exe", through_drive, "Game.exe")
self.assertEqual(str(game), result["cwd"])
self.assertEqual(str(game / "Game.exe"), result[f"realpath:{through_drive}"])
self.assertTrue(result[f"realpath:{through_drive}"].startswith(result["cwd"] + "/"))
def test_the_proc_working_directory_link_matches_getcwd(self):
game = str(self.steam / "steamapps/common/Game")
result = self.path_forms(game, "Game.exe")
self.assertEqual(result["cwd"], result["proc-cwd"])
def test_guest_and_relative_names_keep_the_guest_form(self):
guest_drive = "/root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe"
result = self.path_forms(str(self.root / "etc/alternatives"), "editor", guest_drive, "/etc/alternatives/editor")
self.assertEqual("/bin/nano", result["relative"])
self.assertEqual("/bin/nano", result["climbing-at"])
self.assertEqual("9", result["climbing-size"])
self.assertEqual("/root/.local/share/Steam/steamapps/common/Game/Game.exe", result[f"realpath:{guest_drive}"])
self.assertEqual("/bin/nano", result["realpath:/etc/alternatives/editor"])
if __name__ == "__main__":
unittest.main()
+8
View File
@@ -78,6 +78,7 @@ static int g_loop_stub;
static int g_fallback_accept;
static int g_fallback_token;
static int g_hdr_count;
static int g_mirror_count, g_mirror_capture;
int text_input_host_commit(const char *u, size_t n)
{
@@ -143,6 +144,7 @@ void toplevel_icon_init(struct wl_display *d) { (void)d; }
void single_pixel_init(struct wl_display *d) { (void)d; }
void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; }
void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; }
void droiddeck_set_mirror_capture(int on) { g_mirror_capture = on; g_mirror_count++; }
struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; }
void wl_display_flush_clients(struct wl_display *d) { (void)d; }
@@ -216,7 +218,10 @@ int main(void)
droiddeck_host_key(29, 0);
droiddeck_host_text_commit("later", 5);
droiddeck_host_hdr_output(1);
droiddeck_host_mirror_capture(1);
CHECK(g_mirror_count == 0);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 1 && g_mirror_capture == 1);
CHECK(g_n == saved);
CHECK(g_hdr_count == 1);
CHECK(g_fallback_token > 0);
@@ -259,7 +264,10 @@ int main(void)
droiddeck_host_key(32, 1);
droiddeck_host_key(32, 0);
droiddeck_host_hdr_output(0);
droiddeck_host_mirror_capture(0);
CHECK(g_mirror_count == 1);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 2 && g_mirror_capture == 0);
CHECK(g_n == saved + 1);
CHECK(g_hdr_count == 2);
CHECK(g_fallback_token > 0);
+83
View File
@@ -1,5 +1,6 @@
import os
from pathlib import Path
import platform
import signal
import shutil
import subprocess
@@ -29,6 +30,7 @@ PROGRAM = r"""
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <ucontext.h>
#include <unistd.h>
static const char *ctl;
@@ -220,6 +222,45 @@ static void *writer(void *arg) {
return NULL;
}
static volatile unsigned char dispatch_selector;
static int dispatch_traps, dispatch_done, dispatch_ready;
static long dispatch_result = -1;
static void dispatch_trap(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)info;
__atomic_add_fetch(&dispatch_traps, 1, __ATOMIC_RELAXED);
#ifdef __x86_64__
((ucontext_t *)context)->uc_mcontext.gregs[REG_RAX] = -ENOSYS;
#endif
}
static void *dispatch_signaller(void *arg) {
(void)arg;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGURG);
pthread_sigmask(SIG_BLOCK, &set, NULL);
char ack[256], text[32];
snprintf(ack, sizeof(ack), "%s.trim.%d", ctl, getpid());
unlink(ack);
FILE *f = fopen(ctl, "w");
if (!f) exit(3);
fprintf(f, "2 %ld\n", 1L << 30);
fclose(f);
while (!__atomic_load_n(&dispatch_ready, __ATOMIC_ACQUIRE)) usleep(1000);
kill(getpid(), SIGURG);
for (int i = 0; i < 1200 && dispatch_result < 0; i++) {
f = fopen(ack, "r");
char *line = f ? fgets(text, sizeof(text), f) : NULL;
if (f) fclose(f);
if (line) dispatch_result = atol(text);
else usleep(10000);
}
__atomic_store_n(&dispatch_done, 1, __ATOMIC_RELEASE);
return NULL;
}
int main(int argc, char **argv) {
ctl = argv[1];
size = strtoul(argv[2], NULL, 0) << 20;
@@ -391,6 +432,38 @@ int main(int argc, char **argv) {
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("filtered_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "dispatch")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
struct sigaction trap;
memset(&trap, 0, sizeof(trap));
trap.sa_sigaction = dispatch_trap;
trap.sa_flags = SA_SIGINFO;
sigemptyset(&trap.sa_mask);
sigaction(SIGSYS, &trap, NULL);
errno = 0;
printf("prctlerr %d\n", prctl(-1, 0, 0, 0, 0) == -1 && errno == EINVAL);
if (prctl(59, 1, (unsigned long)sa.sa_restorer, 16, &dispatch_selector)) {
printf("dispatch 0\n");
return 0;
}
printf("dispatch 1\n");
fflush(stdout);
pthread_t signaller;
pthread_create(&signaller, NULL, dispatch_signaller, NULL);
dispatch_selector = 1;
__atomic_store_n(&dispatch_ready, 1, __ATOMIC_RELEASE);
while (!__atomic_load_n(&dispatch_done, __ATOMIC_ACQUIRE)) {
}
char name[16] = {0};
int named = prctl(PR_GET_NAME, name, 0, 0, 0) == 0 && name[0] != 0;
dispatch_selector = 0;
prctl(59, 0, 0, 0, 0);
pthread_join(signaller, NULL);
printf("traps %d\n", __atomic_load_n(&dispatch_traps, __ATOMIC_RELAXED));
printf("trimmed %d\n", dispatch_result >= 0);
printf("named %d\n", named);
return 0;
} else if (!strcmp(argv[4], "burst")) {
send_request('0');
usleep(10000);
@@ -690,6 +763,16 @@ class ZramPreloadTest(unittest.TestCase):
out = self.run_program(None, 48, 0, "burst")
self.assertEqual([1], out["burstack"])
@unittest.skipUnless(platform.machine() == "x86_64", "selector check is x86-64 only")
def test_requests_are_served_while_syscall_user_dispatch_blocks(self):
out = self.run_program(None, 8, 0, "dispatch")
self.assertEqual([1], out["prctlerr"])
if out["dispatch"] != [1]:
self.skipTest("kernel lacks syscall user dispatch")
self.assertEqual([0], out["traps"], out)
self.assertEqual([1], out["trimmed"], out)
self.assertEqual([1], out["named"], out)
if __name__ == "__main__":
unittest.main()
+462
View File
@@ -0,0 +1,462 @@
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define THREADS 4
struct shared {
volatile long progress;
volatile long errors;
volatile int stop;
volatile int quiet; // readers leave the blocks alone (a page-out they would undo is being measured)
volatile int quieted; // readers that have stopped reading
volatile long touched; // pages readers have looked at, counted as they go
};
static const char *ctl;
static size_t size;
static int block_urg;
static struct shared *shared;
static unsigned char *blocks[THREADS];
static void fill(unsigned char *p, size_t n, unsigned seed) {
for (size_t i = 0; i < n; i++) p[i] = (unsigned char)((i * 2654435761u + seed) >> 7);
}
static int same(const unsigned char *p, size_t n, unsigned seed) {
for (size_t i = 0, next = 0; i < n; i += 61) {
if (i >= next) {
__atomic_add_fetch(&shared->touched, 1, __ATOMIC_RELAXED);
next = i + 4096;
}
if (p[i] != (unsigned char)((i * 2654435761u + seed) >> 7)) return 0;
}
return 1;
}
static void *work(void *arg) {
long id = (long)arg;
if (block_urg && id == 0) {
sigset_t set;
sigfillset(&set);
pthread_sigmask(SIG_BLOCK, &set, NULL);
}
unsigned seed = (unsigned)id * 77u + 1u;
int idle = 0;
while (!shared->stop) {
if (shared->quiet) {
if (!idle) {
idle = 1;
__atomic_add_fetch(&shared->quieted, 1, __ATOMIC_RELEASE);
}
continue;
}
if (idle) {
idle = 0;
__atomic_sub_fetch(&shared->quieted, 1, __ATOMIC_RELEASE);
}
if (!same(blocks[id], size, seed)) __atomic_add_fetch(&shared->errors, 1, __ATOMIC_RELAXED);
__atomic_add_fetch(&shared->progress, 1, __ATOMIC_RELAXED);
}
return NULL;
}
static void put(const char *suffix, const char *text) {
char path[512];
snprintf(path, sizeof(path), "%s%s", ctl, suffix);
FILE *f = fopen(path, "w");
if (!f) exit(20);
fputs(text, f);
fclose(f);
}
static long get(const char *suffix, pid_t pid) {
char path[512], text[32] = {0};
snprintf(path, sizeof(path), "%s%s%d", ctl, suffix, pid);
FILE *f = fopen(path, "r");
if (!f) return -2;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
return n == 0 ? -1 : atol(text);
}
static long rss_kb(pid_t pid) {
char path[64], line[256];
long kb = -1;
snprintf(path, sizeof(path), "/proc/%d/status", pid);
FILE *f = fopen(path, "r");
while (f && fgets(line, sizeof(line), f))
if (!strncmp(line, "VmRSS:", 6)) kb = atol(line + 6);
if (f) fclose(f);
return kb;
}
static void nap(long ms) {
struct timespec t = {ms / 1000, ms % 1000 * 1000000};
nanosleep(&t, NULL);
}
static long wait_for(const char *suffix, pid_t pid, long ms) {
for (long waited = 0; waited < ms; waited += 20) {
long v = get(suffix, pid);
if (v >= 0) return v;
nap(20);
}
return -3;
}
static pid_t find_helper(pid_t owner) {
DIR *proc = opendir("/proc");
struct dirent *entry;
while (proc && (entry = readdir(proc)) != NULL) {
pid_t pid = (pid_t)atoi(entry->d_name);
if (pid <= 0) continue;
char path[64], text[512];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
FILE *f = fopen(path, "r");
if (!f) continue;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
text[n] = 0;
char *close = strrchr(text, ')');
int ppid = 0;
if (strstr(text, "(zr-spill)") && close && sscanf(close + 2, "%*c %d", &ppid) == 1 && ppid == owner) {
closedir(proc);
return pid;
}
}
if (proc) closedir(proc);
return -1;
}
static int thread_in_state(pid_t pid, char state) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/task", pid);
DIR *tasks = opendir(path);
struct dirent *entry;
int found = 0;
while (tasks && !found && (entry = readdir(tasks)) != NULL) {
if (atoi(entry->d_name) <= 0) continue;
char stat[64], text[512];
snprintf(stat, sizeof(stat), "/proc/%d/task/%s/stat", pid, entry->d_name);
FILE *f = fopen(stat, "r");
if (!f) continue;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
text[n] = 0;
char *close = strrchr(text, ')');
found = close && close[1] == ' ' && close[2] == state;
}
if (tasks) closedir(tasks);
return found;
}
int main(int argc, char **argv) {
if (argc > 1 && !strcmp(argv[1], "probe")) {
// whether a child may seize its parent, as the spill helper does (Yama's ptrace_scope 1 refuses)
pid_t parent = getpid(), probe = fork();
if (probe == 0) _exit(ptrace(PTRACE_SEIZE, parent, 0, 0) == 0 ? 0 : 1);
int status = 0;
waitpid(probe, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
}
if (argc > 1 && !strcmp(argv[1], "pageout")) {
// whether this host pages anonymous memory out at all (swap, and a kernel that is not emulated)
size_t n = 64u << 20;
unsigned char *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) return 1;
fill(p, n, 3);
long before = rss_kb(getpid());
madvise(p, n, 21 /* MADV_PAGEOUT */);
return rss_kb(getpid()) < before - 32 * 1024 ? 0 : 1;
}
ctl = argv[1];
size = (size_t)atol(argv[2]) << 20;
block_urg = argc > 3 && !strcmp(argv[3], "block");
int undumpable = argc > 3 && !strcmp(argv[3], "undumpable");
if (undumpable) prctl(PR_SET_DUMPABLE, 0);
shared = mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (shared == MAP_FAILED) return 2;
char resume[512];
snprintf(resume, sizeof(resume), "%s.resume", ctl);
unlink(resume);
put(".hold", "");
pid_t child = fork();
if (child == 0) {
// the blocks are the child's alone: a page-out skips pages another process still maps
for (int i = 0; i < THREADS; i++) {
blocks[i] = i % 2 ? malloc(size) : mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (!blocks[i] || blocks[i] == MAP_FAILED) _exit(3);
fill(blocks[i], size, (unsigned)i * 77u + 1u);
}
if (mprotect(blocks[2], size, PROT_READ) != 0) _exit(4);
pthread_t t[THREADS];
for (long i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, work, (void *)i);
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
_exit(0);
}
while (shared->progress < 50) nap(10);
long before = rss_kb(child);
if (undumpable) {
shared->quiet = 1;
for (int waited = 0; __atomic_load_n(&shared->quieted, __ATOMIC_ACQUIRE) < THREADS && waited < 5000; waited += 1) nap(1);
if (__atomic_load_n(&shared->quieted, __ATOMIC_ACQUIRE) < THREADS) {
// a reader still scanning would fault pages back in before the resident set is measured
shared->stop = 1;
kill(child, SIGKILL);
waitpid(child, NULL, 0);
return 5;
}
}
int stale = argc > 3 && !strcmp(argv[3], "stale");
long stale_ack = 0, stale_ran = 0;
if (stale) {
put(".resume", "1"); // resumed already: this request comes too late
put(".hold", "4 0");
kill(child, SIGURG);
for (long waited = 0; waited < 2000 && !stale_ack; waited += 20) {
char path[512];
snprintf(path, sizeof(path), "%s.ack.%d", ctl, child);
stale_ack = access(path, F_OK) == 0; // any acknowledgement, even an empty or cancelled one
nap(20);
}
long at = shared->progress;
nap(500);
stale_ran = shared->progress - at;
}
// a request asked under the current count, which the same handler answers
put(".hold", stale ? "4 1" : "4 0");
kill(child, SIGURG);
if (argc > 3 && (!strcmp(argv[3], "killspill") || !strcmp(argv[3], "killrestore"))) {
// The helper dies while it writes the pages out or reads them back: no owner thread may run after that.
int restore = !strcmp(argv[3], "killrestore");
long low = before, caught = 0;
if (restore) {
if (wait_for(".ack.", child, 20000) > 0) low = rss_kb(child);
put(".resume", "1");
}
for (int waited = 0; !caught && waited < 20000; waited++) {
if ((restore ? get(".restored.", child) : get(".ack.", child)) >= 0) break; // finished before it was caught
long rss = rss_kb(child);
if (restore ? rss > low + 16 * 1024 : rss < low - 16 * 1024) caught = 1;
else nap(1);
}
// The helper is stopped inside the phase and the phase is checked again before it is killed, so it cannot
// finish in between.
// The owner's worker is stopped too, as in killhelper: only the kernel's exit kill can end the owner.
pid_t helper = caught ? find_helper(child) : -1;
int stopped = 0;
if (helper > 0) {
kill(child, SIGSTOP);
for (int waited = 0; !stopped && waited < 1000; waited++) {
stopped = thread_in_state(child, 'T');
if (!stopped) nap(1);
}
kill(helper, SIGSTOP);
int held = 0;
for (int waited = 0; !held && waited < 1000; waited++) {
held = thread_in_state(helper, 'T');
if (!held) nap(1);
}
long rss = rss_kb(child);
int done = (restore ? get(".restored.", child) : get(".ack.", child)) >= 0;
caught = held && !done && (restore ? rss > low + 16 * 1024 : rss < low - 16 * 1024);
}
long at = shared->touched, errors = shared->errors;
if (helper > 0) kill(helper, SIGKILL);
int status = 0, waited = 0, died;
while (!(died = waitpid(child, &status, WNOHANG) == child) && waited < 2000) {
nap(1);
waited += 1;
}
if (!died) {
kill(child, SIGKILL);
waitpid(child, &status, 0);
}
printf("caught=%ld helper=%d stopped=%d died=%d exit=%d moved=%ld errors=%ld\n", caught, (int)helper, stopped, died,
WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status), shared->touched - at,
shared->errors - errors);
return 0;
}
long spilled = wait_for(".ack.", child, 20000);
if (argc > 3 && !strcmp(argv[3], "killhelper")) {
// the helper dies holding pages it dropped: the owner must die with it rather than run without them
// The owner's worker, the one thread the helper does not trace, is group-stopped first: it cannot reap the
// helper and kill the owner itself, so only the kernel's PTRACE_O_EXITKILL can end the owner.
pid_t helper = find_helper(child);
kill(child, SIGSTOP);
int stopped = 0;
for (int waited = 0; !stopped && waited < 1000; waited += 10) {
stopped = thread_in_state(child, 'T');
if (!stopped) nap(10);
}
if (helper > 0) kill(helper, SIGKILL);
int status = 0, waited = 0, died;
while (!(died = waitpid(child, &status, WNOHANG) == child) && waited < 2000) {
nap(10);
waited += 10;
}
if (!died) {
kill(child, SIGKILL);
waitpid(child, &status, 0);
}
printf("spilled=%ld helper=%d stopped=%d waited=%d died=%d exit=%d\n", spilled, (int)helper, stopped, waited,
died, WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status));
return 0;
}
long after = rss_kb(child);
shared->quiet = 0;
long frozen_at = shared->progress;
nap(500);
long frozen_now = shared->progress;
put(".resume", stale ? "2" : "1");
long restored = spilled > 0 ? wait_for(".restored.", child, 20000) : 0;
for (int waited = 0; shared->progress == frozen_now && waited < 10000; waited += 10) nap(10);
long resumed = shared->progress;
long back = rss_kb(child);
shared->stop = 1;
int status = 0;
waitpid(child, &status, 0);
printf("before=%ld after=%ld back=%ld spilled=%ld restored=%ld frozen=%ld resumed=%ld errors=%ld exit=%d "
"stale=%ld stale_ran=%ld\n",
before, after, back, spilled, restored, frozen_now - frozen_at, resumed - frozen_now, shared->errors,
WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status), stale_ack, stale_ran);
return 0;
}
"""
def _fields(text):
return {k: int(v) for k, v in (part.split("=") for part in text.split())}
@unittest.skipUnless(platform.machine() == "aarch64" and shutil.which("cc"), "the spill runs only on arm64")
class ZramSpillPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
cls.ctl = cls.dir / "ctl"
lib = cls.dir / "libzram.so"
prog = cls.dir / "spill"
(cls.dir / "spill.c").write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-shared", "-fPIC", f'-DZR_CTL="{cls.ctl}"', "-o", str(lib),
str(PRELOAD / "zram.c")], check=True)
subprocess.run(["cc", "-O2", "-pthread", "-o", str(prog), str(cls.dir / "spill.c")], check=True)
cls.lib, cls.prog = lib, prog
cls.can_trace = subprocess.run([str(prog), "probe"]).returncode == 0
cls.can_page_out = subprocess.run([str(prog), "pageout"]).returncode == 0
def need_tracing(self):
if not self.can_trace:
self.skipTest("this host does not let a child seize its parent (Yama ptrace_scope)")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, ignore_errors=True)
def run_spill(self, *extra):
self.ctl.write_text("0")
env = dict(os.environ, LD_PRELOAD=str(self.lib))
env.pop("DDNATV_ROOT", None)
out = subprocess.run([str(self.prog), str(self.ctl), "64", *extra], env=env, check=True,
capture_output=True, text=True, timeout=90).stdout
return _fields(out)
def test_spills_to_disk_holds_every_thread_and_restores_intact(self):
self.need_tracing()
r = self.run_spill()
self.assertEqual(r["exit"], 0)
self.assertGreater(r["spilled"], 200 * 1024)
self.assertLess(r["after"], r["before"] - 200 * 1024)
self.assertEqual(r["frozen"], 0)
self.assertGreaterEqual(r["restored"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_a_thread_that_blocks_every_signal_is_held_too(self):
self.need_tracing()
r = self.run_spill("block")
self.assertEqual(r["exit"], 0)
self.assertGreater(r["spilled"], 200 * 1024)
self.assertEqual(r["frozen"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_a_request_that_arrives_after_the_resume_is_dropped(self):
r = self.run_spill("stale")
self.assertEqual(r["exit"], 0)
self.assertEqual(r["stale"], 0) # no acknowledgement of any kind: nothing was held or written
self.assertGreater(r["stale_ran"], 0) # it kept running throughout
# the next request, asked under the current count, is answered by the same handler
self.assertGreaterEqual(r["spilled"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_an_owner_dies_with_a_helper_that_dies_holding_its_pages(self):
self.need_tracing()
r = self.run_spill("killhelper")
self.assertGreater(r["spilled"], 0)
self.assertGreater(r["helper"], 0)
# the worker was stopped before the helper died, so the kernel, not the worker, ended the owner
self.assertEqual(r["stopped"], 1)
self.assertEqual(r["died"], 1)
self.assertEqual(r["exit"], 128 + 9)
def test_no_owner_thread_runs_after_its_helper_dies_mid_spill(self):
self.need_tracing()
r = self.run_spill("killspill")
self.assertEqual(r["caught"], 1) # the helper was killed while it was still writing
self.assertEqual(r["stopped"], 1)
self.assertEqual(r["died"], 1)
self.assertEqual(r["exit"], 128 + 9)
self.assertEqual(r["moved"], 0)
self.assertEqual(r["errors"], 0)
def test_no_owner_thread_runs_after_its_helper_dies_mid_read_back(self):
self.need_tracing()
r = self.run_spill("killrestore")
self.assertEqual(r["caught"], 1) # the helper was killed while it was still reading back
self.assertEqual(r["stopped"], 1)
self.assertEqual(r["died"], 1)
self.assertEqual(r["exit"], 128 + 9)
self.assertEqual(r["moved"], 0)
self.assertEqual(r["errors"], 0)
def test_a_process_that_cannot_be_traced_falls_back_to_zram(self):
r = self.run_spill("undumpable")
self.assertEqual(r["exit"], 0)
self.assertEqual(r["spilled"], 0)
# the fallback pages out to zram before it answers: where the host can page out, the resident set
# has shrunk by then
if self.can_page_out:
self.assertLess(r["after"], r["before"] - 64 * 1024)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -7,10 +7,10 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde
- `build-debs.sh` (run in an `ubuntu:26.04` container on an arm64 runner) rebuilds two Ubuntu source
packages: Mesa with `-Dfreedreno-kmds=msm,kgsl`, so Turnip and freedreno reach Android's
`/dev/kgsl-3d0`, and KWin with `patches/kwin` (nested desktop scale, an explicit render node,
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds KGSL
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7).
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds the KGSL
device numbers for WSI (from [Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)).
KGSL UBWC 5/6 and Icenowy Zheng's Zink fix that keeps the Imagination depth/stencil swizzle off
colour views (Mesa d55418dae7) are in Ubuntu's Mesa 26.2 and no longer patched.
Zink also reclaims the memory a client freed once it has been idle for a second: otherwise only its
next allocation does, and Steam's UI behind a game held 250 MiB more of unswappable GPU memory.
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more