Merge remote-tracking branch 'droiddeck/main' into feat/malibridge

# Conflicts:
#	README.md
#	app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
#	app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
#	app/src/main/res/values-ar/strings.xml
#	app/src/main/res/values-b+es+419/strings.xml
#	app/src/main/res/values-bg/strings.xml
#	app/src/main/res/values-cs/strings.xml
#	app/src/main/res/values-da/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-el/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-fi/strings.xml
#	app/src/main/res/values-fr/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values-hu/strings.xml
#	app/src/main/res/values-in/strings.xml
#	app/src/main/res/values-it/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ko/strings.xml
#	app/src/main/res/values-ms/strings.xml
#	app/src/main/res/values-nb/strings.xml
#	app/src/main/res/values-nl/strings.xml
#	app/src/main/res/values-pl/strings.xml
#	app/src/main/res/values-pt-rPT/strings.xml
#	app/src/main/res/values-pt/strings.xml
#	app/src/main/res/values-ro/strings.xml
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values-sv/strings.xml
#	app/src/main/res/values-th/strings.xml
#	app/src/main/res/values-tr/strings.xml
#	app/src/main/res/values-uk/strings.xml
#	app/src/main/res/values-vi/strings.xml
#	app/src/main/res/values-zh-rCN/strings.xml
#	app/src/main/res/values-zh-rHK/strings.xml
#	app/src/main/res/values-zh-rTW/strings.xml
#	app/src/main/res/values/strings.xml
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
This commit is contained in:
maxjivi05 committed 2026-10-30 11:58:55 -04:00
commit 0a5955d6fa
731 files changed
+54131 -2491

No files matched your search

