mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Merge origin/main into feat/target-sdk-36
This commit is contained in:
commit
c8baca10e6
980 files changed
+88652
-41628
No files matched your search
@@ -0,0 +1,83 @@
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define VK_PRESENT_H
|
||||
const char *vkp_gpu_name(void) { return "cache test"; }
|
||||
void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
|
||||
#include "vk_loader.h"
|
||||
struct vk_api g_vk;
|
||||
#include "effects_chain.c"
|
||||
|
||||
static unsigned views, sets, freed_views, freed_sets;
|
||||
static VkImageView bound_view;
|
||||
static VkResult VKAPI_CALL create_view(VkDevice dev, const VkImageViewCreateInfo *info,
|
||||
const VkAllocationCallbacks *alloc, VkImageView *out) {
|
||||
(void)dev; (void)alloc;
|
||||
assert(info->image != VK_NULL_HANDLE);
|
||||
*out = (VkImageView)(uintptr_t)(100 + ++views);
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
static VkResult VKAPI_CALL allocate_set(VkDevice dev, const VkDescriptorSetAllocateInfo *info,
|
||||
VkDescriptorSet *out) {
|
||||
(void)dev;
|
||||
assert(info->descriptorPool != VK_NULL_HANDLE && info->descriptorSetCount == 1);
|
||||
*out = (VkDescriptorSet)(uintptr_t)(200 + ++sets);
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
static void VKAPI_CALL update_set(VkDevice dev, uint32_t count, const VkWriteDescriptorSet *writes,
|
||||
uint32_t copies, const VkCopyDescriptorSet *copy) {
|
||||
(void)dev; (void)copies; (void)copy;
|
||||
assert(count == 1);
|
||||
bound_view = writes->pImageInfo->imageView;
|
||||
}
|
||||
static VkResult VKAPI_CALL free_set(VkDevice dev, VkDescriptorPool pool, uint32_t count,
|
||||
const VkDescriptorSet *set) {
|
||||
(void)dev; (void)pool;
|
||||
assert(pool != VK_NULL_HANDLE && count == 1 && *set != VK_NULL_HANDLE);
|
||||
freed_sets++;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
static void VKAPI_CALL destroy_view(VkDevice dev, VkImageView view, const VkAllocationCallbacks *alloc) {
|
||||
(void)dev; (void)alloc;
|
||||
assert(view != VK_NULL_HANDLE);
|
||||
freed_views++;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
g_dev = (VkDevice)(uintptr_t)1;
|
||||
g_dpool = (VkDescriptorPool)(uintptr_t)2;
|
||||
g_dsl = (VkDescriptorSetLayout)(uintptr_t)3;
|
||||
g_sampler = (VkSampler)(uintptr_t)4;
|
||||
g_vk.CreateImageView = create_view;
|
||||
g_vk.AllocateDescriptorSets = allocate_set;
|
||||
g_vk.UpdateDescriptorSets = update_set;
|
||||
g_vk.FreeDescriptorSets = free_set;
|
||||
g_vk.DestroyImageView = destroy_view;
|
||||
VkImage source = (VkImage)(uintptr_t)10;
|
||||
assert(scene_ensure(source, 1280, 720) == 0);
|
||||
VkImageView original = bound_view;
|
||||
if (!strcmp(argv[1], "recycled")) {
|
||||
vkp_effects_forget_image(source);
|
||||
assert(freed_sets == 1 && freed_views == 1);
|
||||
assert(scene_ensure(source, 1280, 720) == 0);
|
||||
assert(bound_view != original && views == 2 && sets == 2);
|
||||
} else if (!strcmp(argv[1], "unrelated")) {
|
||||
vkp_effects_forget_image((VkImage)(uintptr_t)11);
|
||||
vkp_effects_forget_image(VK_NULL_HANDLE);
|
||||
assert(scene_ensure(source, 1280, 720) == 0);
|
||||
assert(bound_view == original && views == 1 && !freed_views && !freed_sets);
|
||||
} else if (!strcmp(argv[1], "repeated")) {
|
||||
vkp_effects_forget_image(source);
|
||||
vkp_effects_forget_image(source);
|
||||
assert(freed_sets == 1 && freed_views == 1);
|
||||
} else {
|
||||
assert(!strcmp(argv[1], "resize"));
|
||||
assert(scene_ensure(source, 1920, 1080) == 0);
|
||||
assert(bound_view != original && views == 2 && freed_views == 1 && freed_sets == 1);
|
||||
}
|
||||
puts("PASS");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
int main(void) {
|
||||
int creator = semget(0x5eed0001, 1, IPC_CREAT | IPC_EXCL | 0600);
|
||||
if (creator < 0) { perror("semget"); return 1; }
|
||||
struct semid_ds ds;
|
||||
if (semctl(creator, 0, IPC_STAT, &ds) != 0 || ds.sem_otime != 0 || ds.sem_ctime == 0) {
|
||||
printf("FAIL: a new set has otime %ld ctime %ld\n", (long)ds.sem_otime, (long)ds.sem_ctime);
|
||||
return 1;
|
||||
}
|
||||
struct sembuf up = {0, 1, 0};
|
||||
if (semop(creator, &up, 1) != 0) { perror("semop"); return 1; }
|
||||
int other = semget(0x5eed0001, 1, 0600);
|
||||
if (other < 0 || semctl(other, 0, IPC_STAT, &ds) != 0 || ds.sem_otime == 0) {
|
||||
printf("FAIL: otime still 0 after semop\n");
|
||||
return 1;
|
||||
}
|
||||
if (semctl(other, 0, GETVAL) != 1) { printf("FAIL: value\n"); return 1; }
|
||||
semctl(creator, 0, IPC_RMID);
|
||||
printf("PASS: sysv otime\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
// Drives Java_com_termux_terminal_JNI_createSubprocess against a mock JNIEnv that tracks local
|
||||
// references the way ART does, so the JNI hygiene of app/src/main/cpp/termux/termux.c can be
|
||||
// checked on the host. Built and run by tools/tests/test_termux_jni.py.
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -26,7 +23,6 @@ static jsize mock_array_length(JNIEnv* TERMUX_UNUSED(env), jarray array)
|
||||
static jobject mock_get_element(JNIEnv* TERMUX_UNUSED(env), jobjectArray TERMUX_UNUSED(array), jsize TERMUX_UNUSED(index))
|
||||
{
|
||||
if (++live_refs > peak_refs) peak_refs = live_refs;
|
||||
// ART aborts the process here: "local reference table overflow (max=512)".
|
||||
if (live_refs > LOCAL_REF_LIMIT) overflowed = 1;
|
||||
return (jobject) malloc(1);
|
||||
}
|
||||
@@ -53,7 +49,6 @@ static void mock_release_utf(JNIEnv* TERMUX_UNUSED(env), jstring string, const c
|
||||
{
|
||||
for (size_t i = 0; i < sizeof(pinned) / sizeof(pinned[0]); i++) {
|
||||
if (pinned[i].owner != NULL && pinned[i].chars == chars) {
|
||||
// Releasing chars against some other string is a JNI contract violation.
|
||||
if (pinned[i].owner != string) mismatched_releases++;
|
||||
free(pinned[i].chars);
|
||||
pinned[i].owner = NULL;
|
||||
@@ -83,7 +78,6 @@ int main(int argc, char** argv)
|
||||
jsize arg_count = atoi(argv[1]);
|
||||
jsize env_count = atoi(argv[2]);
|
||||
|
||||
// The struct is JNINativeInterface in the NDK's header and JNINativeInterface_ in the JDK's.
|
||||
__typeof__(**(JNIEnv*) 0) table = {
|
||||
.GetArrayLength = mock_array_length,
|
||||
.GetObjectArrayElement = mock_get_element,
|
||||
@@ -97,7 +91,6 @@ int main(int argc, char** argv)
|
||||
};
|
||||
const __typeof__(table)* env = &table;
|
||||
|
||||
// Arrays are modelled as their length; the caller's own references are not counted.
|
||||
jsize args = arg_count, envs = env_count;
|
||||
jint pid_slot[1] = {0};
|
||||
jstring cmd = (jstring) "cmd", cwd = (jstring) "cwd";
|
||||
|
||||
@@ -46,7 +46,6 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
"""
|
||||
|
||||
# Shell builtins only: anything it ran would be an x86 program, handed back to it.
|
||||
HANDLER = "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$HANDLER_LOG\"\nexit 7\n"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SRC = ROOT / 'app' / 'src' / 'main' / 'cpp' / 'waylandcomp' / 'src'
|
||||
TOOLS = ROOT / 'tools' / 'cardboard'
|
||||
|
||||
|
||||
def spirv_words(header: str) -> list[str]:
|
||||
return re.findall(r'0x[0-9a-fA-F]{8}', header)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'needs a C compiler')
|
||||
class CardboardParamsTest(unittest.TestCase):
|
||||
def test_clamp_and_push_constant_layout(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-cardboard')
|
||||
subprocess.run(['cc', '-std=c11', '-Wall', '-Wextra', '-Werror', '-O2', '-DCARDBOARD_HOST_TEST',
|
||||
'-D_DEFAULT_SOURCE', f'-I{SRC}', f'-I{Path(folder)}', '-o', binary,
|
||||
str(TOOLS / 'test_cardboard_params.c'), str(SRC / 'cardboard.c'), '-lm'],
|
||||
check=True, cwd=folder, env=self._env(folder))
|
||||
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
|
||||
self.assertIn('PASS: cardboard params', result.stdout)
|
||||
|
||||
@staticmethod
|
||||
def _env(folder):
|
||||
import os
|
||||
stub = Path(folder) / 'vulkan'
|
||||
stub.mkdir(exist_ok=True)
|
||||
(stub / 'vulkan.h').write_text('typedef struct VkDevice_T *VkDevice; typedef struct VkImage_T *VkImage;\n'
|
||||
'typedef struct VkCommandBuffer_T *VkCommandBuffer;\n'
|
||||
'typedef struct { int unused; } VkPhysicalDeviceMemoryProperties;\n')
|
||||
return dict(os.environ)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which('glslangValidator'), 'needs glslangValidator')
|
||||
class CardboardShaderTest(unittest.TestCase):
|
||||
def test_committed_spirv_matches_the_glsl(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
out = Path(folder) / 'cardboard_frag.h'
|
||||
subprocess.run(['glslangValidator', '-V', '--vn', 'cardboard_frag_code', '-o', str(out),
|
||||
str(SRC / 'cardboard.frag')], check=True, capture_output=True)
|
||||
self.assertEqual(spirv_words(out.read_text()), spirv_words((SRC / 'cardboard_frag.h').read_text()),
|
||||
'cardboard_frag.h is stale: regenerate it from cardboard.frag (see cardboard.c)')
|
||||
|
||||
def test_push_constants_fit_the_guaranteed_range(self):
|
||||
glsl = (SRC / 'cardboard.frag').read_text()
|
||||
block = glsl[glsl.index('uniform PC {'):glsl.index('} pc;')]
|
||||
self.assertLessEqual(16 * len(re.findall(r'\bvec4\b', block)), 128)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Single-core Steam affinity is rechecked even if its thread count stayed the same."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
SOURCE = SCRIPT.read_text()
|
||||
FUNCTION = SOURCE[SOURCE.index('client_single_core_matches() {'):].split('\n}\n', 1)[0] + '\n}\n'
|
||||
|
||||
|
||||
class ClientCoreMaskTest(unittest.TestCase):
|
||||
def matches(self, wanted, tasks):
|
||||
return subprocess.run(['bash', '-c', FUNCTION + '\nclient_single_core_matches "$@"',
|
||||
'test', wanted, *map(str, tasks)], capture_output=True).returncode
|
||||
|
||||
def test_a_mask_change_without_a_new_thread_needs_repinning(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tasks = [Path(tmp) / str(i) for i in (1, 2)]
|
||||
for task in tasks:
|
||||
task.mkdir()
|
||||
(task / 'status').write_text('Name:\tsteam\nCpus_allowed_list:\t7\n')
|
||||
self.assertEqual(self.matches('7', tasks), 0)
|
||||
(tasks[1] / 'status').write_text('Name:\tsteam\nCpus_allowed_list:\t0-7\n')
|
||||
self.assertEqual(self.matches('7', tasks), 1)
|
||||
|
||||
def test_an_exited_thread_does_not_prevent_checking_live_threads(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
live = Path(tmp) / '1'
|
||||
live.mkdir()
|
||||
(live / 'status').write_text('Cpus_allowed_list:\t3-6\n')
|
||||
self.assertEqual(self.matches('7', [Path(tmp) / 'gone', live]), 1)
|
||||
|
||||
def test_multi_core_masks_keep_the_existing_thread_count_policy(self):
|
||||
self.assertEqual(self.matches('0,1,2,3', []), 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -13,8 +13,6 @@ class DesktopRemovalInventoryTest(unittest.TestCase):
|
||||
self.assertIn('usr/bin/lxqt-session', paths)
|
||||
self.assertIn('usr/bin/labwc', paths)
|
||||
self.assertIn('usr/local/bin/steamdeck-desktop', paths)
|
||||
# The runtime pacman database did not protect libseat on the Thor. Removing it
|
||||
# made gamescope and every Steam/native session exit 127 after desktop cleanup.
|
||||
self.assertNotIn('usr/lib/libseat.so.1', paths)
|
||||
self.assertNotIn('usr/lib/libseat.so', paths)
|
||||
self.assertFalse(any(p.startswith('usr/lib/libSDL2') for p in paths))
|
||||
|
||||
@@ -21,7 +21,6 @@ FAKE = r"""
|
||||
|
||||
int real_opendirs;
|
||||
|
||||
/* COARSE=1: directory stats that never change, like NTFS's whole-second times and fixed size. */
|
||||
static void coarse(const char *path, struct stat *st) {
|
||||
if (getenv("COARSE") && strstr(path, "/fuse/") && S_ISDIR(st->st_mode)) {
|
||||
st->st_mtim = st->st_ctim = (struct timespec){1, 0};
|
||||
@@ -70,7 +69,6 @@ int statfs(const char *path, struct statfs *out) {
|
||||
return r;
|
||||
}
|
||||
|
||||
/* FASTPATH=1: open directories the way the fast-path preload does, through fdopendir. */
|
||||
DIR *opendir(const char *path) {
|
||||
static DIR *(*next)(const char *);
|
||||
if (!next) next = dlsym(RTLD_NEXT, "opendir");
|
||||
|
||||
@@ -91,6 +91,37 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertFalse(path.exists(), "the request file is consumed")
|
||||
return json.loads((self.dir / "resp" / "req.json").read_text())
|
||||
|
||||
def vr_helper(self, body):
|
||||
helper = self.dir / "droiddeck-steamvr"
|
||||
helper.write_text("#!/bin/sh\n" + body)
|
||||
old = os.environ.get("DROIDDECK_VR_HELPER")
|
||||
os.environ["DROIDDECK_VR_HELPER"] = str(helper)
|
||||
self.addCleanup(lambda: os.environ.pop("DROIDDECK_VR_HELPER") if old is None
|
||||
else os.environ.__setitem__("DROIDDECK_VR_HELPER", old))
|
||||
return helper
|
||||
|
||||
def test_vr_status_is_parsed(self):
|
||||
self.vr_helper('echo "installed=1 running=0 installing=0 driver=1"\n')
|
||||
answer = self.ask({"kind": "vr", "action": "status"})
|
||||
self.assertTrue(answer["ok"])
|
||||
self.assertEqual((True, False, False, True),
|
||||
(answer["installed"], answer["running"], answer["installing"], answer["driver"]))
|
||||
|
||||
def test_vr_runs_only_its_own_actions(self):
|
||||
log = self.dir / "args"
|
||||
self.vr_helper('echo "$@" > %s\n' % log)
|
||||
self.assertTrue(self.ask({"kind": "vr", "action": "start"})["ok"])
|
||||
self.assertEqual("start", log.read_text().strip())
|
||||
answer = self.ask({"kind": "vr", "action": "rm -rf /"})
|
||||
self.assertFalse(answer["ok"])
|
||||
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
|
||||
|
||||
def test_vr_without_a_helper_is_unavailable(self):
|
||||
os.environ["DROIDDECK_VR_HELPER"] = str(self.dir / "missing")
|
||||
self.addCleanup(os.environ.pop, "DROIDDECK_VR_HELPER")
|
||||
answer = self.ask({"kind": "vr", "action": "status"})
|
||||
self.assertEqual("UNAVAILABLE", answer["error"]["code"])
|
||||
|
||||
def test_exec_output_and_status(self):
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
|
||||
self.assertTrue(answer["ok"])
|
||||
@@ -208,6 +239,22 @@ class AgentTest(unittest.TestCase):
|
||||
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
|
||||
self.assertEqual("NO_TARGET", missing["error"]["code"])
|
||||
|
||||
def test_steam_selection(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate:
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual(3180310, answer["appId"])
|
||||
self.assertIn("document.activeElement", evaluate.call_args.args[1])
|
||||
self.assertEqual("Steam Big Picture Mode", evaluate.call_args.kwargs["target"])
|
||||
|
||||
def test_steam_selection_allows_no_highlight(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": None}):
|
||||
self.assertIsNone(self.ask({"kind": "steam-selection"})["appId"])
|
||||
|
||||
def test_steam_selection_rejects_invalid_app_id(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "4294967296"}):
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual("INVALID_SELECTION", answer["error"]["code"])
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
|
||||
@@ -28,8 +28,6 @@ def load(name):
|
||||
ctl = load("droiddeckctl")
|
||||
scenario = load("droiddeck-scenario")
|
||||
|
||||
# A stand-in for adb: answers the provider's content calls from a JSON config (a list answers
|
||||
# successive calls), records every invocation, and fakes the few shell commands droiddeckctl uses.
|
||||
FAKE_ADB = textwrap.dedent('''\
|
||||
#!/usr/bin/env python3
|
||||
import base64, json, os, sys
|
||||
@@ -136,7 +134,6 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
"launch": {"ok": True, "command": "launch", "appId": "489830"},
|
||||
"state": [state(focused=769, focusable=[769]), state(focused=489830, focusable=[769])],
|
||||
})
|
||||
# Focus alone is not enough: the game must also be in the list Steam orders from.
|
||||
code, out = self.run_ctl("launch", "489830", "--wait", "--timeout", "1")
|
||||
self.assertEqual(5, code)
|
||||
self.assertEqual("TIMEOUT", out["error"]["code"])
|
||||
@@ -193,7 +190,7 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
|
||||
self.assertEqual(7, code)
|
||||
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
|
||||
self.assertIn("Debugging tools", out["error"]["message"])
|
||||
self.assertIn("Setup > Diagnostics > Debugging tools", out["error"]["message"])
|
||||
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
|
||||
|
||||
def test_override_checks_names_before_pushing_any_file(self):
|
||||
@@ -333,7 +330,7 @@ class ScenarioTest(FakeAdbTest):
|
||||
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 489830}]})
|
||||
code, report = self.run_scenario(path)
|
||||
self.assertEqual(1, code)
|
||||
self.assertEqual(1, len(report["runs"])) # stops at the first failure without --keep-going
|
||||
self.assertEqual(1, len(report["runs"]))
|
||||
self.assertIn("is 769", report["runs"][0]["error"])
|
||||
evidence = json.loads((Path(report["runs"][0]["folder"]) / "evidence.json").read_text())
|
||||
self.assertEqual(769, evidence["focus"]["focusedApp"])
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class EffectsSourceCacheTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if compiler is None:
|
||||
raise unittest.SkipTest('A host C compiler is required for the Vulkan cache test')
|
||||
candidates = [Path('/usr/include/vulkan'), Path('/opt/homebrew/include/vulkan')]
|
||||
for name in ('ANDROID_NDK_HOME', 'ANDROID_NDK_ROOT', 'NDK_HOME'):
|
||||
if os.environ.get(name):
|
||||
candidates.extend(Path(os.environ[name]).glob('toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan'))
|
||||
for sdk in {Path(os.environ.get('ANDROID_HOME', '/nonexistent')),
|
||||
Path(os.environ.get('ANDROID_SDK_ROOT', '/nonexistent')),
|
||||
Path.home() / 'Library/Android/sdk', Path.home() / 'Android/Sdk'}:
|
||||
candidates.extend(sdk.glob('ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan'))
|
||||
headers = next((p for p in candidates if (p / 'vulkan.h').is_file()), None)
|
||||
if headers is None:
|
||||
raise unittest.SkipTest('Vulkan headers from the Android NDK or system SDK are required')
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-effects-cache-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
folder = Path(cls.temp.name)
|
||||
shutil.copytree(headers, folder / 'include/vulkan', ignore=shutil.ignore_patterns('*.hpp'))
|
||||
if (headers.parent / 'vk_video').is_dir():
|
||||
shutil.copytree(headers.parent / 'vk_video', folder / 'include/vk_video')
|
||||
cls.binary = folder / 'cache-test'
|
||||
build = subprocess.run([compiler, '-std=c11', '-pthread', '-I' + str(folder / 'include'),
|
||||
'-I' + str(REPO / 'app/src/main/cpp/waylandcomp/src'),
|
||||
'-I' + str(REPO / 'app/src/main/cpp/shaders'),
|
||||
str(REPO / 'tools/tests/effects_source_cache_harness.c'),
|
||||
'-o', str(cls.binary)], capture_output=True, text=True)
|
||||
if build.returncode:
|
||||
raise RuntimeError(build.stderr)
|
||||
|
||||
def check_cache(self, case):
|
||||
result = subprocess.run([str(self.binary), case], check=True, capture_output=True, text=True)
|
||||
self.assertEqual('PASS', result.stdout.strip())
|
||||
|
||||
def test_recycled_image_handle_gets_a_new_view_and_descriptor(self):
|
||||
self.check_cache('recycled')
|
||||
|
||||
def test_unrelated_and_null_images_preserve_the_current_view(self):
|
||||
self.check_cache('unrelated')
|
||||
|
||||
def test_repeated_owner_invalidation_does_not_double_free(self):
|
||||
self.check_cache('repeated')
|
||||
|
||||
def test_resize_replaces_the_cached_view_and_descriptor(self):
|
||||
self.check_cache('resize')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -746,6 +746,16 @@ class SelectTest(SyncTestCase):
|
||||
self.assertFalse((root / "wanted.tsv").exists())
|
||||
self.assertFalse((root / "dist").exists())
|
||||
|
||||
def test_droiddeck_proton_has_esync_built_in(self):
|
||||
root = self.store()
|
||||
tool = make_tool(self.tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", builtin=True, ge=True, fsync=True)
|
||||
command, env, said = self.select(tool, self.env())
|
||||
self.assertEqual(command[0], str(tool / "proton"))
|
||||
self.assertNotIn("BL_SYNC_PACK", env)
|
||||
self.assertEqual(said, "droiddeck-esync: DroidDeck-Proton 11-7.5 has esync built in\n")
|
||||
self.assertFalse((root / "wanted.tsv").exists())
|
||||
self.assertFalse((root / "dist").exists())
|
||||
|
||||
def test_wanted_rows_are_deduplicated(self):
|
||||
root = self.store()
|
||||
tool = make_tool(self.tools, "GE-Proton11-7", GE_LINE, ge=True)
|
||||
@@ -906,6 +916,15 @@ class ReconcileTest(SyncTestCase):
|
||||
self.assertTrue(self.dist_of("ge-GE-Proton11-7-r1", ge).is_dir())
|
||||
self.assertIn("ge-GE-Proton11-7-r1", (root / "tools.tsv").read_text())
|
||||
|
||||
def test_droiddeck_proton_is_scanned_but_our_own_tools_are_not(self):
|
||||
steam = self.tmp / "steam"
|
||||
tools = steam / "compatibilitytools.d"
|
||||
ours = make_tool(tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", salt=b"dd", builtin=True, ge=True)
|
||||
make_tool(tools, "droiddeck-proton-arm64", salt=b"own")
|
||||
make_tool(tools, "droiddeck-proton-11-arm64", salt=b"own11")
|
||||
with mock.patch.dict(GLOBALS, {"SD_LIBRARY": str(self.tmp / "sd")}):
|
||||
self.assertEqual(SYNC["find_tools"](str(steam)), [str(ours)])
|
||||
|
||||
def test_steam_compatibility_reports_sync(self):
|
||||
steam = self.tmp / "steam"
|
||||
make_tool(steam / "steamapps/common", "Proton Experimental (ARM64)")
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef BACKEND
|
||||
int ioctl(int fd, unsigned long request, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, request);
|
||||
int *value = va_arg(ap, int *);
|
||||
va_end(ap);
|
||||
assert(fd == -1 && request == 0x12345678 && value);
|
||||
*value = 0x51;
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
#else
|
||||
int main(int argc, char **argv) {
|
||||
if (argc > 1) {
|
||||
int value = 0;
|
||||
assert(ioctl(-1, 0x12345678, &value) == -1);
|
||||
assert(value == 0x51 && errno == EACCES);
|
||||
} else {
|
||||
int fds[2];
|
||||
assert(pipe(fds) == 0);
|
||||
struct termios term;
|
||||
assert(ioctl(fds[0], TCGETS, &term) == -1 && errno == ENOTTY);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux" and shutil.which("gcc") and shutil.which("g++"),
|
||||
"needs Linux, gcc and g++")
|
||||
class FakeinputIoctlTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.addClassCleanup(cls.tmp.cleanup)
|
||||
cls.path = Path(cls.tmp.name)
|
||||
source = cls.path / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["gcc", "-o", str(cls.path / "program"), str(source)], check=True)
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-DBACKEND", "-o",
|
||||
str(cls.path / "backend.so"), str(source)], check=True)
|
||||
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread",
|
||||
"-std=c++17", "-static-libstdc++", "-static-libgcc",
|
||||
"-Wl,--exclude-libs,ALL", "-o", str(cls.path / "libfakeinput.so"),
|
||||
str(SOURCE), "-ldl"], check=True)
|
||||
|
||||
def run_program(self, backend=False):
|
||||
preload = str(self.path / "libfakeinput.so")
|
||||
args = [str(self.path / "program")]
|
||||
if backend:
|
||||
preload += ":" + str(self.path / "backend.so")
|
||||
args.append("backend")
|
||||
subprocess.run(args, env=dict(os.environ, LD_PRELOAD=preload), check=True, timeout=10)
|
||||
|
||||
def test_later_interposer_receives_arguments_and_returns_errno(self):
|
||||
self.run_program(backend=True)
|
||||
|
||||
def test_libc_passthrough_retains_kernel_error(self):
|
||||
self.run_program()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,3 +1,4 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -52,6 +53,72 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(env["REMOVE"], "inherited")
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
|
||||
|
||||
def test_component_profiles_override_general_and_restore_it_for_the_next_game(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
home = root / "home"
|
||||
component_dir = home / ".local/share/droiddeck-components"
|
||||
base = root / "proton"
|
||||
target = base / "files/lib/wine/dxvk/aarch64-windows/d3d11.dll"
|
||||
leftover = target.with_name("d3d8.dll")
|
||||
component_dir.mkdir(parents=True)
|
||||
target.parent.mkdir(parents=True)
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
general = root / "general.dll"
|
||||
game = root / "game.dll"
|
||||
general.write_text("general")
|
||||
game.write_text("game")
|
||||
target.write_text("old")
|
||||
leftover.write_text("old")
|
||||
digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
(component_dir / "desired.tsv").write_text(
|
||||
"*\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t%s\t%s\n"
|
||||
"42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t%s\t%s\n"
|
||||
"42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d8.dll\t-\t-\n"
|
||||
% (digest(general), general, digest(game), game)
|
||||
)
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "game")
|
||||
self.assertFalse(leftover.exists())
|
||||
|
||||
env["STEAM_COMPAT_DATA_PATH"] = "/steam/compatdata/43"
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "general")
|
||||
|
||||
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
component_dir = root / ".local/share/droiddeck-components"
|
||||
base = root / "proton"
|
||||
target = base / "files/lib/wine/dxvk/aarch64-windows/d3d11.dll"
|
||||
component_dir.mkdir(parents=True)
|
||||
target.parent.mkdir(parents=True)
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
rows = []
|
||||
for scope in ("*", "42", "4294967295", "2147483648"):
|
||||
source = root / ("default" if scope == "*" else scope)
|
||||
source.write_text(scope)
|
||||
rows.append("%s\tproton\tbuild-1\tdxvk\t%s\t%s\t%s\n" % (
|
||||
scope, target.relative_to(base),
|
||||
hashlib.sha256(source.read_bytes()).hexdigest(), source,
|
||||
))
|
||||
(component_dir / "desired.tsv").write_text("".join(rows))
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
for value in (
|
||||
"42", "00042", "43", "-1", "-0001", "4294967295", "-2147483648",
|
||||
"2147483648", "-1///", "0", "-0", "000", "-2147483649", "4294967296",
|
||||
"999999999999999999999999999", "not-an-id", "1+1", "",
|
||||
):
|
||||
with self.subTest(prefix=value):
|
||||
env = dict(os.environ, HOME=str(root), STEAM_COMPAT_DATA_PATH="/steam/compatdata/" + value)
|
||||
target.write_text("untouched")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True, capture_output=True)
|
||||
scope = MODULE["game_id"](env)
|
||||
expected = "untouched" if scope is None else scope if scope in {"42", "4294967295", "2147483648"} else "*"
|
||||
self.assertEqual(target.read_text(), expected)
|
||||
|
||||
def test_engine_fixes_follow_the_games_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
game = Path(tmp) / "Godot Game"
|
||||
@@ -109,6 +176,22 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfig": bad}, "42")
|
||||
|
||||
def test_game_texture_filtering_overrides_default_without_leaking(self):
|
||||
default = "d3d9.samplerAnisotropy = 16"
|
||||
game = "d3d9.samplerAnisotropy = 4"
|
||||
config = {
|
||||
"version": 1,
|
||||
"shared": {},
|
||||
"games": {},
|
||||
"dxvkConfig": default,
|
||||
"dxvkConfigGames": {"42": game, "43": ""},
|
||||
}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "42")["DXVK_CONFIG"], game)
|
||||
self.assertNotIn("DXVK_CONFIG", MODULE["apply_config"]({}, config, "43"))
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "44")["DXVK_CONFIG"], default)
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfigGames": []}, "42")
|
||||
|
||||
def test_game_ids_and_probes(self):
|
||||
for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"):
|
||||
self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))
|
||||
@@ -257,11 +340,40 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertIn('"$here/proton"', (extra / COMPAT["EXTRA_WRAPPER"]).read_text())
|
||||
self.assertIn("GE-Proton11-7", [entry["name"] for entry in COMPAT["tool_catalog"](str(home), None)])
|
||||
|
||||
def test_droiddeck_proton_is_adopted_and_labelled_like_any_other_extra(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
(home / "label").write_text("Compatible\n")
|
||||
COMPAT["display_name"].__globals__["LABEL_FILE"] = str(home / "label")
|
||||
tools = home / "compatibilitytools.d"
|
||||
extra = tools / "DroidDeck-Proton 11-7.5"
|
||||
extra.mkdir(parents=True)
|
||||
(extra / "proton").write_text("")
|
||||
(extra / "toolmanifest.vdf").write_text('"manifest" { "version" "2" "commandline" "/proton %verb%" "require_tool_appid" "4185400" }')
|
||||
(extra / "compatibilitytool.vdf").write_text(
|
||||
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-7.5" { "install_path" "." '
|
||||
'"display_name" "DroidDeck-Proton 11-7.5" "from_oslist" "windows" "to_oslist" "linux" } } }')
|
||||
COMPAT["build_tool"](str(tools / COMPAT["TOOL"]), None)
|
||||
protect = COMPAT["adopt_extras"](str(tools))
|
||||
self.assertEqual(protect, {"DroidDeck-Proton-11-7.5": "DroidDeck-Proton 11-7.5"})
|
||||
compat = (extra / "compatibilitytool.vdf").read_text()
|
||||
self.assertIn('"DroidDeck-Proton-11-7.5"', compat)
|
||||
self.assertIn('"display_name" "DroidDeck-Proton 11-7.5 (Compatible)"', compat)
|
||||
self.assertNotIn("require_tool_appid", (extra / "toolmanifest.vdf").read_text())
|
||||
self.assertIn('"$here/proton"', (extra / COMPAT["EXTRA_WRAPPER"]).read_text())
|
||||
catalog = COMPAT["tool_catalog"](str(home), None)
|
||||
self.assertIn({"name": "DroidDeck-Proton-11-7.5", "display": "DroidDeck-Proton 11-7.5 (Compatible)",
|
||||
"dir": "DroidDeck-Proton 11-7.5", "valve": False}, catalog)
|
||||
config = home / "config.vdf"
|
||||
config.write_text(config_text([("0", COMPAT["TOOL"]), ("42", "DroidDeck-Proton-11-7.5")]))
|
||||
COMPAT["register_default"](str(config), ["42", "43"], protect=protect)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5", "43": COMPAT["TOOL"]})
|
||||
changes, _ = COMPAT["plan_mapping"]({"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5"}, ["42"], [COMPAT["TOOL"]], COMPAT["TOOL"], {})
|
||||
self.assertEqual(changes, {"42": COMPAT["TOOL"]})
|
||||
|
||||
def test_both_proton_wrappers_call_environment_launcher(self):
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
# Started through bl_run, which execs it - or, for a store game with cloud saves, waits
|
||||
# for it so droiddeck-store-launch --exited can follow (test_store_launch.CloudHooks).
|
||||
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
|
||||
|
||||
def test_wrappers_preload_the_session_library_before_the_input_shim(self):
|
||||
@@ -319,6 +431,57 @@ class ProtonDefaultTest(unittest.TestCase):
|
||||
changes, auto = self.plan({"0": self.TOOL}, [], self.TOOL, {"10": self.TOOL})
|
||||
self.assertEqual((changes, auto), ({}, {}))
|
||||
|
||||
def test_per_game_proton_override_and_inherit_follow_steam_mappings(self):
|
||||
current = {"0": self.TOOL, "10": self.TOOL, "11": "GE-Proton11-7", "12": self.TOOL}
|
||||
overrides = {"10": "GE-Proton11-7", "11": None}
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, ["10", "11", "12"], self.NAMES, COMPAT["TOOL_11"],
|
||||
{"10": self.TOOL, "12": self.TOOL}, overrides=overrides)
|
||||
self.assertEqual(changes, {"0": COMPAT["TOOL_11"], "10": "GE-Proton11-7", "11": COMPAT["TOOL_11"], "12": COMPAT["TOOL_11"]})
|
||||
self.assertEqual(auto, {"11": COMPAT["TOOL_11"], "12": COMPAT["TOOL_11"]})
|
||||
|
||||
def test_per_game_requests_resolve_identity_and_defer_a_new_live_tool(self):
|
||||
requests = {
|
||||
"10": {"valve": False, "dir": "GE-Proton11-7"},
|
||||
"11": None,
|
||||
"12": {"valve": True, "dir": "Proton 11.0 (ARM64)"},
|
||||
"0": None,
|
||||
}
|
||||
self.assertEqual(
|
||||
COMPAT["requested_games"](requests, self.CATALOG),
|
||||
{"10": "GE-Proton11-7", "11": None, "12": COMPAT["TOOL_11"]},
|
||||
)
|
||||
self.assertEqual(
|
||||
COMPAT["requested_games"](requests, self.CATALOG, [self.TOOL, COMPAT["TOOL_11"]]),
|
||||
{"10": COMPAT["DEFERRED_GAME_TOOL"], "11": None, "12": COMPAT["TOOL_11"]},
|
||||
)
|
||||
|
||||
def test_missing_per_game_proton_is_preserved_during_default_registration(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "config.vdf"
|
||||
config.write_text(config_text([
|
||||
("0", self.TOOL),
|
||||
("10", "GE-Proton9-1"),
|
||||
("11", self.TOOL),
|
||||
]))
|
||||
(Path(tmp) / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": False, "dir": "GE-Proton9-1"},
|
||||
},
|
||||
}))
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), ["10", "11"], default=COMPAT["TOOL_11"],
|
||||
catalog=self.CATALOG, directory=tmp,
|
||||
)
|
||||
|
||||
self.assertEqual(mapping_of(config.read_text()), {
|
||||
"0": COMPAT["TOOL_11"],
|
||||
"10": "GE-Proton9-1",
|
||||
"11": COMPAT["TOOL_11"],
|
||||
})
|
||||
|
||||
def test_the_last_side_to_change_wins(self):
|
||||
state = {"default": self.TOOL, "applied": 5}
|
||||
default, state = COMPAT["choose_default"]("GE-Proton11-7", state, {"seq": 5, "dir": "Proton 11.0 (ARM64)", "valve": True}, self.CATALOG, now=100)
|
||||
@@ -396,8 +559,6 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
wine = self.tool / "files/bin-arm64/wine"
|
||||
wine.write_text("#!/bin/sh\necho wine-11.0-4c8f2e1 '(Staging)'\n")
|
||||
wine.chmod(0o755)
|
||||
# Proton's own winepulse.so names the audio interface: the classic table never imports
|
||||
# PsCreateSystemThread, the system-thread one (Proton-CachyOS) always does.
|
||||
(self.tool / "files/lib/wine/aarch64-unix").mkdir(parents=True)
|
||||
self.winepulse = self.tool / "files/lib/wine/aarch64-unix/winepulse.so"
|
||||
self.winepulse.write_bytes(b"\x7fELF classic wine 11 pulse driver")
|
||||
@@ -439,8 +600,6 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
result = self.run_setup()
|
||||
self.assertIn("DirectAudio selected", result.stderr)
|
||||
self.assertIn("WINEDLLPATH=%s/lib/wine" % self.audio, result.stdout)
|
||||
# Proton-CachyOS's mmdevapi takes the driver list from this variable, and its launcher
|
||||
# pre-sets it to pulse,alsa unless it is already set.
|
||||
self.assertIn("WINE_AUDIO_DRIVER=directaudio,pulse\n", result.stdout)
|
||||
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
|
||||
self.assertEqual(self.link("syswow64"), str(self.audio / "lib/wine/i386-windows/winedirectaudio.drv"))
|
||||
@@ -520,6 +679,28 @@ if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class StartWithoutSteamTest(unittest.TestCase):
|
||||
def test_start_without_steam_uses_umu_or_runinprefix_and_only_when_asked(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
ge = Path(tmp) / "ge/proton"
|
||||
ge.parent.mkdir()
|
||||
ge.write_text('if "UMU_ID" in os.environ:\n argv = [wine, "c:\\\\windows\\\\system32\\\\umu.exe"]\n')
|
||||
valve = Path(tmp) / "valve/proton"
|
||||
valve.parent.mkdir()
|
||||
valve.write_text('argv = [wine, "c:\\\\windows\\\\system32\\\\steam.exe"]\n')
|
||||
start = MODULE["start_without_steam"]
|
||||
game = [str(ge), "waitforexitandrun", "/games/Game.exe", "-windowed"]
|
||||
self.assertEqual(start(game, {}, "3384071994"), (game, {}))
|
||||
on = {"DROIDDECK_NO_STEAM": "1"}
|
||||
self.assertEqual(start(game, on, "3384071994"), (game, dict(on, UMU_ID="0")))
|
||||
self.assertEqual(start(game, on, "570940")[1]["UMU_ID"], "570940")
|
||||
self.assertEqual(start(game, dict(on, UMU_ID="umu-1"), "570940")[1]["UMU_ID"], "umu-1")
|
||||
plain = [str(valve)] + game[1:]
|
||||
self.assertEqual(start(plain, on, "570940"), ([str(valve), "runinprefix", "/games/Game.exe", "-windowed"], on))
|
||||
for other in ([str(ge), "run", "/x.exe"], [str(ge), "waitforexitandrun"], [str(valve), "getcompatpath", "/x"]):
|
||||
self.assertEqual(start(other, on, "570940"), (other, on))
|
||||
|
||||
|
||||
class ForceSsbsTest(unittest.TestCase):
|
||||
def test_libssbs_is_preloaded_only_when_asked_and_only_into_arm64_proton(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
MODULE = runpy.run_path(str(BIN / 'droiddeck-launcher-cores'))
|
||||
Holder = MODULE['Holder']
|
||||
Governor = MODULE['Governor']
|
||||
NICE = MODULE['NICE']
|
||||
|
||||
HELPER = 'C:\\Program Files\\Rockstar Games\\Social Club\\SocialClubHelper.exe'
|
||||
LAUNCHER = 'C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe'
|
||||
GAME = 'S:\\steamapps\\common\\Red Dead Redemption 2\\RDR2.exe'
|
||||
ALL = set(range(8))
|
||||
|
||||
|
||||
class FakeCores:
|
||||
"""Per-thread masks and priorities, with every change recorded."""
|
||||
|
||||
def __init__(self):
|
||||
self.state = {}
|
||||
self.calls = []
|
||||
|
||||
def own(self):
|
||||
return set(ALL)
|
||||
|
||||
def get(self, tid):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
return self.state[tid]
|
||||
|
||||
def set(self, tid, cpus, nice):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
self.calls.append((tid, set(cpus), nice))
|
||||
self.state[tid] = (set(cpus), nice)
|
||||
|
||||
|
||||
class LauncherCoresTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.proc = self.root / 'proc'
|
||||
self.proc.mkdir()
|
||||
cpufreq = self.root / 'cpu'
|
||||
for cpu in ALL:
|
||||
(cpufreq / f'cpu{cpu}/cpufreq').mkdir(parents=True)
|
||||
(cpufreq / f'cpu{cpu}/cpufreq/cpuinfo_max_freq').write_text('3532800\n' if cpu < 6 else '4320000\n')
|
||||
self.cores = FakeCores()
|
||||
self.holder = Holder(self.proc, cpufreq, self.cores)
|
||||
self.focus = self.root / 'focus.json'
|
||||
self.now = 0.0
|
||||
self.governor = Governor(self.focus, self.holder, clock=lambda: self.now)
|
||||
|
||||
def process(self, pid, argv0, threads=(), cpus=ALL, nice=0):
|
||||
directory = self.proc / str(pid)
|
||||
(directory / 'task').mkdir(parents=True)
|
||||
(directory / 'cmdline').write_bytes(argv0.encode() + b'\0--type=renderer\0')
|
||||
for tid in (pid, *threads):
|
||||
self.thread(pid, tid, cpus, nice)
|
||||
|
||||
def thread(self, pid, tid, cpus=ALL, nice=0):
|
||||
(self.proc / str(pid) / 'task' / str(tid)).mkdir()
|
||||
self.cores.state[tid] = (set(cpus), nice)
|
||||
|
||||
def end(self, pid):
|
||||
for tid in os.listdir(self.proc / str(pid) / 'task'):
|
||||
self.cores.state.pop(int(tid), None)
|
||||
(self.proc / str(pid) / 'task' / tid).rmdir()
|
||||
(self.proc / str(pid) / 'task').rmdir()
|
||||
(self.proc / str(pid) / 'cmdline').unlink()
|
||||
(self.proc / str(pid)).rmdir()
|
||||
|
||||
def focus_on(self, pid, app=1174180):
|
||||
stamp = getattr(self, 'stamp', 1_000_000_000) + 1_000_000_000
|
||||
self.stamp = stamp
|
||||
self.focus.write_text(json.dumps({
|
||||
'focusedApp': app, 'focusedWindow': 0x200001,
|
||||
'focusableWindows': [{'window': 0x100001, 'appId': 769, 'pid': 9},
|
||||
{'window': 0x200001, 'appId': app, 'pid': pid}]}))
|
||||
os.utime(self.focus, ns=(stamp, stamp))
|
||||
|
||||
def held(self, tid):
|
||||
return self.cores.state[tid] == ({5}, NICE)
|
||||
|
||||
def test_helpers_held_on_the_slow_clusters_last_core_while_the_game_has_focus(self):
|
||||
self.process(100, LAUNCHER, (101,))
|
||||
self.process(200, HELPER, (201, 202), nice=-2)
|
||||
self.process(300, HELPER, (301,))
|
||||
self.process(400, GAME, (401,))
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
for tid in (200, 201, 202, 300, 301):
|
||||
self.assertTrue(self.held(tid), tid)
|
||||
for tid in (100, 101, 400, 401):
|
||||
self.assertEqual((ALL, 0), self.cores.state[tid])
|
||||
|
||||
def test_launcher_focus_gives_each_thread_its_own_mask_and_priority_back(self):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER, (201,), cpus={0, 1, 2, 3}, nice=-2)
|
||||
self.cores.state[201] = ({6, 7}, 4)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(100)
|
||||
self.governor.tick()
|
||||
self.assertEqual(({0, 1, 2, 3}, -2), self.cores.state[200])
|
||||
self.assertEqual(({6, 7}, 4), self.cores.state[201])
|
||||
self.assertEqual({}, self.holder.held)
|
||||
|
||||
def test_nothing_is_touched_before_a_game_has_focus(self):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.governor.tick()
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.focus_on(100)
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
def test_a_launcher_left_after_its_game_stays_held_behind_the_client(self):
|
||||
self.process(200, HELPER)
|
||||
self.process(400, GAME)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.end(400)
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(200))
|
||||
|
||||
def test_a_thread_inheriting_the_hold_is_released_to_what_its_process_had(self):
|
||||
self.process(200, HELPER, cpus={0, 1, 2, 3, 4, 5}, nice=1)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.thread(200, 203, {5}, NICE)
|
||||
self.process(500, HELPER, (501,), cpus={5}, nice=NICE)
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
for tid in (200, 203, 500, 501):
|
||||
self.assertEqual(({0, 1, 2, 3, 4, 5}, 1), self.cores.state[tid], tid)
|
||||
|
||||
def test_a_held_thread_the_program_moves_back_is_held_again_on_the_next_look(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.cores.state[201] = (ALL, -5)
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertFalse(self.held(201))
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
self.assertEqual((ALL, 0), self.cores.state[201])
|
||||
|
||||
def test_a_steady_hold_is_not_rewritten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
calls = len(self.cores.calls)
|
||||
for _ in range(5):
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.assertEqual(calls, len(self.cores.calls))
|
||||
|
||||
def test_threads_that_end_are_skipped_and_ended_helpers_forgotten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(300, HELPER)
|
||||
self.process(400, GAME)
|
||||
del self.cores.state[201]
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertNotIn(201, self.holder.held[200])
|
||||
self.end(300)
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.assertEqual([200], list(self.holder.held))
|
||||
|
||||
def test_stop_releases(self):
|
||||
self.process(200, HELPER)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
with self.assertRaises(SystemExit):
|
||||
self.governor.stop()
|
||||
self.assertEqual((ALL, 0), self.cores.state[200])
|
||||
|
||||
def test_unreadable_focus_is_ignored(self):
|
||||
self.process(200, HELPER)
|
||||
self.focus.write_text('{"focusedApp": 1174')
|
||||
self.governor.tick()
|
||||
self.focus.write_text('[]')
|
||||
os.utime(self.focus, ns=(5, 5))
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
def test_window_without_a_pid_is_left_alone(self):
|
||||
self.process(200, HELPER)
|
||||
self.focus.write_text(json.dumps({'focusedApp': 1174180, 'focusedWindow': 7, 'focusableWindows': []}))
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -80,7 +80,7 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
token = self.suspend()
|
||||
self.assertTrue(self.preparing())
|
||||
self.state(token, "paused")
|
||||
self.state("0" * 32, "awake") # stale session acknowledgments cannot wake this one
|
||||
self.state("0" * 32, "awake")
|
||||
time.sleep(0.1)
|
||||
self.assertTrue(self.preparing())
|
||||
self.state(token, "awake")
|
||||
|
||||
@@ -119,6 +119,32 @@ class LayoutTest(unittest.TestCase):
|
||||
inst.select()
|
||||
self.assertEqual(inst.included_components, {"Up", "Wide"})
|
||||
|
||||
def test_a_duplicate_onto_the_file_itself_is_skipped(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "cab" / "dotnet.exe"
|
||||
src.parent.mkdir()
|
||||
src.write_bytes(b"MZ")
|
||||
out = Path(tmp) / "out"
|
||||
inst = installer({
|
||||
"Directory": rows("Directory Directory_Parent DefaultDir",
|
||||
("TARGETDIR", "", "SourceDir"),
|
||||
("ProgramFilesFolder", "TARGETDIR", "PFiles"),
|
||||
("DOTNETHOME", "ProgramFilesFolder", "dotnet"),
|
||||
("DOTNETHOME_X86", "ProgramFilesFolder", "dotnet")),
|
||||
"Component": rows("Component Directory_ Attributes Condition KeyPath",
|
||||
("Host", "DOTNETHOME", "0", "", "DotnetExe")),
|
||||
"Feature": rows("Feature Feature_Parent Level", ("Main", "", "1")),
|
||||
"FeatureComponents": rows("Feature_ Component_", ("Main", "Host")),
|
||||
"File": rows("File Component_ FileName", ("DotnetExe", "Host", "dotnet.exe")),
|
||||
"DuplicateFile": rows("FileKey Component_ File_ DestName DestFolder",
|
||||
("Dup", "Host", "DotnetExe", "", "DOTNETHOME_X86")),
|
||||
}, out=str(out))
|
||||
inst.select()
|
||||
inst.install_files({"DotnetExe": src})
|
||||
placed = out / "drive_c/Program Files (x86)/dotnet/dotnet.exe"
|
||||
self.assertEqual(placed.read_bytes(), b"MZ")
|
||||
self.assertEqual(inst.counts["files"], 1)
|
||||
|
||||
def test_global_assembly_paths(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
dll = Path(tmp) / "a.dll"
|
||||
@@ -240,13 +266,11 @@ class RegistryApplyTest(unittest.TestCase):
|
||||
text = (self.pfx / "system.reg").read_text()
|
||||
self.assertIn('"Version"="4.0"', text)
|
||||
self.assertIn('"Kept"="mine"', text)
|
||||
# Through the Wow6432Node\Classes link into the shared Classes\Wow6432Node key, never under the link.
|
||||
self.assertIn('[Software\\\\Classes\\\\Wow6432Node\\\\CLSID\\\\{X}]', text)
|
||||
self.assertNotIn('[Software\\\\Wow6432Node\\\\Classes\\\\CLSID', text)
|
||||
self.assertIn('"PATH"=str(2):"C:\\\\PhysX;%SystemRoot%\\\\system32;%SystemRoot%"', text)
|
||||
self.assertNotIn("[System\\\\CurrentControlSet\\\\", text)
|
||||
self.assertIn('"Opt"=dword:00000002', (self.pfx / "user.reg").read_text())
|
||||
# The prefix's own spelling of Program Files (x86) is kept.
|
||||
self.assertTrue((self.pfx / "drive_c/program files (x86)/Microsoft XNA/xna.dll").is_file())
|
||||
self.assertFalse((self.pfx / "drive_c/Program Files (x86)").exists())
|
||||
|
||||
|
||||
@@ -117,7 +117,6 @@ class NetworkObjectsTest(unittest.TestCase):
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x100)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x400)
|
||||
self.assertEqual(found[nm.ap_path(other["bssid"])][nm.NAME + ".AccessPoint"]["Flags"].unpack(), 0)
|
||||
# Keep nearby-network discovery while a cellular connection provides the default route.
|
||||
cellular = nm.objects(dict(CELLULAR, accessPoints=[other]))
|
||||
self.assertIn(nm.ap_path(other["bssid"]), cellular)
|
||||
self.assertEqual(cellular[nm.ROOT + "/Devices/Wifi"][nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), "/")
|
||||
@@ -131,7 +130,6 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.write(WIFI)
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
# Use the production service and only redirect its input file for the fixture.
|
||||
launch = "import runpy,sys; from pathlib import Path; n=runpy.run_path(sys.argv[1]); g=n['main'].__globals__; g['SNAPSHOT']=Path(sys.argv[2]); g['SCAN_REQUEST']=Path(sys.argv[2]).with_suffix('.request'); n['main']()"
|
||||
self.process = subprocess.Popen([sys.executable, "-c", launch, str(SCRIPT), str(self.snapshot)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
@@ -217,7 +215,6 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.assertTrue(any(interface == nm.OBJECT_MANAGER and member == "InterfacesRemoved" and args[0] == nm.AP
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(member == "AccessPointAdded" for _, _, member, _ in signals))
|
||||
# A missing/invalid snapshot is a transient input error, never a fake Ethernet handover.
|
||||
self.snapshot.write_text("{")
|
||||
time.sleep(1.2)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType"), "802-11-wireless")
|
||||
@@ -250,8 +247,6 @@ class NetworkBusTest(unittest.TestCase):
|
||||
from gi.repository import NM
|
||||
except ValueError:
|
||||
self.skipTest("requires gir1.2-nm-1.0")
|
||||
# libnm is a real consumer of the same API Steam reads. It caches objects by path,
|
||||
# so the handover must replace the Wi-Fi device with a modem rather than mutate its type.
|
||||
previous = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS")
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = os.environ["DBUS_SESSION_BUS_ADDRESS"]
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
PROOT = Path(__file__).resolve().parents[1] / "proot"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include "statx_mnt_id.h"
|
||||
|
||||
static int fdinfo_mnt_id(int fd, uint64_t *out) {
|
||||
char path[64], line[256];
|
||||
snprintf(path, sizeof path, "/proc/self/fdinfo/%d", fd);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return 0;
|
||||
int found = 0;
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
unsigned long long id;
|
||||
if (sscanf(line, "mnt_id:%llu", &id) == 1) {
|
||||
*out = (uint64_t)id;
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
return found;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
char name[] = "/tmp/droiddeck-statx-mnt-id-XXXXXX";
|
||||
int fd = mkstemp(name);
|
||||
if (fd < 0) return 1;
|
||||
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) < 0) return 2;
|
||||
uint64_t expected;
|
||||
if (!fdinfo_mnt_id(fd, &expected) || expected == 0) return 3;
|
||||
|
||||
/* Model a successful pre-5.8 statx: inode fields are present, MNT_ID is absent. */
|
||||
struct statx result = {0};
|
||||
result.stx_mask = STATX_TYPE | STATX_INO;
|
||||
result.stx_mode = st.st_mode;
|
||||
result.stx_ino = st.st_ino;
|
||||
result.stx_dev_major = major(st.st_dev);
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
unsigned flags = AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW;
|
||||
unsigned mask = STATX_TYPE | STATX_INO | STATX_MNT_ID;
|
||||
if (!droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", mask, &result)) return 4;
|
||||
if (!(result.stx_mask & STATX_MNT_ID) || result.stx_mnt_id != expected) return 5;
|
||||
|
||||
/* A reused fd can name the same inode number on another device. Inode alone is not identity. */
|
||||
result.stx_mask = STATX_TYPE | STATX_INO;
|
||||
result.stx_dev_major = major(st.st_dev) ^ 1U;
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", mask, &result)) return 6;
|
||||
if (result.stx_mask & STATX_MNT_ID) return 7;
|
||||
|
||||
/* Only ordinary MNT_ID is reconstructed; never claim the newer UNIQUE bit. */
|
||||
result.stx_ino = st.st_ino;
|
||||
result.stx_dev_major = major(st.st_dev);
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", 0x4000U, &result)) return 8;
|
||||
if (result.stx_mask & STATX_MNT_ID) return 9;
|
||||
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), AT_FDCWD, flags, "", mask, &result)) return 10;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), -1, flags, "", mask, &result)) return 11;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, AT_SYMLINK_NOFOLLOW, "", mask, &result)) return 12;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "file", mask, &result)) return 13;
|
||||
int stale = dup(fd);
|
||||
if (stale < 0 || close(stale) < 0) return 14;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), stale, flags, "", mask, &result)) return 15;
|
||||
|
||||
/* Pin the original referent, then reuse its tracee fd number. The pin's fdinfo stays stable,
|
||||
* while recovery against the reused number must reject the different inode/device. */
|
||||
char replacement_name[] = "/tmp/droiddeck-statx-mnt-id-replacement-XXXXXX";
|
||||
int replacement = mkstemp(replacement_name);
|
||||
if (replacement < 0) return 16;
|
||||
int pinned;
|
||||
char path[64];
|
||||
snprintf(path, sizeof path, "/proc/%ld/fd/%d", (long)getpid(), fd);
|
||||
pinned = open(path, O_PATH | O_CLOEXEC);
|
||||
if (pinned < 0) return 17;
|
||||
uint64_t pinned_mnt_id, pinned_ino;
|
||||
if (!droiddeck_proot_read_fdinfo(pinned, &pinned_mnt_id, &pinned_ino) ||
|
||||
pinned_mnt_id != expected || pinned_ino != st.st_ino) return 18;
|
||||
|
||||
struct stat replacement_st;
|
||||
if (fstat(replacement, &replacement_st) < 0) return 19;
|
||||
if (replacement_st.st_dev == st.st_dev && replacement_st.st_ino == st.st_ino) return 20;
|
||||
unlink(name);
|
||||
if (close(fd) < 0 || dup2(replacement, fd) != fd) return 21;
|
||||
close(replacement);
|
||||
unlink(replacement_name);
|
||||
|
||||
result.stx_mask = STATX_TYPE | STATX_INO;
|
||||
result.stx_ino = st.st_ino;
|
||||
result.stx_dev_major = major(st.st_dev);
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", mask, &result)) return 22;
|
||||
if (result.stx_mask & STATX_MNT_ID) return 23;
|
||||
if (!droiddeck_proot_read_fdinfo(pinned, &pinned_mnt_id, &pinned_ino) ||
|
||||
pinned_mnt_id != expected || pinned_ino != st.st_ino) return 24;
|
||||
|
||||
close(pinned);
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc") and sys.platform.startswith("linux"), "requires Linux and a C compiler")
|
||||
class ProotStatxMountIdTest(unittest.TestCase):
|
||||
def test_missing_mount_id_is_recovered_only_for_the_same_open_inode(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
source = Path(tmp) / "test.c"
|
||||
program = Path(tmp) / "test"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-I", str(PROOT), "-o", str(program), str(source)], check=True)
|
||||
subprocess.run([str(program)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,105 @@
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
EXTRA = runpy.run_path(str(BIN / "droiddeck-proton-extra"))
|
||||
GLOBALS = EXTRA["pick_asset"].__globals__
|
||||
|
||||
|
||||
def asset(name):
|
||||
return {"name": name, "browser_download_url": "https://github.com/o/r/releases/download/t/" + name}
|
||||
|
||||
|
||||
def droiddeck_release(ver, prerelease=False, draft=False):
|
||||
stem = "DroidDeck-Proton-%s-aarch64" % ver
|
||||
return {"tag_name": "DroidDeck-Proton-" + ver, "prerelease": prerelease, "draft": draft,
|
||||
"assets": [asset(stem + ".build-info.json"), asset(stem + ".sha512sum"), asset(stem + ".tar.gz")]}
|
||||
|
||||
|
||||
class ProtonExtraTest(unittest.TestCase):
|
||||
def test_sources_and_their_arm64_assets(self):
|
||||
self.assertEqual(list(EXTRA["SOURCES"]), ["ge", "cachyos", "droiddeck"])
|
||||
repo, pattern = EXTRA["SOURCES"]["droiddeck"]
|
||||
self.assertEqual(repo, "The412Banner/DroidDeck-Proton")
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
|
||||
|
||||
def test_the_newest_full_release_with_its_sha512_file(self):
|
||||
releases = [droiddeck_release("11-8", prerelease=True), droiddeck_release("11-7.9", draft=True), droiddeck_release("11-7.5")]
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: releases}):
|
||||
tag, url, sums = EXTRA["pick_asset"]("droiddeck")
|
||||
self.assertEqual(tag, "DroidDeck-Proton-11-7.5")
|
||||
self.assertTrue(url.endswith("/DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(sums.endswith("/DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: [droiddeck_release("11-8", prerelease=True)]}):
|
||||
self.assertEqual(EXTRA["pick_asset"]("droiddeck"), (None, None, None))
|
||||
|
||||
def test_a_tagged_release_is_fetched_by_its_tag(self):
|
||||
asked = []
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: asked.append(url) or droiddeck_release("11-7.5")}):
|
||||
tag, url, sums = EXTRA["release_asset"]("droiddeck", "DroidDeck-Proton-11-7.5")
|
||||
self.assertEqual(asked, ["https://api.github.com/repos/The412Banner/DroidDeck-Proton/releases/tags/DroidDeck-Proton-11-7.5"])
|
||||
self.assertTrue(url.endswith(".tar.gz") and sums.endswith(".sha512sum"))
|
||||
|
||||
def test_a_ge_style_sha512_file_verifies_the_download(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tarball = Path(tmp) / "DroidDeck-Proton-11-7.5-aarch64.tar.gz"
|
||||
tarball.write_bytes(b"tarball")
|
||||
line = "%s %s\n" % (hashlib.sha512(b"tarball").hexdigest(), tarball.name)
|
||||
|
||||
class Reply(io.BytesIO):
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
with mock.patch.object(GLOBALS["urllib"].request, "urlopen", lambda req, timeout: Reply(line.encode())), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
EXTRA["verify"](str(tarball), "https://example/sums")
|
||||
self.assertIn("checksum ok", said.getvalue())
|
||||
self.assertTrue(tarball.exists())
|
||||
bad = "%s %s\n" % ("0" * 128, tarball.name)
|
||||
with mock.patch.object(GLOBALS["urllib"].request, "urlopen", lambda req, timeout: Reply(bad.encode())), \
|
||||
contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit):
|
||||
EXTRA["verify"](str(tarball), "https://example/sums")
|
||||
self.assertFalse(tarball.exists())
|
||||
|
||||
def test_a_top_folder_with_a_space_is_installed_under_its_own_name(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "src" / "DroidDeck-Proton 11-7.5"
|
||||
(src / "files/bin").mkdir(parents=True)
|
||||
(src / "proton").write_text("#!/usr/bin/python3\n")
|
||||
(src / "toolmanifest.vdf").write_text('"manifest" { "commandline" "/proton %verb%" }')
|
||||
(src / "compatibilitytool.vdf").write_text(
|
||||
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-7.5" { "install_path" "." '
|
||||
'"display_name" "DroidDeck-Proton 11-7.5" } } }')
|
||||
(src / "version").write_text("1791000000 DroidDeck-Proton-11-7.5\n")
|
||||
tarball = Path(tmp) / "DroidDeck-Proton-11-7.5-aarch64.tar.gz"
|
||||
with tarfile.open(tarball, "w:gz") as tar:
|
||||
tar.add(src, arcname=src.name)
|
||||
steam = Path(tmp) / "Steam"
|
||||
adopted = []
|
||||
real = subprocess.call
|
||||
fake = lambda args, **kw: adopted.append(args) or 0 if args[0] == "steam-compatibility" else real(args, **kw)
|
||||
with mock.patch.object(GLOBALS["subprocess"], "call", fake), contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
with mock.patch.object(GLOBALS["sys"], "argv", ["droiddeck-proton-extra", str(steam), str(tarball)]):
|
||||
EXTRA["main"]()
|
||||
tools = steam / "compatibilitytools.d"
|
||||
self.assertEqual(sorted(os.listdir(tools)), [".droiddeck-download", "DroidDeck-Proton 11-7.5"])
|
||||
self.assertTrue((tools / "DroidDeck-Proton 11-7.5" / "toolmanifest.vdf").is_file())
|
||||
self.assertEqual(adopted, [["steam-compatibility", str(steam)]])
|
||||
self.assertIn("droiddeck-proton-extra: installed DroidDeck-Proton 11-7.5\n", said.getvalue())
|
||||
self.assertEqual(EXTRA["installed"](str(tools)), ["DroidDeck-Proton 11-7.5"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,23 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
QUEST = Path(__file__).resolve().parents[1] / 'quest'
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'linux' and shutil.which('gcc'), 'needs Linux and gcc')
|
||||
class QuestKgslTest(unittest.TestCase):
|
||||
def test_allocation_passthrough_translation_and_cleanup(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-kgsl')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-Werror', '-O2', '-o', binary,
|
||||
str(QUEST / 'test_kgsl_compat.c'), str(QUEST / 'kgsl_compat.c')], check=True)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
|
||||
self.assertIn('PASS: 12 GPUOBJ', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -55,6 +55,20 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_changed_quest_source_rejects_old_outputs(self):
|
||||
source = self.root / 'tools/quest/kgsl_compat.c'
|
||||
source.parent.mkdir(parents=True)
|
||||
source.write_text('old compatibility code')
|
||||
runtime.record(self.root)
|
||||
source.write_text('new compatibility code')
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_missing_quest_driver_cannot_be_attested(self):
|
||||
(self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'quest1.tzst'):
|
||||
runtime.record(self.root)
|
||||
|
||||
def test_modified_prebuilt_binary_is_rejected(self):
|
||||
runtime.record(self.root)
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
|
||||
|
||||
@@ -22,6 +22,28 @@ GAME_SCRIPT = r'''"InstallScript"
|
||||
}
|
||||
'''
|
||||
|
||||
VULKAN_SCRIPT = r'''"InstallScript"
|
||||
{
|
||||
"Run Process"
|
||||
{
|
||||
"Vulkan111080"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\1174180"
|
||||
"process 1" "%INSTALLDIR%\\Redistributables\\VulkanRT-1.1.108.0-Installer.exe"
|
||||
"command 1" "/S"
|
||||
"NoCleanUp" "0"
|
||||
}
|
||||
"RockstarLauncher"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Rockstar Games\\Steam\\Launcher"
|
||||
"process 1" "%INSTALLDIR%\\Redistributables\\Rockstar-Games-Launcher.exe"
|
||||
"command 1" "/s /t"
|
||||
"NoCleanUp" "0"
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SeedRedistsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -91,6 +113,44 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.run_seed()
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
|
||||
def rdr2(self):
|
||||
path = self.steam / "steamapps/common/Red Dead Redemption 2/installscript.vdf"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(VULKAN_SCRIPT)
|
||||
(self.steam / "steamapps/appmanifest_1174180.acf").write_text('"AppState" { "installdir" "Red Dead Redemption 2" }')
|
||||
|
||||
def test_a_vulkan_runtime_installer_is_left_to_run(self):
|
||||
self.rdr2()
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertNotIn("Vulkan111080", reg)
|
||||
self.assertIn('"RockstarLauncher"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_a_vulkan_marker_an_earlier_seeding_wrote_comes_out_once(self):
|
||||
self.rdr2()
|
||||
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080"
|
||||
self.reg.write_text(
|
||||
"WINE REGISTRY Version 2\n"
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791729070\n#time=1dd598d29161f72\n"
|
||||
'"Other"=dword:00000001\n"Vulkan111080"=dword:00000001\n'
|
||||
"\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791729070\n"
|
||||
'"Vulkan111080"=dword:00000001\n'
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\22380] 1791311644\n"
|
||||
'"Vulkan111080"=dword:00000001\n')
|
||||
(self.reg.parent / ".droiddeck-redists").write_text(marker + "\n")
|
||||
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertEqual(reg.count('"Vulkan111080"'), 1, "only the other app's value stays")
|
||||
self.assertIn('"Other"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
with self.reg.open("a") as out:
|
||||
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791730000\n"Vulkan111080"=dword:00000001\n')
|
||||
self.run_seed()
|
||||
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Exercise the literal launch prefix from SessionService without an Android runtime.
|
||||
|
||||
This is a focused source/exec regression check, not a Kotlin or PRoot integration
|
||||
test. PRoot executes the first guest argument directly; KEY=VALUE is meaningful
|
||||
only after /usr/bin/env. Read the production prefix rather than duplicate it.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
|
||||
SERVICE = Path(__file__).resolve().parents[2] / (
|
||||
"app/src/main/java/com/droiddeck/launcher/session/SessionService.kt")
|
||||
|
||||
VARIANTS = Path(__file__).resolve().parents[1] / "release/variants.txt"
|
||||
PACKAGES = [line.split()[1] for line in VARIANTS.read_text().splitlines()
|
||||
if line.strip() and not line.startswith("#")]
|
||||
|
||||
|
||||
def guest_prefix(package):
|
||||
source = SERVICE.read_text()
|
||||
before_environment = source.split("val guest = ArrayList<String>()", 1)[1].split(
|
||||
"addClientEnvironment(guest, steamHere)", 1)[0]
|
||||
environment = source.split("private fun addClientEnvironment(", 1)[1].split(
|
||||
'guest.add("HOME=/root")', 1)[0]
|
||||
prefix = []
|
||||
for line in (before_environment + environment).splitlines():
|
||||
line = line.strip()
|
||||
if not line.startswith("guest.add("):
|
||||
continue
|
||||
expression = line[len("guest.add("):-1]
|
||||
match = re.fullmatch(r'("[^"\\]*")(?: \+ (.+))?', expression)
|
||||
if match is None:
|
||||
raise AssertionError("Launch prefix changed; update its regression harness: " + line)
|
||||
value = json.loads(match[1])
|
||||
if match[2]:
|
||||
if match[2] != "com.droiddeck.launcher.runtime.BwrapSpawner.socket(this)":
|
||||
raise AssertionError("Unexpected dynamic launch-prefix argument: " + line)
|
||||
value += package + ".bwrap"
|
||||
prefix.append(value)
|
||||
return prefix
|
||||
|
||||
|
||||
class SessionGuestCommandTest(unittest.TestCase):
|
||||
def test_env_is_the_executable_for_every_package(self):
|
||||
for package in PACKAGES:
|
||||
with self.subTest(package=package):
|
||||
self.assertEqual(["/usr/bin/env", "-i"], guest_prefix(package)[:2])
|
||||
|
||||
@unittest.skipUnless(Path("/usr/bin/env").is_file(), "needs /usr/bin/env")
|
||||
def test_child_receives_its_package_socket_after_environment_is_cleared(self):
|
||||
for package in PACKAGES:
|
||||
with self.subTest(package=package):
|
||||
result = subprocess.run(
|
||||
guest_prefix(package), capture_output=True, text=True, check=True,
|
||||
timeout=5, env={"DROIDDECK_BWRAP_SOCKET": "wrong.bwrap", "STALE_HOST": "1"})
|
||||
self.assertEqual(
|
||||
["DROIDDECK_BWRAP_SOCKET=" + package + ".bwrap"],
|
||||
result.stdout.splitlines())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,95 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
STEAM = ["mangohud.Ab3dE6gH", ".com.valvesoftware.Steam.x1Y2z3/", "steam_chrome_shmem_uid10480_0", "steamADfAnd/"]
|
||||
CHROMIUM = ["scoped_dir3yu9Xt/SingletonSocket"]
|
||||
APPIMAGE = ["droiddeck-appimage.19PoOD"]
|
||||
BUS = ["dbus-1zWfOP1IaR="]
|
||||
KDE = ["plasma-csd-generator.BVWIWA/"]
|
||||
STALE = STEAM + CHROMIUM + APPIMAGE + BUS + KDE
|
||||
KEPT = ["droiddeck-mangohud.conf", ".X11-unix/", "steamworks", "steamABCDEF/inside", "notes.txt",
|
||||
"mangohud.conf", ".wine-10480/", "dbus-1zWfOP1IaR.log", "dbus-notasocket",
|
||||
"plasma-csd-generator.CQGZSw/kept"]
|
||||
|
||||
|
||||
def sweep_function(tmp):
|
||||
match = re.search(r"^clear_stale_tmp\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0).replace("find /tmp ", "find %s " % tmp)
|
||||
|
||||
|
||||
class SessionTmpTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.root, True)
|
||||
self.tmp = self.root / "tmp"
|
||||
self.tmp.mkdir()
|
||||
for name in STALE + KEPT:
|
||||
path = self.tmp / name
|
||||
if name.endswith("/"):
|
||||
path.mkdir(parents=True)
|
||||
elif name.endswith("="):
|
||||
listener = socket.socket(socket.AF_UNIX)
|
||||
listener.bind(str(self.tmp / name[:-1]))
|
||||
listener.close()
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("x")
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
|
||||
def sweep(self, running=""):
|
||||
pgrep = self.bin / "pgrep"
|
||||
pgrep.write_text("#!/bin/sh\nprintf '%s' '" + running + "'\n")
|
||||
pgrep.chmod(0o755)
|
||||
env = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]))
|
||||
return subprocess.run(["bash", "-c", sweep_function(self.tmp) + "clear_stale_tmp"], env=env,
|
||||
capture_output=True, text=True, timeout=30, check=True).stdout
|
||||
|
||||
def exists(self, name):
|
||||
return os.path.lexists(self.tmp / name.rstrip("=").split("/")[0])
|
||||
|
||||
def test_what_killed_sessions_left_goes_and_nothing_else(self):
|
||||
self.assertEqual("== /tmp: cleared 8 entries earlier sessions left\n", self.sweep())
|
||||
for name in STALE:
|
||||
self.assertFalse(self.exists(name), name)
|
||||
for name in KEPT:
|
||||
self.assertTrue((self.tmp / name).exists(), name)
|
||||
|
||||
def kept_while(self, running, owned):
|
||||
self.sweep(running)
|
||||
for name in STALE:
|
||||
self.assertEqual(name in owned, self.exists(name), name)
|
||||
|
||||
def test_a_running_client_keeps_its_own(self):
|
||||
self.kept_while("1234 /root/.local/share/Steam/steamrtarm64/steam -gamepadui\n", STEAM)
|
||||
|
||||
def test_a_running_chromium_keeps_its_singleton(self):
|
||||
self.kept_while("88 /opt/Heroic/heroic --type=renderer --enable-features=x\n", CHROMIUM)
|
||||
|
||||
def test_a_running_appimage_keeps_its_stamp(self):
|
||||
self.kept_while("77 /bin/bash /usr/local/bin/droiddeck-appimage-run /root/Apps/X.AppImage\n", APPIMAGE)
|
||||
|
||||
def test_a_running_session_bus_keeps_its_socket(self):
|
||||
self.kept_while("66 dbus-daemon --config-file=/usr/share/dbus-1/session.conf --nofork --session\n", BUS)
|
||||
|
||||
def test_the_system_bus_is_not_a_session_bus(self):
|
||||
self.kept_while("55 dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork\n", [])
|
||||
|
||||
def test_a_running_desktop_keeps_its_decorations(self):
|
||||
self.kept_while("44 kwin_wayland --xwayland\n", KDE)
|
||||
|
||||
def test_a_clean_tmp_says_nothing(self):
|
||||
self.sweep()
|
||||
self.assertEqual("", self.sweep())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -208,6 +208,33 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual((state["pending"], state.get("applied", 0)), (TOOL_11, 0))
|
||||
self.assertTrue(self.helper.request_waiting())
|
||||
|
||||
def test_per_game_customize_and_inherit_apply_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"},
|
||||
"11": None,
|
||||
},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL_11), ("11", TOOL)])
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_missing_per_game_proton_stays_deferred_live(self):
|
||||
page = FakePage({"0": TOOL, "10": "GE-Proton9-1", "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": False, "dir": "GE-Proton9-1"},
|
||||
"11": None,
|
||||
},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("11", TOOL)])
|
||||
self.assertEqual(page.mapping["10"], "GE-Proton9-1")
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_file_mode_defers_to_the_live_helper(self):
|
||||
(self.state / "live.pid").write_text("%d\n" % os.getpid())
|
||||
self.assertTrue(COMPAT["live_helper_running"]())
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Desktop Steam stays on KDE; explicit Big Picture still switches sessions."""
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
|
||||
|
||||
class DesktopSteamLaunchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.session = self.root / 'session'
|
||||
self.session.mkdir()
|
||||
self.env = dict(os.environ, HOME=str(self.root), XDG_DATA_HOME=str(self.root / 'data'),
|
||||
XDG_CACHE_HOME=str(self.root / 'cache'), BL_DESKTOP='1',
|
||||
BL_LAUNCH_DIR=str(self.session))
|
||||
supervisor = self.root / 'supervisor'
|
||||
supervisor.write_text('#!/bin/bash\nprintf "%s\\n" "$BL_INSIDE" "$BL_STEAM_UI" "$DISPLAY" "$@"\n')
|
||||
supervisor.chmod(0o755)
|
||||
self.launcher = self.root / 'launch'
|
||||
self.launcher.write_text((BIN / 'droiddeck-steam-launch').read_text().replace(
|
||||
'/usr/local/bin/droiddeck-session', str(supervisor)))
|
||||
|
||||
def launch(self, *args):
|
||||
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
|
||||
text=True, capture_output=True)
|
||||
|
||||
def test_desktop_keeps_display_and_does_not_request_session_switch(self):
|
||||
self.env['DISPLAY'] = ':7'
|
||||
result = self.launch('desktop')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), ['1', 'desktop', ':7', 'steam', 'steam://open/library'])
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_desktop_game_url_goes_to_client(self):
|
||||
result = self.launch('desktop', '501590')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines()[-1], 'steam://rungameid/501590')
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_second_click_forwards_without_another_supervisor(self):
|
||||
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
|
||||
lock.parent.mkdir(parents=True)
|
||||
steam = self.root / 'data/Steam/steamrtarm64/steam'
|
||||
steam.parent.mkdir(parents=True)
|
||||
steam.write_text('#!/bin/bash\nprintf "%s\\n" "$@"\n')
|
||||
steam.chmod(0o755)
|
||||
(self.root / '.steam').mkdir()
|
||||
os.mkfifo(self.root / '.steam/steam.pipe')
|
||||
(self.root / '.steam/steam.pid').write_text(str(os.getpid()))
|
||||
with lock.open('w') as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
result = self.launch('desktop', 'steam://open/settings')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), ['-nobigpicture', '-no-cef-sandbox', '-cef-ozone-platform=x11',
|
||||
'-cef-disable-gpu', 'steam://open/settings'])
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_second_click_waits_for_steam_ipc_during_startup(self):
|
||||
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
|
||||
lock.parent.mkdir(parents=True)
|
||||
steam = self.root / 'data/Steam/steamrtarm64/steam'
|
||||
steam.parent.mkdir(parents=True)
|
||||
marker = self.root / 'forwarded'
|
||||
steam.write_text(f'#!/bin/bash\ntouch "{marker}"\n')
|
||||
steam.chmod(0o755)
|
||||
with lock.open('w') as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
process = subprocess.Popen(['bash', str(self.launcher), 'desktop'], env=self.env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
time.sleep(0.7)
|
||||
self.assertIsNone(process.poll())
|
||||
self.assertFalse(marker.exists())
|
||||
(self.root / '.steam').mkdir()
|
||||
(self.root / '.steam/steam.pid').write_text(str(os.getpid()))
|
||||
os.mkfifo(self.root / '.steam/steam.pipe')
|
||||
_, stderr = process.communicate(timeout=3)
|
||||
self.assertEqual(process.returncode, 0, stderr)
|
||||
self.assertTrue(marker.exists())
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.communicate()
|
||||
|
||||
def test_big_picture_requests_explicit_handoff(self):
|
||||
result = self.launch('bigpicture')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.session / 'steam-launch').read_text(), 'ui=bigpicture\nurl=\n')
|
||||
|
||||
def test_outside_desktop_preserves_session_request(self):
|
||||
self.env.pop('BL_DESKTOP')
|
||||
result = self.launch('desktop', 'steam://open/settings')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.session / 'steam-launch').read_text(),
|
||||
'ui=desktop\nurl=steam://open/settings\n')
|
||||
|
||||
def test_invalid_target_cannot_trigger_a_handoff(self):
|
||||
self.assertEqual(self.launch('desktop', 'bad').returncode, 64)
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_cef_software_is_scoped_to_the_kde_client(self):
|
||||
source = (BIN / 'droiddeck-session').read_text()
|
||||
setup = source[source.index(' _bl_ui=(-gamepadui)'):source.index(' if [ "${BL_STEAM_UI:-}" != desktop ]; then')]
|
||||
for desktop, ui, software in [('1', 'desktop', True), ('1', 'bigpicture', False), ('', 'desktop', False)]:
|
||||
with self.subTest(desktop=desktop, ui=ui):
|
||||
env = dict(self.env, BL_DESKTOP=desktop, BL_STEAM_UI=ui)
|
||||
result = subprocess.check_output(['bash', '-c', setup + '\nprintf "%s\\n" "${_bl_cef[@]}"'],
|
||||
env=env, text=True)
|
||||
self.assertEqual('-cef-disable-gpu' in result, software)
|
||||
self.assertEqual('-cef-use-angle=vulkan' in result, not software)
|
||||
@@ -25,7 +25,6 @@ class SteamInstallTest(unittest.TestCase):
|
||||
self.requests = self.root / 'requests'
|
||||
self.bin = self.root / 'bin'
|
||||
self.bin.mkdir()
|
||||
# Only the network is faked: exercise real manifest parsing, checksums and zip extraction.
|
||||
curl = self.bin / 'curl'
|
||||
curl.write_text('''#!/bin/bash
|
||||
set -eu
|
||||
@@ -33,7 +32,6 @@ printf '%s\\n' "$2" >> "$TEST_REQUESTS"
|
||||
cp "$TEST_CDN/${2##*/}" "$4"
|
||||
''')
|
||||
curl.chmod(0o755)
|
||||
# macOS has shasum; the guest and Linux CI have sha256sum.
|
||||
if shutil.which('sha256sum') is None:
|
||||
sha = self.bin / 'sha256sum'
|
||||
sha.write_text('#!/bin/bash\nexec shasum -a 256 "$@"\n')
|
||||
@@ -78,7 +76,6 @@ cp "$TEST_CDN/${2##*/}" "$4"
|
||||
self.assert_installed()
|
||||
|
||||
def test_an_install_from_another_branch_is_left_for_steam_to_move(self):
|
||||
# An older app could install publicbeta; droiddeck-session moves the client at its start.
|
||||
self.assert_installed()
|
||||
requests = self.requests.read_text()
|
||||
(self.steam / 'package/beta').write_text('publicbeta\n')
|
||||
|
||||
@@ -37,7 +37,6 @@ def value(text, *path):
|
||||
STEAM = ('Registry', 'HKCU', 'Software', 'Valve', 'Steam', 'language')
|
||||
GLOBAL = ('Registry', 'HKCU', 'Software', 'Valve', 'Steamsteamglobal', 'language')
|
||||
|
||||
# As the client leaves it on a device (trimmed): both keys, other values beside them, and HKLM.
|
||||
CLIENT = '''"Registry"
|
||||
{
|
||||
"HKLM"
|
||||
|
||||
@@ -172,7 +172,6 @@ class ShortcutsTest(unittest.TestCase):
|
||||
self.assertEqual('Example: Renamed', entry['AppName'])
|
||||
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
|
||||
self.assertEqual('-dx11', entry['LaunchOptions'])
|
||||
# One shortcut, the same appid.
|
||||
self.assertEqual([APPID], list(self.run_writer(game)))
|
||||
|
||||
def test_a_target_chosen_in_the_app_updates_the_same_shortcut(self):
|
||||
|
||||
@@ -14,6 +14,8 @@ DISPLAY = MODULE['DISPLAY']
|
||||
seed_native_resolution = MODULE['seed_native_resolution']
|
||||
initialize_native_resolution = MODULE['initialize_native_resolution']
|
||||
NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION']
|
||||
seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game']
|
||||
initialize_screensaver = MODULE['initialize_screensaver']
|
||||
|
||||
|
||||
class SteamUiScaleTest(unittest.TestCase):
|
||||
@@ -151,3 +153,60 @@ class SteamNativeResolutionTest(unittest.TestCase):
|
||||
initialize_native_resolution(self.root)
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
self.assertFalse(self.marker.exists())
|
||||
|
||||
|
||||
class SteamScreensaverTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.config = self.root / 'config/config.vdf'
|
||||
self.config.parent.mkdir()
|
||||
self.marker = self.config.with_name('droiddeck-screensaver-initialized')
|
||||
|
||||
def in_game(self, text):
|
||||
return parse(text).get('InstallConfigStore').get('Customization').get('Screensaver').get('WhileInGame')
|
||||
|
||||
def test_fresh_client_shows_no_screensaver_over_a_game(self):
|
||||
self.assertTrue(initialize_screensaver(self.root))
|
||||
self.assertEqual('0', self.in_game(self.config.read_text()))
|
||||
self.assertTrue(self.marker.exists())
|
||||
|
||||
def test_it_goes_beside_the_screensaver_the_user_picked(self):
|
||||
text = ('"InstallConfigStore"\n{\n\t"Customization"\n\t{\n\t\t"Screensaver"\n\t\t{\n'
|
||||
'\t\t\t"CurrentScreensaver"\t\t"steam-bouncinglogo"\n\t\t}\n\t}\n}\n')
|
||||
updated, changed = seed_no_screensaver_in_game(text)
|
||||
self.assertTrue(changed)
|
||||
screensaver = parse(updated).get('InstallConfigStore').get('Customization').get('Screensaver')
|
||||
self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver'))
|
||||
self.assertEqual('0', screensaver.get('WhileInGame'))
|
||||
self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated)
|
||||
|
||||
def test_users_choice_is_kept(self):
|
||||
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }'
|
||||
self.assertEqual((text, False), seed_no_screensaver_in_game(text))
|
||||
|
||||
def test_turning_it_back_on_survives_restart(self):
|
||||
initialize_screensaver(self.root)
|
||||
text = '"InstallConfigStore" { "Customization" { } }'
|
||||
self.config.write_text(text)
|
||||
self.assertFalse(initialize_screensaver(self.root))
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
|
||||
def test_every_seeded_setting_lands_in_one_valid_config(self):
|
||||
initialize(self.root, 2340, 1080)
|
||||
initialize_native_resolution(self.root)
|
||||
initialize_screensaver(self.root)
|
||||
store = parse(self.config.read_text()).get('InstallConfigStore')
|
||||
self.assertIsNotNone(store.get('UI').get('display').get(DISPLAY))
|
||||
self.assertEqual('1', store.get('Gamescope').get(NATIVE_RESOLUTION))
|
||||
self.assertEqual('0', store.get('Customization').get('Screensaver').get('WhileInGame'))
|
||||
|
||||
def test_invalid_config_is_never_rewritten_or_marked_initialized(self):
|
||||
for text in ('"InstallConfigStore" {', '"InstallConfigStore" { "Customization" "bad" }',
|
||||
'"InstallConfigStore" { "Customization" { "Screensaver" "bad" } }'):
|
||||
self.config.write_text(text)
|
||||
with self.assertRaises(ValueError):
|
||||
initialize_screensaver(self.root)
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
self.assertFalse(self.marker.exists())
|
||||
@@ -10,6 +10,7 @@ import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
|
||||
@@ -55,7 +56,6 @@ class Detection(unittest.TestCase):
|
||||
def test_anything_else_is_left_alone(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root)
|
||||
# The exe of a store game is one too (a GOG game without a launcher); a stray file is not.
|
||||
self.assertEqual(folder, store.find_store_game([str(folder / 'Metalstorm.exe')])[0])
|
||||
self.assertIsNone(store.find_store_game([str(Path(root) / 'elsewhere/readme.txt')]))
|
||||
(folder / '.droiddeck-store.json').unlink()
|
||||
@@ -64,15 +64,16 @@ class Detection(unittest.TestCase):
|
||||
def test_only_epic_asks_for_a_code(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog')
|
||||
# Cloud saves off: nothing else to ask for either.
|
||||
sc = json.loads((folder / '.droiddeck-store.json').read_text()); sc['cloud'] = False
|
||||
(folder / '.droiddeck-store.json').write_text(json.dumps(sc))
|
||||
os.environ['BL_LAUNCH_DIR'] = str(Path(root) / 'session')
|
||||
try:
|
||||
self.assertEqual(0, store.main([str(folder / '.droiddeck-launch.bat')]))
|
||||
with patch.object(store, 'ask', return_value={'ready': False, 'reason': 'off'}) as ask:
|
||||
self.assertEqual(0, store.main([str(folder / '.droiddeck-launch.bat')]))
|
||||
self.assertEqual('gog-achievements', ask.call_args.args[1]['op'])
|
||||
finally:
|
||||
del os.environ['BL_LAUNCH_DIR']
|
||||
self.assertFalse((Path(root) / 'session/stores').exists())
|
||||
|
||||
|
||||
|
||||
class Asking(unittest.TestCase):
|
||||
@@ -133,7 +134,6 @@ class Prefix(unittest.TestCase):
|
||||
text = self.reg.read_text()
|
||||
self.assertIn('[Software\\\\Wine\\\\WineBrowser] ', text)
|
||||
self.assertIn('"Browsers"="/usr/local/bin/droiddeck-open-url,xdg-open"', text)
|
||||
# A second launch adds nothing: the last word already says so.
|
||||
store.provision_prefix(str(self.compat))
|
||||
self.assertEqual(text, self.reg.read_text())
|
||||
|
||||
@@ -155,7 +155,6 @@ class Choices(unittest.TestCase):
|
||||
folder = game(root)
|
||||
sidecar = json.loads((folder / '.droiddeck-store.json').read_text())
|
||||
self.assertEqual({'eos': True, 'offline': False}, store.options(sidecar))
|
||||
# An earlier build's overlay field is read past.
|
||||
self.assertEqual({'eos': True, 'offline': False}, store.options({'epic': {'v': 2, 'overlay': True}}))
|
||||
sidecar['epic'] = {'eos': True, 'offline': True}
|
||||
sidecar['cloud'] = False
|
||||
@@ -172,7 +171,6 @@ class Choices(unittest.TestCase):
|
||||
finally:
|
||||
del os.environ['BL_LAUNCH_DIR']
|
||||
del os.environ['STEAM_COMPAT_DATA_PATH']
|
||||
# Offline: no request was made and no code is left; the old overlay pointer is gone.
|
||||
self.assertFalse((Path(root) / 'session/stores/req').exists())
|
||||
self.assertFalse((folder / '.droiddeck-epic-code').exists())
|
||||
text = reg.read_text()
|
||||
@@ -197,7 +195,6 @@ class Browser(unittest.TestCase):
|
||||
|
||||
class ExeTarget(unittest.TestCase):
|
||||
def test_a_game_started_by_its_exe_is_found_from_a_subfolder(self):
|
||||
# Most GOG games have no launcher .bat: Steam runs the exe, which may sit in a subfolder.
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207664643')
|
||||
(folder / 'bin/x64').mkdir(parents=True)
|
||||
@@ -219,15 +216,15 @@ class CloudHooks(unittest.TestCase):
|
||||
original = store.ask
|
||||
asked = []
|
||||
store.ask = lambda channel, request, timeout=5.0: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'}
|
||||
# 10: the launcher waits for Proton and calls --exited afterwards.
|
||||
self.assertEqual(store.STORE_GAME, store.main([bat]))
|
||||
self.assertEqual(0, store.main(['--exited', bat]))
|
||||
finally:
|
||||
store.ask = original
|
||||
del os.environ['BL_LAUNCH_DIR']
|
||||
self.assertEqual({'op': 'cloud-down', 'store': 'gog', 'id': '1207664643'}, asked[0][0])
|
||||
self.assertEqual(store.CLOUD_TIMEOUT, asked[0][1])
|
||||
self.assertEqual('cloud-up', asked[1][0]['op'])
|
||||
self.assertEqual('gog-achievements', asked[0][0]['op'])
|
||||
self.assertEqual({'op': 'cloud-down', 'store': 'gog', 'id': '1207664643'}, asked[1][0])
|
||||
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
|
||||
self.assertEqual('cloud-up', asked[2][0]['op'])
|
||||
|
||||
def test_cloud_off_or_amazon_runs_proton_as_before(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
@@ -260,3 +257,60 @@ class Launchers(unittest.TestCase):
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
|
||||
class GogAchievements(unittest.TestCase):
|
||||
def test_cloud_off_still_prepares_the_gog_companion(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog')
|
||||
sidecar = json.loads((folder / store.SIDECAR).read_text())
|
||||
sidecar['cloud'] = False
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
with patch.dict(os.environ, {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat', 'BL_STORE_PROTON': '/chosen/proton'}), patch.object(store, 'ask', return_value={'ready': True}) as ask, patch.object(store, 'provision_galaxy', return_value='ready') as provision:
|
||||
self.assertEqual(0, store.main([str(folder / store.LAUNCHER)]))
|
||||
ask.assert_called_once()
|
||||
provision.assert_called_once_with(root + '/compat', '/chosen/proton')
|
||||
|
||||
def test_unavailable_companion_does_not_provision_or_block_the_game(self):
|
||||
with patch.object(store, 'ask', return_value=None), patch.object(store, 'provision_galaxy') as provision:
|
||||
self.assertFalse(store.prepare_gog({'id': '1', 'achievements': False}, '/pfx', '/session'))
|
||||
provision.assert_not_called()
|
||||
|
||||
def test_a_fresh_prefix_is_bootstrapped_before_marking_success(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
base = Path(root)
|
||||
tools = base / 'tools'; tools.mkdir()
|
||||
for name in ('GalaxyCommunication.exe', 'update-permissions.exe', 'version'):
|
||||
(tools / name).write_text(name)
|
||||
proton = base / 'proton'; proton.write_text('selected Proton')
|
||||
data = base / 'compat'
|
||||
seen = []
|
||||
def run(argv, **kwargs):
|
||||
self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c'], argv[:5])
|
||||
bat = Path(argv[5][2:].replace('\\', '/'))
|
||||
text = bat.read_text()
|
||||
seen.append(text)
|
||||
self.assertIn('goto existing', text)
|
||||
self.assertIn('update-permissions.exe', text)
|
||||
result = text.split('echo ready>"')[1].split('"')[0]
|
||||
Path(result[2:].replace('\\', '/')).write_text('ready')
|
||||
(data / 'pfx').mkdir(parents=True)
|
||||
(data / 'pfx/system.reg').write_text('Wine registry')
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
with patch.object(store, 'COMET_DIR', tools), patch.object(store.subprocess, 'run', side_effect=run):
|
||||
self.assertEqual('ready', store.provision_galaxy(str(data), str(proton)))
|
||||
self.assertTrue((data / 'pfx/.droiddeck-comet-service').is_file())
|
||||
self.assertEqual('ready', store.provision_galaxy(str(data), str(proton)))
|
||||
self.assertEqual(1, len(seen))
|
||||
__import__('shutil').rmtree(data / 'pfx')
|
||||
self.assertEqual('ready', store.provision_galaxy(str(data), str(proton)))
|
||||
self.assertEqual(2, len(seen))
|
||||
|
||||
def test_failed_service_install_is_not_marked_done(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
base = Path(root)
|
||||
for name in ('GalaxyCommunication.exe', 'update-permissions.exe', 'version', 'proton'):
|
||||
(base / name).write_text(name)
|
||||
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())
|
||||
@@ -0,0 +1,25 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / 'linuxfs' / 'preload'
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'linux' and shutil.which('gcc'), 'needs Linux and gcc')
|
||||
class SysvPreloadTest(unittest.TestCase):
|
||||
def test_semop_sets_otime_for_waiters(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-sysv')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary,
|
||||
str(Path(__file__).resolve().parent / 'sysv_otime_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=10, env=env)
|
||||
self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -59,8 +59,6 @@ class TermuxJniTest(unittest.TestCase):
|
||||
return {key: int(value) for key, value in re.findall(r"(\w+)=(\d+)", line)}
|
||||
|
||||
def test_a_long_argv_and_environment_stay_under_the_local_reference_limit(self):
|
||||
# 300 + 300 is under 512 for each loop on its own but over it together, as the issue says:
|
||||
# ART aborts with "local reference table overflow (max=512)".
|
||||
stats = self.run_harness(300, 300)
|
||||
self.assertEqual(stats["overflowed"], 0, stats)
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ class WinComponentsTest(unittest.TestCase):
|
||||
self.pick("vc")
|
||||
self.apply()
|
||||
self.assertEqual(installer.read_bytes(), b"ours")
|
||||
self.apply() # a second launch keeps the first backup, not ours
|
||||
self.apply()
|
||||
self.pick()
|
||||
names, notes = self.apply()
|
||||
self.assertEqual(installer.read_bytes(), b"from a real installer")
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
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 <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *ctl;
|
||||
static size_t size, page;
|
||||
static volatile int stop;
|
||||
static unsigned char *shared;
|
||||
|
||||
static long status(const char *key) {
|
||||
FILE *f = fopen("/proc/self/status", "r");
|
||||
char line[256];
|
||||
long v = -1;
|
||||
while (f && fgets(line, sizeof(line), f))
|
||||
if (!strncmp(line, key, strlen(key))) v = atol(line + strlen(key));
|
||||
if (f) fclose(f);
|
||||
return v;
|
||||
}
|
||||
|
||||
static void request(char mode) {
|
||||
int fd = open(ctl, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0 || write(fd, &mode, 1) != 1) exit(3);
|
||||
close(fd);
|
||||
kill(getpid(), SIGURG);
|
||||
}
|
||||
|
||||
static uint64_t sum(const unsigned char *p, size_t n) {
|
||||
uint64_t s = 0;
|
||||
for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i];
|
||||
return s;
|
||||
}
|
||||
|
||||
static void *writer(void *arg) {
|
||||
unsigned char *mine = shared + (size_t)(uintptr_t)arg * (size / 4);
|
||||
for (unsigned char round = 1; !stop; round++) {
|
||||
for (size_t i = 0; i < size / 4; i += page) {
|
||||
if (round > 1 && mine[i] != (unsigned char)(round - 1)) {
|
||||
printf("corrupt\n");
|
||||
exit(4);
|
||||
}
|
||||
mine[i] = round;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
ctl = argv[1];
|
||||
size = strtoul(argv[2], NULL, 0) << 20;
|
||||
int cycles = atoi(argv[3]);
|
||||
page = (size_t)sysconf(_SC_PAGESIZE);
|
||||
unsigned char *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
for (size_t i = 0; i < size; i++) data[i] = (unsigned char)(i * 7 + i / 4096);
|
||||
uint64_t before = sum(data, size);
|
||||
shared = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
memset(shared, 0, size);
|
||||
pthread_t t[2];
|
||||
for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i);
|
||||
struct sigaction sa;
|
||||
sigaction(SIGURG, NULL, &sa);
|
||||
printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0);
|
||||
if (argc > 4) {
|
||||
unsigned char *ro = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
memset(ro, 0x5a, size);
|
||||
mprotect(ro, size, PROT_READ);
|
||||
madvise(ro, size, 21);
|
||||
printf("elsewhere %ld\n", status("VmSwap:"));
|
||||
request('0');
|
||||
printf("back %ld\n", status("VmSwap:"));
|
||||
}
|
||||
for (int c = 0; c < cycles; c++) {
|
||||
request('1');
|
||||
printf("out %ld\n", status("VmSwap:"));
|
||||
request('0');
|
||||
printf("back %ld\n", status("VmSwap:"));
|
||||
}
|
||||
stop = 1;
|
||||
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
|
||||
printf("intact %d\n", sum(data, size) == before);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def swap_total_kb():
|
||||
for line in Path("/proc/meminfo").read_text().splitlines():
|
||||
if line.startswith("SwapTotal:"):
|
||||
return int(line.split()[1])
|
||||
return 0
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class ZramPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.dir = Path(tempfile.mkdtemp())
|
||||
cls.ctl = cls.dir / "ctl"
|
||||
build = cls.dir / "build"
|
||||
build.mkdir()
|
||||
(build / "program.c").write_text(PROGRAM)
|
||||
cls.lib = build / "libblsession.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DZR_CTL=\"%s\"" % cls.ctl,
|
||||
"-o", str(cls.lib), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
|
||||
cls.steam = cls.dir / "steam"
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.steam), str(build / "program.c")], check=True)
|
||||
cls.game = cls.dir / "game"
|
||||
shutil.copy(cls.steam, cls.game)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.dir, True)
|
||||
|
||||
def setUp(self):
|
||||
self.ctl.write_text("0")
|
||||
|
||||
def run_program(self, program=None, mb=48, cycles=1, *extra):
|
||||
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
|
||||
result = subprocess.run([str(program or self.steam), str(self.ctl), str(mb), str(cycles), *extra], env=environment,
|
||||
capture_output=True, text=True, check=True, timeout=120)
|
||||
out = {}
|
||||
for line in result.stdout.splitlines():
|
||||
key, value = line.split()
|
||||
out.setdefault(key, []).append(int(value))
|
||||
return out
|
||||
|
||||
def test_only_the_client_takes_the_signal(self):
|
||||
self.assertEqual([1], self.run_program()["handler"])
|
||||
self.assertEqual([0], self.run_program(self.game)["handler"])
|
||||
|
||||
def test_nothing_is_installed_without_the_control_file(self):
|
||||
self.ctl.unlink()
|
||||
try:
|
||||
self.assertEqual([0], self.run_program(cycles=0)["handler"])
|
||||
finally:
|
||||
self.ctl.write_text("0")
|
||||
|
||||
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
|
||||
def test_pages_out_and_reads_back(self):
|
||||
out = self.run_program(mb=48)
|
||||
self.assertGreater(out["out"][0], 32 * 1024)
|
||||
self.assertLess(out["back"][0], out["out"][0] // 4)
|
||||
self.assertEqual([1], out["intact"])
|
||||
|
||||
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
|
||||
def test_reads_back_what_the_kernel_swapped_elsewhere(self):
|
||||
out = self.run_program(None, 32, 0, "read-only")
|
||||
self.assertGreater(out["elsewhere"][0], 16 * 1024)
|
||||
self.assertLess(out["back"][0], out["elsewhere"][0] // 4)
|
||||
|
||||
def test_memory_stays_intact_under_writers(self):
|
||||
out = self.run_program(mb=32, cycles=6)
|
||||
self.assertEqual([1], out["intact"])
|
||||
self.assertEqual(6, len(out["out"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user