mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
Merge main into Steam client download PR
This commit is contained in:
commit
c8cc17bf3a
491 files changed
+34864
-2441
No files matched your search
@@ -0,0 +1,88 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/msg.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct note { long mtype; char text[32]; };
|
||||
|
||||
static int count_lines(const char *path) {
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return -1;
|
||||
int n = 0, c;
|
||||
while ((c = fgetc(f)) != EOF) n += c == '\n';
|
||||
fclose(f);
|
||||
return n;
|
||||
}
|
||||
|
||||
static void *wait_for_note(void *arg) {
|
||||
struct note n;
|
||||
long rc = msgrcv(*(int *)arg, &n, sizeof(n.text), 0, 0);
|
||||
return (void *)(rc < 0 && errno == EIDRM ? 1L : 0L);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int q = msgget(0x5eed0002, IPC_CREAT | IPC_EXCL | 0600);
|
||||
if (q < 0) { perror("msgget"); return 1; }
|
||||
struct note n;
|
||||
if (msgrcv(q, &n, sizeof(n.text), 0, IPC_NOWAIT) != -1 || errno != ENOMSG) { printf("FAIL: empty queue\n"); return 1; }
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
struct note a = {2, "second"}, b = {1, "first"};
|
||||
return msgsnd(q, &a, sizeof(a.text), 0) || msgsnd(q, &b, sizeof(b.text), 0);
|
||||
}
|
||||
int status;
|
||||
waitpid(child, &status, 0);
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status)) { printf("FAIL: child send\n"); return 1; }
|
||||
if (msgrcv(q, &n, sizeof(n.text), 1, 0) < 0 || n.mtype != 1 || strcmp(n.text, "first")) { printf("FAIL: typed receive\n"); return 1; }
|
||||
if (msgrcv(q, &n, sizeof(n.text), 0, 0) < 0 || n.mtype != 2 || strcmp(n.text, "second")) { printf("FAIL: any receive\n"); return 1; }
|
||||
int maps = count_lines("/proc/self/maps");
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
struct note p = {3, "poll"};
|
||||
if (msgsnd(q, &p, sizeof(p.text), 0) || msgrcv(q, &n, sizeof(n.text), 0, 0) < 0 ||
|
||||
msgrcv(q, &n, sizeof(n.text), 0, IPC_NOWAIT) != -1) { printf("FAIL: round %d\n", i); return 1; }
|
||||
}
|
||||
if (count_lines("/proc/self/maps") != maps) { printf("FAIL: mappings grew\n"); return 1; }
|
||||
pthread_t waiter;
|
||||
pthread_create(&waiter, NULL, wait_for_note, &q);
|
||||
usleep(100000);
|
||||
if (msgctl(q, IPC_RMID, NULL) != 0) { perror("msgctl"); return 1; }
|
||||
void *woken;
|
||||
pthread_join(waiter, &woken);
|
||||
if (!woken) { printf("FAIL: waiter not told the queue was removed\n"); return 1; }
|
||||
if (msgsnd(q, &n, sizeof(n.text), IPC_NOWAIT) != -1) { printf("FAIL: send to a removed queue\n"); return 1; }
|
||||
int again = msgget(0x5eed0002, IPC_CREAT | 0600);
|
||||
struct note r = {4, "again"};
|
||||
if (again < 0 || msgsnd(again, &r, sizeof(r.text), 0) || msgrcv(again, &n, sizeof(n.text), 0, 0) < 0 || strcmp(n.text, "again")) {
|
||||
printf("FAIL: queue made again after removal\n");
|
||||
return 1;
|
||||
}
|
||||
msgctl(again, IPC_RMID, NULL);
|
||||
int watched = msgget(0x5eed0003, IPC_CREAT | 0600);
|
||||
pid_t blocked = fork();
|
||||
if (blocked == 0) return msgrcv(watched, &n, sizeof(n.text), 0, 0) < 0 && errno == EIDRM ? 0 : 1;
|
||||
int filler[64];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
struct note f = {5, "fill"};
|
||||
filler[i] = msgget(0x5eed0100 + i, IPC_CREAT | 0600);
|
||||
if (filler[i] < 0 || msgsnd(filler[i], &f, sizeof(f.text), 0)) { printf("FAIL: filler %d\n", i); return 1; }
|
||||
}
|
||||
usleep(100000);
|
||||
if (msgctl(watched, IPC_RMID, NULL) != 0) { perror("msgctl with a full cache"); return 1; }
|
||||
waitpid(blocked, &status, 0);
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status)) { printf("FAIL: waiter not woken with a full cache\n"); return 1; }
|
||||
int extra = msgget(0x5eed0200, IPC_CREAT | 0600);
|
||||
struct note x = {6, "extra"};
|
||||
if (extra < 0 || msgsnd(extra, &x, sizeof(x.text), 0) || msgrcv(extra, &n, sizeof(n.text), 6, 0) < 0 || strcmp(n.text, "extra")) {
|
||||
printf("FAIL: queue past a full cache\n");
|
||||
return 1;
|
||||
}
|
||||
msgctl(extra, IPC_RMID, NULL);
|
||||
for (int i = 0; i < 64; i++) msgctl(filler[i], IPC_RMID, NULL);
|
||||
printf("PASS: sysv msg\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
|
||||
|
||||
|
||||
class BwrapSocketTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
self.shim = runpy.run_path(str(BWRAP))
|
||||
self.shim["socket_name"].__globals__["SOCKET_FILE"] = str(self.dir / "bwrap-socket")
|
||||
|
||||
def name(self, env):
|
||||
with mock.patch.dict(os.environ, env, clear=True):
|
||||
return self.shim["socket_name"]()
|
||||
|
||||
def test_flatpak_empty_environment_reaches_a_renamed_package(self):
|
||||
(self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n")
|
||||
self.assertEqual("\0com.antutu.benchmark.full.bwrap", self.name({}))
|
||||
|
||||
def test_the_environment_still_wins(self):
|
||||
(self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n")
|
||||
self.assertEqual("\0com.tencent.ig.bwrap", self.name({"DROIDDECK_BWRAP_SOCKET": "com.tencent.ig.bwrap"}))
|
||||
|
||||
def test_without_either_the_standard_package_is_asked(self):
|
||||
self.assertEqual("\0com.droiddeck.launcher.bwrap", self.name({}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,51 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def read(path):
|
||||
return path.read_text(encoding='utf-8')
|
||||
|
||||
|
||||
BUILD = ROOT / 'tools/desktop-kde/build.sh'
|
||||
WORKFLOW = ROOT / '.github/workflows/build-desktop-kde.yml'
|
||||
|
||||
|
||||
class DesktopLanguageBuildTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.build = read(BUILD)
|
||||
|
||||
def test_the_main_package_keeps_english_and_every_other_language_becomes_a_pack(self):
|
||||
loop = self.build.split('usr/share/locale/*/', 1)[1].split('rm -rf "$work/root/usr/share/doc"', 1)[0]
|
||||
self.assertIn("case $loc in en*) continue ;; esac", loop)
|
||||
self.assertIn('[ -d "$dir/LC_MESSAGES" ] || continue', loop)
|
||||
self.assertIn('desktop-kde-i18n-$loc.tar.zst', loop)
|
||||
self.assertIn('> "$out/desktop-kde.i18n.txt"', loop)
|
||||
self.assertIn('find "$work/root/usr/share/locale" -mindepth 1 -maxdepth 1 -type d ! -name \'en*\'',
|
||||
self.build.split('i18n.txt"', 1)[1])
|
||||
|
||||
def test_the_index_lines_carry_what_the_app_verifies(self):
|
||||
record = re.search(r"printf '%s %s %s\\n' \"\$loc\" \"\$\(sha256sum \"\$file\" \| cut -d' ' -f1\)\" \"\$\(stat -c %s \"\$file\"\)\"",
|
||||
self.build)
|
||||
self.assertIsNotNone(record)
|
||||
line = 'de ' + 'a' * 64 + ' 262144'
|
||||
fields = line.split()
|
||||
self.assertEqual(3, len(fields))
|
||||
self.assertTrue(re.fullmatch(r'[0-9a-f]{64}', fields[1]))
|
||||
self.assertEqual(262144, int(fields[2]))
|
||||
|
||||
def test_the_workflow_ships_the_index_and_the_packs(self):
|
||||
workflow = read(WORKFLOW)
|
||||
self.assertIn('out/desktop-kde.i18n.txt', workflow)
|
||||
self.assertEqual(1, len([line for line in workflow.splitlines()
|
||||
if line.strip() == 'out/desktop-kde-i18n-*.tar.zst']))
|
||||
release = workflow.split('gh release create', 1)[1]
|
||||
self.assertIn('out/desktop-kde.i18n.txt', release)
|
||||
self.assertIn('out/desktop-kde-i18n-*.tar.zst', release)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -6,6 +6,7 @@ import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
@@ -77,6 +78,79 @@ class FakeDevTools(threading.Thread):
|
||||
conn.close()
|
||||
|
||||
|
||||
class FakeSteamClient(threading.Thread):
|
||||
|
||||
def __init__(self, showing):
|
||||
super().__init__(daemon=True)
|
||||
self.showing = showing
|
||||
self.server = socket.socket()
|
||||
self.server.bind(("127.0.0.1", 0))
|
||||
self.server.listen(4)
|
||||
self.port = self.server.getsockname()[1]
|
||||
self.seen = []
|
||||
self.conn = None
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.server.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def send(self, conn, message):
|
||||
payload = json.dumps(message).encode()
|
||||
header = bytes([0x81, 126]) + struct.pack(">H", len(payload)) if len(payload) > 125 else bytes([0x81, len(payload)])
|
||||
with self.lock:
|
||||
conn.sendall(header + payload)
|
||||
|
||||
def push(self, payload, name=None):
|
||||
self.send(self.conn, {"method": "Runtime.bindingCalled",
|
||||
"params": {"name": name or agent.KEYBOARD_BINDING, "payload": payload}})
|
||||
|
||||
def drop(self):
|
||||
self.conn.shutdown(socket.SHUT_RDWR)
|
||||
self.conn.close()
|
||||
|
||||
def serve(self, conn):
|
||||
stream = conn.makefile("rb")
|
||||
head = b""
|
||||
while not head.endswith(b"\r\n\r\n"):
|
||||
head += stream.read(1)
|
||||
request = head.decode()
|
||||
if request.startswith("GET /json"):
|
||||
body = json.dumps([{"title": "Steam Big Picture Mode", "url": "https://steamloopback.host/routes/",
|
||||
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/2" % self.port},
|
||||
{"title": "SharedJSContext", "url": "https://steamloopback.host/",
|
||||
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/1" % self.port}]).encode()
|
||||
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
||||
conn.close()
|
||||
return
|
||||
key = [l.split(":", 1)[1].strip() for l in request.split("\r\n") if l.lower().startswith("sec-websocket-key")][0]
|
||||
accept = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode()
|
||||
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: %s\r\n\r\n" % accept).encode())
|
||||
self.conn = conn
|
||||
try:
|
||||
while True:
|
||||
b0, b1 = stream.read(2)
|
||||
n = b1 & 0x7F
|
||||
if n == 126:
|
||||
n = struct.unpack(">H", stream.read(2))[0]
|
||||
elif n == 127:
|
||||
n = struct.unpack(">Q", stream.read(8))[0]
|
||||
mask = stream.read(4)
|
||||
data = stream.read(n)
|
||||
message = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
|
||||
self.seen.append(message)
|
||||
self.push("true", name="unrelated")
|
||||
result = {"result": {"type": "boolean", "value": self.showing}} if message["method"] == "Runtime.evaluate" else {}
|
||||
self.send(conn, {"id": message["id"], "result": result})
|
||||
except (OSError, ValueError):
|
||||
conn.close()
|
||||
|
||||
|
||||
class AgentTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
@@ -338,6 +412,45 @@ class AgentTest(unittest.TestCase):
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
|
||||
self.assertEqual(1, agent.main(["--steam-asleep"]))
|
||||
|
||||
def test_supports_vr_command_separates_vr_flat_and_unknown_apps(self):
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
|
||||
for value, code in ((True, 0), (False, 5), (None, 1)):
|
||||
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
|
||||
self.assertEqual(code, agent.main(["--steam-supports-vr", "204360"]))
|
||||
self.assertIn('GetAppOverviewByGameID?.("204360")', ask.call_args.args[1])
|
||||
self.assertIn("vr_supported", ask.call_args.args[1])
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
|
||||
self.assertEqual(1, agent.main(["--steam-supports-vr", "204360"]))
|
||||
for bad in ([], ["1;x"], ["-1"], ["1", "2"]):
|
||||
self.assertEqual(2, agent.main(["--steam-supports-vr"] + bad))
|
||||
|
||||
def test_idle_inhibit_command_reports_whether_steam_reached_the_state(self):
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
|
||||
for value, code in ((True, 0), (False, 1), (None, 1)):
|
||||
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
|
||||
self.assertEqual(code, agent.main(["--steam-idle-inhibit", "on"]))
|
||||
self.assertIn("toggle_idle_suspend_inhibit 1", ask.call_args.args[1])
|
||||
self.assertTrue(ask.call_args.args[1].rstrip().endswith("(true)"))
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": True}) as ask:
|
||||
self.assertEqual(0, agent.main(["--steam-idle-inhibit", "off"]))
|
||||
self.assertTrue(ask.call_args.args[1].rstrip().endswith("(false)"))
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
|
||||
self.assertEqual(1, agent.main(["--steam-idle-inhibit", "on"]))
|
||||
self.assertEqual(2, agent.main(["--steam-idle-inhibit", "maybe"]))
|
||||
|
||||
def test_idle_suspend_seconds_follow_the_power_source(self):
|
||||
vpower = self.dir / "ac_status"
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": [3600, 900]}):
|
||||
vpower.write_text("Connected\n")
|
||||
self.assertEqual(3600, agent.steam_idle_suspend_seconds(self.dir, vpower))
|
||||
vpower.write_text("Disconnected\n")
|
||||
self.assertEqual(900, agent.steam_idle_suspend_seconds(self.dir, vpower))
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": None}):
|
||||
self.assertIsNone(agent.steam_idle_suspend_seconds(self.dir, vpower))
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}), \
|
||||
patch.object(agent, "steam_idle_suspend_seconds", return_value=None):
|
||||
self.assertEqual(1, agent.main(["--steam-idle-suspend-seconds"]))
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
@@ -382,6 +495,144 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertIn(child.pid, agent.game_pids(424242))
|
||||
|
||||
|
||||
class SteamKeyboardTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.dir = Path(self.temp.name)
|
||||
|
||||
def state(self):
|
||||
try:
|
||||
return json.loads((self.dir / "keyboard.json").read_text())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
def wait_for(self, check):
|
||||
for _ in range(200):
|
||||
if check():
|
||||
return
|
||||
time.sleep(0.02)
|
||||
self.fail("timed out; keyboard.json is %s" % self.state())
|
||||
|
||||
def test_report_writes_only_changes(self):
|
||||
watcher = agent.KeyboardWatcher(self.dir)
|
||||
watcher.report(False)
|
||||
self.assertEqual({"steamKeyboard": False, "seq": 1}, self.state())
|
||||
watcher.report(False)
|
||||
watcher.report(True)
|
||||
self.assertEqual({"steamKeyboard": True, "seq": 2}, self.state())
|
||||
|
||||
def test_follows_the_clients_keyboard_and_rechecks_while_idle(self):
|
||||
client = FakeSteamClient(False)
|
||||
client.start()
|
||||
self.addCleanup(client.server.close)
|
||||
(self.dir / "cdp-port").write_text(str(client.port))
|
||||
watcher = agent.KeyboardWatcher(self.dir)
|
||||
failure = []
|
||||
with patch.object(agent, "KEYBOARD_CHECK_SECONDS", 0.3):
|
||||
thread = threading.Thread(target=lambda: failure.append(self.capture(watcher.watch)), daemon=True)
|
||||
thread.start()
|
||||
self.wait_for(lambda: self.state() == {"steamKeyboard": False, "seq": 1})
|
||||
self.assertEqual("Runtime.addBinding", client.seen[0]["method"])
|
||||
self.assertEqual(agent.KEYBOARD_BINDING, client.seen[0]["params"]["name"])
|
||||
self.assertIn("IsShowingVirtualKeyboard", client.seen[1]["params"]["expression"])
|
||||
self.assertIn(agent.KEYBOARD_BINDING, client.seen[1]["params"]["expression"])
|
||||
self.assertNotIn("__BINDING__", client.seen[1]["params"]["expression"])
|
||||
client.push("true")
|
||||
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True)
|
||||
client.push("false")
|
||||
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is False)
|
||||
client.showing = True
|
||||
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True)
|
||||
self.assertGreaterEqual(len([m for m in client.seen if m["method"] == "Runtime.evaluate"]), 2)
|
||||
client.drop()
|
||||
thread.join(5)
|
||||
self.assertFalse(thread.is_alive())
|
||||
self.assertIsInstance(failure[0], OSError)
|
||||
|
||||
def test_any_loss_reports_the_keyboard_closed_and_backs_off(self):
|
||||
watcher = agent.KeyboardWatcher(self.dir)
|
||||
watcher.report(True)
|
||||
|
||||
def attached_then_lost():
|
||||
watcher.attached = True
|
||||
raise OSError("DevTools closed the connection")
|
||||
|
||||
steps = iter([agent.AgentError("NO_DEVTOOLS", "no port"), agent.AgentError("NO_DEVTOOLS", "no port"),
|
||||
attached_then_lost, KeyError("SteamUIStore")])
|
||||
|
||||
def watch():
|
||||
step = next(steps, None)
|
||||
if step is None:
|
||||
raise SystemExit
|
||||
if callable(step):
|
||||
step()
|
||||
raise step
|
||||
|
||||
with patch.object(watcher, "watch", side_effect=watch), patch.object(agent.time, "sleep") as sleep, \
|
||||
patch.object(agent, "log") as log:
|
||||
with self.assertRaises(SystemExit):
|
||||
watcher.run()
|
||||
self.assertEqual({"steamKeyboard": False, "seq": 2}, self.state())
|
||||
self.assertEqual([2, 4, 2, 4], [c.args[0] for c in sleep.call_args_list])
|
||||
self.assertFalse(watcher.attached)
|
||||
self.assertEqual(3, log.call_count)
|
||||
|
||||
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:
|
||||
agent.KeyboardWatcher(self.dir).watch()
|
||||
self.assertEqual("NO_TARGET", caught.exception.code)
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node is not installed")
|
||||
def test_page_script_watches_every_window_with_or_without_subscribe(self):
|
||||
harness = r"""
|
||||
const assert = require('assert');
|
||||
globalThis.window = globalThis;
|
||||
const script = require('fs').readFileSync(process.argv[2], 'utf8');
|
||||
const calls = [];
|
||||
window.droiddeckSteamKeyboard = value => calls.push(value);
|
||||
const tick = ms => new Promise(done => setTimeout(done, ms));
|
||||
const value = subscribe => {
|
||||
const v = { m_currentValue: false, m_callbacks: [] };
|
||||
if (subscribe) v.Subscribe = cb => { v.m_callbacks.push(cb); return { Unsubscribe() {} }; };
|
||||
v.set = next => { v.m_currentValue = next; for (const cb of v.m_callbacks) cb(next); };
|
||||
return v;
|
||||
};
|
||||
(async () => {
|
||||
assert.strictEqual(eval(script), false);
|
||||
assert.deepStrictEqual(calls, ['false']);
|
||||
const main = value(true), overlay = value(false);
|
||||
globalThis.SteamUIStore = { WindowStore: { SteamUIWindows: [{ VirtualKeyboardManager: { IsShowingVirtualKeyboard: main } }] } };
|
||||
assert.strictEqual(eval(script), false);
|
||||
main.set(true);
|
||||
await tick(20);
|
||||
assert.deepStrictEqual(calls, ['false', 'true']);
|
||||
main.set(false);
|
||||
await tick(20);
|
||||
SteamUIStore.WindowStore.SteamUIWindows.push({}, { VirtualKeyboardManager: { IsShowingVirtualKeyboard: overlay } });
|
||||
overlay.m_currentValue = true;
|
||||
await tick(700);
|
||||
assert.deepStrictEqual(calls, ['false', 'true', 'false', 'true']);
|
||||
assert.strictEqual(eval(script), true);
|
||||
assert.strictEqual(main.m_callbacks.length, 1);
|
||||
clearInterval(window.__droiddeckKeyboard.timer);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
"""
|
||||
(self.dir / "keyboard.js").write_text(agent.KEYBOARD_JS)
|
||||
(self.dir / "harness.js").write_text(harness)
|
||||
result = subprocess.run(["node", str(self.dir / "harness.js"), str(self.dir / "keyboard.js")],
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
|
||||
@staticmethod
|
||||
def capture(call):
|
||||
try:
|
||||
call()
|
||||
except Exception as e:
|
||||
return e
|
||||
|
||||
|
||||
class VrFocusTest(unittest.TestCase):
|
||||
def test_scene_dashboard_and_external_focus_changes(self):
|
||||
focus = agent.VrSceneFocus()
|
||||
|
||||
@@ -45,6 +45,8 @@ class FexTestCase(unittest.TestCase):
|
||||
"WANTED": str(self.home / ".config/droiddeck/fex-wanted"),
|
||||
"PRELOADS": str(self.tmp / "preloads"),
|
||||
"HOST_PRELOAD": str(self.tmp / "ld.so.preload"),
|
||||
"DEVICE_FONTS": str(self.tmp / "android-fonts"),
|
||||
"FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"),
|
||||
}
|
||||
patcher = mock.patch.dict(G, patches)
|
||||
patcher.start()
|
||||
@@ -69,9 +71,10 @@ class FexTestCase(unittest.TestCase):
|
||||
self.write(Path(library or self.steam) / "steamapps/appmanifest_3127680.acf", '"AppState" { "installdir" "FEX-Emu" }')
|
||||
return tool
|
||||
|
||||
def runtime(self, version="3.0.20260805.254768", lines=None):
|
||||
runtime = self.steam / "steamapps/common/SteamLinuxRuntime_sniper"
|
||||
platform = runtime / ("sniper_platform_" + version)
|
||||
def runtime(self, version="3.0.20260805.254768", lines=None, app="1628350", folder="SteamLinuxRuntime_sniper",
|
||||
prefix="sniper_platform_"):
|
||||
runtime = self.steam / "steamapps/common" / folder
|
||||
platform = runtime / (prefix + version)
|
||||
files = platform / "files"
|
||||
self.write(files / "lib/x86_64-linux-gnu/libc.so.6", elf(62))
|
||||
self.write(files / "ab/cdef-1.bin", b"blob")
|
||||
@@ -89,9 +92,16 @@ class FexTestCase(unittest.TestCase):
|
||||
]
|
||||
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
|
||||
out.write("\n".join(mtree) + "\n")
|
||||
self.write(self.steam / "steamapps/appmanifest_1628350.acf", '"AppState" { "installdir" "SteamLinuxRuntime_sniper" }')
|
||||
self.write(self.steam / ("steamapps/appmanifest_%s.acf" % app), '"AppState" { "installdir" "%s" }' % folder)
|
||||
return platform
|
||||
|
||||
def steamrt4(self):
|
||||
return self.runtime("4.0.20260928.262390", app="4183110", folder="SteamLinuxRuntime_4", prefix="steamrt4_platform_")
|
||||
|
||||
def proton(self, require):
|
||||
proton = self.steam / "steamapps/common/Proton - Experimental"
|
||||
self.write(proton / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/proton %%verb%%"\n "require_tool_appid" "%s"\n}\n' % require)
|
||||
return self.write(proton / "proton", "#!/usr/bin/env python3\n", 0o755)
|
||||
def graphics(self, sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41", libstdcxx=b"GLIBCXX_3.4.28 GLIBCXX_3.4.33"):
|
||||
files = Path(sniper) / "files"
|
||||
x86 = files / "lib/x86_64-linux-gnu"
|
||||
@@ -119,6 +129,9 @@ class FexTestCase(unittest.TestCase):
|
||||
self.write(provided / "gconv/NEW.so", b"new gconv")
|
||||
self.write(platform / "files/lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.41")
|
||||
self.write(platform / "files/lib/i386-linux-gnu/ld-linux.so.2", b"new ld32")
|
||||
for arch in ("x86_64", "i386"):
|
||||
for name in ("libssl.so.3", "libcrypto.so.3"):
|
||||
self.write(platform / "files/lib" / (arch + "-linux-gnu") / name, arch.encode() + name.encode())
|
||||
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
|
||||
out.write("#mtree\n. type=dir\n")
|
||||
self.write(self.steam / "steamapps/appmanifest_4183110.acf", '"AppState" { "installdir" "SteamLinuxRuntime_4" }')
|
||||
@@ -238,6 +251,8 @@ class PrepareTest(FexTestCase):
|
||||
self.assertEqual((root / "etc/ld.so.preload").read_text(),
|
||||
"/usr/$LIB/droiddeck/libblsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n")
|
||||
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfakeinput.so").read_bytes(), b"i386libfakeinput.so")
|
||||
self.assertEqual((root / "etc/asound.conf").read_text(),
|
||||
"pcm.!default {\n type pulse\n}\nctl.!default {\n type pulse\n}\n")
|
||||
self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libblsession.so\n")
|
||||
FEX["install_preloads"](str(root))
|
||||
self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libblsession.so\n")
|
||||
@@ -253,6 +268,21 @@ class PrepareTest(FexTestCase):
|
||||
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfaultreport.so").read_bytes(), b"report32")
|
||||
self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libfaultreport.so\n")
|
||||
|
||||
def test_device_fonts_reach_the_x86_runtime(self):
|
||||
root = self.tmp / "root"
|
||||
conf = root / str(self.tmp / "66-droiddeck-device-fonts.conf").lstrip("/")
|
||||
rules = '<?xml version="1.0"?><fontconfig>\n<match target="pattern"></match>\n</fontconfig>\n'
|
||||
self.write(self.tmp / "66-droiddeck-device-fonts.conf", rules)
|
||||
FEX["install_fonts"](str(root))
|
||||
self.assertFalse(conf.exists())
|
||||
(self.tmp / "android-fonts").mkdir()
|
||||
FEX["install_fonts"](str(root))
|
||||
self.assertEqual(conf.read_text(), '<?xml version="1.0"?><fontconfig>\n<dir>%s</dir>\n<match target="pattern"></match>\n</fontconfig>\n'
|
||||
% (self.tmp / "android-fonts"))
|
||||
(self.tmp / "66-droiddeck-device-fonts.conf").unlink()
|
||||
FEX["install_fonts"](str(root))
|
||||
self.assertFalse(conf.exists())
|
||||
|
||||
def test_config_turns_thunks_on_only_when_complete(self):
|
||||
FEX["write_config"]({"host_thunks": "/h", "guest_thunks": "/g", "thunks_db": "/db"}, "/root")
|
||||
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
|
||||
@@ -272,6 +302,29 @@ class PrepareTest(FexTestCase):
|
||||
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
|
||||
self.assertFalse(status["ready"])
|
||||
|
||||
def test_a_missing_steam_runtime_4_is_named(self):
|
||||
self.fex_tool()
|
||||
self.runtime()
|
||||
with mock.patch.dict(G, {"steam_running": lambda: False}):
|
||||
fex, said = self.quiet(FEX["prepare"], "4183110")
|
||||
self.assertIsNone(fex)
|
||||
self.assertIn("Steam Linux Runtime 4.0 (steamrt4, Steam app 4183110)", said)
|
||||
self.assertNotIn("FEX (Steam app", said)
|
||||
|
||||
def test_the_x86_runtime_gets_its_own_steam_client_link(self):
|
||||
self.fex_tool()
|
||||
platform = self.runtime()
|
||||
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
|
||||
self.write(self.steam / "linux64/steamclient.so", elf(62))
|
||||
self.write(self.steam / "linux32/steamclient.so", elf(3))
|
||||
(self.home / ".steam").mkdir()
|
||||
os.symlink(self.steam / "linuxarm64", self.home / ".steam/sdk64")
|
||||
self.quiet(FEX["prepare"])
|
||||
guest = platform / "files" / str(self.home).lstrip("/") / ".steam"
|
||||
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
|
||||
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
|
||||
self.assertEqual(os.readlink(self.home / ".steam/sdk64"), str(self.steam / "linux64"))
|
||||
|
||||
def test_a_ready_install_is_prepared(self):
|
||||
tool = self.fex_tool()
|
||||
platform = self.runtime()
|
||||
@@ -302,6 +355,10 @@ class PrepareTest(FexTestCase):
|
||||
self.assertEqual((x86 / "ld-linux-x86-64.so.2").read_bytes(), b"new ld")
|
||||
self.assertEqual((x86 / "gconv/NEW.so").read_bytes(), b"new gconv")
|
||||
self.assertEqual((root / "lib/i386-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.41")
|
||||
self.assertEqual((x86 / "libssl.so.3").read_bytes(), b"x86_64libssl.so.3")
|
||||
self.assertEqual((x86 / "libcrypto.so.3").read_bytes(), b"x86_64libcrypto.so.3")
|
||||
self.assertEqual((root / "lib/i386-linux-gnu/libssl.so.3").read_bytes(), b"i386libssl.so.3")
|
||||
self.assertEqual((root / "lib/i386-linux-gnu/libcrypto.so.3").read_bytes(), b"i386libcrypto.so.3")
|
||||
self.assertEqual((x86 / "libSDL2-2.0.so.0").read_bytes(), b"sdl")
|
||||
self.assertEqual(os.readlink(x86 / "libfoo.so.1"), "libfoo.so.1.2")
|
||||
self.assertEqual((x86 / "libfoo.so.1").read_bytes(), b"foo")
|
||||
@@ -528,6 +585,20 @@ class LaunchTest(FexTestCase):
|
||||
thunks = json.loads((self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json").read_text())
|
||||
self.assertEqual(thunks, {"ThunksDB": {"GL": 1, "Vulkan": 1}})
|
||||
|
||||
def test_host_libc_tunables_stay_on_the_host(self):
|
||||
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
|
||||
self.assertNotIn("GLIBC_TUNABLES", guest)
|
||||
|
||||
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
|
||||
self.fex_tool()
|
||||
self.runtime()
|
||||
platform = self.steamrt4()
|
||||
proton = self.proton("4183110")
|
||||
with mock.patch("os.execve") as emulated:
|
||||
self.quiet(FEX["launch"], [str(proton), "waitforexitandrun", "game.exe"], {}, "on")
|
||||
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
|
||||
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
|
||||
|
||||
def test_native_programs_run_directly(self):
|
||||
program = self.write(self.tmp / "native", elf(183), 0o755)
|
||||
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
|
||||
|
||||
@@ -1164,7 +1164,9 @@ class BundleTest(unittest.TestCase):
|
||||
bundle = steps["Bundle the droiddeck-esync packs"]
|
||||
self.assertNotIn("if", bundle)
|
||||
self.assertIn("tools/droiddeck-esync/release.env", bundle["run"])
|
||||
self.assertEqual(bundle["run"].count('-R "$SYNC_BUNDLE_REPO"'), 2)
|
||||
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("sha256sum -c -", bundle["run"])
|
||||
self.assertNotIn("revoked.txt", bundle["run"])
|
||||
stage = next(step for step in apk["jobs"]["build"]["steps"] if "overlay/usr/local/bin/droiddeck-*" in step.get("run", ""))
|
||||
|
||||
@@ -18,24 +18,44 @@ READER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void)
|
||||
static int vector_count;
|
||||
|
||||
static ssize_t controller_read(int fd, void *buffer, size_t size)
|
||||
{
|
||||
if (!vector_count)
|
||||
return read(fd, buffer, size);
|
||||
struct iovec vectors[3] = {
|
||||
{buffer, sizeof(struct input_event)},
|
||||
{(char *)buffer + sizeof(struct input_event), 0},
|
||||
{(char *)buffer + sizeof(struct input_event), size - sizeof(struct input_event)},
|
||||
};
|
||||
if (vector_count == 1) {
|
||||
vectors[0].iov_len = size;
|
||||
return readv(fd, vectors, 1);
|
||||
}
|
||||
return readv(fd, vectors, 3);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0;
|
||||
struct input_event events[64];
|
||||
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0) {
|
||||
perror("open");
|
||||
return 1;
|
||||
}
|
||||
while (read(fd, events, sizeof(events)) > 0)
|
||||
while (controller_read(fd, events, sizeof(events)) > 0)
|
||||
;
|
||||
puts("ready");
|
||||
fflush(stdout);
|
||||
char go;
|
||||
if (read(0, &go, 1) != 1)
|
||||
return 1;
|
||||
ssize_t got = read(fd, events, sizeof(events));
|
||||
ssize_t got = controller_read(fd, events, sizeof(events));
|
||||
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
|
||||
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
|
||||
events[i].code, events[i].value);
|
||||
@@ -65,6 +85,146 @@ int main(void)
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
READV_CHECKS = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
struct input_event events[64];
|
||||
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0)
|
||||
return 1;
|
||||
while (read(fd, events, sizeof(events)) > 0)
|
||||
;
|
||||
struct iovec vector = {events, sizeof(events)};
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EAGAIN)
|
||||
return 2;
|
||||
if (readv(fd, NULL, 0) != 0)
|
||||
return 3;
|
||||
vector.iov_len = 0;
|
||||
if (readv(fd, &vector, 1) != 0)
|
||||
return 4;
|
||||
vector.iov_len = sizeof(struct input_event) - 1;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EINVAL)
|
||||
return 5;
|
||||
ssize_t (*invoke)(int, const struct iovec *, int) = readv;
|
||||
if (invoke(fd, NULL, -1) != -1 || errno != EINVAL)
|
||||
return 6;
|
||||
if (invoke(fd, NULL, 1025) != -1 || errno != EINVAL)
|
||||
return 7;
|
||||
if (invoke(fd, NULL, 1) != -1 || errno != EFAULT)
|
||||
return 8;
|
||||
long page = sysconf(_SC_PAGESIZE);
|
||||
void *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (area == MAP_FAILED)
|
||||
return 10;
|
||||
struct iovec *boundary = (struct iovec *)((char *)area + page - sizeof(struct iovec));
|
||||
*boundary = vector;
|
||||
if (mprotect((char *)area + page, page, PROT_NONE))
|
||||
return 11;
|
||||
if (invoke(fd, boundary, 2) != -1 || errno != EFAULT)
|
||||
return 12;
|
||||
if (invoke(fd, boundary + 1, 1) != -1 || errno != EFAULT)
|
||||
return 13;
|
||||
if (munmap(area, 2 * page))
|
||||
return 14;
|
||||
if (invoke(fd, boundary, 1) != -1 || errno != EFAULT)
|
||||
return 15;
|
||||
int pipefd[2];
|
||||
char text[5] = {0};
|
||||
struct iovec parts[2] = {{text, 1}, {text + 1, 3}};
|
||||
if (pipe(pipefd) || write(pipefd[1], "test", 4) != 4 ||
|
||||
readv(pipefd[0], parts, 2) != 4 || strcmp(text, "test"))
|
||||
return 9;
|
||||
puts("ok");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
READV_DESTINATION_CHECKS = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct input_event events[64];
|
||||
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0)
|
||||
return 1;
|
||||
if (argc > 1)
|
||||
while (read(fd, events, sizeof(events)) > 0)
|
||||
;
|
||||
puts("ready");
|
||||
fflush(stdout);
|
||||
char go;
|
||||
if (read(0, &go, 1) != 1)
|
||||
return 2;
|
||||
long page = sysconf(_SC_PAGESIZE);
|
||||
char *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (area == MAP_FAILED || mprotect(area + page, page, PROT_NONE))
|
||||
return 3;
|
||||
struct iovec vector = {area + page, sizeof(struct input_event)};
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 4;
|
||||
if (read(fd, vector.iov_base, vector.iov_len) != -1 || errno != EFAULT)
|
||||
return 5;
|
||||
if (mprotect(area, page, PROT_READ))
|
||||
return 6;
|
||||
vector.iov_base = area;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 7;
|
||||
if (mprotect(area, page, PROT_READ | PROT_WRITE) || munmap(area + page, page))
|
||||
return 8;
|
||||
vector.iov_base = area + page;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 9;
|
||||
vector.iov_base = area + page - 1;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 15;
|
||||
vector.iov_base = area + page - sizeof(struct input_event);
|
||||
vector.iov_len = 2 * sizeof(struct input_event);
|
||||
if (readv(fd, &vector, 1) != sizeof(struct input_event))
|
||||
return 10;
|
||||
struct input_event *first = vector.iov_base;
|
||||
if (first->type != EV_KEY || first->code != BTN_A)
|
||||
return 11;
|
||||
struct iovec parts[2] = {{events, sizeof(struct input_event)}, {NULL, sizeof(struct input_event)}};
|
||||
if (readv(fd, parts, 2) != sizeof(struct input_event))
|
||||
return 12;
|
||||
if (events[0].type != (argc > 1 ? EV_ABS : EV_KEY) || events[0].code != (argc > 1 ? ABS_Y : BTN_B))
|
||||
return 13;
|
||||
vector.iov_base = events;
|
||||
vector.iov_len = sizeof(events);
|
||||
ssize_t got = readv(fd, &vector, 1);
|
||||
if (got != (argc > 1 ? 1 : 18) * sizeof(struct input_event) ||
|
||||
events[0].type != (argc > 1 ? EV_SYN : EV_KEY) || events[0].code != (argc > 1 ? SYN_REPORT : BTN_X))
|
||||
return 14;
|
||||
munmap(area, page);
|
||||
puts("ok");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
OVERLAY_READ = r"""
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
ssize_t read(int fd, void *buffer, size_t size)
|
||||
{
|
||||
struct iovec vector = {buffer, size};
|
||||
return readv(fd, &vector, 1);
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def can_build(bits):
|
||||
@@ -82,15 +242,16 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
|
||||
def ring(self):
|
||||
def ring(self, virtual=True):
|
||||
hooks = self.tmp / "hooks"
|
||||
hooks.mkdir()
|
||||
(hooks / "event16").touch()
|
||||
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
|
||||
(hooks / ("event16" if virtual else "event0")).touch()
|
||||
ring = bytearray(HEADER + CAPACITY * EVENT + (DESCRIPTION if virtual else 0))
|
||||
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 5, 0, 0)
|
||||
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
|
||||
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
|
||||
path = hooks / ".uinput-event16"
|
||||
if virtual:
|
||||
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
|
||||
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
|
||||
path = hooks / ".uinput-event16" if virtual else self.tmp / "ring0"
|
||||
path.write_bytes(bytes(ring))
|
||||
return hooks, path
|
||||
|
||||
@@ -106,11 +267,22 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
|
||||
return library, binary
|
||||
|
||||
def read_through(self, bits):
|
||||
library, reader = self.build(bits, READER, "reader")
|
||||
hooks, path = self.ring()
|
||||
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER):
|
||||
if not virtual:
|
||||
program = program.replace("event16", "event0")
|
||||
library, reader = self.build(bits, program, "reader")
|
||||
hooks, path = self.ring(virtual=virtual)
|
||||
env = dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks))
|
||||
process = subprocess.Popen([str(reader)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
|
||||
if not virtual:
|
||||
env["FAKE_EVDEV_MEMFD_PATHS"] = "0=" + str(path)
|
||||
if overlay:
|
||||
source = self.tmp / "overlay.c"
|
||||
source.write_text(OVERLAY_READ)
|
||||
overlay_library = self.tmp / "overlay.so"
|
||||
subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True)
|
||||
env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library)
|
||||
command = [str(reader)] + ([str(vectors)] if vectors else [])
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
|
||||
self.addCleanup(process.kill)
|
||||
self.assertEqual(process.stdout.readline(), "ready\n")
|
||||
with open(path, "r+b") as ring:
|
||||
@@ -131,6 +303,43 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
self.assertEqual(self.read_through("-m64"),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_reads_events_instead_of_the_backing_file(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=1),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_reads_the_original_controller_ring(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=1, virtual=False),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_an_overlay_read_fallback_to_readv_reads_events_without_recursion(self):
|
||||
self.assertEqual(self.read_through("-m64", overlay=True),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_reads_event_aligned_vectors_and_skips_empty_ones(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=3),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_a_32_bit_guest_reads_the_same_events_with_readv(self):
|
||||
self.assertEqual(self.read_through("-m32", vectors=1),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_preserves_nonblocking_errors_and_other_descriptors(self):
|
||||
library, probe = self.build("-m64", READV_CHECKS, "readv-checks")
|
||||
hooks, _ = self.ring()
|
||||
run = subprocess.run([str(probe)], capture_output=True, text=True, timeout=10,
|
||||
env=dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks)))
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
self.assertEqual(run.stdout, "ok\n")
|
||||
|
||||
def test_readv_keyframes_handle_destination_faults_and_partial_progress(self):
|
||||
self.assertEqual(self.read_through("-m64", program=READV_DESTINATION_CHECKS), "ok\n")
|
||||
|
||||
def test_readv_ring_events_handle_destination_faults_and_partial_progress(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=1, program=READV_DESTINATION_CHECKS), "ok\n")
|
||||
|
||||
def test_a_32_bit_guest_handles_readv_destination_faults(self):
|
||||
self.assertEqual(self.read_through("-m32", program=READV_DESTINATION_CHECKS), "ok\n")
|
||||
|
||||
def test_an_event_node_rejects_joydev_requests_so_sdl_reads_its_id(self):
|
||||
library, probe = self.build("-m64", PROBE, "probe")
|
||||
hooks, _ = self.ring()
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -43,6 +44,17 @@ class ReadConfigMappingTest(unittest.TestCase):
|
||||
|
||||
|
||||
class GameEnvironmentTest(unittest.TestCase):
|
||||
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
|
||||
from unittest.mock import patch
|
||||
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
|
||||
calls = []
|
||||
with patch.dict(os.environ, {}, clear=True), patch('sys.argv', ['droiddeck-game-env', '/stock', 'run']), \
|
||||
patch('runpy.run_path', side_effect=error), patch('os.execvpe', side_effect=lambda *args: calls.append(args)), \
|
||||
patch.dict(MODULE['main'].__globals__, load_sync=lambda: None, select_sync=lambda command, env, sync: (command, env)):
|
||||
MODULE['main']()
|
||||
self.assertEqual(calls[0][0:2], ('/stock', ['/stock', 'run']))
|
||||
|
||||
|
||||
def test_directaudio_capture_follows_the_session_microphone_setting(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
@@ -83,6 +95,73 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(calls[0][0][1], str(root))
|
||||
self.assertEqual(calls[0][1]["DROIDDECK_SEED_SCRIPTS"], str(script))
|
||||
|
||||
SCRIPT = ('"evaluatorscript" { "0" { "appid" "228980" "compat_installscript" { "run process" { '
|
||||
'"x64 14.28.29334.0" { "hasrunkey" "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019" '
|
||||
'"process 1" "%INSTALLDIR%\\\\x64.cmd" "requirement_os" { "Is64BitWindows" "1" } } '
|
||||
'"Setup" { "process 1" "%INSTALLDIR%\\\\setup.exe" } } } } }')
|
||||
REDIST = "[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019] 1\n\"x64 14.28.29334.0\"=dword:00000001\n"
|
||||
SETUP = "[Software\\\\Valve\\\\Steam\\\\Apps\\\\228980] 1\n\"Setup\"=dword:00000001\n"
|
||||
|
||||
def test_install_script_run_keys_default_to_the_app_key(self):
|
||||
keys = MODULE["run_keys"](MODULE["read_vdf"](self.SCRIPT))
|
||||
self.assertEqual(keys, {
|
||||
("hkey_local_machine\\software\\valve\\steam\\apps\\commonredist\\vcredist\\2019", "x64 14.28.29334.0"),
|
||||
("hkey_local_machine\\software\\valve\\steam\\apps\\228980", "setup"),
|
||||
})
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["read_vdf"]('"a" { "b" }')
|
||||
|
||||
def test_install_scripts_count_as_done_only_when_recorded_and_still_marked(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
script = Path(tmp) / "evaluatorscript_1.vdf"
|
||||
script.write_text(self.SCRIPT)
|
||||
prefix = Path(tmp) / "compat/pfx"
|
||||
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
|
||||
done = MODULE["install_scripts_done"]
|
||||
self.assertFalse(done([str(script)], env))
|
||||
prefix.mkdir(parents=True)
|
||||
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
(prefix / "system.reg").write_text(self.REDIST)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||
self.assertTrue(done([str(script)], env))
|
||||
script.write_text(self.SCRIPT.replace("x64.cmd", "x64-update.cmd"))
|
||||
self.assertFalse(done([str(script)], env))
|
||||
script.write_text('"InstallScript" { "Registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "%INSTALLDIR%" } } } }')
|
||||
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
|
||||
def test_the_evaluator_is_skipped_once_it_finished_the_same_scripts(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "legacycompat").mkdir()
|
||||
evaluator = root / "legacycompat/iscriptevaluator.exe"
|
||||
evaluator.write_bytes(b"evaluator")
|
||||
script = root / "legacycompat/evaluatorscript_1.vdf"
|
||||
prefix = root / "compatdata/1/pfx"
|
||||
prefix.mkdir(parents=True)
|
||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||
runs = root / "runs"
|
||||
proton = root / "proton"
|
||||
proton.write_text("#!/bin/sh\necho run >> %s\nexit ${EXIT_CODE:-0}\n" % shlex.quote(str(runs)))
|
||||
proton.chmod(0o755)
|
||||
|
||||
def evaluate(exit_code="0"):
|
||||
script.write_text(self.SCRIPT if exit_code != "changed" else self.SCRIPT.replace("setup.exe", "setup-update.exe"))
|
||||
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_CLIENT_INSTALL_PATH=str(root),
|
||||
STEAM_COMPAT_DATA_PATH=str(prefix.parent), EXIT_CODE="0" if exit_code == "changed" else exit_code)
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "run",
|
||||
str(evaluator), "legacycompat\\evaluatorscript_1.vdf"],
|
||||
env=env, text=True, capture_output=True)
|
||||
return result.returncode, len(runs.read_text().splitlines()) if runs.exists() else 0
|
||||
|
||||
self.assertEqual(evaluate("3"), (3, 1))
|
||||
self.assertFalse((prefix / ".droiddeck-install-scripts").exists())
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate("changed"), (0, 3))
|
||||
|
||||
def test_profile_precedence_and_unset(self):
|
||||
env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"}
|
||||
config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}}
|
||||
@@ -90,6 +169,17 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(env["REMOVE"], "inherited")
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
|
||||
|
||||
def test_games_get_their_own_turnip_debug_and_a_game_profile_still_wins(self):
|
||||
gpu = MODULE["game_gpu"]
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "KEEP": "1"}), {"KEEP": "1"})
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "sysmem"}), {"TU_DEBUG": "sysmem"})
|
||||
self.assertEqual(gpu({"DROIDDECK_GAME_TU_DEBUG": "nolrz"}), {"TU_DEBUG": "nolrz"})
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem"}), {"TU_DEBUG": "sysmem"})
|
||||
config = {"version": 1, "games": {"42": {"TU_DEBUG": "sysmem"}}}
|
||||
env = gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""})
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
|
||||
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
|
||||
|
||||
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
|
||||
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
|
||||
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
|
||||
@@ -179,6 +269,75 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(other / "Other.exe").touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
|
||||
|
||||
def test_easy_anti_cheat_games_start_offline_only_when_opted_in(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
game = Path(tmp) / "ELDEN RING/Game"
|
||||
(game / "EasyAntiCheat").mkdir(parents=True)
|
||||
for name in ("start_protected_game.exe", "eldenring.exe"):
|
||||
(game / name).touch()
|
||||
(game / "EasyAntiCheat/settings.json").write_text('\ufeff{ "executable" : "eldenring.exe" }', encoding="utf-8")
|
||||
command = ["proton", "waitforexitandrun", str(game / "start_protected_game.exe"), "-arg"]
|
||||
offline = MODULE["offline_without_anticheat"]
|
||||
self.assertEqual(offline(command, {}), command)
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "0"}), command)
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}),
|
||||
["proton", "waitforexitandrun", str(game / "eldenring.exe"), "-arg"])
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "../../escape.exe" }')
|
||||
(Path(tmp) / "escape.exe").touch()
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "missing.exe" }')
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "link/escape.exe" }')
|
||||
outside = Path(tmp) / "outside"
|
||||
outside.mkdir()
|
||||
(outside / "escape.exe").touch()
|
||||
(game / "link").symlink_to(outside, target_is_directory=True)
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "eldenring.exe" }')
|
||||
plain = ["proton", "waitforexitandrun", str(game / "eldenring.exe")]
|
||||
self.assertEqual(offline(plain, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), plain)
|
||||
self.assertEqual(offline(["proton", "run", command[2]],
|
||||
{"DROIDDECK_ANTICHEAT_OFFLINE": "1"}),
|
||||
["proton", "run", command[2]])
|
||||
|
||||
def test_easy_anti_cheat_forwarding_through_entrypoint(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
game = home / "ELDEN RING/Game"
|
||||
(game / "EasyAntiCheat").mkdir(parents=True)
|
||||
bootstrapper = game / "start_protected_game.exe"
|
||||
target = game / "eldenring.exe"
|
||||
bootstrapper.touch()
|
||||
target.touch()
|
||||
(game / "EasyAntiCheat/settings.json").write_text(json.dumps({"executable": "eldenring.exe"}))
|
||||
proton = home / "fake-proton"
|
||||
proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n")
|
||||
proton.chmod(0o755)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
|
||||
env.pop("DROIDDECK_ANTICHEAT_OFFLINE", None)
|
||||
for setting, expected in (("1", target), ("0", bootstrapper), (None, bootstrapper)):
|
||||
with self.subTest(setting=setting):
|
||||
values = {} if setting is None else {"DROIDDECK_ANTICHEAT_OFFLINE": setting}
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": values}}))
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"),
|
||||
str(proton), "waitforexitandrun", str(bootstrapper), "-arg"],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(json.loads(result.stdout.strip()),
|
||||
["waitforexitandrun", str(expected), "-arg"])
|
||||
|
||||
def test_deep_rock_gdk_avoids_the_raytracing_pipeline_crash(self):
|
||||
game = "/game/FSD/Binaries/WinGDK/FSD-WinGDK-Shipping.exe"
|
||||
env, extra, notes = MODULE["engine_fixes"](game, [])
|
||||
self.assertEqual(extra, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"])
|
||||
self.assertEqual(env, {})
|
||||
self.assertTrue(notes)
|
||||
for choice in ("-raytracing", "-noraytracing"):
|
||||
self.assertEqual(MODULE["engine_fixes"](game, [choice]), ({}, [], []))
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/FSD-Win64-Shipping.exe", []), ({}, [], []))
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Other-WinGDK-Shipping.exe", []), ({}, [], []))
|
||||
|
||||
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
|
||||
@@ -434,6 +593,8 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(changes, {"42": COMPAT["TOOL"]})
|
||||
|
||||
def test_both_proton_wrappers_call_environment_launcher(self):
|
||||
self.assertIn('bl_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
|
||||
self.assertIn('bl_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
|
||||
@@ -849,12 +1010,15 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
(self.windows / folder).mkdir(parents=True)
|
||||
self.reg = self.compat / "pfx/user.reg"
|
||||
|
||||
def run_setup(self, verb="waitforexitandrun"):
|
||||
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
|
||||
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat))
|
||||
def run_setup(self, verb="waitforexitandrun", target="game.exe", cwd=None):
|
||||
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1" "$3"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
|
||||
steam = self.compat.parent / "Steam"
|
||||
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat),
|
||||
STEAM_COMPAT_CLIENT_INSTALL_PATH=str(steam))
|
||||
env.pop("WINEDLLPATH", None)
|
||||
env.pop("WINE_AUDIO_DRIVER", None)
|
||||
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb], env=env, capture_output=True, text=True, check=True)
|
||||
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb, target], cwd=cwd, env=env,
|
||||
capture_output=True, text=True, check=True)
|
||||
|
||||
def audio_values(self):
|
||||
found, current = [], None
|
||||
@@ -869,6 +1033,35 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
path = self.windows / folder / "winedirectaudio.drv"
|
||||
return os.readlink(path) if path.is_symlink() else None
|
||||
|
||||
def test_steam_installscript_evaluator_does_not_change_prefix_audio(self):
|
||||
legacycompat = self.compat.parent / "Steam/legacycompat"
|
||||
legacycompat.mkdir(parents=True)
|
||||
(legacycompat / "iscriptevaluator.exe").write_bytes(b"Steam install-script evaluator")
|
||||
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
|
||||
|
||||
result = self.run_setup(target="iscriptevaluator.exe", cwd=legacycompat)
|
||||
|
||||
self.assertIn("DirectAudio skipped for Steam's install-script evaluator", result.stderr)
|
||||
self.assertIn("WINEDLLPATH=\n", result.stdout)
|
||||
self.assertIn("WINE_AUDIO_DRIVER=\n", result.stdout)
|
||||
self.assertEqual(self.reg.read_text(), "WINE REGISTRY Version 2\n\n#arch=win64\n")
|
||||
self.assertIsNone(self.link("system32"))
|
||||
self.assertIsNone(self.link("syswow64"))
|
||||
|
||||
def test_same_basename_outside_steam_legacycompat_keeps_normal_setup(self):
|
||||
legacycompat = self.compat.parent / "Steam/legacycompat"
|
||||
legacycompat.mkdir(parents=True)
|
||||
(legacycompat / "iscriptevaluator.exe").write_bytes(b"Steam install-script evaluator")
|
||||
other = self.compat.parent / "other"
|
||||
other.mkdir()
|
||||
(other / "iscriptevaluator.exe").write_bytes(b"unrelated executable")
|
||||
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
|
||||
|
||||
result = self.run_setup(target="iscriptevaluator.exe", cwd=other)
|
||||
|
||||
self.assertIn("DirectAudio selected", result.stderr)
|
||||
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
|
||||
self.assertEqual(self.audio_values(), [("[Software\\\\Wine\\\\Drivers]", '"Audio"="directaudio,pulse"')])
|
||||
def test_non_launch_verbs_preserve_audio_configuration(self):
|
||||
for verb in ("getcompatpath", "getnativepath", "destroyprefix"):
|
||||
with self.subTest(verb=verb):
|
||||
|
||||
@@ -77,6 +77,7 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
GLib.Variant("(ss)", (IFACE, "PreparingForSleep")))[0]
|
||||
|
||||
def suspend(self):
|
||||
(self.dir / "steam-sleep").unlink(missing_ok=True)
|
||||
self.call(IFACE, "Suspend", GLib.Variant("(b)", (True,)))
|
||||
self.wait_for(lambda: (self.dir / "steam-sleep").exists())
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
@@ -239,6 +240,7 @@ class FakeAgentCase(unittest.TestCase):
|
||||
suspend = SleepHandshakeTest.suspend
|
||||
state = SleepHandshakeTest.state
|
||||
request_wake = SleepHandshakeTest.request_wake
|
||||
request_native = SleepHandshakeTest.request_native
|
||||
|
||||
def asked(self):
|
||||
path = self.dir / "agent-calls"
|
||||
@@ -264,7 +266,7 @@ class AwakeSteamTest(FakeAgentCase):
|
||||
self.state(token, "paused")
|
||||
self.request_wake()
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertEqual([], self.asked())
|
||||
self.assertNotIn("--steam-asleep", self.asked())
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
@@ -276,6 +278,53 @@ class AsleepSteamTest(FakeAgentCase):
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertEqual(["--steam-asleep"], self.asked())
|
||||
|
||||
def test_steam_sleep_request_holds_idle_sleep_before_the_host_pauses(self):
|
||||
token = self.suspend()
|
||||
self.assertEqual(["--steam-idle-inhibit", "on"], self.asked())
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.wait_for(lambda: self.asked()[-1:] == ["off"])
|
||||
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
|
||||
"--steam-idle-inhibit", "off"], self.asked())
|
||||
|
||||
def test_idle_pause_holds_idle_sleep_without_a_sleep_wake_pair(self):
|
||||
token = self.request_native("2" * 32 + " idle").split()[0]
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.assertEqual(token, (self.dir / "steam-native-ready").read_text().strip())
|
||||
self.assertEqual(["--steam-idle-inhibit", "on"], self.asked())
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.asked()[-1:] == ["off"])
|
||||
self.assertEqual([], self.signals)
|
||||
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
|
||||
"--steam-idle-inhibit", "off"], self.asked())
|
||||
|
||||
def test_a_failed_release_is_tried_again(self):
|
||||
failed = self.dir / "release-failed"
|
||||
(self.dir / "bin/droiddeck-agent").write_text(
|
||||
"#!/bin/sh\necho \"$@\" >> \"%s\"\n"
|
||||
"if [ \"$2\" = off ] && [ ! -e \"%s\" ]; then : > \"%s\"; exit 1; fi\nexit 0\n"
|
||||
% (self.dir / "agent-calls", failed, failed))
|
||||
token = self.suspend()
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.asked().count("off") == 2)
|
||||
time.sleep(2.5)
|
||||
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
|
||||
"--steam-idle-inhibit", "off", "--steam-idle-inhibit", "off"], self.asked())
|
||||
|
||||
def test_a_hold_steam_did_not_confirm_is_still_released(self):
|
||||
(self.dir / "bin/droiddeck-agent").write_text(
|
||||
"#!/bin/sh\necho \"$@\" >> \"%s\"\n[ \"$2\" = on ] && exit 1\nexit 0\n" % (self.dir / "agent-calls"))
|
||||
token = self.suspend()
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.wait_for(lambda: self.asked()[-1:] == ["off"])
|
||||
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
|
||||
"--steam-idle-inhibit", "off"], self.asked())
|
||||
|
||||
|
||||
class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
ARGS = ["--with-netmanager"]
|
||||
|
||||
@@ -7,6 +7,7 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
|
||||
|
||||
# Opens each "<dirfd>\t<flags>\t<path>" case with openat2(RESOLVE_IN_ROOT) as FEX does: first through the kernel's own
|
||||
# openat2 on argv[1] when it has one, then, with openat2 failing ENOSYS as under proot, through the preload on argv[2].
|
||||
@@ -84,6 +85,62 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
"""
|
||||
|
||||
COUNTER = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int opens, stats, links;
|
||||
|
||||
int openat(int dirfd, const char *path, int flags, ...) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
mode_t mode = va_arg(args, int);
|
||||
va_end(args);
|
||||
opens++;
|
||||
return ((int (*)(int, const char *, int, ...))dlsym(RTLD_NEXT, "openat"))(dirfd, path, flags, mode);
|
||||
}
|
||||
|
||||
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
|
||||
stats++;
|
||||
return ((int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat"))(dirfd, path, st, flags);
|
||||
}
|
||||
|
||||
int fstatat64(int dirfd, const char *path, struct stat64 *st, int flags) {
|
||||
stats++;
|
||||
return ((int (*)(int, const char *, struct stat64 *, int))dlsym(RTLD_NEXT, "fstatat64"))(dirfd, path, st, flags);
|
||||
}
|
||||
|
||||
ssize_t readlinkat(int dirfd, const char *path, char *buf, size_t size) {
|
||||
links++;
|
||||
return ((ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"))(dirfd, path, buf, size);
|
||||
}
|
||||
|
||||
__attribute__((destructor)) static void report(void) {
|
||||
fprintf(stderr, "calls %d %d %d\n", opens, stats, links);
|
||||
}
|
||||
"""
|
||||
|
||||
RAW_OPEN = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char text[16] = "";
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, argv[1], O_RDONLY | O_CLOEXEC, 0);
|
||||
if (fd < 0 || read((int)fd, text, sizeof(text) - 1) < 0) return 1;
|
||||
printf("%s\n", text);
|
||||
return syscall(SYS_openat, AT_FDCWD, argv[2], O_RDONLY | O_CLOEXEC, 0) == -1 ? 0 : 1;
|
||||
}
|
||||
"""
|
||||
|
||||
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.
|
||||
@@ -117,8 +174,17 @@ CASES = [
|
||||
("o", os.O_RDONLY, "proc/self/status", "proc"),
|
||||
]
|
||||
|
||||
# Only the preload: an absolute link to a path missing in the tree but present outside it, as droiddeck-fex's rootfs has.
|
||||
HOST_CASES = [
|
||||
("r", os.O_RDONLY, "lib/x86_64-linux-gnu/libbar.so.2", "host:libbar.so.2"),
|
||||
("r", os.O_RDONLY, "hostdir/sub/data", "host:sub/data"),
|
||||
("r", os.O_RDONLY | os.O_DIRECTORY, "hostdir/sub", "host:sub"),
|
||||
("r", os.O_RDONLY, "etc/alternatives/hn", "etc/hostname"),
|
||||
("r", os.O_RDONLY, "hostdir/missing", "ENOENT"),
|
||||
]
|
||||
|
||||
def make_tree(root):
|
||||
|
||||
def make_tree(root, outside):
|
||||
for folder in ("usr/lib/x86_64-linux-gnu", "etc/alternatives", "loop", "chain"):
|
||||
(root / folder).mkdir(parents=True)
|
||||
(root / "usr/lib/x86_64-linux-gnu/libfoo.so.1.2").write_text("x86")
|
||||
@@ -129,16 +195,24 @@ def make_tree(root):
|
||||
"etc/alternatives/hn": "/etc/hostname", "etc/escape": "../../../../../../etc/hostname", "loop/a": "b",
|
||||
"loop/b": "a", "dirlink": "/usr", "rootlink": "/", "dangling": "/usr/newfile"}
|
||||
links.update({"chain/l%d" % i: ("l%d" % (i + 1) if i < 41 else "end") for i in range(1, 42)})
|
||||
links.update({"usr/lib/x86_64-linux-gnu/libbar.so.2": str(outside / "libbar.so.2"), "hostdir": str(outside)})
|
||||
for link, target in links.items():
|
||||
os.symlink(target, root / link)
|
||||
|
||||
|
||||
def labels(lines, root):
|
||||
def make_outside(outside):
|
||||
(outside / "sub").mkdir(parents=True)
|
||||
(outside / "libbar.so.2").write_text("host")
|
||||
(outside / "sub/data").write_text("host")
|
||||
|
||||
|
||||
def labels(lines, root, outside):
|
||||
inodes = {(os.lstat(root).st_dev, os.lstat(root).st_ino): "."}
|
||||
for folder, dirs, files in os.walk(root):
|
||||
for name in dirs + files:
|
||||
st = os.lstat(os.path.join(folder, name))
|
||||
inodes[(st.st_dev, st.st_ino)] = os.path.relpath(os.path.join(folder, name), root)
|
||||
for base, prefix in ((root, ""), (outside, "host:")):
|
||||
for folder, dirs, files in os.walk(base):
|
||||
for name in dirs + files:
|
||||
st = os.lstat(os.path.join(folder, name))
|
||||
inodes[(st.st_dev, st.st_ino)] = prefix + os.path.relpath(os.path.join(folder, name), base)
|
||||
out = []
|
||||
for line in lines:
|
||||
kind, *values = line.split()
|
||||
@@ -161,16 +235,50 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
|
||||
cls.trees = (cls.tmp / "kernel", cls.tmp / "preload")
|
||||
cls.outside = cls.tmp / "outside"
|
||||
make_outside(cls.outside)
|
||||
for tree in cls.trees:
|
||||
make_tree(tree)
|
||||
cases = "".join("%s\t%d\t%s\n" % case[:3] for case in CASES)
|
||||
make_tree(tree, cls.outside)
|
||||
every = CASES + HOST_CASES
|
||||
cases = "".join("%s\t%d\t%s\n" % case[:3] for case in every)
|
||||
result = subprocess.run([str(cls.tmp / "openat2"), *map(str, cls.trees)], input=cases, capture_output=True, text=True,
|
||||
env=dict(os.environ, LD_PRELOAD=str(cls.lib)), timeout=60)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(result.stdout + result.stderr)
|
||||
lines = result.stdout.splitlines()
|
||||
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0]) if lines[0] == "kernel" else None
|
||||
cls.preload = labels(lines[-len(CASES):], cls.trees[1])
|
||||
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0], cls.outside) if lines[0] == "kernel" else None
|
||||
cls.preload = labels(lines[-len(every):], cls.trees[1], cls.outside)
|
||||
counter = cls.tmp / "counter.c"
|
||||
counter.write_text(COUNTER)
|
||||
(cls.tmp / "fp").mkdir()
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o", str(cls.tmp / "fp/libblfastpath.so"),
|
||||
str(counter), "-ldl"], check=True)
|
||||
tree = cls.tmp / "counted"
|
||||
make_tree(tree, cls.outside)
|
||||
counted = subprocess.run([str(cls.tmp / "openat2"), str(tree), str(tree)], input=cases, capture_output=True,
|
||||
text=True, env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")),
|
||||
timeout=60)
|
||||
if counted.returncode != 0:
|
||||
raise AssertionError(counted.stdout + counted.stderr)
|
||||
cls.counted = labels(counted.stdout.splitlines()[-len(every):], tree, cls.outside)
|
||||
cls.calls = [int(n) for n in counted.stderr.split("calls ")[-1].split()]
|
||||
raw = cls.tmp / "raw_open.c"
|
||||
raw.write_text(RAW_OPEN)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "raw_open"), str(raw)], check=True)
|
||||
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")))
|
||||
(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)
|
||||
shutil.copy(cls.tmp / "raw_open", cls.tmp / "FEX")
|
||||
try:
|
||||
cls.fex = subprocess.run([str(cls.tmp / "FEX"), str(tree / "etc/hostname"), str(tree / "missing")],
|
||||
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 = None
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
@@ -181,6 +289,24 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
self.assertEqual(got, case[3], case)
|
||||
self.assertTrue((self.trees[1] / "usr/newfile").exists())
|
||||
|
||||
def test_preload_finishes_a_link_to_a_path_only_outside_the_root_there(self):
|
||||
for case, got in zip(HOST_CASES, self.preload[len(CASES):]):
|
||||
self.assertEqual(got, case[3], case)
|
||||
|
||||
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)
|
||||
|
||||
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"])
|
||||
|
||||
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_kernel_agrees(self):
|
||||
if self.kernel is None:
|
||||
self.skipTest("this kernel or sandbox has no openat2")
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-pipewire'
|
||||
|
||||
|
||||
class PipeWireHelperTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.lib = self.root / 'lib'
|
||||
self.runtime = self.root / 'run'
|
||||
self.lib.mkdir()
|
||||
self.runtime.mkdir()
|
||||
self.bundle = self.lib / 'droiddeck-pipewire.tzst'
|
||||
self.dir = self.lib / 'droiddeck-pipewire'
|
||||
text = SOURCE.read_text().replace('/usr/local/lib/droiddeck-pipewire', str(self.dir))
|
||||
self.helper = self.root / 'droiddeck-pipewire'
|
||||
self.helper.write_text(text)
|
||||
self.environment = dict(os.environ, XDG_RUNTIME_DIR=str(self.runtime))
|
||||
|
||||
def pack(self, daemon_body):
|
||||
tree = self.root / 'tree'
|
||||
for name, body in (('pipewire', daemon_body), ('wireplumber', 'exec sleep 30')):
|
||||
path = tree / 'bin' / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('#!/bin/sh\n' + body + '\n')
|
||||
path.chmod(0o755)
|
||||
tar = self.root / 'bundle.tar'
|
||||
with tarfile.open(tar, 'w') as archive:
|
||||
archive.add(tree, arcname='.')
|
||||
subprocess.run(['zstd', '-q', '-f', str(tar), '-o', str(self.bundle)], check=True)
|
||||
|
||||
def run_helper(self, *args):
|
||||
with tempfile.TemporaryFile('w+') as out, tempfile.TemporaryFile('w+') as err:
|
||||
done = subprocess.run(['sh', str(self.helper), *args], env=self.environment, stdout=out, stderr=err,
|
||||
text=True, timeout=15)
|
||||
out.seek(0)
|
||||
err.seek(0)
|
||||
return subprocess.CompletedProcess(done.args, done.returncode, out.read(), err.read())
|
||||
|
||||
def tearDown(self):
|
||||
self.run_helper('stop')
|
||||
|
||||
def test_env_points_clients_at_the_bundle(self):
|
||||
out = self.run_helper('env').stdout
|
||||
for part in ('PIPEWIRE_CONFIG_DIR=%s/share/pipewire', 'PIPEWIRE_MODULE_DIR=%s/lib/pipewire-0.3',
|
||||
'SPA_PLUGIN_DIR=%s/lib/spa-0.2'):
|
||||
self.assertIn(part % self.dir, out)
|
||||
|
||||
def test_start_waits_for_the_socket_and_stop_ends_both_daemons(self):
|
||||
socket = self.runtime / 'pipewire-0'
|
||||
self.pack('python3 -c "import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); '
|
||||
'import time; time.sleep(30)" "$XDG_RUNTIME_DIR/pipewire-0"')
|
||||
result = self.run_helper('start')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue(socket.is_socket())
|
||||
pids = (self.runtime / 'droiddeck-pipewire/pids').read_text().split()
|
||||
self.assertEqual(len(pids), 2)
|
||||
self.run_helper('stop')
|
||||
for pid in pids:
|
||||
subprocess.run(['sh', '-c', 'for i in 1 2 3 4 5 6 7 8 9 10; do kill -0 %s 2>/dev/null || exit 0; '
|
||||
'sleep 0.1; done; exit 1' % pid], check=True)
|
||||
|
||||
def test_start_fails_cleanly_when_pipewire_never_listens(self):
|
||||
self.pack('exec sleep 30')
|
||||
result = self.run_helper('start')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('did not open', result.stderr)
|
||||
self.assertFalse((self.runtime / 'droiddeck-pipewire/pids').exists())
|
||||
|
||||
def test_unchanged_bundle_is_not_unpacked_again(self):
|
||||
self.pack('exec sleep 30')
|
||||
self.run_helper('start')
|
||||
marker = self.dir / 'kept'
|
||||
marker.write_text('x')
|
||||
self.run_helper('start')
|
||||
self.assertTrue(marker.exists())
|
||||
self.pack('exec sleep 31')
|
||||
self.run_helper('start')
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -29,6 +29,32 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
self.source.parent.mkdir(parents=True)
|
||||
self.source.write_text('current source')
|
||||
self.audio(['pactl', 'modules/arm64/module-aaudio-sink.so', 'modules/arm64/module-directaudio-native-sink.so'])
|
||||
self.packs()
|
||||
|
||||
def pack(self, name, files):
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w') as archive:
|
||||
for rel, content in files.items():
|
||||
entry = tarfile.TarInfo(rel)
|
||||
entry.size = len(content)
|
||||
archive.addfile(entry, io.BytesIO(content))
|
||||
path = self.root / runtime.PACKS / (name + '.tar.zst')
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(), capture_output=True, check=True).stdout)
|
||||
|
||||
def packs(self):
|
||||
self.pack('tracking', {library.rsplit('/', 1)[1]: b'library' for library in runtime.PACKED_LIBRARIES})
|
||||
proot = {}
|
||||
for name, (pack, rel) in runtime.PACKED_FILES.items():
|
||||
proot[rel] = (self.root / runtime.outputs(self.root)[name]).read_bytes()
|
||||
self.pack('proot', proot)
|
||||
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()})
|
||||
|
||||
@staticmethod
|
||||
def in_apk(name):
|
||||
return name not in runtime.PACKED_FILES and not any(name.startswith(prefix) for prefix in runtime.PACKED)
|
||||
|
||||
def audio(self, names):
|
||||
stream = io.BytesIO()
|
||||
@@ -40,6 +66,11 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
path = self.root / 'app/build/prepared-assets/pulseaudio.tzst'
|
||||
path.write_bytes(subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(), capture_output=True, check=True).stdout)
|
||||
|
||||
def test_an_apk_still_carrying_proot_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {'lib/arm64-v8a/libproot.so': b'prepared runtime'})
|
||||
with self.assertRaisesRegex(ValueError, 'proot pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_missing_proot_cannot_be_attested(self):
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'libproot.so'):
|
||||
@@ -82,6 +113,8 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'old.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if not self.in_apk(name):
|
||||
continue
|
||||
content = b'stale' if name == 'assets/linuxfs/libssbs.so' else (self.root / output['path']).read_bytes()
|
||||
package.writestr(name, content)
|
||||
with self.assertRaisesRegex(ValueError, 'stale runtime input'):
|
||||
@@ -93,9 +126,43 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'current.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
if self.in_apk(name):
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def current_apk(self, path, extra=None):
|
||||
runtime.record(self.root)
|
||||
data = runtime.verify(self.root)
|
||||
with ZipFile(path, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if self.in_apk(name):
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
for name, content in (extra or {}).items():
|
||||
package.writestr(name, content)
|
||||
return path
|
||||
|
||||
def test_an_apk_still_carrying_a_packed_tree_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {'assets/linuxfs/usr/local/lib/droiddeck-xbox/xodus-cli': b'prepared runtime'})
|
||||
with self.assertRaisesRegex(ValueError, 'xbox pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_an_apk_still_carrying_tracking_libraries_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {runtime.PACKED_LIBRARIES[0]: b'library'})
|
||||
with self.assertRaisesRegex(ValueError, 'tracking pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_a_stale_pack_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'current.apk')
|
||||
self.pack('comet', {'comet': b'old build', 'version': b'old'})
|
||||
with self.assertRaisesRegex(ValueError, 'comet is missing or has a stale'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_a_missing_pack_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'current.apk')
|
||||
(self.root / runtime.PACKS / 'xbox.tar.zst').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'Missing add-on pack xbox'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_windows_manifest_matches_portable_apk_paths(self):
|
||||
path_type = type(self.root)
|
||||
original_relative_to = path_type.relative_to
|
||||
@@ -114,6 +181,8 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'portable.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if not self.in_apk(name):
|
||||
continue
|
||||
self.assertNotIn('\\', name)
|
||||
self.assertNotIn('\\', output['path'])
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
@@ -125,6 +194,8 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'expanded.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if not self.in_apk(name):
|
||||
continue
|
||||
content = (self.root / output['path']).read_bytes()
|
||||
if name.endswith('.gzip'):
|
||||
name = name.removesuffix('.gzip')
|
||||
|
||||
@@ -155,6 +155,26 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_an_unchanged_registry_is_not_read_again(self):
|
||||
self.game()
|
||||
self.run_seed()
|
||||
self.run_seed()
|
||||
shim = self.tmp / "bin"
|
||||
shim.mkdir()
|
||||
log = self.tmp / "awk.log"
|
||||
(shim / "awk").write_text('#!/bin/sh\nprintf "%%s\\n" "$*" >> "%s"\nexec %s "$@"\n' % (log, shutil.which("awk")))
|
||||
(shim / "awk").chmod(0o755)
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
|
||||
once = self.reg.read_text()
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(once, self.reg.read_text())
|
||||
self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "")
|
||||
replaced = self.reg.with_name("system.reg.new")
|
||||
replaced.write_text("WINE REGISTRY Version 2\n")
|
||||
os.replace(replaced, self.reg)
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
|
||||
|
||||
def test_the_prefix_date_is_kept(self):
|
||||
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
|
||||
self.run_seed()
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
|
||||
|
||||
|
||||
def target_case():
|
||||
match = re.search(r"^ case \$\{target,,\} in\n.*?^ esac\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0)
|
||||
|
||||
|
||||
class SessionAppImageTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
self.image = self.dir / "rpcs3.AppImage"
|
||||
self.image.write_bytes(b"\x7fELF")
|
||||
self.uruntime = self.dir / "uruntime"
|
||||
self.uruntime.write_text("#!/bin/sh\n")
|
||||
self.uruntime.chmod(0o755)
|
||||
|
||||
def launch(self, fex=()):
|
||||
script = ("set -u\n"
|
||||
"run_program() { printf '%%s\\n' \"TARGET=${TARGET_APPIMAGE:-} EXTRACT=${APPIMAGE_EXTRACT_AND_RUN:-}\" \"$@\"; exit 0; }\n"
|
||||
"target=%s\nfex=(%s)\nset -- --no-gui\n" % (self.image, " ".join(fex))
|
||||
+ target_case().replace(URUNTIME, str(self.uruntime)))
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN")}
|
||||
return subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30).stdout.splitlines()
|
||||
|
||||
def test_an_arm64_image_runs_through_the_shipped_runtime(self):
|
||||
self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, str(self.uruntime), "--no-gui"], self.launch())
|
||||
|
||||
def test_without_the_shipped_runtime_the_image_runs_itself(self):
|
||||
self.uruntime.unlink()
|
||||
self.assertEqual(["TARGET= EXTRACT=1", str(self.image), "--no-gui"], self.launch())
|
||||
|
||||
def test_an_x86_image_still_starts_under_fex(self):
|
||||
fex = ("/usr/local/bin/droiddeck-fex", "run", "--mode", "on", "--")
|
||||
self.assertEqual(["TARGET= EXTRACT=1", *fex, str(self.image), "--no-gui"], self.launch(fex))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
def run_case():
|
||||
return re.search(r"^ run\)\n.*?^ ;;\n", SESSION.read_text(), re.M | re.S).group(0)
|
||||
|
||||
|
||||
def steam_display():
|
||||
return re.search(r"^ steam\)\n(.*?)^ steam_x64=0\n", SESSION.read_text(), re.M | re.S).group(1)
|
||||
|
||||
|
||||
class SessionRunDisplayTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
self.target = self.dir / "target.sh"
|
||||
self.target.write_text("printf '%s\\n' \"${WAYLAND_DISPLAY-unset}\" \"${XDG_SESSION_TYPE-unset}\""
|
||||
" > \"$1\"\n")
|
||||
|
||||
def display(self, **env):
|
||||
base = {k: v for k, v in os.environ.items()
|
||||
if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE",
|
||||
"BL_LAUNCH_DIR")}
|
||||
seen = self.dir / "seen"
|
||||
script = ("program_cores() { :; }\nmode=run\ncase $mode in\n" + run_case() + "esac\n"
|
||||
+ "echo unreachable\n")
|
||||
run = subprocess.run(["bash", "-c", script, "droiddeck-session", str(self.target), str(seen)],
|
||||
env={**base, **env}, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, run.returncode, run.stderr)
|
||||
self.assertNotIn("unreachable", run.stdout)
|
||||
return seen.read_text().splitlines()
|
||||
|
||||
def test_programs_under_gamescope_cannot_reach_a_wayland_server(self):
|
||||
self.assertEqual(["", "x11"], self.display(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
|
||||
WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
def test_without_gamescope_the_display_is_left_alone(self):
|
||||
self.assertEqual(["wayland-0", "wayland"], self.display(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
def steam_env(self, **env):
|
||||
base = {k: v for k, v in os.environ.items()
|
||||
if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE")}
|
||||
script = steam_display() + ('printf "%s\\n" "${WAYLAND_DISPLAY-unset}" "${XDG_SESSION_TYPE-unset}"'
|
||||
' "${MOZ_SHM_NO_SEALS-unset}" "${MOZ_DISABLE_CONTENT_SANDBOX-unset}"\n')
|
||||
run = subprocess.run(["bash", "-c", script], env={**base, **env}, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, run.returncode, run.stderr)
|
||||
return run.stdout.splitlines()
|
||||
|
||||
def test_steam_games_under_gamescope_cannot_reach_a_wayland_server(self):
|
||||
self.assertEqual(["", "x11", "1", "1"], self.steam_env(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
|
||||
WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
def test_steam_without_gamescope_keeps_the_display(self):
|
||||
self.assertEqual(["wayland-0", "wayland", "1", "1"],
|
||||
self.steam_env(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,82 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
SOURCE = SESSION.read_text()
|
||||
ARM64_BRANCH = SOURCE.index(' else\n step "checking the Steam client (first run')
|
||||
START = SOURCE.index(' droiddeck-steam-install || steam_setup_failed $?\n', ARM64_BRANCH)
|
||||
END = SOURCE.index(' step "Steam client ready"\n', START)
|
||||
HELPER = re.search(r'^steam_setup_failed\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group()
|
||||
INSTALL_BLOCK = HELPER + textwrap.dedent(SOURCE[START:END])
|
||||
RUN_GAMESCOPE = re.search(r'^run_gamescope\(\) \(\n.*?^\)\n', SOURCE, re.M | re.S).group()
|
||||
MARKER = '== steam: the Steam client could not be set up'
|
||||
|
||||
|
||||
class SteamClientSetupFailureTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
|
||||
def installer(self, status):
|
||||
script = self.root / 'droiddeck-steam-install'
|
||||
script.write_text('#!/bin/bash\n'
|
||||
'echo "curl: (35) Recv failure: Connection reset by peer" >&2\n'
|
||||
'exit ' + str(status) + '\n')
|
||||
script.chmod(0o755)
|
||||
|
||||
def env(self, **extra):
|
||||
base = {k: v for k, v in os.environ.items() if k != 'BL_STEAM_EXIT_FILE'}
|
||||
return dict(base, PATH=str(self.root) + os.pathsep + os.environ['PATH'],
|
||||
XDG_RUNTIME_DIR=str(self.root), **extra)
|
||||
|
||||
def run_block(self, status, exit_file=None):
|
||||
self.installer(status)
|
||||
extra = {'BL_STEAM_EXIT_FILE': str(exit_file)} if exit_file else {}
|
||||
return subprocess.run(['bash', '-c', INSTALL_BLOCK + 'echo continued\n'], env=self.env(**extra),
|
||||
capture_output=True, text=True, timeout=10)
|
||||
|
||||
def test_failed_install_reports_its_status_in_the_exit_file(self):
|
||||
exit_file = self.root / 'exit'
|
||||
result = self.run_block(1, exit_file)
|
||||
self.assertEqual(1, result.returncode)
|
||||
self.assertIn(MARKER + ' (status 1)', result.stdout)
|
||||
self.assertNotIn('continued', result.stdout)
|
||||
self.assertEqual('1\n', exit_file.read_text())
|
||||
|
||||
def test_failed_install_outside_gamescope_still_exits_with_its_status(self):
|
||||
result = self.run_block(50)
|
||||
self.assertEqual(50, result.returncode)
|
||||
self.assertIn(MARKER + ' (status 50)', result.stdout)
|
||||
|
||||
def test_ready_client_continues_without_a_report(self):
|
||||
exit_file = self.root / 'exit'
|
||||
result = self.run_block(0, exit_file)
|
||||
self.assertEqual(0, result.returncode)
|
||||
self.assertIn('continued', result.stdout)
|
||||
self.assertNotIn(MARKER, result.stdout)
|
||||
self.assertFalse(exit_file.exists())
|
||||
|
||||
def test_failed_install_survives_successful_compositor_shutdown(self):
|
||||
self.installer(1)
|
||||
compositor = self.root / 'gamescope'
|
||||
compositor.write_text('#!/bin/bash\n"$@"\nexit 0\n')
|
||||
compositor.chmod(0o755)
|
||||
child = self.root / 'session-child'
|
||||
child.write_text('#!/bin/bash\n' + INSTALL_BLOCK + 'exit 0\n')
|
||||
child.chmod(0o755)
|
||||
result = subprocess.run(['bash', '-c', RUN_GAMESCOPE + '\nrun_gamescope "$@"', 'session', str(child)],
|
||||
env=self.env(), capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(1, result.returncode)
|
||||
self.assertIn(MARKER, result.stdout)
|
||||
self.assertEqual(list(self.root.glob('droiddeck-steam-exit.??????')), [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Requested Steam games are handed over as soon as the interface is up; a shortcut is handed over again only if it never took focus."""
|
||||
"""Retry a dropped shortcut without duplicating a launch that is still preparing its first window."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
@@ -48,14 +48,21 @@ class SteamColdLaunchTest(unittest.TestCase):
|
||||
sleep = self.bin / "sleep"
|
||||
sleep.write_text("#!/bin/sh\nprintf '%s\n' \"$@\" >> \"$SLEEP_ARGS\"\n")
|
||||
sleep.chmod(0o755)
|
||||
pgrep = self.bin / "pgrep"
|
||||
pgrep.write_text(
|
||||
"#!/bin/sh\n"
|
||||
"printf '%s\\n' \"$@\" > \"$HOME/pgrep-args\"\n"
|
||||
"n=$(cat \"$HOME/pgrep-count\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$HOME/pgrep-count\"\n"
|
||||
"[ \"$n\" -ge \"${RUNNING_AFTER:-999}\" ]\n")
|
||||
pgrep.chmod(0o755)
|
||||
self.block = LAUNCH_BLOCK.replace("/usr/local/bin/droiddeck-agent", str(agent))
|
||||
|
||||
def run_launch(self, target, focus="769", helper_status=0):
|
||||
def run_launch(self, target, focus="769", helper_status=0, running_after=999):
|
||||
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
|
||||
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
|
||||
AGENT_COUNT=str(self.agent_count), AGENT_STATUS=str(helper_status),
|
||||
FOCUS=focus, FOCUS_COUNT=str(self.focus_count))
|
||||
FOCUS=focus, FOCUS_COUNT=str(self.focus_count), RUNNING_AFTER=str(running_after))
|
||||
script = self.block + "\nprintf 'ARG:%s\n' \"$@\"\nwait\n"
|
||||
url = target if target.startswith("steam://") else "steam://rungameid/" + target
|
||||
result = subprocess.run(["bash", "-c", script, "cold-launch", url],
|
||||
@@ -85,6 +92,20 @@ class SteamColdLaunchTest(unittest.TestCase):
|
||||
self.assertEqual(2, len(self.hand_offs(result)), result.stdout)
|
||||
self.assertIn("overview status 1", result.stdout)
|
||||
|
||||
def test_a_game_still_starting_without_a_window_is_not_launched_twice(self):
|
||||
result = self.run_launch(SHORTCUT, running_after=1)
|
||||
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
|
||||
self.assertFalse(self.agent_args.exists())
|
||||
self.assertEqual(["-f", "reaper SteamLaunch AppId=3551182975( |$)"],
|
||||
(self.root / "pgrep-args").read_text().splitlines())
|
||||
self.assertIn("already starting", result.stdout)
|
||||
|
||||
def test_a_game_starting_during_the_overview_wait_is_not_launched_twice(self):
|
||||
result = self.run_launch(SHORTCUT, running_after=2)
|
||||
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
|
||||
self.assertTrue(self.agent_args.exists())
|
||||
self.assertIn("started while waiting", result.stdout)
|
||||
|
||||
def test_a_game_that_takes_focus_during_the_overview_wait_is_not_started_twice(self):
|
||||
focus = " ".join(["769"] * 23) + " 4242"
|
||||
result = self.run_launch(SHORTCUT, focus=focus, helper_status=0)
|
||||
|
||||
@@ -54,6 +54,7 @@ class FakeSocket {
|
||||
state.authed = dec.decode(h[40][0]) === "secret" && dec.decode(body[1][0]) === "secret";
|
||||
result = state.authed ? 1 : 5;
|
||||
} else if (!state.authed) result = 5;
|
||||
else if (method === "CompatManager.GetCompatTools#1" && ["16", "128"].includes(String(body[1][0]))) result = Number(body[1][0]);
|
||||
else if (method === "CompatManager.GetCompatTools#1") {
|
||||
const app = String(body[1] ? body[1][0] : 0n);
|
||||
for (const name of state.known) { const t = []; lenField(1, enc.encode(name), t); lenField(2, enc.encode(name + " shown"), t); lenField(1, t, out); }
|
||||
@@ -79,17 +80,19 @@ const install = require("fs").readFileSync(process.argv[4], "utf8");
|
||||
const before = await c.get(0);
|
||||
await c.set(0, "droiddeck-proton-11-arm64");
|
||||
await c.set(42, "");
|
||||
const after = await c.many(["0", "42", "43"]);
|
||||
const after = await c.many(["0", "42", "43", "128"]);
|
||||
const timedOut = await c.many(["0", "16"]).then(() => null, (e) => e.eresult);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
console.log(JSON.stringify({ before, after, log: state.log, notify: state.notify, url: state.socket.url }));
|
||||
console.log(JSON.stringify({ before, after, timedOut, log: state.log, notify: state.notify, url: state.socket.url }));
|
||||
})().catch((e) => { console.error(e.stack || String(e)); process.exit(1); });
|
||||
"""
|
||||
|
||||
|
||||
class FakePage:
|
||||
def __init__(self, mapping, known):
|
||||
def __init__(self, mapping, known, refused=()):
|
||||
self.mapping = dict(mapping)
|
||||
self.known = list(known)
|
||||
self.refused = set(refused)
|
||||
self.sets = []
|
||||
|
||||
def compat(self, call):
|
||||
@@ -98,8 +101,10 @@ class FakePage:
|
||||
if name == "get":
|
||||
return {"selected": self.mapping.get(str(args[0]), ""), "fallback": "proton_experimental", "tools": self.known}
|
||||
if name == "many":
|
||||
return {app: self.mapping.get(app, "") for app in args[0]}
|
||||
return {app: self.mapping.get(app, "") for app in args[0] if app not in self.refused}
|
||||
if name == "set":
|
||||
if str(args[0]) in self.refused:
|
||||
raise RuntimeError("SpecifyCompatTool %s failed (128)" % args[0])
|
||||
self.mapping[str(args[0])] = args[1]
|
||||
self.sets.append((str(args[0]), args[1]))
|
||||
return True
|
||||
@@ -202,6 +207,7 @@ assert.deepStrictEqual(calls, [['611670', 'custom args', -1, 100], ['2508200', '
|
||||
self.assertEqual(out["url"], "ws://127.0.0.1:4242/transportsocket/")
|
||||
self.assertEqual(out["before"], {"selected": TOOL, "fallback": "proton_experimental", "tools": [TOOL, TOOL_11, "proton_experimental"]})
|
||||
self.assertEqual(out["after"], {"0": TOOL_11, "42": "", "43": ""})
|
||||
self.assertEqual(out["timedOut"], 16)
|
||||
self.assertEqual(out["log"], ["0=" + TOOL_11, "42="])
|
||||
self.assertEqual(out["notify"], ["1", "2"])
|
||||
|
||||
@@ -264,6 +270,21 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertTrue(state["live"])
|
||||
self.assertEqual(self.helper.installed, ["10", "11"])
|
||||
|
||||
def test_an_app_the_client_refuses_is_dropped_instead_of_failing_the_sync(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": "proton_experimental"}, [TOOL, TOOL_11], refused={"1628350"})
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "1628350": TOOL}}))
|
||||
(self.state / "games.json").write_text(json.dumps({"version": 1, "games": {"1628350": {"valve": True, "dir": "Proton 11.0 (ARM64)"}}}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("11", TOOL)])
|
||||
self.assertEqual(state["auto"], {"10": TOOL, "11": TOOL})
|
||||
|
||||
def test_a_refused_apps_native_choice_is_kept(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11], refused={"20"})
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "native_choices": ["20"]}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], ["20"])
|
||||
|
||||
def test_app_request_moves_the_default_and_followers(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": "GE-Proton11-7"}, [TOOL, TOOL_11])
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL}}))
|
||||
@@ -488,6 +509,70 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
|
||||
def test_clearing_a_tool_picked_in_steam_keeps_the_native_build(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
|
||||
page.known.append(COMPAT["FEX_TOOL"])
|
||||
page.mapping[app] = COMPAT["FEX_TOOL"]
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"]))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertNotIn(app, state["auto"])
|
||||
|
||||
page.mapping[app] = ""
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
|
||||
restarted = LIVE["Helper"](str(self.steam), 1)
|
||||
restarted.page = page
|
||||
restarted.reconcile()
|
||||
self.assertEqual(page.sets, [])
|
||||
|
||||
def test_a_new_tool_for_a_picked_game_is_kept_before_the_client_writes_its_config(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]})
|
||||
page.mapping[app] = TOOL_11
|
||||
with mock.patch.dict(COMPAT, {"native_targets": lambda _root, apps: {app: COMPAT["FEX_TOOL"]} if app in apps else {}}):
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(page.mapping[app], TOOL_11)
|
||||
self.assertIn(app, state["picked"])
|
||||
|
||||
def test_a_cleared_picked_game_showing_a_stale_inherited_tool_stays_native(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]})
|
||||
page.mapping[app] = "proton"
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
|
||||
def test_a_clear_saved_after_the_helper_stopped_is_kept_at_the_next_start(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
|
||||
page.known.append(COMPAT["FEX_TOOL"])
|
||||
page.mapping[app] = COMPAT["FEX_TOOL"]
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"]))
|
||||
state = self.reconcile(page)
|
||||
self.assertIn(app, state["picked"])
|
||||
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
with mock.patch.dict(COMPAT["register_default"].__globals__, {"native_targets": COMPAT["native_targets"]}):
|
||||
COMPAT["register_default"](str(config), ["10", "11", app], settle=True, directory=str(self.state))
|
||||
self.assertNotIn(app, COMPAT["read_config_mapping"](str(config)))
|
||||
state = json.loads((self.state / "state.json").read_text())
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
self.assertNotIn(app, state["picked"])
|
||||
|
||||
def test_unmapped_dual_platform_game_gets_the_default_without_a_readable_config(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL}, "native_choices": ["11"]})
|
||||
(self.steam / "config/config.vdf").unlink()
|
||||
|
||||
@@ -311,6 +311,24 @@ class ImportsTest(unittest.TestCase):
|
||||
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
|
||||
self.assertFalse(os.path.lexists(self.steam / 'steamapps/common/DroidDeck-42'))
|
||||
|
||||
def test_imported_game_stays_imported_when_ownership_is_unconfirmed(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
for owned, account in [(False, '123'), (True, '456')]:
|
||||
self.snapshot(owned, account)
|
||||
self.assertEqual(([], {str(self.game['appid']): 42}), imports.route(self.steam, self.acct, [self.game]))
|
||||
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
|
||||
|
||||
def test_unlisted_card_library_is_not_another_clients_install(self):
|
||||
card = self.root / 'card'
|
||||
(card / 'steamapps').mkdir(parents=True)
|
||||
(card / 'steamapps/appmanifest_42.acf').write_text('the other client installed it here')
|
||||
self.snapshot()
|
||||
with patch.object(imports, 'LIBRARY', str(card)):
|
||||
self.assertEqual(([], {str(self.game['appid']): 42}), imports.route(self.steam, self.acct, [self.game]))
|
||||
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
|
||||
self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve())
|
||||
|
||||
def test_replaced_game_does_not_inherit_cached_ownership(self):
|
||||
self.snapshot()
|
||||
self.exe.write_bytes(b'a different game')
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64'
|
||||
|
||||
REGISTRY = ('"Registry"\n{\n\t"HKCU"\n\t{\n\t\t"Software"\n\t\t{\n\t\t\t"Valve"\n\t\t\t{\n\t\t\t\t"Steam"\n\t\t\t\t{\n'
|
||||
'\t\t\t\t\t"language"\t\t"english"\n%s\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
|
||||
CONFIG = ('"InstallConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n\t\t\t"Steam"\n\t\t\t{\n%s'
|
||||
'\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
|
||||
ACCOUNTS = ('\t\t\t\t"Accounts"\n\t\t\t\t{\n\t\t\t\t\t"someone"\n\t\t\t\t\t{\n'
|
||||
'\t\t\t\t\t\t"SteamID"\t\t"76561198000000001"\n\t\t\t\t\t}\n\t\t\t\t}\n')
|
||||
|
||||
|
||||
def local(token):
|
||||
entry = '\t\t"abc1"\t\t"%s"\n' % token if token else ''
|
||||
return '"MachineUserConfigStore"\n{\n\t"ConnectCache"\n\t{\n%s\t}\n}\n' % entry
|
||||
|
||||
|
||||
class X64SignInTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.home = Path(self.temp.name)
|
||||
self.arm = self.home / '.local/share/Steam'
|
||||
self.x64 = self.home / '.droiddeck-x64/.local/share/Steam'
|
||||
for root in (self.arm, self.x64):
|
||||
(root / 'config').mkdir(parents=True)
|
||||
(self.home / '.steam').mkdir()
|
||||
(self.home / '.droiddeck-x64/.steam').mkdir(parents=True)
|
||||
self.write(self.arm / 'local.vdf', local('00ff'))
|
||||
self.write(self.arm / 'config/loginusers.vdf', '"users"\n{\n}\n')
|
||||
self.write(self.arm / 'config/config.vdf', CONFIG % ACCOUNTS)
|
||||
self.write(self.home / '.steam/registry.vdf', REGISTRY % '\t\t\t\t\t"AutoLoginUser"\t\t"someone"\n')
|
||||
self.write(self.x64 / 'local.vdf', local(None))
|
||||
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 % '')
|
||||
|
||||
def write(self, path, text):
|
||||
path.write_text(text)
|
||||
|
||||
def sync(self):
|
||||
env = dict(os.environ, HOME=str(self.home))
|
||||
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)
|
||||
|
||||
def test_a_refused_x64_sign_in_gets_the_token_account_and_auto_login(self):
|
||||
self.assertIn('sign-in shared from the arm64 client', self.sync().stdout)
|
||||
self.assertEqual(local('00ff'), (self.x64 / 'local.vdf').read_text())
|
||||
self.assertIn('"SteamID"\t\t"76561198000000001"', (self.x64 / 'config/config.vdf').read_text())
|
||||
self.assertIn('"AutoLoginUser"\t\t"someone"', (self.home / '.droiddeck-x64/.steam/registry.vdf').read_text())
|
||||
|
||||
def test_an_earlier_copy_still_gains_the_account_and_nothing_repeats(self):
|
||||
self.sync()
|
||||
self.write(self.x64 / 'config/config.vdf', CONFIG % '')
|
||||
self.write(self.home / '.droiddeck-x64/.steam/registry.vdf', REGISTRY % '')
|
||||
self.assertNotIn('sign-in shared', self.sync().stdout)
|
||||
self.assertIn('"76561198000000001"', (self.x64 / 'config/config.vdf').read_text())
|
||||
self.assertIn('"AutoLoginUser"', (self.home / '.droiddeck-x64/.steam/registry.vdf').read_text())
|
||||
self.sync()
|
||||
for root in (self.arm, self.x64):
|
||||
self.assertEqual(1, (root / 'config/config.vdf').read_text().count('"SteamID"'))
|
||||
self.assertEqual(1, (self.home / '.droiddeck-x64/.steam/registry.vdf').read_text().count('AutoLoginUser'))
|
||||
|
||||
def test_a_newer_x64_sign_in_moves_to_arm64(self):
|
||||
self.write(self.x64 / 'local.vdf', local('11ee'))
|
||||
os.utime(self.arm / 'local.vdf', (1, 1))
|
||||
self.assertIn('from the x86-64 client', self.sync().stdout)
|
||||
self.assertEqual(local('11ee'), (self.arm / 'local.vdf').read_text())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -210,6 +210,44 @@ class SteamVrHelperTest(unittest.TestCase):
|
||||
def test_flat_presenter_does_not_enable_the_producer_lease(self):
|
||||
self.assertIn('present=unset lease=unset', self.lease_log())
|
||||
|
||||
def registration(self):
|
||||
return (self.home / '.config/openvr/openvrpaths.vrpath',
|
||||
self.home / '.config/openxr/1/active_runtime.json')
|
||||
|
||||
def helper_action(self, action):
|
||||
subprocess.run(['sh', str(self.helper), action], env=self.environment, check=True,
|
||||
capture_output=True, timeout=5)
|
||||
|
||||
def test_runtime_is_registered_only_while_a_session_is_active(self):
|
||||
vrpath, xr = self.registration()
|
||||
self.start()
|
||||
self.assertTrue(vrpath.is_file())
|
||||
self.assertTrue(xr.is_symlink())
|
||||
self.helper_action('status')
|
||||
self.assertTrue(vrpath.is_file())
|
||||
self.helper_action('stop')
|
||||
self.assertFalse(vrpath.exists())
|
||||
self.assertFalse(xr.is_symlink())
|
||||
|
||||
def test_idle_status_and_session_start_clear_a_leftover_registration(self):
|
||||
vrpath, xr = self.registration()
|
||||
for action in ('status', 'unregister'):
|
||||
self.start()
|
||||
(self.runtime / 'droiddeck-steamvr/active').unlink()
|
||||
self.helper_action(action)
|
||||
self.assertFalse(vrpath.exists(), action)
|
||||
self.assertFalse(xr.is_symlink(), action)
|
||||
|
||||
def test_unregister_leaves_another_runtime_alone(self):
|
||||
vrpath, xr = self.registration()
|
||||
vrpath.parent.mkdir(parents=True)
|
||||
xr.parent.mkdir(parents=True)
|
||||
vrpath.write_text('{"runtime": ["/opt/other-runtime"]}')
|
||||
xr.symlink_to('/opt/monado/openxr_monado.json')
|
||||
self.helper_action('unregister')
|
||||
self.assertTrue(vrpath.is_file())
|
||||
self.assertTrue(xr.is_symlink())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -226,6 +226,43 @@ class CloudHooks(unittest.TestCase):
|
||||
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
|
||||
self.assertEqual('cloud-up', asked[2][0]['op'])
|
||||
|
||||
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='epic', ident='fa4240e5')
|
||||
sidecar = json.loads((folder / store.SIDECAR).read_text())
|
||||
sidecar['epic'] = {'eos': False, 'offline': True}
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
compat = Path(root) / 'compatdata/1'
|
||||
order = []
|
||||
|
||||
def run(argv, **kwargs):
|
||||
order.append(argv)
|
||||
(compat / 'pfx').mkdir(parents=True)
|
||||
(compat / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
|
||||
env = {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'BL_STORE_PROTON': str(proton)}
|
||||
with patch.dict(os.environ, env), patch.object(store.subprocess, 'run', side_effect=run), \
|
||||
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: order.append(request) or {'result': 'ok'}):
|
||||
self.assertEqual(store.STORE_GAME, store.main([str(folder / store.LAUNCHER)]))
|
||||
self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c', 'exit'], order[0])
|
||||
self.assertEqual({'op': 'cloud-down', 'store': 'epic', 'id': 'fa4240e5'}, order[-1])
|
||||
self.assertEqual('present', store.create_prefix(str(compat), str(proton)))
|
||||
self.assertEqual(2, len(order))
|
||||
|
||||
def test_a_prefix_that_is_not_made_leaves_the_deferred_download(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
with patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
|
||||
self.assertEqual('failed', store.create_prefix(root + '/compatdata/1', str(proton)))
|
||||
with patch.object(store.subprocess, 'run', side_effect=__import__('subprocess').TimeoutExpired('proton', 1)):
|
||||
self.assertEqual('timeout', store.create_prefix(root + '/compatdata/1', str(proton)))
|
||||
self.assertEqual('no-proton', store.create_prefix(root + '/compatdata/1', root + '/missing'))
|
||||
self.assertEqual('no-proton', store.create_prefix('', str(proton)))
|
||||
|
||||
def test_cloud_off_or_amazon_runs_proton_as_before(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1')
|
||||
@@ -314,3 +351,96 @@ class GogAchievements(unittest.TestCase):
|
||||
with patch.object(store, 'COMET_DIR', base), patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
|
||||
self.assertEqual('service-unavailable', store.provision_galaxy(str(base / 'compat'), str(base / 'proton')))
|
||||
self.assertFalse((base / 'compat/pfx/.droiddeck-comet-service').exists())
|
||||
|
||||
|
||||
def gog_script(folder, product, actions):
|
||||
(folder / ('goggame-%s.script' % product)).write_text(json.dumps({'actions': actions, 'baseProductId': product, 'version': 1}))
|
||||
|
||||
|
||||
def set_registry(**arguments):
|
||||
return {'install': {'action': 'setRegistry', 'arguments': arguments}, 'name': 'setRegistry'}
|
||||
|
||||
|
||||
class GogRegistry(unittest.TestCase):
|
||||
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')
|
||||
gog_script(folder, '1454587428', [
|
||||
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Bethesda Softworks\\FalloutNV',
|
||||
valueName='Installed Path', valueData='{app}\\', valueType='string'),
|
||||
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\GOG.com\\Games\\{productId}',
|
||||
valueName='buildId', valueData='42', valueType='dword'),
|
||||
set_registry(root='HKEY_CURRENT_USER', subkey='Software\\Game', valueName='', valueData='AAH/', valueType='binary'),
|
||||
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Empty'),
|
||||
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Game', valueName='x', valueData='1', valueType='qword'),
|
||||
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Game', valueName='x', valueData='{nowhere}', valueType='string'),
|
||||
set_registry(root='HKEY_USERS', subkey='S-1-5', valueName='x', valueData='1', valueType='string'),
|
||||
{'install': {'action': 'Execute', 'arguments': {'executable': 'setup.exe'}}},
|
||||
'nonsense',
|
||||
])
|
||||
entries, skipped = store.gog_registry(folder)
|
||||
app = store.windows_path(str(folder)).replace('\\', '\\\\')
|
||||
self.assertEqual([
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\Bethesda Softworks\\FalloutNV]\r\n"Installed Path"="%s\\\\"' % app,
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\GOG.com\\Games\\1454587428]\r\n"buildId"=dword:0000002a',
|
||||
'[HKEY_CURRENT_USER\\Software\\Game]\r\n@=hex:00,01,ff',
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\Empty]',
|
||||
], entries)
|
||||
self.assertEqual(3, skipped)
|
||||
|
||||
def test_a_game_without_a_script_starts_without_proton(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog')
|
||||
with patch.object(store.subprocess, 'run') as run:
|
||||
self.assertEqual('none', store.apply_gog_registry(folder, root + '/compat', root + '/proton'))
|
||||
run.assert_not_called()
|
||||
|
||||
def test_values_are_imported_into_the_32_bit_view_once_until_the_script_changes(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1454587428')
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
data = Path(root) / 'compat'
|
||||
action = set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\FalloutNV',
|
||||
valueName='Installed Path', valueData='{app}', valueType='string')
|
||||
gog_script(folder, '1454587428', [action])
|
||||
imported = []
|
||||
def run(argv, **kwargs):
|
||||
self.assertEqual([str(proton), 'run', 'reg.exe', 'import'], argv[:4])
|
||||
self.assertEqual('/reg:32', argv[5])
|
||||
raw = Path(argv[4][2:].replace('\\', '/')).read_bytes()
|
||||
self.assertTrue(raw.startswith(b'\xff\xfe'))
|
||||
imported.append(raw[2:].decode('utf-16-le'))
|
||||
(data / 'pfx').mkdir(parents=True, exist_ok=True)
|
||||
(data / 'pfx/system.reg').write_text('Wine registry')
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
with patch.object(store.subprocess, 'run', side_effect=run):
|
||||
self.assertEqual('written=1', store.apply_gog_registry(folder, str(data), str(proton)))
|
||||
self.assertTrue(imported[0].startswith('Windows Registry Editor Version 5.00\r\n'))
|
||||
self.assertIn('[HKEY_LOCAL_MACHINE\\Software\\Bethesda Softworks\\FalloutNV]', imported[0])
|
||||
self.assertEqual('ready', store.apply_gog_registry(folder, str(data), str(proton)))
|
||||
self.assertEqual(1, len(imported))
|
||||
action['install']['arguments']['valueData'] = '{app}\\'
|
||||
gog_script(folder, '1454587428', [action])
|
||||
self.assertEqual('written=1', store.apply_gog_registry(folder, str(data), str(proton)))
|
||||
self.assertEqual(2, len(imported))
|
||||
|
||||
def test_a_failed_import_is_tried_again_next_launch(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='7')
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
gog_script(folder, '7', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string')])
|
||||
with patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
|
||||
self.assertEqual('import-failed', store.apply_gog_registry(folder, root + '/compat', str(proton)))
|
||||
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_REGISTRY_MARK).exists())
|
||||
self.assertEqual('no-proton', store.apply_gog_registry(folder, root + '/compat', root + '/missing'))
|
||||
|
||||
def test_every_gog_launch_brings_the_registry_in(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog')
|
||||
with patch.dict(os.environ, {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat/', 'BL_STORE_PROTON': '/chosen/proton'}), \
|
||||
patch.object(store, 'prepare_gog', return_value=False), patch.object(store, 'ask', return_value=None), \
|
||||
patch.object(store, 'apply_gog_registry', return_value='ready') as apply:
|
||||
store.main([str(folder / store.LAUNCHER)])
|
||||
apply.assert_called_once_with(folder, root + '/compat', '/chosen/proton')
|
||||
@@ -20,6 +20,15 @@ class SysvPreloadTest(unittest.TestCase):
|
||||
result = subprocess.run([binary], capture_output=True, text=True, timeout=10, env=env)
|
||||
self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr)
|
||||
|
||||
def test_message_queue_mapping_is_reused_and_removal_wakes_waiters(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-sysv-msg')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary,
|
||||
str(Path(__file__).resolve().parent / 'sysv_msg_harness.c'), str(PRELOAD / 'sysv.c')], check=True)
|
||||
env = dict(os.environ, BL_SYSV_DIR=folder)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, timeout=20, env=env)
|
||||
self.assertIn('PASS: sysv msg', result.stdout, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,227 @@
|
||||
import array
|
||||
import mmap
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROTO = ROOT / 'app/src/main/cpp/venc/venc_proto.h'
|
||||
VENC = ROOT / 'tools/linuxfs/preload/venc.c'
|
||||
TOUCH = ROOT / 'tools/linuxfs/preload/rptouch.c'
|
||||
|
||||
DRIVER = r'''
|
||||
#include <errno.h>
|
||||
#include <linux/videodev2.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
|
||||
int bl_venc_open(const char *path, int flags);
|
||||
int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc);
|
||||
int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
|
||||
void *(*real)(void *, size_t, int, int, int, off_t), void **out);
|
||||
void bl_venc_closed(int fd);
|
||||
|
||||
static int fd;
|
||||
static int call(unsigned long req, void *arg) {
|
||||
int rc;
|
||||
if (!bl_venc_ioctl(fd, req, arg, &rc)) return -100;
|
||||
return rc < 0 ? -errno : 0;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
if (bl_venc_open("/dev/video0", 0) != -2) return 2;
|
||||
fd = bl_venc_open("/dev/video-enc0", 0);
|
||||
if (fd < 0) return 3;
|
||||
struct v4l2_capability cap;
|
||||
if (call(VIDIOC_QUERYCAP, &cap) || !(cap.device_caps & V4L2_CAP_VIDEO_M2M_MPLANE)) return 4;
|
||||
struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
|
||||
f.fmt.pix_mp.width = 640; f.fmt.pix_mp.height = 360; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
|
||||
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.plane_fmt[0].sizeimage != 640 * 360 * 3 / 2) return 5;
|
||||
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
|
||||
f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC;
|
||||
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.pixelformat != V4L2_PIX_FMT_HEVC) return 6;
|
||||
struct v4l2_control c = { V4L2_CID_MPEG_VIDEO_BITRATE, 8000000 };
|
||||
if (call(VIDIOC_S_CTRL, &c)) return 7;
|
||||
unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
|
||||
unsigned char *maps[2][2];
|
||||
for (int t = 0; t < 2; t++) {
|
||||
struct v4l2_requestbuffers r = { .count = 2, .type = types[t], .memory = V4L2_MEMORY_MMAP };
|
||||
if (call(VIDIOC_REQBUFS, &r) || r.count != 2) return 8;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
struct v4l2_plane p;
|
||||
struct v4l2_buffer b = { .index = i, .type = types[t], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
|
||||
if (call(VIDIOC_QUERYBUF, &b)) return 9;
|
||||
void *m;
|
||||
if (!bl_venc_mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, p.m.mem_offset, mmap, &m) ||
|
||||
m == MAP_FAILED) return 10;
|
||||
maps[t][i] = m;
|
||||
if (t == 1 && call(VIDIOC_QBUF, &b)) return 11;
|
||||
}
|
||||
if (call(VIDIOC_STREAMON, &types[t])) return 12;
|
||||
}
|
||||
struct v4l2_plane cp;
|
||||
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &cp };
|
||||
if (call(VIDIOC_DQBUF, &cb) != -EAGAIN) return 13;
|
||||
for (int frame = 0; frame < 3; frame++) {
|
||||
memset(maps[0][frame % 2], 'a' + frame, 640 * 360);
|
||||
struct v4l2_plane p = { .bytesused = 640 * 360 * 3 / 2 };
|
||||
struct v4l2_buffer b = { .index = frame % 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
|
||||
b.timestamp.tv_sec = frame;
|
||||
if (frame == 1) {
|
||||
struct v4l2_control k = { V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME, 1 };
|
||||
call(VIDIOC_S_CTRL, &k);
|
||||
}
|
||||
if (call(VIDIOC_QBUF, &b)) return 14;
|
||||
if (call(VIDIOC_DQBUF, &cb)) return 15;
|
||||
printf("%d %u %d %ld %.*s\n", frame, cp.bytesused, !!(cb.flags & V4L2_BUF_FLAG_KEYFRAME),
|
||||
(long)cb.timestamp.tv_sec, (int)cp.bytesused, maps[1][cb.index]);
|
||||
if (call(VIDIOC_DQBUF, &b)) return 16;
|
||||
if (call(VIDIOC_QBUF, &cb)) return 17;
|
||||
}
|
||||
bl_venc_closed(fd);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
TOUCH_DRIVER = r'''
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int bl_venc_open(const char *path, int flags);
|
||||
void bl_venc_closed(int fd);
|
||||
int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay);
|
||||
int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay);
|
||||
int XDisplayWidth(void *dpy, int screen) { return 1281; }
|
||||
int XDisplayHeight(void *dpy, int screen) { return 721; }
|
||||
|
||||
int main(void) {
|
||||
XTestFakeButtonEvent(NULL, 1, 1, 0);
|
||||
XTestFakeButtonEvent(NULL, 1, 0, 0);
|
||||
int fd = bl_venc_open("/dev/video-enc0", 0);
|
||||
if (fd < 0) return 3;
|
||||
XTestFakeMotionEvent(NULL, 0, 1280, 360, 0);
|
||||
XTestFakeButtonEvent(NULL, 1, 1, 0);
|
||||
XTestFakeMotionEvent(NULL, 0, 640, 0, 0);
|
||||
XTestFakeButtonEvent(NULL, 3, 1, 0);
|
||||
XTestFakeButtonEvent(NULL, 1, 0, 0);
|
||||
char marker[512];
|
||||
snprintf(marker, sizeof marker, "%s/droiddeck-remote-play", getenv("XDG_RUNTIME_DIR"));
|
||||
if (access(marker, F_OK) != 0) return 4;
|
||||
pid_t child = fork();
|
||||
if (child == 0) { bl_venc_closed(fd); _exit(access(marker, F_OK) == 0 ? 0 : 1); }
|
||||
int status;
|
||||
waitpid(child, &status, 0);
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return 5;
|
||||
bl_venc_closed(fd);
|
||||
if (access(marker, F_OK) == 0) return 6;
|
||||
XTestFakeButtonEvent(NULL, 1, 1, 0);
|
||||
usleep(200000);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
CONFIG = struct.Struct('<' + 'I' * 12 + 'ii' + 'I' * 4)
|
||||
FRAME = struct.Struct('<IIIII4xq')
|
||||
DONE = struct.Struct('<IiII')
|
||||
|
||||
|
||||
class FakeEncoder(threading.Thread):
|
||||
def __init__(self, path):
|
||||
super().__init__(daemon=True)
|
||||
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
|
||||
self.listener.bind(path)
|
||||
self.listener.listen(1)
|
||||
self.configs, self.frames, self.touches = [], [], []
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def serve(self, conn):
|
||||
outputs = []
|
||||
while True:
|
||||
fds = array.array('i')
|
||||
msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(32 * fds.itemsize))
|
||||
if not msg:
|
||||
return
|
||||
for level, kind, data in ancdata:
|
||||
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
|
||||
fds.frombytes(data[:len(data) - len(data) % fds.itemsize])
|
||||
kind = struct.unpack_from('<I', msg)[0]
|
||||
if kind == 5:
|
||||
self.touches.append(struct.unpack('<IIII', msg)[1:])
|
||||
elif kind == 1:
|
||||
c = CONFIG.unpack(msg)
|
||||
self.configs.append(c)
|
||||
inputs, size = c[14], c[17]
|
||||
outputs = [mmap.mmap(fd, size) for fd in fds[inputs:]]
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
conn.send(DONE.pack(3, 0, 0, 0))
|
||||
elif kind == 2:
|
||||
_, _, output, nbytes, key, pts = FRAME.unpack(msg)
|
||||
self.frames.append((nbytes, key, pts))
|
||||
payload = b'frame%d' % len(self.frames)
|
||||
outputs[output][:len(payload)] = payload
|
||||
conn.send(DONE.pack(3, 0, len(payload), 1 if key or len(self.frames) == 1 else 0))
|
||||
|
||||
|
||||
class VencEmulatorTest(unittest.TestCase):
|
||||
def test_steam_style_session_round_trips_through_the_app_socket(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
driver = tmp / 'driver.c'
|
||||
driver.write_text(DRIVER)
|
||||
binary = tmp / 'driver'
|
||||
subprocess.run(['cc', '-O1', '-pthread', '-o', str(binary), str(driver), str(VENC), '-ldl'],
|
||||
check=True)
|
||||
sock = tmp / 'venc.sock'
|
||||
server = FakeEncoder(str(sock))
|
||||
self.addCleanup(server.listener.close)
|
||||
server.start()
|
||||
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)),
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
|
||||
self.assertEqual(done.stdout.split('\n')[:3],
|
||||
['0 6 1 0 frame1', '1 6 1 1 frame2', '2 6 0 2 frame3'])
|
||||
self.assertEqual(len(server.configs), 1)
|
||||
config = server.configs[0]
|
||||
self.assertEqual(config[1], 1)
|
||||
self.assertEqual(config[2:6], (640, 360, 640, 360))
|
||||
self.assertEqual(config[8], 8000000)
|
||||
self.assertEqual([f[1] for f in server.frames], [0, 1, 0])
|
||||
self.assertEqual([f[2] for f in server.frames], [0, 1000000, 2000000])
|
||||
self.assertTrue(all(f[0] == 640 * 360 * 3 // 2 for f in server.frames))
|
||||
|
||||
def test_remote_touch_and_stream_marker_follow_the_streaming_process(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
driver = tmp / 'touch.c'
|
||||
driver.write_text(TOUCH_DRIVER)
|
||||
binary = tmp / 'touch'
|
||||
subprocess.run(['cc', '-O1', '-pthread', '-rdynamic', '-o', str(binary), str(driver), str(VENC), str(TOUCH),
|
||||
'-ldl'], check=True)
|
||||
sock = tmp / 'venc.sock'
|
||||
server = FakeEncoder(str(sock))
|
||||
self.addCleanup(server.listener.close)
|
||||
server.start()
|
||||
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock), XDG_RUNTIME_DIR=str(tmp)),
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertEqual(server.touches, [(0, 65535, 32767), (1, 32767, 0), (2, 32767, 0)])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,108 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <stdint.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void) {
|
||||
unsigned char *code = mmap((void *)0xc0000000UL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (sizeof(void *) == 4 && (uintptr_t)code <= 0x7fffffffU) return 3;
|
||||
unsigned char *data = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
memset(code, 0x90, 4096);
|
||||
mprotect(code, 4096, PROT_READ | PROT_EXEC);
|
||||
int ready[2];
|
||||
if (pipe(ready)) return 2;
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
prctl(PR_SET_PDEATHSIG, SIGKILL);
|
||||
close(ready[0]);
|
||||
if (write(ready[1], "", 1) != 1) _exit(1);
|
||||
pause();
|
||||
_exit(0);
|
||||
}
|
||||
char c;
|
||||
close(ready[1]);
|
||||
if (read(ready[0], &c, 1) != 1) return 2;
|
||||
unsigned char patch[4] = {0xB8, 0x78, 0x56, 0x34};
|
||||
struct iovec mine = {patch, sizeof patch};
|
||||
struct iovec theirs[2] = {{code, sizeof patch}, {data, sizeof patch}};
|
||||
for (int i = 0; i < 2; i++) {
|
||||
ssize_t n = process_vm_writev(child, &mine, 1, &theirs[i], 1, 0);
|
||||
printf("%s %zd %d", i ? "data" : "code", n, n < 0 ? errno : 0);
|
||||
unsigned char back[4] = {0};
|
||||
struct iovec got = {back, sizeof back};
|
||||
process_vm_readv(child, &got, 1, &theirs[i], 1, 0);
|
||||
printf(" %s\n", memcmp(back, patch, sizeof patch) ? "old" : "new");
|
||||
}
|
||||
struct iovec split[2] = {{patch, 2}, {patch + 2, 2}};
|
||||
ssize_t n = process_vm_writev(child, split, 2, &theirs[0], 1, 0);
|
||||
printf("split %zd %d\n", n, n < 0 ? errno : 0);
|
||||
n = process_vm_writev(child, (const struct iovec *)8, 1, &theirs[0], 1, 0);
|
||||
printf("invalid %zd %d\n", n, n < 0 ? errno : 0);
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc") and os.path.exists("/proc/self/mem"), "needs cc and /proc")
|
||||
class VmWritePreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.addClassCleanup(shutil.rmtree, cls.tmp, ignore_errors=True)
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
cls.bits32 = True
|
||||
for flags, sub in (([], "64"), (["-m32"], "32")):
|
||||
(cls.tmp / sub).mkdir()
|
||||
try:
|
||||
subprocess.run(["cc", *flags, "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o",
|
||||
str(cls.tmp / sub / "libvmwrite.so"), str(PRELOAD / "vmwrite.c"), "-ldl"],
|
||||
check=True, capture_output=True)
|
||||
for name in ("wineserver", "game"):
|
||||
subprocess.run(["cc", *flags, "-O2", "-o", str(cls.tmp / sub / name), str(source)],
|
||||
check=True, capture_output=True)
|
||||
except subprocess.CalledProcessError:
|
||||
if not flags:
|
||||
raise
|
||||
cls.bits32 = False
|
||||
|
||||
def run_as(self, name, preload=True, bits="64"):
|
||||
lib = self.tmp / bits / "libvmwrite.so"
|
||||
env = dict(os.environ, LD_PRELOAD=str(lib)) if preload else {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
result = subprocess.run([str(self.tmp / bits / name)], env=env, capture_output=True, text=True, check=True)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def test_wineserver_writes_a_page_the_kernel_refused(self):
|
||||
self.assertEqual(self.run_as("wineserver"), ["code 4 0 new", "data 4 0 new", "split -1 14", "invalid -1 14"])
|
||||
|
||||
def test_a_32_bit_wineserver_writes_above_2_gib(self):
|
||||
if not self.bits32:
|
||||
self.skipTest("needs cc -m32")
|
||||
self.assertEqual(self.run_as("wineserver", bits="32"), ["code 4 0 new", "data 4 0 new", "split -1 14", "invalid -1 14"])
|
||||
|
||||
def test_everyone_else_keeps_the_kernel_answer(self):
|
||||
for refused in (self.run_as("game"), self.run_as("wineserver", preload=False)):
|
||||
self.assertEqual(refused, ["code -1 14 old", "data 4 0 new", "split -1 14", "invalid -1 14"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
class XboxBuildSourceTest(unittest.TestCase):
|
||||
def test_main_advancing_between_jobs_does_not_change_packaged_source(self):
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
self.fail('PyYAML is required to execute workflow steps')
|
||||
workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text())
|
||||
jobs = workflow['jobs']
|
||||
step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
env = dict(os.environ, GIT_AUTHOR_NAME='test', GIT_COMMITTER_NAME='test',
|
||||
GIT_AUTHOR_EMAIL='test@example.test', GIT_COMMITTER_EMAIL='test@example.test',
|
||||
GITHUB_STEP_SUMMARY=str(root / 'summary'))
|
||||
def git(*args, cwd=root):
|
||||
return subprocess.check_output(['git', *args], cwd=cwd, env=env, stderr=subprocess.DEVNULL, text=True).strip()
|
||||
git('init', '-q', '-b', 'main')
|
||||
(root / 'backend').write_text('base')
|
||||
git('add', '.'); git('commit', '-qm', 'base')
|
||||
git('switch', '-qc', 'feature')
|
||||
(root / 'app').write_text('feature')
|
||||
git('add', '.'); git('commit', '-qm', 'feature')
|
||||
head = git('rev-parse', 'HEAD')
|
||||
git('switch', '-q', 'main')
|
||||
(root / 'backend').write_text('merged backend')
|
||||
git('commit', '-qam', 'backend changed after branch')
|
||||
for name in ('xbox', 'apk'):
|
||||
git('clone', '-q', str(root), str(root / name))
|
||||
git('checkout', '-q', head, cwd=root / name)
|
||||
output = root / 'output'
|
||||
env['GITHUB_OUTPUT'] = str(output)
|
||||
subprocess.run(['bash', '-c', step('xbox', 'Pin and merge the APK source')], cwd=root / 'xbox', env=env, check=True, capture_output=True)
|
||||
base = output.read_text().strip().split('=', 1)[1]
|
||||
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'xbox')
|
||||
(root / 'backend').write_text('newer main, after backend build')
|
||||
git('commit', '-qam', 'main advanced again')
|
||||
env.update(BUILD_BASE_SHA=base, XBOX_SOURCE_TREE=tree)
|
||||
subprocess.run(['bash', '-c', step('build', 'Merge onto main, or say what conflicts')], cwd=root / 'apk', env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step('build', 'Verify backend and APK source match')], cwd=root / 'apk', env=env, check=True, capture_output=True)
|
||||
self.assertEqual((root / 'apk/backend').read_text(), 'merged backend')
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'apk'), tree)
|
||||
@@ -0,0 +1,131 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
xbox = runpy.run_path(str(BIN / 'droiddeck-xbox'))
|
||||
|
||||
|
||||
class XboxLaunchTest(unittest.TestCase):
|
||||
def test_other_stores_keep_their_existing_launch(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = Path(root)
|
||||
(folder / '.droiddeck-store.json').write_text(json.dumps({'store': 'gog', 'id': '1'}))
|
||||
self.assertIsNone(xbox['launch'](['/proton', 'waitforexitandrun', str(folder / 'Game.exe')], {}))
|
||||
|
||||
def test_renewal_retries_a_timeout_and_stops_after_rejection(self):
|
||||
stopped = unittest.mock.Mock()
|
||||
stopped.wait.side_effect = [False, False, False, AssertionError('renewed a rejected lease')]
|
||||
ask = unittest.mock.Mock(side_effect=[None, {'ok': True}, {'ok': False}])
|
||||
xbox['renew_lease'](ask, Path('/channel'), 'GAME', 'lease-1', stopped)
|
||||
self.assertEqual(ask.call_count, 3)
|
||||
|
||||
def test_stopping_a_launch_stops_renewal_without_another_request(self):
|
||||
stopped = threading.Event()
|
||||
stopped.set()
|
||||
ask = unittest.mock.Mock()
|
||||
xbox['renew_lease'](ask, Path('/channel'), 'GAME', 'lease-1', stopped)
|
||||
ask.assert_not_called()
|
||||
|
||||
def test_missing_store_detector_keeps_stock_launch(self):
|
||||
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
|
||||
with self.subTest(error=error), patch('runpy.run_path', side_effect=error):
|
||||
self.assertIsNone(xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {}))
|
||||
|
||||
def test_launch_uses_prepared_image_and_never_receives_account_credentials(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
runtime = root / 'runtime/windows'
|
||||
runtime.mkdir(parents=True)
|
||||
for name in xbox['DLLS']:
|
||||
(runtime / name).write_bytes(b'MZ')
|
||||
store = {'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}),
|
||||
'ask': unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1',
|
||||
'exe': '/private/Game.exe', 'playfab': 'game-token'})}
|
||||
close = unittest.mock.Mock()
|
||||
with patch('runpy.run_path', return_value=store), patch.dict(xbox['launch'].__globals__, RUNTIME=runtime.parent), \
|
||||
patch.dict(xbox['launch'].__globals__, bridge=lambda path: (1234, 'key', close)), \
|
||||
patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)):
|
||||
launch = xbox['launch']
|
||||
self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'],
|
||||
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale'}), 7)
|
||||
wine = launch.__globals__['wine']
|
||||
self.assertEqual(wine.call_args.args[0], ['/private/Game.exe'])
|
||||
env = wine.call_args.args[1]
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', env)
|
||||
self.assertEqual(env['XODUS_XSTS_PLAYFAB'], 'game-token')
|
||||
close.assert_called_once()
|
||||
self.assertEqual(store['ask'].call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
|
||||
|
||||
def test_bridge_start_failure_still_releases_the_lease(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
runtime = root / 'windows'
|
||||
runtime.mkdir()
|
||||
for name in xbox['DLLS']:
|
||||
(runtime / name).touch()
|
||||
ask = unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1'})
|
||||
with patch('runpy.run_path', return_value={'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}), 'ask': ask}), \
|
||||
patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=unittest.mock.Mock(side_effect=OSError('bind failed'))):
|
||||
with self.assertRaises(OSError):
|
||||
xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {'BL_LAUNCH_DIR': '/launch'})
|
||||
self.assertEqual(ask.call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
|
||||
|
||||
def test_bridge_authenticates_before_forwarding(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
path = str(Path(root) / 'service.sock')
|
||||
upstream = socket.socket(socket.AF_UNIX)
|
||||
upstream.bind(path); upstream.listen(1); upstream.settimeout(3)
|
||||
received = []
|
||||
def serve():
|
||||
connection, _ = upstream.accept()
|
||||
with connection:
|
||||
received.append(connection.recv(8))
|
||||
connection.sendall(b'reply')
|
||||
worker = threading.Thread(target=serve); worker.start()
|
||||
port, key, close = xbox['bridge'](path)
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1', port), timeout=2) as denied:
|
||||
denied.sendall(b'x' * 64)
|
||||
self.assertEqual(denied.recv(1), b'')
|
||||
with socket.create_connection(('127.0.0.1', port), timeout=2) as client:
|
||||
client.sendall(key[:20].encode())
|
||||
client.sendall(key[20:].encode() + b'request')
|
||||
self.assertEqual(client.recv(5), b'reply')
|
||||
worker.join(3)
|
||||
self.assertFalse(worker.is_alive())
|
||||
self.assertEqual(received, [b'request'])
|
||||
finally:
|
||||
close(); upstream.close()
|
||||
|
||||
def test_wine_wrapper_preserves_selected_proton_args_and_prefix_isolation(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
prefix = root / 'compat/pfx'
|
||||
prefix.mkdir(parents=True)
|
||||
runtime = root / 'runtime/windows'; runtime.mkdir(parents=True)
|
||||
for name in xbox['DLLS']:
|
||||
(runtime / name).write_bytes(b'MZ-synthetic')
|
||||
command = root / 'command.json'
|
||||
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe', '--custom', 'two words']))
|
||||
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command),
|
||||
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'XODUS_BRIDGE_KEY': 'runtime-key'}
|
||||
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', return_value=7) as call:
|
||||
initialize.return_value.returncode = 0
|
||||
self.assertEqual(xbox['wine'](['/private-view/Game.exe']), 7)
|
||||
argv = call.call_args.args[0]
|
||||
self.assertEqual(argv, ['/selected/proton', 'waitforexitandrun', '/private-view/Game.exe', '--custom', 'two words'])
|
||||
self.assertIn('xgameruntime=n', call.call_args.kwargs['env']['WINEDLLOVERRIDES'])
|
||||
self.assertEqual((prefix / 'drive_c/windows/system32/xgameruntime.dll').read_bytes(), b'MZ-synthetic')
|
||||
initialize.assert_called_once()
|
||||
for child in (initialize, call):
|
||||
child_env = child.call_args.kwargs['env']
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', child_env)
|
||||
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
|
||||
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
|
||||
Reference in new issue
Block a user