+10 -2
View File
@@ -44,6 +44,7 @@ typedef struct pa_sink {
struct android_volume;
struct userdata { struct android_volume *android_volume; };
static int restarts, frees;
static uint64_t last_delay;
static char *pa_sprintf_malloc(const char *format, ...) {
va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result;
}
@@ -57,7 +58,7 @@ static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_s
static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; }
static void pa_subscription_post(pa_core *core, int event, unsigned index) {}
static uint64_t pa_rtclock_now(void) { return 0; }
static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; }
static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; last_delay=time; }
static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time,
void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) {
return calloc(1,sizeof(pa_time_event));
@@ -76,11 +77,18 @@ int main(int argc, char **argv) {
assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute);
state(argv[1],"invalid\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1);
assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1 && last_delay==100*PA_USEC_PER_MSEC);
state(argv[1],"3 15 1\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16);
assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2);
assert(last_delay==16*PA_USEC_PER_MSEC);
state(argv[1],"4 15 1\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==4*PA_VOLUME_NORM/15 && last_delay==16*PA_USEC_PER_MSEC);
for (int i = 0; i < ANDROID_VOLUME_ACTIVE_TICKS + 1; i++)
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(last_delay==100*PA_USEC_PER_MSEC);
sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink);
char *request=pa_sprintf_malloc("%s/volume.request",argv[1]);
FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request);
+74
View File
@@ -0,0 +1,74 @@
import hashlib
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
REMEMBER = Path(__file__).resolve().parents[1] / "ubuntu/overlay-runtime/usr/share/droiddeck/apt/remember"
class AptRememberTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.top = Path(temp.name)
self.dir = self.top / "share/apt"
self.state = self.top / "state"
self.etc = self.top / "etc/apt"
self.keys = self.top / "keyrings"
self.autostart = self.top / "autostart"
for d in (self.dir, self.etc / "sources.list.d", self.keys, self.autostart, self.top / "bin"):
d.mkdir(parents=True)
(self.dir / "system-manual.txt").write_text("base\n")
(self.dir / "runtime-id").write_text("new\n")
system = self.keys / "ubuntu-archive.gpg"
system.write_text("system key")
(self.dir / "system-sources.txt").write_text("%s %s\n" % (system, hashlib.sha256(b"system key").hexdigest()))
apt_mark = self.top / "bin/apt-mark"
apt_mark.write_text("#!/bin/sh\nprintf 'base\\nvlc\\n'\n")
apt_mark.chmod(0o755)
script = REMEMBER.read_text()
script = script.replace("/usr/share/droiddeck/apt", str(self.dir))
script = script.replace("/root/.local/share/droiddeck/apt", str(self.state))
script = script.replace("/etc/xdg/autostart", str(self.autostart))
script = script.replace("/usr/share/keyrings", str(self.keys))
script = script.replace("/etc/apt", str(self.etc))
self.script = self.top / "remember"
self.script.write_text(script)
def run_remember(self):
env = dict(os.environ, PATH="%s:%s" % (self.top / "bin", os.environ["PATH"]))
env.pop("DROIDDECK_APT_RESTORING", None)
subprocess.run(["bash", str(self.script)], env=env, check=True, timeout=30)
def test_user_sources_and_keys_outside_etc_apt_are_kept(self):
(self.etc / "sources.list").write_text("deb http://example.invalid stable main\n")
(self.keys / "example.gpg").write_text("user key")
self.run_remember()
self.assertEqual("vlc\n", (self.state / "packages.txt").read_text())
self.assertTrue((self.state / "sources/sources.list").is_file())
self.assertEqual("user key", (self.state / "keyrings" / ("%s_example.gpg" % str(self.keys).lstrip("/").replace("/", "_"))).read_text())
self.assertFalse(any("ubuntu-archive" in p.name for p in (self.state / "keyrings").iterdir()))
def test_the_previous_runtime_snapshot_waits_for_the_desktop_restore(self):
(self.autostart / "droiddeck-apt-restore.desktop").write_text("")
self.state.mkdir()
(self.state / "packages.txt").write_text("old-app\n")
(self.state / "restored").write_text("old\n")
self.run_remember()
self.assertEqual("old-app\n", (self.state / "packages.txt").read_text())
(self.state / "attempted").write_text("new\n")
self.run_remember()
self.assertEqual("vlc\n", (self.state / "packages.txt").read_text())
def test_without_the_desktop_the_snapshot_follows_the_runtime(self):
self.state.mkdir()
(self.state / "packages.txt").write_text("old-app\n")
(self.state / "restored").write_text("old\n")
self.run_remember()
self.assertEqual("vlc\n", (self.state / "packages.txt").read_text())
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -60,7 +60,7 @@ class BinfmtPreloadTest(unittest.TestCase):
cls.library = cls.tmp / "libbinfmt.so"
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DBINFMT_TEST",
'-DBINFMT_HANDLER="%s"' % cls.handler, "-o", str(cls.library),
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "webhelper.c")] + ["-ldl"],
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")] + ["-ldl"],
check=True)
source = cls.tmp / "program.c"
source.write_text(PROGRAM)
+107
View File
@@ -0,0 +1,107 @@
import json
import os
import runpy
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import unittest
from pathlib import Path
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
PROBE = """
import fcntl, os, sys
fd = os.open(sys.argv[1], os.O_RDWR)
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
print("held")
else:
print("free")
"""
class BwrapLockFileTest(unittest.TestCase):
def setUp(self):
self.shim = runpy.run_path(str(BWRAP))
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.instance = Path(self.temp.name) / "instance"
self.instance.mkdir()
(self.instance / ".ref").write_text("")
def spec(self, *extra):
argv = ["--ro-bind", str(self.instance), "/run/user/1000/.flatpak/7", *extra, "--", "true"]
return self.shim["parse"](argv)
def probe(self):
return subprocess.run([sys.executable, "-c", PROBE, str(self.instance / ".ref")],
capture_output=True, text=True, timeout=30, check=True).stdout.strip()
def test_sandbox_paths_resolve_through_the_binds(self):
spec = self.spec()
self.assertEqual(str(self.instance / ".ref"), self.shim["host_path"](spec, "/run/user/1000/.flatpak/7/.ref"))
self.assertEqual("/etc/hosts", self.shim["host_path"](spec, "/etc/hosts"))
def test_the_instance_lock_is_held_while_the_sandbox_runs(self):
spec = self.spec("--lock-file", "/run/user/1000/.flatpak/7/.ref")
self.assertEqual("free", self.probe())
self.shim["hold_locks"](spec)
self.assertEqual("held", self.probe())
def test_without_a_lock_file_nothing_is_locked(self):
self.shim["hold_locks"](self.spec())
self.assertEqual("free", self.probe())
def test_the_lock_survives_exec(self):
script = (
"import runpy, sys; shim = runpy.run_path(sys.argv[1]); "
"spec = shim['parse'](['--ro-bind', sys.argv[2], '/run/user/1000/.flatpak/7', "
"'--lock-file', '/run/user/1000/.flatpak/7/.ref', '--', 'true']); "
"shim['hold_locks'](spec); "
"import os; os.execv(sys.executable, [sys.executable, '-c', "
"'import subprocess, sys; print(subprocess.run([sys.executable, \"-c\", sys.argv[1], sys.argv[2]], "
"capture_output=True, text=True).stdout.strip())', sys.argv[3], sys.argv[4]])"
)
out = subprocess.run([sys.executable, "-c", script, str(BWRAP), str(self.instance), PROBE,
str(self.instance / ".ref")], capture_output=True, text=True, timeout=30, check=True)
self.assertEqual("held", out.stdout.strip())
class BwrapReportedPidTest(unittest.TestCase):
def test_flatpak_is_given_the_wrapper_so_killing_it_ends_the_whole_sandbox(self):
name = "droiddeck-bwrap-test-%d" % os.getpid()
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind("\0" + name)
server.listen(1)
self.addCleanup(server.close)
def answer():
conn, _ = server.accept()
with conn:
head = conn.recv(5)
size = struct.unpack(">I", head[1:])[0]
while size > 0:
size -= len(conn.recv(size))
for kind, payload in ((b"P", b"424242"), (b"X", b"0")):
conn.sendall(kind + struct.pack(">I", len(payload)) + payload)
thread = threading.Thread(target=answer, daemon=True)
thread.start()
read_end, write_end = os.pipe()
env = dict(os.environ, DROIDDECK_BWRAP_SOCKET=name)
proc = subprocess.Popen([sys.executable, str(BWRAP), "--ro-bind", "/", "/elsewhere", "--info-fd",
str(write_end), "--", "true"], env=env, pass_fds=[write_end])
os.close(write_end)
info = os.read(read_end, 4096)
os.close(read_end)
self.assertEqual(0, proc.wait(30))
thread.join(5)
self.assertEqual({"child-pid": proc.pid}, json.loads(info))
if __name__ == "__main__":
unittest.main()
+24
View File
@@ -19,6 +19,30 @@ def run_bash(script, env=None):
class ClientZramFocusTest(unittest.TestCase):
def test_the_hidden_epic_launcher_is_compressed_with_the_client(self):
with tempfile.TemporaryDirectory() as tmp:
proc = Path(tmp)
def task(pid, argv, env=()):
folder = proc / str(pid)
folder.mkdir()
(folder / 'cmdline').write_bytes(b''.join(arg.encode() + b'\0' for arg in argv))
(folder / 'environ').write_bytes(b''.join(item.encode() + b'\0' for item in env))
fex = '/s/FEX-Emu/usr/bin/FEX'
task(5000010, ['/s/steamrtarm64/steam', '-gamepadui'])
task(5000011, [fex, '/e/usr/bin/EpicGamesLauncher'], ['HOME=/root', 'DROIDDECK_EPIC_HIDDEN=1'])
task(5000012, [fex, './/lib/webkit2gtk-4.1/WebKitWebProcess', '4'], ['DROIDDECK_EPIC_HIDDEN=1', 'LANG=C'])
task(5000013, [fex, '/e/usr/bin/EpicGamesLauncher'], ['HOME=/root'])
task(5000014, ['/e/WebKitWebProcess', '4'], ['DROIDDECK_EPIC_HIDDEN=1'])
task(5000015, [fex, '/e/usr/bin/EpicGamesLauncher'], ['DROIDDECK_EPIC_HIDDEN=10'])
task(5000016, ['/s/reaper', 'SteamLaunch', 'AppId=413150', '--', 'game'])
source = function_source('bl_zram_scan').replace('/proc/[0-9]*', tmp + '/[0-9]*')
result = run_bash(source + '\nbl_zram_scan\necho "${_bl_pids[*]}|${_bl_others[*]}|$_bl_game|$_bl_apps"')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual('5000010 5000011 5000012|5000013 5000014 5000015|1| 413150', result.stdout.strip())
def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self):
source = SCRIPT.read_text()
start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then')
+278
View File
@@ -0,0 +1,278 @@
import hashlib
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import deploy_fast
def make_apk(path, entries):
with ZipFile(path, 'w') as package:
for name, (data, method) in entries.items():
info = ZipInfo(name)
info.extra = b'\0' * 6
package.writestr(info, data, compress_type=method)
class ClassifyTest(unittest.TestCase):
agent = 'tools/linuxfs/overlay/usr/local/bin/droiddeck-agent'
targets = {agent: 'assets/linuxfs/usr/local/bin/droiddeck-agent',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-new': 'assets/linuxfs/usr/local/bin/droiddeck-new'}
entries = {'assets/linuxfs/usr/local/bin/droiddeck-agent'}
def classify(self, changes):
return deploy_fast.classify(changes, self.targets, self.entries)
def test_helpers_graft_and_tests_or_docs_are_ignored(self):
grafts, ignored, blocked = self.classify({
self.agent: 'M', 'tools/tests/test_x.py': 'M', 'docs/a/b.txt': 'A', 'README.md': 'M'})
self.assertEqual(grafts, {self.agent: 'assets/linuxfs/usr/local/bin/droiddeck-agent'})
self.assertEqual(sorted(ignored), ['README.md', 'docs/a/b.txt', 'tools/tests/test_x.py'])
self.assertEqual(blocked, {})
def test_everything_else_fails_closed(self):
changes = {'app/src/main/java/com/droiddeck/launcher/Foo.kt': 'M', 'tools/proot/build.sh': 'M',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-new': 'A'}
self.assertEqual(set(self.classify(changes)[2]), set(changes))
self.assertEqual(set(self.classify({self.agent: 'D'})[2]), {self.agent})
def test_real_graft_targets_exist_in_the_overlay(self):
for path in deploy_fast.graft_targets():
self.assertTrue((deploy_fast.ROOT / path).is_file(), path)
class GraftTest(unittest.TestCase):
def test_replaces_entries_keeps_the_rest_and_drops_the_signature(self):
with tempfile.TemporaryDirectory() as directory:
donor, output = Path(directory) / 'donor.apk', Path(directory) / 'out.apk'
make_apk(donor, {'classes.dex': (b'dex', ZIP_DEFLATED), 'lib/arm64-v8a/libx.so': (b'elf', ZIP_STORED),
'assets/a': (b'old', ZIP_DEFLATED), 'META-INF/MANIFEST.MF': (b'm', ZIP_DEFLATED),
'META-INF/CERT.SF': (b's', ZIP_DEFLATED), 'META-INF/CERT.RSA': (b'r', ZIP_DEFLATED),
'META-INF/keep.version': (b'v', ZIP_DEFLATED)})
deploy_fast.graft(donor, {'assets/a': b'new'}, output)
with ZipFile(output) as package:
self.assertEqual(package.read('assets/a'), b'new')
self.assertEqual(package.read('classes.dex'), b'dex')
self.assertEqual(package.getinfo('lib/arm64-v8a/libx.so').compress_type, ZIP_STORED)
self.assertEqual(package.getinfo('classes.dex').compress_type, ZIP_DEFLATED)
self.assertEqual(package.getinfo('classes.dex').extra, b'')
self.assertEqual([n for n in package.namelist() if n.startswith('META-INF/')],
['META-INF/keep.version'])
def test_unknown_replacement_entry_is_refused(self):
with tempfile.TemporaryDirectory() as directory:
donor = Path(directory) / 'donor.apk'
make_apk(donor, {'assets/a': (b'old', ZIP_DEFLATED)})
with self.assertRaises(deploy_fast.Refused):
deploy_fast.graft(donor, {'assets/missing': b'x'}, Path(directory) / 'out.apk')
class RepoTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
patch = mock.patch.object(deploy_fast, 'ROOT', self.root)
patch.start()
self.addCleanup(patch.stop)
self.git('init', '-q', '-b', 'trunk')
self.git('config', 'user.email', 'a@b.c')
self.git('config', 'user.name', 'a')
(self.root / 'kept').write_text('1')
(self.root / 'gone').write_text('1')
self.git('add', '.')
self.git('commit', '-q', '-m', 'base')
self.base = self.git('rev-parse', 'HEAD').strip()
def git(self, *args):
return subprocess.run(['git', '-C', str(self.root), *args], capture_output=True, text=True, check=True).stdout
def test_changed_paths_cover_staged_untracked_and_deleted_files(self):
(self.root / 'kept').write_text('2')
(self.root / 'gone').unlink()
(self.root / 'fresh').write_text('x')
self.git('add', 'kept')
self.assertEqual(deploy_fast.changed_paths(self.base), {'kept': 'M', 'gone': 'D', 'fresh': 'A'})
def test_helper_bytes_normalize_text_but_not_binaries(self):
(self.root / 'script').write_bytes(b'a\r\nb\r\n')
(self.root / 'binary').write_bytes(b'\0a\r\n')
self.assertEqual(deploy_fast.helper_bytes('script'), b'a\nb\n')
self.assertEqual(deploy_fast.helper_bytes('binary'), b'\0a\r\n')
def test_a_donor_ahead_of_the_checkout_is_not_an_ancestor(self):
self.git('checkout', '-q', '-b', 'side')
(self.root / 'kept').write_text('3')
self.git('commit', '-qam', 'side')
side = self.git('rev-parse', 'HEAD').strip()
self.git('checkout', '-q', 'trunk')
self.assertTrue(deploy_fast.is_ancestor(self.base))
self.assertFalse(deploy_fast.is_ancestor(side))
class DonorTest(unittest.TestCase):
def test_pick_tag_takes_the_newest_ancestor(self):
commits = {'main-new': 'n', 'main-mid': 'm', 'main-old': 'o'}
with mock.patch.object(deploy_fast, 'release_tags', return_value=list(commits)), \
mock.patch.object(deploy_fast, 'donor_commit', side_effect=lambda tag: commits[tag]), \
mock.patch.object(deploy_fast, 'is_ancestor', side_effect=lambda commit: commit != 'n'):
self.assertEqual(deploy_fast.pick_tag(None), 'main-mid')
self.assertEqual(deploy_fast.pick_tag('main-new'), 'main-new')
def test_pick_tag_without_an_ancestor_is_refused(self):
with mock.patch.object(deploy_fast, 'release_tags', return_value=['main-a']), \
mock.patch.object(deploy_fast, 'donor_commit', return_value='a'), \
mock.patch.object(deploy_fast, 'is_ancestor', return_value=False):
with self.assertRaises(deploy_fast.Refused):
deploy_fast.pick_tag(None)
def test_checksum_mismatch_discards_the_cached_donor(self):
with tempfile.TemporaryDirectory() as directory:
folder = Path(directory) / 'main-x'
folder.mkdir()
apk = folder / 'DroidDeck-main-x.apk'
sums = folder / 'SHA256SUMS.txt'
apk.write_bytes(b'apk')
sums.write_text('0' * 64 + ' DroidDeck-main-x.apk\n')
with mock.patch.object(deploy_fast, 'CACHE', Path(directory)):
with self.assertRaises(deploy_fast.Refused):
deploy_fast.fetch_donor('main-x')
self.assertFalse(apk.exists())
apk.write_bytes(b'apk')
sums.write_text(hashlib.sha256(b'apk').hexdigest() + ' DroidDeck-main-x.apk\n')
self.assertEqual(deploy_fast.fetch_donor('main-x'), apk)
def test_a_cached_apk_without_checksums_is_downloaded_again(self):
with tempfile.TemporaryDirectory() as directory:
folder = Path(directory) / 'main-x'
folder.mkdir()
apk = folder / 'DroidDeck-main-x.apk'
apk.write_bytes(b'truncated')
calls = []
sums = hashlib.sha256(b'apk').hexdigest() + ' ' + apk.name + '\n'
def download(command, timeout, **options):
pattern = command[command.index('-p') + 1]
calls.append(pattern)
(folder / pattern).write_bytes(b'apk' if pattern.endswith('.apk') else sums.encode())
return mock.Mock(returncode=0, stderr='')
with mock.patch.object(deploy_fast, 'CACHE', Path(directory)):
with mock.patch.object(deploy_fast, 'run_bounded', download):
self.assertEqual(deploy_fast.fetch_donor('main-x'), apk)
self.assertEqual(calls, [apk.name, 'SHA256SUMS.txt'])
def test_a_failed_download_removes_the_apk_and_a_timeout_is_refused(self):
with tempfile.TemporaryDirectory() as directory:
folder = Path(directory) / 'main-x'
folder.mkdir()
apk = folder / 'DroidDeck-main-x.apk'
apk.write_bytes(b'partial')
failed = mock.Mock(returncode=1, stderr='boom')
with mock.patch.object(deploy_fast, 'CACHE', Path(directory)):
with mock.patch.object(deploy_fast, 'run_bounded', return_value=failed):
with self.assertRaises(deploy_fast.Refused):
deploy_fast.fetch_donor('main-x')
self.assertFalse(apk.exists())
timeout = deploy_fast.subprocess.TimeoutExpired('git', 1)
with mock.patch.object(deploy_fast.subprocess, 'run', side_effect=timeout):
with self.assertRaises(deploy_fast.Refused):
deploy_fast.git('status')
class SignTest(unittest.TestCase):
def test_paths_with_apostrophes_are_escaped_for_powershell(self):
seen = []
def run(command, **options):
seen.append(command)
return mock.Mock(returncode=1, stdout='', stderr='')
with mock.patch.object(deploy_fast, 'pwsh', return_value='pwsh'), \
mock.patch.object(deploy_fast, 'signing_env', return_value=None):
with mock.patch.object(deploy_fast, 'SIGNER', Path("C:/O'Brien/sign.ps1")):
with mock.patch.object(deploy_fast.subprocess, 'run', side_effect=run):
with self.assertRaises(deploy_fast.Refused):
deploy_fast.sign(Path("C:/a'b/in.apk"), Path("C:/a'b/out.apk"))
script = seen[0][-1]
self.assertIn("O''Brien", script)
self.assertIn("a''b", script)
self.assertNotIn("a'b", script.replace("a''b", ''))
self.assertNotIn("O'Brien", script.replace("O''Brien", ''))
def test_signing_env_prefers_the_override_then_the_checkout_then_the_main_checkout(self):
with tempfile.TemporaryDirectory() as directory:
base = Path(directory)
(base / 'main').mkdir()
(base / 'checkout').mkdir()
base = base.resolve()
override, local, shared = base / 'override.env', base / 'checkout/.signing.env', base / 'main/.signing.env'
common = (str(base / 'main/.git') + '\n').encode()
with mock.patch.object(deploy_fast, 'ROOT', base / 'checkout'), \
mock.patch.object(deploy_fast, 'git', return_value=common), \
mock.patch.dict(deploy_fast.os.environ, {'DROIDDECK_SIGNING_ENV': str(override)}):
self.assertIsNone(deploy_fast.signing_env())
shared.write_text('x')
self.assertEqual(deploy_fast.signing_env(), shared)
local.write_text('x')
self.assertEqual(deploy_fast.signing_env(), local)
override.write_text('x')
self.assertEqual(deploy_fast.signing_env(), override)
def test_the_env_signer_is_used_when_the_windows_signer_is_missing(self):
with tempfile.TemporaryDirectory() as directory:
base = Path(directory)
(base / 'build-tools/35.0.0').mkdir(parents=True)
for tool in ('aapt', 'zipalign', 'apksigner'):
(base / 'build-tools/35.0.0' / tool).write_text('')
signed = base / 'out.apk'
def run(command, **options):
signed.write_text('apk')
return mock.Mock(returncode=0, stdout='', stderr='')
with mock.patch.object(deploy_fast, 'SIGNER', base / 'missing.ps1'), \
mock.patch.object(deploy_fast, 'signing_env', return_value=base / '.signing.env'), \
mock.patch.object(deploy_fast, 'sdk_root', return_value=base), \
mock.patch.object(deploy_fast.subprocess, 'run', side_effect=run) as run_:
deploy_fast.sign(base / 'in.apk', signed)
self.assertEqual(run_.call_args[0][0][-4:], [str(deploy_fast.ROOT / 'tools/release/sign-apk.sh'), str(base / 'in.apk'), str(signed), str((base / 'build-tools/35.0.0').resolve())])
failed = mock.Mock(returncode=1, stdout='', stderr='boom')
signed.unlink()
with mock.patch.object(deploy_fast, 'SIGNER', base / 'missing.ps1'), \
mock.patch.object(deploy_fast, 'signing_env', return_value=base / '.signing.env'), \
mock.patch.object(deploy_fast, 'sdk_root', return_value=base), \
mock.patch.object(deploy_fast.subprocess, 'run', return_value=failed):
with self.assertRaises(deploy_fast.Refused):
deploy_fast.sign(base / 'in.apk', signed)
def test_the_newest_build_tools_win_numerically_and_the_env_file_cannot_replace_them(self):
with tempfile.TemporaryDirectory() as directory:
base = Path(directory).resolve()
for version in ('9.0.0', '35.0.0', '100.0.0'):
(base / 'build-tools' / version).mkdir(parents=True)
for tool in ('aapt', 'zipalign', 'apksigner'):
(base / 'build-tools' / version / tool).write_text('')
(base / 'build-tools/200.0.0').mkdir()
(base / 'build-tools/200.0.0/aapt').write_text('')
root = base / 'checkout'
(root / 'tools/release').mkdir(parents=True)
fake = root / 'tools/release/sign-apk.sh'
fake.write_text('#!/bin/bash\necho "$BUILD_TOOLS" > "$3"\n')
fake.chmod(0o755)
env_file = base / 'keys/.signing.env'
env_file.parent.mkdir()
env_file.write_text('BUILD_TOOLS=/wrong\n')
signed = base / 'out.apk'
with mock.patch.object(deploy_fast, 'ROOT', root), mock.patch.object(deploy_fast, 'sdk_root', return_value=base):
deploy_fast.sign_with_env(env_file, base / 'in.apk', signed)
self.assertEqual(signed.read_text().strip(), str(base / 'build-tools/100.0.0'))
if __name__ == '__main__':
unittest.main()
+88
View File
@@ -0,0 +1,88 @@
import os
from pathlib import Path
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu"
PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
FLAGS = " --no-sandbox --ozone-platform=x11"
def load():
source = SCRIPT.read_text()
assert source.rstrip().endswith("main()")
scope = {"__name__": "droiddeck_desktop_gpu"}
exec(compile(source.rstrip()[:-len("main()")], str(SCRIPT), "exec"), scope)
return scope
class DesktopChromiumAppsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.gpu = load()
self.electron = self.app("lib/chat/chat", sandbox=True)
self.plain = self.app("lib/editor/editor", sandbox=False)
bin_dir = self.root / "bin"
bin_dir.mkdir()
(bin_dir / "chat").symlink_to(self.electron)
old_path = os.environ.get("PATH", "")
os.environ["PATH"] = "%s:%s" % (bin_dir, old_path)
self.addCleanup(os.environ.__setitem__, "PATH", old_path)
def app(self, relative, sandbox):
path = self.root / relative
path.parent.mkdir(parents=True)
path.write_text("#!/bin/sh\n")
path.chmod(0o755)
if sandbox:
(path.parent / "chrome-sandbox").write_text("")
return path
def entry(self, exec_line, categories="Network;", actions=""):
text = "[Desktop Entry]\nType=Application\nName=App\nExec=%s\nCategories=%s\n" % (exec_line, categories)
if actions:
text += "Actions=new;\n\n[Desktop Action new]\nName=New\nExec=%s\n" % actions
return text
def exec_lines(self, text):
return [l[5:] for l in text.splitlines() if l.startswith("Exec=")]
def test_an_electron_app_starts_without_the_sandbox_on_x11(self):
out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U",
PREFIX + str(self.electron) + FLAGS + " --new"])
self.assertIn("X-DroidDeck-GPU=1", out)
self.assertIn("Actions=new;", out)
self.assertNotIn("droiddeck-window", out)
def test_a_command_on_the_path_is_followed_to_its_install_folder(self):
out = self.gpu["wrap"](self.entry("chat %U"))
self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"])
def test_a_quoted_program_keeps_its_quotes(self):
out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron))
self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"])
def test_other_apps_are_left_alone(self):
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain)))
self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F")))
def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"))
fixed = PREFIX + str(self.electron) + FLAGS
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed])
def test_with_the_gpu_off_electron_apps_are_still_fixed(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS])
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False))
def test_games_that_are_not_chromium_are_unchanged(self):
out = self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"))
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.plain), str(self.plain)])
if __name__ == "__main__":
unittest.main()
+104
View File
@@ -0,0 +1,104 @@
import json
import os
from pathlib import Path
import socket
import struct
import subprocess
import tempfile
import time
import unittest
IME = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-ime'
def message(obj, opcode, payload=b''):
return struct.pack('<II', obj, ((8 + len(payload)) << 16) | opcode) + payload
def wl_string(value):
data = value.encode() + b'\0'
return struct.pack('<I', len(data)) + data + b'\0' * (-len(data) % 4)
class DesktopImeTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.session = Path(self.temp.name)
self.server, client = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(self.server.close)
env = dict(os.environ, BL_LAUNCH_DIR=str(self.session), WAYLAND_SOCKET=str(client.fileno()))
self.proc = subprocess.Popen(['python3', str(IME)], env=env, pass_fds=[client.fileno()],
stderr=subprocess.PIPE, text=True)
client.close()
self.addCleanup(self.stop)
self.server.settimeout(5)
self.assertEqual(self.read(12), message(1, 1, struct.pack('<I', 2)))
self.server.sendall(message(2, 0, struct.pack('<I', 7) + wl_string('zwp_input_method_v1') + struct.pack('<I', 1)))
bind = self.read(8 + 4 + len(wl_string('zwp_input_method_v1')) + 8)
self.assertEqual(bind, message(2, 0, struct.pack('<I', 7) + wl_string('zwp_input_method_v1') + struct.pack('<II', 1, 3)))
def stop(self):
if self.proc.poll() is None:
self.proc.kill()
self.proc.wait(5)
self.proc.stderr.close()
def read(self, size):
data = b''
while len(data) < size:
chunk = self.server.recv(size - len(data))
if not chunk:
break
data += chunk
return data
def state(self, seq, timeout=5):
path = self.session / 'agent/ime.json'
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
snapshot = json.loads(path.read_text())
except (OSError, ValueError):
snapshot = None
if snapshot and snapshot['seq'] >= seq:
return snapshot
time.sleep(0.02)
self.fail('ime.json never reached seq %d' % seq)
def test_focus_and_blur_are_reported(self):
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
self.assertTrue(self.state(1)['textField'])
self.server.sendall(message(100, 2, struct.pack('<II', 0, 9)))
snapshot = self.state(2)
self.assertEqual((snapshot['textField'], snapshot['purpose']), (True, 9))
self.server.sendall(message(3, 1, struct.pack('<I', 100)))
self.assertEqual(self.read(8), message(100, 0))
self.assertFalse(self.state(3)['textField'])
self.assertEqual(oct((self.session / 'agent/ime.json').stat().st_mode & 0o777), '0o600')
def test_switching_fields_does_not_flicker(self):
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
self.assertTrue(self.state(1)['textField'])
self.server.sendall(message(3, 1, struct.pack('<I', 100)) + message(3, 0, struct.pack('<I', 101)))
self.assertEqual(self.read(8), message(100, 0))
time.sleep(0.4)
self.assertEqual(self.state(1), {'textField': True, 'hint': 0, 'purpose': 0, 'seq': 1})
def test_compositor_exit_clears_the_field(self):
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
self.assertTrue(self.state(1)['textField'])
self.server.close()
self.assertEqual(self.proc.wait(5), 0)
self.assertFalse(self.state(2)['textField'])
def test_a_protocol_error_clears_the_field(self):
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
self.assertTrue(self.state(1)['textField'])
self.server.sendall(message(1, 0, struct.pack('<II', 3, 1) + wl_string('bad request')))
self.assertEqual(self.proc.wait(5), 1)
self.assertFalse(self.state(2)['textField'])
if __name__ == '__main__':
unittest.main()
+38
View File
@@ -30,6 +30,7 @@ class DeviceControlsTest(unittest.TestCase):
page.evaluate.side_effect = evaluate
page.drain.side_effect = drain
helper.reconcile = mock.Mock()
helper.sync_frame_limit = mock.Mock()
helper.ensure_tools = mock.Mock(side_effect=[None, StopIteration])
helper.open_chooser = mock.Mock()
watcher = mock.Mock()
@@ -53,6 +54,8 @@ const assert = require('assert');
globalThis.window = globalThis;
const requests = [], callbacks = [];
const timers = [];
let now = 0;
Object.defineProperty(globalThis, 'performance', { value: { now: () => now }, configurable: true });
globalThis.setTimeout = callback => timers.push(callback);
let current = 1;
window.droiddeckBrightnessChanged = value => requests.push(Number(value));
@@ -68,16 +71,19 @@ const script = require('fs').readFileSync(process.argv[2], 'utf8');
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
const bridge = window.__droiddeckBrightness;
now = 10000;
bridge.set(0.5);
bridge.set(0.5);
assert.deepStrictEqual(requests, []);
callbacks.forEach(cb => cb({ flBrightness: 0.8 }));
assert.deepStrictEqual(requests, [0.8]);
now += 1000;
bridge.set(0.7992126);
assert.deepStrictEqual(requests, [0.8]);
for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value }));
assert.deepStrictEqual(requests, [0.8]);
assert.strictEqual(callbacks.length, 1);
now += 1000;
SteamClient.System.Display.SetBrightness = value => callbacks.forEach(cb => cb({ flBrightness: value + 0.1 }));
bridge.set(0.3);
assert.deepStrictEqual(requests, [0.8]);
@@ -88,6 +94,17 @@ bridge.set(0.65);
timers.forEach(callback => callback());
callbacks.forEach(cb => cb({ flBrightness: 0.7 }));
assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]);
// A held stick: Android's lagging readbacks must not pull Steam back while it keeps stepping.
let applied = [];
SteamClient.System.Display.SetBrightness = value => applied.push(value);
for (const value of [0.71, 0.72, 0.73]) { now += 50; callbacks.forEach(cb => cb({ flBrightness: value })); }
assert.strictEqual(bridge.set(0.71), 'held');
now += 100;
assert.strictEqual(bridge.set(0.72), 'held');
assert.deepStrictEqual(applied, []);
now += 800;
assert.strictEqual(bridge.set(0.3), true);
assert.deepStrictEqual(applied, [0.3]);
"""
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "bridge.js"
@@ -127,6 +144,27 @@ assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]);
finally:
globals_["CONTROLS_DIR"] = previous
def test_a_readback_held_by_the_bridge_is_retried_instead_of_cached(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
results = ["held", "held", True]
helper = LIVE["Helper"]("/steam", 0)
helper.controls_installed = True
helper.page = type("Page", (), {"evaluate": lambda self, expression: results.pop(0)})()
helper.sync_controls()
helper.sync_controls()
self.assertTrue(helper.controls_installed)
self.assertIsNone(helper.controls_state)
helper.sync_controls()
self.assertEqual(helper.controls_state["revision"], 1)
self.assertEqual(results, [])
finally:
globals_["CONTROLS_DIR"] = previous
def test_display_bridge_retries_binding_and_install_before_caching_state(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
+159
View File
@@ -635,6 +635,165 @@ class SteamKeyboardTest(unittest.TestCase):
self.assertFalse(watcher.attached)
self.assertEqual(3, log.call_count)
def test_requests_and_route_files(self):
watcher = agent.KeyboardWatcher(self.dir)
watcher.request()
watcher.request()
self.assertEqual({"seq": 2}, json.loads((self.dir / "keyboard-request.json").read_text()))
self.assertFalse(watcher.wanted_route())
(self.dir / "keyboard-route").write_text("bottom")
self.assertTrue(watcher.wanted_route())
(self.dir / "keyboard-route").write_text("top")
self.assertFalse(watcher.wanted_route())
watcher.event({"method": "Runtime.bindingCalled", "params": {"name": agent.KEYBOARD_BINDING, "payload": "request"}})
self.assertEqual({"seq": 3}, json.loads((self.dir / "keyboard-request.json").read_text()))
self.assertIsNone(self.state())
def test_dismissals_are_written_for_the_app(self):
watcher = agent.KeyboardWatcher(self.dir)
watcher.event({"method": "Runtime.bindingCalled", "params": {"name": agent.KEYBOARD_BINDING, "payload": "dismiss"}})
watcher.event({"method": "Runtime.bindingCalled", "params": {"name": agent.KEYBOARD_BINDING, "payload": "dismiss"}})
self.assertEqual({"seq": 2}, json.loads((self.dir / "keyboard-dismiss.json").read_text()))
self.assertFalse((self.dir / "keyboard-request.json").exists())
@unittest.skipUnless(shutil.which("node"), "node is not installed")
def test_page_script_reports_when_the_routed_field_loses_focus(self):
harness = r"""
const assert = require('assert');
globalThis.window = globalThis;
const fs = require('fs');
const script = fs.readFileSync(process.argv[2], 'utf8');
const route = fs.readFileSync(process.argv[3], 'utf8');
const calls = [];
window.droiddeckSteamKeyboard = value => calls.push(value);
const open = { m_currentValue: false };
const vkm = {
m_currentVirtualKeyboardRef: null,
IsShowingVirtualKeyboard: { m_currentValue: false },
m_bIsInlineVirtualKeyboardOpen: open,
m_bIsVirtualKeyboardModal: { m_currentValue: false },
BUseVRKeyboard: () => false,
m_Instance: { IsDesktopOverlayWindow: () => false },
SetActiveVirtualKeyboardTarget(ref, props) { this.m_currentVirtualKeyboardRef = ref; },
SetVirtualKeyboardHidden() { open.m_currentValue = false; this.m_currentVirtualKeyboardRef = null; },
ShowVirtualKeyboard(ref, props, modal) { this.m_currentVirtualKeyboardRef = ref; open.m_currentValue = true; },
};
globalThis.SteamUIStore = { WindowStore: { SteamUIWindows: [{ VirtualKeyboardManager: vkm }] } };
eval(script);
vkm.ShowVirtualKeyboard('a', {}, false);
eval(route.replace('__ROUTE__', 'true'));
assert.strictEqual(open.m_currentValue, false);
assert.strictEqual(vkm.m_currentVirtualKeyboardRef, 'a');
const wait = ms => new Promise(done => setTimeout(done, ms));
(async () => {
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), []);
vkm.m_currentVirtualKeyboardRef = null;
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss']);
vkm.ShowVirtualKeyboard('b', {}, false);
assert.strictEqual(open.m_currentValue, false);
vkm.m_currentVirtualKeyboardRef = null;
await wait(160);
vkm.ShowVirtualKeyboard('c', {}, false);
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss']);
vkm.m_currentVirtualKeyboardRef = null;
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss', 'dismiss']);
let focused = false;
vkm.ShowVirtualKeyboard({ BIsElementValidForInput: () => focused }, {}, false);
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss', 'dismiss']);
focused = true;
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss', 'dismiss']);
focused = false;
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss', 'dismiss', 'dismiss']);
const doc = { activeElement: { tagName: 'INPUT', type: 'text' } };
vkm.m_ownerWindow = { document: doc };
vkm.ShowVirtualKeyboard({ BIsElementValidForInput: () => false }, {}, false);
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss', 'dismiss', 'dismiss']);
doc.activeElement = { tagName: 'DIV' };
await wait(500);
assert.deepStrictEqual(calls.filter(c => c === 'dismiss'), ['dismiss', 'dismiss', 'dismiss', 'dismiss']);
clearInterval(window.__droiddeckKeyboard.timer);
})().catch(e => { console.error(e); process.exit(1); });
"""
(self.dir / "keyboard.js").write_text(agent.KEYBOARD_JS)
(self.dir / "route.js").write_text(agent.KEYBOARD_ROUTE_JS)
(self.dir / "harness.js").write_text(harness)
result = subprocess.run(["node", str(self.dir / "harness.js"), str(self.dir / "keyboard.js"), str(self.dir / "route.js")],
capture_output=True, text=True, timeout=20)
self.assertEqual(0, result.returncode, result.stderr)
def test_route_is_applied_once_per_change(self):
watcher = agent.KeyboardWatcher(self.dir)
sent = []
with patch.object(watcher, "call", side_effect=lambda ws, method, params: sent.append(params["expression"]) or {}):
watcher.apply_route(None)
watcher.apply_route(None)
(self.dir / "keyboard-route").write_text("bottom")
watcher.apply_route(None)
watcher.apply_route(None, force=True)
self.assertEqual(3, len(sent))
self.assertTrue(sent[0].rstrip().endswith("(false)"))
self.assertTrue(sent[1].rstrip().endswith("(true)"))
self.assertNotIn("__ROUTE__", sent[2])
self.assertNotIn("__BINDING__", sent[2])
@unittest.skipUnless(shutil.which("node"), "node is not installed")
def test_page_script_routes_the_keyboard_to_the_app(self):
harness = r"""
const assert = require('assert');
globalThis.window = globalThis;
const fs = require('fs');
const script = fs.readFileSync(process.argv[2], 'utf8');
const route = fs.readFileSync(process.argv[3], 'utf8');
const calls = [];
window.droiddeckSteamKeyboard = value => calls.push(value);
const shown = [], targets = [];
const open = { m_currentValue: false };
const vkm = {
IsShowingVirtualKeyboard: { m_currentValue: false },
m_bIsInlineVirtualKeyboardOpen: open,
m_bIsVirtualKeyboardModal: { m_currentValue: false },
BUseVRKeyboard: () => false,
m_Instance: { IsDesktopOverlayWindow: () => false },
SetActiveVirtualKeyboardTarget(ref, props) { targets.push(ref); },
SetVirtualKeyboardHidden() { open.m_currentValue = false; },
ShowVirtualKeyboard(ref, props, modal) { shown.push(ref); open.m_currentValue = true; },
};
globalThis.SteamUIStore = { WindowStore: { SteamUIWindows: [{ VirtualKeyboardManager: vkm }] } };
eval(script);
vkm.ShowVirtualKeyboard('a', {}, false);
assert.deepStrictEqual(shown, ['a']);
assert.strictEqual(eval(route.replace('__ROUTE__', 'true')), true);
assert.strictEqual(open.m_currentValue, false);
assert.deepStrictEqual(calls.filter(c => c === 'request'), ['request']);
vkm.ShowVirtualKeyboard('b', {}, false);
assert.deepStrictEqual(shown, ['a']);
assert.deepStrictEqual(targets, ['b']);
assert.deepStrictEqual(calls.filter(c => c === 'request'), ['request', 'request']);
vkm.ShowVirtualKeyboard('c', {}, true);
assert.deepStrictEqual(shown, ['a', 'c']);
eval(script);
vkm.ShowVirtualKeyboard('d', {}, false);
assert.deepStrictEqual(targets, ['b', 'd']);
eval(route.replace('__ROUTE__', 'false'));
vkm.ShowVirtualKeyboard('e', {}, false);
assert.deepStrictEqual(shown, ['a', 'c', 'e']);
clearInterval(window.__droiddeckKeyboard.timer);
"""
(self.dir / "keyboard.js").write_text(agent.KEYBOARD_JS)
(self.dir / "route.js").write_text(agent.KEYBOARD_ROUTE_JS)
(self.dir / "harness.js").write_text(harness)
result = subprocess.run(["node", str(self.dir / "harness.js"), str(self.dir / "keyboard.js"), str(self.dir / "route.js")],
capture_output=True, text=True, timeout=20)
self.assertEqual(0, result.returncode, result.stderr)
def test_no_shared_context_yet(self):
with patch.object(agent, "cdp_targets", return_value=[{"title": "Steam", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]):
with self.assertRaises(agent.AgentError) as caught:
+23
View File
@@ -326,6 +326,15 @@ class SignInHandoffTest(EpicTestCase):
self.assertEqual((None, None, "unix:abstract=a11y"),
(carried.get("NO_AT_BRIDGE"), carried.get("GTK_A11Y"), carried.get("AT_SPI_BUS_ADDRESS")))
def test_only_the_hidden_launcher_skips_the_store_and_fab_pages(self):
with mock.patch.dict(G, {"fex_environment": lambda fex, files, base: {}}):
visible = G["client_environment"]({}, None, None, ":0", "bus", "broker")
hidden = G["client_environment"]({}, None, None, ":2", "bus", "broker", hidden=True)
self.assertNotIn("DROIDDECK_EPIC_HIDDEN", visible)
self.assertNotIn("EGL_DISABLE_STORE_PREWARM", visible)
self.assertEqual(("1", "1"), (hidden.get("DROIDDECK_EPIC_HIDDEN"), hidden.get("EGL_DISABLE_STORE_PREWARM")))
self.assertEqual(visible["WEBKIT_SKIA_ENABLE_CPU_RENDERING"], hidden["WEBKIT_SKIA_ENABLE_CPU_RENDERING"])
def session(self):
session = G["Session"]("visible")
session.carried = True
@@ -906,6 +915,20 @@ class BrokerTest(EpicTestCase):
self.assertNotIn(G["STEAM_PRELOAD"], envs[0])
self.assertNotIn("LD_PRELOAD", envs[1])
def test_a_game_started_by_the_hidden_launcher_does_not_inherit_its_page_switches(self):
folder = self.tmp / "Fig"
folder.mkdir()
envs = []
def popen(command, env=None, cwd=None, start_new_session=False):
envs.append(env)
return mock.Mock(wait=mock.Mock(return_value=0))
with mock.patch.object(subprocess, "Popen", popen):
G["run_game"]({"exe": str(folder / "Fig.exe"), "args": []}, dict(G["HIDDEN_ENV"], PATH="/usr/bin"))
self.assertFalse(set(G["HIDDEN_ENV"]) & set(envs[0]))
self.assertEqual("/usr/bin", envs[0]["PATH"])
def test_an_owner_gone_ends_a_game_the_open_launcher_handed_to_steam(self):
broker, _ = self.broker("visible")
session = G["Session"]("visible")
+5 -3
View File
@@ -1085,7 +1085,9 @@ class LauncherTest(SyncTestCase):
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
(str(tool / "proton"), command)])
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1"))
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1"))
self.assertIn("could not start (", said.getvalue())
def test_generated_launchers_run_the_dist_proton(self):
@@ -1169,8 +1171,8 @@ class BundleTest(unittest.TestCase):
self.assertNotIn("if", bundle)
self.assertIn("tools/droiddeck-esync/release.env", bundle["run"])
self.assertIn('release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"', bundle["run"])
self.assertIn('curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"', bundle["run"])
self.assertIn('curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"', bundle["run"])
self.assertIn('curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"', bundle["run"])
self.assertIn('curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o sync-index.json "$release_url/index.json"', bundle["run"])
self.assertIn("sha256sum -c -", bundle["run"])
self.assertNotIn("revoked.txt", bundle["run"])
stage = {"run": (self.ROOT / recipes["runtime"]["script"]).read_text()}
+290
View File
@@ -0,0 +1,290 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
HEADER = Path(__file__).resolve().parents[1] / "proot/fastpath/svc-patch.h"
class FastPathSvcEncodingTest(unittest.TestCase):
def compile_check(self, source, header):
if shutil.which("cc") is None:
self.skipTest("cc is not available")
with tempfile.TemporaryDirectory() as directory:
program = Path(directory) / "check.c"
program.write_text(source.replace('"HEADER"', '"' + (HEADER.parent / header).as_posix() + '"'))
output = Path(directory) / "check"
subprocess.run(["cc", "-O2", "-Wall", "-Wextra", "-Werror", str(program), "-o", str(output)], check=True)
subprocess.run([str(output)], check=True, timeout=10)
def test_benchmark_checks_execute_with_ndebug(self):
self.compile_check(r'''
#define NDEBUG
#include "HEADER"
int main(void) {
int calls = 0;
assert(++calls == 1);
return calls != 1;
}
''', "../bench/checks.h")
def test_stack_bounds_and_alternate_stack_fallback(self):
self.compile_check(r'''
#define _GNU_SOURCE
#include <assert.h>
#include <stdint.h>
#include <stddef.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/resource.h>
static rlim_t stack_limit = 1024 * 1024;
static long sc(long n, long a, long b, long c, long d, long e) {
if (n == SYS_prlimit64) {
if (!stack_limit) return -1;
((struct rlimit *)d)->rlim_cur = stack_limit;
return 0;
}
return syscall(n,a,b,c,d,e);
}
#include "HEADER"
int main(void) {
uintptr_t low, high;
assert(svc_stack_line("1000-9000 rw-p 00000000 00:00 0", 0x8000, &low, &high));
assert(low == 0x1000 && high == 0x9000);
assert(!svc_stack_line("1000-9000 r--p", 0x8000, &low, &high));
assert(!svc_stack_line("1000-9000 rw-p", 0x9000, &low, &high));
assert(!svc_stack_line("9000-1000 rw-p", 0x8000, &low, &high));
assert(!svc_stack_line("fffffffffffffffff-9000 rw-p", 0x8000, &low, &high));
assert(!svc_stack_line("", 0x8000, &low, &high));
char local;
assert(svc_stack_find((uintptr_t)&local));
assert((uintptr_t)&local >= svc_stack_low && (uintptr_t)&local < svc_stack_high);
svc_stack_main = 0; svc_stack_low = 0x1000; svc_stack_high = 0x100000;
assert(!svc_stack_room(0x1000 + 96 * 1024 - 1));
assert(svc_stack_room(0x1000 + 96 * 1024));
svc_stack_main = 1; svc_stack_low = 0xf0000; svc_stack_gap = 0x1000;
assert(svc_stack_room(0xff000));
stack_limit = 64 * 1024;
assert(!svc_stack_room(0xff000));
stack_limit = 0;
assert(!svc_stack_room(0xff000));
return 0;
}
''', "svc-stack.h")
def test_patch_publication_failure_and_partial_success(self):
self.compile_check(r'''
#define _GNU_SOURCE
#include <assert.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
static struct svc_site { uint32_t *site; uint32_t branch; } svc_plan[3];
static size_t svc_planned = 3;
static unsigned svc_sites, svc_pages;
static int fail_alloc, fail_emit, fail_rx, fail_write, writes, live, rx;
static uint32_t *svc_relay_page(uintptr_t site, size_t page) {
(void)site;
if (fail_alloc) return NULL;
live++; rx = 0;
return calloc(1, page);
}
static int svc_emit(uint32_t *code, uint32_t *site, uint32_t *branch) {
(void)code; (void)site;
*branch = 0x14000001;
return !fail_emit;
}
static int mock_rx(void *p, size_t size, int prot) {
(void)p; (void)size;
assert(prot == (PROT_READ | PROT_EXEC));
if (fail_rx) return -1;
rx = 1;
return 0;
}
static int mock_unmap(void *p, size_t size) { (void)size; free(p); live--; return 0; }
static long sc(long nr, long fd, long buf, long len, long at, long unused) {
(void)fd; (void)unused;
assert(nr == SYS_pwrite64 && len == 4 && rx);
if (++writes == fail_write) return -1;
memcpy((void *)at, (void *)buf, len);
return len;
}
#define mprotect mock_rx
#define munmap mock_unmap
#include "HEADER"
int main(void) {
static uint32_t sites[3];
for (int mode = 0; mode < 5; mode++) {
for (int i=0; i<3; i++) { sites[i]=0xd4000001; svc_plan[i].site=&sites[i]; }
svc_sites=svc_pages=writes=live=rx=0;
fail_alloc=mode==0; fail_emit=mode==1; fail_rx=mode==2; fail_write=mode==3 ? 2 : 0;
svc_publish(7,4096);
if (mode<3) assert(!svc_sites && !svc_pages && !writes && !live);
else assert(svc_sites==(mode==3 ? 2U : 3U) && svc_pages==1 && live==1);
for (int i=0; i<3; i++) assert(sites[i]==(mode<3 || (mode==3 && i==1) ? 0xd4000001 : 0x14000001));
}
return 0;
}
''', "svc-publish.h")
def test_instruction_decoding_and_branch_limits(self):
if shutil.which("cc") is None:
self.skipTest("cc is not available")
source = r'''
#include <assert.h>
#include <stdint.h>
#include <stddef.h>
#define FP_SVC_ENCODINGS_ONLY
#include "HEADER"
int main(void) {
assert(svc_number(0xd2800708) == 56);
assert(svc_number(0x528009e8) == 79);
assert(svc_number(0xd2800709) == -1);
assert(svc_number(0xd2a00708) == -1);
assert(svc_number(0xf2800708) == -1);
assert(svc_number(0xaa0003e8) == -1);
const uint32_t create[] = {0xd2800708, 0x29047fe0, 0x92800c60, 0xd4000001};
const uint32_t create_at[] = {0xd2800708, 0x29047fe3, 0xb9404be3, 0xd4000001};
const uint32_t xstat[] = {0xd28009e8, 0xaa0203e1, 0xaa0303e2, 0x93407c83, 0xd4000001};
const uint32_t overwritten[] = {0xd2800708, 0xaa0003e8, 0xd4000001};
const uint32_t loaded[] = {0xd2800708, 0xf94003e8, 0xd4000001};
const uint32_t branch[] = {0xd2800708, 0x14000001, 0xd4000001};
const uint32_t call[] = {0xd2800708, 0x94000001, 0xd4000001};
const uint32_t shift[] = {0xd2800708, 0xd2a00708, 0xd4000001};
const uint32_t robust[] = {0xd2800c68, 0xf9000260, 0xa9000261, 0xf9400260, 0x9100e260, 0xd4000001};
const uint32_t writeback[] = {0xd2800708, 0xa9bf07e0, 0xd4000001};
const uint32_t added[] = {0xd2800708, 0x91000408, 0xd4000001};
assert(svc_site_number(create, 3) == 56);
assert(svc_site_number(create_at, 3) == 56);
assert(svc_site_number(xstat, 4) == 79);
assert(svc_site_number(overwritten, 2) == -1);
assert(svc_site_number(loaded, 2) == -1);
assert(svc_site_number(branch, 2) == -1);
assert(svc_site_number(call, 2) == -1);
assert(svc_site_number(shift, 2) == -1);
assert(svc_site_number(robust, 5) == 99);
assert(svc_site_number(writeback, 2) == -1);
assert(svc_site_number(added, 2) == -1);
uint32_t out;
uintptr_t pc = 0x10000000;
assert(svc_branch(pc, pc + 4, &out) && out == 0x14000001);
assert(svc_branch(pc, pc - 4, &out) && out == 0x17ffffff);
assert(svc_branch(pc, pc + 0x7fffffc, &out) && out == 0x15ffffff);
assert(svc_branch(pc, pc - 0x8000000, &out) && out == 0x16000000);
assert(!svc_branch(pc, pc + 0x8000000, &out));
assert(!svc_branch(pc, pc - 0x8000004, &out));
assert(!svc_branch(pc, pc + 2, &out));
return 0;
}
'''
with tempfile.TemporaryDirectory() as directory:
work = Path(directory)
program = work / "check.c"
program.write_text(source.replace("HEADER", HEADER.as_posix()))
output = work / "check"
subprocess.run(["cc", "-O2", "-Wall", "-Wextra", "-Werror", str(program), "-o", str(output)], check=True)
subprocess.run([str(output)], check=True, timeout=10)
def test_cache_revalidates_image_offsets_and_untrusted_files(self):
if shutil.which("cc") is None:
self.skipTest("cc is not available")
source = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <link.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#define FP_SVC_ENCODINGS_ONLY
#include "HEADER"
static int svc_android_api = 33;
static struct { uint32_t *site; } svc_plan[256];
static size_t svc_planned;
static int svc_supported(int nr) { return nr == 56 || nr == 79; }
#define sc(n,a,b,c,d,e) syscall(n,a,b,c,d,e)
static long fp_open(int d, const char *p, int f, mode_t m) { return openat(d,p,f,m); }
static long fp_rename(int d, const char *p, int e, const char *q, int f) { (void)f; return renameat(d,p,e,q); }
static long fp_unlink(int d, const char *p, int f) { return unlinkat(d,p,f); }
#include "CACHE"
static void store(const char *path, struct svc_cached_sites *table) {
int fd = open(path, O_WRONLY | O_TRUNC);
assert(fd >= 0 && write(fd, table, sizeof *table) == sizeof *table && close(fd) == 0);
}
int main(void) {
uint32_t image[32] = {0xd2800708, 0xd4000001, 0xd28009e8, 0xd4000001};
ElfW(Phdr) ph[] = {{.p_type=PT_LOAD, .p_flags=PF_R|PF_X, .p_memsz=sizeof image},
{.p_type=PT_NOTE, .p_vaddr=64, .p_memsz=24}};
struct dl_phdr_info info = {.dlpi_addr=(uintptr_t)image, .dlpi_phdr=ph, .dlpi_phnum=2};
ElfW(Nhdr) note = {.n_type=NT_GNU_BUILD_ID, .n_namesz=4, .n_descsz=8};
memcpy((char *)image+64, &note, sizeof note);
memcpy((char *)image+76, "GNU", 4);
uint64_t id = getpid();
memcpy((char *)image+80, &id, 8);
char path[256], other[256];
assert(svc_cache_name(&info, path, sizeof path));
svc_android_api = 35;
assert(svc_cache_name(&info, other, sizeof other) && strcmp(path, other));
svc_android_api = 33;
setenv("PROOT_FP_SVC_CACHE", "0", 1);
assert(!svc_cache_name(&info, other, sizeof other));
unsetenv("PROOT_FP_SVC_CACHE");
ph[1].p_memsz = sizeof image;
assert(!svc_cache_name(&info, other, sizeof other));
ph[1].p_memsz = 24;
svc_plan[0].site = image+1; svc_plan[1].site = image+3; svc_planned=2;
svc_cache_write(&info, path, 0);
svc_planned=0;
assert(svc_cache_read(&info, path) && svc_planned==2 && svc_plan[1].site==image+3);
struct svc_cached_sites valid, table;
int fd = open(path, O_RDONLY);
assert(fd >= 0 && read(fd, &valid, sizeof valid)==sizeof valid && close(fd)==0);
#define REJECT(change) do { table=valid; change; store(path,&table); svc_planned=0; \
assert(!svc_cache_read(&info,path) && svc_planned==0); } while(0)
REJECT(table.magic++);
REJECT(table.api=35);
REJECT(table.count=0);
REJECT(table.count=257);
REJECT(table.offset[0]=3);
REJECT(table.offset[0]=sizeof image);
REJECT(table.offset[0]=UINT64_MAX-3);
REJECT(table.offset[1]=table.offset[0]);
REJECT(table.offset[0]=12; table.offset[1]=4);
store(path,&valid);
image[1]=0x14000001;
assert(!svc_cache_read(&info,path));
image[1]=0xd4000001; image[0]=0xd2800008;
assert(!svc_cache_read(&info,path));
image[0]=0xd2800708;
assert(chmod(path,0644)==0 && !svc_cache_read(&info,path));
assert(chmod(path,0600)==0 && truncate(path,8)==0 && !svc_cache_read(&info,path));
assert(unlink(path)==0 && symlink("/dev/zero",path)==0 && !svc_cache_read(&info,path));
assert(unlink(path)==0 && mkdir(path,0700)==0 && !svc_cache_read(&info,path));
assert(rmdir(path)==0);
svc_planned=0;
svc_cache_write(&info,path,0);
assert(access(path,F_OK)<0);
(void)svc_cache_hits; (void)svc_cache_misses;
return 0;
}
'''
with tempfile.TemporaryDirectory() as directory:
work = Path(directory)
program = work / "cache.c"
program.write_text(source.replace('"HEADER"', '"' + HEADER.as_posix() + '"')
.replace('"CACHE"', '"' + HEADER.with_name("svc-cache.h").as_posix() + '"'))
output = work / "cache"
subprocess.run(["cc", "-O2", "-Wall", "-Wextra", "-Werror", str(program), "-o", str(output)], check=True)
subprocess.run([str(output)], check=True, timeout=10)
+139
View File
@@ -0,0 +1,139 @@
"""The Quick Access Frame Limit follows the panel when its refresh rate changes."""
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
HARNESS = r"""
const assert = require('assert');
globalThis.window = globalThis;
globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64');
let timers = new Map(), nextTimer = 0;
globalThis.setTimeout = (callback, ms) => { timers.set(++nextTimer, callback); return nextTimer; };
globalThis.clearTimeout = id => timers.delete(id);
globalThis.setInterval = () => 0;
const fire = async () => {
const pending = [...timers.values()]; timers = new Map();
for (const callback of pending) await callback();
};
let rates = [36, 48, 72, 144];
const notify = [];
const service = {
GetState: async () => ({ BSuccess: () => true,
Body: () => ({ toObject: () => ({ state: { active_display_info: { supported_frame_rates: rates } } }) }) }),
RegisterForNotifyStateChanged(callback) { notify.push(callback); return {}; },
SetBlurParams() {},
};
const writes = [];
globalThis.settingsStore = { clientSettings: {
gamescope_enable_app_target_framerate: true, gamescope_app_target_framerate: 120, gamescope_disable_framelimit: false } };
const varints = bytes => { const out = []; let value = 0, shift = 0;
for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } }
return out; };
globalThis.SteamClient = { Settings: { SetSetting(encoded) {
const [key, value] = varints([...Buffer.from(encoded, 'base64')]);
assert.strictEqual(key, 21002 * 8);
writes.push(value);
settingsStore.clientSettings.gamescope_app_target_framerate = value;
} } };
const modules = {
1: { source: () => 'RegisterForNotifyStateChanged only', exports: { other: { GetState() {} } } },
2: { source: () => 'n.MX.SetBlurParams(); n.MX.RegisterForNotifyStateChanged()', exports: { hooks: () => {} } },
3: { source: () => 'SetBlurParams RegisterForNotifyStateChanged GetState', exports: { MX: service } },
};
const webpack = modules => { const require = id => modules[id].exports;
require.m = Object.fromEntries(Object.entries(modules).map(([id, m]) => [id, { toString: m.source }]));
return require; };
globalThis.webpackChunksteamui = { push([, , callback]) { callback(webpack(modules)); } };
const script = require('fs').readFileSync(process.argv[2], 'utf8');
const change = async next => { rates = next; notify.forEach(callback => callback()); };
(async () => {
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
await fire();
assert.deepStrictEqual(writes, [144], 'a remembered limit the panel does not offer moves to the highest value');
await fire();
assert.deepStrictEqual(writes, [144], 'unchanged choices are not written again');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
await change([24, 30, 40, 60, 120]);
await fire();
assert.deepStrictEqual(writes, [144, 120], '72 is not offered at 120 Hz');
settingsStore.clientSettings.gamescope_app_target_framerate = 60;
await change([12, 15, 20, 30, 60]);
await fire();
assert.deepStrictEqual(writes, [144, 120], '60 is still offered at 60 Hz and is kept');
await change([18, 24, 36, 72]);
await change([24, 30, 40, 60, 120]);
await fire();
assert.deepStrictEqual(writes, [144, 120], 'a passing rate during a mode switch is not acted on');
settingsStore.clientSettings.gamescope_enable_app_target_framerate = false;
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
await change([36, 48, 144]);
await fire();
assert.deepStrictEqual(writes, [144, 120], 'nothing changes while Steam has the frame limit turned off');
settingsStore.clientSettings.gamescope_enable_app_target_framerate = true;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144], 'turning the limit on after a rate change moves an unoffered value');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
const setSetting = SteamClient.Settings.SetSetting;
SteamClient.Settings.SetSetting = () => { throw new Error('busy'); };
window.__droiddeckFrameLimit.schedule();
await fire();
SteamClient.Settings.SetSetting = setSetting;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144, 144], 'a failed write is tried again on the next check');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
SteamClient.Settings.SetSetting = () => Promise.reject(new Error('busy'));
window.__droiddeckFrameLimit.schedule();
await fire();
SteamClient.Settings.SetSetting = setSetting;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144, 144, 144], 'a rejected write is caught and tried again');
delete window.__droiddeckFrameLimit;
webpackChunksteamui.push = ([, , callback]) => callback(webpack({ 1: modules[1], 2: modules[2] }));
assert.strictEqual(eval(script), 'unavailable');
})().catch(error => { console.error(error); process.exit(1); });
"""
class FrameLimitSyncTest(unittest.TestCase):
def test_limit_is_kept_when_offered_and_moved_to_the_highest_value_otherwise(self):
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "frame_limit.js"
script.write_text(LIVE["FRAME_LIMIT_JS"])
test = Path(directory) / "test.js"
test.write_text(HARNESS)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_install_is_retried_until_steam_is_ready_and_reported_once_per_state(self):
helper = LIVE["Helper"]("/steam", 0)
page = mock.Mock()
page.evaluate.side_effect = ["unavailable", "unavailable", "installed"]
helper.page = page
said = []
clock = [100.0]
globals_ = LIVE["Helper"].sync_frame_limit.__globals__
with mock.patch.dict(globals_, {"say": said.append}), mock.patch.object(globals_["time"], "monotonic", lambda: clock[0]):
helper.sync_frame_limit()
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
self.assertEqual(page.evaluate.call_count, 3)
self.assertEqual(said, ["frame limit sync: unavailable", "frame limit sync: installed"])
if __name__ == "__main__":
unittest.main()
+358
View File
@@ -1,4 +1,5 @@
import hashlib
import io
import json
import os
import shutil
@@ -28,6 +29,139 @@ def config_text(entries):
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class GameDebugLoggingTest(unittest.TestCase):
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"},
"games": {"42": {"FEX_X87REDUCEDPRECISION": "1"}}}))
probe = home / "proton"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ['FEX_X87REDUCEDPRECISION'])\n")
probe.chmod(0o755)
base = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42")}
maintenance = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "run"],
env={**base, "DROIDDECK_GOG_MAINTENANCE": "1", "FEX_X87REDUCEDPRECISION": "0"}, text=True, capture_output=True, check=True)
game = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"],
env={**base, "FEX_X87REDUCEDPRECISION": "1"}, text=True, capture_output=True, check=True)
self.assertEqual("0", maintenance.stdout.strip())
self.assertEqual("1", game.stdout.strip())
def test_real_game_launch_without_config_file_keeps_the_base_environment(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
probe = home / "proton"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ['PROTON_LOG'])\n")
probe.chmod(0o755)
result = subprocess.run(
[sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"],
env={**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42"),
"BL_DEBUG_DIR": tmp, "PROTON_LOG": "0"},
text=True, capture_output=True, check=True,
)
self.assertEqual(result.stdout.strip(), "0")
def test_game_debug_logs_override_only_diagnostic_values_and_keep_raw_settings(self):
with tempfile.TemporaryDirectory(prefix="game logs '") as debug_dir:
inherited = {"BL_DEBUG_DIR": debug_dir, "PROTON_LOG": "0", "WINEDEBUG": "-all,+relay",
"PROTON_LOG_DIR": "/old", "PROTON_CRASH_REPORT_DIR": "/old-crashes",
"DXVK_LOG_PATH": "/old-dxvk", "DXVK_LOG_LEVEL": "none", "VKD3D_DEBUG": "none",
"CUSTOM": "$(touch never); 'quoted' = literal", "DXVK_CONFIG": "dxvk.tearFree = True"}
config = {"version": 1, "gameDebugLogs": True,
"shared": {"PROTON_LOG": "0", "BL_DEBUG_DIR": "/profile-redirect"},
"games": {"42": {"PROTON_LOG_DIR": None, "DXVK_LOG_PATH": "/game-redirect"}}}
normal = MODULE["apply_config"](inherited, config, "42")
debug = MODULE["apply_game_debug_logs"](normal, config, inherited["BL_DEBUG_DIR"])
self.assertEqual(debug["PROTON_LOG"], "1")
for key in ("PROTON_LOG_DIR", "PROTON_CRASH_REPORT_DIR", "DXVK_LOG_PATH"):
self.assertEqual(debug[key], debug_dir)
self.assertEqual(debug["DXVK_LOG_LEVEL"], "debug")
self.assertEqual(debug["VKD3D_DEBUG"], "info")
self.assertIn("+relay", debug["WINEDEBUG"].split(","))
self.assertTrue(debug["WINEDEBUG"].endswith("+loaddll,+mscoree"))
for key in ("CUSTOM", "DXVK_CONFIG", "BL_DEBUG_DIR"):
self.assertEqual(debug[key], normal[key])
self.assertEqual(normal["PROTON_LOG"], "0")
self.assertEqual(inherited["PROTON_LOG_DIR"], "/old")
self.assertIs(MODULE["apply_game_debug_logs"](normal, {**config, "gameDebugLogs": False}, debug_dir), normal)
self.assertEqual(MODULE["apply_game_debug_logs"](debug, config, debug_dir), debug)
def test_wine_debug_channels_are_formatted_deduplicated_and_diagnostics_win(self):
formatted = MODULE["game_debug_channels"](
" +relay, trace-vulkan, -all, -seh, +relay, trace+vulkan, garbage, $(touch never) ",
"+seh,warn-foo,warn+foo,+relay",
)
self.assertEqual(formatted, "-all,trace+vulkan,warn+foo,+relay," +
"+timestamp,+pid,+tid,+seh,+unwind,+threadname,+debugstr,+loaddll,+mscoree")
self.assertEqual(MODULE["game_debug_channels"](formatted, "1"), formatted)
self.assertNotIn("-seh", formatted)
for value in ("x\0,+relay", "+" + "x" * 8192, 1, None):
self.assertEqual(MODULE["game_debug_channels"](value), MODULE["game_debug_channels"]())
oversized = ",".join("+channel_" + str(i) for i in range(550))
other = ",".join("+other_" + str(i) for i in range(550))
self.assertLessEqual(len(MODULE["game_debug_channels"](oversized, other)), 8192)
self.assertTrue(MODULE["game_debug_channels"](oversized, other).endswith("+loaddll,+mscoree"))
def test_game_debug_logs_require_opt_in_and_a_real_session_log_directory(self):
env = {"PROTON_LOG": "user", "CUSTOM": "keep"}
for config in ({}, {"version": 1}, {"version": 1, "gameDebugLogs": False},
{"version": 1, "gameDebugLogs": "true"}, {"version": 2, "gameDebugLogs": True}):
self.assertIs(MODULE["apply_game_debug_logs"](env, config, "/"), env)
with tempfile.TemporaryDirectory() as tmp:
not_a_directory = Path(tmp) / "file"
not_a_directory.write_text("file")
for path in (None, "", "relative", "bad\0path", str(not_a_directory), str(Path(tmp) / "missing")):
with self.subTest(path=path):
self.assertIs(MODULE["apply_game_debug_logs"](env, {"version": 1, "gameDebugLogs": True}, path), env)
def test_game_debug_toggle_is_live_preserves_command_and_excludes_probes(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
config_path = home / ".config/droiddeck/game-environment.json"
config_path.parent.mkdir(parents=True)
debug_dir = home / "session logs '$literal; directory'"
debug_dir.mkdir()
probe = home / "fake proton"
probe.write_text("#!" + sys.executable + "\nimport json, os, sys\n"
"print(json.dumps({'env': dict(os.environ), 'argv': sys.argv[1:]}))\n")
probe.chmod(0o755)
literal = "$(touch " + str(home / "never-created") + "); 'literal'=value"
config = {"version": 1, "gameDebugLogs": True,
"shared": {"PROTON_LOG": "0", "WINEDEBUG": "-all,+relay", "CUSTOM": literal,
"BL_DEBUG_DIR": "/profile-must-not-redirect"}}
env = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42"),
"BL_DEBUG_DIR": str(debug_dir), "PROTON_LOG": "0", "WINEDEBUG": "-all"}
command = [str(probe), "waitforexitandrun", "game 'with quotes'.exe", "argument with spaces", "$(literal)", "%command%"]
def launch(arguments, environment):
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), *arguments],
env=environment, text=True, capture_output=True, check=True)
return json.loads(result.stdout)
for enabled in (True, False, True):
config_path.write_text(json.dumps({**config, "gameDebugLogs": enabled}))
result = launch(command, env)
self.assertEqual(result["argv"], command[1:])
self.assertEqual(result["env"]["CUSTOM"], literal)
self.assertEqual(result["env"]["PROTON_LOG"], "1" if enabled else "0")
if enabled:
self.assertEqual(result["env"]["PROTON_LOG_DIR"], str(debug_dir))
self.assertIn("+relay", result["env"]["WINEDEBUG"].split(","))
self.assertIn("+seh", result["env"]["WINEDEBUG"].split(","))
else:
self.assertEqual(result["env"]["WINEDEBUG"], "-all,+relay")
for verb, prefix in (("run", "42"), ("waitforexitandrun", "0"), ("waitforexitandrun", "not-a-game")):
result = launch([str(probe), verb], {**env, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata" / prefix)})
self.assertEqual(result["env"]["PROTON_LOG"], "0")
self.assertEqual(result["env"]["WINEDEBUG"], "-all")
# Non-Steam shortcuts use the same normalized unsigned compatdata identity.
result = launch(command, {**env, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/-1")})
self.assertEqual(result["env"]["PROTON_LOG"], "1")
self.assertFalse((home / "never-created").exists())
self.assertEqual(json.loads(config_path.read_text())["shared"], config["shared"])
class ReadConfigMappingTest(unittest.TestCase):
def test_missing_parent_or_unbalanced_vdf_is_not_treated_as_absent_choices(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -411,6 +545,27 @@ class GameEnvironmentTest(unittest.TestCase):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_d3dgear_capture_hook_beside_the_game_is_turned_off(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "The Crew 2"
game.mkdir()
for name in ("TheCrew2.exe", "TheCrew2_BE.exe", "d3dgear64.dll"):
(game / name).touch()
env, extra, notes = MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])
self.assertEqual((env, extra), ({"WINEDLLOVERRIDES": "d3dgear64=d"}, []))
self.assertTrue(notes)
(game / "d3dgear64.dll").rename(game / "D3DGear64.DLL")
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])[0], {"WINEDLLOVERRIDES": "d3dgear64=d"})
(game / "D3DGear64.DLL").unlink()
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), []), ({}, [], []))
def test_dll_overrides_from_several_fixes_are_all_kept(self):
with tempfile.TemporaryDirectory() as tmp:
for name in ("Game.exe", "Game.pck", "GodotSharp.dll", "libsentry.windows.release.x86_64.dll", "d3dgear64.dll"):
(Path(tmp) / name).touch()
env = MODULE["engine_fixes"](str(Path(tmp) / "Game.exe"), [])[0]
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d;d3dgear64=d")
def test_black_ops_iii_and_dark_souls_remastered_skip_protonfixes(self):
for exe in ("/game/Call of Duty Black Ops III/BlackOps3.exe", "/game/DARK SOULS REMASTERED/DarkSoulsRemastered.exe"):
env, extra, notes = MODULE["engine_fixes"](exe, [])
@@ -437,6 +592,179 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(calls, [{0, 1, 2}])
self.assertEqual(MODULE["parse_cores"]("0,2-7"), {0, 2, 3, 4, 5, 6, 7})
def test_windows_games_see_only_the_cores_they_are_pinned_to(self):
os_mod = MODULE["os"]
online = {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}
cases = [
({"BL_GAME_CPUS": "6,7"}, {6, 7}, "2:6,7", "2:6,7"),
({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, "3:0,1,2", "3:0,1,2"),
({"BL_GAME_CPUS": "0-7"}, set(range(8)), None, None),
({}, {6, 7}, None, None),
({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": "4:0,1,2,3"}, {6, 7}, "4:0,1,2,3", "4:0,1,2,3"),
({"WINE_CPU_TOPOLOGY": "2:0,1"}, set(range(8)), "2:0,1", "2:0,1"),
({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": ""}, {6, 7}, "", None),
({"BL_GAME_CPUS": "6,7", "PROTON_CPU_TOPOLOGY": "1:7"}, {6, 7}, None, "1:7"),
({"BL_GAME_CPUS": "9"}, {9}, None, None),
]
for env, affinity, expected, proton in cases:
env["DROIDDECK_FASTEST_CORES"] = "0"
with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
MODULE["cpu_topology"](env)
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton, env)
def test_only_games_get_the_larger_swapchain(self):
game = {"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/945360"}
self.assertTrue(MODULE["game_images"](game))
self.assertEqual(game["GAMESCOPE_WSI_MIN_IMAGE_COUNT"], "8")
self.assertEqual(game["GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT"], "1")
own = {"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/945360", "GAMESCOPE_WSI_MIN_IMAGE_COUNT": "3"}
MODULE["game_images"](own)
self.assertEqual(own["GAMESCOPE_WSI_MIN_IMAGE_COUNT"], "3")
for env in ({}, {"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}):
self.assertFalse(MODULE["game_images"](env))
self.assertNotIn("GAMESCOPE_WSI_MIN_IMAGE_COUNT", env)
def test_opengl_games_do_not_wait_for_the_screen_refresh(self):
cases = [
({}, "0"),
({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/-686078602"}, "0"),
({"vblank_mode": "2"}, "2"),
({"vblank_mode": ""}, ""),
({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}, None),
({"STEAM_COMPAT_DATA_PATH": ""}, None),
]
for env, expected in cases:
env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/3608888694")
added = expected == "0" and "vblank_mode" not in env
self.assertEqual(MODULE["gl_vsync"](env), added, env)
self.assertEqual(env.get("vblank_mode"), expected, env)
said = "OpenGL does not wait for the screen refresh"
with tempfile.TemporaryDirectory() as tmp:
probe = Path(tmp) / "probe"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('vblank_mode', 'unset'))\n")
probe.chmod(0o755)
config = Path(tmp) / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
for inherited, edits, expected in (({}, None, "0"), ({"vblank_mode": "3"}, None, "3"),
({}, {"vblank_mode": None}, "unset"), ({}, {"vblank_mode": "2"}, "2"),
({"vblank_mode": "3"}, {"vblank_mode": None}, "unset")):
with self.subTest(inherited=inherited, edits=edits):
config.write_text(json.dumps({"version": 1, "games": {"42": edits or {}}}))
env = {name: value for name, value in os.environ.items() if name != "vblank_mode"}
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42", **inherited)
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip(), expected)
self.assertEqual(said in result.stderr, expected == "0" and not inherited, result.stderr)
def test_teardown_keeps_its_own_vsync_unless_the_player_chose(self):
with tempfile.TemporaryDirectory() as tmp:
probe = Path(tmp) / "probe"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('vblank_mode', 'unset'))\n")
probe.chmod(0o755)
game = Path(tmp) / "Teardown/teardown.exe"
game.parent.mkdir()
game.write_bytes(b"MZ")
config = Path(tmp) / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
for inherited, edits, shared, expected in (({}, None, None, "2"), ({"vblank_mode": "0"}, None, None, "0"),
({}, {"vblank_mode": "1"}, None, "1"),
({}, None, {"vblank_mode": "1"}, "1")):
with self.subTest(inherited=inherited, edits=edits, shared=shared):
config.write_text(json.dumps({"version": 1, "shared": shared or {}, "games": {"1167630": edits or {}}}))
env = {name: value for name, value in os.environ.items() if name != "vblank_mode"}
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/1167630", **inherited)
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", str(game)],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip(), expected, result.stderr)
def test_windows_cpu_0_is_the_fastest_core(self):
os_mod = MODULE["os"]
pocket_fit = {0: 379, 1: 379, 2: 923, 3: 923, 4: 923, 5: 867, 6: 867, 7: 1024}
every = set(range(8))
with tempfile.TemporaryDirectory() as tmp:
proton = Path(tmp) / "proton"
proton.write_text('default_cpu_limit = {\n "19900" : "16", # Far Cry 2\n'
' "2229830" : "1", # Command & Conquer\n "11440" : "4", # DiRT\n'
' "1038250" : "P", # DIRT 5\n "618970" : 4, # Outcast, written as Proton 10 does\n'
'}\n\nother = {\n "620" : "2",\n}\n')
command = [str(proton), "waitforexitandrun", "/game/game.exe"]
cases = [
({}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"),
({"BL_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:7,6", "2:7,6"),
({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, pocket_fit, "3:2,0,1", "3:2,0,1"),
({"BL_GAME_CPUS": "0-7"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"),
({"WINE_CPU_TOPOLOGY": "2:0,1"}, every, pocket_fit, "2:0,1", "2:0,1"),
({"WINE_CPU_TOPOLOGY": ""}, every, pocket_fit, "", None),
({"PROTON_CPU_TOPOLOGY": "1:0"}, every, pocket_fit, None, "1:0"),
({"DROIDDECK_FASTEST_CORES": "0"}, every, pocket_fit, None, None),
({"SteamGameId": "2229830"}, every, pocket_fit, "1:7", "1:7"),
({"SteamGameId": "11440"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"),
({"SteamGameId": "19900"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"),
({"SteamGameId": "1038250"}, every, pocket_fit, None, None),
({"SteamGameId": "618970"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"),
({"SteamGameId": "620"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"),
({"SteamGameId": "2229830", "BL_GAME_CPUS": "0,1"}, {0, 1}, pocket_fit, "2:0,1", "2:0,1"),
({"SteamGameId": "2229830", "DROIDDECK_GAME_CORES": "12-13"}, every, pocket_fit, "1:7", "1:7"),
({"SteamGameId": "11440", "BL_GAME_CPUS": "0-7"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"),
({}, every, {core: 100 for core in every}, None, None),
({}, every, None, None, None),
({"SteamGameId": "11440"}, every, None, "4:0,1,2,3", "4:0,1,2,3"),
({"BL_GAME_CPUS": "9"}, {9}, pocket_fit, None, None),
]
cases += [
({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}, every, pocket_fit, None, None),
({"STEAM_COMPAT_DATA_PATH": ""}, every, pocket_fit, None, None),
({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0", "BL_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:6,7", "2:6,7"),
]
for env, affinity, speeds, expected, proton_topology in cases:
env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/3608888694")
with mock.patch.dict(MODULE["cpu_topology"].__globals__, {"online_cores": lambda: every}), \
mock.patch.dict(MODULE["fastest_first"].__globals__, {"core_speeds": lambda cores, speeds=speeds: speeds}), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
MODULE["cpu_topology"](env, command)
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton_topology, env)
self.assertIsNone(MODULE["proton_cpu_limit"](["/missing/proton"], {"SteamGameId": "11440"}))
self.assertIsNone(MODULE["proton_cpu_limit"](command, {}))
self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "1038250"}), "P")
self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "618970"}), 4)
def test_core_speeds_read_capacity_then_top_clock(self):
with tempfile.TemporaryDirectory() as tmp:
for core, capacity, clock in ((0, "379", "2265600"), (1, None, "3302400")):
folder = Path(tmp) / ("cpu%d" % core) / "cpufreq"
folder.mkdir(parents=True)
(folder / "cpuinfo_max_freq").write_text(clock + "\n")
if capacity:
(folder.parent / "cpu_capacity").write_text(capacity + "\n")
speeds = MODULE["core_speeds"]
self.assertEqual(speeds([0], tmp), {0: 379})
self.assertEqual(speeds([0, 1], tmp), {0: 2265600, 1: 3302400})
self.assertIsNone(speeds([0, 2], tmp))
def test_reskate_runs_at_feature_level_12_1(self):
with tempfile.TemporaryDirectory() as tmp:
reskate = Path(tmp) / "ReSkate"
reskate.mkdir()
for name in ("Skate.exe", "ReSkate.dll", "ReSkateLauncher.exe", "EAAntiCheat.GameServiceLauncher.exe"):
(reskate / name).touch()
for exe in ("ReSkateLauncher.exe", "Skate.exe"):
env, extra, notes = MODULE["engine_fixes"](str(reskate / exe), [])
self.assertEqual((env, extra), ({"VKD3D_FEATURE_LEVEL": "12_1"}, []), exe)
self.assertTrue(notes)
config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_1")
config["games"] = {"3354750": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_2")
skate = Path(tmp) / "Skate"
skate.mkdir()
for name in ("Skate.exe", "EAAntiCheat.GameServiceLauncher.exe"):
(skate / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(skate / "EAAntiCheat.GameServiceLauncher.exe"), [])[:2], ({}, []))
def test_caravan_sandwitch_robocop_and_cyberpunk_run_at_feature_level_12_1(self):
with tempfile.TemporaryDirectory() as tmp:
caravan = Path(tmp) / "Caravan SandWitch"
@@ -737,6 +1065,36 @@ class GameEnvironmentTest(unittest.TestCase):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
def test_both_proton_wrappers_answer_steams_driver_query_without_wine(self):
scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton"))
query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe"
probe = "/root/.local/share/Steam/steamapps/compatdata/0"
for script in scripts:
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("bl_components "))
for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"),
([query.replace("64.exe", ".exe")], probe)):
result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True,
env={"PATH": os.defpath, "HOME": "/nonexistent", "STEAM_COMPAT_DATA_PATH": prefix},
timeout=10)
self.assertEqual(result.returncode, 1, result.stderr)
self.assertEqual(result.stdout, "")
self.assertIn("D3D driver query is not run", result.stderr)
skip = COMPAT["BL_DRIVER_QUERY_SKIP"]
for verb, args, prefix in (
("getcompatpath", [query], probe),
("run", [query], "/root/.local/share/Steam/steamapps/compatdata/2276548447"),
("run", [query], None),
("waitforexitandrun", ["/games/AIO/AIO-Graphics-Test-64bit.exe", "--cube", "dx11"], probe),
("run", ["/games/Tool/tool.exe", query], probe),
("run", ["/games/d3ddriverquery64.exe.bak"], probe)):
env = {"PATH": os.defpath}
if prefix is not None:
env["STEAM_COMPAT_DATA_PATH"] = prefix
out = subprocess.run(["bash", "-c", "verb=" + verb + "\n" + skip + "echo continued", "_"] + args,
env=env, capture_output=True, text=True, check=True).stdout
self.assertEqual(out, "continued\n", (verb, args, prefix))
def test_wrappers_preload_the_session_library_before_the_input_shim(self):
overlay = "/root/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so"
with tempfile.TemporaryDirectory() as tmp:
+216
View File
@@ -0,0 +1,216 @@
import contextlib
import concurrent.futures
import errno
import json
import os
from pathlib import Path
import runpy
import subprocess
import sys
import stat
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
G = runpy.run_path(str(BIN / "droiddeck-gog-maintenance"))["main"].__globals__
class GogMaintenance(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.folder = Path(self.temp.name)
self.control = G["control"](self.folder)
(self.folder / ".droiddeck-store.json").write_text(json.dumps({"store": "gog", "id": "1"}))
def test_only_downloaded_windows_executables_can_be_patches(self):
download = self.control / "downloads"
download.mkdir()
patch = download / "patch.exe"
patch.write_bytes(b"MZtest")
self.assertEqual(patch, G["validate_installer"](self.folder, patch))
outside = self.folder / "outside.exe"
outside.write_bytes(b"MZtest")
with self.assertRaises(ValueError):
G["validate_installer"](self.folder, outside)
patch.write_bytes(b"not PE")
with self.assertRaises(ValueError):
G["validate_installer"](self.folder, patch)
def test_overlapping_metadata_writes_publish_complete_documents(self):
target = self.control / "operation.json"
def publish(value):
G["write"](target, {"value": value, "payload": str(value) * 10000})
result = G["read"](target)
self.assertEqual(str(result["value"]) * 10000, result["payload"])
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
list(pool.map(publish, range(32)))
self.assertEqual([], list(self.control.glob("*.new")))
def test_directory_sync_unsupported_by_external_storage_keeps_the_record(self):
original = os.fsync
def fsync(fd):
if stat.S_ISDIR(os.fstat(fd).st_mode):
raise OSError(errno.EINVAL, "directory sync unsupported")
return original(fd)
target = self.control / "operation.json"
with mock.patch.object(G["os"], "fsync", side_effect=fsync):
G["write"](target, {"phase": "download"})
self.assertEqual("download", G["read"](target)["phase"])
def test_unsuccessful_registry_preparation_never_runs_the_installer(self):
download = self.control / "downloads"; download.mkdir()
patch = download / "patch.exe"; patch.write_bytes(b"MZtest")
prefix = self.folder / "prefix/pfx"
(prefix / "drive_c/windows/system32").mkdir(parents=True)
(prefix / "drive_c/windows/system32/reg.exe").write_bytes(b"MZreg")
(prefix / "system.reg").write_text("registry")
for result in ("timeout", "import-failed", "no-proton", "none", "unexpected"):
with self.subTest(result=result):
G["write"](self.control / "operation.json", {"phase": "patch-starting", "before": {"id": "1"}})
def setup_main():
pass
with mock.patch.dict(setup_main.__globals__, {"apply_gog_registry": lambda *a, **k: result}), \
mock.patch.dict(G, {"runner": lambda *a: ("/proton", {}, str(self.folder / "prefix")), "active": lambda *a: []}), \
mock.patch.object(G["runpy"], "run_path", return_value={"main": setup_main}), \
mock.patch.object(G["subprocess"], "Popen") as spawn:
self.assertEqual(1, G["run_patch"](str(self.folder), "1", str(patch), "game.exe"))
spawn.assert_not_called()
self.assertIn("registry preparation failed", G["read"](self.control / "patch-status.json")["reason"])
def test_only_recognized_inno_installers_get_the_gog_ui_compatibility_argument(self):
path = self.folder / "patch.exe"
path.write_bytes(b"MZunknown installer")
self.assertEqual([], G["installer_arguments"](path))
path.write_bytes(b"MZdata Inno Setup Setup Data (6.2.1)")
self.assertEqual(["/NOGUI"], G["installer_arguments"](path))
def test_game_launch_lease_excludes_updater_and_releases_on_owner_exit(self):
import fcntl
owner = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
self.addCleanup(lambda: owner.poll() is None and owner.kill())
lease = subprocess.Popen([sys.executable, str(BIN / "droiddeck-gog-maintenance"), "lease", str(self.folder), str(owner.pid)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.addCleanup(lease.stdout.close)
self.addCleanup(lease.stderr.close)
self.addCleanup(lambda: lease.poll() is None and lease.kill())
self.assertEqual(b"ready\n", lease.stdout.readline())
with G["lock_file"](self.control) as stream:
with self.assertRaises(BlockingIOError):
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
owner.terminate(); owner.wait()
lease.wait(timeout=5)
with G["lock_file"](self.control) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
def test_incomplete_update_cannot_launch(self):
(self.folder / ".droiddeck-store.json").write_text(json.dumps({"store": "gog", "id": "1", "state": "updating"}))
with self.assertRaises(ValueError):
G["lease"](self.folder, os.getpid())
def test_running_game_and_wrong_prefix_are_distinguished(self):
proc = self.folder / "proc"
for pid, prefix, name in [(10, "/prefix/pfx", "game.exe"), (11, "/other/pfx", "other.exe"), (12, "/prefix/pfx", "services.exe")]:
row = proc / str(pid); row.mkdir(parents=True)
(row / "environ").write_bytes(b"WINEPREFIX=" + prefix.encode() + b"\0")
(row / "cmdline").write_bytes(name.encode() + b"\0")
self.assertEqual([10], G["active"]("/prefix", proc))
def test_desktop_installer_inherits_the_nested_display_not_the_bridge_display(self):
proc = self.folder / "proc"
row = proc / "10"; row.mkdir(parents=True)
(row / "cmdline").write_bytes(b"/usr/bin/plasmashell\0")
(row / "environ").write_bytes(b"BL_DESKTOP=1\0XDG_RUNTIME_DIR=/run/session\0WAYLAND_DISPLAY=wayland-1\0DISPLAY=:0\0XAUTHORITY=/run/session/auth\0UNRELATED=value\0")
env = G["desktop_environment"]({"DROIDDECK_GOG_DESKTOP": "1", "XDG_RUNTIME_DIR": "/run/session", "WAYLAND_DISPLAY": "wayland-0"}, proc)
self.assertEqual("wayland-1", env["WAYLAND_DISPLAY"])
self.assertEqual(":0", env["DISPLAY"])
self.assertEqual("/run/session/auth", env["XAUTHORITY"])
self.assertEqual("1", env["BL_DESKTOP"])
self.assertNotIn("UNRELATED", env)
def test_maintenance_uses_full_x87_precision_without_changing_game_preferences(self):
target = mock.Mock(compatdata="/selected/prefix", appid="2526420341")
run = {"tools": lambda root: {"selected": ("/selected/proton", "proton")},
"mapping": lambda root: {}, "choose_tool": lambda *args: ("selected", None),
"environment": lambda env, *args, **kwargs: dict(env)}
with mock.patch.dict(G, {"target_for": lambda *args: (run, "/steam", target)}), \
mock.patch.dict(os.environ, {"FEX_X87REDUCEDPRECISION": "1"}):
command, env, prefix = G["runner"]("/game", "2526420341", "/game/game.exe")
self.assertEqual("/selected/proton/proton", command)
self.assertEqual("/selected/prefix", prefix)
self.assertEqual("0", env["FEX_X87REDUCEDPRECISION"])
self.assertEqual("1", os.environ["FEX_X87REDUCEDPRECISION"])
def test_legacy_setup_uses_authentic_timestamp_and_support_layout(self):
program = self.folder / "support/1/setup.exe"
program.parent.mkdir(parents=True); program.write_bytes(b"MZtest")
record = {"id": "1", "build": "3301", "products": ["1"], "language": "en-US", "manifest": {"product": {
"timestamp": 31847977, "support_commands": [{"gameID": "1", "executable": "/setup.exe", "languages": ["English"]}]}}}
G["write"](self.control / "installed.json", {"verified": False})
G["write"](self.control / "operation.json", {"before": record})
G["write"](self.folder / "goggame-1.info", {"language": "English"})
with mock.patch.object(G["subprocess"], "run", return_value=mock.Mock(returncode=0)) as run:
G["prepare_setup"](str(self.folder), "/proton", {})
args = run.call_args.args[0]
self.assertEqual(str(program), args[2])
self.assertIn("/buildId=31847977", args)
self.assertNotIn("/buildId=3301", args)
self.assertIn("/Language=English", args)
def test_interrupted_patch_is_not_started_again(self):
(self.control / "operation.json").write_text(json.dumps({"phase": "patch-applying"}))
with mock.patch.dict(G, {"validate_installer": lambda *a: self.folder / "patch.exe"}):
with self.assertRaises(ValueError):
G["start"](str(self.folder), "2147483666", "patch.exe", "game.exe")
def test_dead_installer_helper_requires_recovery_without_replay(self):
G["write"](self.control / "operation.json", {"phase": "patch-applying"})
G["write"](self.control / "patch-status.json", {"state": "running", "pid": 99999999, "generation": "123"})
with mock.patch.dict(G, {"generation": lambda pid: None}), mock.patch.object(G["subprocess"], "Popen") as spawn:
self.assertEqual(0, G["status"](str(self.folder)))
self.assertFalse(spawn.called)
self.assertEqual("uncertain", G["read"](self.control / "patch-status.json")["state"])
self.assertEqual("patch-uncertain", G["read"](self.control / "operation.json")["phase"])
def test_abandoned_start_and_confirmed_completion_are_distinct(self):
G["write"](self.control / "operation.json", {"phase": "patch-starting"})
G["write"](self.control / "patch-status.json", {"state": "starting", "startedAt": 10})
with mock.patch.object(G["time"], "time", return_value=100):
G["status"](str(self.folder))
self.assertEqual("uncertain", G["read"](self.control / "patch-status.json")["state"])
G["write"](self.control / "patch-status.json", {"state": "done", "exitCode": 0})
G["status"](str(self.folder))
self.assertEqual({"state": "done", "exitCode": 0}, G["read"](self.control / "patch-status.json"))
def test_registry_and_installer_use_same_prefix_without_cloud_launch(self):
download = self.control / "downloads"; download.mkdir()
patch = download / "patch.exe"; patch.write_bytes(b"MZtest")
prefix = self.folder / "prefix/pfx"
(prefix / "drive_c/windows/system32").mkdir(parents=True)
(prefix / "drive_c/windows/system32/reg.exe").write_bytes(b"MZreg")
(prefix / "system.reg").write_text("registry")
G["write"](self.control / "operation.json", {"phase": "patch-starting"})
calls = []
setup = {"main": lambda: None}
def setup_main():
pass
setup_main.__globals__["apply_gog_registry"] = lambda *a, **k: calls.append(("registry", a[1])) or "written=1"
fake = mock.Mock(); fake.wait.return_value = 0
def spawn(argv, **kwargs):
self.assertEqual("run", argv[1])
self.assertEqual("1", kwargs["env"]["DROIDDECK_GOG_MAINTENANCE"])
calls.append(("patch", kwargs["env"]["STEAM_COMPAT_DATA_PATH"]))
return fake
with mock.patch.dict(G, {"runner": lambda *a: ("/proton", {"STEAM_COMPAT_DATA_PATH": str(self.folder / "prefix"), "DROIDDECK_GOG_MAINTENANCE": "1"}, str(self.folder / "prefix")),
"active": lambda *a: []}), \
mock.patch.object(G["runpy"], "run_path", return_value={"main": setup_main}), \
mock.patch.object(G["subprocess"], "Popen", side_effect=spawn):
self.assertEqual(0, G["run_patch"](str(self.folder), "2147483666", str(patch), "game.exe"))
self.assertEqual([("registry", str(self.folder / "prefix")), ("patch", str(self.folder / "prefix"))], calls)
self.assertEqual("done", G["read"](self.control / "patch-status.json")["state"])
self.assertEqual("updating", G["read"](self.folder / ".droiddeck-store.json")["state"])
if __name__ == "__main__":
unittest.main()
+136
View File
@@ -0,0 +1,136 @@
from pathlib import Path
import os
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0125-droiddeck-hud-frame-times.patch"
READER = ROOT / "app/src/main/cpp/waylandcomp/src/hudframes.c"
def patch_writer():
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
text = "\n".join(added)
start = text.index("// DroidDeck's own HUD reads")
end = text.index("\n}\n", text.index("static void publish_droiddeck_hud_info()", start)) + 3
return text[start:end]
PREAMBLE = r'''
#include <assert.h>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <memory>
#include <mutex>
#include <string>
#include <sys/mman.h>
#include <unistd.h>
#include <unordered_map>
extern "C" {
#include "hudframes.h"
}
struct steamcompmgr_win_t { int appID; };
struct global_focus_t {
uint64_t ulBasePlaneCommitID = 0;
pid_t nFocusWindowPid = 0;
std::shared_ptr<std::string> pFocusWindowEngine;
steamcompmgr_win_t *inputFocusWindow = nullptr;
};
static std::unordered_map<uint64_t, global_focus_t> g_VirtualConnectorFocuses;
static global_focus_t *GetCurrentFocus() { return nullptr; }
static bool window_is_steam(steamcompmgr_win_t *w) { return w && w->appID == 769; }
static uint64_t g_now = 1000000000ull;
static uint64_t get_time_in_nanos() { return g_now; }
static uint32_t g_nOutputWidth = 1280, g_nOutputHeight = 720;
static int g_nOutputRefresh = 144000;
struct Log {
void infof(const char *, ...) {}
void errorf_errno(const char *fmt, ...) { va_list a; va_start(a, fmt); vfprintf(stderr, fmt, a); va_end(a); }
} xwm_log;
'''
MAIN = r'''
static void frame(uint64_t step) { g_now += step; droiddeck_hud_app_frame(g_now); }
int main(int argc, char **argv) {
setenv("DROIDDECK_HUD_FRAMES", argv[1], 1);
assert(droiddeck_hud_frames_wanted());
global_focus_t &focus = g_VirtualConnectorFocuses[0];
focus.nFocusWindowPid = 4242;
focus.pFocusWindowEngine = std::make_shared<std::string>("DXVK");
steamcompmgr_win_t game{ 12345 };
focus.inputFocusWindow = &game;
publish_droiddeck_hud_info();
droiddeck_hud_app_frame(g_now);
struct hud_frames *h = hud_frames_open(argv[1]);
assert(h);
int64_t ft[2048], tm[2048];
assert(hud_frames_poll(h, ft, tm, 2048) == 0);
const uint64_t steps[] = { 2700000, 2800000, 41600000, 6944000 };
for (uint64_t step : steps) frame(step);
int n = hud_frames_poll(h, ft, tm, 2048);
assert(n == 4);
for (int i = 0; i < 4; i++) assert((uint64_t)ft[i] == steps[i]);
assert((uint64_t)tm[3] == g_now);
assert(hud_frames_poll(h, ft, tm, 2048) == 0);
int32_t info[5];
char engine[41];
assert(hud_frames_info(h, info, engine, sizeof(engine)));
assert(info[0] == 4242 && info[1] == 1280 && info[2] == 720 && info[3] == 144000 && info[4] == 0);
assert(strcmp(engine, "DXVK") == 0);
game.appID = 769;
publish_droiddeck_hud_info();
assert(hud_frames_info(h, info, engine, sizeof(engine)) && info[4] == 1);
for (int i = 0; i < 3000; i++) frame(1000000 + i);
n = hud_frames_poll(h, ft, tm, 2048);
assert(n == 1024);
assert(ft[1023] == 1000000 + 2999);
assert(ft[0] == 1000000 + 2999 - 1023);
for (int i = 0; i < 10; i++) frame(2000000);
assert(hud_frames_poll(h, ft, tm, 4) == 4 && ft[3] == 2000000);
hud_frames_close(h);
puts("ok");
return 0;
}
'''
@unittest.skipUnless(shutil.which("cc") and shutil.which("c++"), "needs a C and C++ compiler")
class HudFramesTest(unittest.TestCase):
def test_gamescope_writer_and_app_reader_agree(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
source = tmp / "writer.cpp"
source.write_text(PREAMBLE + patch_writer() + MAIN)
include = READER.parent
subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-c", str(READER), "-o", str(tmp / "reader.o")], check=True)
subprocess.run(["c++", "-std=c++20", "-Wall", "-Werror", "-Wno-unused-function", f"-I{include}", str(source), str(tmp / "reader.o"),
"-o", str(tmp / "hudframes")], check=True)
result = subprocess.run([str(tmp / "hudframes"), str(tmp / "frames")], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), "ok")
self.assertEqual(os.path.getsize(tmp / "frames"), 128 + 1024 * 16)
def test_session_points_gamescope_at_the_file_the_app_reads(self):
session = (ROOT / "tools/linuxfs/overlay/usr/local/bin/droiddeck-session").read_text()
self.assertIn("export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames", session)
app = (ROOT / "app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt").read_text()
self.assertIn('"run/droiddeck-hud/frames"', app)
if __name__ == "__main__":
unittest.main()
+98
View File
@@ -0,0 +1,98 @@
import os
from pathlib import Path
import stat
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-library-perms"
class LibraryPermsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.restore)
self.root = Path(self.temp.name)
self.home = self.root / "home"
self.steam = self.home / ".local/share/Steam"
self.card = self.root / "card"
self.stores = self.root / "stores"
(self.steam / "steamapps").mkdir(parents=True)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n\t"1"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n'
% (self.steam, self.card))
self.locked = []
def restore(self):
for path in self.locked:
if path.exists() and not path.is_symlink():
path.chmod(0o700 if path.is_dir() else 0o600)
for path in sorted(self.root.rglob("*"), key=lambda p: len(p.parts), reverse=True):
if path.is_dir() and not path.is_symlink():
path.chmod(0o700)
self.temp.cleanup()
def file(self, path, mode=0o400):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("x")
path.chmod(mode)
self.locked.append(path)
return path
def folder(self, path, mode=0o500):
path.mkdir(parents=True, exist_ok=True)
self.locked.append(path)
return path
def run_script(self):
env = dict(os.environ, HOME=str(self.home), DROIDDECK_STORES_ROOT=str(self.stores))
for path in reversed(self.locked):
if path.is_dir():
path.chmod(0o500)
return subprocess.run([sys.executable, str(SCRIPT)], env=env, check=True, capture_output=True, text=True).stdout
def mode(self, path):
return stat.S_IMODE(os.lstat(path).st_mode)
def test_read_only_game_files_and_folders_become_writable_in_every_library(self):
ini = self.file(self.steam / "steamapps/compatdata/3712566526/pfx/drive_c/users/steamuser/Documents/My Games/FalloutNV/FALLOUT.INI")
data = self.folder(self.steam / "steamapps/common/Game/Data")
game = self.file(data / "game.esm", 0o444)
card = self.file(self.card / "steamapps/common/Other/settings.ini")
gog = self.file(self.home / "Games/Stores/GOG/Fallout New Vegas/Fallout_default.ini")
store = self.file(self.stores / "abc/Game/config.cfg")
out = self.run_script()
self.assertEqual(self.mode(ini) & 0o600, 0o600)
self.assertEqual(self.mode(game), 0o644)
self.assertEqual(self.mode(data) & 0o700, 0o700)
for path in (card, gog, store):
self.assertEqual(self.mode(path) & 0o600, 0o600, path)
self.assertIn("made writable", out)
def test_proton_and_steam_runtimes_are_left_as_valve_ships_them(self):
proton = self.file(self.steam / "steamapps/common/Proton Experimental (ARM64)/files/lib/wine/a.so", 0o444)
runtime = self.file(self.card / "steamapps/common/SteamLinuxRuntime_sniper/run", 0o555)
nested = self.file(self.steam / "steamapps/common/Game/Proton notes.txt")
self.run_script()
self.assertEqual(self.mode(proton), 0o444)
self.assertEqual(self.mode(runtime), 0o555)
self.assertEqual(self.mode(nested) & 0o600, 0o600)
def test_symlinks_are_not_followed(self):
outside = self.file(self.root / "outside/keep.ini")
link = self.steam / "steamapps/compatdata/1/pfx/dosdevices/z:"
link.parent.mkdir(parents=True)
link.symlink_to(self.root / "outside")
self.run_script()
self.assertEqual(self.mode(outside), 0o400)
def test_writable_files_are_untouched_and_missing_libraries_are_fine(self):
fine = self.file(self.steam / "steamapps/common/Game/ok.ini", 0o640)
out = self.run_script()
self.assertEqual(self.mode(fine), 0o640)
self.assertIn("0 files and folders made writable", out)
if __name__ == "__main__":
unittest.main()
+123 -4
View File
@@ -94,7 +94,7 @@ COUNTER = r"""
#include <sys/stat.h>
#include <unistd.h>
static int opens, stats, links;
static int opens, stats, links, statxs;
int openat(int dirfd, const char *path, int flags, ...) {
va_list args;
@@ -120,8 +120,13 @@ ssize_t readlinkat(int dirfd, const char *path, char *buf, size_t size) {
return ((ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"))(dirfd, path, buf, size);
}
int statx(int dirfd, const char *path, int flags, unsigned int mask, struct statx *out) {
statxs++;
return ((int (*)(int, const char *, int, unsigned int, struct statx *))dlsym(RTLD_NEXT, "statx"))(dirfd, path, flags, mask, out);
}
__attribute__((destructor)) static void report(void) {
fprintf(stderr, "calls %d %d %d\n", opens, stats, links);
fprintf(stderr, "calls %d %d %d %d\n", opens, stats, links, statxs);
}
"""
@@ -141,6 +146,83 @@ int main(int argc, char **argv) {
}
"""
WRAPPER = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef SYS_openat2
#define SYS_openat2 437
#endif
struct how { uint64_t flags, mode, resolve; };
int main(int argc, char **argv) {
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_openat2, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
if (argc < 3 || prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return 3;
int (*call)(int, const char *, struct how *, size_t) = (int (*)(int, const char *, struct how *, size_t))dlsym(RTLD_DEFAULT, "openat2");
if (!call) return 4;
int dir = open(argv[1], O_PATH | O_DIRECTORY | O_CLOEXEC);
struct how h = {O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644, 0x08};
int fd = call(dir, argv[2], &h, sizeof(h));
if (fd < 0) {
printf("ERR %d\n", errno);
return 1;
}
printf("OK\n");
return close(fd);
}
"""
RAW_LOOKUP = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef SYS_newfstatat
#define RAW_FSTATAT SYS_newfstatat
#else
#define RAW_FSTATAT SYS_fstatat64
#endif
int main(int argc, char **argv) {
struct stat st;
struct statx sx;
char link[64] = "";
if (syscall(RAW_FSTATAT, AT_FDCWD, argv[1], &st, 0) != 0) return 1;
if (syscall(RAW_FSTATAT, AT_FDCWD, argv[2], &st, 0) != -1 || errno != ENOENT) return 2;
long n = syscall(SYS_readlinkat, AT_FDCWD, argv[3], link, sizeof(link) - 1);
if (n <= 0) return 3;
sx.stx_size = 0;
long found = syscall(SYS_statx, AT_FDCWD, argv[1], 0, STATX_SIZE, &sx);
int have_statx = !(found == -1 && errno == ENOSYS);
if (have_statx && found != 0) return 4;
long missing = syscall(SYS_statx, AT_FDCWD, argv[2], 0, STATX_SIZE, &sx);
if (have_statx && (missing != -1 || errno != ENOENT)) return 5;
printf("%lld %.*s %llu\n", (long long)st.st_size, (int)n, link, (unsigned long long)sx.stx_size);
return 0;
}
"""
O_PATH = getattr(os, "O_PATH", 0o10000000)
# (dirfd: r = the tree, o = "/"), flags, path, expected: a path in the tree, an errno name, or "proc" for a file outside it.
@@ -268,6 +350,14 @@ class Openat2PreloadTest(unittest.TestCase):
cls.raw = subprocess.run([str(cls.tmp / "raw_open"), str(tree / "etc/hostname"), str(tree / "missing")],
capture_output=True, text=True, timeout=60,
env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")))
lookup = cls.tmp / "raw_lookup.c"
lookup.write_text(RAW_LOOKUP)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "raw_lookup"), str(lookup)], check=True)
cls.lookup_args = [str(tree / "etc/hostname"), str(tree / "missing"), str(tree / "etc/alternatives/hn")]
cls.lookup_plain = subprocess.run([str(cls.tmp / "raw_lookup"), *cls.lookup_args], capture_output=True, text=True,
timeout=60, env=dict(os.environ, LD_PRELOAD=str(cls.lib)))
cls.lookup = subprocess.run([str(cls.tmp / "raw_lookup"), *cls.lookup_args], capture_output=True, text=True, timeout=60,
env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")))
(cls.tmp / "real").mkdir()
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o",
str(cls.tmp / "real/libblfastpath.so"), str(FASTPATH), "-ldl"], check=True)
@@ -279,6 +369,20 @@ class Openat2PreloadTest(unittest.TestCase):
LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so")))
except subprocess.TimeoutExpired:
cls.fex = None
wrapper = cls.tmp / "wrapper.c"
wrapper.write_text(WRAPPER)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "wrapper"), str(wrapper), "-ldl"], check=True)
(cls.tmp / "extract").mkdir()
cls.wrapper = subprocess.run([str(cls.tmp / "wrapper"), str(cls.tmp / "extract"), "file"], capture_output=True,
text=True, timeout=20, env=dict(os.environ, LD_PRELOAD=str(cls.lib)))
(cls.tmp / "fex-lookup").mkdir()
shutil.copy(cls.tmp / "raw_lookup", cls.tmp / "fex-lookup/FEX")
try:
cls.fex_lookup = subprocess.run([str(cls.tmp / "fex-lookup/FEX"), *cls.lookup_args], capture_output=True, text=True,
timeout=20, env=dict(os.environ, PROOT_FP_ROOT="/", PROOT_FP_KEY="test",
LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so")))
except subprocess.TimeoutExpired:
cls.fex_lookup = None
@classmethod
def tearDownClass(cls):
@@ -295,18 +399,33 @@ class Openat2PreloadTest(unittest.TestCase):
def test_the_walk_asks_the_fast_path_when_it_is_loaded(self):
self.assertEqual(self.counted, self.preload)
self.assertTrue(all(n > 0 for n in self.calls), self.calls)
self.assertTrue(all(n > 0 for n in self.calls[:3]), self.calls)
def test_a_raw_openat_syscall_asks_the_fast_path_too(self):
self.assertEqual(self.raw.returncode, 0, self.raw.stderr)
self.assertEqual(self.raw.stdout, "inside\n")
self.assertEqual(self.raw.stderr.split("calls ")[-1].split(), ["2", "0", "0"])
self.assertEqual(self.raw.stderr.split("calls ")[-1].split(), ["2", "0", "0", "0"])
def test_raw_stat_readlink_and_statx_syscalls_ask_the_fast_path(self):
self.assertEqual(self.lookup_plain.returncode, 0, self.lookup_plain.stderr)
self.assertEqual(self.lookup.returncode, 0, self.lookup.stderr)
self.assertEqual(self.lookup.stdout, self.lookup_plain.stdout)
self.assertEqual(self.lookup.stderr.split("calls ")[-1].split(), ["0", "2", "1", "2"])
def test_raw_lookups_in_fex_answer_through_the_real_fast_path(self):
self.assertIsNotNone(self.fex_lookup, "hung")
self.assertEqual(self.fex_lookup.returncode, 0, self.fex_lookup.stderr)
self.assertEqual(self.fex_lookup.stdout, self.lookup_plain.stdout)
def test_a_first_raw_openat_in_fex_does_not_wait_on_the_fast_path_starting(self):
self.assertIsNotNone(self.fex, "hung")
self.assertEqual(self.fex.returncode, 0, self.fex.stderr)
self.assertEqual(self.fex.stdout, "inside\n")
def test_the_libc_openat2_wrapper_creates_files_without_openat2(self):
self.assertEqual(self.wrapper.returncode, 0, self.wrapper.stdout + self.wrapper.stderr)
self.assertTrue((self.tmp / "extract/file").exists())
def test_the_kernel_agrees(self):
if self.kernel is None:
self.skipTest("this kernel or sandbox has no openat2")
+71
View File
@@ -0,0 +1,71 @@
import io
import os
import runpy
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path
PACMAN = Path(__file__).resolve().parents[1] / "desktop-kde/overlay/usr/share/droiddeck/pacman"
class PacmanSharedFilesTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.top = Path(temp.name)
def keep(self, action):
lib = self.top / "lib"
lib.mkdir(exist_ok=True)
script = (PACMAN / "keep").read_text().replace("/var/lib/pacman", str(lib))
subprocess.run(["bash", "-c", script, "keep", action], check=True, timeout=30)
return lib
def test_an_upgrade_that_drops_a_shared_file_gets_it_back(self):
shared = self.top / "usr/lib/libshared.so"
shared.parent.mkdir(parents=True)
shared.write_text("shared")
lib = self.top / "lib"
lib.mkdir()
(lib / "droiddeck-shared-files").write_text("%s\n%s\n" % (shared, self.top / "usr/lib/never-there"))
self.keep("save")
shared.unlink()
self.keep("restore")
self.assertEqual("shared", shared.read_text())
self.assertFalse((self.top / "usr/lib/never-there").exists())
self.assertFalse((lib / "droiddeck-shared-keep").exists())
def test_a_backup_for_a_file_still_missing_survives_the_next_save(self):
shared = self.top / "usr/lib/libshared.so"
shared.parent.mkdir(parents=True)
shared.write_text("shared")
lib = self.top / "lib"
lib.mkdir()
(lib / "droiddeck-shared-files").write_text("%s\n" % shared)
self.keep("save")
shared.unlink()
self.keep("save")
self.keep("restore")
self.assertEqual("shared", shared.read_text())
def test_only_identical_files_are_taken_over(self):
adopt = runpy.run_path(str(PACMAN / "adopt"), run_name="adopt")
package = io.BytesIO()
with tarfile.open(fileobj=package, mode="w") as archive:
for name, data in (("same", b"one"), ("different", b"two")):
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
(self.top / "same").write_bytes(b"one")
(self.top / "different").write_bytes(b"other")
package.seek(0)
with tarfile.open(fileobj=package) as archive:
members = {m.name: m for m in archive}
self.assertTrue(adopt["same"](archive, members["same"], str(self.top / "same")))
self.assertFalse(adopt["same"](archive, members["different"], str(self.top / "different")))
if __name__ == "__main__":
unittest.main()
+223
View File
@@ -0,0 +1,223 @@
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from test_output_refresh import SOURCE, extract_function
PREAMBLE = r'''
#include <assert.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
struct wl_event_source { int armed; };
static struct wl_event_source idle_source, timer_source;
static void (*idle_func)(void *);
static int idles_added, timers_armed, renders, window_requests, effects_changes, pose_changes;
static int64_t clock_ns;
static int g_display_storage;
static void *g_display = &g_display_storage;
static struct wl_event_source *g_render_idle, *g_fallback_timer;
static int g_fallback_armed, g_dirty, g_hud_fresh, framegen;
static void *g_hud_surface;
static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns;
static int g_tick_held;
static int64_t g_hold_missed_ns;
#define HOLD_RETRY_NS 1000000000LL
static int64_t g_refresh_ns = 16666667;
volatile int g_render_on_commit = 1;
volatile int g_release_unpaced = 1;
static atomic_int g_stream_on;
static struct { unsigned ticks, ticks_late_2ms, commit_renders; int64_t tick_late_ns, tick_late_max_ns; } g_pace;
static struct { unsigned ticks; } g_perf;
static int64_t now_ns(void) { return clock_ns; }
static void *wl_display_get_event_loop(void *display) { return display; }
static struct wl_event_source *wl_event_loop_add_idle(void *loop, void (*func)(void *), void *data) {
idles_added++; idle_func = func; return &idle_source;
}
static struct wl_event_source *wl_event_loop_add_timer(void *loop, int (*func)(void *), void *data) { return &timer_source; }
static int wl_event_source_timer_update(struct wl_event_source *source, int ms) { timers_armed++; return 0; }
static int vkp_framegen_active(void) { return framegen; }
static int vkp_apply_window_request(void) { return window_requests; }
static int vkp_effects_sync(void) { return effects_changes; }
static int vkp_cardboard_pose_changed(void) { return pose_changes; }
static void render_scene(void) { renders++; g_dirty = 0; g_dirty_since_ns = 0; g_rendered_tick_ns = g_tick_vsync_ns; g_tick_held = 0; }
static int on_fallback_timer(void *data) { return 0; }
static void on_commit_idle(void *data);
'''
CHECKS = r'''
static void run_idle(void) {
void (*func)(void *) = idle_func;
idle_func = NULL;
if (func) func(NULL);
}
static void tick(int64_t t) { clock_ns = t; on_vsync(t); }
static void arrive(int64_t after_ns) { clock_ns += after_ns; schedule_render(); }
int main(void) {
const int64_t refresh = 6944444, ms = 1000000;
int64_t t = 1000000000LL;
int r0;
unsigned c0;
g_refresh_ns = refresh;
tick(t);
assert(renders == 0);
/* a new frame is drawn when it arrives */
arrive(2 * ms);
assert(idles_added == 1 && renders == 0);
run_idle();
assert(renders == 1 && g_pace.commit_renders == 1 && g_render_idle == NULL);
/* a second frame in the same refresh is left for the next arrival, which is drawn when it arrives */
arrive(1 * ms);
assert(idles_added == 1);
tick(t += refresh);
assert(renders == 1 && g_tick_held == 1);
arrive(2 * ms);
assert(idles_added == 2);
run_idle();
assert(renders == 2 && g_pace.commit_renders == 2 && g_tick_held == 0);
/* a frame no other frame follows is drawn at the tick after next */
arrive(1 * ms);
tick(t += refresh);
assert(renders == 2);
tick(t += refresh);
assert(renders == 3 && g_pace.commit_renders == 2);
/* after that, the tick draws every frame for a second, then holds one again */
arrive(1 * ms);
tick(t += refresh);
assert(renders == 4 && g_tick_held == 0);
t += HOLD_RETRY_NS;
tick(t);
arrive(1 * ms);
run_idle();
arrive(1 * ms);
tick(t += refresh);
assert(renders == 5 && g_tick_held == 1);
arrive(2 * ms);
run_idle();
assert(renders == 6 && g_pace.commit_renders == 4);
/* one frame per refresh, starting right after a tick draw, settles on drawing every frame when it arrives */
window_requests = 1;
tick(t += refresh);
window_requests = 0;
arrive(2 * ms);
r0 = renders; c0 = g_pace.commit_renders;
for (int i = 0; i < 10; i++) {
tick(t += refresh);
arrive(2 * ms);
run_idle();
}
assert(renders - r0 == 10 && g_pace.commit_renders - c0 == 10);
/* a client that draws again only after its frame callback (sent when the scene is drawn) keeps one frame
per refresh: two held frames in 200 refreshes, about 1.4 s */
r0 = renders; c0 = g_pace.commit_renders;
{
int seen = renders - 1;
for (int i = 0; i < 200; i++) {
if (renders != seen) { seen = renders; arrive(1 * ms); run_idle(); }
tick(t += refresh);
}
}
assert(renders - r0 == 198 && g_pace.commit_renders == c0);
/* a window, effect or headset change at the tick draws the waiting frame now */
t += HOLD_RETRY_NS;
tick(t);
arrive(1 * ms);
run_idle();
r0 = renders;
arrive(1 * ms);
window_requests = 1;
tick(t += refresh);
window_requests = 0;
assert(renders - r0 == 1 && g_tick_held == 0);
/* a draw queued before the tick still draws the frame once */
tick(t += refresh);
r0 = renders; c0 = g_pace.commit_renders;
arrive(1 * ms);
tick(t += refresh);
assert(renders == r0);
run_idle();
assert(renders - r0 == 1 && g_pace.commit_renders - c0 == 1);
tick(t += refresh);
assert(renders - r0 == 1);
/* streaming switched on after the draw was queued leaves the frame for the tick */
tick(t += refresh);
r0 = renders; c0 = g_pace.commit_renders;
arrive(1 * ms);
atomic_store(&g_stream_on, 1);
run_idle();
assert(renders == r0);
tick(t += refresh);
atomic_store(&g_stream_on, 0);
assert(renders - r0 == 1 && g_pace.commit_renders == c0);
/* paced output, frame generation, the switch off and streaming keep drawing on the tick */
const int idles = idles_added;
r0 = renders;
for (int c = 0; c < 4; c++) {
tick(t += refresh);
if (c == 0) g_release_unpaced = 0;
if (c == 1) framegen = 1;
if (c == 2) g_render_on_commit = 0;
if (c == 3) atomic_store(&g_stream_on, 1);
arrive(1 * ms);
assert(idles_added == idles);
tick(t += refresh);
g_release_unpaced = 1; framegen = 0; g_render_on_commit = 1; atomic_store(&g_stream_on, 0);
assert(renders - r0 == c + 1);
}
/* without screen ticks the fallback timer still draws */
clock_ns += 200000000LL;
schedule_render();
assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1);
puts("PASS");
return 0;
}
'''
@unittest.skipUnless(sys.platform.startswith('linux'), 'needs a Linux host compiler')
class RenderOnCommitTest(unittest.TestCase):
def test_a_new_frame_is_drawn_on_arrival_at_most_once_per_refresh(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
self.skipTest('A host C compiler is required')
source = SOURCE.read_text()
render = extract_function(source, 'render_scene')
self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render)
self.assertIn('g_tick_held = 0;', render)
functions = ('commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync')
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder:
path = Path(folder)
(path / 'commit.c').write_text(harness)
binary = path / 'commit-test'
build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror',
'-Wno-unused-parameter', '-Wno-unused-function', '-O2',
str(path / 'commit.c'), '-o', str(binary)], capture_output=True, text=True)
self.assertEqual(0, build.returncode, build.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('PASS', result.stdout.strip())
if __name__ == '__main__':
unittest.main()
+1
View File
@@ -48,6 +48,7 @@ class RuntimeInputsTest(unittest.TestCase):
for name, (pack, rel) in runtime.PACKED_FILES.items():
proot[rel] = (self.root / runtime.outputs(self.root)[name]).read_bytes()
self.pack('proot', proot)
self.pack('butler', {'butler': b'butler', '7z.so': b'7z', 'libc7zip.so': b'c7zip', 'version': b'15.32.0'})
for prefix, name in runtime.PACKED.items():
base = self.root / 'app/src/main' / prefix
self.pack(name, {path.relative_to(base).as_posix(): path.read_bytes() for path in base.rglob('*') if path.is_file()})
+7
View File
@@ -43,3 +43,10 @@ class SessionAssetsTest(unittest.TestCase):
assets.check_extraction(self.overlay, ''))
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1"'
self.assertEqual([], assets.check_extraction(self.overlay, mapping))
def test_helper_extracted_under_another_name_counts(self):
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/login1"'
self.assertEqual([], assets.check_extraction(self.overlay, mapping))
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"'
self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'],
assets.check_extraction(self.overlay, mapping))
+2 -2
View File
@@ -9,8 +9,8 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d
def log_redirect():
match = re.search(r"^\s*(exec > >\(.*\) 2>&1)$", SESSION.read_text(), re.M)
return match.group(1)
match = re.search(r"^\s*(dd=.*)\n\s*(exec > >\(.*\) 2>&1)$", SESSION.read_text(), re.M)
return "%s\n%s" % match.groups()
class SessionLogTest(unittest.TestCase):
+10 -1
View File
@@ -18,16 +18,19 @@ class SessionPacingTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH=str(refresh),
BL_MANGOAPP='0', BL_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0')
env.pop('GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST', None)
env.update(overrides)
script = '''
set -u
mode=steam
pipewire_stub() { return 1; }
run_gamescope() { printf 'ARG:%s\\n' "$@"; }
run_gamescope() { printf 'ARG:%s\\n' "$@"; printf 'FOLLOW:%s\\n' "${GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST:-}"; }
''' + block
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True,
text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
self.follow = [line.removeprefix('FOLLOW:') for line in result.stdout.splitlines()
if line.startswith('FOLLOW:')]
return [line.removeprefix('ARG:') for line in result.stdout.splitlines()
if line.startswith('ARG:')]
@@ -38,6 +41,12 @@ run_gamescope() { printf 'ARG:%s\\n' "$@"; }
self.assertEqual(str(refresh), args[args.index('-r') + 1])
self.assertIn('-e', args)
def test_gamescope_follows_the_panel_after_the_starting_rate(self):
self.launch(144)
self.assertEqual(['1'], self.follow)
self.launch(0)
self.assertEqual([''], self.follow)
def test_retired_cap_variables_do_not_override_the_display_rate(self):
for performance in ('0', '1'):
with self.subTest(performance=performance):
+29
View File
@@ -0,0 +1,29 @@
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
PACKAGE = 'com.droiddeck.launcher'
class SignApkRenamesTest(unittest.TestCase):
def test_variants_rename_every_authority_and_task_named_after_the_package(self):
# sign-apk.sh renames a fixed list of names for the pubg/antutu/ludashi variants and fails the
# main build on any authority or task affinity it leaves on the base package; PR builds do not sign.
manifest = (ROOT / 'app/src/main/AndroidManifest.xml').read_text()
names = set()
for attribute in ('authorities', 'taskAffinity'):
for value in re.findall(r'android:%s="([^"]*)"' % attribute, manifest):
self.assertNotIn(';', value, 'sign-apk.sh renames whole values, so give each authority its own provider')
name = value.strip().replace('${applicationId}', PACKAGE)
if name.startswith(PACKAGE + '.'):
names.add(name[len(PACKAGE):])
self.assertIn('.agent', names)
script = (ROOT / 'tools/release/sign-apk.sh').read_text()
renamed = set(re.findall(r'"\$P(\.[A-Za-z0-9_.-]+)=\$pkg\1"', script))
self.assertEqual(set(), names - renamed, 'add these to the axml_rename call in tools/release/sign-apk.sh')
if __name__ == '__main__':
unittest.main()
+17
View File
@@ -57,6 +57,23 @@ class DesktopSteamLaunchTest(unittest.TestCase):
self.assertEqual(result.stdout.splitlines()[-1], 'steam://rungameid/501590')
self.assertFalse((self.session / 'steam-launch').exists())
def test_exit_without_a_running_client_starts_nothing(self):
result = self.launch('desktop', 'steam://exit')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, '')
self.assertFalse((self.session / 'steam-launch').exists())
def test_shim_turns_shutdown_into_exit_url(self):
launch = self.root / 'record-launch'
launch.write_text('#!/bin/bash\nprintf "%s\\n" "$@"\n')
launch.chmod(0o755)
shim = self.root / 'shim'
shim.write_text((BIN / 'droiddeck-steam-shim').read_text().replace(
'/usr/local/bin/droiddeck-steam-launch', str(launch)))
result = subprocess.run(['bash', str(shim), '-shutdown'], env=self.env, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ['desktop', 'steam://exit'])
def test_second_click_forwards_without_another_supervisor(self):
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
lock.parent.mkdir(parents=True)
+78
View File
@@ -0,0 +1,78 @@
import re
import shlex
import socket
import subprocess
import tempfile
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
def devtools_function():
match = re.search(r"^steam_devtools\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S)
return match.group(0) if match else None
class SteamDevtoolsPortTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
def free_port(self):
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def choose(self, port):
function = devtools_function()
self.assertIsNotNone(function, "droiddeck-session has no steam_devtools()")
script = function + "steam_root=%s\nsteam_devtools %d\n" % (shlex.quote(str(self.root)), port)
script += 'echo "port=$BL_CDP_PORT"\necho "args=${_bl_cdp[*]}"\n'
out = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30, check=True).stdout
lines = out.splitlines()
port_line = next(l for l in lines if l.startswith("port="))
args_line = next(l for l in lines if l.startswith("args="))
return int(port_line[5:]), args_line[5:].split(), out
def test_without_remote_debugging_steam_gets_a_private_port(self):
port, args, _ = self.choose(self.free_port())
self.assertEqual(["-cef-enable-debugging", "-devtools-port", str(port)], args)
self.assertTrue(20000 <= port < 50000)
def test_remote_debugging_keeps_the_fixed_port_when_it_is_free(self):
(self.root / ".cef-enable-remote-debugging").touch()
fixed = self.free_port()
port, args, out = self.choose(fixed)
self.assertEqual(fixed, port)
self.assertEqual([], args)
self.assertNotIn("held by another app", out)
def test_a_fixed_port_another_app_holds_falls_back_to_a_private_one(self):
(self.root / ".cef-enable-remote-debugging").touch()
with socket.socket() as other:
other.bind(("127.0.0.1", 0))
other.listen(1)
taken = other.getsockname()[1]
port, args, out = self.choose(taken)
self.assertNotEqual(taken, port)
self.assertEqual(["-cef-enable-debugging", "-devtools-port", str(port)], args)
self.assertIn("held by another app", out)
def test_a_fixed_port_bound_without_listening_also_falls_back(self):
(self.root / ".cef-enable-remote-debugging").touch()
with socket.socket() as other:
other.bind(("127.0.0.1", 0))
taken = other.getsockname()[1]
port, args, out = self.choose(taken)
self.assertNotEqual(taken, port)
self.assertEqual(["-cef-enable-debugging", "-devtools-port", str(port)], args)
def test_the_x86_64_decky_exemption_only_covers_the_fixed_port(self):
text = SESSION.read_text()
self.assertIn('[ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]', text)
if __name__ == "__main__":
unittest.main()
+46 -1
View File
@@ -113,9 +113,11 @@ class ImportsTest(unittest.TestCase):
listing = self.root / 'games.json'
listing.write_text(json.dumps([self.game]))
from unittest.mock import Mock
idle = imports.downloads_idle
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \
patch.object(imports, 'request_restart'), \
patch.object(imports, 'ask_restart', return_value=True), \
patch.object(imports, 'time', Mock(monotonic=Mock(side_effect=[0, 301]),
sleep=Mock(side_effect=[None, RuntimeError('stop')]))), \
patch.object(imports.subprocess, 'run', return_value=result), \
@@ -126,7 +128,7 @@ class ImportsTest(unittest.TestCase):
snapshot = imports.read_json(self.acct / 'config' / imports.STATE, {})
self.assertTrue(snapshot['owned']['42'])
def run_watch(self, beats, routes=None, busy=False):
def run_watch(self, beats, routes=None, busy=False, answer=True, started=False):
listing = self.root / 'games.json'
listing.write_text(json.dumps([self.game]))
if routes is not None:
@@ -134,21 +136,64 @@ class ImportsTest(unittest.TestCase):
if busy:
(self.steam / 'steamapps/downloading/7').mkdir(parents=True)
from unittest.mock import Mock
idle = imports.downloads_idle
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
with patch.object(imports, 'identify', return_value=42), \
patch.object(imports, 'game_running', return_value=False), \
patch.object(imports, 'request_restart') as restart, \
patch.object(imports, 'ask_restart', return_value=answer) as asked, \
patch.object(imports, 'downloads_idle', side_effect=lambda root: idle(root) and not (started and asked.called)), \
patch.object(imports, 'time', Mock(monotonic=Mock(side_effect=list(range(0, 30 * beats, 30))),
sleep=Mock(side_effect=[None] * (beats - 1) + [RuntimeError('stop')]))), \
patch.object(imports.subprocess, 'run', return_value=result), \
patch('builtins.print'):
with self.assertRaisesRegex(RuntimeError, 'stop'):
imports.watch(self.steam, listing)
self.asked = asked
return restart
def test_newly_owned_game_restarts_the_client_once(self):
self.assertEqual(1, self.run_watch(3).call_count)
def test_an_import_that_did_not_take_restarts_only_once_across_sessions(self):
self.assertEqual(1, self.run_watch(3).call_count)
self.assertEqual(0, self.run_watch(3).call_count)
self.assertEqual([42], imports.read_json(self.acct / 'config' / imports.TRIED, None))
def test_later_skips_the_restart_and_does_not_ask_again(self):
self.assertEqual(0, self.run_watch(3, answer=False).call_count)
self.assertEqual([['Example']], [c.args[0] for c in self.asked.call_args_list])
self.assertEqual(0, self.run_watch(3).call_count)
self.assertEqual(0, self.asked.call_count)
def test_a_download_started_while_asking_leaves_the_import_for_the_next_start(self):
self.assertEqual(0, self.run_watch(3, started=True).call_count)
self.assertEqual(1, self.asked.call_count)
def test_the_app_answers_the_restart_question(self):
home = self.root / 'home'
folder = home / '.cache/droiddeck'
replies = []
def sleep(_):
ask = json.loads((folder / 'steam-import.json').read_text())
replies.append(ask['games'])
(folder / 'steam-import.answer').write_text(json.dumps(dict(token=ask['token'], choice=choice)))
for choice, expected in (('now', True), ('later', False)):
with patch.dict(os.environ, HOME=str(home)):
self.assertEqual(expected, imports.ask_restart(['Example'], clock=iter(range(100)).__next__, sleep=sleep))
self.assertFalse((folder / 'steam-import.json').exists())
self.assertFalse((folder / 'steam-import.answer').exists())
self.assertEqual([['Example'], ['Example']], replies)
def test_no_answer_means_later(self):
with patch.dict(os.environ, HOME=str(self.root / 'home')):
self.assertFalse(imports.ask_restart(['Example'], timeout=5, clock=iter(range(100)).__next__, sleep=lambda _: None))
def test_a_tried_import_that_took_is_forgotten(self):
imports.save_json(self.acct / 'config' / imports.TRIED, [42])
self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count)
self.assertEqual([], imports.read_json(self.acct / 'config' / imports.TRIED, None))
def test_imported_game_does_not_restart_the_client(self):
self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count)
+26
View File
@@ -1,5 +1,7 @@
import re
import shlex
import subprocess
import tempfile
import unittest
from pathlib import Path
@@ -20,6 +22,30 @@ class SteamRestartCapTest(unittest.TestCase):
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,
check=True).stdout.split()
def installs(self, *steps):
function = stuck_function()
self.assertIsNotNone(function, "droiddeck-session has no steam_update_stuck()")
with tempfile.TemporaryDirectory() as root:
script = function + "steam_root=%s\nmkdir -p \"$steam_root/package\"\n" % shlex.quote(root)
script += "installed=\"$steam_root/package/steam_client_linuxarm64.installed\"\n"
script += "echo 0 > \"$installed\"\nsteam_updates=0\nsteam_installs=0\n"
script += "steam_update_stamp=$(stat -c '%n %Y %s' \"$steam_root\"/package/*.installed)\n"
for n, installed in enumerate(steps, 1):
if installed:
script += "printf '%%0%dd' 0 > \"$installed\"\n" % (n + 1)
script += "if steam_update_stuck 10; then echo stop; else echo restart; fi\n"
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,
check=True).stdout.split()
def test_restarts_that_each_install_an_update_go_on(self):
self.assertEqual(["restart"] * 4, self.installs(True, False, True, False))
def test_an_update_that_never_installs_is_stopped_on_the_third(self):
self.assertEqual(["restart", "restart", "stop"], self.installs(False, False, False))
def test_installs_that_never_settle_are_stopped(self):
self.assertIn("stop", self.installs(*[True] * 12))
def test_an_update_that_keeps_asking_at_once_is_stopped_on_the_third(self):
self.assertEqual(["restart", "restart", "stop"], self.restarts(11, 13, 9))
+79
View File
@@ -0,0 +1,79 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64'
class SteamX64CpuTest(unittest.TestCase):
def selection(self, features, *, forced=False, same_build=True, unreadable=False):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
arm = root / 'arm'
x64 = root / 'x64'
for base in (arm, x64):
(base / 'package').mkdir(parents=True)
(arm / 'steamrtarm64').mkdir()
(arm / 'steamrtarm64/steamwebhelper').touch(mode=0o700)
shim = root / 'arm-shim'
shim.touch(mode=0o700)
(x64 / 'package/beta').write_text('publicbeta\n')
for base, arch, version in ((x64, 'steamrt64', '123'), (arm, 'linuxarm64', '123' if same_build else '122')):
(base / f'package/steam_client_publicbeta_{arch}.manifest').write_text(f'"version" "{version}"\n')
cpuinfo = root / 'cpuinfo'
if not unreadable:
cpuinfo.write_text(features)
text = SCRIPT.read_text()
start = text.find('x64_arm_webhelper_cpu_supported() {')
helper = text[start:text.index('x64_exec() {')] if start >= 0 else ''
selection = text.split('x64_exec() {', 1)[1].split(' mkdir -p "$STEAM_X64/logs"', 1)[0]
shell = helper + '\nx64_env() { :; }\nx64_webhelper_gpu() { return 1; }\nselect_helper() {' + selection + '\nprintf "%s|%s\\n" "${BL_X64_ARM_WEBHELPER:-x86}" "${BL_WEBHELPER_ARGS:-}";\n}\nselect_helper\n'
shell = shell.replace('/proc/cpuinfo', str(cpuinfo)).replace('/usr/local/bin/droiddeck-x64-arm-webhelper', str(shim))
env = dict(os.environ, STEAM_X64=str(x64), ARM_STEAM=str(arm), X64_CHANNEL='publicbeta', BL_X64_X86_WEBHELPER='1' if forced else '0')
env.pop('BL_X64_ARM_WEBHELPER', None)
env.pop('BL_WEBHELPER_ARGS', None)
result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout.strip(), str(shim)
def test_missing_atomics_keeps_x86_helper(self):
result, _ = self.selection('Features : fp asimd aes crc32\n')
self.assertEqual(result, 'x86|stock')
def test_atomics_keeps_same_build_arm_helper(self):
result, arm = self.selection('Features : fp asimd atomics aes\n')
self.assertEqual(result, arm + '|')
def test_exact_token_required(self):
result, _ = self.selection('Features : fp noatomics atomics_extra\n')
self.assertEqual(result, 'x86|stock')
def test_any_explicit_core_without_atomics_keeps_x86_helper(self):
result, _ = self.selection('processor : 0\nFeatures : fp atomics\nprocessor : 1\nFeatures : fp aes\n')
self.assertEqual(result, 'x86|stock')
def test_empty_features_is_explicitly_unsupported(self):
result, _ = self.selection('Features : \n')
self.assertEqual(result, 'x86|stock')
def test_absent_features_preserves_existing_behavior(self):
result, arm = self.selection('processor : 0\n')
self.assertEqual(result, arm + '|')
def test_unreadable_cpuinfo_preserves_existing_behavior(self):
result, arm = self.selection('', unreadable=True)
self.assertEqual(result, arm + '|')
def test_forced_x86_still_wins(self):
result, _ = self.selection('Features : atomics\n', forced=True)
self.assertEqual(result, 'x86|stock')
def test_supported_cpu_still_requires_same_build(self):
result, _ = self.selection('Features : atomics\n', same_build=False)
self.assertEqual(result, 'x86|stock')
if __name__ == '__main__':
unittest.main()
+5 -1
View File
@@ -39,12 +39,16 @@ class X64SignInTest(unittest.TestCase):
self.write(self.x64 / 'config/loginusers.vdf', '"users"\n{\n}\n')
self.write(self.x64 / 'config/config.vdf', CONFIG % '')
self.write(self.home / '.droiddeck-x64/.steam/registry.vdf', REGISTRY % '')
self.bin = self.home / 'bin'
self.bin.mkdir()
(self.bin / 'pgrep').write_text('#!/bin/sh\nexit 1\n')
(self.bin / 'pgrep').chmod(0o755)
def write(self, path, text):
path.write_text(text)
def sync(self):
env = dict(os.environ, HOME=str(self.home))
env = dict(os.environ, HOME=str(self.home), PATH='%s:%s' % (self.bin, os.environ['PATH']))
env.pop('XDG_DATA_HOME', None)
env.pop('BL_X64_HOME', None)
return subprocess.run(['bash', str(SCRIPT), '--sync-login'], env=env, capture_output=True, text=True, check=True)
+105
View File
@@ -0,0 +1,105 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
FAKE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/statfs.h>
#include <sys/syscall.h>
#include <unistd.h>
uid_t getuid(void) {
return (uid_t)syscall(SYS_getuid) + 1;
}
int fstatfs(int fd, struct statfs *out) {
char link[32], path[4096];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
long n = syscall(SYS_readlinkat, AT_FDCWD, link, path, sizeof(path) - 1);
path[n > 0 ? n : 0] = '\0';
int result = (int)syscall(SYS_fstatfs, fd, out);
if (result == 0 && strstr(path, "/fuse/")) out->f_type = 0x65735546;
if (result == 0 && strstr(path, "/sdcardfs/")) out->f_type = 0x5dca2df5;
if (result == 0 && strstr(path, "/ext4/")) out->f_type = 0xef53;
return result;
}
"""
PROGRAM = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
uid_t real = (uid_t)syscall(SYS_getuid);
for (int i = 1; i < argc; i++) {
int fd = open(argv[i], O_RDONLY);
struct stat st;
errno = 1234;
int result = fstat(fd, &st);
printf("%s %d\n", st.st_uid == real ? "real" : st.st_uid == real + 1 ? "user" : "other", result == 0 && errno == 1234);
close(fd);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class StorageOwnerPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp = tempfile.TemporaryDirectory()
cls.dir = Path(cls.temp.name)
build = cls.dir / "build"
build.mkdir()
(build / "fake.c").write_text(FAKE)
(build / "program.c").write_text(PROGRAM)
cls.preload = build / "libblsession.so"
cls.fake = build / "fake.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c")], check=True)
cls.wineserver = build / "wineserver"
subprocess.run(["cc", "-O2", "-o", str(cls.wineserver), str(build / "program.c")], check=True)
cls.other = build / "wine64-preloader"
shutil.copy(cls.wineserver, cls.other)
for kind in ("fuse", "sdcardfs", "ext4"):
(cls.dir / kind).mkdir()
(cls.dir / kind / "file").write_text("x")
@classmethod
def tearDownClass(cls):
cls.temp.cleanup()
def owners(self, program, *kinds):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.fake, self.preload))
env.pop("BL_STORAGE_DIAGNOSTICS", None)
paths = [str(self.dir / kind / "file") for kind in kinds]
result = subprocess.run([str(program)] + paths, env=env, capture_output=True, text=True, check=True)
return result.stdout.split()
def test_wineserver_owns_what_is_on_android_storage(self):
self.assertEqual(["user", "1", "user", "1"], self.owners(self.wineserver, "fuse", "sdcardfs"))
def test_other_filesystems_keep_their_owner(self):
self.assertEqual(["real", "1"], self.owners(self.wineserver, "ext4"))
def test_other_programs_see_the_real_owner(self):
self.assertEqual(["real", "1", "real", "1"], self.owners(self.other, "fuse", "sdcardfs"))
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -81,7 +81,7 @@ class StoragePreloadTest(unittest.TestCase):
(build / "program.c").write_text(PROGRAM)
cls.storage = build / "storage.so"
cls.fake = build / "fake.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.storage), str(PRELOAD / "storage.c"), "-ldl"], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.storage), str(PRELOAD / "storage.c"), str(PRELOAD / "owner.c"), "-ldl"], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c")], check=True)
cls.steam = cls.dir / "steamrtarm64/steam"
cls.steam.parent.mkdir()
+24
View File
@@ -391,6 +391,30 @@ def set_registry(**arguments):
class GogRegistry(unittest.TestCase):
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='7')
(folder / 'goggame-7.id').write_text(json.dumps({'buildId': 'opaque-0001'}))
proton = Path(root) / 'proton'; proton.write_text('selected Proton')
data = Path(root) / 'compat'
executable = data / 'pfx/drive_c/windows/system32/reg.exe'
executable.parent.mkdir(parents=True); executable.write_bytes(b'MZreg')
(data / 'pfx/system.reg').write_text('registry')
imported = []
def run(argv, **kwargs):
self.assertEqual([str(proton), 'run', str(executable), 'import'], argv[:4])
text = Path(argv[4][2:].replace('\\', '/')).read_bytes()[2:].decode('utf-16-le')
imported.append(text)
return __import__('subprocess').CompletedProcess(argv, 0)
record = {'id': '7', 'build': 'opaque-0001', 'version': 'RC-final'}
with patch.object(store.subprocess, 'run', side_effect=run):
self.assertTrue(store.apply_gog_registry(folder, str(data), str(proton), installation=record).startswith('written='))
self.assertIn('[HKEY_LOCAL_MACHINE\\Software\\GOG.com\\Games\\7]', imported[0])
self.assertIn('"BUILDID"="opaque-0001"', imported[0])
self.assertIn('"VER"="RC-final"', imported[0])
with self.assertRaises(ValueError):
store.apply_gog_registry(folder, str(data), str(proton), installation=dict(record, build='invented'))
def test_the_scripts_registry_values_are_read_with_the_games_paths(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1454587428')
+53
View File
@@ -0,0 +1,53 @@
import getpass
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SU = Path(__file__).resolve().parents[1] / "ubuntu/overlay-runtime/usr/local/bin/su"
class SuWrapperTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.dir = Path(temp.name)
sudo = self.dir / "sudo"
sudo.write_text("#!/bin/bash\nprintf 'sudo'; printf ' <%s>' \"$@\"; echo\n")
sudo.chmod(0o755)
self.su = self.dir / "su"
self.su.write_text(SU.read_text().replace("/usr/local/bin/sudo", str(sudo)))
self.su.chmod(0o755)
def run_su(self, *args):
env = dict(os.environ, SHELL="/bin/bash")
return subprocess.run([str(self.su), *args], capture_output=True, text=True, timeout=30, env=env)
def test_a_command_after_the_user_reaches_the_root_shell(self):
out = self.run_su("root", "-c", "echo hi")
self.assertEqual("sudo <-s> <echo hi>\n", out.stdout)
def test_the_current_user_is_not_elevated(self):
out = self.run_su(getpass.getuser(), "-c", "echo as-me")
if getpass.getuser() == "root":
self.assertEqual("sudo <-s> <echo as-me>\n", out.stdout)
else:
self.assertEqual("as-me\n", out.stdout)
def test_arguments_after_the_user_go_to_the_shell(self):
out = self.run_su("-", "root", "-c", "echo $0 $1", "zero", "one")
self.assertEqual("sudo <-i> </bin/bash> <-c> <echo $0 $1> <zero> <one>\n", out.stdout)
def test_other_users_are_refused(self):
out = self.run_su("droiddeck-nobody-here")
self.assertEqual(1, out.returncode)
self.assertEqual("", out.stdout)
def test_plain_su_opens_a_root_shell(self):
self.assertEqual("sudo <-s>\n", self.run_su().stdout)
self.assertEqual("sudo <-i>\n", self.run_su("-").stdout)
if __name__ == "__main__":
unittest.main()
+17 -1
View File
@@ -28,7 +28,8 @@ class ValidateApkTest(unittest.TestCase):
def git(self, *args):
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"):
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write"):
(self.root / filename).parent.mkdir(parents=True, exist_ok=True)
(self.root / filename).write_text(message)
self.git("add", filename)
self.git("commit", "--allow-empty", "-qm", message)
@@ -42,6 +43,8 @@ class ValidateApkTest(unittest.TestCase):
path.write_text(json.dumps(event))
def api(path, *args):
if path.endswith("/collaborators/human/permission"):
return {"permission": permission, "role_name": role_name}
if "/statuses/" in path:
self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value))
return {}
@@ -96,6 +99,19 @@ class ValidateApkTest(unittest.TestCase):
self.validate(filename="README.md", result="pending")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_trusted_list_requires_maintainer_pr_opener(self):
with self.assertRaisesRegex(RuntimeError, "Only a maintainer"):
self.validate(filename=".github/trusted-test-builds.txt")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_maintainer_can_change_trusted_list(self):
self.validate(filename=".github/trusted-test-builds.txt", permission="write", role_name="maintain")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_admin_can_change_trusted_list(self):
self.validate(filename=".github/trusted-test-builds.txt", permission="admin", role_name="admin")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_renaming_code_to_documentation_still_requires_compilation(self):
(self.root / "source.kt").write_text("source")
self.git("add", "source.kt")
+282
View File
@@ -0,0 +1,282 @@
import array
import mmap
import os
import socket
import struct
import subprocess
import tempfile
import threading
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
VDEC = ROOT / 'tools/linuxfs/preload/vdec.c'
VENC = ROOT / 'tools/linuxfs/preload/venc.c'
DRIVER = r'''
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
int bl_vdec_open(const char *path, int flags);
int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc);
void bl_vdec_closed(int fd);
void *SDL_LoadObject(const char *name);
void *SDL_LoadFunction(void *handle, const char *name);
struct heap_alloc { uint64_t len; uint32_t fd, fd_flags; uint64_t heap_flags; };
struct create_dumb { uint32_t height, width, bpp, flags, handle, pitch; uint64_t size; };
struct prime_handle { uint32_t handle, flags; int32_t fd; };
struct destroy_dumb { uint32_t handle; };
struct drm_device { char **nodes; int available_nodes; };
static int heap = -1;
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
va_list ap;
va_start(ap, flags);
int mode = va_arg(ap, int);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "open");
if (strcmp(path, "/dev/dma_heap/system") == 0) return heap = memfd_create("heap", 0);
return real(path, flags, mode);
}
int ioctl(int fd, unsigned long req, ...) {
static int (*real)(int, unsigned long, ...);
va_list ap;
va_start(ap, req);
void *arg = va_arg(ap, void *);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "ioctl");
if (fd == heap && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = memfd_create("dmabuf", 0);
if (ftruncate(buf, (off_t)a->len) != 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (req == _IOW('b', 0, uint64_t)) return 0;
return real(fd, req, arg);
}
static int vfd;
static int call(unsigned long req, void *arg) {
int rc;
if (!bl_vdec_ioctl(vfd, req, arg, &rc)) return -100;
return rc < 0 ? -errno : 0;
}
int main(void) {
if (bl_vdec_open("/dev/video0", O_RDWR) != -2) return 2;
void *drm = SDL_LoadObject("libdrm.so.2");
if (!drm) return 3;
int (*devices)(uint32_t, struct drm_device **, int) = SDL_LoadFunction(drm, "drmGetDevices2");
int (*drm_ioctl)(int, unsigned long, void *) = SDL_LoadFunction(drm, "drmIoctl");
if (!devices || !drm_ioctl || !SDL_LoadFunction(drm, "drmModeAtomicCommit")) return 4;
struct drm_device *dev[1];
if (devices(0, NULL, 0) != 1 || devices(0, dev, 1) != 1 || !(dev[0]->available_nodes & 1)) return 5;
int card = open(dev[0]->nodes[0], O_RDWR | O_CLOEXEC);
if (card < 0) return 6;
vfd = bl_vdec_open("/dev/video-dec0", O_RDWR);
if (vfd < 0) return 7;
struct v4l2_capability cap;
if (call(VIDIOC_QUERYCAP, &cap) || (cap.capabilities & 0x04004000) != 0x04004000) return 8;
struct v4l2_fmtdesc d = { .index = 1, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
if (call(VIDIOC_ENUM_FMT, &d) || d.pixelformat != V4L2_PIX_FMT_HEVC) return 9;
struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 720; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC;
if (call(VIDIOC_S_FMT, &f)) return 10;
struct v4l2_requestbuffers r = { .count = 4, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, .memory = V4L2_MEMORY_MMAP };
if (call(VIDIOC_REQBUFS, &r) || r.count != 4) return 11;
unsigned char *in[4];
for (int i = 0; i < 4; i++) {
struct v4l2_plane p = { 0 };
struct v4l2_buffer b = { .index = i, .type = r.type, .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
if (call(VIDIOC_QUERYBUF, &b)) return 12;
in[i] = mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, vfd, p.m.mem_offset);
if (in[i] == MAP_FAILED) return 13;
}
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14;
uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15;
r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16;
int out[3];
for (int i = 0; i < 3; i++) {
struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17;
struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &h)) return 18;
struct destroy_dumb x = { .handle = c.handle };
if (drm_ioctl(card, 0xc00464b4, &x)) return 19;
out[i] = h.fd;
}
unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
if (call(VIDIOC_STREAMON, &types[0]) || call(VIDIOC_STREAMON, &types[1])) return 20;
for (int i = 0; i < 3; i++) {
struct v4l2_plane p = { .m.fd = out[i] };
struct v4l2_buffer b = { .index = i, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &p };
if (call(VIDIOC_QBUF, &b)) return 21;
}
struct pollfd pf = { .fd = vfd, .events = 0xc9 };
if (poll(&pf, 1, 0) != 0) return 22;
for (int frame = 1; frame <= 5; frame++) {
int slot = frame % 4;
memset(in[slot], 'a' + frame, 100 + frame);
struct v4l2_plane p = { .bytesused = 100 + frame };
struct v4l2_buffer b = { .index = slot, .type = types[0], .memory = V4L2_MEMORY_MMAP, .flags = 0x4008, .length = 1, .m.planes = &p };
b.timestamp.tv_usec = frame;
if (call(VIDIOC_QBUF, &b)) return 23;
pf = (struct pollfd){ .fd = vfd, .events = 0xc9 };
if (poll(&pf, 1, 30) != 1 || !(pf.revents & POLLIN)) return 24;
struct v4l2_plane cp = { 0 };
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp };
if (call(VIDIOC_DQBUF, &cb)) return 25;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0);
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size);
munmap(m, size);
pf = (struct pollfd){ .fd = vfd, .events = 0x306 };
if (poll(&pf, 1, 0) != 1) return 26;
struct v4l2_plane op = { 0 };
struct v4l2_buffer ob = { .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &op };
if (call(VIDIOC_DQBUF, &ob) || ob.index != (unsigned)slot) return 27;
struct v4l2_plane rp = { .m.fd = out[cb.index] };
struct v4l2_buffer rb = { .index = cb.index, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &rp };
if (call(VIDIOC_QBUF, &rb)) return 28;
}
if (call(VIDIOC_STREAMOFF, &types[1])) return 29;
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.width = 1920; f.fmt.pix_mp.height = 1088; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f)) return 30;
size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r)) return 31;
struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &big)) return 32;
struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &bh)) return 33;
if (call(VIDIOC_STREAMON, &types[1])) return 34;
struct v4l2_plane bp = { .m.fd = bh.fd };
struct v4l2_buffer bb = { .index = 0, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &bp };
if (call(VIDIOC_QBUF, &bb)) return 35;
memset(in[2], 'z', 50);
struct v4l2_plane zp = { .bytesused = 50 };
struct v4l2_buffer zb = { .index = 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &zp };
zb.timestamp.tv_usec = 6;
if (call(VIDIOC_QBUF, &zb)) return 36;
struct v4l2_plane dp = { 0 };
struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp };
if (call(VIDIOC_DQBUF, &db)) return 37;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]);
bl_vdec_closed(vfd);
return 0;
}
'''
CONFIG = struct.Struct('<IIIIIIII')
CAPTURE = struct.Struct('<III')
PACKET = struct.Struct('<IIII q')
RESULT = struct.Struct('<IiI')
class FakeDecoder(threading.Thread):
def __init__(self, path):
super().__init__(daemon=True)
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
self.listener.bind(path)
self.listener.listen(1)
self.configs, self.packets = [], []
def run(self):
while True:
try:
conn, _ = self.listener.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def serve(self, conn):
bitstream, captures, config = None, {}, None
while True:
fds = array.array('i')
msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(4 * fds.itemsize))
if not msg:
return
for level, kind, data in ancdata:
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
fds.frombytes(data[:len(data) - len(data) % fds.itemsize])
kind = struct.unpack_from('<I', msg)[0]
if kind == 6:
config = CONFIG.unpack(msg)
self.configs.append(config)
bitstream = mmap.mmap(fds[0], config[6] * config[7], prot=mmap.PROT_READ)
os.close(fds[0])
conn.send(RESULT.pack(9, 0, 0))
elif kind == 7:
_, index, size = CAPTURE.unpack(msg)
captures[index] = mmap.mmap(fds[0], size)
os.close(fds[0])
elif kind == 8:
_, source, nbytes, target, pts = PACKET.unpack(msg)
self.packets.append((source, nbytes, target, pts))
first = bitstream[source * config[7]]
frame = captures[target]
frame[0] = first
frame[config[4] * config[5]] = ord('u')
conn.send(RESULT.pack(9, 0, 1))
class VdecEmulatorTest(unittest.TestCase):
def test_remote_play_client_decodes_through_the_app_socket(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC),
str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
self.assertEqual(done.stdout.split('\n')[:6],
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
self.assertEqual([c[1:6] for c in server.configs],
[(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)])
self.assertEqual([p[:3] for p in server.packets],
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
def test_other_programs_keep_the_real_libdrm(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / 'main.c').write_text(
'void *SDL_LoadObject(const char *);\n'
'int main(void) { return SDL_LoadObject("libdrm.so.2") != 0; }\n')
binary = tmp / 'steam'
subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(tmp / 'main.c'),
str(VDEC), str(VENC), '-ldl'], check=True)
done = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stderr)
if __name__ == '__main__':
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import os
import platform
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / "tools/linuxfs/fex/webkitinput.c"
WEBKIT = r"""
#include <stdio.h>
#include <stdlib.h>
const char *g_getenv(const char *name) { return getenv(name); }
void webkit_web_view_load_uri(void *view, const char *uri) { (void)view; printf("%s\n", uri); }
"""
LOADER = r"""
void webkit_web_view_load_uri(void *view, const char *uri);
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) webkit_web_view_load_uri(0, argv[i]);
return 0;
}
"""
URIS = [
"https://www.fab.com",
"https://fab.com/listings/1",
"http://www.fab.com?x=1",
"https://www.fab.com:443/",
"https://store.epicgames.com/en-US/",
"https://www.fab.community/",
"https://notfab.com/",
"tauri://localhost",
]
@unittest.skipUnless(platform.machine() == "x86_64" and shutil.which("gcc"), "webkitinput is built for x86_64 guests")
class WebKitInputTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
(cls.tmp / "webkit.c").write_text(WEBKIT)
(cls.tmp / "loader.c").write_text(LOADER)
subprocess.run(["gcc", "-m64", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-nostdlib", "-fno-stack-protector",
"-fno-builtin", "-fvisibility=hidden", "-o", str(cls.tmp / "libwebkitinput.so"), str(SOURCE)], check=True)
subprocess.run(["gcc", "-shared", "-fPIC", "-o", str(cls.tmp / "libfakewebkit.so"), str(cls.tmp / "webkit.c")], check=True)
subprocess.run(["gcc", "-o", str(cls.tmp / "loader"), str(cls.tmp / "loader.c"), "-L" + str(cls.tmp),
"-Wl,--no-as-needed", "-lwebkitinput", "-lfakewebkit", "-ldl", "-Wl,-rpath," + str(cls.tmp)], check=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def load(self, hidden):
env = {k: v for k, v in os.environ.items() if k != "DROIDDECK_EPIC_HIDDEN"}
if hidden is not None:
env["DROIDDECK_EPIC_HIDDEN"] = hidden
result = subprocess.run([str(self.tmp / "loader")] + URIS, env=env, capture_output=True, text=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
return result.stdout.splitlines()
def test_the_hidden_launcher_loads_a_blank_page_for_fab(self):
self.assertEqual(["about:blank"] * 4 + URIS[4:], self.load("1"))
def test_the_visible_launcher_loads_every_page(self):
self.assertEqual(URIS, self.load(None))
self.assertEqual(URIS, self.load("0"))
self.assertEqual(URIS, self.load("10"))
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -123,6 +123,103 @@ class WinComponentsTest(unittest.TestCase):
self.assertEqual(names, [])
self.assertEqual(notes, ["physx is not installed; skipped"])
def test_a_component_gone_from_the_store_keeps_what_it_placed(self):
self.component("dmband", ["dmband"], {"syswow64/dmband.dll": b"band"})
meta = self.store / "directmusic"
meta.mkdir(parents=True)
(meta / "component.json").write_text(json.dumps({"id": "directmusic", "overrides": [], "requires": ["dmband"]}))
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86"})
self.pick("directmusic", "openal")
self.apply()
for cid in ("dmband", "directmusic", "openal"):
for path in sorted((self.store / cid).rglob("*"), reverse=True):
path.rmdir() if path.is_dir() else path.unlink()
(self.store / cid).rmdir()
names, notes = self.apply()
self.assertEqual(MODULE["overrides_value"](names), "dmband=n,b;openal32=n,b")
self.assertEqual((self.pfx / "syswow64/dmband.dll").read_bytes(), b"band")
self.assertEqual((self.pfx / "syswow64/openal32.dll").read_bytes(), b"x86")
self.assertTrue(all("kept the files it placed" in note for note in notes), notes)
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86 v2"})
os.utime(self.store / "openal/syswow64/OpenAL32.dll", (1, 1))
names, _ = self.apply()
self.assertEqual(MODULE["overrides_value"](names), "dmband=n,b;openal32=n,b")
self.assertEqual((self.pfx / "syswow64/openal32.dll").read_bytes(), b"x86 v2")
self.pick()
self.apply()
self.assertFalse((self.pfx / "syswow64/dmband.dll").exists())
self.assertFalse((self.pfx / "syswow64/openal32.dll").exists())
def test_state_from_before_the_update_keeps_a_missing_bundles_parts(self):
self.component("dmband", ["dmband"], {"syswow64/dmband.dll": b"band"})
meta = self.store / "directmusic"
meta.mkdir(parents=True)
(meta / "component.json").write_text(json.dumps({"id": "directmusic", "overrides": [], "requires": ["dmband"]}))
self.pick("directmusic")
self.apply()
state_file = self.compat / ".droiddeck-wincomponents.json"
state = json.loads(state_file.read_text())
rel = next(iter(state["files"]))
state_file.write_text(json.dumps({"files": state["files"], "components": state["components"], "registry": {}}))
for cid in ("dmband", "directmusic"):
for path in sorted((self.store / cid).rglob("*"), reverse=True):
path.rmdir() if path.is_dir() else path.unlink()
(self.store / cid).rmdir()
dll = self.compat / "pfx" / rel
for _ in range(2):
names, notes = self.apply()
self.assertEqual(MODULE["overrides_value"](names), "dmband=n,b")
self.assertEqual(dll.read_bytes(), b"band")
self.assertEqual(len(notes), 2)
saved = json.loads(state_file.read_text())
self.assertEqual(saved["guessed"], ["directmusic"])
self.assertNotIn("directmusic", saved["requires"])
self.component("dmband", ["dmband"], {"syswow64/dmband.dll": b"band2"})
names, _ = self.apply()
self.assertEqual(MODULE["overrides_value"](names), "dmband=n,b")
self.assertEqual(dll.read_bytes(), b"band2")
self.assertEqual(json.loads(state_file.read_text())["guessed"], ["directmusic"])
self.pick()
self.apply()
self.assertFalse(dll.exists())
def test_a_missing_legacy_bundle_with_its_own_files_keeps_its_parts_and_their_registry(self):
self.pfx.parent.mkdir(parents=True)
user = self.compat / "pfx/user.reg"
user.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Test] 1700000000\n"Mode"="ours"\n')
ident = "HKCU\tsoftware\\test\tmode"
own = self.compat / "pfx/drive_c/windows/syswow64/bundle.dll"
part = self.compat / "pfx/drive_c/windows/syswow64/part.dll"
for path in (own, part):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"x")
self.compat.joinpath(".droiddeck-wincomponents.json").write_text(json.dumps({
"files": {"drive_c/windows/syswow64/bundle.dll": "bundle", "drive_c/windows/syswow64/part.dll": "part"},
"components": ["bundle", "part", "tweak"],
"registry": {ident: {"prev": None, "cid": "tweak", "hive": "HKCU", "key": "Software\\Test", "name": "Mode"}}}))
self.pick("bundle")
names, _ = self.apply()
self.assertEqual(set(MODULE["overrides_value"](names).split(";")), {"bundle=n,b", "part=n,b"})
self.assertTrue(own.exists() and part.exists())
self.assertIn('"Mode"="ours"', user.read_text())
saved = json.loads((self.compat / ".droiddeck-wincomponents.json").read_text())
self.assertEqual(saved["guessed"], ["bundle"])
self.assertIn(ident, saved["registry"])
def test_a_missing_component_that_only_set_registry_values_keeps_them(self):
self.pfx.parent.mkdir(parents=True)
user = self.compat / "pfx/user.reg"
user.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Test] 1700000000\n"Mode"="ours"\n')
ident = "HKCU\tsoftware\\test\tmode"
self.compat.joinpath(".droiddeck-wincomponents.json").write_text(json.dumps({
"files": {}, "components": ["tweak"], "requires": {}, "overrides": {"tweak": []},
"registry": {ident: {"prev": None, "cid": "tweak", "hive": "HKCU", "key": "Software\\Test", "name": "Mode"}}}))
self.pick("tweak")
_, notes = self.apply()
self.assertIn('"Mode"="ours"', user.read_text())
self.assertIn("tweak is not in the store; kept the files it placed until it is installed again", notes)
self.assertIn(ident, json.loads((self.compat / ".droiddeck-wincomponents.json").read_text())["registry"])
def test_no_selection_touches_nothing(self):
self.assertEqual(self.apply(), ([], []))
self.assertFalse(self.compat.exists())
+109
View File
@@ -0,0 +1,109 @@
import os
from pathlib import Path
import shutil
import stat
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
for (int i = 1; i + 1 < argc; i += 2) {
const char *op = argv[i], *path = argv[i + 1];
int ok;
if (strcmp(op, "access") == 0) ok = access(path, W_OK) == 0;
else if (strcmp(op, "access-rw") == 0) ok = access(path, R_OK | W_OK) == 0;
else if (strcmp(op, "faccessat") == 0) {
int dir = open(".", O_RDONLY | O_DIRECTORY);
ok = faccessat(dir, path, W_OK, 0) == 0;
close(dir);
} else if (strcmp(op, "write") == 0) {
int fd = open(path, O_WRONLY | O_TRUNC);
ok = fd >= 0 && write(fd, "saved", 5) == 5;
if (fd >= 0) close(fd);
} else if (strcmp(op, "create") == 0) {
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
ok = fd >= 0;
if (fd >= 0) close(fd);
} else ok = 0;
printf("%s %d\n", op, ok);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc") and os.geteuid() != 0, "needs a C compiler and a non-root user")
class WritablePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
(build / "program.c").write_text(PROGRAM)
cls.preload = build / "libblsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
cls.editor = build / "kate"
subprocess.run(["cc", "-O2", "-o", str(cls.editor), str(build / "program.c")], check=True)
cls.wine = build / "wine64-preloader"
shutil.copy(cls.editor, cls.wine)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def setUp(self):
self.work = Path(tempfile.mkdtemp(dir=self.dir))
self.addCleanup(self.unlock)
self.ini = self.work / "My Games/FalloutNV/FALLOUT.INI"
self.ini.parent.mkdir(parents=True)
self.ini.write_text("bUseThreadedAI=0\n")
self.ini.chmod(0o400)
self.locked = self.work / "Locked"
self.locked.mkdir()
self.locked.chmod(0o500)
def unlock(self):
for path in (self.ini, self.locked):
path.chmod(0o700)
def run_as(self, program, *args, preload=True):
env = dict(os.environ)
env.pop("LD_PRELOAD", None)
if preload:
env["LD_PRELOAD"] = str(self.preload)
out = subprocess.run([str(program), *map(str, args)], env=env, cwd=self.ini.parent,
capture_output=True, text=True, check=True, timeout=60).stdout
return dict(line.split() for line in out.splitlines())
def test_without_the_preload_a_read_only_file_cannot_be_saved(self):
out = self.run_as(self.editor, "access", self.ini, "write", self.ini, preload=False)
self.assertEqual(out, {"access": "0", "write": "0"})
def test_a_desktop_app_can_save_a_read_only_file_like_root(self):
out = self.run_as(self.editor, "access", self.ini, "access-rw", self.ini, "faccessat", self.ini.name,
"write", self.ini, "create", self.locked / "new.tmp")
self.assertEqual(out, {"access": "1", "access-rw": "1", "faccessat": "1", "write": "1", "create": "1"})
self.assertEqual(self.ini.read_text(), "saved")
def test_checking_access_alone_leaves_the_mode_alone(self):
self.run_as(self.editor, "access", self.ini)
self.assertEqual(stat.S_IMODE(self.ini.stat().st_mode), 0o400)
def test_wine_keeps_windows_read_only_files_read_only(self):
out = self.run_as(self.wine, "access", self.ini, "write", self.ini, "create", self.locked / "new.tmp")
self.assertEqual(out, {"access": "0", "write": "0", "create": "0"})
self.assertEqual(self.ini.read_text(), "bUseThreadedAI=0\n")
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -136,7 +136,7 @@ class XboxLaunchTest(unittest.TestCase):
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
def test_launch_view_runs_from_a_short_drive_letter(self):
def test_launch_view_runs_from_its_own_folder_on_a_short_drive_letter(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
prefix = root / 'compat/pfx'
@@ -156,7 +156,7 @@ class XboxLaunchTest(unittest.TestCase):
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', side_effect=call):
initialize.return_value.returncode = 0
self.assertEqual(xbox['wine']([str(view / 'Bin/Game.exe')]), 0)
self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\Bin\\Game.exe'], str(view))])
self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\droiddeck-xbox-1ZpM3D\\Bin\\Game.exe'], str(view.parent))])
self.assertFalse(os.path.lexists(prefix / 'dosdevices/x:'))
def test_view_drive_keeps_drives_in_use_and_reuses_a_stale_view(self):
@@ -170,8 +170,8 @@ class XboxLaunchTest(unittest.TestCase):
(devices / 'w:').symlink_to(root / 'games')
(devices / 'v:').symlink_to(views / 'launch-0/droiddeck-xbox-gone')
exe, link = xbox['view_drive'](root / 'pfx', str(view / 'Game.exe'))
self.assertEqual((exe, link), ('V:\\Game.exe', devices / 'v:'))
self.assertEqual(os.readlink(devices / 'v:'), str(view))
self.assertEqual((exe, link), ('V:\\droiddeck-xbox-new\\Game.exe', devices / 'v:'))
self.assertEqual(os.readlink(devices / 'v:'), str(view.parent))
self.assertEqual(os.readlink(devices / 'x:'), str(live))
self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:'])
self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None))