Merge upstream shortcuts and dual-screen session updates

Preserve profile bindings, shared held-input ownership and custom panels alongside upstream physical shortcuts, mouse routing and docked menus. Add integration regressions and record the full 2,918-test JVM run.
This commit is contained in:
Delete228 committed 2026-10-30 17:00:29 +03:00
commit d6b4b0589b
630 files changed
+42269 -1875

No files matched your search

+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()
+37
View File
@@ -54,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));
@@ -69,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]);
@@ -89,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"
@@ -128,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)
+85
View File
@@ -1,4 +1,5 @@
import hashlib
import io
import json
import os
import shutil
@@ -29,6 +30,24 @@ def config_text(entries):
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)
@@ -586,6 +605,72 @@ class GameEnvironmentTest(unittest.TestCase):
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}
+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()
+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):
+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))
+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()
+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()