Files
DroidDeck/tools/tests/test_droiddeck_fex.py
T
2d25fb91c5 Run Easy Anti-Cheat and BattlEye games on x86-64 DroidDeck-Proton under FEX (#3641)
* FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* Update FEX before deciding anti-cheat routing

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

* Leave MAP_FIXED_NOREPLACE above the host limit to the host

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

* Translate only pointer syscall arguments into high guest memory

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

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

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

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

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

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

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

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

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

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

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

* Serve memory trim requests while syscall user dispatch blocks

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

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

* Allow syscalls for a forwarded prctl while dispatch blocks

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

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

* Merge high regions after protection changes and translate message batches

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

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

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

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

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

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

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

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

* Send translated message batches one message at a time

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

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

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

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

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

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

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

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

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

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

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

* Defer user signals while guest high memory mappings are held

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

* Rebase the FEX patch series onto FEX-2612

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

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

* FEX: submit aio control blocks through private host copies

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

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

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

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

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

* Kept AIO completions and key stores stable against sibling remaps

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

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

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

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

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

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

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

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

---------

Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com>
Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>
2026-12-05 02:26:42 -05:00

1611 lines
91 KiB
Python

import contextlib
import gzip
import io
import json
import os
import runpy
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
FEX = runpy.run_path(str(BIN / "droiddeck-fex"))
G = FEX["main"].__globals__
def elf(machine, data=1, size=64):
head = bytearray(size)
head[0:4] = b"\x7fELF"
head[4] = 2
head[5] = data
struct.pack_into("<H" if data == 1 else ">H", head, 18, machine)
return bytes(head)
class FexTestCase(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.home = self.tmp / "home"
self.steam = self.home / ".local/share/Steam"
(self.steam / "steamapps/common").mkdir(parents=True)
state = self.home / ".local/share/droiddeck-fex"
patches = {
"HOME": str(self.home),
"STEAM_ROOT": str(self.steam),
"LIBRARIES": (str(self.tmp / "sd"),),
"STATE": str(state),
"CONFIG_DIR": str(state / "config"),
"DATA_DIR": str(state / "data"),
"CACHE_DIR": str(self.home / ".cache/droiddeck-fex"),
"STATUS_FILE": str(state / "status.json"),
"WANTED": str(self.home / ".config/droiddeck/fex-wanted"),
"PRELOADS": str(self.tmp / "preloads"),
"HOST_PRELOAD": str(self.tmp / "ld.so.preload"),
"DEVICE_FONTS": str(self.tmp / "android-fonts"),
"FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"),
"OWN_FEX": str(self.tmp / "own"),
"OWN_FEX_TAG": str(self.tmp / "own/share/fex-emu/.droiddeck-tag"),
}
patcher = mock.patch.dict(G, patches)
patcher.start()
self.addCleanup(patcher.stop)
def write(self, path, data=b"", mode=0o644):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data if isinstance(data, bytes) else data.encode())
path.chmod(mode)
return path
def fex_tool(self, library=None, server=True, thunks=True):
tool = Path(library or self.steam) / "steamapps/common/FEX-Emu"
self.write(tool / "usr/bin/FEX", elf(183), 0o755)
if server:
self.write(tool / "usr/bin/FEXServer", elf(183), 0o755)
if thunks:
(tool / "usr/lib/aarch64-linux-gnu/fex-emu/HostThunks").mkdir(parents=True)
(tool / "usr/share/fex-emu/GuestThunks").mkdir(parents=True)
self.write(tool / "usr/share/fex-emu/ThunksDB.json", "{}")
self.write(Path(library or self.steam) / "steamapps/appmanifest_3127680.acf", '"AppState" { "installdir" "FEX-Emu" }')
return tool
def runtime(self, version="3.0.20260805.254768", lines=None, app="1628350", folder="SteamLinuxRuntime_sniper",
prefix="sniper_platform_"):
runtime = self.steam / "steamapps/common" / folder
platform = runtime / (prefix + version)
files = platform / "files"
self.write(files / "lib/x86_64-linux-gnu/libc.so.6", elf(62))
self.write(files / "ab/cdef-1.bin", b"blob")
self.write(files / "share/ca/real.crt", b"cert")
mtree = lines or [
"#mtree",
". type=dir",
"./bin type=dir",
"./lib64 type=dir",
"./lib64/ld-linux-x86-64.so.2 type=link link=/usr/lib/x86_64-linux-gnu/ld-2.31.so",
"./lib/x86_64-linux-gnu/libc.so.6 type=file mode=644 size=64",
"./bin/\\133 type=file mode=755 size=4 contents=./ab/cdef-1.bin",
"./share/ca/Na\\075me.crt type=link link=real.crt",
"./etc/ssl/cert.pem type=link link=/etc/ssl/certs/ca.pem",
]
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
out.write("\n".join(mtree) + "\n")
self.write(self.steam / ("steamapps/appmanifest_%s.acf" % app), '"AppState" { "installdir" "%s" }' % folder)
return platform
def steamrt4(self):
return self.runtime("4.0.20260928.262390", app="4183110", folder="SteamLinuxRuntime_4", prefix="steamrt4_platform_")
def proton(self, require):
proton = self.steam / "steamapps/common/Proton - Experimental"
self.write(proton / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/proton %%verb%%"\n "require_tool_appid" "%s"\n}\n' % require)
return self.write(proton / "proton", "#!/usr/bin/env python3\n", 0o755)
def graphics(self, sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41", libstdcxx=b"GLIBCXX_3.4.28 GLIBCXX_3.4.33"):
files = Path(sniper) / "files"
x86 = files / "lib/x86_64-linux-gnu"
self.write(x86 / "libc-2.31.so", b"GLIBC_2.2.5 GLIBC_2.31")
os.unlink(x86 / "libc.so.6")
os.symlink("libc-2.31.so", x86 / "libc.so.6")
self.write(x86 / "ld-2.31.so", b"old ld")
os.symlink("ld-2.31.so", x86 / "ld-linux-x86-64.so.2")
self.write(x86 / "libstdc++.so.6", b"GLIBCXX_3.4.28")
self.write(x86 / "libSegFault.so", b"old")
self.write(x86 / "libSDL2-2.0.so.0", b"sdl")
self.write(x86 / "libfoo.so.1.2", b"foo")
os.symlink("libfoo.so.1.2", x86 / "libfoo.so.1")
self.write(x86 / "gconv/OLD.so", b"old gconv")
self.write(files / "lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.31")
self.write(files / "lib/i386-linux-gnu/ld-2.31.so", b"old ld32")
os.symlink("i386-linux-gnu/ld-2.31.so", files / "lib/ld-linux.so.2")
os.unlink(files / "lib64/ld-linux-x86-64.so.2")
os.symlink("../lib/x86_64-linux-gnu/ld-2.31.so", files / "lib64/ld-linux-x86-64.so.2")
platform = self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390"
provided = platform / "files/lib/x86_64-linux-gnu"
self.write(provided / "libc.so.6", libc)
self.write(provided / "libstdc++.so.6", libstdcxx)
self.write(provided / "ld-linux-x86-64.so.2", b"new ld")
self.write(provided / "gconv/NEW.so", b"new gconv")
self.write(platform / "files/lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.41")
self.write(platform / "files/lib/i386-linux-gnu/ld-linux.so.2", b"new ld32")
for arch in ("x86_64", "i386"):
for name in ("libssl.so.3", "libcrypto.so.3"):
self.write(platform / "files/lib" / (arch + "-linux-gnu") / name, arch.encode() + name.encode())
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
out.write("#mtree\n. type=dir\n")
self.write(self.steam / "steamapps/appmanifest_4183110.acf", '"AppState" { "installdir" "SteamLinuxRuntime_4" }')
return platform
def quiet(self, function, *args):
with contextlib.redirect_stderr(io.StringIO()) as err:
return function(*args), err.getvalue()
class ArchitectureTest(FexTestCase):
def test_elf_machines(self):
self.assertEqual(FEX["elf_arch"](self.write(self.tmp / "a", elf(62))), "x86_64")
self.assertEqual(FEX["elf_arch"](self.write(self.tmp / "b", elf(3))), "i386")
self.assertEqual(FEX["elf_arch"](self.write(self.tmp / "c", elf(183))), "arm64")
self.assertEqual(FEX["elf_arch"](self.write(self.tmp / "d", elf(62, data=2))), "x86_64")
self.assertEqual(FEX["elf_arch"](self.write(self.tmp / "e", elf(8))), "other")
self.assertIsNone(FEX["elf_arch"](self.write(self.tmp / "f", "#!/bin/sh\n")))
self.assertIsNone(FEX["elf_arch"](self.tmp / "missing"))
def test_a_script_follows_the_programs_beside_it(self):
game = self.tmp / "game"
script = self.write(game / "start.sh", "#!/bin/bash\n./bin/game\n")
self.assertFalse(FEX["needs_fex"](str(script)))
self.write(game / "bin/game.x86_64", elf(62), 0o755)
self.assertTrue(FEX["needs_fex"](str(script)))
self.assertTrue(FEX["needs_fex"](str(game)))
self.write(game / "bin/game.arm64", elf(183), 0o755)
self.assertFalse(FEX["needs_fex"](str(script)))
self.assertTrue(FEX["needs_fex"](str(game / "bin/game.x86_64")))
self.assertFalse(FEX["needs_fex"](str(game / "bin/game.arm64")))
def test_the_scan_stops_at_its_depth(self):
game = self.tmp / "deep"
self.write(game / "a/b/c/d/e/game", elf(62), 0o755)
self.assertFalse(FEX["needs_fex"](str(game)))
self.write(game / "a/b/game", elf(62), 0o755)
self.assertTrue(FEX["needs_fex"](str(game)))
def test_appimage_offset_is_the_end_of_the_section_headers(self):
head = bytearray(elf(62))
struct.pack_into("<Q", head, 0x28, 1000)
struct.pack_into("<HH", head, 0x3A, 64, 30)
self.assertEqual(FEX["appimage_offset"](self.write(self.tmp / "x.AppImage", bytes(head))), 1000 + 64 * 30)
head = bytearray(elf(3))
head[4] = 1
struct.pack_into("<I", head, 0x20, 500)
struct.pack_into("<HH", head, 0x2E, 40, 10)
self.assertEqual(FEX["appimage_offset"](self.write(self.tmp / "y.AppImage", bytes(head))), 900)
def test_run_options(self):
self.assertEqual(FEX["parse_run"](["--mode", "on", "--for", "/x", "--", "a", "--mode"]), ("on", "/x", ["a", "--mode"]))
self.assertEqual(FEX["parse_run"](["a"]), ("auto", None, ["a"]))
with self.assertRaises(ValueError):
FEX["parse_run"](["--mode", "maybe", "a"])
with self.assertRaises(ValueError):
FEX["parse_run"](["--bogus", "a"])
class LocateTest(FexTestCase):
def test_tools_are_found_in_any_library(self):
self.assertIsNone(FEX["fex_install"]() if not os.access("/usr/bin/FEX", os.X_OK) else None)
sd = self.tmp / "sd"
(sd / "steamapps/common").mkdir(parents=True)
tool = self.fex_tool(sd)
fex = FEX["fex_install"]()
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(tool / "usr/bin/FEX"), str(tool / "usr/bin/FEXServer"), True))
self.assertTrue(fex["host_thunks"].endswith("HostThunks") and fex["guest_thunks"].endswith("GuestThunks") and fex["thunks_db"])
def own_fex(self, tag, loads=True):
own = self.tmp / "own"
self.write(own / "bin/FEX", mode=0o755)
self.write(own / "bin/FEXServer", mode=0o755)
self.write(own / "share/fex-emu/.droiddeck-tag", tag + "\n")
listing = b"libc.so.6 => /usr/lib/libc.so.6\n" if loads else b"libxxhash.so.0 => not found\n"
patcher = mock.patch.object(G["subprocess"], "run", lambda args, **kw: subprocess.CompletedProcess(args, 0, listing))
patcher.start()
self.addCleanup(patcher.stop)
return own
def test_an_own_build_that_no_longer_loads_is_installed_again_and_skipped(self):
tool = self.fex_tool(self.steam)
self.own_fex("fex-2610-r7", loads=False)
calls = []
with mock.patch.dict(os.environ, {"DD_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 1):
FEX["update_own_fex"]()
self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls)
self.assertEqual(FEX["fex_install"]()["bin"], str(tool / "usr/bin/FEX"))
def test_droiddeck_s_own_build_comes_before_the_steam_tool(self):
self.fex_tool(self.steam)
own = self.own_fex("fex-2610-r7")
fex = FEX["fex_install"]()
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(own / "bin/FEX"), str(own / "bin/FEXServer"), False))
def test_the_build_the_session_names_is_installed_once(self):
self.own_fex("fex-2610-r6")
calls = []
with mock.patch.dict(os.environ, {"DD_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0):
FEX["update_own_fex"]()
self.write(self.tmp / "own/share/fex-emu/.droiddeck-tag", "fex-2610-r7\n")
FEX["update_own_fex"]()
self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls)
def test_a_failed_build_waits_an_hour_unless_the_session_names_another(self):
self.own_fex("fex-2610-r6")
Path(G["STATE"]).mkdir(parents=True, exist_ok=True)
calls = []
tag = {"DD_FEX_TAG": "fex-2610-r7"}
with mock.patch.dict(os.environ, tag), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(os.environ["DD_FEX_TAG"]) or 1):
FEX["update_own_fex"]()
FEX["update_own_fex"]()
failed = Path(G["STATE"]) / "update-failed"
os.utime(failed, (failed.stat().st_atime, failed.stat().st_mtime - 3601))
FEX["update_own_fex"]()
os.environ["DD_FEX_TAG"] = "fex-2610-r8"
FEX["update_own_fex"]()
self.assertEqual(["fex-2610-r7", "fex-2610-r7", "fex-2610-r8"], calls)
def test_a_missing_updater_falls_back_to_the_fex_already_here(self):
self.fex_tool(self.steam)
Path(G["STATE"]).mkdir(parents=True, exist_ok=True)
with mock.patch.dict(os.environ, {"DD_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", mock.Mock(side_effect=FileNotFoundError)):
FEX["update_own_fex"]()
self.assertEqual(FEX["fex_install"]()["bin"], str(self.steam / "steamapps/common/FEX-Emu/usr/bin/FEX"))
def test_no_build_is_installed_without_one_from_the_session(self):
calls = []
with mock.patch.dict(os.environ, {}, clear=False), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0):
os.environ.pop("DD_FEX_TAG", None)
FEX["update_own_fex"]()
self.assertEqual([], calls)
def test_library_folders_are_read(self):
other = self.tmp / "other"
(other / "steamapps/common").mkdir(parents=True)
self.write(self.steam / "steamapps/libraryfolders.vdf", '"libraryfolders" { "1" { "path" "%s" } }' % other)
tool = self.fex_tool(other)
self.assertEqual(FEX["app_dir"]("3127680"), str(tool))
def test_the_newest_runtime_platform_wins(self):
self.runtime("3.0.20260805.254768")
newer = self.runtime("3.0.20261001.1")
self.assertEqual(FEX["runtime_platform"](), str(newer))
class PrepareTest(FexTestCase):
def test_materialize_links_the_tree_in_place(self):
platform = self.runtime()
files = platform / "files"
self.assertTrue(FEX["materialize"](str(platform)))
self.assertEqual(os.readlink(files / "lib64/ld-linux-x86-64.so.2"), "../lib/x86_64-linux-gnu/ld-2.31.so")
self.assertEqual(os.readlink(files / "bin/["), "../ab/cdef-1.bin")
self.assertEqual((files / "bin/[").read_bytes(), b"blob")
self.assertEqual((files / "share/ca/Na=me.crt").read_bytes(), b"cert")
self.assertEqual(os.readlink(files / "etc/ssl/cert.pem"), "certs/ca.pem")
self.assertEqual(os.readlink(files / "usr"), ".")
self.assertEqual((files / "usr/lib/x86_64-linux-gnu/libc.so.6").read_bytes()[:4], b"\x7fELF")
self.assertFalse(FEX["materialize"](str(platform)))
os.unlink(files / "bin/[")
os.utime(platform / "usr-mtree.txt.gz", ns=(1, 1))
self.assertTrue(FEX["materialize"](str(platform)))
self.assertTrue(os.path.islink(files / "bin/["))
def test_materialize_ignores_paths_outside_the_tree(self):
platform = self.runtime(lines=["./../escape type=link link=x", "/abs type=dir", "./ok type=link link=x"])
FEX["materialize"](str(platform))
self.assertFalse((platform / "escape").exists() or os.path.islink(platform / "escape"))
self.assertTrue(os.path.islink(platform / "files/ok"))
def test_preloads_mirror_the_host_list(self):
root = self.tmp / "root"
for arch in ("x86_64", "i386"):
for name in ("libddsession.so", "libfakeinput.so"):
self.write(self.tmp / "preloads" / arch / name, arch.encode() + name.encode())
self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", b"pin")
self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libddsession.so\n/usr/local/lib/libfakeinput.so\n")
FEX["install_preloads"](str(root))
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so.1").read_bytes(), b"pin")
self.assertEqual(os.readlink(root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so"), "libvulkan.so.1")
self.assertEqual((root / "etc/ld.so.preload").read_text(),
"/usr/$LIB/droiddeck/libddsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n")
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfakeinput.so").read_bytes(), b"i386libfakeinput.so")
self.assertEqual((root / "etc/asound.conf").read_text(),
"pcm.!default {\n type pulse\n}\nctl.!default {\n type pulse\n}\n")
self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libddsession.so\n")
FEX["install_preloads"](str(root))
self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libddsession.so\n")
def test_only_x86_loaders_preload_the_fault_report(self):
root = self.tmp / "root"
self.write(self.tmp / "preloads/x86_64/libfaultreport.so", b"report64")
FEX["install_preloads"](str(root))
self.assertNotIn("libfaultreport.so", (root / "etc/ld.so.preload").read_text())
self.write(self.tmp / "preloads/i386/libfaultreport.so", b"report32")
FEX["install_preloads"](str(root))
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/libfaultreport.so").read_bytes(), b"report64")
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfaultreport.so").read_bytes(), b"report32")
self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libfaultreport.so\n")
def test_device_fonts_reach_the_x86_runtime(self):
root = self.tmp / "root"
conf = root / str(self.tmp / "66-droiddeck-device-fonts.conf").lstrip("/")
rules = '<?xml version="1.0"?><fontconfig>\n<match target="pattern"></match>\n</fontconfig>\n'
self.write(self.tmp / "66-droiddeck-device-fonts.conf", rules)
FEX["install_fonts"](str(root))
self.assertFalse(conf.exists())
(self.tmp / "android-fonts").mkdir()
FEX["install_fonts"](str(root))
self.assertEqual(conf.read_text(), '<?xml version="1.0"?><fontconfig>\n<dir>%s</dir>\n<match target="pattern"></match>\n</fontconfig>\n'
% (self.tmp / "android-fonts"))
(self.tmp / "66-droiddeck-device-fonts.conf").unlink()
FEX["install_fonts"](str(root))
self.assertFalse(conf.exists())
def test_config_turns_thunks_on_only_when_complete(self):
FEX["write_config"]({"host_thunks": "/h", "guest_thunks": "/g", "thunks_db": "/db"}, "/root")
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(config, {"Config": {"RootFS": "/root", "ThunkHostLibs": "/h", "ThunkGuestLibs": "/g"}, "ThunksDB": {"GL": 1, "Vulkan": 1}})
FEX["write_config"]({"host_thunks": None, "guest_thunks": "/g", "thunks_db": "/db"}, "/root")
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(config, {"Config": {"RootFS": "/root"}})
def test_missing_pieces_are_asked_for(self):
with mock.patch.dict(G, {"fex_install": lambda: None, "steam_running": lambda: False}):
fex, said = self.quiet(FEX["prepare"])
self.assertIsNone(fex)
self.assertIn("FEX (Steam app 3127680)", said)
self.assertIn("Steam Linux Runtime 3.0", said)
self.assertTrue(said.startswith("droiddeck-fex: x86 Linux programs need "))
self.assertTrue((self.home / ".config/droiddeck/fex-wanted").is_file())
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertFalse(status["ready"])
def test_a_missing_steam_runtime_4_is_named(self):
self.fex_tool()
self.runtime()
with mock.patch.dict(G, {"steam_running": lambda: False}):
fex, said = self.quiet(FEX["prepare"], "4183110")
self.assertIsNone(fex)
self.assertIn("Steam Linux Runtime 4.0 (steamrt4, Steam app 4183110)", said)
self.assertNotIn("FEX (Steam app", said)
def test_the_x86_runtime_gets_its_own_steam_client_link(self):
self.fex_tool()
platform = self.runtime()
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
self.write(self.steam / "linux64/steamclient.so", elf(62))
self.write(self.steam / "linux32/steamclient.so", elf(3))
(self.home / ".steam").mkdir()
os.symlink(self.steam / "linuxarm64", self.home / ".steam/sdk64")
self.quiet(FEX["prepare"])
guest = platform / "files" / str(self.home).lstrip("/") / ".steam"
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(os.readlink(self.home / ".steam/sdk64"), str(self.steam / "linux64"))
def test_a_ready_install_is_prepared(self):
tool = self.fex_tool()
platform = self.runtime()
self.write(self.home / ".config/droiddeck/fex-wanted", "1\n")
fex, said = self.quiet(FEX["prepare"])
self.assertEqual(fex["bin"], str(tool / "usr/bin/FEX"))
self.assertIn("prepared sniper_platform_", said)
self.assertTrue(os.path.islink(platform / "files/usr"))
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertEqual((status["ready"], status["runtime"], status["thunks"]), (True, str(platform), True))
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
self.assertNotIn("prepared", self.quiet(FEX["prepare"])[1])
def test_a_newer_runtime_supplies_the_c_and_cxx_libraries(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
fex, said = self.quiet(FEX["prepare"])
root = self.home / ".local/share/droiddeck-fex/rootfs"
self.assertIn("built the x86 runtime from sniper_platform_", said)
self.assertEqual(fex["rootfs"], str(root))
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(config["Config"]["RootFS"], str(root))
x86 = root / "lib/x86_64-linux-gnu"
self.assertEqual((x86 / "libc.so.6").read_bytes(), b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41")
self.assertEqual((x86 / "libstdc++.so.6").read_bytes(), b"GLIBCXX_3.4.28 GLIBCXX_3.4.33")
self.assertEqual((x86 / "ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual((x86 / "gconv/NEW.so").read_bytes(), b"new gconv")
self.assertEqual((root / "lib/i386-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.41")
self.assertEqual((x86 / "libssl.so.3").read_bytes(), b"x86_64libssl.so.3")
self.assertEqual((x86 / "libcrypto.so.3").read_bytes(), b"x86_64libcrypto.so.3")
self.assertEqual((root / "lib/i386-linux-gnu/libssl.so.3").read_bytes(), b"i386libssl.so.3")
self.assertEqual((root / "lib/i386-linux-gnu/libcrypto.so.3").read_bytes(), b"i386libcrypto.so.3")
self.assertEqual((x86 / "libSDL2-2.0.so.0").read_bytes(), b"sdl")
self.assertEqual(os.readlink(x86 / "libfoo.so.1"), "libfoo.so.1.2")
self.assertEqual((x86 / "libfoo.so.1").read_bytes(), b"foo")
for stale in ("libc-2.31.so", "ld-2.31.so", "libSegFault.so"):
self.assertFalse(os.path.lexists(x86 / stale), stale)
self.assertEqual(os.readlink(root / "lib/ld-linux.so.2"), "i386-linux-gnu/ld-linux.so.2")
self.assertEqual((root / "lib/ld-linux.so.2").read_bytes(), b"new ld32")
self.assertEqual(os.readlink(root / "lib64/ld-linux-x86-64.so.2"), "../lib/x86_64-linux-gnu/ld-linux-x86-64.so.2")
self.assertEqual((root / "lib64/ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual(os.readlink(root / "usr"), ".")
self.assertEqual((root / "usr/bin/[").read_bytes(), b"blob")
self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.2.5 GLIBC_2.31")
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertEqual(status["graphics"], str(provider))
self.assertNotIn("built", self.quiet(FEX["prepare"])[1])
os.utime(provider / "usr-mtree.txt.gz", ns=(1, 1))
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"])
def test_wayland_and_its_ffi_dependency_come_from_the_newer_runtime(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
names = ("libwayland-client.so.0", "libwayland-cursor.so.0", "libwayland-egl.so.1",
"libwayland-server.so.0", "libffi.so.8")
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
base = sniper / "files/lib" / arch / name
if name != "libffi.so.8":
self.write(base, b"old ABI")
source = provider / "files/lib" / arch / name
self.write(str(source) + ".new", b"new ABI " + name.encode())
os.symlink(name + ".new", source)
self.write(sniper / "files/lib" / arch / "libffi.so.7", b"old ffi")
fex, _ = self.quiet(FEX["prepare"])
root = Path(fex["rootfs"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
library = root / "lib" / arch / name
expected = sniper if name == "libwayland-cursor.so.0" else provider
self.assertEqual(library.read_bytes(), b"old ABI" if expected == sniper else b"new ABI " + name.encode())
self.assertEqual((root / "lib" / arch / "libffi.so.7").read_bytes(), b"old ffi")
self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"old ABI")
@unittest.skipUnless(shutil.which("cc"), "C compiler unavailable")
def test_bundled_library_resolves_the_new_wayland_symbol(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
base = sniper / "files/lib/x86_64-linux-gnu"
newer = provider / "files/lib/x86_64-linux-gnu"
source = self.tmp / "library.c"
self.write(newer / "libffi.so.8", b"ffi")
for folder, symbol in ((base, "wl_proxy_marshal"), (newer, "wl_proxy_marshal_flags")):
source.write_text("void *%s(void) { return 0; }\n" % symbol)
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libwayland-client.so.0",
"-o", str(folder / "libwayland-client.so.0"), str(source)], check=True, capture_output=True)
fex, _ = self.quiet(FEX["prepare"])
root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu"
source.write_text("extern void *wl_proxy_marshal_flags(void);\nvoid *probe(void) { return wl_proxy_marshal_flags(); }\n")
probe = self.tmp / "libprobe.so"
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source),
"-L" + str(newer), "-l:libwayland-client.so.0", "-Wl,-rpath," + str(root)],
check=True, capture_output=True)
command = [sys.executable, "-c",
"import ctypes,sys; "
"ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; "
"ctypes.CDLL(sys.argv[1]).probe()",
str(probe)]
env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")}
broken = subprocess.run(command + [str(base / "libwayland-client.so.0")], env=env, capture_output=True, text=True)
self.assertNotEqual(broken.returncode, 0)
self.assertIn("undefined symbol: wl_proxy_marshal_flags", broken.stderr)
fixed = subprocess.run(command, env=env, capture_output=True, text=True)
self.assertEqual(fixed.returncode, 0, fixed.stderr)
def test_gbm_and_its_dependencies_use_the_newer_runtime_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
names = ("libgbm.so.1", "libdrm.so.2", "libexpat.so.1")
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
self.write(sniper / "files/lib" / arch / name, b"old ABI")
self.write(provider / "files/lib" / arch / name, b"new ABI " + name.encode())
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode())
def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch")
self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode())
os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode())
self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch")
def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in ("libgbm.so.1", "libdrm.so.2"):
self.write(sniper / "files/lib" / arch / name, b"base")
self.write(provider / "files/lib" / arch / name, b"provider")
os.symlink("missing-expat.so", provider / "files/lib" / arch / "libexpat.so.1")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
self.assertEqual((root / "libgbm.so.1").read_bytes(), b"base")
self.assertEqual((root / "libdrm.so.2").read_bytes(), b"provider")
@unittest.skipUnless(shutil.which("cc"), "C compiler unavailable")
def test_bundled_library_resolves_the_new_gbm_symbol(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
base = sniper / "files/lib/x86_64-linux-gnu"
newer = provider / "files/lib/x86_64-linux-gnu"
source = self.tmp / "gbm.c"
self.write(newer / "libdrm.so.2", b"drm")
self.write(newer / "libexpat.so.1", b"expat")
for folder, symbol in ((base, "gbm_bo_create_with_modifiers"), (newer, "gbm_bo_create_with_modifiers2")):
source.write_text("void *%s(void) { return 0; }\n" % symbol)
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libgbm.so.1",
"-o", str(folder / "libgbm.so.1"), str(source)], check=True, capture_output=True)
fex, _ = self.quiet(FEX["prepare"])
root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu"
source.write_text("extern void *gbm_bo_create_with_modifiers2(void);\n"
"void *probe(void) { return gbm_bo_create_with_modifiers2(); }\n")
probe = self.tmp / "libgbmprobe.so"
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source),
"-L" + str(newer), "-l:libgbm.so.1", "-Wl,-rpath," + str(root)],
check=True, capture_output=True)
command = [sys.executable, "-c",
"import ctypes,sys; "
"ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; "
"ctypes.CDLL(sys.argv[1]).probe()",
str(probe)]
env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")}
broken = subprocess.run(command + [str(base / "libgbm.so.1")], env=env, capture_output=True, text=True)
self.assertNotEqual(broken.returncode, 0)
self.assertIn("undefined symbol: gbm_bo_create_with_modifiers2", broken.stderr)
fixed = subprocess.run(command, env=env, capture_output=True, text=True)
self.assertEqual(fixed.returncode, 0, fixed.stderr)
def test_freetype_and_dependencies_use_the_newer_runtime_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
names = ("libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1",
"libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1")
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
self.write(sniper / "files/lib" / arch / name, b"base")
self.write(provider / "files/lib" / arch / name, b"new")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new")
self.assertEqual((sniper / "files/lib" / arch / name).read_bytes(), b"base")
@unittest.skipUnless(shutil.which("cc"), "C compiler unavailable")
def test_bundled_library_resolves_the_new_freetype_symbol(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
base = sniper / "files/lib/x86_64-linux-gnu"
newer = provider / "files/lib/x86_64-linux-gnu"
source = self.tmp / "freetype.c"
for folder, symbol in ((base, "FT_Init_FreeType"), (newer, "FT_Get_Color_Glyph_Paint")):
source.write_text("void *%s(void) { return 0; }\n" % symbol)
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libfreetype.so.6",
"-o", str(folder / "libfreetype.so.6"), str(source)], check=True, capture_output=True)
fex, _ = self.quiet(FEX["prepare"])
root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu"
source.write_text("extern void *FT_Get_Color_Glyph_Paint(void);\nvoid *probe(void) { return FT_Get_Color_Glyph_Paint(); }\n")
probe = self.tmp / "libprobe.so"
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source),
"-L" + str(newer), "-l:libfreetype.so.6", "-Wl,-rpath," + str(root)],
check=True, capture_output=True)
command = [sys.executable, "-c",
"import ctypes,sys; "
"ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; "
"ctypes.CDLL(sys.argv[1]).probe()", str(probe)]
env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")}
broken = subprocess.run(command + [str(base / "libfreetype.so.6")], env=env, capture_output=True, text=True)
self.assertNotEqual(broken.returncode, 0)
self.assertIn("undefined symbol: FT_Get_Color_Glyph_Paint", broken.stderr)
fixed = subprocess.run(command, env=env, capture_output=True, text=True)
self.assertEqual(fixed.returncode, 0, fixed.stderr)
def test_missing_freetype_provider_keeps_base_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.write(sniper / "files/lib" / arch / "libfreetype.so.6", b"base")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libfreetype.so.6").read_bytes(), b"base")
def test_missing_provider_libraries_keep_the_base_runtime_libraries(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
base = self.write(sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0", b"base wayland")
fex, _ = self.quiet(FEX["prepare"])
self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"base wayland")
def test_provider_symlinks_require_existing_targets_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
base = sniper / "files/lib" / arch
newer = provider / "files/lib" / arch
self.write(base / "libwayland-client.so.0", b"base")
os.symlink("missing-client.so", newer / "libwayland-client.so.0")
os.symlink("missing-ffi.so", newer / "libffi.so.8")
self.write(newer / "wayland-server-real.so", b"provider")
os.symlink("wayland-server-real.so", newer / "libwayland-server.so.0")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
self.assertEqual((root / "libwayland-client.so.0").read_bytes(), b"base")
self.assertFalse(os.path.lexists(root / "libffi.so.8"))
self.assertFalse(os.path.lexists(root / "libwayland-server.so.0"))
def test_wayland_requires_usable_provider_ffi_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for ffi_state in ("missing", "dangling"):
with self.subTest(ffi_state=ffi_state):
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
base = sniper / "files/lib" / arch
newer = provider / "files/lib" / arch
for name in ("libwayland-client.so.0", "libwayland-server.so.0", "libwayland-cursor.so.0"):
self.write(base / name, b"base")
self.write(newer / name, b"provider")
if ffi_state == "dangling":
os.symlink("missing-ffi.so", newer / "libffi.so.8")
marker = self.home / ".local/share/droiddeck-fex/rootfs/.droiddeck-fex"
if marker.exists():
marker.unlink()
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
for name in ("libwayland-client.so.0", "libwayland-server.so.0", "libwayland-cursor.so.0"):
self.assertEqual((root / name).read_bytes(), b"base")
self.assertFalse(os.path.lexists(root / "libffi.so.8"))
def test_wayland_cursor_requires_usable_provider_client_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for client_state in ("missing", "dangling"):
with self.subTest(client_state=client_state):
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
base = sniper / "files/lib" / arch
newer = provider / "files/lib" / arch
self.write(base / "libwayland-client.so.0", b"base client")
self.write(base / "libwayland-cursor.so.0", b"base cursor")
self.write(newer / "libwayland-cursor.so.0", b"provider cursor")
self.write(newer / "libffi.so.8", b"provider ffi")
if client_state == "dangling":
os.symlink("missing-client.so", newer / "libwayland-client.so.0")
marker = self.home / ".local/share/droiddeck-fex/rootfs/.droiddeck-fex"
if marker.exists():
marker.unlink()
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
self.assertEqual((root / "libwayland-client.so.0").read_bytes(), b"base client")
self.assertEqual((root / "libwayland-cursor.so.0").read_bytes(), b"base cursor")
self.assertEqual((root / "libffi.so.8").read_bytes(), b"provider ffi")
def test_restored_provider_clients_rebuild_the_rootfs_without_marker_changes(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.write(sniper / "files/lib" / arch / "libwayland-client.so.0", b"base")
self.write(provider / "files/lib" / arch / "libffi.so.8", b"ffi")
os.symlink("client-real.so", provider / "files/lib" / arch / "libwayland-client.so.0")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libwayland-client.so.0").read_bytes(), b"base")
self.write(provider / "files/lib" / arch / "client-real.so", b"restored")
fex, said = self.quiet(FEX["prepare"])
self.assertIn("built the x86 runtime", said)
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libwayland-client.so.0").read_bytes(), b"restored")
self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
client = provider / "files/lib/i386-linux-gnu/client-real.so"
client.write_bytes(b"updated client")
fex, said = self.quiet(FEX["prepare"])
self.assertIn("built the x86 runtime", said)
self.assertEqual((Path(fex["rootfs"]) / "lib/i386-linux-gnu/libwayland-client.so.0").read_bytes(), b"updated client")
@unittest.skipUnless(shutil.which("cc"), "C compiler unavailable")
def test_base_cursor_works_with_guest_selected_old_client(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
base = sniper / "files/lib/x86_64-linux-gnu"
newer = provider / "files/lib/x86_64-linux-gnu"
source = self.tmp / "cursor.c"
self.write(newer / "libffi.so.8", b"ffi")
for folder, symbol in ((base, "wl_proxy_marshal"), (newer, "wl_proxy_marshal_flags")):
source.write_text("void %s(void) {}\n" % symbol)
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libwayland-client.so.0",
"-o", str(folder / "libwayland-client.so.0"), str(source)], check=True, capture_output=True)
source.write_text("extern void %s(void); void probe(void) { %s(); }\n" % (symbol, symbol))
subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(folder / "libwayland-cursor.so.0"),
str(source), "-L" + str(folder), "-l:libwayland-client.so.0"], check=True, capture_output=True)
fex, _ = self.quiet(FEX["prepare"])
cursor = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-cursor.so.0"
command = [sys.executable, "-c", "import ctypes,sys; ctypes.CDLL(sys.argv[1], mode=ctypes.RTLD_GLOBAL); ctypes.CDLL(sys.argv[2]).probe()", str(base / "libwayland-client.so.0")]
env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")}
broken = subprocess.run(command + [str(newer / "libwayland-cursor.so.0")], env=env, capture_output=True, text=True)
self.assertNotEqual(broken.returncode, 0)
self.assertIn("undefined symbol: wl_proxy_marshal_flags", broken.stderr)
fixed = subprocess.run(command + [str(cursor)], env=env, capture_output=True, text=True)
self.assertEqual(fixed.returncode, 0, fixed.stderr)
def test_the_old_rootfs_layout_is_rebuilt(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
with mock.patch.dict(G, {"ROOTFS_LAYOUT": 6}):
self.quiet(FEX["prepare"])
_, said = self.quiet(FEX["prepare"])
self.assertIn("built the x86 runtime", said)
self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
def test_the_built_x86_runtime_holds_nothing_that_leaves_it(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
os.chmod(sniper / "files/share/ca", 0o750)
self.quiet(FEX["prepare"])
root = (self.home / ".local/share/droiddeck-fex/rootfs").resolve()
self.assertEqual(stat.S_IMODE(os.stat(root / "share/ca").st_mode), 0o750)
entries = 0
for directory, dirs, files in os.walk(root):
for name in dirs + files:
path = Path(directory) / name
entries += 1
if path.is_symlink():
self.assertFalse(os.path.isabs(os.readlink(path)), path)
self.assertTrue(path.resolve().is_relative_to(root), path)
self.assertGreater(entries, 10)
self.assertEqual((root / "bin/[").read_bytes(), b"blob")
self.assertEqual((root / "share/ca/real.crt").read_bytes(), b"cert")
self.assertFalse(os.path.lexists(root / "ab"))
def test_guest_writes_do_not_mutate_runtime_blob_files(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
self.quiet(FEX["prepare"])
root = self.home / ".local/share/droiddeck-fex/rootfs"
marker = root / ".droiddeck-fex"
stamp = marker.read_text()
marker.write_text("3\n" + stamp.partition("\n")[2])
source = sniper / "files/ab/cdef-1.bin"
guest = root / "bin/["
guest.unlink()
os.link(source, guest)
self.assertEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertNotEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
guest.write_bytes(b"guest mutation")
self.assertEqual(source.read_bytes(), b"blob")
self.assertEqual(guest.read_bytes(), b"guest mutation")
def test_a_rebuilt_x86_runtime_refreshes_the_steam_client_links_and_drops_read_only_trees(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
base = sniper / "files"
(base / str(self.home).lstrip("/") / ".steam").mkdir(parents=True)
os.symlink(self.steam / "linuxarm64", base / str(self.home).lstrip("/") / ".steam/sdk64")
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
os.chmod(base / "share/ca", 0o500)
self.addCleanup(os.chmod, base / "share/ca", 0o700)
self.quiet(FEX["prepare"])
rootfs = self.home / ".local/share/droiddeck-fex/rootfs"
os.chmod(rootfs / "share/ca", 0o000)
self.write(self.steam / "linux64/steamclient.so", elf(62))
self.write(self.steam / "linux32/steamclient.so", elf(3))
os.utime(self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390/usr-mtree.txt.gz", ns=(1, 1))
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
guest = rootfs / str(self.home).lstrip("/") / ".steam"
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(sorted(os.listdir(rootfs.parent)), ["config", "lock", "rootfs", "status.json"])
def test_a_runtime_that_is_not_newer_is_left_out(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31", libstdcxx=b"GLIBCXX_3.4.28")
fex, said = self.quiet(FEX["prepare"])
self.assertEqual(fex["rootfs"], str(sniper / "files"))
self.assertIn("has no newer C and C++ libraries than sniper_platform_", said)
self.assertFalse((self.home / ".local/share/droiddeck-fex/rootfs").exists())
def test_x86_steamworks_finds_the_x86_client(self):
for directory, machine in (("linux64", 62), ("linux32", 3), ("linuxarm64", 183)):
self.write(self.steam / directory / "steamclient.so", elf(machine))
sdk = self.home / ".steam"
sdk.mkdir(parents=True)
os.symlink(self.steam / "linuxarm64", sdk / "sdk64")
os.symlink(self.steam / "linuxarm64", sdk / "sdkarm64")
FEX["link_steam_sdk"]()
self.assertEqual(os.readlink(sdk / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(sdk / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(os.readlink(sdk / "sdkarm64"), str(self.steam / "linuxarm64"))
os.unlink(sdk / "sdk32")
os.symlink(self.tmp / "elsewhere", sdk / "sdk32")
self.write(self.tmp / "elsewhere/steamclient.so", elf(3))
FEX["link_steam_sdk"]()
self.assertEqual(os.readlink(sdk / "sdk32"), str(self.tmp / "elsewhere"))
self.assertEqual(sorted(os.listdir(sdk)), ["sdk32", "sdk64", "sdkarm64"])
def test_status_refreshes_what_the_app_reads_once_steam_installed_fex(self):
with mock.patch.dict(G, {"steam_running": lambda: False}):
self.quiet(FEX["prepare"])
status_file = self.home / ".local/share/droiddeck-fex/status.json"
self.assertFalse(json.loads(status_file.read_text())["ready"])
self.fex_tool()
self.runtime()
with contextlib.redirect_stdout(io.StringIO()) as out:
self.assertEqual(0, FEX["main"](["status"]))
self.assertTrue(json.loads(out.getvalue())["ready"])
self.assertTrue(json.loads(status_file.read_text())["ready"])
def test_fex_is_found_at_the_tool_root_too(self):
tool = self.steam / "steamapps/common/FEX-Emu"
self.write(tool / "bin/FEX", elf(183), 0o755)
self.write(tool / "bin/FEXServer", elf(183), 0o755)
self.write(self.steam / "steamapps/appmanifest_3127680.acf", '"AppState" { "installdir" "FEX-Emu" }')
fex = FEX["fex_install"]()
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(tool / "bin/FEX"), str(tool / "bin/FEXServer"), True))
def test_an_installed_tool_without_fex_says_what_it_holds(self):
tool = self.steam / "steamapps/common/FEX-Emu"
self.write(tool / "toolmanifest.vdf", "")
self.write(self.steam / "steamapps/appmanifest_3127680.acf", '"AppState" { "installdir" "FEX-Emu" }')
with mock.patch.dict(G, {"steam_running": lambda: False}), mock.patch("shutil.which", return_value=None), \
mock.patch("os.access", lambda path, mode: False):
fex, said = self.quiet(FEX["prepare"])
self.assertIsNone(fex)
self.assertIn("holds no FEX or FEXInterpreter", said)
self.assertIn("toolmanifest.vdf", said)
def test_a_missing_server_is_not_ready(self):
self.fex_tool(server=False)
self.runtime()
with mock.patch.dict(G, {"steam_running": lambda: False}), mock.patch("shutil.which", return_value=None):
fex, said = self.quiet(FEX["prepare"])
self.assertIsNone(fex)
self.assertIn("FEXServer beside", said)
class ExtractTest(FexTestCase):
def setUp(self):
super().setUp()
self.work = self.tmp / "work"
self.work.mkdir()
self.image = self.write(self.work / "image.AppImage", elf(62) + b"payload", 0o755)
chdir = contextlib.chdir(self.work)
chdir.__enter__()
self.addCleanup(chdir.__exit__, None, None, None)
def uruntime(self, body):
return str(self.write(self.tmp / "uruntime", "#!/bin/sh\n" + body, 0o755))
def test_uruntime_unpacks_an_x86_image_without_fex(self):
tool = self.uruntime('[ "$1" = --appimage-extract ] && [ "$TARGET_APPIMAGE" = "%s" ] || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual((status, said), (0, ""))
self.assertEqual(os.readlink("squashfs-root"), "AppDir")
self.assertTrue(Path("squashfs-root/AppRun").is_file())
self.assertTrue((self.home / ".config/droiddeck/fex-wanted").is_file())
self.assertFalse(json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())["ready"])
def test_uruntime_that_only_drops_extended_attributes_still_unpacks(self):
tool = self.uruntime(
"mkdir -p AppDir && touch AppDir/AppRun\n"
"echo 'Failed to exec memfd: EACCES: Permission denied. Trying tmpfile in /tmp...' >&2\n"
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
"echo 'Further error messages of this type are suppressed!' >&2\n"
"exit 2\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("could not keep the image's extended attributes", said)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_an_attribute_only_failure_without_apprun_is_not_taken_as_unpacked(self):
tool = self.uruntime(
"mkdir -p AppDir\n"
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
"exit 2\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False, "prepare": lambda: None}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertIn("uruntime could not extract it (status 2)", said)
self.assertNotIn("could not keep the image's extended attributes", said)
self.assertFalse(os.path.lexists("squashfs-root/AppRun"))
def test_other_uruntime_errors_are_not_taken_as_unpacked(self):
self.assertFalse(FEX["only_xattrs_failed"]("write_xattr: could not write xattr\nwrite_file: failed to create file x\n"))
self.assertFalse(FEX["only_xattrs_failed"](""))
self.assertTrue(FEX["only_xattrs_failed"]("proot error: execveat() failed\nwrite_xattr: could not write xattr\n"))
def test_an_arm64_image_does_not_ask_for_fex(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime("mkdir -p squashfs-root\n")
with mock.patch.dict(G, {"URUNTIME": tool}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual((status, said), (0, ""))
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
def test_nothing_to_unpack_with_says_so(self):
tool = self.uruntime("mkdir -p squashfs-root\nexit 1\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}), \
mock.patch("shutil.which", return_value=None):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 1)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertIn("no AppImage runtime for ARM64, no FEX yet and no unsquashfs", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def test_unsquashfs_fallback_disables_unwritable_xattrs(self):
tool = self.uruntime("exit 1\n")
commands = []
def call(argv, **kwargs):
commands.append(argv)
if argv[0] == tool:
return 1
(self.work / "squashfs-root").mkdir()
(self.work / "squashfs-root/AppRun").touch()
return 0
with mock.patch.dict(G, {
"URUNTIME": tool,
"prepare": lambda: None,
"fex_install": lambda: None,
"steam_running": lambda: False,
"want_fex": lambda: None,
}), mock.patch("shutil.which", return_value="/usr/bin/unsquashfs"), \
mock.patch("subprocess.call", side_effect=call):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual(commands[-1][0], "/usr/bin/unsquashfs")
self.assertIn("-no-xattrs", commands[-1])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def seven_zip(self, tool, which, works=True):
commands = []
def call(argv, **kwargs):
commands.append(argv)
if argv[0] != "/usr/bin/7z" or not works:
return 2
(self.work / "squashfs-root").mkdir()
(self.work / "squashfs-root/AppRun").touch()
return 0
with mock.patch.dict(G, {
"URUNTIME": tool,
"prepare": lambda: None,
"fex_install": lambda: None,
"steam_running": lambda: False,
"want_fex": lambda: None,
}), mock.patch("shutil.which", side_effect=lambda name: which.get(name)), \
mock.patch("subprocess.call", side_effect=call):
status, said = self.quiet(FEX["extract"], "image.AppImage")
return status, said, commands
def test_without_proot_the_shipped_runtime_reads_the_open_image(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime('cmp "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual((status, said), (0, ""))
self.assertEqual([], commands)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_without_proot_runtime_failure_falls_back_to_7zip(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime("exit 1\n")
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual("/usr/bin/7z", commands[-1][0])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_with_proot_the_shipped_runtime_is_still_tried_first(self):
ran = self.tmp / "uruntime-ran"
tool = self.uruntime("touch %s\nexit 1\n" % ran)
env = {k: v for k, v in os.environ.items() if k != "DDNATV_ROOT"}
with mock.patch.dict(os.environ, env, clear=True):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertTrue(ran.exists())
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual("/usr/bin/7z", commands[-1][0])
def test_unsquashfs_is_preferred_over_7zip(self):
tool = self.uruntime("exit 1\n")
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertIn("unsquashfs could not extract it (status 2)", said)
self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands])
def test_a_7zip_failure_leaves_nothing_unpacked(self):
tool = self.uruntime("exit 1\n")
status, said, _ = self.seven_zip(tool, {"7z": "/usr/bin/7z"}, works=False)
self.assertEqual(status, 1)
self.assertIn("7-Zip could not extract it (status 2)", said)
self.assertNotIn("no unsquashfs", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def runtime_elf(self):
head = bytearray(elf(183))
struct.pack_into("<Q", head, 0x28, len(head))
return bytes(head)
def dwarfs(self, body):
self.write(self.image, self.runtime_elf() + b"DWARFS\x02\x05payload", 0o755)
self.ran = self.tmp / "dwarfsextract-ran"
return str(self.write(self.tmp / "dwarfsextract", "#!/bin/sh\ntouch %s\n%s" % (self.ran, body), 0o755))
def test_a_dwarfs_image_the_runtime_cannot_unpack_is_read_through_its_open_descriptor(self):
reader = self.dwarfs(
'[ "$1 $3 $4 $5" = "--input --image-offset=64 --output squashfs-root" ] || exit 9\n'
'case $2 in /proc/self/fd/*) ;; *) exit 8 ;; esac\n'
'cmp -s "$2" "%s" || exit 7\ntouch squashfs-root/AppRun\n' % self.image)
tool = self.uruntime("echo 'Failed to execute dwarfsextract: EACCES: Permission denied' >&2\nexit 1\n")
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}), \
mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \
mock.patch("shutil.which", return_value=None):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertNotIn("dwarfsextract could not", said)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
def test_a_dwarfs_image_the_runtime_unpacks_never_runs_dwarfsextract(self):
reader = self.dwarfs("touch squashfs-root/AppRun\n")
tool = self.uruntime("mkdir -p AppDir && touch AppDir/AppRun\n")
with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual((status, said), (0, ""))
self.assertFalse(self.ran.exists())
def test_a_dwarfsextract_failure_leaves_nothing_unpacked(self):
reader = self.dwarfs("mkdir -p squashfs-root/usr\nexit 3\n")
tool = self.uruntime("exit 1\n")
with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \
mock.patch("shutil.which", return_value=None):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 1)
self.assertTrue(self.ran.exists())
self.assertIn("dwarfsextract could not extract it (status 3)", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def test_a_squashfs_image_still_goes_to_unsquashfs(self):
reader = self.dwarfs("exit 0\n")
self.write(self.image, self.runtime_elf() + b"hsqs" + b"payload", 0o755)
tool = self.uruntime("exit 1\n")
with mock.patch.dict(G, {"DWARFSEXTRACT": reader}):
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertNotIn("dwarfsextract", said)
self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands])
class LaunchTest(FexTestCase):
def test_the_guest_environment(self):
arm = self.write(self.tmp / "arm.so", elf(183))
x86 = self.write(self.tmp / "x86.so", elf(62))
env = {"LD_PRELOAD": "%s:%s %s libMelonLoader.Bootstrap.so" % (arm, x86, self.tmp / "gone.so"),
"LD_LIBRARY_PATH": "/steam/steamrtarm64:/usr/lib/aarch64-linux-gnu:/game/lib:/steam/linuxarm64",
"FEX_ROOTFS": "/usr/share/guestos/fex-mesa", "FEX_TSOENABLED": "1"}
guest = FEX["guest_environment"]({"portable": True}, env)
self.assertEqual((guest["LD_PRELOAD"], guest["LD_LIBRARY_PATH"], guest["FEX_PORTABLE"]),
("%s:libMelonLoader.Bootstrap.so" % x86, "/game/lib", "1"))
self.assertNotIn("FEX_ROOTFS", guest)
self.assertEqual(guest["FEX_TSOENABLED"], "1")
self.assertTrue(guest["FEX_APP_CONFIG_LOCATION"].endswith("/config/"))
self.assertEqual((guest["FEX_SILENTLOG"], guest["FEX_OUTPUTLOG"]), ("0", "stderr"))
self.assertEqual(guest["GC_DISABLE_INCREMENTAL"], "1")
self.assertEqual(guest["DOTNET_INTERNAL_ThreadSuspendInjection"], "0")
self.assertEqual(guest["COMPlus_INTERNAL_ThreadSuspendInjection"], "0")
legacy = FEX["guest_environment"]({"portable": False}, {"COMPlus_INTERNAL_ThreadSuspendInjection": "1"})
self.assertEqual(legacy["COMPlus_INTERNAL_ThreadSuspendInjection"], "1")
self.assertNotIn("DOTNET_INTERNAL_ThreadSuspendInjection", legacy)
blank = FEX["guest_environment"]({"portable": False}, {"COMPlus_INTERNAL_ThreadSuspendInjection": "",
"DOTNET_INTERNAL_ThreadSuspendInjection": ""})
self.assertEqual(blank["DOTNET_INTERNAL_ThreadSuspendInjection"], "0")
self.assertEqual(blank["COMPlus_INTERNAL_ThreadSuspendInjection"], "0")
guest = FEX["guest_environment"]({"portable": False}, {"LD_PRELOAD": str(arm), "FEX_PORTABLE": "1", "FEX_OUTPUTLOG": "/tmp/fex.log",
"GC_DISABLE_INCREMENTAL": "0", "DOTNET_INTERNAL_ThreadSuspendInjection": "1"})
self.assertEqual((guest["FEX_OUTPUTLOG"], guest["GC_DISABLE_INCREMENTAL"]), ("/tmp/fex.log", "0"))
self.assertEqual(guest["DOTNET_INTERNAL_ThreadSuspendInjection"], "1")
self.assertEqual(guest["COMPlus_INTERNAL_ThreadSuspendInjection"], "1")
self.assertNotIn("LD_PRELOAD", guest)
self.assertNotIn("FEX_PORTABLE", guest)
def test_the_server_socket_stays_under_the_runtime_directory(self):
runtime = self.tmp / "run"
runtime.mkdir()
guest = FEX["guest_environment"]({"portable": True}, {"XDG_RUNTIME_DIR": str(runtime)})
self.assertEqual(guest["FEX_APP_DATA_LOCATION"], str(runtime / "fex") + "/")
self.assertTrue((runtime / "fex").is_dir())
guest = FEX["guest_environment"]({"portable": True}, {"XDG_RUNTIME_DIR": str(self.tmp / "missing")})
self.assertEqual(guest["FEX_APP_DATA_LOCATION"], G["DATA_DIR"] + "/")
def test_the_runtime_and_thunks_are_passed_to_fex(self):
fex = {"portable": True, "rootfs": "/rt/files", "host_thunks": "/h", "guest_thunks": "/g", "thunks_db": "/db"}
guest = FEX["guest_environment"](fex, {})
self.assertEqual((guest["FEX_ROOTFS"], guest["FEX_THUNKHOSTLIBS"], guest["FEX_THUNKGUESTLIBS"]), ("/rt/files", "/h", "/g"))
self.assertTrue(guest["FEX_THUNKCONFIG"].endswith("/config/ThunksConfig.json"))
guest = FEX["guest_environment"](dict(fex, host_thunks=None), {})
self.assertEqual(guest["FEX_ROOTFS"], "/rt/files")
self.assertNotIn("FEX_THUNKCONFIG", guest)
FEX["write_config"](fex, "/rt/files")
thunks = json.loads((self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json").read_text())
self.assertEqual(thunks, {"ThunksDB": {"GL": 1, "Vulkan": 1}})
def test_wayland_and_egl_thunks_turn_on_only_when_the_build_ships_all_of_them(self):
guest = self.tmp / "guest-thunks"
guest.mkdir()
fex = {"host_thunks": "/h", "guest_thunks": str(guest), "thunks_db": "/db"}
thunks_file = self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json"
for name in ("libwayland-client-guest.so", "libEGL-guest.so"):
(guest / name).write_bytes(b"")
FEX["write_config"](fex, "/root")
self.assertEqual({"GL": 1, "Vulkan": 1}, json.loads(thunks_file.read_text())["ThunksDB"])
(guest / "libwayland-egl-guest.so").write_bytes(b"")
FEX["write_config"](fex, "/root")
expected = {"GL": 1, "Vulkan": 1, "WaylandClient": 1, "EGL": 1, "WaylandEGL": 1}
self.assertEqual(expected, json.loads(thunks_file.read_text())["ThunksDB"])
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(expected, config["ThunksDB"])
def test_host_libc_tunables_stay_on_the_host(self):
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
self.assertNotIn("GLIBC_TUNABLES", guest)
def test_host_iconv_modules_stay_on_the_host(self):
guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"})
self.assertEqual(guest["GCONV_PATH"], "")
own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"})
self.assertEqual(own["GCONV_PATH"], "/opt/gconv")
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
self.fex_tool()
self.runtime()
platform = self.steamrt4()
proton = self.proton("4183110")
with mock.patch("os.execve") as emulated:
self.quiet(FEX["launch"], [str(proton), "waitforexitandrun", "game.exe"], {}, "on")
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:
FEX["launch"]([str(program), "--flag"], {"PATH": "/usr/bin"}, "auto")
native.assert_called_once_with(str(program), [str(program), "--flag"], {"PATH": "/usr/bin"})
emulated.assert_not_called()
def test_x86_programs_run_under_fex(self):
tool = self.fex_tool()
self.runtime()
program = self.write(self.tmp / "game.x86_64", elf(62), 0o755)
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
self.quiet(FEX["launch"], [str(program), "-w"], {"PATH": "/usr/bin"}, "auto")
native.assert_not_called()
binary, argv, env = emulated.call_args[0]
self.assertEqual((binary, argv), (str(tool / "usr/bin/FEX"), [str(tool / "usr/bin/FEX"), str(program), "-w"]))
self.assertEqual(env["FEX_PORTABLE"], "1")
self.assertNotIn("LD_PRELOAD", env)
self.assertEqual(env["FEX_ROOTFS"], str(self.steam / "steamapps/common/SteamLinuxRuntime_sniper/sniper_platform_3.0.20260805.254768/files"))
for arch in ("x86_64", "i386"):
self.write(self.tmp / "preloads" / arch / "libfaultreport.so", elf(62 if arch == "x86_64" else 3))
x86 = self.write(self.tmp / "x86.so", elf(62))
with mock.patch("os.execve") as emulated:
self.quiet(FEX["launch"], [str(program)], {"LD_PRELOAD": str(x86)}, "auto")
self.assertEqual(emulated.call_args[0][2]["LD_PRELOAD"], str(x86))
old = self.write(self.tmp / "game.i386", elf(3), 0o755)
with mock.patch("os.execve") as emulated:
self.quiet(FEX["launch"], [str(old)], {}, "auto")
self.assertNotIn("LD_PRELOAD", emulated.call_args[0][2])
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
self.quiet(FEX["launch"], [str(program)], {}, "off")
native.assert_called_once()
emulated.assert_not_called()
def test_programs_that_bring_a_new_enough_runtime_get_the_vulkan_thunk(self):
tool = self.fex_tool()
self.runtime()
self.write(tool / "usr/share/fex-emu/GuestThunks/libvulkan-guest.so",
elf(62) + b"\0libstdc++.so.6\0GLIBCXX_3.4\0GLIBCXX_3.4.29\0libc.so.6\0GLIBC_2.2.5\0GLIBC_2.34\0")
pin = self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", elf(62) + b"\0libc.so.6\0GLIBC_2.2.5\0")
pinned = "/usr/lib/x86_64-linux-gnu/droiddeck/vulkan"
def app(name, glibc=b"GLIBC_2.34\0GLIBC_2.44", glibcxx=b"GLIBCXX_3.4.29\0GLIBCXX_3.4.36", bundled=True):
run = self.write(self.tmp / name / "AppRun", elf(62), 0o755)
if bundled:
self.write(self.tmp / name / "shared/lib/libc.so.6", elf(62) + b"\0GLIBC_2.2.5\0" + glibc + b"\0")
self.write(self.tmp / name / "shared/lib/libstdc++.so.6",
elf(62) + b"\0GLIBCXX_3.4\0" + glibcxx + b"\0GLIBC_2.34\0")
return run
def started(program, env=None, decide=None):
with mock.patch("os.execve") as emulated:
_, said = self.quiet(FEX["launch"], [str(program)], dict(env or {}), "on", decide)
return emulated.call_args[0][2], said
def search(env):
return env.get("LD_LIBRARY_PATH", "").split(":")[0]
env, said = started(app("new"))
self.assertEqual(search(env), pinned)
self.assertNotIn("LD_AUDIT", env)
self.assertNotIn("LD_BIND_NOW", env)
self.assertIn("thunks on, its own Vulkan loader too", said)
env, _ = started(app("kept"), {"LD_LIBRARY_PATH": "/game/lib"})
self.assertEqual(env["LD_LIBRARY_PATH"], pinned + ":/game/lib")
env, _ = started(self.write(self.tmp / "elsewhere/run.sh", "#!/bin/sh\n", 0o755), decide=str(self.tmp / "new"))
self.assertEqual(search(env), pinned)
env, said = started(app("old-cxx", glibcxx=b"GLIBCXX_3.4.28"))
self.assertNotEqual(search(env), pinned)
self.assertIn("thunks on)", said)
self.assertNotEqual(search(started(app("old-libc", glibc=b"GLIBC_2.31"))[0]), pinned)
self.assertNotEqual(search(started(app("runtime-only", bundled=False))[0]), pinned)
i386 = self.write(self.tmp / "new/game.i386", elf(3), 0o755)
self.assertNotEqual(search(started(i386)[0]), pinned)
self.write(pin, elf(62) + b"\0libc.so.6\0GLIBC_2.45\0")
self.assertNotEqual(search(started(app("new"))[0]), pinned)
pin.unlink()
self.assertNotEqual(search(started(app("no-pin"))[0]), pinned)
self.write(pin, elf(62))
(tool / "usr/share/fex-emu/GuestThunks/libvulkan-guest.so").unlink()
self.assertNotEqual(search(started(app("no-thunk"))[0]), pinned)
def test_steam_verbs(self):
with mock.patch.dict(G, {"launch": mock.Mock(return_value=0)}):
self.assertEqual(FEX["main"](["steam", "getcompatpath", "/x"]), 0)
G["launch"].assert_not_called()
FEX["main"](["steam", "waitforexitandrun", "/game/run.sh", "-a"])
command, env, mode = G["launch"].call_args[0]
self.assertEqual((command, mode), (["/game/run.sh", "-a"], "auto"))
def test_steam_games_get_their_settings_and_linux_unity_keeps_tso(self):
config = self.home / ".config/droiddeck/game-environment.json"
unity = self.write(self.tmp / "Megabonk/Megabonk.x86_64", elf(62), 0o755)
self.write(self.tmp / "Megabonk/UnityPlayer.so", elf(62))
self.write(self.tmp / "Megabonk/GameAssembly.so", elf(62))
other = self.write(self.tmp / "Other/game.x86_64", elf(62), 0o755)
self.write(config, json.dumps({"version": 1, "shared": {"FEX_TSOENABLED": "0", "FEX_MULTIBLOCK": "1"},
"games": {"20": {"FEX_TSOENABLED": "0"}}}))
def started(program, app):
with mock.patch.dict(G, {"launch": mock.Mock(return_value=0), "GAME_ENVIRONMENT": str(config)}), \
mock.patch.dict(os.environ, {"SteamAppId": app}, clear=True):
_, said = self.quiet(FEX["main"], ["steam", "waitforexitandrun", str(program), "-arg"])
command, env, _ = G["launch"].call_args[0]
self.assertEqual(command, [str(program), "-arg"])
return env.get("FEX_TSOENABLED"), env.get("FEX_MULTIBLOCK"), said
tso, multiblock, said = started(unity, "10")
self.assertEqual((tso, multiblock), ("1", "1"))
self.assertIn("Unity: FEX with TSO", said)
self.assertEqual(started(other, "10")[:2], ("0", "1"))
self.assertEqual(started(unity, "20")[:2], ("0", "1"))
config.unlink()
self.assertEqual(started(unity, "10")[:2], ("1", None))
self.assertEqual(started(other, "10")[:2], (None, None))
class AppInfoTest(unittest.TestCase):
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
@staticmethod
def appinfo(apps, magic=0x07564429):
strings = []
def key(name):
if magic != 0x07564429:
return name.encode() + b"\0"
if name not in strings:
strings.append(name)
return struct.pack("<I", strings.index(name))
def section(items):
out = b""
for name, value in items.items():
if isinstance(value, dict):
out += b"\x00" + key(name) + section(value)
else:
out += b"\x01" + key(name) + value.encode() + b"\0"
return out + b"\x08"
body = b""
records = apps.items() if isinstance(apps, dict) else apps
for app, entry in records:
if isinstance(entry, dict):
data = section({"appinfo": dict(entry, appid=str(app))})
else:
oslist, osarch, kind = entry
data = section({"appinfo": {"appid": str(app), "common": {"type": kind, "oslist": oslist, "osarch": osarch}}})
header = struct.pack("<IIQ", 2, 0, 0) + b"\0" * 20 + struct.pack("<I", 1) + (b"\0" * 20 if magic >= 0x07564428 else b"")
body += struct.pack("<II", app, len(header) + len(data)) + header + data
body += struct.pack("<I", 0)
if magic != 0x07564429:
return struct.pack("<II", magic, 1) + body
table_at = 16 + len(body)
table = struct.pack("<I", len(strings)) + b"".join(s.encode() + b"\0" for s in strings)
return struct.pack("<IIq", magic, 1, table_at) + body + table
def test_linux_only_titles_are_sent_to_fex_and_dual_platform_is_deferred(self):
for magic in (0x07564427, 0x07564428, 0x07564429):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "appcache").mkdir()
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: ("windows", "", "Game"), 20: ("linux", "64", "Game"), 30: ("windows,linux,macos", "", "game"),
40: ("linux", "arm64", "game"), 41: ("windows,linux", "aarch64", "game"),
50: ("linux", "", "Demo"), 70: ("linux", "", "Tool"), 80: ("linux", "", "config"),
90: ("linux", "", ""),
}, magic))
self.COMPAT["APPINFO_CACHE"].clear()
targets = self.COMPAT["native_targets"](str(steam), ["10", "20", "30", "40", "41", "50", "70", "80", "90", "1628350", "60"])
self.assertEqual(targets, {
"20": "droiddeck-fex", "30": self.COMPAT["NATIVE_CHOICE"],
"40": None, "41": None, "50": "droiddeck-fex",
}, hex(magic))
@staticmethod
def manifest(steam, app, flags="4"):
(steam / "steamapps").mkdir(exist_ok=True)
(steam / ("steamapps/appmanifest_%s.acf" % app)).write_text('"AppState" { "appid" "%s" "StateFlags" "%s" }' % (app, flags))
def test_dual_platform_titles_keep_the_proton_default_unless_the_user_picks_fex(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp) / "Steam"
(steam / "appcache").mkdir(parents=True)
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: ("windows,linux", "", "game"), 20: ("windows,linux", "", "game"), 30: ("windows,linux", "", "game"),
40: ("linux", "", "game"),
}))
self.COMPAT["APPINFO_CACHE"].clear()
for app in ("3127680", "1628350", "4183110"):
self.manifest(steam, app)
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
state = Path(tmp) / "state"
state.mkdir()
(state / "state.json").write_text(json.dumps({"auto": {"20": fex}}))
catalog = [{"name": tool, "display": "Proton Experimental ARM64", "dir": "Proton Experimental (ARM64)", "valve": True}]
config = steam / "config/config.vdf"
config.parent.mkdir()
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { '
'"0" { "name" "%s" "config" "" "priority" "75" } '
'"20" { "name" "%s" "config" "" "priority" "250" } '
'"30" { "name" "%s" "config" "" "priority" "250" } } } } } }' % (tool, fex, fex))
self.COMPAT["register_default"](str(config), ["10", "20", "30", "40"], catalog=catalog, directory=str(state))
self.assertEqual(self.COMPAT["read_config_mapping"](str(config)),
{"0": tool, "10": tool, "20": tool, "30": fex, "40": fex})
def test_tools_are_fetched_until_fully_installed_and_up_to_date(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "steamapps").mkdir()
downloads = self.COMPAT["tool_downloads"]
self.assertEqual(downloads(str(steam)), [
("4427310", "install"), ("3127680", "install"), ("1628350", "install"), ("4183110", "install")])
self.manifest(steam, "4427310", flags="6")
self.manifest(steam, "3127680", flags="1026")
self.manifest(steam, "1628350", flags="4")
(steam / "steamapps/appmanifest_4183110.acf").write_text('"AppState" { "appid" "4183110" }')
self.assertEqual(downloads(str(steam)), [("4427310", "update"), ("3127680", "update"), ("4183110", "update")])
for app in ("4427310", "3127680", "4183110"):
self.manifest(steam, app)
self.assertEqual(downloads(str(steam)), [])
def test_valve_proton_on_demand_waits_for_a_title_that_uses_it(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
for app in ("3127680", "1628350", "4183110"):
self.manifest(steam, app)
downloads, needed, tool = self.COMPAT["tool_downloads"], self.COMPAT["valve_proton_needed"], self.COMPAT["TOOL"]
own = steam / "compatibilitytools.d/DroidDeck-Proton 11-14.1"
with mock.patch.dict(os.environ, {"DD_VALVE_PROTON": "0"}):
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
ge = steam / "compatibilitytools.d/GE-Proton10-25"
ge.mkdir(parents=True)
(ge / "droiddeck-proton-wrap").write_text("")
(ge / "compatibilitytool.vdf").write_text(
'"compatibilitytools" { "compat_tools" { "GE-Proton10-25" { "install_path" "." } } }')
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
own.mkdir(parents=True)
(own / "droiddeck-proton-wrap").write_text("")
(own / "compatibilitytool.vdf").write_text(
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-14.1" { "install_path" "." } } }')
self.assertEqual(downloads(str(steam)), [])
self.assertFalse(needed(str(steam), {"DroidDeck-Proton-11-14.1", None}))
self.assertTrue(needed(str(steam), {"DroidDeck-Proton-11-14.1", tool}))
self.assertTrue(needed(str(steam), {"proton-experimental-arm64"}))
self.assertEqual(downloads(str(steam), True), [("4427310", "install")])
config = steam / "config/config.vdf"
config.parent.mkdir()
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { '
'"0" { "name" "DroidDeck-Proton-11-14.1" "config" "" "priority" "75" } '
'"10" { "name" "%s" "config" "" "priority" "250" } } } } } }' % tool)
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
config.unlink()
self.manifest(steam, "4427310", flags="6")
self.assertEqual(downloads(str(steam), False), [("4427310", "update")])
with mock.patch.dict(os.environ, {"DD_VALVE_PROTON": "1"}):
(steam / "steamapps/appmanifest_4427310.acf").unlink()
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
def deck(oslist, runtime, kind="game"):
common = {"type": kind, "oslist": oslist, "steam_deck_compatibility": {"configuration": {"recommended_runtime": runtime}}}
if oslist is None:
del common["oslist"]
return {"common": common}
for magic in (0x07564427, 0x07564428, 0x07564429):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "appcache").mkdir()
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: deck("windows", "proton-stable"), 11: deck("windows,linux", "native"), 12: deck(None, "proton-7.0-5"),
13: deck("linux", "native"), 14: deck("windows", "proton-stable", "Tool"), 15: ("windows", "", "game"),
16: ("windows", "", "game"), 1628350: deck("linux", "native", "game"),
891390: {"common": {"type": "Config"}, "extended": {"app_mappings": {
"16": {"appid": "16", "tool": "proton-stable"}, "17": {"appid": "17", "tool": ""}}}},
}, magic))
self.COMPAT["APPINFO_CACHE"].clear()
self.assertEqual(self.COMPAT["valve_picks"](str(steam)), ["10", "11", "12", "16"], hex(magic))
def test_titles_with_a_valve_pick_follow_the_default_until_the_user_picks(self):
tool = self.COMPAT["TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "31": "GE-Proton11-7", "32": "proton_11_arm64", "33": "steamlinuxruntime"},
["40"], [tool, "GE-Proton11-7"], tool, {}, {}, ["30", "31", "32", "33"])
self.assertEqual(changes, {"30": tool, "32": tool, "40": tool})
self.assertEqual(auto, {"30": tool, "32": tool, "40": tool})
changes, auto = self.COMPAT["plan_mapping"](
{"0": "GE-Proton11-7", "30": tool, "31": "GE-Proton11-7", "32": tool}, [], [tool, "GE-Proton11-7"], "GE-Proton11-7", auto, {}, ["30", "31", "32"])
self.assertEqual(changes, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
self.assertEqual(auto, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
def test_automatic_native_mapping_uses_fex_and_keeps_explicit_tools(self):
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "20": "fex", "21": "steamlinuxruntime_sniper", "22": "GE-Proton11-7"},
["20", "21", "22", "23", "24"], [tool, "GE-Proton11-7"], tool, {},
{"20": fex, "21": fex, "22": fex, "23": fex})
self.assertEqual(changes, {"23": fex, "24": tool})
self.assertEqual(auto, {"23": fex, "24": tool})
def test_explicit_linux_runtime_and_fex_selections_survive_default_maintenance(self):
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "20": "steamlinuxruntime_arm64", "21": fex},
["20", "21"], [tool], tool, {}, {"20": None, "21": fex}, ["20", "21"])
self.assertEqual(changes, {})
self.assertEqual(auto, {})
def test_native_arm64_default_stays_unmapped_and_old_auto_proton_is_cleared(self):
tool = self.COMPAT["TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "20": tool}, ["20"], [tool], tool, {"20": tool}, {"20": None}, ["20"])
self.assertEqual(changes, {"20": None})
self.assertEqual(auto, {})
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool}, ["20"], [tool], tool, {}, {"20": None}, ["20"])
self.assertEqual(changes, {})
self.assertEqual(auto, {})
def test_the_tool_files(self):
with tempfile.TemporaryDirectory() as tmp:
tool = Path(tmp) / "droiddeck-fex"
self.COMPAT["build_fex_tool"](str(tool))
self.assertEqual(sorted(os.listdir(tool)), sorted(self.COMPAT["FEX_FILES"]))
self.assertIn('"commandline" "/droiddeck-fex-tool %verb%"', (tool / "toolmanifest.vdf").read_text())
self.assertTrue(os.access(tool / "droiddeck-fex-tool", os.X_OK))
vdf = (tool / "compatibilitytool.vdf").read_text()
self.assertIn('"from_oslist" "linux"', vdf)
self.assertIn('"to_oslist" "linux"', vdf)
def test_the_tool_runs_games_on_the_chosen_cores(self):
with tempfile.TemporaryDirectory() as tmp:
tool, bin_dir = Path(tmp) / "droiddeck-fex", Path(tmp) / "bin"
self.COMPAT["build_fex_tool"](str(tool))
bin_dir.mkdir()
(bin_dir / "taskset").write_text('#!/bin/sh\necho "taskset $*"\n')
(bin_dir / "taskset").chmod(0o755)
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ.get("PATH", "")), DD_GAME_CPUS="2-7")
run = subprocess.run([str(tool / "droiddeck-fex-tool"), "waitforexitandrun", "/games/a/game"],
env=env, capture_output=True, text=True, timeout=10)
self.assertEqual(run.stdout,
"taskset -c 2-7 /usr/local/bin/droiddeck-fex steam waitforexitandrun /games/a/game\n")
self.assertIn("game cores 2-7", run.stderr)
self.assertIn('exec /usr/local/bin/droiddeck-steamvr-game ${DD_TASKSET:-} '
'/usr/local/bin/droiddeck-fex steam "$verb" "$@"', self.COMPAT["FEX_LAUNCHER_SH"])
if __name__ == "__main__":
unittest.main()