mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
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>
This commit is contained in:
40 files changed
+13520
-77
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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.
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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>
|
||||
@@ -18,6 +19,9 @@
|
||||
#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
|
||||
@@ -538,13 +542,40 @@ 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) {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user