Merge #570 (PowerVR + Xclipse system Vulkan) into the non-Adreno test branch

# Conflicts:
#	.github/workflows/build.yml
#	app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
#	app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
#	tools/build_local.sh
#	tools/dxvk/build.sh
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-session
#	tools/release/runtime_inputs.py
#	tools/tests/test_runtime_inputs.py
This commit is contained in:
The412Banner committed 2026-10-12 18:34:02 -04:00
commit 56dc433673
104 files changed
+7206 -206

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
#define _GNU_SOURCE
#include <assert.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
/* Only the device/driver boundary is simulated. Descriptors and their lifetimes are real.
* F_DUPFD_QUERY is modelled so this test also runs on older CI kernels; the device probe
* separately exercises the actual query on Android. */
#define TEST_FD_LIMIT 65536
static _Atomic unsigned identities[TEST_FD_LIMIT];
static unsigned identity_serial = 1;
static int identity_denied, kgsl_present;
static int kernel_error = EINVAL;
static int native_imports, native_exports, native_closes;
static const char *driver_name = "pvr";
static const char *pvr_node = "/dev/dri/renderD129";
static int fixture_stat(const char *path, struct stat *st);
static long fixture_syscall(long number, ...);
static int fixture_fcntl(int fd, int op, int arg);
static void *fixture_dlsym(void *object, const char *name);
static int fixture_close(int fd);
#define stat(path, st) fixture_stat(path, st)
#define syscall fixture_syscall
#define fcntl fixture_fcntl
#define dlsym fixture_dlsym
#define close fixture_close
#include "../linuxfs/preload/drm.c"
#undef stat
#undef syscall
#undef fcntl
#undef dlsym
#undef close
static int test_open(const char *path) {
int fd = open(path, O_RDWR | O_CLOEXEC);
assert(fd >= 0 && fd < TEST_FD_LIMIT);
identities[fd] = identity_serial++;
return fd;
}
static int fixture_close(int fd) {
if (fd >= 0 && fd < TEST_FD_LIMIT) identities[fd] = 0;
return close(fd);
}
static int fixture_stat(const char *path, struct stat *st) {
if (!strcmp(path, "/dev/kgsl-3d0")) {
if (kgsl_present) return stat("/dev/zero", st);
errno = ENOENT;
return -1;
}
if (!strcmp(path, pvr_node)) return stat("/dev/null", st);
if (!strcmp(path, "/dev/dri/renderD128")) return stat("/dev/zero", st);
if (!strncmp(path, "/dev/dri/", 9)) { errno = ENOENT; return -1; }
return stat(path, st);
}
/* The intercepted DRM calls all take an integer argument. Keep that contract
* explicit; native_import's argument-free F_GETFD uses libc after #undef above. */
static int fixture_fcntl(int fd, int op, int arg) {
if (op == F_DUPFD_QUERY) {
if (identity_denied) { errno = EINVAL; return -1; }
if (fd < 0 || arg < 0 || fd >= TEST_FD_LIMIT || arg >= TEST_FD_LIMIT ||
!identities[fd] || !identities[arg]) { errno = EBADF; return -1; }
return identities[fd] == identities[arg];
}
int ret = fcntl(fd, op, arg);
if (ret >= 0 && (op == F_DUPFD || op == F_DUPFD_CLOEXEC)) {
assert(ret < TEST_FD_LIMIT);
identities[ret] = identities[fd];
}
return ret;
}
static long fixture_syscall(long number, ...) {
va_list ap;
va_start(ap, number);
if (number == SYS_ioctl) {
(void)va_arg(ap, int);
unsigned long request = va_arg(ap, unsigned long);
struct bl_drm_version *v = va_arg(ap, void *);
assert(request == BL_DRM_VERSION);
snprintf(v->name, v->name_len, "%s", driver_name);
v->name_len = strlen(driver_name);
va_end(ap);
return 0;
}
va_end(ap);
assert(number == SYS_kcmp);
errno = EPERM;
return -1;
}
static int native_import(int fd, int dma, uint32_t *handle) {
(void)fd;
native_imports++;
if (fcntl(dma, F_GETFD) < 0) return -1;
if (!handle) { errno = EFAULT; return -1; }
if (kernel_error) { errno = kernel_error; return -1; }
*handle = 42;
return 0;
}
static int native_export(int fd, uint32_t handle, uint32_t flags, int *out) {
(void)flags;
native_exports++;
if (handle != 42 || !out) { errno = EINVAL; return -1; }
*out = fixture_fcntl(fd, F_DUPFD_CLOEXEC, 0);
return *out < 0 ? -1 : 0;
}
static int native_close(int fd, uint32_t handle) {
(void)fd;
native_closes++;
if (handle == 42) return 0;
errno = EINVAL;
return -1;
}
static void *fixture_dlsym(void *object, const char *name) {
assert(object == RTLD_NEXT);
if (!strcmp(name, "drmPrimeFDToHandle")) return native_import;
if (!strcmp(name, "drmPrimeHandleToFD")) return native_export;
if (!strcmp(name, "drmCloseBufferHandle")) return native_close;
abort();
}
static int count_fds(void) {
int count = 0;
for (int fd = 0; fd < TEST_FD_LIMIT; ++fd) count += identities[fd] != 0;
return count;
}
static void empty_table(void) {
for (int i = 0; i < MAX_HANDLES; ++i) assert(!handle_entries[i].handle);
}
int main(void) {
int drm = test_open("/dev/null"), dma = test_open("/dev/zero");
uint32_t handle = 0;
unsetenv("BL_POWERVR_DRM_HANDLES");
setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
setenv("BL_POWERVR_DRM_HANDLES", "yes", 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
setenv("BL_POWERVR_DRM_HANDLES", "1", 1);
unsetenv("BL_POWERVR_RENDER_NODE");
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* no selected node */
setenv("BL_POWERVR_RENDER_NODE", "", 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
setenv("BL_POWERVR_RENDER_NODE", "/dev/dri/renderD128", 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* another GPU owns 128 */
setenv("BL_POWERVR_RENDER_NODE", "/dev/dri/renderD130", 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* selected node is absent */
setenv("BL_POWERVR_RENDER_NODE", __FILE__, 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* regular files are not DRM nodes */
setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1);
driver_name = "other";
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
driver_name = "pvr";
assert(drmPrimeFDToHandle(dma, dma, &handle) != 0); /* wrong character device */
kernel_error = EACCES;
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0 && errno == EACCES);
kernel_error = EINVAL;
assert(drmPrimeFDToHandle(drm, -1, &handle) != 0 && errno == EBADF);
empty_table();
int baseline = count_fds();
identity_denied = 1;
assert(drmPrimeFDToHandle(drm, dma, &handle) == -EOPNOTSUPP);
assert(count_fds() == baseline);
identity_denied = 0;
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && (handle & PVR_HANDLE_BIT));
assert(count_fds() == baseline + 2);
int alias = fixture_fcntl(drm, F_DUPFD_CLOEXEC, 0), out = -1;
int separate = test_open("/dev/null");
assert(drmPrimeHandleToFD(separate, handle, O_CLOEXEC | O_RDWR, &out) != 0);
struct gem_close close_request = {.handle = handle};
int rc = 123;
assert(bl_drm_gem_close(separate, GEM_CLOSE, &close_request, &rc) == 0 && rc == 123);
assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC | O_RDWR, &out) == 0);
assert(fcntl(out, F_GETFD) & FD_CLOEXEC);
struct stat src, dst;
assert(fstat(dma, &src) == 0 && fstat(out, &dst) == 0);
assert(src.st_dev == dst.st_dev && src.st_ino == dst.st_ino);
fixture_close(out);
assert(drmPrimeHandleToFD(alias, handle, 0, &out) == 0);
assert(!(fcntl(out, F_GETFD) & FD_CLOEXEC));
fixture_close(out);
assert(drmPrimeHandleToFD(alias, handle, 0x40, &out) == -EINVAL);
/* A closed-and-reused descriptor must not inherit the old open file's handles. */
int old_number = drm;
fixture_close(drm);
drm = test_open("/dev/null");
assert(drm == old_number);
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) != 0);
assert(drmCloseBufferHandle(drm, handle) != 0);
assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC, &out) == 0);
fixture_close(out);
assert(bl_drm_gem_close(alias, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0);
assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC, &out) != 0);
fixture_close(alias);
fixture_close(separate);
assert(count_fds() == baseline);
empty_table();
/* Real kernel handles and their direct GEM_CLOSE ioctls are never swallowed. */
kernel_error = 0;
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && handle == 42);
empty_table();
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0);
fixture_close(out);
close_request.handle = handle;
assert(bl_drm_gem_close(drm, GEM_CLOSE, &close_request, &rc) == 0);
assert(drmCloseBufferHandle(drm, handle) == 0);
assert(native_imports && native_exports && native_closes);
kernel_error = EINVAL;
/* Slot reuse must not reuse public tokens or leak either owned descriptor. */
uint32_t previous = 0;
for (int n = 0; n < 1000; ++n) {
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && handle != previous);
assert(drmCloseBufferHandle(drm, handle) == 0);
if (previous) assert(drmPrimeHandleToFD(drm, previous, O_CLOEXEC, &out) != 0);
previous = handle;
}
assert(count_fds() == baseline);
empty_table();
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0);
pid_t child = fork();
assert(child >= 0);
if (child == 0) {
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0);
fixture_close(out);
assert(drmCloseBufferHandle(drm, handle) == 0);
_exit(0);
}
int status;
assert(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0);
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0);
fixture_close(out);
assert(drmCloseBufferHandle(drm, handle) == 0);
/* Preserve the original device layout when PowerVR owns renderD128. */
pvr_node = "/dev/dri/renderD128";
setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1);
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && (handle & PVR_HANDLE_BIT));
assert(drmCloseBufferHandle(drm, handle) == 0);
/* Retain the old KGSL path with the PowerVR opt-in unset. */
unsetenv("BL_POWERVR_DRM_HANDLES");
kgsl_present = 1;
kgsl_state = 0;
assert(drmPrimeFDToHandle(dma, drm, &handle) == 0 && !(handle & PVR_HANDLE_BIT));
assert(drmPrimeHandleToFD(dma, handle, O_CLOEXEC | O_RDWR, &out) == 0);
fixture_close(out);
close_request.handle = handle;
assert(bl_drm_gem_close(dma, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0);
assert(drmCloseBufferHandle(dma, handle) == -EINVAL);
empty_table();
assert(count_fds() == baseline);
fixture_close(drm);
fixture_close(dma);
puts("DRM adapter scoping, ownership, reuse, fork and kernel-passthrough tests passed");
}
+26
View File
@@ -0,0 +1,26 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
class DrmHandleTest(unittest.TestCase):
def test_handle_lifetime_and_device_scope(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the DRM adapter regression test")
source = Path(__file__).with_name("drm_handles_test.c")
with tempfile.TemporaryDirectory(prefix="droiddeck-drm-") as tmp:
program = Path(tmp) / "drm-handles"
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror",
"-UNDEBUG", "-pthread", str(source), "-ldl", "-o", str(program)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
if __name__ == "__main__":
unittest.main()
+181
View File
@@ -8,6 +8,7 @@ import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
MODULE = runpy.run_path(str(BIN / "droiddeck-game-env"))
@@ -26,6 +27,137 @@ def config_text(entries):
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class SystemGraphicsLaunchTest(unittest.TestCase):
def runtime(self, root):
runtime = root / "system_vulkan" / ("a" * 64)
files = ["run-proton.py", "lib/libVkLayer_hybris_compat.so",
"wsi/libVkLayer_window_system_integration.so",
"wsi/VkLayer_window_system_integration.json"]
files += ["dxvk/%s/%s.dll" % (arch, name) for arch in ("x32", "x64")
for name in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi")]
for name in files:
target = runtime / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(b"component")
(runtime / "run-proton.py").chmod(0o755)
return runtime, files
def test_other_gpus_and_non_game_calls_keep_the_original_launch(self):
command = ["/proton", "waitforexitandrun", "game.exe"]
base = {"STEAM_COMPAT_DATA_PATH": "/compatdata/42", "VK_LAYER_PATH": "original"}
selected = dict(base, DROIDDECK_POWERVR_RUNTIME="/not-installed")
cases = [(command, base), (command, dict(selected, STEAM_COMPAT_DATA_PATH="/compatdata/0")),
(command, dict(selected, STEAM_COMPAT_DATA_PATH="/compatdata/invalid")),
(["/proton", "run", "iscriptevaluator.exe"], selected),
(["/proton", "getcompatpath", "x"], selected), (command[:2], selected)]
for args, env in cases:
with self.subTest(args=args, env=env):
actual, inherited = MODULE["system_graphics_launch"](args, env)
self.assertIs(actual, args)
self.assertIs(inherited, env)
def test_system_graphics_follow_game_configuration_and_preserve_other_keys(self):
with tempfile.TemporaryDirectory() as tmp:
runtime, _ = self.runtime(Path(tmp))
base = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
config = {"version": 1, "games": {"42": {
"PROTON_USE_WINED3D": "1", "DISABLE_WSI_LAYER": "1",
"ENABLE_VK_LAYER_VALVE_steam_fossilize_1": "1", "HYBRIS_BC_TEXTURES": "0",
"VK_LAYER_PATH": "old", "VK_INSTANCE_LAYERS": "old", "ENABLE_GAMESCOPE_WSI": "1",
"FEX_TSOENABLED": "1", "WINESERVER": "/selected/wineserver", "CUSTOM": "literal $value",
}}}
env = MODULE["apply_config"](base, config, "42")
command = ["/selected/proton", "waitforexitandrun", "game with spaces.exe"]
launch, result = MODULE["system_graphics_launch"](command, env)
self.assertEqual(launch, [str(runtime / "run-proton.py"), *command])
self.assertEqual(result["HYBRIS_BC_TEXTURES"], "dxvk")
self.assertEqual(result["VK_LAYER_PATH"], f"{runtime}/wsi:{runtime}/lib")
self.assertEqual(result["VK_INSTANCE_LAYERS"], "VK_LAYER_window_system_integration:VK_LAYER_HYBRIS_compat")
self.assertEqual(result["VK_LOADER_LAYERS_DISABLE"], "*gamescope*")
self.assertEqual(result["ENABLE_GAMESCOPE_WSI"], "0")
self.assertEqual(result["DISABLE_VK_LAYER_VALVE_steam_fossilize_1"], "1")
for key in ("PROTON_USE_WINED3D", "DISABLE_WSI_LAYER", "ENABLE_VK_LAYER_VALVE_steam_fossilize_1"):
self.assertNotIn(key, result)
self.assertIn(key, env)
for key in ("FEX_TSOENABLED", "WINESERVER", "CUSTOM"):
self.assertEqual(result[key], env[key])
def test_xclipse_selection_adds_its_layers_layer_path_and_dxvk_payload(self):
with tempfile.TemporaryDirectory() as tmp:
runtime, _ = self.runtime(Path(tmp))
env = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": "/compatdata/42",
"DROIDDECK_HYBRIS_LAYERS": "VK_LAYER_DROIDDECK_xclipse:VK_LAYER_HYBRIS_compat",
"DROIDDECK_HYBRIS_LAYER_PATH": "/usr/local/lib/droiddeck-xclipse",
"DROIDDECK_HYBRIS_DXVK": "dxvk-2.6.2"}
command = ["/proton", "waitforexitandrun", "game.exe"]
# The selected payload is required like the default one.
with self.assertRaises(MODULE["SystemGraphicsError"]):
MODULE["system_graphics_launch"](command, env)
for arch in ("x32", "x64"):
for name in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi"):
target = runtime / "dxvk-2.6.2" / arch / (name + ".dll")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(b"component")
launch, result = MODULE["system_graphics_launch"](command, env)
self.assertEqual(launch, [str(runtime / "run-proton.py"), *command])
self.assertEqual(result["VK_INSTANCE_LAYERS"],
"VK_LAYER_window_system_integration:VK_LAYER_DROIDDECK_xclipse:VK_LAYER_HYBRIS_compat")
self.assertEqual(result["VK_LAYER_PATH"], f"{runtime}/wsi:{runtime}/lib:/usr/local/lib/droiddeck-xclipse")
self.assertEqual(result["DROIDDECK_HYBRIS_DXVK"], "dxvk-2.6.2")
for name in ("../dxvk", "other", "dxvk/x"):
with self.subTest(name=name), self.assertRaises(MODULE["SystemGraphicsError"]):
MODULE["system_graphics_launch"](command, dict(env, DROIDDECK_HYBRIS_DXVK=name))
def test_incomplete_runtime_fails_before_any_proton_exec(self):
with tempfile.TemporaryDirectory() as tmp:
runtime, files = self.runtime(Path(tmp))
env = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
command = ["/proton", "waitforexitandrun", "game.exe"]
for name in files:
target = runtime / name
original = target.read_bytes()
for missing in (False, True):
with self.subTest(name=name, missing=missing):
target.unlink() if missing else target.write_bytes(b"")
with patch.object(os, "execvpe") as execute:
with self.assertRaises(MODULE["SystemGraphicsError"]):
MODULE["exec_proton"](command, env)
execute.assert_not_called()
target.write_bytes(original)
if name == "run-proton.py":
target.chmod(0o755)
(runtime / "run-proton.py").chmod(0o644)
with self.assertRaises(MODULE["SystemGraphicsError"]):
MODULE["system_graphics_launch"](command, env)
with self.assertRaises(MODULE["SystemGraphicsError"]):
MODULE["system_graphics_launch"](command, dict(env, DROIDDECK_POWERVR_RUNTIME="relative"))
def test_wrapper_receives_the_sync_selected_proton(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
runtime, _ = self.runtime(root)
env = {"HOME": tmp, "DROIDDECK_POWERVR_RUNTIME": str(runtime),
"STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
command = ["/stock/proton", "waitforexitandrun", "game.exe"]
selected = ["/sync-pack/proton", *command[1:]]
selected_env = dict(env, WINESERVER="/sync-pack/wineserver", BL_SYNC_PACK="selected")
main = MODULE["main"]
with patch.dict(os.environ, env, clear=True), patch.object(sys, "argv", ["game-env", *command]), \
patch.dict(main.__globals__, {"load_sync": lambda: {},
"select_sync": lambda *args: (selected, selected_env),
"win_components": lambda *args: ""}), \
patch.object(os, "execvpe", side_effect=SystemExit(23)) as execute:
with self.assertRaises(SystemExit) as stopped:
main()
self.assertEqual(stopped.exception.code, 23)
execute.assert_called_once()
path, args, actual_env = execute.call_args.args
self.assertEqual(path, str(runtime / "run-proton.py"))
self.assertEqual(args, [path, *selected])
self.assertEqual(actual_env["WINESERVER"], "/sync-pack/wineserver")
self.assertEqual(actual_env["BL_SYNC_PACK"], "selected")
class GameEnvironmentTest(unittest.TestCase):
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -87,6 +219,55 @@ class GameEnvironmentTest(unittest.TestCase):
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
self.assertEqual(target.read_text(), "general")
def test_system_powervr_preserves_dxvk_profiles_without_applying_them(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
home = root / "home"
component_dir = home / ".local/share/droiddeck-components"
component_dir.mkdir(parents=True)
base = root / "proton"
paths = {
"dxvk": "files/lib/wine/dxvk/aarch64-windows/d3d11.dll",
"fex": "files/lib/wine/aarch64-windows/libarm64ecfex.dll",
"vkd3d": "files/lib/wine/vkd3d-proton/aarch64-windows/d3d12.dll",
}
rows = []
for comp, rel in paths.items():
target = base / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("bundled " + comp)
for scope in ("*", "42"):
source = root / (comp + ("-general" if scope == "*" else "-game"))
source.write_text(source.name)
rows.append("%s\tproton\tbuild-1\t%s\t%s\t%s\t%s\n" % (
scope, comp, rel, hashlib.sha256(source.read_bytes()).hexdigest(), source,
))
leftover = (base / paths["dxvk"]).with_name("d3d8.dll")
leftover.write_text("bundled d3d8")
rows.append("42\tproton\tbuild-1\tdxvk\t%s\t-\t-\n" % leftover.relative_to(base))
(base / "version").write_text("1 build-1\n")
selection = component_dir / "desired.tsv"
selection.write_text("".join(rows))
saved = selection.read_bytes()
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",
DROIDDECK_POWERVR_RUNTIME="/system_vulkan/runtime")
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
self.assertEqual((base / paths["dxvk"]).read_text(), "bundled dxvk")
self.assertEqual(leftover.read_text(), "bundled d3d8")
for comp in ("fex", "vkd3d"):
self.assertEqual((base / paths[comp]).read_text(), comp + "-game")
self.assertEqual(selection.read_bytes(), saved)
# A subsequent manual-driver session still applies the saved per-game DXVK choice.
env.pop("DROIDDECK_POWERVR_RUNTIME")
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
self.assertEqual((base / paths["dxvk"]).read_text(), "dxvk-game")
self.assertFalse(leftover.exists())
self.assertEqual(selection.read_bytes(), saved)
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
+102
View File
@@ -0,0 +1,102 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
DESKTOP_GPU = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-gpu"
class GamescopeBackendTest(unittest.TestCase):
def select(self, backend=None):
source = SESSION.read_text()
start = source.index(' backend=${BL_GAMESCOPE_BACKEND:-wayland}')
end = source.index('\n', source.index(' args=(--backend ', start))
script = 'width=1280; height=720; nested=1280\n' + source[start:end]
script += '\nprintf "%s\\n" "${args[0]}" "${args[1]}" "${SDL_VIDEODRIVER:-unset}"\n'
env = dict(os.environ)
env.pop("BL_GAMESCOPE_BACKEND", None)
env.pop("SDL_VIDEODRIVER", None)
if backend is not None:
env["BL_GAMESCOPE_BACKEND"] = backend
return subprocess.run(["bash", "-c", script], env=env, text=True,
capture_output=True, timeout=5)
def test_default_retains_the_wayland_backend(self):
result = self.select()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(["--backend", "wayland", "unset"], result.stdout.splitlines())
def test_sdl_uses_the_host_wayland_vulkan_swapchain(self):
result = self.select("sdl")
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(["--backend", "sdl", "wayland"], result.stdout.splitlines())
def test_unknown_backend_fails_before_gamescope(self):
result = self.select("drm")
self.assertEqual(64, result.returncode)
self.assertIn("unsupported gamescope backend: drm", result.stdout)
class DesktopGamescopeBackendTest(unittest.TestCase):
def launch(self, backend=None):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
capture = root / "gamescope.json"
gamescope = root / "gamescope"
gamescope.write_text(
f"#!{sys.executable}\n"
"import json, os, sys\n"
"from pathlib import Path\n"
"Path(os.environ['GAMESCOPE_CAPTURE']).write_text(json.dumps({\n"
" 'args': sys.argv[1:],\n"
" 'sdl': os.environ.get('SDL_VIDEODRIVER'),\n"
" 'gdk': os.environ.get('GDK_BACKEND'),\n"
" 'qt': os.environ.get('QT_QPA_PLATFORM'),\n"
" 'wayland': os.environ.get('WAYLAND_DISPLAY'),\n"
"}))\n"
)
gamescope.chmod(0o755)
env = dict(os.environ)
for name in ("BL_GAMESCOPE_BACKEND", "BL_DEBUG_DIR", "BL_FPS", "BL_REFRESH", "BL_HDR"):
env.pop(name, None)
env.update(PATH=f"{root}{os.pathsep}{env.get('PATH', '')}",
GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0",
SDL_VIDEODRIVER="dummy", GDK_BACKEND="wayland", QT_QPA_PLATFORM="wayland")
if backend is not None:
env["BL_GAMESCOPE_BACKEND"] = backend
result = subprocess.run(["bash", str(DESKTOP_GPU), "demo", "one argument"],
env=env, text=True, capture_output=True, timeout=5)
return result, json.loads(capture.read_text()) if capture.exists() else None
def assert_xwayland_application(self, capture):
args = capture["args"]
self.assertEqual(["env", "SDL_VIDEODRIVER=x11", "/usr/local/bin/droiddeck-gpu-window",
"demo", "one argument"], args[args.index("--") + 1:])
self.assertEqual("x11", capture["gdk"])
self.assertEqual("xcb", capture["qt"])
self.assertEqual("wayland-0", capture["wayland"])
def test_default_keeps_wayland_and_xwayland_application(self):
result, capture = self.launch()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(["--backend", "wayland"], capture["args"][:2])
self.assertEqual("x11", capture["sdl"])
self.assert_xwayland_application(capture)
def test_sdl_uses_wayland_without_leaking_to_the_application(self):
result, capture = self.launch("sdl")
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(["--backend", "sdl"], capture["args"][:2])
self.assertEqual("wayland", capture["sdl"])
self.assert_xwayland_application(capture)
def test_unknown_backend_fails_before_gamescope(self):
result, capture = self.launch("drm")
self.assertEqual(64, result.returncode)
self.assertIn("unsupported gamescope backend: drm", result.stderr)
self.assertIsNone(capture)
+291
View File
@@ -0,0 +1,291 @@
import importlib.util
import io
import json
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from zipfile import ZipFile, ZipInfo
spec = importlib.util.spec_from_file_location('powervr_fetch',
Path(__file__).resolve().parents[1] / 'powervr/fetch.py')
runtime = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runtime)
def elf():
content = bytearray(64)
content[:6], content[18:20] = b'\x7fELF\x02\x01', b'\xb7\x00'
return bytes(content)
def pe(architecture):
content = bytearray(128)
content[:2], content[60:64], content[64:68] = b'MZ', (64).to_bytes(4, 'little'), b'PE\0\0'
content[68:70] = b'\x4c\x01' if architecture == 'x32' else b'\x64\x86'
content[88:90] = b'\x0b\x01' if architecture == 'x32' else b'\x0b\x02'
return bytes(content)
def tar(entries):
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w') as archive:
for name, kind, content in entries:
info = tarfile.TarInfo(name)
info.type = kind
if kind in (tarfile.SYMTYPE, tarfile.LNKTYPE):
info.linkname = content
archive.addfile(info)
elif kind == tarfile.REGTYPE:
info.size = len(content)
archive.addfile(info, io.BytesIO(content))
else:
archive.addfile(info)
return subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(),
capture_output=True, check=True).stdout
def tar_gz(entries):
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w:gz') as archive:
for name, kind, content in entries:
info = tarfile.TarInfo(name)
info.type = kind
if kind == tarfile.SYMTYPE:
info.linkname = content
archive.addfile(info)
elif kind == tarfile.REGTYPE:
info.size = len(content)
archive.addfile(info, io.BytesIO(content))
else:
archive.addfile(info)
return stream.getvalue()
def upstream_dxvk(version, architecture_of=lambda arch: arch):
return {'dxvk-%s/%s/%s' % (version, arch, name): pe(architecture_of(arch))
for arch in ('x32', 'x64')
for name in ('d3d8.dll', 'd3d9.dll', 'd3d10core.dll', 'd3d11.dll', 'dxgi.dll')}
class PowerVRRuntimeTest(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.cache = self.root / 'cache'
self.cache.mkdir()
for name, content in {
'tools/powervr/fetch.py': b'fixture assembler',
'tools/hybris/run-proton.py': b'print("fixture Proton wrapper")\n',
'tools/hybris/source.env': b'HYBRIS_REVISION=fixture\n',
'tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md': b'Khronos headers attribution\n',
'tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt': b'MIT license fixture\n',
}.items():
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
bridge = {name: ('file', 0o755, elf()) for name in runtime.REQUIRED_LIBRARIES if name.startswith('lib/')}
bridge['lib/libhybris-common.so.1.0.0'] = bridge.pop('lib/libhybris-common.so.1')
bridge['lib/libhybris-common.so.1'] = ('symlink', 0o777, 'libhybris-common.so.1.0.0')
data = runtime.pack(bridge)
self.release = {'format': 1, 'hybris': self.component('bridge.tzst', data), 'archives': []}
self.release['hybris'].update({
'tree_sha256': runtime.tree_digest(bridge),
'recipe_inputs': {'tools/hybris/source.env': runtime.sha256((self.root / 'tools/hybris/source.env').read_bytes())}})
files = {'dxvk/' + arch + '/' + name: pe(arch)
for arch in ('x32', 'x64')
for name in ('d3d8.dll', 'd3d9.dll', 'd3d10core.dll', 'd3d11.dll', 'dxgi.dll')}
files['wsi/libVkLayer_window_system_integration.so'] = elf()
stream = io.BytesIO()
with ZipFile(stream, 'w') as archive:
for name, content in files.items():
archive.writestr(name, content)
component = self.component('graphics.zip', stream.getvalue())
component.update({'ignored': [], 'files': [
{'name': name, 'path': name, 'size': len(content), 'sha256': runtime.sha256(content), 'mode': 0o644}
for name, content in files.items()]})
self.release['archives'].append(component)
self.pins = self.root / 'tools/powervr/release.json'
self.pins.write_bytes(runtime.json_bytes(self.release))
def component(self, name, data):
component = {'url': 'https://example.invalid/' + name, 'size': len(data),
'sha256': runtime.sha256(data), 'recipe_inputs': {}}
(self.cache / (component['sha256'] + '-' + name)).write_bytes(data)
return component
def add_upstream_dxvk(self, files):
top = next(iter(files)).split('/')[0]
data = tar_gz([(top, tarfile.DIRTYPE, None)] +
[(name, tarfile.REGTYPE, content) for name, content in files.items()])
component = self.component('dxvk-upstream.tar.gz', data)
component.update({'format': 'tar.gz', 'ignored': [], 'files': [
{'name': name, 'path': name, 'size': len(content), 'sha256': runtime.sha256(content), 'mode': 0o755}
for name, content in files.items()]})
self.release['archives'].append(component)
self.pins.write_bytes(runtime.json_bytes(self.release))
return component
def assembled(self):
runtime.assemble(self.root, self.cache)
return runtime.read_tar((self.root / runtime.ASSETS / 'runtime.tzst').read_bytes())
def test_complete_payload_preserves_symlinks_and_is_reproducible(self):
self.assembled()
first = (self.root / runtime.ASSETS / 'runtime.tzst').read_bytes()
runtime.verify(self.root)
self.assembled()
self.assertEqual(first, (self.root / runtime.ASSETS / 'runtime.tzst').read_bytes())
self.assertEqual(runtime.read_tar(first)['lib/libhybris-common.so.1'][0], 'symlink')
def test_upstream_tarball_adds_a_second_dxvk_payload(self):
files = upstream_dxvk('2.6.2')
self.add_upstream_dxvk(files)
entries = self.assembled()
runtime.verify(self.root)
for name, content in files.items():
self.assertEqual(entries[name], ('file', 0o755, content))
self.assertIn('dxvk/x64/d3d9.dll', entries)
def test_second_dxvk_payload_with_wrong_pe_architecture_is_rejected(self):
self.add_upstream_dxvk(upstream_dxvk('2.6.2', lambda arch: 'x64' if arch == 'x32' else 'x32'))
with self.assertRaisesRegex(ValueError, 'wrong PE architecture: dxvk-2.6.2/'):
self.assembled()
def test_tar_gz_rejects_symlinks_unknown_members_and_changed_files(self):
pin = {'name': 'dxvk-1/x64/d3d9.dll', 'path': 'dxvk-1/x64/d3d9.dll', 'size': 4,
'sha256': runtime.sha256(b'good'), 'mode': 0o755}
component = {'files': [pin], 'ignored': []}
cases = [
[('dxvk-1/x64/d3d9.dll', tarfile.SYMTYPE, '../../outside')],
[('dxvk-1/x64/d3d9.dll', tarfile.REGTYPE, b'good'), ('dxvk-1/extra.dll', tarfile.REGTYPE, b'x')],
[('dxvk-1/x64/d3d9.dll', tarfile.REGTYPE, b'evil')],
[],
]
for entries in cases:
with self.subTest(entries=[name for name, _, _ in entries]), self.assertRaises(ValueError):
runtime.read_tar_gz(tar_gz(entries), component)
self.assertEqual(runtime.read_tar_gz(tar_gz([('dxvk-1/x64/d3d9.dll', tarfile.REGTYPE, b'good')]), component),
{'dxvk-1/x64/d3d9.dll': ('file', 0o755, b'good')})
with self.assertRaisesRegex(ValueError, 'unsupported component archive format'):
runtime.read_component(b'', {'format': 'rar'})
def test_stale_wrapper_cannot_pass_with_an_updated_archive_checksum(self):
self.assembled()
(self.root / 'tools/hybris/run-proton.py').write_text('print("new wrapper")\n')
with self.assertRaisesRegex(ValueError, 'assembly inputs changed'):
runtime.verify(self.root)
def test_header_licenses_are_bundled_verbatim(self):
entries = self.assembled()
for source, target in runtime.BUNDLED_LICENSES.items():
self.assertEqual(runtime.read(entries, target), (self.root / source).read_bytes())
def test_missing_or_modified_header_license_is_rejected(self):
original = self.assembled()
target = 'licenses/Vulkan-Headers/MIT.txt'
for replacement in (None, ('file', 0o644, b'stale license')):
with self.subTest(replacement=replacement):
entries = dict(original)
if replacement is None:
del entries[target]
else:
entries[target] = replacement
with self.assertRaisesRegex(ValueError, 'license missing or stale'):
runtime.check_bundle(entries, self.release, self.root)
def test_changed_tracked_header_license_rejects_old_bundle(self):
self.assembled()
source = next(iter(runtime.BUNDLED_LICENSES))
(self.root / source).write_bytes(b'changed license text')
with self.assertRaisesRegex(ValueError, 'assembly inputs changed'):
runtime.verify(self.root)
def test_changed_component_recipe_requires_new_release_pin(self):
self.assembled()
(self.root / 'tools/hybris/source.env').write_text('HYBRIS_REVISION=new-source\n')
with self.assertRaisesRegex(ValueError, 'recipe changed'):
runtime.verify(self.root)
def test_old_dxvk_cannot_pass_by_updating_only_the_bundle_checksum(self):
entries = self.assembled()
entries['dxvk/x64/d3d11.dll'] = ('file', 0o644, pe('x64') + b'old DLL')
archive = runtime.pack(entries)
with self.assertRaisesRegex(ValueError, 'component mismatch'):
runtime.verify_archive(archive, runtime.sha256(archive), self.root)
def test_wrong_pe_architecture_rejected_even_with_matching_member_pin(self):
entries = self.assembled()
name = 'dxvk/x32/d3d11.dll'
entries[name] = ('file', 0o644, pe('x64'))
pin = next(item for item in self.release['archives'][0]['files'] if item['path'] == name)
pin['sha256'] = runtime.sha256(pe('x64'))
with self.assertRaisesRegex(ValueError, 'wrong PE architecture'):
runtime.check_bundle(entries, self.release, self.root)
def test_unpinned_bridge_file_is_rejected(self):
entries = self.assembled()
entries['lib/extra-loader.so'] = ('file', 0o755, elf())
with self.assertRaisesRegex(ValueError, 'bridge differs'):
runtime.check_bundle(entries, self.release, self.root)
def test_failed_download_leaves_the_previous_payload_ready(self):
self.assembled()
before = (self.root / runtime.ASSETS / 'version.txt').read_bytes()
component = self.release['archives'][0]
(self.cache / (component['sha256'] + '-graphics.zip')).write_bytes(b'bad cache')
with patch.object(runtime, 'urlopen', return_value=io.BytesIO(b'corrupt response')):
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
runtime.assemble(self.root, self.cache)
self.assertEqual(before, (self.root / runtime.ASSETS / 'version.txt').read_bytes())
runtime.verify(self.root)
def test_tar_rejects_traversal_duplicate_special_files_and_symlink_escape(self):
cases = [
[('../escape', tarfile.REGTYPE, b'x')],
[('file', tarfile.REGTYPE, b'x'), ('./file', tarfile.REGTYPE, b'y')],
[('device', tarfile.CHRTYPE, b'')],
[('file', tarfile.LNKTYPE, 'other')],
[('lib/link', tarfile.SYMTYPE, '../../outside')],
[('lib/link', tarfile.SYMTYPE, '/absolute')],
[('lib/a', tarfile.SYMTYPE, 'b'), ('lib/b', tarfile.SYMTYPE, 'a')],
[('lib', tarfile.SYMTYPE, 'target'), ('target', tarfile.REGTYPE, b'x'),
('lib/child', tarfile.REGTYPE, b'x')],
]
for members in cases:
with self.subTest(members=members):
with self.assertRaises(ValueError):
runtime.read_tar(tar(members))
def test_relative_symlink_that_stays_inside_runtime_is_preserved(self):
entries = runtime.read_tar(tar([
('lib/a', tarfile.REGTYPE, b'library'), ('lib/child/link', tarfile.SYMTYPE, '../a')]))
self.assertEqual(runtime.read(entries, 'lib/child/link'), b'library')
def test_zip_rejects_symlink_even_if_name_is_allowed(self):
stream = io.BytesIO()
with ZipFile(stream, 'w') as archive:
info = ZipInfo('allowed')
info.create_system = 3
info.external_attr = 0o120777 << 16
archive.writestr(info, '../outside')
with self.assertRaisesRegex(ValueError, 'unexpected component archive entry'):
runtime.read_zip(stream.getvalue(), {'files': [], 'ignored': ['allowed']})
def test_zip_rejects_unknown_and_duplicate_members(self):
for names in (['unexpected'], ['allowed', 'allowed'], ['../escape']):
with self.subTest(names=names):
stream = io.BytesIO()
with ZipFile(stream, 'w') as archive:
for name in names:
archive.writestr(name, b'file')
with self.assertRaises(ValueError):
runtime.read_zip(stream.getvalue(), {'files': [], 'ignored': ['allowed']})
if __name__ == '__main__':
unittest.main()
+228
View File
@@ -0,0 +1,228 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
WRAPPER_SOURCE = TOOLS / "hybris/run-proton.py"
DLL_NAMES = ("d3d8.dll", "d3d9.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll")
DXVK_X64_ANCHOR = 'g_proton.arch_pe_dir("wine/dxvk", False) + f + ".dll"'
DXVK_X32_ANCHOR = 'g_proton.arch_pe_dir("wine/dxvk", True) + f + ".dll"'
PREFIX_ANCHOR = " # check whether any prefix config has changed"
PROTON_SOURCE = '''import json
import os
from pathlib import Path
import sys
from neighbor import NEIGHBOR
class Proton:
def arch_pe_dir(self, directory, is32):
return str(Path(__file__).parent / "stock" / ("x32" if is32 else "x64")) + "/"
g_proton = Proton()
def prefix_marker():
if True:
prefix_info = "stock"
# check whether any prefix config has changed
return prefix_info
def payloads():
result = {"x64": {}, "x32": {}}
for f in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi"):
x64 = g_proton.arch_pe_dir("wine/dxvk", False) + f + ".dll"
x32 = g_proton.arch_pe_dir("wine/dxvk", True) + f + ".dll"
result["x64"][f + ".dll"] = Path(x64).read_text()
result["x32"][f + ".dll"] = Path(x32).read_text()
return result
def main():
record = {
"argv0": sys.argv[0],
"argv": sys.argv[1:],
"file": __file__,
"neighbor": NEIGHBOR,
"prefix": prefix_marker(),
"payloads": payloads(),
"openvr": g_proton.arch_pe_dir("wine/dxvk", False) + "openvr_api_dxvk.dll",
}
Path(os.environ["PROBE"]).write_text(json.dumps(record))
raise SystemExit(int(os.environ.get("PROTON_EXIT", "0")))
main()
'''
class ProtonWrapperTest(unittest.TestCase):
def fixture(self, root):
wrapper_dir = root / 'DXVK profile "quotes" $dollar `backticks`'
wrapper_dir.mkdir(parents=True)
wrapper = wrapper_dir / "run-proton.py"
shutil.copy2(WRAPPER_SOURCE, wrapper)
dxvk = wrapper_dir / "dxvk"
for architecture in ("x32", "x64"):
payload = dxvk / architecture
payload.mkdir(parents=True)
for name in DLL_NAMES:
(payload / name).write_text(f"{architecture}:{name}")
depot = root / "Proton depot with spaces"
depot.mkdir()
proton = depot / "selected proton.py"
proton.write_text(PROTON_SOURCE)
(depot / "neighbor.py").write_text('NEIGHBOR = "imported from selected depot"\n')
return {"wrapper": wrapper, "dxvk": dxvk, "depot": depot, "proton": proton,
"probe": root / "proton-ran.json"}
def run_wrapper(self, fixture, *proton_args, check=False, exit_status=0, env=None):
command = [sys.executable, str(fixture["wrapper"])]
if check:
command.append("--check")
command.extend((str(fixture["proton"]), *proton_args))
return subprocess.run(
command,
cwd=fixture["wrapper"].parent,
env={"PATH": os.defpath, "PROBE": str(fixture["probe"]),
"PROTON_EXIT": str(exit_status), **(env or {})},
text=True,
capture_output=True,
)
def test_launch_uses_both_staged_payloads_and_selected_proton_context(self):
with tempfile.TemporaryDirectory() as tmp:
fixture = self.fixture(Path(tmp))
original_source = fixture["proton"].read_bytes()
arguments = ("waitforexitandrun", "game with spaces.exe", 'quoted "value"',
"$literal-dollar", "`literal-backticks`")
result = self.run_wrapper(fixture, *arguments)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(fixture["proton"].read_bytes(), original_source)
record = json.loads(fixture["probe"].read_text())
self.assertEqual(record["argv0"], str(fixture["proton"]))
self.assertEqual(record["argv"], list(arguments))
self.assertEqual(record["file"], str(fixture["proton"]))
self.assertEqual(record["neighbor"], "imported from selected depot")
self.assertEqual(record["prefix"], "stock\ndroiddeck-dxvk-profile-v1")
self.assertEqual(record["openvr"], str(fixture["depot"] / "stock/x64/openvr_api_dxvk.dll"))
for architecture in ("x32", "x64"):
self.assertEqual(
record["payloads"][architecture],
{name: f"{architecture}:{name}" for name in DLL_NAMES},
)
def test_named_sibling_payload_replaces_the_default(self):
with tempfile.TemporaryDirectory() as tmp:
fixture = self.fixture(Path(tmp))
for architecture in ("x32", "x64"):
payload = fixture["wrapper"].parent / "dxvk-2.6.2" / architecture
payload.mkdir(parents=True)
for name in DLL_NAMES:
(payload / name).write_text(f"2.6.2 {architecture}:{name}")
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe",
env={"DROIDDECK_HYBRIS_DXVK": "dxvk-2.6.2"})
self.assertEqual(result.returncode, 0, result.stderr)
record = json.loads(fixture["probe"].read_text())
for architecture in ("x32", "x64"):
self.assertEqual(
record["payloads"][architecture],
{name: f"2.6.2 {architecture}:{name}" for name in DLL_NAMES},
)
def test_payload_names_outside_the_wrapper_directory_are_refused(self):
for name in ("../dxvk", "dxvk/../../x", "/tmp/dxvk", "other", ".dxvk"):
with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
fixture = self.fixture(Path(tmp))
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe",
env={"DROIDDECK_HYBRIS_DXVK": name})
self.assertEqual(result.returncode, 1)
self.assertIn("invalid payload name", result.stderr)
self.assertFalse(fixture["probe"].exists())
def test_check_validates_without_executing_proton(self):
with tempfile.TemporaryDirectory() as tmp:
fixture = self.fixture(Path(tmp))
result = self.run_wrapper(fixture, check=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("payload present and Proton layout supported", result.stdout)
self.assertFalse(fixture["probe"].exists())
def test_check_rejects_malformed_source_before_its_top_level_code_runs(self):
with tempfile.TemporaryDirectory() as tmp:
fixture = self.fixture(Path(tmp))
source = fixture["proton"].read_text()
source = source.replace(
"import sys\n", 'import sys\n\nPath(os.environ["PROBE"]).write_text("top-level")\n', 1)
fixture["proton"].write_text(source + "\nthis is not valid =\n")
result = self.run_wrapper(fixture, check=True)
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("DroidDeck DXVK profile:", result.stderr)
self.assertFalse(fixture["probe"].exists())
def test_preflight_rejects_each_missing_or_empty_payload_before_proton_runs(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for state in ("missing", "empty"):
for architecture in ("x32", "x64"):
for name in DLL_NAMES:
with self.subTest(state=state, architecture=architecture, name=name):
fixture = self.fixture(root / f"{state}-{architecture}-{name}")
payload = fixture["dxvk"] / architecture / name
if state == "missing":
payload.unlink()
else:
payload.write_bytes(b"")
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe")
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn(f"{state} DXVK file", result.stderr)
self.assertFalse(fixture["probe"].exists())
def test_preflight_rejects_changed_proton_layout_or_syntax_before_proton_runs(self):
mutations = []
for label, anchor in (("x64", DXVK_X64_ANCHOR), ("x32", DXVK_X32_ANCHOR),
("prefix", PREFIX_ANCHOR)):
mutations.extend(((f"missing-{label}", lambda text, anchor=anchor: text.replace(anchor, "missing_anchor", 1)),
(f"duplicate-{label}", lambda text, anchor=anchor: text + "\n# " + anchor + "\n")))
mutations.append(("syntax-error", lambda text: text + "\nthis is not valid =\n"))
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for label, mutate in mutations:
with self.subTest(layout=label):
fixture = self.fixture(root / label)
fixture["proton"].write_text(mutate(fixture["proton"].read_text()))
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe")
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("DroidDeck DXVK profile:", result.stderr)
self.assertFalse(fixture["probe"].exists())
def test_proton_exit_status_is_propagated(self):
with tempfile.TemporaryDirectory() as tmp:
fixture = self.fixture(Path(tmp))
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe", exit_status=23)
self.assertEqual(result.returncode, 23, result.stderr)
self.assertTrue(fixture["probe"].exists())
if __name__ == "__main__":
unittest.main()
+19
View File
@@ -6,6 +6,7 @@ import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from zipfile import ZipFile
@@ -19,6 +20,10 @@ class RuntimeInputsTest(unittest.TestCase):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
# Component archive validation has its own binary/archive fixtures.
component_check = patch.object(runtime, 'verify_powervr')
component_check.start()
self.addCleanup(component_check.stop)
paths = runtime.outputs(self.root)
for name in runtime.required():
path = self.root / paths.get(name, 'app/src/main/' + name)
@@ -69,6 +74,20 @@ class RuntimeInputsTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'quest1.tzst'):
runtime.record(self.root)
def test_changed_powervr_wrapper_rejects_old_outputs(self):
wrapper = self.root / 'tools/hybris/run-proton.py'
wrapper.parent.mkdir(parents=True)
wrapper.write_text('current wrapper')
runtime.record(self.root)
wrapper.write_text('changed wrapper')
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_missing_powervr_bundle_cannot_be_attested(self):
(self.root / 'app/src/main/assets/hybris/runtime.tzst').unlink()
with self.assertRaisesRegex(ValueError, 'assets/hybris/runtime.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')
+91
View File
@@ -0,0 +1,91 @@
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import tempfile
import unittest
WRAPPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset"
class SteamHelperAffinityTest(unittest.TestCase):
def launch(self, status, form="helper", configured=True):
with tempfile.TemporaryDirectory(prefix="droiddeck-helper-") as temporary:
root = Path(temporary)
helper = root / "steamwebhelper"
helper.write_text(f"#!{sys.executable}\n" +
'import json, os, sys\n'
'with open(os.environ["STARTS"],"a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
'sys.exit(23)\n')
helper.chmod(0o755)
real = root / "real-taskset"
real.write_text(f"#!{sys.executable}\n" +
'import json, os, sys\n'
'with open(os.environ["TRACE"],"a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
f'sys.exit({status})\n')
real.chmod(0o755)
wrapper = root / "taskset"
wrapper.write_text(WRAPPER.read_text().replace("/usr/bin/taskset", shlex.quote(str(real))))
helper_path = helper
if form == "alias":
helper_path = root / "helper symlink"
helper_path.symlink_to(helper)
elif form == "other":
helper_path = root / "other/steamwebhelper"
helper_path.parent.mkdir()
helper_path.write_text(helper.read_text())
helper_path.chmod(0o755)
args = ["0x7c", str(helper_path), "arg with spaces", "--literal=$HOME"]
if form == "query":
args = ["-p", "12345"]
elif form == "invalid":
args[0] = "not-a-mask"
elif form == "empty":
args = []
env = dict(os.environ, TRACE=str(root / "trace"), STARTS=str(root / "starts"))
env.pop("BL_STEAM_WEBHELPER", None)
if configured:
env["BL_STEAM_WEBHELPER"] = str(helper)
result = subprocess.run(["bash", str(wrapper), *args], env=env,
capture_output=True, text=True, timeout=5)
trace = [json.loads(x) for x in (root / "trace").read_text().splitlines()]
starts = ([json.loads(x) for x in (root / "starts").read_text().splitlines()]
if (root / "starts").exists() else [])
return result, trace, starts, args
def test_denied_pinning_still_executes_helper_once(self):
result, trace, starts, args = self.launch(1)
self.assertEqual(result.returncode, 23)
self.assertEqual(starts, [args[2:]])
self.assertEqual(len(trace), 1)
self.assertEqual(trace[0][:2], ["-p", "0x7c"])
self.assertRegex(trace[0][2], r"^[1-9][0-9]*$")
self.assertIn("using the allowed CPUs", result.stderr)
def test_successful_pinning_preserves_helper_exit_status(self):
result, trace, starts, args = self.launch(0)
self.assertEqual(result.returncode, 23)
self.assertEqual(starts, [args[2:]])
self.assertEqual(trace[0][:2], ["-p", "0x7c"])
self.assertNotIn("pinning unavailable", result.stderr)
def test_symlink_to_actual_helper_is_recognized(self):
result, _, starts, args = self.launch(1, "alias")
self.assertEqual(result.returncode, 23)
self.assertEqual(starts, [args[2:]])
def test_other_taskset_forms_and_targets_pass_through(self):
for form, configured in [("other", True), ("query", True), ("invalid", True),
("empty", True), ("helper", False)]:
with self.subTest(form=form, configured=configured):
result, trace, starts, args = self.launch(47, form, configured)
self.assertEqual(result.returncode, 47)
self.assertEqual(trace, [args])
self.assertEqual(starts, [])
self.assertNotIn("pinning unavailable", result.stderr)
if __name__ == "__main__":
unittest.main()
+73
View File
@@ -0,0 +1,73 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
class SteamPresentationTest(unittest.TestCase):
def launch(self, enabled=None, inherited=None):
source = SESSION.read_text()
begin = source.index(" bl_steam_path=$PATH")
end = source.index("\n # Decky", begin)
command = source.index(' PATH="$bl_steam_path"')
command_end = source.index("\n rc=$?", command)
script = (source[begin:end] + '\n_bl_ui=(-gamepadui); _bl_cdp=(); _bl_lang=()\n'
+ source[command:command_end])
env = dict(os.environ)
for key in ("BL_STEAM_GL_PRESENT", "DISABLE_GAMESCOPE_WSI", "LIBGL_KOPPER_DISABLE"):
env.pop(key, None)
if enabled is not None:
env["BL_STEAM_GL_PRESENT"] = enabled
env.update(inherited or {})
with tempfile.TemporaryDirectory(prefix="droiddeck-steam-gl-") as tmp:
program = Path(tmp) / "steamrtarm64/steam"
program.parent.mkdir()
program.write_text(f"#!{sys.executable}\n" +
'import json, os, sys\nprint(json.dumps({"args":sys.argv[1:],'
'"disable":os.getenv("DISABLE_GAMESCOPE_WSI"),'
'"kopper":os.getenv("LIBGL_KOPPER_DISABLE"),'
'"path":os.getenv("PATH"),'
'"helper":os.getenv("BL_STEAM_WEBHELPER")}))\n')
program.chmod(0o755)
env.update(steam_root=tmp, steam_channel="steamdeck_publicbeta")
result = subprocess.run(["bash", "-c", script, "test", "steam://open/main"],
env=env, capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, 0, result.stderr)
launch = json.loads(result.stdout.splitlines()[-1])
self.assertEqual(enabled == "1", launch["path"].startswith("/usr/local/libexec/droiddeck-steam:"))
self.assertEqual(launch["helper"], str(Path(tmp) / "steamrtarm64/steamwebhelper"))
return launch
def test_default_keeps_vulkan(self):
result = self.launch()
self.assertIn("-cef-use-angle=vulkan", result["args"])
self.assertNotIn("-cef-disable-gpu-compositing", result["args"])
self.assertIsNone(result["disable"])
self.assertIsNone(result["kopper"])
def test_system_powervr_keeps_gpu_gl_with_software_web_compositing(self):
result = self.launch("1")
self.assertIn("-cef-use-angle=gl", result["args"])
self.assertIn("-cef-use-gl=angle", result["args"])
self.assertIn("-cef-force-gpu", result["args"])
self.assertIn("-cef-disable-gpu-compositing", result["args"])
self.assertNotIn("-cef-disable-gpu", result["args"])
self.assertEqual(result["disable"], "1")
self.assertEqual(result["kopper"], "true")
self.assertEqual(result["args"][-1], "steam://open/main")
def test_disabled_option_preserves_existing_environment(self):
result = self.launch("0", {"DISABLE_GAMESCOPE_WSI": "0", "LIBGL_KOPPER_DISABLE": "false"})
self.assertIn("-cef-use-angle=vulkan", result["args"])
self.assertNotIn("-cef-disable-gpu-compositing", result["args"])
self.assertEqual(result["disable"], "0")
self.assertEqual(result["kopper"], "false")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,63 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
def vulkan_include_args():
candidates = []
for name in ("ANDROID_NDK_HOME", "ANDROID_NDK_ROOT"):
if os.environ.get(name):
candidates.append(Path(os.environ[name]))
android_home = os.environ.get("ANDROID_HOME")
if android_home:
ndk_root = Path(android_home) / "ndk"
version = os.environ.get("NDK_VERSION")
if version:
candidates.append(ndk_root / version)
if ndk_root.is_dir():
candidates.extend(sorted(ndk_root.iterdir(), reverse=True))
for ndk in candidates:
include = ndk / "toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include"
if (include / "vulkan/vulkan.h").is_file():
return ["-idirafter", str(include)]
return []
class VkExternalImageSyncTest(unittest.TestCase):
def test_client_barrier_pair(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the Vulkan image-sync regression test")
tests = Path(__file__).resolve().parent
source = tests / "vk_external_image_sync_test.c"
includes = tests.parents[1] / "app/src/main/cpp/waylandcomp/src"
with tempfile.TemporaryDirectory(prefix="droiddeck-vk-sync-") as tmp:
program = Path(tmp) / "vk-external-image-sync"
command = [
compiler,
"-std=c11",
"-Wall",
"-Wextra",
"-Werror",
"-UNDEBUG",
"-I",
str(includes),
*vulkan_include_args(),
str(source),
"-o",
str(program),
]
built = subprocess.run(command, capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
LAYER = TOOLS / "linuxfs/xclipse-layer"
class XclipseLayerTest(unittest.TestCase):
def test_layer_against_a_mock_loader_and_driver(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the Xclipse layer regression test")
# The build compiles the layer against the distribution's headers (libvulkan-dev);
# VULKAN_INCLUDE points elsewhere, e.g. a Vulkan-Headers checkout on macOS.
include = Path(os.environ.get("VULKAN_INCLUDE", "/usr/include"))
if not (include / "vulkan/vk_layer.h").is_file():
self.fail("Vulkan headers are required: install libvulkan-dev or set VULKAN_INCLUDE")
with tempfile.TemporaryDirectory(prefix="droiddeck-xclipse-") as tmp:
program = Path(tmp) / "xclipse-layer"
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
"-UNDEBUG", "-pthread", "-I", str(LAYER), "-I", str(include),
str(Path(__file__).with_name("xclipse_layer_test.c")), "-ldl", "-o", str(program)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
self.assertIn("xclipse layer ok", ran.stdout)
def test_device_chain_table_matches_its_generator(self):
registry = os.environ.get("VULKAN_REGISTRY")
if not registry:
self.skipTest("set VULKAN_REGISTRY to a Vulkan-Headers 1.3.275 checkout to recheck device_chain.inc")
with tempfile.TemporaryDirectory(prefix="droiddeck-chain-") as tmp:
output = Path(tmp) / "device_chain.inc"
subprocess.run(["python3", str(LAYER / "gen_device_chain.py"), str(Path(registry) / "registry/vk.xml"),
str(Path(registry) / "include/vulkan/vulkan_core.h"), str(output)],
check=True, capture_output=True)
self.assertEqual(output.read_text(), (LAYER / "device_chain.inc").read_text())
if __name__ == "__main__":
unittest.main()
+63
View File
@@ -0,0 +1,63 @@
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include "vk_external_image_sync.h"
static void check_external_pair(const struct vkp_external_client_barrier_pair *pair,
VkImage image, uint32_t queue_family) {
assert(pair->acquire.sType == VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER);
assert(pair->acquire.oldLayout == VK_IMAGE_LAYOUT_GENERAL);
assert(pair->acquire.newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
assert(pair->acquire.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
assert(pair->acquire.dstQueueFamilyIndex == queue_family);
assert(pair->acquire.image == image);
assert(pair->acquire.srcAccessMask == 0);
assert(pair->acquire.dstAccessMask == VK_ACCESS_TRANSFER_READ_BIT);
assert(pair->acquire.subresourceRange.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
assert(pair->acquire.subresourceRange.baseMipLevel == 0);
assert(pair->acquire.subresourceRange.levelCount == 1);
assert(pair->acquire.subresourceRange.baseArrayLayer == 0);
assert(pair->acquire.subresourceRange.layerCount == 1);
assert(pair->release.sType == VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER);
assert(pair->release.oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
assert(pair->release.newLayout == VK_IMAGE_LAYOUT_GENERAL);
assert(pair->release.srcQueueFamilyIndex == queue_family);
assert(pair->release.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
assert(pair->release.image == image);
assert(pair->release.srcAccessMask == VK_ACCESS_MEMORY_READ_BIT);
assert(pair->release.dstAccessMask == 0);
assert(pair->release.subresourceRange.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
assert(pair->release.subresourceRange.levelCount == 1);
assert(pair->release.subresourceRange.layerCount == 1);
}
int main(void) {
const VkImage image = (VkImage)(uintptr_t)0x1234;
const VkImage ahb_image = (VkImage)(uintptr_t)0x5678;
const uint32_t queue_family = 7;
struct vkp_external_client_barrier_pair generic, ahb;
assert(vkp_external_client_barrier_pair(image, queue_family, 1, 0, &generic));
check_external_pair(&generic, image, queue_family);
/* AHardwareBuffer imports deliberately use the same client flags and lifecycle. */
assert(vkp_external_client_barrier_pair(ahb_image, queue_family, 1, 0, &ahb));
check_external_pair(&ahb, ahb_image, queue_family);
unsigned char untouched[sizeof(generic)];
memset(&generic, 0xa5, sizeof(generic));
memcpy(untouched, &generic, sizeof(generic));
assert(!vkp_external_client_barrier_pair(image, queue_family, 0, 0, &generic));
assert(memcmp(&generic, untouched, sizeof(generic)) == 0);
assert(!vkp_is_external_client_image(0, 0));
memset(&generic, 0x5a, sizeof(generic));
memcpy(untouched, &generic, sizeof(generic));
assert(!vkp_external_client_barrier_pair(image, queue_family, 1, 1, &generic));
assert(memcmp(&generic, untouched, sizeof(generic)) == 0);
assert(!vkp_is_external_client_image(1, 1));
assert(vkp_is_external_client_image(1, 0));
return 0;
}
+217
View File
@@ -0,0 +1,217 @@
/* The Xclipse layer between a simulated loader and a mock driver. The driver refuses what the compat
* layer and Samsung's driver refuse: textureCompressionBC, and a compute layout holding an immutable
* YCbCr sampler. Built by test_xclipse_layer.py with the layer source included directly. */
#include "xclipse_layer.c"
#include <assert.h>
struct object { void *dispatch; };
static int instance_table, device_table[4];
static struct object mock_instance = {&instance_table}, mock_physical = {&instance_table};
static struct object mock_devices[4] = {{&device_table[0]}, {&device_table[1]}, {&device_table[2]}, {&device_table[3]}};
static int devices_created;
/* What the driver last saw. */
static int driver_saw_bc, driver_saw_layout_sampler_count;
static VkSampler driver_layout_samplers[16];
static uint64_t next_sampler = 0x100;
static VkSampler driver_ycbcr[16];
static int driver_ycbcr_count;
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance) {
*instance = (VkInstance)&mock_instance;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features) {
memset(features, 0, sizeof(*features));
}
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features) {
mock_features(physical, &features->features);
}
/* The compat layer's emulation: BC formats sample, the feature bit stays off. */
static void VKAPI_CALL mock_format_properties(VkPhysicalDevice physical, VkFormat format, VkFormatProperties *out) {
memset(out, 0, sizeof(*out));
if (format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC7_SRGB_BLOCK)
out->optimalTilingFeatures = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
}
static void VKAPI_CALL mock_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out) {
mock_format_properties(physical, format, &out->formatProperties);
}
static VkResult VKAPI_CALL mock_time_domains(VkPhysicalDevice physical, uint32_t *count, VkTimeDomainEXT *domains) {
if (domains) { domains[0] = VK_TIME_DOMAIN_DEVICE_EXT; domains[1] = VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT; }
*count = 2;
return VK_SUCCESS;
}
static VkResult VKAPI_CALL mock_create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDevice *device) {
driver_saw_bc = info->pEnabledFeatures && info->pEnabledFeatures->textureCompressionBC;
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext)
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
((const VkPhysicalDeviceFeatures2 *)p)->features.textureCompressionBC) driver_saw_bc = 1;
if (driver_saw_bc) return VK_ERROR_FEATURE_NOT_PRESENT;
assert(devices_created < 4);
*device = (VkDevice)&mock_devices[devices_created++];
return VK_SUCCESS;
}
static VkResult VKAPI_CALL mock_create_sampler(VkDevice device, const VkSamplerCreateInfo *info,
const VkAllocationCallbacks *allocator, VkSampler *sampler) {
*sampler = (VkSampler)next_sampler++;
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext)
if (p->sType == VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO) driver_ycbcr[driver_ycbcr_count++] = *sampler;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_sampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *allocator) {
for (int i = 0; i < driver_ycbcr_count; i++)
if (driver_ycbcr[i] == sampler) driver_ycbcr[i] = driver_ycbcr[--driver_ycbcr_count];
}
static VkResult VKAPI_CALL mock_create_set_layout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDescriptorSetLayout *layout) {
driver_saw_layout_sampler_count = 0;
for (uint32_t b = 0; b < info->bindingCount; b++) {
const VkDescriptorSetLayoutBinding *binding = &info->pBindings[b];
for (uint32_t s = 0; binding->pImmutableSamplers && s < binding->descriptorCount; s++) {
VkSampler sampler = binding->pImmutableSamplers[s];
driver_layout_samplers[driver_saw_layout_sampler_count++] = sampler;
for (int i = 0; i < driver_ycbcr_count; i++)
if ((binding->stageFlags & VK_SHADER_STAGE_COMPUTE_BIT) && driver_ycbcr[i] == sampler)
return VK_ERROR_UNKNOWN;
}
}
*layout = (VkDescriptorSetLayout)0x5000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_timestamps(VkDevice device, uint32_t count, const VkCalibratedTimestampInfoEXT *infos,
uint64_t *timestamps, uint64_t *deviation) {
for (uint32_t i = 0; i < count; i++) timestamps[i] = 42;
*deviation = 1;
return VK_SUCCESS;
}
#define MOCK(name, function) if (!strcmp(requested, name)) return (PFN_vkVoidFunction)function
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gipa(VkInstance instance, const char *requested) {
MOCK("vkCreateInstance", mock_create_instance);
MOCK("vkCreateDevice", mock_create_device);
MOCK("vkGetPhysicalDeviceFeatures", mock_features);
MOCK("vkGetPhysicalDeviceFeatures2", mock_features2);
MOCK("vkGetPhysicalDeviceFormatProperties", mock_format_properties);
MOCK("vkGetPhysicalDeviceFormatProperties2", mock_format_properties2);
MOCK("vkGetPhysicalDeviceCalibrateableTimeDomainsEXT", mock_time_domains);
return NULL;
}
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const char *requested) {
MOCK("vkCreateSampler", mock_create_sampler);
MOCK("vkDestroySampler", mock_destroy_sampler);
MOCK("vkCreateDescriptorSetLayout", mock_create_set_layout);
MOCK("vkDestroyDevice", mock_destroy_device);
MOCK("vkGetCalibratedTimestampsEXT", mock_timestamps);
return NULL;
}
/* The loader's link for one vkCreateDevice call, then the caller's own chain. */
static VkResult create(const void *chain, const VkPhysicalDeviceFeatures *enabled, VkDevice *device) {
VkLayerDeviceLink link = {NULL, mock_gipa, mock_gdpa};
VkLayerDeviceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, chain, VK_LAYER_LINK_INFO, {&link}};
VkDeviceCreateInfo info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &loader, 0, 0, NULL, 0, NULL, 0, NULL, enabled};
PFN_vkCreateDevice create_device = (PFN_vkCreateDevice)vkGetInstanceProcAddr((VkInstance)&mock_instance, "vkCreateDevice");
return create_device((VkPhysicalDevice)&mock_physical, &info, NULL, device);
}
int main(void) {
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
VkLayerInstanceLink instance_link = {NULL, mock_gipa, NULL};
VkLayerInstanceCreateInfo instance_loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO,
{&instance_link}};
VkInstanceCreateInfo instance_info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &instance_loader};
VkInstance instance;
PFN_vkCreateInstance create_instance_fn = (PFN_vkCreateInstance)vkGetInstanceProcAddr(NULL, "vkCreateInstance");
assert(create_instance_fn(&instance_info, NULL, &instance) == VK_SUCCESS);
/* The emulated bit is reported... */
VkPhysicalDeviceFeatures features;
((PFN_vkGetPhysicalDeviceFeatures)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures"))(
(VkPhysicalDevice)&mock_physical, &features);
assert(features.textureCompressionBC);
/* ...and cleared before the driver, through pEnabledFeatures... */
VkDevice device;
VkPhysicalDeviceFeatures legacy = {.textureCompressionBC = VK_TRUE};
assert(create(NULL, &legacy, &device) == VK_SUCCESS && !driver_saw_bc && legacy.textureCompressionBC);
/* ...and through a VkPhysicalDeviceFeatures2 behind another structure, leaving the caller's chain intact. */
VkPhysicalDeviceVulkan12Features vk12 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
VkPhysicalDeviceFeatures2 features2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &vk12,
{.textureCompressionBC = VK_TRUE}};
VkPhysicalDeviceTimelineSemaphoreFeatures timeline = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES,
&features2, VK_TRUE};
VkPhysicalDeviceFeatures2 features2_before = features2;
VkPhysicalDeviceTimelineSemaphoreFeatures timeline_before = timeline;
VkDevice chained;
assert(create(&timeline, NULL, &chained) == VK_SUCCESS && !driver_saw_bc);
assert(!memcmp(&features2, &features2_before, sizeof(features2)));
assert(!memcmp(&timeline, &timeline_before, sizeof(timeline)));
/* A structure newer than the headers this was built with cannot be copied: the chain passes as it
* is and the driver refuses the bit, without the caller's structures being written. */
struct { VkStructureType sType; const void *pNext; uint32_t payload; } future = {(VkStructureType)0x7ffffff0, &features2, 7};
VkDevice unused;
assert(create(&future, NULL, &unused) == VK_ERROR_FEATURE_NOT_PRESENT);
assert(!memcmp(&features2, &features2_before, sizeof(features2)) && future.pNext == &features2);
/* Compute layouts get a plain sampler in place of a YCbCr one. */
PFN_vkCreateSampler create_sampler_fn = (PFN_vkCreateSampler)vkGetDeviceProcAddr(device, "vkCreateSampler");
PFN_vkDestroySampler destroy_sampler_fn = (PFN_vkDestroySampler)vkGetDeviceProcAddr(device, "vkDestroySampler");
PFN_vkCreateDescriptorSetLayout create_layout = (PFN_vkCreateDescriptorSetLayout)vkGetDeviceProcAddr(device, "vkCreateDescriptorSetLayout");
VkSamplerYcbcrConversionInfo conversion = {VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, NULL, (VkSamplerYcbcrConversion)1};
VkSamplerCreateInfo ycbcr_info = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .pNext = &conversion};
VkSamplerCreateInfo plain_info = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
VkSampler ycbcr;
assert(create_sampler_fn(device, &ycbcr_info, NULL, &ycbcr) == VK_SUCCESS);
VkSampler immutable[2] = {ycbcr, ycbcr};
VkDescriptorSetLayoutBinding binding = {4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, VK_SHADER_STAGE_COMPUTE_BIT, immutable};
VkDescriptorSetLayoutCreateInfo layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 1, &binding};
VkDescriptorSetLayout layout;
assert(create_layout(device, &layout_info, NULL, &layout) == VK_SUCCESS);
assert(driver_layout_samplers[0] != ycbcr && immutable[0] == ycbcr);
/* A destroyed YCbCr sampler's handle, reused for a plain sampler, is left alone. */
destroy_sampler_fn(device, ycbcr, NULL);
next_sampler = (uint64_t)ycbcr;
VkSampler reused;
assert(create_sampler_fn(device, &plain_info, NULL, &reused) == VK_SUCCESS && reused == ycbcr);
immutable[0] = immutable[1] = reused;
assert(create_layout(device, &layout_info, NULL, &layout) == VK_SUCCESS && driver_layout_samplers[0] == reused);
/* Registrations belong to their device and go with it. */
VkSampler other;
assert(create_sampler_fn(chained, &ycbcr_info, NULL, &other) == VK_SUCCESS && ycbcr_count == 1);
((PFN_vkDestroyDevice)vkGetDeviceProcAddr(chained, "vkDestroyDevice"))(chained, NULL);
assert(ycbcr_count == 0);
/* The KHR calibrated-timestamp entry points reach the EXT ones. */
uint32_t domains = 0;
PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT time_domains = (PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT)
vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR");
assert(time_domains((VkPhysicalDevice)&mock_physical, &domains, NULL) == VK_SUCCESS && domains == 2);
VkCalibratedTimestampInfoEXT stamp = {VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, NULL, VK_TIME_DOMAIN_DEVICE_EXT};
uint64_t value = 0, deviation = 0;
PFN_vkGetCalibratedTimestampsEXT timestamps = (PFN_vkGetCalibratedTimestampsEXT)vkGetDeviceProcAddr(device, "vkGetCalibratedTimestampsKHR");
assert(timestamps(device, 1, &stamp, &value, &deviation) == VK_SUCCESS && value == 42);
puts("xclipse layer ok");
return 0;
}