): String? = when (gpu.family) {
- Family.NOT_ADRENO -> null
+ Family.NOT_ADRENO, Family.POWERVR -> null
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
Family.A7XX_LOW -> BANNER_710
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt
index 87bf01d4dd..b27c85aaaf 100644
--- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt
+++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt
@@ -35,6 +35,7 @@ data class GpuInfo(
A6XX("Adreno 6xx"),
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
ADRENO_UNKNOWN("Adreno"),
+ POWERVR("PowerVR"),
NOT_ADRENO("Not an Adreno GPU");
/** [label] in the app's language: the Adreno families are names, the rest is words. */
@@ -56,15 +57,22 @@ data class GpuInfo(
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
- Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
- else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
- Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
+ Support.UNTESTED -> when (family) {
+ Family.POWERVR -> "System PowerVR driver: compatibility varies by device"
+ Family.A7XX_LOW -> "Experimental: its drivers are test builds"
+ else -> "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
+ }
+ Support.UNSUPPORTED -> "Not supported: no compatible graphics backend is available for this GPU"
}
/** [supportText] in the app's language. */
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
- Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
+ Support.UNTESTED -> when (family) {
+ Family.POWERVR -> R.string.gpuinfo_powervr
+ Family.A7XX_LOW -> R.string.gpuinfo_experimental
+ else -> R.string.gpuinfo_below_tested
+ }
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
})
@@ -94,10 +102,17 @@ data class GpuInfo(
fromPlatform > 0 -> "platform"
else -> ""
}
- val family = familyOf(adreno, model)
+ val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr())
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
- name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
+ name = when {
+ family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
+ VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
+ }
+ !adreno -> Build.HARDWARE.ifBlank { UNNAMED }
+ model > 0 -> "Adreno $model"
+ else -> "Adreno"
+ },
model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source,
@@ -122,7 +137,8 @@ data class GpuInfo(
""
}
- internal fun familyOf(adreno: Boolean, model: Int): Family = when {
+ internal fun familyOf(adreno: Boolean, model: Int, powerVr: Boolean = false): Family = when {
+ !adreno && powerVr -> Family.POWERVR
!adreno -> Family.NOT_ADRENO
model == 0 -> Family.ADRENO_UNKNOWN
model >= 800 -> Family.A8XX
diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java
index 4662f894f9..87d71f6497 100644
--- a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java
+++ b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java
@@ -3,8 +3,12 @@ package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
+import com.droiddeck.launcher.R;
+
import java.util.ArrayList;
import java.util.List;
+import java.util.function.Function;
+import java.util.function.Supplier;
/**
* The Vulkan driver a session draws with inside the runtime: in Steam mode the native client's
@@ -17,7 +21,8 @@ import java.util.List;
* these are glibc processes, that one is bionic.
*
* "" (the default) means the driver the runtime was built with, at
- * {@code usr/lib/libvulkan_freedreno.so} inside it - nothing is set and nothing is touched.
+ * {@code usr/lib/libvulkan_freedreno.so} on Adreno, or the bundled bridge to the system
+ * PowerVR driver.
* Otherwise the value is an imported driver's id ({@link LinuxVulkanDriverManager}), and the
* session is handed that driver's ICD manifest in {@code BL_VK_DRIVER}: the session script points
* the Vulkan loader at it with {@code VK_DRIVER_FILES} after checking both the manifest and the
@@ -47,30 +52,44 @@ public final class LinuxVulkanDriver {
}
/**
- * Label for a stored value. An id that is no longer installed says so - the launch path falls
- * back to the runtime's own driver for it.
+ * Label for a stored value. Missing imports fall back to the runtime on Adreno;
+ * PowerVR requires another explicit selection or Auto before launching.
*/
public static String optionLabel(Context context, String value) {
- if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
+ if (value == null || value.isEmpty()) return SystemVulkanDriver.isPowerVr()
+ ? context.getString(R.string.gpu_system_powervr) : "Runtime default (built into the runtime)";
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
- if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
+ if (!m.isInstalled(value)) return value + (SystemVulkanDriver.isPowerVr()
+ ? " (imported, missing)" : " (imported, missing - uses the runtime default)");
String ver = m.getDriverVersion(value);
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
}
/**
* The ICD manifest path to hand the session, or null to leave the runtime's own driver alone.
- * An id whose import is gone resolves to null rather than failing the launch.
+ * A missing import uses the runtime's own driver on Adreno. PowerVR fails clearly instead:
+ * its system backend needs environment setup that an explicit import does not receive.
*/
public static String resolveIcdPath(Context context, String value) {
+ boolean powerVr = SystemVulkanDriver.isPowerVr();
+ return resolveIcdPath(value, powerVr,
+ () -> SystemVulkanDriver.icdPath(context), id -> {
+ String icd = new LinuxVulkanDriverManager(context).getIcdPath(id);
+ if (icd == null) Log.w(TAG, "imported Linux driver \"" + id + "\" is gone"
+ + (powerVr ? "" : "; using the runtime's own driver"));
+ else Log.i(TAG, "Linux session draws with imported driver " + id + " (" + icd + ")");
+ return icd;
+ });
+ }
+
+ /** Resolve the selected backend before looking up an imported driver. */
+ static String resolveIcdPath(String value, boolean powerVr, Supplier systemIcd,
+ Function importedIcd) {
+ if (SystemVulkanDriver.usesDefault(powerVr, value)) return systemIcd.get();
if (value == null || value.isEmpty()) return null;
- LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
- String icd = m.getIcdPath(value);
- if (icd == null) {
- Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
- return null;
- }
- Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
+ String icd = importedIcd.apply(value);
+ if (powerVr && icd == null) throw new IllegalStateException(
+ "Selected Linux Vulkan driver \"" + value + "\" is unavailable. Select an installed driver or use Auto.");
return icd;
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java
new file mode 100644
index 0000000000..b6f0e6efd2
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java
@@ -0,0 +1,254 @@
+package com.droiddeck.launcher.gpu;
+
+import android.content.Context;
+import android.os.Build;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+import com.droiddeck.launcher.core.FileUtils;
+import com.droiddeck.launcher.core.TarZst;
+import java.io.File;
+import java.io.IOException;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.List;
+import java.util.TreeSet;
+import java.util.UUID;
+import java.util.function.Predicate;
+import org.json.JSONObject;
+
+/** Isolated glibc-to-Android Vulkan bridge. It does not replace the rootfs's Mesa libraries. */
+public final class SystemVulkanDriver {
+ private static final String ASSET = "hybris/runtime.tzst";
+ /** Vendor HALs the bridge loads. Samsung Xclipse (Exynos, sgpu) is experimental. */
+ private static final String[] HALS = {
+ "/vendor/lib64/hw/vulkan.powervr.so",
+ "/vendor/lib64/hw/vulkan.samsung.so"
+ };
+ private static final String[] REQUIRED = {
+ "lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
+ "lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
+ "run-proton.py", "wsi/libVkLayer_window_system_integration.so",
+ "wsi/VkLayer_window_system_integration.json",
+ "dxvk/x32/d3d8.dll", "dxvk/x32/d3d9.dll", "dxvk/x32/d3d10core.dll",
+ "dxvk/x32/d3d11.dll", "dxvk/x32/dxgi.dll",
+ "dxvk/x64/d3d8.dll", "dxvk/x64/d3d9.dll", "dxvk/x64/d3d10core.dll",
+ "dxvk/x64/d3d11.dll", "dxvk/x64/dxgi.dll"
+ };
+
+ /** Rootfs directory of the Xclipse layer the apk stages (SessionFiles). */
+ private static final String XCLIPSE_LAYER_DIR = "/usr/local/lib/droiddeck-xclipse";
+
+ private SystemVulkanDriver() {}
+
+ /** The first vendor HAL present, or null. */
+ public static String hal() {
+ for (String path : HALS) if (new File(path).isFile()) return path;
+ return null;
+ }
+
+ /** Samsung's Xclipse (Exynos, sgpu) rather than PowerVR. */
+ public static boolean isXclipse() {
+ String hal = hal();
+ return hal != null && hal.endsWith("/vulkan.samsung.so");
+ }
+
+ /** The system-driver GPU family, for labels. */
+ public static String gpuName() { return isXclipse() ? "Xclipse" : "PowerVR"; }
+
+ /** Whether a system-driver GPU (PowerVR or Xclipse) is present; the name predates Xclipse. */
+ public static boolean isPowerVr() { return hal() != null; }
+
+ /** HAL detection names the GPU; launching also needs the real DRM render node. */
+ public static boolean isAvailable() { return isPowerVr() && renderNodeAvailable(); }
+
+ public static boolean renderNodeAvailable() {
+ return renderNodePath() != null;
+ }
+
+ /** Select the actual PowerVR node, including devices where another GPU owns renderD128. */
+ public static String renderNodePath() {
+ String[] nodes = new File("/dev/dri").list();
+ if (nodes == null) nodes = new File("/sys/class/drm").list();
+ return findRenderNode(nodes, SystemVulkanDriver::renderNodeAvailable);
+ }
+
+ static String findRenderNode(String[] nodes, Predicate available) {
+ TreeSet candidates = new TreeSet<>();
+ // Android can deny directory listing while allowing direct access. Probe the kernel's
+ // reserved render range too; directory entries also cover dynamically allocated minors.
+ for (int minor = 128; minor < 192; minor++) candidates.add("renderD" + minor);
+ if (nodes != null) for (String node : nodes)
+ if (node.matches("renderD[0-9]+")) candidates.add(node);
+ for (String node : candidates) {
+ String path = "/dev/dri/" + node;
+ if (available.test(path)) return path;
+ }
+ return null;
+ }
+
+ private static boolean renderNodeAvailable(String node) {
+ try {
+ if (!renderNodeAvailable(OsConstants.S_ISCHR(Os.stat(node).st_mode),
+ Os.access(node, OsConstants.R_OK), Os.access(node, OsConstants.W_OK))) return false;
+ return powerVrDevice(new File("/sys/class/drm/" + new File(node).getName() + "/device"));
+ } catch (ErrnoException error) {
+ return false;
+ }
+ }
+
+ static boolean powerVrDriver(String driver) {
+ return "pvrsrvkm".equals(driver) || "pvr".equals(driver) || "powervr".equals(driver)
+ || "sgpu".equals(driver);
+ }
+
+ static boolean powerVrDevice(File device) {
+ try {
+ return powerVrDriver(Files.readSymbolicLink(new File(device, "driver").toPath())
+ .getFileName().toString());
+ } catch (IOException error) {
+ // Some Android policies expose uevent but deny reading the driver symlink.
+ try (BufferedReader input = Files.newBufferedReader(
+ new File(device, "uevent").toPath(), StandardCharsets.US_ASCII)) {
+ String line;
+ while ((line = input.readLine()) != null)
+ if (line.startsWith("DRIVER=")) return powerVrDriver(line.substring(7));
+ } catch (IOException ignored) { }
+ return false;
+ }
+ }
+
+ static boolean renderNodeAvailable(boolean characterDevice, boolean readable, boolean writable) {
+ return characterDevice && readable && writable;
+ }
+
+ public static boolean usesDefault(String choice) {
+ return usesDefault(isPowerVr(), choice);
+ }
+
+ static boolean usesDefault(boolean powerVr, String choice) {
+ return powerVr && (choice == null || choice.isEmpty());
+ }
+
+ /** APK-versioned directories stay intact while an older session still has libraries mapped. */
+ public static synchronized File prepare(Context context) throws IOException {
+ if (!isPowerVr()) throw new IOException("System PowerVR Vulkan driver is unavailable");
+ if (!renderNodeAvailable()) throw new IOException(
+ "System PowerVR requires an identifiable, readable and writable DRM render node");
+ File target = runtimeDirectory(context);
+ File base = target.getParentFile();
+ if (complete(target)) return target;
+ if (!base.isDirectory() && !base.mkdirs()) throw new IOException("Cannot create system Vulkan directory");
+ File staged = new File(base, ".stage-" + UUID.randomUUID());
+ try {
+ if (!TarZst.extractAsset(context, ASSET, staged)) throw new IOException("Cannot unpack system Vulkan runtime");
+ for (String name : REQUIRED)
+ if (!present(staged, name)) throw new IOException("Missing system Vulkan component: " + name);
+ if (!new File(staged, "run-proton.py").canExecute())
+ throw new IOException("System Vulkan Proton wrapper is not executable");
+ JSONObject library = new JSONObject();
+ library.put("library_path", new File(target, REQUIRED[0]).getPath());
+ library.put("api_version", "1.3.0");
+ JSONObject manifest = new JSONObject();
+ manifest.put("file_format_version", "1.0.0");
+ manifest.put("ICD", library);
+ Files.write(new File(staged, "icd.json").toPath(), manifest.toString().getBytes(StandardCharsets.UTF_8));
+ if (target.exists()) throw new IOException("Incomplete system Vulkan runtime directory: " + target.getName());
+ if (!staged.renameTo(target)) throw new IOException("Cannot publish system Vulkan runtime");
+ return target;
+ } catch (org.json.JSONException error) {
+ throw new IOException("Cannot write system Vulkan manifest", error);
+ } finally {
+ if (staged.exists()) FileUtils.delete(staged);
+ }
+ }
+
+ /** The current APK's versioned runtime path, without extracting or modifying it. */
+ public static File runtimeDirectory(Context context) throws IOException {
+ String version;
+ try (BufferedReader input = new BufferedReader(new InputStreamReader(
+ context.getAssets().open("hybris/version.txt"), StandardCharsets.US_ASCII))) {
+ version = input.readLine();
+ }
+ if (version == null || !version.matches("[0-9a-f]{64}")) throw new IOException("Invalid system Vulkan runtime version");
+ return new File(new File(context.getFilesDir(), "system_vulkan"), version);
+ }
+
+ /** Collect abandoned stages, and obsolete versions once older guests can no longer load them. */
+ public static synchronized void pruneUnused(Context context, boolean guestsStopped) throws IOException {
+ pruneUnused(runtimeDirectory(context), guestsStopped);
+ }
+
+ static synchronized void pruneUnused(File current, boolean guestsStopped) {
+ File base = current.getParentFile();
+ if (base == null || Files.isSymbolicLink(base.toPath()) || Files.isSymbolicLink(current.toPath())) return;
+ File[] entries = base.listFiles();
+ if (entries == null) return;
+ // Retain the previous good version if publishing the replacement failed.
+ boolean pruneVersions = guestsStopped && complete(current);
+ for (File entry : entries) {
+ if (entry.equals(current)) continue;
+ String name = entry.getName();
+ boolean oldVersion = pruneVersions && name.matches("[0-9a-f]{64}");
+ boolean abandonedStage = name.matches("\\.stage-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+ // The prepare monitor excludes any extraction still writing a .stage directory.
+ if (oldVersion || abandonedStage) FileUtils.delete(entry);
+ }
+ }
+
+ private static boolean complete(File directory) {
+ if (!new File(directory, "icd.json").isFile()) return false;
+ for (String name : REQUIRED) if (!present(directory, name)) return false;
+ return new File(directory, "run-proton.py").canExecute();
+ }
+
+ private static boolean present(File directory, String name) {
+ File file = new File(directory, name);
+ return file.isFile() && file.length() > 0;
+ }
+
+ public static String icdPath(Context context) {
+ try {
+ return new File(prepare(context), "icd.json").getPath();
+ } catch (IOException error) {
+ throw new IllegalStateException("System Vulkan runtime is unavailable", error);
+ }
+ }
+
+ public static void addEnvironment(Context context, List environment) {
+ File directory;
+ try { directory = prepare(context); }
+ catch (IOException error) { throw new IllegalStateException("System Vulkan runtime is unavailable", error); }
+ String node = renderNodePath();
+ if (node == null) throw new IllegalStateException("System PowerVR render node is unavailable");
+ environment.add("HYBRIS_ANDROID_SDK_VERSION=" + Build.VERSION.SDK_INT);
+ environment.add("HYBRIS_VULKAN_HAL=" + hal());
+ environment.add("HYBRIS_LINKER_DIR=" + new File(directory, "lib/libhybris/linker").getPath());
+ // Prefer framework dependencies for the system Vulkan loader, including libbase.so.
+ environment.add("HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64");
+ boolean xclipse = isXclipse();
+ // Xclipse gets its own layer (tools/linuxfs/xclipse-layer) in front of everything: it sets
+ // bionic's environ for the driver's shader compiler, among other driver workarounds. The
+ // session's own clients need nothing else; games keep the compat layer's BC emulation.
+ String layers = xclipse ? "VK_LAYER_DROIDDECK_xclipse" : "VK_LAYER_HYBRIS_compat";
+ environment.add("VK_LAYER_PATH=" + new File(directory, "lib").getPath() + (xclipse ? ":" + XCLIPSE_LAYER_DIR : ""));
+ environment.add("VK_INSTANCE_LAYERS=" + layers);
+ // Proton game launches add their WSI layer in front of these (droiddeck-game-env).
+ environment.add("DROIDDECK_HYBRIS_LAYERS=" + (xclipse ? layers + ":VK_LAYER_HYBRIS_compat" : layers));
+ if (xclipse) environment.add("DROIDDECK_HYBRIS_LAYER_PATH=" + XCLIPSE_LAYER_DIR);
+ // DXVK 3 needs 256 bytes of push constants; this driver has 128.
+ if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
+ // The Android driver has a render node, but no KMS primary node. SDL presents
+ // through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
+ environment.add("BL_GAMESCOPE_BACKEND=sdl");
+ // The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
+ environment.add("BL_POWERVR_DRM_HANDLES=1");
+ environment.add("BL_POWERVR_RENDER_NODE=" + node);
+ // Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
+ environment.add("BL_STEAM_GL_PRESENT=1");
+ // Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
+ environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
index 27083a544a..cfa9c44b88 100644
--- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
+++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
@@ -25,9 +25,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
- * The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
+ * The Vulkan driver the in-app compositor runs on. Adreno uses Turnip: the system Adreno driver
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
- * over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
+ * over fails and the session renders nothing. PowerVR uses the system driver and Android hardware
+ * buffers instead. Two Turnip builds ship in the apk, one per Adreno
* generation, and the GPU decides which is unpacked - unless the user has imported an AdrenoTools
* zip of their own and chosen it, which then wins.
*
@@ -314,6 +315,7 @@ public final class TurnipDriver {
* and falls through, so a stale preference never blocks a session.
*/
private String choose() {
+ SessionPrefs.ensurePowerVrAutoDrivers(context);
String chosen = SessionPrefs.androidDriver(context);
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
@@ -339,6 +341,7 @@ public final class TurnipDriver {
if (forced.startsWith("a8")) return DRIVER_A8XX;
if (forced.startsWith("a7")) return DRIVER_A7XX;
}
+ if (SystemVulkanDriver.isPowerVr()) return null;
String model = gpuModel();
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
if (model != null) {
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
index 082bf814e9..64c90f2401 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
@@ -6,6 +6,7 @@ import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStat;
import android.system.StructUtsname;
+import com.droiddeck.launcher.gpu.SystemVulkanDriver;
import com.droiddeck.launcher.session.SessionPrefs;
@@ -200,6 +201,13 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
+ if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
+ // The glibc bridge loads the device's existing Android HAL and its dependencies.
+ // These read-only Android partitions remain subject to the app's normal permissions.
+ for (String path : new String[]{"/system", "/vendor", "/apex", "/system_ext", "/product", "/odm"})
+ if (new File(path).isDirectory()) bind(cmd, path);
+ if (new File("/linkerconfig/ld.config.txt").isFile()) bind(cmd, "/linkerconfig/ld.config.txt");
+ }
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin");
@@ -277,7 +285,11 @@ public final class LinuxRuntime {
bind(cmd, fake.getPath() + ":" + entry[1]);
}
}
- bindGpuNode(context, cmd);
+ if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
+ bindPowerVrGpuNode(context, cmd);
+ } else {
+ bindGpuNode(context, cmd);
+ }
bindAdrenoStats(cmd, extraBinds);
bindCpuTemps(cmd, root);
if (extraBinds != null) {
@@ -288,6 +300,30 @@ public final class LinuxRuntime {
return specs;
}
+ /**
+ * Tensor's render node is accessible directly, but Android denies listing its parent
+ * directory. libdrm enumerates that directory even when given the device number. Expose
+ * the real node through a listable private directory; retain its real sysfs identity.
+ */
+ private static void bindPowerVrGpuNode(Context context, List cmd) {
+ if (new File("/dev/dri").list() != null) return;
+ String node = SystemVulkanDriver.renderNodePath();
+ if (node == null) return;
+ String name = new File(node).getName();
+ // Keep only this node listable even if a previous boot assigned a different minor.
+ File dri = new File(context.getCacheDir(), "powervr-drm/" + name + "/dri");
+ try {
+ if (!dri.isDirectory() && !dri.mkdirs()) return;
+ new File(dri, name).createNewFile();
+ } catch (IOException e) {
+ android.util.Log.w("LinuxRuntime", "Cannot expose the PowerVR render node", e);
+ return;
+ }
+ bind(cmd, dri.getPath() + ":/dev/dri");
+ bind(cmd, node + ":" + node);
+ android.util.Log.i("LinuxRuntime", "PowerVR: exposing real " + name + " through a listable directory");
+ }
+
/**
* An app process may not open {@code /dev/dri} - the nodes exist but are labelled
* {@code graphics_device}, which stock policy grants surfaceflinger and not us - yet libdrm and
diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt
index aa489198f1..2bc822f19d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.GpuInfo
+import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
import com.github.luben.zstd.ZstdOutputStream
@@ -219,9 +220,13 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
- fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
+ fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
+ setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
+
+ internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
require(comp in COMPONENTS)
+ if (file != null) requireSelectable(context, comp, managed)
val state = loadState(context)
val profiles = state.sub("profiles")
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
@@ -694,6 +699,16 @@ object ComponentsManager {
return PreparedLaunchState(lines.toString(), keep)
}
+ /** DXVK is supplied at game launch by the selected system PowerVR runtime. */
+ internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
+
+ private fun runtimeManaged(context: Context, comp: String): Boolean =
+ runtimeManaged(comp, SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)))
+
+ private fun requireSelectable(context: Context, comp: String, managed: (String) -> Boolean = { runtimeManaged(context, it) }) {
+ check(!managed(comp)) { context.getString(R.string.cmgr_powervr_dxvk_managed) }
+ }
+
// ------------------------------------------------------------------ actions
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
@@ -701,6 +716,7 @@ object ComponentsManager {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
+ requireSelectable(context, info.comp)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
@@ -724,6 +740,7 @@ object ComponentsManager {
}
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
+ requireSelectable(context, comp)
val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
@@ -750,7 +767,9 @@ object ComponentsManager {
}
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
- fun applyQueued(context: Context): List = synchronized(lock) {
+ fun applyQueued(context: Context): List = applyQueued(context) { runtimeManaged(context, it) }
+
+ internal fun applyQueued(context: Context, managed: (String) -> Boolean): List = synchronized(lock) {
val state = loadState(context)
val queued = state.sub("queued")
if (queued.length() == 0) return emptyList()
@@ -762,6 +781,7 @@ object ComponentsManager {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val q = comps.optJSONObject(comp) ?: continue
+ if (managed(comp)) continue
runCatching {
if (q.optString("kind") == "original") {
val v = q.optString("protonVersion")
diff --git a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt
index 9a17a97aea..badcc34028 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt
@@ -27,6 +27,23 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
+ /** Signal 0 checks ownership/liveness without sending a signal, even when /proc is unreadable. */
+ fun hasOtherProcesses(): Boolean = hasOtherProcesses(
+ File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(),
+ ) { pid ->
+ try {
+ android.system.Os.kill(pid, 0)
+ true
+ } catch (error: android.system.ErrnoException) {
+ error.errno != android.system.OsConstants.ESRCH && error.errno != android.system.OsConstants.EPERM
+ } catch (error: SecurityException) {
+ true
+ }
+ }
+
+ internal fun hasOtherProcesses(pids: List?, ownPid: Int, signalable: (Int) -> Boolean): Boolean =
+ pids == null || pids.any { it > 1 && it != ownPid && signalable(it) }
+
fun reap(reason: String): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
index 4d2c1c3916..ef6455ede6 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
@@ -53,6 +53,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
+ "usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
@@ -129,6 +130,10 @@ object SessionFiles {
"usr/local/lib/mangoapp/libtraceevent.so.1",
"usr/local/lib/mangoapp/libtracefs.so.1",
).map { it to it }
+ // Samsung Xclipse driver workarounds (tools/linuxfs/xclipse-layer), the Vulkan layer
+ // SystemVulkanDriver enables on that GPU.
+ val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
+ .map { "usr/local/lib/droiddeck-xclipse/$it" }
// What the Windows components installer reads .msi packages with (tools/msitools).
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
.map { "usr/local/lib/droiddeck-msitools/$it" } +
@@ -140,7 +145,7 @@ object SessionFiles {
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
- ) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
+ ) + mangoapp + xclipse.map { it to it } + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
index 871bb17d80..ecd2de33ca 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.ScreenEffects
+import com.droiddeck.launcher.gpu.SystemVulkanDriver
+import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
@@ -216,6 +218,15 @@ object SessionPrefs {
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
}
+ /** Also called by direct session launches, which may never open the driver settings. */
+ @JvmStatic
+ fun ensurePowerVrAutoDrivers(context: Context) = ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
+
+ internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
+ if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
+ prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
+ }
+
/** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */
fun gpuAutoInstalled(context: Context): Set =
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
index 01f9112eb4..037151ba39 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
+import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.app.Notification
import android.app.NotificationChannel
@@ -318,6 +319,7 @@ class SessionService : Service() {
// ── The session ─────────────────────────────────────────────────────────────────────────
private fun runSession(gen: Int) {
+ SessionPrefs.ensurePowerVrAutoDrivers(this)
SessionTerminal.clear()
try {
LinuxRuntime.writeAccounts(this)
@@ -331,7 +333,17 @@ class SessionService : Service() {
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
killStragglers()
- SessionFiles.stage(this, root)
+ try {
+ if (SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))) {
+ SystemVulkanDriver.prepare(this)
+ pruneSystemVulkanRuntime()
+ }
+ SessionFiles.stage(this, root)
+ } catch (error: Exception) {
+ Log.e(TAG, "Could not prepare the session graphics runtime", error)
+ stopSession(-1)
+ return
+ }
com.droiddeck.launcher.agent.AgentGuest.reset(this)
// The compat tool asks for an Epic game's sign-in code at every launch, the client's Play button included.
com.droiddeck.launcher.stores.gog.GogComet.begin()
@@ -617,6 +629,9 @@ class SessionService : Service() {
// import falls back to. One driver for every session: the driver's shader cache is keyed on
// its build, and with one per mode every emulator compiled its shaders twice.
val linuxDriverId = SessionPrefs.linuxDriver(this)
+ if (SystemVulkanDriver.usesDefault(linuxDriverId)) {
+ SystemVulkanDriver.addEnvironment(this, guest)
+ }
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
@@ -1477,6 +1492,12 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
+ /** Background-only: preserve old runtimes until all earlier guest processes are gone. */
+ private fun pruneSystemVulkanRuntime() {
+ runCatching { SystemVulkanDriver.pruneUnused(this, !OrphanReaper.hasOtherProcesses()) }
+ .onFailure { Log.w(TAG, "could not prune unused system Vulkan runtimes", it) }
+ }
+
private fun finishSessionStop(status: Int, stoppedGen: Int) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
@@ -1594,9 +1615,11 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
+ pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen)
}, "session-teardown").start()
} else {
+ Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({ com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession); finishSessionStop(status, stoppedGen) }, "gog-session-stop").start()
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt
index 48ac4a28dc..b4ad0f6fd8 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt
@@ -502,9 +502,10 @@ fun ComponentsPage(
val active = gpu.activePair
InUseBar(
queued = gpu.busy != null,
- sentence = (active?.let { "${it.name} ${it.version}" } ?: gpu.activeBundle ?: stringResource(R.string.gpu_builtin))
+ sentence = (active?.let { "${it.name} ${it.version}" } ?: gpu.activeBundle ?: stringResource(if (gpu.systemPowerVr) R.string.gpu_system_powervr else R.string.gpu_builtin))
.let { if (gpu.auto) stringResource(R.string.gpu_bar_auto, it) else it },
note = if (gpu.busy != null) (if (gpu.percent >= 0) "${gpu.percent}%" else "…")
+ else if (gpu.systemPowerVr) stringResource(R.string.gpu_auto_system_hint)
else gpu.autoStatus.ifEmpty { if (active != null || gpu.activeBundle != null) "" else gpu.pairs.firstOrNull { it.recommended }?.let { stringResource(R.string.gpu_recommended_for, it.name) } ?: stringResource(R.string.gpu_refresh_hint) },
)
}
@@ -515,17 +516,27 @@ fun ComponentsPage(
)
else -> {
val st = compState(l)
+ val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val label = ComponentsManager.LABEL[l] ?: l
if (st == null) InUseBar(false, stringResource(R.string.comp_no_proton), "")
else {
val reappliedAt = view?.reappliedAt?.takeIf { it > 0 }?.let { DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(it * 1000)) }
- InUseBar(
- queued = st.queued != null,
- sentence = (if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
- .let { if (reappliedAt != null) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
- note = if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
- onCancel = if (st.queued != null) onCancelQueued else null,
- )
+ Column {
+ InUseBar(
+ queued = st.queued != null,
+ sentence = (if (managedDxvk) stringResource(R.string.comp_in_use, label, stringResource(R.string.gpu_system_powervr)) +
+ (st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
+ else if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
+ .let { if (reappliedAt != null && !managedDxvk) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
+ note = if (managedDxvk) "" else if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
+ onCancel = if (st.queued != null) onCancelQueued else null,
+ maxLines = if (managedDxvk && st.queued != null) 3 else 2,
+ )
+ if (managedDxvk) Text(
+ stringResource(R.string.cmgr_powervr_dxvk_managed),
+ fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp),
+ )
+ }
}
}
}
@@ -552,11 +563,11 @@ fun ComponentsPage(
GPU_TAB -> {
val autoKey = "gpu:auto"
ChoiceLine(
- stringResource(R.string.common_auto), stringResource(R.string.gpu_auto_keeps), gpu.auto, removable = false,
+ stringResource(R.string.common_auto), stringResource(if (gpu.powerVr) R.string.gpu_auto_system_hint else R.string.gpu_auto_keeps), gpu.auto, removable = false,
modifier = Modifier.focusRequester(firstRow).trackRow(autoKey, rowsAt),
onSelect = {
if (gpu.auto) return@ChoiceLine
- ask(autoKey, right, ctx.getString(R.string.gpu_use_title, ctx.getString(R.string.common_auto)), ctx.getString(R.string.gpu_auto_hint), ctx.getString(R.string.common_use), false, ctx.getString(R.string.common_auto)) {
+ ask(autoKey, right, ctx.getString(R.string.gpu_use_title, ctx.getString(R.string.common_auto)), ctx.getString(if (gpu.powerVr) R.string.gpu_auto_system_hint else R.string.gpu_auto_hint), ctx.getString(R.string.common_use), false, ctx.getString(R.string.common_auto)) {
gpuActions.onAuto(true); flyHome(autoKey, GPU_TAB)
}
},
@@ -601,16 +612,17 @@ fun ComponentsPage(
}
else -> {
val label = ComponentsManager.LABEL[l] ?: l
- val rows = installedFor(l, view, snapshot)
+ val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
+ val rows = installedFor(l, view, snapshot, managedDxvk)
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_stored, label))
val p = view?.proton
rows.forEachIndexed { i, item ->
val key = "row:$l:${item.file ?: item.protonVersion}"
ChoiceLine(
- item.name, item.detail, item.selected, item.removable, tag = item.tag,
- modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
+ item.name, item.detail, item.selected, item.removable, tag = item.tag, enabled = !managedDxvk,
+ modifier = (if (i == 0 && !managedDxvk) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = {
- if (item.selected || p == null) return@ChoiceLine
+ if (managedDxvk || item.selected || p == null) return@ChoiceLine
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
if (item.file != null) ask(key, right, ctx.getString(R.string.comp_swap_title, label), ctx.getString(R.string.comp_swap_body, item.name, p.name, waits), ctx.getString(R.string.comp_swap), false, item.name) {
onSwap(item.file); flyHome(key, l)
@@ -712,14 +724,19 @@ fun ComponentsPage(
}
}
else -> {
- SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
+ val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
+ SmallButton(
+ stringResource(R.string.comp_import_wcp), onClick = onImport,
+ modifier = if (managedDxvk) Modifier.focusRequester(firstRow) else Modifier,
+ )
val st = compState(l)
val p = view?.proton
val build = p?.let { ComponentsManager.safeName(it.version) }
if (st != null && p != null && st.activeFile != null && view.originals.any { it.comp == l && it.protonVersion == build }) {
val label = ComponentsManager.LABEL[l] ?: l
Box(Modifier.trackRow("restore:$l", rowsAt)) {
- FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
+ if (managedDxvk) SmallButton(stringResource(R.string.comp_restore_original), enabled = false) {}
+ else FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
ask("restore:$l", false, ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_original_body, p.name, label), ctx.getString(R.string.common_restore), false, ctx.getString(R.string.comp_restore_original)) {
onRestore(build!!); flyHome("restore:$l", l)
}
@@ -867,6 +884,7 @@ fun ComponentsPage(
protonChoice = gameProtonChoice,
packages = snapshot?.packages.orEmpty(),
componentChoices = gameComponents,
+ systemPowerVr = gpu.systemPowerVr,
componentMenu = gameComponentMenu,
protonMenu = gameProtonMenu,
fexMenu = fexMenu,
@@ -1010,11 +1028,11 @@ fun ComponentsPage(
/** The Installed rows of one component layer for the Proton the page shows. */
@Composable
-private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?): List {
+private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?, runtimeManaged: Boolean = false): List {
view ?: return emptyList()
val st = view.components[l] ?: return emptyList()
val build = ComponentsManager.safeName(view.proton.version)
- val activeIsOriginal = st.activeFile == null
+ val activeIsOriginal = !runtimeManaged && st.activeFile == null
return view.originals.filter { it.comp == l }.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
@@ -1023,7 +1041,7 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
- InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
+ InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
@@ -1062,11 +1080,12 @@ private fun Stack(
LayerCard(
title = LayerTitle(l),
value = when (l) {
- GPU_TAB -> if (gpu.auto) auto else gpu.activePair?.name ?: gpu.activeBundle ?: auto
+ GPU_TAB -> if (gpu.systemPowerVr) stringResource(R.string.gpu_system_powervr) else if (gpu.auto) auto else gpu.activePair?.name ?: gpu.activeBundle ?: auto
PROTON_TAB -> (view?.proton?.name ?: "") + " ▾"
- else -> st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
+ else -> if (ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
+ else st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
},
- swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null,
+ swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null && !ComponentsManager.runtimeManaged(l, gpu.systemPowerVr),
selected = l == layer,
landed = landed[l] ?: 0, ring = rings[l] ?: 0,
modifier = Modifier.focusRequester(focus.getValue(l)).onGloballyPositioned { onPlaced(l, it.boundsInRoot()) },
@@ -1137,7 +1156,7 @@ private fun LayerCard(
/** What is in use for the layer: a dot (green, or amber while a change waits), a sentence, and a note or Cancel. */
@Composable
-private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null) {
+private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null, maxLines: Int = 2) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
@@ -1146,7 +1165,7 @@ private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel:
.border(1.dp, pal.line, RoundedCornerShape(12.dp)).padding(horizontal = 14.dp, vertical = 8.dp),
) {
Box(Modifier.size(8.dp).background(if (queued) QUEUED else pal.good, CircleShape))
- Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
+ Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = maxLines, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (onCancel != null) FocusText(stringResource(R.string.common_cancel), pal.signal, onClick = onCancel)
else if (note.isNotEmpty() && !LocalNarrowPane.current) Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
@@ -1182,6 +1201,7 @@ private fun GameComponentOverrides(
protonChoice: ProtonDefault.GameChoice?,
packages: List,
componentChoices: Map,
+ systemPowerVr: Boolean,
componentMenu: String?,
protonMenu: Boolean,
fexMenu: Boolean,
@@ -1273,6 +1293,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "dxvk",
+ runtimeManaged = ComponentsManager.runtimeManaged("dxvk", systemPowerVr),
packages = packages,
selectedFile = componentChoices["dxvk"],
open = componentMenu == "dxvk",
@@ -1337,13 +1358,16 @@ private fun GamePackageRow(
onMenu: (String?) -> Unit,
onPick: (String, String?) -> Unit,
onRuntimeOptions: (() -> Unit)? = null,
+ runtimeManaged: Boolean = false,
) {
val choices = packages.filter { it.comp == comp }
val selected = choices.firstOrNull { it.file == selectedFile }
val title = ComponentsManager.LABEL[comp] ?: comp
+ val enabled = !busy && (!runtimeManaged || selectedFile != null)
SettingsRow(
title,
- if (selected == null) {
+ if (runtimeManaged) stringResource(R.string.cmgr_powervr_dxvk_managed)
+ else if (selected == null) {
if (proton == null) stringResource(R.string.comp_game_component_general)
else stringResource(R.string.comp_game_component_runtime, proton.name)
} else stringResource(R.string.comp_game_component_override, selected.version),
@@ -1351,18 +1375,18 @@ private fun GamePackageRow(
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Box {
ValueChip(
- selected?.version ?: stringResource(R.string.comp_game_use_general),
- open,
- enabled = !busy,
+ if (runtimeManaged) stringResource(R.string.gpu_system_powervr) else selected?.version ?: stringResource(R.string.comp_game_use_general),
+ open && enabled,
+ enabled = enabled,
modifier = Modifier.widthIn(max = 240.dp),
) { onMenu(if (open) null else comp) }
- AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
+ AnchoredMenu(open && enabled, onDismiss = { onMenu(null) }, title = title) { first ->
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = selected == null,
focusRequester = first,
) { onPick(comp, null); onMenu(null) }
- choices.forEach { option ->
+ if (!runtimeManaged) choices.forEach { option ->
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
onPick(comp, option.file)
onMenu(null)
@@ -1492,13 +1516,13 @@ private fun Tag(text: String) {
@Composable
private fun ChoiceLine(
name: String, detail: String, selected: Boolean, removable: Boolean,
- modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null,
+ modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null, enabled: Boolean = true,
onSelect: () -> Unit, onDelete: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
- val hot = rememberHot(src)
+ val hot = rememberHot(src) && enabled
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
@@ -1508,8 +1532,8 @@ private fun ChoiceLine(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
.glideBorder(hot, ROW_SHAPE, pal.signal)
- .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onSelect)
- .controllerConfirm(onClick = onSelect)
+ .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onSelect)
+ .controllerConfirm(enabled = enabled, onClick = onSelect)
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).border(2.dp, if (selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
@@ -1519,7 +1543,7 @@ private fun ChoiceLine(
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis,
- color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
+ color = if (!enabled) colors.onSurfaceVariant else if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
)
if (tag != null) Tag(tag)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt
index eec0f20875..c4c8e7781c 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt
@@ -84,6 +84,9 @@ class GpuDriversState(
val supported: Boolean = true,
val unsupported: Boolean = false,
val auto: Boolean = true,
+ val powerVr: Boolean = false,
+ /** The selected runtime supplies DXVK for PowerVR game launches. */
+ val systemPowerVr: Boolean = false,
val pairs: List = emptyList(),
/** The pair key being installed, and how far along (-1 = unknown). */
val busy: String? = null,
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
index 205c51d1d4..9c42d987f3 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
@@ -263,6 +263,8 @@ class DrawerActions(
val onClose: () -> Unit,
/** Games tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
+ /** DXVK is supplied by the selected system PowerVR runtime. */
+ val systemPowerVr: Boolean = false,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
/** Installed games available for profile inspection in the session drawer. */
@@ -1049,7 +1051,11 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
for (component in ComponentsManager.COMPONENTS) {
val value = profile.components.getValue(component)
if (!value.inherited) {
- ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
+ ProfileSummaryRow(
+ ComponentsManager.LABEL.getValue(component),
+ if (ComponentsManager.runtimeManaged(component, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
+ else profileValueLabel(value),
+ )
}
}
if (profile.startWithoutSteam) {
@@ -1151,20 +1157,23 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
}
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
+ val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
- snap.packages.filter { it.comp == comp }.map { it.file to it.version }
+ if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
label = ComponentsManager.LABEL.getValue(comp),
- hint = if (value.inherited) {
+ hint = if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) else if (value.inherited) {
stringResource(R.string.drawer_component_inherited, value.value)
} else {
null
},
options = options,
selected = gameProfile.componentFiles[comp],
+ enabled = !managedDxvk || gameProfile.componentFiles[comp] != null,
+ valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
chipModifier = track("cmp-$comp"),
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
)
@@ -1200,7 +1209,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
for (comp in ComponentsManager.COMPONENTS) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
- Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(
+ if (ComponentsManager.runtimeManaged(comp, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
+ else r.components.getValue(comp).inUse,
+ fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
}
}
}
@@ -1228,17 +1241,22 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val build = ComponentsManager.safeName(p.version)
for (comp in ComponentsManager.COMPONENTS) {
val st = view.components.getValue(comp)
+ val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
- if (options.isEmpty()) continue
+ if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
// The box already shows the choice: only say more when there is more to say.
- st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
+ if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) +
+ (st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
+ else st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
options, current,
+ enabled = !managedDxvk,
+ valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
note = if (view.inUseByGame) stringResource(R.string.comp_waits_long) else stringResource(R.string.comp_applies_long),
chipModifier = track("cmp-$comp"),
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
@@ -1259,11 +1277,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
private fun DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
options: List>, selected: T, note: String? = null,
- chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
+ chipModifier: Modifier = Modifier, enabled: Boolean = true, valueLabel: String? = null, onPick: (T) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
- val open = host.open == key
+ val open = host.open == key && enabled
Column(
modifier = Modifier.fillMaxWidth()
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
@@ -1271,7 +1289,7 @@ private fun DrawerStackedChoice(
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
- ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
+ ValueChip(valueLabel ?: options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled = enabled, modifier = chipModifier.fillMaxWidth()) {
host.open = if (open) null else key
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 349bc9909d..124e0e44f2 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -588,7 +588,7 @@
GPU no compatible
%1$s · %2$s
%1$s: %2$s
- Steam necesita un controlador Adreno; %1$s puede mostrar una pantalla negra
+ No hay un motor gráfico compatible disponible; %1$s puede mostrar una pantalla negra
Runtime de Linux
%1$s · %2$d%%
No instalado · unos 3 GB, se instala al jugar por primera vez
@@ -1107,10 +1107,10 @@
La Depuración inalámbrica no está disponible
Comando ADB copiado
Elige la carpeta de ROMs
- La GPU no es Adreno
+ GPU no compatible
- Turnip es compatible con GPU Adreno. En %1$s, Steam puede mostrar una pantalla negra. Descarga: %2$.0f MB.
+ No hay un motor gráfico compatible disponible para %1$s. Steam puede mostrar una pantalla negra. Descarga: %2$.0f MB.
Instalar de todos modos
Eliminar el runtime de Linux
Esto elimina el runtime, el cliente de Steam que contiene y todos los juegos instalados en él.
@@ -1934,7 +1934,7 @@
Compatible
Experimental: sus controladores son versiones de prueba
Por debajo del hardware probado (Adreno 725 y posteriores): puede que no funcione
- No compatible: DroidDeck necesita una GPU Adreno (Snapdragon)
+ No compatible: no hay un motor gráfico compatible disponible para esta GPU
Se alcanzó el límite de solicitudes de GitHub - inténtalo más tarde
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index feb46b7d54..14a63977af 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -471,7 +471,7 @@
GPU non pris en charge
%1$s · %2$s
%1$s : %2$s
- Steam nécessite un pilote Adreno ; %1$s peut afficher un écran noir.
+ Aucun moteur graphique compatible n’est disponible ; %1$s peut afficher un écran noir.
Environnement d\'exécution Linux
%1$s · %2$d%%
Non installé · Environ 3 Go, installé lors du premier lancement d\'un jeu
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index e787b47336..1c1fa30093 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -584,7 +584,7 @@
GPUはサポートされていません
%1$s · %2$s
%1$s:%2$s
- SteamにはAdrenoドライバーが必要です。%1$sでは画面が真っ暗になる可能性があります。
+ 利用できる互換グラフィックスバックエンドがありません。%1$sでは画面が真っ暗になる可能性があります。
Linux実行環境
%1$s · %2$d%%
未インストール · 約3GB、初回ゲーム起動時にインストール
@@ -1089,10 +1089,10 @@
ワイヤレスデバッグは利用できません
ADBコマンドをコピーしました
ROMフォルダを選択
- Adreno GPUではありません
+ サポート対象外のGPU
- TurnipはAdreno GPUをサポートしています。%1$sでは、Steamの画面が真っ暗になる可能性があります。ダウンロード:%2$.0f MB。
+ %1$sで利用できる互換グラフィックスバックエンドがありません。Steamの画面が真っ暗になる可能性があります。ダウンロード:%2$.0f MB。
インストールする
Linux実行環境を削除
実行環境、その中のSteamクライアント、そこにインストールされたすべてのゲームが削除されます。
@@ -1894,7 +1894,7 @@
サポート対象
実験的:ドライバーはテストビルドです
テスト済みハードウェア(Adreno 725以降)未満:動作しない可能性があります
- サポート対象外:DroidDeckにはAdreno(Snapdragon)GPUが必要です
+ サポート対象外:このGPUで利用できる互換グラフィックスバックエンドがありません
GitHubのレート制限に達しました。後でもう一度お試しください
diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml
index 6305e623d4..032a7494b3 100644
--- a/app/src/main/res/values-ko/strings.xml
+++ b/app/src/main/res/values-ko/strings.xml
@@ -584,7 +584,7 @@
GPU 지원되지 않음
%1$s · %2$s
%1$s: %2$s
- Steam에는 Adreno 드라이버가 필요합니다. %1$s에서 화면이 검게 변할 수 있습니다.
+ 사용할 수 있는 호환 그래픽 백엔드가 없습니다. %1$s에서 화면이 검게 표시될 수 있습니다.
Linux 런타임
%1$s · %2$d%%
설치되지 않음 · 약 3GB, 처음 \"Steam 실행\" 시 설치
@@ -1089,10 +1089,10 @@
무선 디버깅을 사용할 수 없습니다
ADB 명령이 복사되었습니다
ROM 폴더 선택
- Adreno GPU가 아님
+ 지원되지 않는 GPU
- Turnip은 Adreno GPU를 지원합니다. %1$s에서는 Steam 화면이 검게 표시될 수 있습니다. 다운로드: %2$.0f MB.
+ %1$s에서 사용할 수 있는 호환 그래픽 백엔드가 없습니다. Steam 화면이 검게 표시될 수 있습니다. 다운로드: %2$.0f MB.
그래도 설치
Linux 런타임 제거
런타임과 그 안의 Steam 클라이언트, 그리고 런타임에 설치된 모든 게임이 삭제됩니다.
@@ -1894,7 +1894,7 @@
지원됨
실험적: 드라이버가 테스트 빌드입니다
테스트된 하드웨어(Adreno 725 이상)보다 낮음: 실행되지 않을 수 있습니다
- 지원되지 않음: DroidDeck에는 Adreno(Snapdragon) GPU가 필요합니다
+ 지원되지 않음: 이 GPU에서 사용할 수 있는 호환 그래픽 백엔드가 없습니다
GitHub 요청 한도에 도달했습니다. 나중에 다시 시도하세요
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index f1f6765583..222dfbb8cb 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -546,7 +546,7 @@
GPU не поддерживается
%1$s · %2$s
%1$s: %2$s
- Steam требует драйвер Adreno; на %1$s возможен черный экран.
+ Совместимый графический бэкенд недоступен; на %1$s возможен черный экран.
Среда выполнения Linux
%1$s · %2$d%%
Не установлено · около 3 ГБ, устанавливается при первом запуске игры
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index 80b2233d9d..b2bee0561e 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -584,7 +584,7 @@
GPU 不受支持
%1$s · %2$s
%1$s:%2$s
- Steam 需要 Adreno 驱动;%1$s 可能显示黑屏
+ 没有可用的兼容图形后端;%1$s 可能显示黑屏
Linux 运行时
%1$s · %2$d%%
未安装 · 约 3 GB,首次点“游玩”时安装
@@ -1089,10 +1089,10 @@
无线调试不可用
已复制 ADB 命令
选择 ROM 文件夹
- 不是 Adreno GPU
+ 不受支持的 GPU
- Turnip 支持 Adreno GPU。在 %1$s 上,Steam 可能显示黑屏。需下载:%2$.0f MB。
+ 没有适用于 %1$s 的兼容图形后端。Steam 可能显示黑屏。需下载:%2$.0f MB。
仍要安装
移除 Linux 运行时
这会删除运行时、其中的 Steam 客户端,以及安装在其中的所有游戏。
@@ -1894,7 +1894,7 @@
受支持
实验性:其驱动为测试构建
低于已测试的硬件(Adreno 725 及更新):可能无法运行
- 不受支持:DroidDeck 需要 Adreno(骁龙)GPU
+ 不受支持:没有适用于此 GPU 的兼容图形后端
已达到 GitHub 的请求频率限制 — 请稍后重试
diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml
index 9371b68312..53b88aad4e 100644
--- a/app/src/main/res/values-zh-rHK/strings.xml
+++ b/app/src/main/res/values-zh-rHK/strings.xml
@@ -584,7 +584,7 @@
GPU 不受支援
%1$s · %2$s
%1$s:%2$s
- Steam 需要 Adreno 驅動程式;%1$s 可能會出現黑畫面
+ 沒有可用的兼容圖形後端;%1$s 可能會出現黑畫面
Linux 運行環境
%1$s · %2$d%%
未安裝 · 約 3 GB,首次開啟 Steam 時安裝
@@ -1089,10 +1089,10 @@
無法使用無線偵錯
已複製 ADB 指令
選擇 ROM 資料夾
- 不是 Adreno GPU
+ 不受支援的 GPU
- Turnip 支援 Adreno GPU。在 %1$s 上,Steam 可能會出現黑畫面。下載大小:%2$.0f MB。
+ 沒有適用於 %1$s 的兼容圖形後端。Steam 可能會出現黑畫面。下載大小:%2$.0f MB。
仍要安裝
移除 Linux 運行環境
此操作會刪除運行環境、其中的 Steam 用戶端,以及安裝在其中的所有遊戲。
@@ -1894,7 +1894,7 @@
受支援
實驗性:其驅動程式為測試版本
低於已測試的硬件(Adreno 725 或更新):可能無法執行
- 不受支援:DroidDeck 需要 Adreno (Snapdragon) GPU
+ 不受支援:沒有適用於此 GPU 的兼容圖形後端
已達 GitHub 的速率限制 - 請稍後再試
diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml
index 846a91e01d..4193770a96 100644
--- a/app/src/main/res/values-zh-rTW/strings.xml
+++ b/app/src/main/res/values-zh-rTW/strings.xml
@@ -584,7 +584,7 @@
GPU 不受支援
%1$s · %2$s
%1$s:%2$s
- Steam 需要 Adreno 驅動程式;%1$s 可能出現黑畫面。
+ 沒有可用的相容圖形後端;%1$s 可能出現黑畫面。
Linux 執行環境
%1$s · %2$d%%
未安裝 · 約 3 GB,首次點擊「執行」時安裝
@@ -1089,10 +1089,10 @@
無法使用無線偵錯
已複製 ADB 指令
選擇 ROM 資料夾
- 不是 Adreno GPU
+ 不受支援的 GPU
- Turnip 支援 Adreno GPU。在 %1$s 上,Steam 可能會出現黑畫面。下載大小:%2$.0f MB。
+ 沒有適用於 %1$s 的相容圖形後端。Steam 可能會出現黑畫面。下載大小:%2$.0f MB。
仍要安裝
移除 Linux 執行環境
這會刪除執行環境、其中的 Steam 用戶端,以及安裝在其中的所有遊戲。
@@ -1894,7 +1894,7 @@
受支援
實驗性:其驅動程式為測試版本
低於已測試的硬體(Adreno 725 及更新機型):可能無法執行
- 不受支援:DroidDeck 需要 Adreno(Snapdragon)GPU
+ 不受支援:沒有適用於此 GPU 的相容圖形後端
已達 GitHub 速率限制 - 請稍後再試
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index df6e20e478..0da417389e 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -651,7 +651,7 @@
GPU not supported
%1$s · %2$s
%1$s: %2$s
- Steam needs an Adreno driver; %1$s may show a black screen
+ No compatible graphics backend is available; %1$s may show a black screen
Linux runtime
%1$s · %2$d%%
Not installed · about 3 GB, installed on first Play
@@ -1183,9 +1183,9 @@
Wireless debugging is unavailable
ADB command copied
Choose the ROMs folder
- Not an Adreno GPU
+ Unsupported GPU
- Turnip supports Adreno GPUs. On %1$s, Steam may show a black screen. Download: %2$.0f MB.
+ No compatible graphics backend is available for %1$s. Steam may show a black screen. Download: %2$.0f MB.
Install anyway
Remove Linux runtime
This deletes the runtime, the Steam client inside it, and every game installed there.
@@ -1902,10 +1902,16 @@
Not an Adreno GPU
+ System PowerVR driver: compatibility varies by device
+ System PowerVR
+ Uses the built-in drivers for this GPU
+ The system PowerVR driver is selected for the runtime and display.
+ Queued: %1$s (waiting for a different runtime driver)
+ DXVK is provided by the system PowerVR runtime. Other DXVK packages can be stored but are not applied with this driver.
Supported
Experimental: its drivers are test builds
Below tested hardware (Adreno 725 and newer): it may not run
- Not supported: DroidDeck needs an Adreno (Snapdragon) GPU
+ Not supported: no compatible graphics backend is available for this GPU
GitHub\'s rate limit was hit - try again later
diff --git a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt
new file mode 100644
index 0000000000..6338889980
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt
@@ -0,0 +1,14 @@
+package com.droiddeck.launcher.core
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class DeviceSupportTest {
+ @Test fun runtimeDownloadAcceptsOnlyRecognizedGraphicsBackends() {
+ assertTrue(DeviceSupport.graphicsAvailable(adreno = true, powerVrReady = false))
+ assertTrue(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = true))
+ // A PowerVR HAL without usable DRM access also reaches this unavailable case.
+ assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DeviceInfoTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DeviceInfoTest.kt
new file mode 100644
index 0000000000..808425f67d
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/gpu/DeviceInfoTest.kt
@@ -0,0 +1,13 @@
+package com.droiddeck.launcher.gpu
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class DeviceInfoTest {
+ @Test fun builtinLabelsDistinguishPowerVrFromTurnipAndGenericSystemVulkan() {
+ assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = true))
+ assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = false))
+ assertEquals("the runtime's own Turnip", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = true))
+ assertEquals("System Vulkan", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = false))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt
index b5d632fdc4..1131afd4ca 100644
--- a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt
@@ -42,6 +42,23 @@ class DriverPairsTest {
assertEquals(GpuInfo.Support.UNSUPPORTED, gpu(0, adreno = false).support)
}
+ @Test
+ fun powerVrUsesItsOwnFamilyWithoutClaimingAllModelsAreTested() {
+ assertEquals(Family.POWERVR, GpuInfo.familyOf(false, 0, powerVr = true))
+ assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0, powerVr = false))
+ assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740, powerVr = true))
+ val powerVr = GpuInfo("PowerVR", 0, Family.POWERVR, "", false)
+ assertEquals(GpuInfo.Support.UNTESTED, powerVr.support)
+ assertNull("PowerVR never downloads an Adreno driver pair", DriverPairs.recommendedKey(powerVr, emptyList()))
+ val pairs = DriverPairs.from(TurnipReleases.Check(
+ listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
+ asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)),
+ emptyList(), emptyList(), 0L,
+ ))
+ assertFalse(pairs.single().suits(powerVr))
+ assertNull(DriverPairs.recommendedKey(powerVr, pairs))
+ }
+
@Test
fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() {
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList()))
diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SystemVulkanPruningTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SystemVulkanPruningTest.kt
new file mode 100644
index 0000000000..9f593658f7
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/gpu/SystemVulkanPruningTest.kt
@@ -0,0 +1,109 @@
+package com.droiddeck.launcher.gpu
+
+import java.io.File
+import java.nio.file.Files
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+class SystemVulkanPruningTest {
+ @get:Rule val temporary = TemporaryFolder()
+
+ @Test fun completedReplacementCollectsOnlyManagedOldDirectories() {
+ val base = temporary.newFolder("system_vulkan")
+ val current = completeRuntime(base, "a".repeat(64))
+ val old = completeRuntime(base, "b".repeat(64))
+ val stage = abandonedStage(base)
+ val unrelated = File(base, "notes").apply { mkdir(); File(this, "keep").writeText("keep") }
+
+ SystemVulkanDriver.pruneUnused(current, true)
+
+ assertEquals("current ICD", File(current, "icd.json").readText())
+ assertTrue(File(current, "run-proton.py").canExecute())
+ assertFalse(old.exists())
+ assertFalse(stage.exists())
+ assertEquals("keep", File(unrelated, "keep").readText())
+ }
+
+ @Test fun aSurvivingGuestKeepsOldVersionsButNotAbandonedStages() {
+ val base = temporary.newFolder("system_vulkan")
+ val current = completeRuntime(base, "a".repeat(64))
+ val old = completeRuntime(base, "b".repeat(64))
+ val stage = abandonedStage(base)
+
+ SystemVulkanDriver.pruneUnused(current, false)
+
+ assertTrue(current.isDirectory)
+ assertTrue(old.isDirectory)
+ assertFalse(stage.exists())
+ SystemVulkanDriver.pruneUnused(current, true)
+ assertFalse("collect the old version once guests stop", old.exists())
+ }
+
+ @Test fun failedReplacementPreservesThePreviousGoodRuntime() {
+ val base = temporary.newFolder("system_vulkan")
+ val current = File(base, "a".repeat(64))
+ val old = completeRuntime(base, "b".repeat(64))
+ val stage = abandonedStage(base)
+
+ SystemVulkanDriver.pruneUnused(current, true)
+ assertTrue("missing replacement", old.isDirectory)
+ assertFalse(stage.exists())
+
+ current.mkdir()
+ File(current, "icd.json").writeText("incomplete")
+ SystemVulkanDriver.pruneUnused(current, true)
+ assertEquals("current ICD", File(old, "icd.json").readText())
+ }
+
+ @Test fun deletingOldRuntimeDoesNotFollowItsSymlinks() {
+ val base = temporary.newFolder("system_vulkan")
+ val current = completeRuntime(base, "a".repeat(64))
+ val old = File(base, "b".repeat(64)).apply { mkdir() }
+ val outside = temporary.newFolder("outside")
+ val sentinel = File(outside, "keep").apply { writeText("keep") }
+ Files.createSymbolicLink(File(old, "outside").toPath(), outside.toPath())
+
+ SystemVulkanDriver.pruneUnused(current, true)
+
+ assertFalse(old.exists())
+ assertEquals("keep", sentinel.readText())
+ }
+
+ @Test fun linkedBaseOrCurrentRuntimePreventsCleanup() {
+ val base = temporary.newFolder("system_vulkan")
+ val old = completeRuntime(base, "b".repeat(64))
+ val current = File(base, "a".repeat(64))
+ Files.createSymbolicLink(current.toPath(), old.toPath())
+ SystemVulkanDriver.pruneUnused(current, true)
+ assertTrue(old.isDirectory)
+
+ Files.delete(current.toPath())
+ completeRuntime(base, current.name)
+ val alias = File(temporary.root, "alias")
+ Files.createSymbolicLink(alias.toPath(), base.toPath())
+ SystemVulkanDriver.pruneUnused(File(alias, current.name), true)
+ assertTrue(old.isDirectory)
+ }
+
+ private fun abandonedStage(base: File) =
+ File(base, ".stage-12345678-1234-1234-1234-123456789abc").apply { mkdir(); File(this, "partial").writeText("partial") }
+
+ private fun completeRuntime(base: File, version: String): File {
+ val directory = File(base, version).apply { mkdir() }
+ val components = listOf(
+ "lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1", "lib/libhybris/linker/q.so",
+ "lib/libVkLayer_hybris_compat.so", "run-proton.py",
+ "wsi/libVkLayer_window_system_integration.so", "wsi/VkLayer_window_system_integration.json",
+ ) + listOf("x32", "x64").flatMap { arch ->
+ listOf("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi").map { "dxvk/$arch/$it.dll" }
+ }
+ components.forEach { path -> File(directory, path).apply { parentFile!!.mkdirs(); writeText("component") } }
+ File(directory, "run-proton.py").setExecutable(true)
+ File(directory, "icd.json").writeText("current ICD")
+ return directory
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SystemVulkanSelectionTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SystemVulkanSelectionTest.kt
new file mode 100644
index 0000000000..29a25037ff
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/gpu/SystemVulkanSelectionTest.kt
@@ -0,0 +1,129 @@
+package com.droiddeck.launcher.gpu
+
+import java.io.File
+import java.nio.file.Files
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Assert.assertThrows
+import org.junit.Test
+
+class SystemVulkanSelectionTest {
+ @Test fun defaultPowerVrUsesTheSystemBridge() {
+ assertTrue(SystemVulkanDriver.usesDefault(true, ""))
+ assertTrue(SystemVulkanDriver.usesDefault(true, null))
+ }
+
+ @Test fun otherGpusAndExplicitImportsKeepTheirDriver() {
+ assertFalse(SystemVulkanDriver.usesDefault(false, ""))
+ assertFalse(SystemVulkanDriver.usesDefault(false, null))
+ assertFalse(SystemVulkanDriver.usesDefault(true, "custom-driver"))
+ }
+ @Test fun renderNodeRequiresARealCharacterDeviceAndBothAccessModes() {
+ assertTrue(SystemVulkanDriver.renderNodeAvailable(true, true, true))
+ assertFalse("a regular placeholder is not a DRM device", SystemVulkanDriver.renderNodeAvailable(false, true, true))
+ assertFalse("read access is required", SystemVulkanDriver.renderNodeAvailable(true, false, true))
+ assertFalse("write access is required", SystemVulkanDriver.renderNodeAvailable(true, true, false))
+ assertFalse("a missing node is unavailable", SystemVulkanDriver.renderNodeAvailable(false, false, false))
+ }
+
+ @Test fun renderNodeDriverMustIdentifyPowerVrExactly() {
+ for (name in listOf("pvrsrvkm", "pvr", "powervr"))
+ assertTrue(name, SystemVulkanDriver.powerVrDriver(name))
+ for (name in listOf(null, "", "msm", "panfrost", "not-pvr"))
+ assertFalse(name, SystemVulkanDriver.powerVrDriver(name))
+ }
+
+ @Test fun samsungXclipseGpuNodeIsSelectedOverItsDisplayNode() {
+ assertTrue(SystemVulkanDriver.powerVrDriver("sgpu"))
+ assertFalse("the display controller is not the GPU", SystemVulkanDriver.powerVrDriver("exynos-drm"))
+ // Galaxy A56 (Exynos 1580): the GPU owns renderD128, the display controller renderD129.
+ val drivers = mapOf("/dev/dri/renderD128" to "sgpu", "/dev/dri/renderD129" to "exynos-drm")
+ assertEquals("/dev/dri/renderD128", SystemVulkanDriver.findRenderNode(null) { path ->
+ SystemVulkanDriver.powerVrDriver(drivers[path])
+ })
+ }
+
+ @Test fun renderNodeIdentityUsesTheDriverLinkOrUevent() {
+ val device = Files.createTempDirectory("powervr-device").toFile()
+ try {
+ assertFalse("missing identity is unavailable", SystemVulkanDriver.powerVrDevice(device))
+ val uevent = File(device, "uevent")
+ uevent.writeText("DRIVER=pvrsrvkm\nOF_NAME=gpu0\n")
+ assertTrue(SystemVulkanDriver.powerVrDevice(device))
+ uevent.writeText("DRIVER=msm\nOF_COMPATIBLE_0=not-pvr\n")
+ assertFalse(SystemVulkanDriver.powerVrDevice(device))
+ val driver = File(device, "driver").toPath()
+ Files.createSymbolicLink(driver, File("../../drivers/pvrsrvkm").toPath())
+ assertTrue(SystemVulkanDriver.powerVrDevice(device))
+ Files.delete(driver)
+ Files.createSymbolicLink(driver, File("../../drivers/msm").toPath())
+ uevent.writeText("DRIVER=pvrsrvkm\n")
+ assertFalse("an unrelated driver link must not fall back", SystemVulkanDriver.powerVrDevice(device))
+ } finally {
+ device.deleteRecursively()
+ }
+ }
+
+ @Test fun renderNodeDiscoverySkipsOtherDriversAndDeniedNodes() {
+ val drivers = mapOf(
+ "/dev/dri/renderD128" to "msm",
+ "/dev/dri/renderD129" to "pvr",
+ "/dev/dri/renderD130" to "pvrsrvkm",
+ )
+ assertEquals("/dev/dri/renderD129", SystemVulkanDriver.findRenderNode(null) { path ->
+ SystemVulkanDriver.powerVrDriver(drivers[path])
+ })
+ assertEquals("/dev/dri/renderD130", SystemVulkanDriver.findRenderNode(null) { path ->
+ SystemVulkanDriver.powerVrDriver(drivers[path]) &&
+ SystemVulkanDriver.renderNodeAvailable(true, path != "/dev/dri/renderD129", true)
+ })
+ }
+
+ @Test fun renderNodesAreDiscoveredWithoutDirectoryListing() {
+ for (minor in listOf(128, 129, 191)) {
+ val expected = "/dev/dri/renderD$minor"
+ assertEquals(expected, SystemVulkanDriver.findRenderNode(null) { it == expected })
+ }
+ assertNull(SystemVulkanDriver.findRenderNode(null) { false })
+ }
+
+ @Test fun listedRenderNodesCoverExtendedMinorNumbers() {
+ assertEquals("/dev/dri/renderD256", SystemVulkanDriver.findRenderNode(
+ arrayOf("card0", "renderD256", "renderD128/device", "../renderD129"),
+ ) { path ->
+ assertTrue(path, path.matches(Regex("/dev/dri/renderD[0-9]+")))
+ path == "/dev/dri/renderD256"
+ })
+ }
+
+ @Test fun defaultPowerVrResolvesToTheSystemIcd() {
+ assertEquals("system/icd.json", LinuxVulkanDriver.resolveIcdPath("", true,
+ { "system/icd.json" }, { error("default must not resolve an import") }))
+ }
+
+ @Test fun defaultAdrenoLeavesTheRuntimeIcdUnchanged() {
+ assertNull(LinuxVulkanDriver.resolveIcdPath("", false,
+ { error("Adreno must not prepare the system bridge") }, { error("default must not resolve an import") }))
+ }
+
+ @Test fun missingManualPowerVrImportFailsWithoutSwitchingBackends() {
+ val failure = assertThrows(IllegalStateException::class.java) {
+ LinuxVulkanDriver.resolveIcdPath("missing-driver", true,
+ { error("manual preference must not silently switch to the system backend") }, { null })
+ }
+ assertTrue(failure.message!!.contains("missing-driver"))
+ assertTrue(failure.message!!.contains("use Auto"))
+ }
+
+ @Test fun missingAdrenoImportKeepsTheExistingRuntimeFallback() {
+ assertNull(LinuxVulkanDriver.resolveIcdPath("missing-driver", false,
+ { error("Adreno must not prepare the system bridge") }, { null }))
+ }
+
+ @Test fun manualPowerVrResolvesTheChosenImport() {
+ assertEquals("imports/chosen/icd.json", LinuxVulkanDriver.resolveIcdPath("chosen", true,
+ { error("manual must not prepare the system bridge") }, { "imports/$it/icd.json" }))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt
index 3f5e6e8e41..a5f8b47c76 100644
--- a/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt
@@ -130,6 +130,34 @@ class ForcedPackageTest {
assertDefaultDxvkRestoreRow(protonName)
}
+ @Test fun systemPowerVrRejectsNewGameDxvkSelectionsWithoutChangingSavedProfiles() {
+ writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
+ val state = File(context.filesDir, "components/state.json")
+ val saved = state.readText()
+
+ assertThrows(IllegalStateException::class.java) {
+ ComponentsManager.setGameComponent(context, "42", "dxvk", "replacement.wcp") {
+ ComponentsManager.runtimeManaged(it, true)
+ }
+ }
+
+ assertEquals(saved, state.readText())
+ assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
+ assertFalse(launchState().exists())
+ }
+
+ @Test fun systemPowerVrAllowsClearingASavedGameDxvkSelection() {
+ proton("proton-exp")
+ writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
+
+ ComponentsManager.setGameComponent(context, "42", "dxvk", null) {
+ ComponentsManager.runtimeManaged(it, true)
+ }
+
+ assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
+ assertDefaultDxvkRestoreRow("proton-exp")
+ }
+
@Test fun aNewProtonIsCapturedWhenTheLastOverrideIsReset() {
proton("existing")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
diff --git a/app/src/test/java/com/droiddeck/launcher/session/OrphanReaperProcessTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OrphanReaperProcessTest.kt
new file mode 100644
index 0000000000..bb766e75ca
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/OrphanReaperProcessTest.kt
@@ -0,0 +1,23 @@
+package com.droiddeck.launcher.session
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class OrphanReaperProcessTest {
+ @Test fun unavailableProcessListDefersCleanup() {
+ assertTrue(OrphanReaper.hasOtherProcesses(null, 100) { false })
+ }
+
+ @Test fun theAppAndForeignProcessesDoNotKeepOldRuntimes() {
+ assertFalse(OrphanReaper.hasOtherProcesses(listOf(0, 1, 100, 200), 100) { pid ->
+ check(pid == 200) { "do not probe self or process groups" }
+ false
+ })
+ }
+
+ @Test fun anyRemainingAppProcessDefersCleanup() {
+ assertTrue(OrphanReaper.hasOtherProcesses(listOf(100, 200, 300), 100) { it == 300 })
+ assertFalse(OrphanReaper.hasOtherProcesses(emptyList(), 100) { true })
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt
new file mode 100644
index 0000000000..fe2f6a8125
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt
@@ -0,0 +1,44 @@
+package com.droiddeck.launcher.session
+
+import android.content.Context
+import org.robolectric.RuntimeEnvironment
+import com.droiddeck.launcher.gpu.TurnipDriver
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28], manifest = Config.NONE)
+class PowerVrAutoDriversTest {
+ private val context: Context = RuntimeEnvironment.getApplication()
+
+ @Before fun reset() {
+ context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
+ SessionPrefs.setLinuxDriver(context, "imported-linux")
+ SessionPrefs.setAndroidDriver(context, "imported-display")
+ }
+
+ @Test fun autoRepairsStaleAdrenoSelectionsOnPowerVr() {
+ SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
+ SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
+ assertEquals("", SessionPrefs.linuxDriver(context))
+ assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
+ }
+
+ @Test fun explicitManualChoicesRemainOnPowerVr() {
+ SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL)
+ SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
+ assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
+ assertEquals("imported-display", SessionPrefs.androidDriver(context))
+ }
+
+ @Test fun adrenoAutoChoicesRemain() {
+ SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
+ SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = false)
+ assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
+ assertEquals("imported-display", SessionPrefs.androidDriver(context))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/PowerVrComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PowerVrComponentsTest.kt
new file mode 100644
index 0000000000..3a768aee77
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/PowerVrComponentsTest.kt
@@ -0,0 +1,14 @@
+package com.droiddeck.launcher.session
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PowerVrComponentsTest {
+ @Test fun onlyDxvkIsManagedWithTheSystemPowerVrRuntime() {
+ assertTrue(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = true))
+ assertFalse(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = false))
+ assertFalse(ComponentsManager.runtimeManaged("fex", systemPowerVr = true))
+ assertFalse(ComponentsManager.runtimeManaged("vkd3d", systemPowerVr = true))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/PowerVrQueuedComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PowerVrQueuedComponentsTest.kt
new file mode 100644
index 0000000000..66aaeb650c
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/PowerVrQueuedComponentsTest.kt
@@ -0,0 +1,41 @@
+package com.droiddeck.launcher.session
+
+import android.content.Context
+import com.droiddeck.launcher.runtime.LinuxRuntime
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+import java.io.File
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28], manifest = Config.NONE)
+class PowerVrQueuedComponentsTest {
+ @Test fun managedDxvkQueueRemainsVisibleAndCanBeCancelled() {
+ val context: Context = RuntimeEnvironment.getApplication()
+ val root = LinuxRuntime.rootDir(context)
+ root.deleteRecursively()
+ val data = File(context.filesDir, "components")
+ data.deleteRecursively()
+ data.mkdirs()
+ val proton = File(root, "root/.local/share/Steam/compatibilitytools.d/test-proton")
+ File(proton, "files/lib/wine").mkdirs()
+ File(proton, "proton").writeText("# test Proton\n")
+ File(proton, "version").writeText("1 test-build\n")
+ File(data, "state.json").writeText(JSONObject().put("queued", JSONObject().put("test-proton",
+ JSONObject().put("dxvk", JSONObject().put("kind", "package").put("file", "chosen.wcp").put("label", "chosen DXVK"))
+ )).toString())
+
+ assertTrue(ComponentsManager.applyQueued(context) { ComponentsManager.runtimeManaged(it, true) }.isEmpty())
+ val deferred = ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk")
+ assertEquals("chosen DXVK", deferred.queued)
+
+ ComponentsManager.cancelQueued(context, "test-proton", "dxvk")
+ assertNull(ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk").queued)
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt
index e01d884da5..377771bf72 100644
--- a/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt
@@ -1,9 +1,23 @@
package com.droiddeck.launcher.ui
+import android.app.Application
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.SemanticsProperties
+import androidx.compose.ui.test.SemanticsMatcher
+import androidx.compose.ui.test.assertCountEquals
+import androidx.compose.ui.test.assertIsEnabled
+import androidx.compose.ui.test.assertIsNotEnabled
+import androidx.compose.ui.test.hasText
+import androidx.compose.ui.test.onAllNodesWithText
+import androidx.compose.ui.test.onLast
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performScrollTo
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
+import com.droiddeck.launcher.session.ComponentsManager
+import java.io.File
+import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@@ -11,8 +25,9 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
+// Exercise the component UI without starting App's process-wide servers or crash handler.
@RunWith(RobolectricTestRunner::class)
-@Config(sdk = [28])
+@Config(sdk = [28], application = Application::class)
class ComponentsPageProfileTest {
@get:Rule val compose = createRobolectricComposeRule()
@@ -56,4 +71,143 @@ class ComponentsPageProfileTest {
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText(stackHeading).assertExists()
}
+
+ @Test @Config(qualifiers = "w1280dp-h1000dp")
+ fun systemPowerVrKeepsStoredDxvkDisabledAndQueuedDxvkCancellable() {
+ val context = RuntimeEnvironment.getApplication()
+ var cancelled = 0
+ var imported = 0
+ var swapped = 0
+ var restored = 0
+ showDxvk(
+ systemPowerVr = true,
+ onCancel = { cancelled++ },
+ onImport = { imported++ },
+ onSwap = { swapped++ },
+ onRestore = { restored++ },
+ )
+
+ compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
+ compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_queued, "Next DXVK"), substring = true).assertExists()
+ compose.onNodeWithText("Stored DXVK").assertIsNotEnabled()
+ compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsNotEnabled()
+ compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsNotEnabled()
+ compose.onNodeWithText(context.getString(R.string.common_cancel)).performClick()
+ compose.onNodeWithText(context.getString(R.string.comp_import_wcp)).performScrollTo().assertIsEnabled().performClick()
+ compose.runOnIdle {
+ assertEquals(1, cancelled)
+ assertEquals(1, imported)
+ assertEquals(0, swapped)
+ assertEquals(0, restored)
+ }
+ }
+
+ @Test @Config(qualifiers = "w1280dp-h1000dp")
+ fun manualRuntimeKeepsDxvkSelectionAvailable() {
+ val context = RuntimeEnvironment.getApplication()
+ showDxvk(systemPowerVr = false)
+
+ compose.onNode(hasText("Stored DXVK") and SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.RadioButton)).assertIsEnabled()
+ compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsEnabled()
+ compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsEnabled()
+ compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertDoesNotExist()
+ }
+
+ @Test @Config(qualifiers = "w1280dp-h1000dp")
+ fun systemPowerVrGameProfileKeepsOtherComponentChoicesAndRuntimeOptionsAvailable() {
+ val context = RuntimeEnvironment.getApplication()
+ showDxvk(systemPowerVr = true)
+ compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
+ compose.onNodeWithText("Game A").performClick()
+ compose.waitUntil(5_000) {
+ compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
+ }
+
+ compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
+ compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
+ val inheritedChoices = compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general))
+ inheritedChoices.assertCountEquals(4) // FEX preset, FEX package, Proton and VKD3D remain selectable.
+ repeat(4) { inheritedChoices[it].assertIsEnabled() }
+ val runtimeOptions = compose.onAllNodesWithText(context.getString(R.string.comp_game_runtime_options))
+ runtimeOptions.assertCountEquals(2)
+ repeat(2) { runtimeOptions[it].assertIsEnabled() }
+ compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertDoesNotExist()
+
+ compose.onNodeWithText("Game A").performClick()
+ compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
+ compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
+ }
+
+ @Test @Config(qualifiers = "w1280dp-h1000dp")
+ fun systemPowerVrGameProfileCanClearAnExistingDxvkOverrideWithoutSelectingAnother() {
+ val context = RuntimeEnvironment.getApplication()
+ showDxvk(systemPowerVr = true, gameDxvkOverride = true)
+ compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
+ compose.onNodeWithText("Game A").performClick()
+ compose.waitUntil(5_000) {
+ compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
+ }
+
+ compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).performScrollTo().assertIsEnabled().performClick()
+ compose.onNodeWithText("Stored DXVK").assertDoesNotExist()
+ compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general)).onLast().performClick()
+ compose.waitUntil(5_000) { "dxvk" !in ComponentsManager.gameComponents(context, "42") }
+ compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
+ }
+
+ private fun showDxvk(
+ systemPowerVr: Boolean,
+ gameDxvkOverride: Boolean = false,
+ onCancel: () -> Unit = {},
+ onImport: () -> Unit = {},
+ onSwap: (String) -> Unit = {},
+ onRestore: (String) -> Unit = {},
+ ) {
+ val context = RuntimeEnvironment.getApplication()
+ File(context.filesDir, "components/state.json").apply {
+ parentFile!!.mkdirs()
+ writeText(if (gameDxvkOverride) """{"profiles":{"42":{"dxvk":"stored.wcp"}}}""" else "{}")
+ }
+ val proton = ComponentsManager.Proton(
+ "test-proton", "Test Proton", File(context.filesDir, "test-proton"), "/test-proton", "1.0", false,
+ )
+ val snapshot = ComponentsManager.Snapshot(
+ protons = listOf(ComponentsManager.ProtonView(
+ proton = proton,
+ components = mapOf("dxvk" to ComponentsManager.Component("1.0", "", "Stored DXVK", "", "stored.wcp", "Next DXVK")),
+ originals = listOf(ComponentsManager.Original("dxvk", "1.0", "Original DXVK", 1)),
+ inUseByGame = false,
+ )),
+ packages = listOf(ComponentsManager.Package("stored.wcp", "dxvk", "Stored DXVK", "", 1)),
+ )
+ compose.setContent {
+ DroidDeckTheme {
+ ComponentsPage(
+ snapshot = snapshot,
+ catalog = emptyList(),
+ catalogAt = 0,
+ protonId = proton.id,
+ comp = "dxvk",
+ checking = false,
+ busy = null,
+ downloads = emptyMap(),
+ onProton = {},
+ onComp = {},
+ onSwap = onSwap,
+ onRestore = onRestore,
+ onCancelQueued = onCancel,
+ onDeletePackage = {},
+ onDeleteOriginal = {},
+ onDownload = {},
+ onRefresh = {},
+ onImport = onImport,
+ onBack = {},
+ gpu = GpuDriversState(powerVr = true, systemPowerVr = systemPowerVr),
+ games = listOf(Library.SteamGame(42, "Game A", null, "internal")),
+ requestInitialFocus = false,
+ )
+ }
+ }
+ }
+
}
diff --git a/tools/build_local.sh b/tools/build_local.sh
index 224e9b8351..b13c0958be 100755
--- a/tools/build_local.sh
+++ b/tools/build_local.sh
@@ -13,7 +13,7 @@ else
fi
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
-image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
+image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v4}
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
case "$build_variant" in
debug) gradle_task=assembleDebug ;;
@@ -102,6 +102,11 @@ docker run --rm --platform linux/amd64 \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
+ mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
+ aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
+ -o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
+ aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
+ install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
mkdir -p "$d/usr/local/bin"
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
@@ -322,6 +327,7 @@ fi
cd "${repo_root}"
python3 tools/quest/build-driver.py "${NDK}"
bash tools/comet/build-local.sh
+python3 tools/powervr/fetch.py
python3 tools/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md
index acb3455152..6c02250743 100644
--- a/tools/gamescope/PATCHES.md
+++ b/tools/gamescope/PATCHES.md
@@ -45,5 +45,20 @@ library list, before anything is published.
`GAMESCOPE_FOCUSABLE_WINDOWS`, so the client kept its loading screen over the running game
(Skyrim SE, A Plague Tale: Innocence, on the games' own Xwayland). MapNotify now refreshes the flag.
+The system PowerVR driver uses the existing SDL/Wayland swapchain backend. Its additional patches are:
+
+- `0120-nested-swapchain-capability-fallback.patch`: negotiate the surface's usages, mutable-format
+ support, image count, alpha and extent; use offscreen composition and GPU copies when required.
+- `0121-powervr-single-pixel-rcas.patch`: use the existing single-pixel RCAS shader on PowerVR,
+ where the quad variant fails compilation.
+- `0122-powervr-linear-dmabuf-import.patch`: retain the explicit linear layout when PowerVR
+ rejects the mutable-format query, and intersect imported-image and FD memory-type masks.
+- `0123-powervr-rgba-copy-surface.patch`: require an advertised RGBA SDR copy surface matching
+ the shader's `rgba8` storage view. The tested workaround leaves other vendors, HDR and direct
+ composition unchanged; it does not restrict game-facing BGRA formats.
+- `0124-sdl-preserve-explicit-refresh.patch` and `0125-sdl-wait-before-present.patch`: preserve
+ configured refresh across SDL events and finish composition before presenting without a
+ render-finished semaphore. The build runs the focused capability, format and refresh tests.
+
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
diff --git a/tools/gamescope/build-in-arch.sh b/tools/gamescope/build-in-arch.sh
index 2078592aa0..55d6db7b03 100755
--- a/tools/gamescope/build-in-arch.sh
+++ b/tools/gamescope/build-in-arch.sh
@@ -55,9 +55,12 @@ makepkg -A -s --noconfirm --skipchecksums --skippgpcheck # -A: the PKGBUILD lis
ls -l *.pkg.tar.*
"
cd "$WORK"
+g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \
+ tools/gamescope/tests/nested-swapchain.cpp -o pkg/test-nested-swapchain
+pkg/test-nested-swapchain
rm -rf out && mkdir -p out/usr/local/bin
PKG=$(ls pkg/arch/gamescope-*.pkg.tar.* | grep -v -- '-debug-' | head -1)
-tar --use-compress-program=unzstd -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope
+tar -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope
mv out/gamescope out/usr/local/bin/gamescope
chmod 755 out/usr/local/bin/gamescope
strip --strip-unneeded out/usr/local/bin/gamescope || true
diff --git a/tools/gamescope/patches/0120-nested-swapchain-capability-fallback.patch b/tools/gamescope/patches/0120-nested-swapchain-capability-fallback.patch
new file mode 100644
index 0000000000..c26c8f82bb
--- /dev/null
+++ b/tools/gamescope/patches/0120-nested-swapchain-capability-fallback.patch
@@ -0,0 +1,358 @@
+diff --git a/src/nested_swapchain.hpp b/src/nested_swapchain.hpp
+new file mode 100644
+index 0000000..06fc987
+--- /dev/null
++++ b/src/nested_swapchain.hpp
+@@ -0,0 +1,53 @@
++#pragma once
++
++#include
++#include
++
++namespace gamescope
++{
++struct NestedSwapchainConfig
++{
++ bool copy = false;
++ uint32_t imageCount = 0;
++ VkImageUsageFlags usage = 0;
++ VkCompositeAlphaFlagBitsKHR alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
++ VkExtent2D extent = {};
++};
++
++inline bool ChooseNestedSwapchainConfig( const VkSurfaceCapabilitiesKHR &caps,
++ bool mutableFormat, uint32_t width, uint32_t height, NestedSwapchainConfig &config )
++{
++ constexpr VkImageUsageFlags direct = VK_IMAGE_USAGE_SAMPLED_BIT |
++ VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
++ config.copy = !mutableFormat || ( caps.supportedUsageFlags & direct ) != direct;
++ config.usage = config.copy ? VkImageUsageFlags{VK_IMAGE_USAGE_TRANSFER_DST_BIT} : direct;
++ if ( ( caps.supportedUsageFlags & config.usage ) != config.usage )
++ return false;
++
++ bool foundAlpha = false;
++ for ( auto alpha : { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
++ VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR } )
++ {
++ if ( caps.supportedCompositeAlpha & alpha )
++ {
++ config.alpha = alpha;
++ foundAlpha = true;
++ break;
++ }
++ }
++ if ( !foundAlpha || caps.maxImageExtent.width < caps.minImageExtent.width ||
++ caps.maxImageExtent.height < caps.minImageExtent.height )
++ return false;
++
++ config.imageCount = caps.minImageCount + ( caps.minImageCount != UINT32_MAX );
++ if ( caps.maxImageCount )
++ config.imageCount = std::min( config.imageCount, caps.maxImageCount );
++ if ( config.imageCount < caps.minImageCount )
++ return false;
++ config.extent = caps.currentExtent.width == UINT32_MAX
++ ? VkExtent2D{ std::clamp( width, caps.minImageExtent.width, caps.maxImageExtent.width ),
++ std::clamp( height, caps.minImageExtent.height, caps.maxImageExtent.height ) }
++ : caps.currentExtent;
++ return config.extent.width && config.extent.height;
++}
++}
+diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
+index ffad695..ffc8e28 100644
+--- a/src/rendervulkan.cpp
++++ b/src/rendervulkan.cpp
+@@ -12,6 +12,7 @@
+ #include
+ #include
+ #include "vulkan_include.h"
++#include "nested_swapchain.hpp"
+ #include "Utils/Algorithm.h"
+
+ #if defined(__linux__)
+@@ -450,6 +451,8 @@ bool CVulkanDevice::createDevice()
+ bool hasDrmProps = vulkan_has_drm_props();
+ bool supportsForeignQueue = false;
+ bool supportsHDRMetadata = false;
++ bool presentIdExtension = false;
++ bool presentWaitExtension = false;
+ for (const auto& ext : m_supportedExts) {
+ if ( strcmp(ext.extensionName, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0 )
+ m_bSupportsModifiers = true;
+@@ -457,6 +460,13 @@ bool CVulkanDevice::createDevice()
+ if ( strcmp(ext.extensionName, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME) == 0 )
+ supportsForeignQueue = true;
+
++ if ( strcmp(ext.extensionName, VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME) == 0 )
++ m_bSupportsMutableSwapchain = true;
++ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_ID_EXTENSION_NAME) == 0 )
++ presentIdExtension = true;
++ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_WAIT_EXTENSION_NAME) == 0 )
++ presentWaitExtension = true;
++
+ if ( strcmp(ext.extensionName, VK_EXT_HDR_METADATA_EXTENSION_NAME) == 0 )
+ supportsHDRMetadata = true;
+ }
+@@ -576,10 +586,24 @@ bool CVulkanDevice::createDevice()
+ if ( GetBackend()->UsesVulkanSwapchain() )
+ {
+ enabledExtensions.push_back( VK_KHR_SWAPCHAIN_EXTENSION_NAME );
+- enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
++ if ( m_bSupportsMutableSwapchain )
++ enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
+
+- enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
+- enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
++ if ( presentIdExtension && presentWaitExtension )
++ {
++ VkPhysicalDevicePresentWaitFeaturesKHR wait = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR };
++ VkPhysicalDevicePresentIdFeaturesKHR id = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR, .pNext = &wait };
++ VkPhysicalDeviceFeatures2 features = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &id };
++ vk.GetPhysicalDeviceFeatures2( physDev(), &features );
++ m_bSupportsPresentWait = id.presentId && wait.presentWait;
++ }
++ if ( m_bSupportsPresentWait )
++ {
++ enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
++ enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
++ }
++ else
++ vk_log.infof( "Using FIFO acquire pacing; presentation timestamps unavailable" );
+
+ if ( supportsHDRMetadata )
+ enabledExtensions.push_back( VK_EXT_HDR_METADATA_EXTENSION_NAME );
+@@ -654,7 +678,7 @@ bool CVulkanDevice::createDevice()
+
+ VkPhysicalDeviceFeatures2 features2 = {
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
+- .pNext = &presentIdFeatures,
++ .pNext = m_bSupportsPresentWait ? static_cast( &presentIdFeatures ) : static_cast( &features13 ),
+ .features = {
+ .shaderInt16 = m_bSupportsFp16,
+ },
+@@ -2660,7 +2684,7 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
+ return true;
+ }
+
+-bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format )
++bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format, bool transferOnly )
+ {
+ m_drmFormat = VulkanFormatToDRM( format );
+ m_vkImage = image;
+@@ -2672,6 +2696,12 @@ bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t
+ m_contentWidth = width;
+ m_contentHeight = height;
+ m_bOutputImage = true;
++ if ( transferOnly )
++ {
++ // A copy destination needs no views (and the swapchain need not be mutable).
++ m_bInitialized = true;
++ return true;
++ }
+
+ VkImageViewCreateInfo createInfo = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
+@@ -3094,7 +3124,7 @@ void vulkan_present_to_window( void )
+
+ VkPresentInfoKHR presentInfo = {
+ .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
+- .pNext = &presentIdInfo,
++ .pNext = g_device.supportsPresentWait() ? &presentIdInfo : nullptr,
+ .swapchainCount = 1,
+ .pSwapchains = &g_output.swapChain,
+ .pImageIndices = &g_output.nOutImage,
+@@ -3102,14 +3132,22 @@ void vulkan_present_to_window( void )
+
+ if ( g_device.vk.QueuePresentKHR( g_device.queue(), &presentInfo ) == VK_SUCCESS )
+ {
+- g_currentPresentWaitId = presentId;
+- g_currentPresentWaitId.notify_all();
++ if ( g_device.supportsPresentWait() )
++ {
++ g_currentPresentWaitId = presentId;
++ g_currentPresentWaitId.notify_all();
++ }
+ }
+ else
+ vulkan_remake_swapchain();
+
+ while ( !acquire_next_image() )
+ vulkan_remake_swapchain();
++ if ( !g_device.supportsPresentWait() )
++ {
++ // Estimated scheduling anchor after FIFO buffer acquisition, not presentation feedback.
++ GetVBlankTimer().MarkVBlank( get_time_in_nanos(), true );
++ }
+ }
+
+ gamescope::Rc vulkan_create_1d_lut(uint32_t size)
+@@ -3219,7 +3257,19 @@ extern bool g_bOutputHDREnabled;
+
+ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
+ {
+- uint32_t imageCount = pOutput->surfaceCaps.minImageCount + 1;
++ // Re-query on resize as well as initial creation.
++ if ( g_device.vk.GetPhysicalDeviceSurfaceCapabilitiesKHR( g_device.physDev(), pOutput->surface, &pOutput->surfaceCaps ) != VK_SUCCESS )
++ return false;
++ gamescope::NestedSwapchainConfig config;
++ if ( !gamescope::ChooseNestedSwapchainConfig( pOutput->surfaceCaps, g_device.supportsMutableSwapchain(), g_nOutputWidth, g_nOutputHeight, config ) )
++ {
++ vk_log.errorf( "Surface supports neither direct composition nor transfer presentation" );
++ return false;
++ }
++ pOutput->copyToSwapchain = config.copy;
++ g_nOutputWidth = config.extent.width;
++ g_nOutputHeight = config.extent.height;
++ uint32_t imageCount = config.imageCount;
+ uint32_t formatCount = pOutput->surfaceFormats.size();
+ uint32_t surfaceFormat = formatCount;
+ VkColorSpaceKHR preferredColorSpace = g_bOutputHDREnabled ? VK_COLOR_SPACE_HDR10_ST2084_EXT : VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
+@@ -3254,6 +3304,13 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
+ }
+ }
+
++ if ( surfaceFormat == formatCount )
++ {
++ for ( surfaceFormat = 0; surfaceFormat < formatCount; ++surfaceFormat )
++ if ( pOutput->surfaceFormats[surfaceFormat].format == VK_FORMAT_R8G8B8A8_UNORM &&
++ pOutput->surfaceFormats[surfaceFormat].colorSpace == preferredColorSpace )
++ break;
++ }
+ if ( surfaceFormat == formatCount )
+ return false;
+
+@@ -3276,8 +3333,8 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
+
+ VkSwapchainCreateInfoKHR createInfo = {
+ .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
+- .pNext = formats[0] != formats[1] ? &usageListInfo : nullptr,
+- .flags = formats[0] != formats[1] ? VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR : (VkSwapchainCreateFlagBitsKHR )0,
++ .pNext = !config.copy && formats[0] != formats[1] ? &usageListInfo : nullptr,
++ .flags = !config.copy && formats[0] != formats[1] ? VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR : (VkSwapchainCreateFlagBitsKHR )0,
+ .surface = pOutput->surface,
+ .minImageCount = imageCount,
+ .imageFormat = eVkFormat,
+@@ -3287,10 +3344,10 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
+ .height = g_nOutputHeight,
+ },
+ .imageArrayLayers = 1,
+- .imageUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
++ .imageUsage = config.usage,
+ .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
+ .preTransform = pOutput->surfaceCaps.currentTransform,
+- .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
++ .compositeAlpha = config.alpha,
+ .presentMode = VK_PRESENT_MODE_FIFO_KHR,
+ .clipped = VK_TRUE,
+ };
+@@ -3304,12 +3361,30 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
+ g_device.vk.GetSwapchainImagesKHR( g_device.device(), pOutput->swapChain, &imageCount, swapchainImages.data() );
+
+ pOutput->outputImages.resize(imageCount);
++ pOutput->presentationImages.clear();
++ if ( config.copy )
++ {
++ vk_log.infof( "Nested swapchain: composing offscreen and copying to FIFO presentation images" );
++ pOutput->presentationImages.resize(imageCount);
++ }
+
+ for ( uint32_t i = 0; i < pOutput->outputImages.size(); i++ )
+ {
+ pOutput->outputImages[i] = new CVulkanTexture();
+
+- if ( !pOutput->outputImages[i]->BInitFromSwapchain(swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat))
++ if ( config.copy )
++ {
++ CVulkanTexture::createFlags flags;
++ flags.bStorage = true;
++ flags.bSampled = true;
++ flags.bTransferSrc = true;
++ if ( !pOutput->outputImages[i]->BInit( g_nOutputWidth, g_nOutputHeight, 1, pOutput->uOutputFormat, flags ) )
++ return false;
++ pOutput->presentationImages[i] = new CVulkanTexture();
++ if ( !pOutput->presentationImages[i]->BInitFromSwapchain( swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat, true ) )
++ return false;
++ }
++ else if ( !pOutput->outputImages[i]->BInitFromSwapchain(swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat))
+ return false;
+ }
+
+@@ -3335,6 +3410,10 @@ bool vulkan_remake_swapchain( void )
+ g_device.vk.QueueWaitIdle( g_device.queue() );
+
+ pOutput->outputImages.clear();
++ pOutput->presentationImages.clear();
++ if ( pOutput->acquireFence )
++ g_device.vk.DestroyFence( g_device.device(), pOutput->acquireFence, nullptr );
++ pOutput->acquireFence = VK_NULL_HANDLE;
+
+ g_device.vk.DestroySwapchainKHR( g_device.device(), pOutput->swapChain, nullptr );
+
+@@ -3670,7 +3749,7 @@ bool vulkan_init( VkInstance instance, VkSurfaceKHR surface )
+ if (!init_nis_data())
+ return false;
+
+- if ( GetBackend()->UsesVulkanSwapchain() )
++ if ( GetBackend()->UsesVulkanSwapchain() && g_device.supportsPresentWait() )
+ {
+ std::thread present_wait_thread( present_wait_thread_func );
+ present_wait_thread.detach();
+@@ -4579,6 +4658,9 @@ std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
+ CompositeTimingEnd( cmdBuffer.get(), *oTimingSlot, pszKey, pszKeyPre, pszKeyPost );
+ }
+
++ if ( !pOutputOverride && g_output.copyToSwapchain )
++ cmdBuffer->copyImage( compositeImage, g_output.presentationImages[g_output.nOutImage] );
++
+ uint64_t sequence = g_device.submit(std::move(cmdBuffer));
+ if ( oTimingSlot )
+ g_CompositeTiming.pending.back().ulSeqNo = sequence;
+diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
+index fa519db..674a3b4 100644
+--- a/src/rendervulkan.hpp
++++ b/src/rendervulkan.hpp
+@@ -162,7 +162,7 @@ public:
+ };
+
+ bool BInit( uint32_t width, uint32_t height, uint32_t depth, uint32_t drmFormat, createFlags flags, wlr_dmabuf_attributes *pDMA = nullptr, uint32_t contentWidth = 0, uint32_t contentHeight = 0, CVulkanTexture *pExistingImageToReuseMemory = nullptr, gamescope::OwningRc pBackendFb = nullptr );
+- bool BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format );
++ bool BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format, bool transferOnly = false );
+
+ uint32_t IncRef();
+ uint32_t DecRef();
+@@ -586,7 +586,9 @@ struct VulkanOutput_t
+
+ std::shared_ptr swapchainHDRMetadata;
+ VkSwapchainKHR swapChain;
+- VkFence acquireFence;
++ VkFence acquireFence = VK_NULL_HANDLE;
++ bool copyToSwapchain = false;
++ std::vector> presentationImages;
+
+ uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs
+ std::vector> outputImages;
+@@ -756,6 +758,7 @@ static inline uint32_t div_roundup(uint32_t x, uint32_t y)
+ VK_FUNC(CreateDescriptorPool) \
+ VK_FUNC(CreateDescriptorSetLayout) \
+ VK_FUNC(CreateFence) \
++ VK_FUNC(DestroyFence) \
+ VK_FUNC(CreateGraphicsPipelines) \
+ VK_FUNC(CreateImage) \
+ VK_FUNC(CreateImageView) \
+@@ -862,6 +865,8 @@ public:
+ inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
+ inline int drmRenderFd() {return m_drmRendererFd;}
+ inline bool supportsModifiers() {return m_bSupportsModifiers;}
++ inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
++ inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
+ inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
+ inline dev_t primaryDevId() {return m_drmPrimaryDevId;}
+ inline bool supportsFp16() {return m_bSupportsFp16;}
+@@ -930,6 +935,8 @@ protected:
+ uint32_t m_uVendorID = 0;
+ bool m_bHasDrmPrimaryDevId = false;
+ bool m_bSupportsModifiers = false;
++ bool m_bSupportsMutableSwapchain = false;
++ bool m_bSupportsPresentWait = false;
+ bool m_bInitialized = false;
+
+
diff --git a/tools/gamescope/patches/0121-powervr-single-pixel-rcas.patch b/tools/gamescope/patches/0121-powervr-single-pixel-rcas.patch
new file mode 100644
index 0000000000..d2b3aafeab
--- /dev/null
+++ b/tools/gamescope/patches/0121-powervr-single-pixel-rcas.patch
@@ -0,0 +1,15 @@
+diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
+--- a/src/rendervulkan.cpp
++++ b/src/rendervulkan.cpp
+@@ -996,8 +996,9 @@
+ SHADER(BLUR, cs_composite_blur);
+ SHADER(BLUR_COND, cs_composite_blur_cond);
+ SHADER(BLUR_FIRST_PASS, cs_gaussian_blur_horizontal);
+- // The one pixel layout is only measured on Adreno, every other vendor keeps the quad swizzle.
+- if (m_uVendorID == 0x5143) /* Qualcomm */
++ // PowerVR rejects the quad-swizzled RCAS for 3+ layers with YCbCr mask 2.
++ // The existing one-pixel shader compiles those variants and covers the same 16x16 tile.
++ if (m_uVendorID == 0x5143 || m_uVendorID == 0x1010) /* Qualcomm or Imagination */
+ {
+ SHADER(RCAS, cs_composite_rcas_1px);
+ }
diff --git a/tools/gamescope/patches/0122-powervr-linear-dmabuf-import.patch b/tools/gamescope/patches/0122-powervr-linear-dmabuf-import.patch
new file mode 100644
index 0000000000..40a913560c
--- /dev/null
+++ b/tools/gamescope/patches/0122-powervr-linear-dmabuf-import.patch
@@ -0,0 +1,156 @@
+diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
+--- a/src/rendervulkan.cpp
++++ b/src/rendervulkan.cpp
+@@ -13,6 +13,7 @@
+ #include
+ #include "vulkan_include.h"
+ #include "nested_swapchain.hpp"
++#include "dmabuf_import.hpp"
+ #include "Utils/Algorithm.h"
+
+ #if defined(__linux__)
+@@ -2229,8 +2230,27 @@
+ return false;
+ }
+
+- if ( res == VK_SUCCESS &&
+- ( externalImageProperties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT ) )
++ bool importable = res == VK_SUCCESS &&
++ ( externalImageProperties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT );
++ if ( gamescope::RetryPowerVRLinearQuery( g_device.vendorID(), imageInfo.format,
++ pDMA->modifier, pDMA->n_planes, imageInfo.flags, res ) )
++ {
++ // PowerVR's mutable-format query rejects this linear import even though
++ // explicit-layout imports and UNORM/sRGB GPU sampling work. Query the base
++ // format without changing the image we actually create or its supplied stride.
++ VkImageCreateInfo baseFormat = imageInfo;
++ baseFormat.flags &= ~VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
++ baseFormat.pNext = nullptr;
++ res = getModifierProps( &baseFormat, pDMA->modifier, &externalImageProperties );
++ importable = res == VK_SUCCESS &&
++ ( externalImageProperties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT );
++ }
++ if ( !importable && g_device.vendorID() == 0x1010 )
++ {
++ vk_log.errorf( "PowerVR DMA-BUF modifier is not importable; refusing a different tiling" );
++ return false;
++ }
++ if ( importable )
+ {
+ modifierInfo = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
+@@ -2348,6 +2368,22 @@
+
+ m_format = imageInfo.format;
+
++ VkMemoryFdPropertiesKHR fdProperties = {
++ .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
++ };
++ if ( pDMA )
++ {
++ if ( !g_device.vk.GetMemoryFdPropertiesKHR )
++ return false;
++ res = g_device.vk.GetMemoryFdPropertiesKHR( g_device.device(),
++ VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, pDMA->fd[0], &fdProperties );
++ if ( res != VK_SUCCESS )
++ {
++ vk_errorf( res, "vkGetMemoryFdPropertiesKHR failed" );
++ return false;
++ }
++ }
++
+ res = g_device.vk.CreateImage(g_device.device(), &imageInfo, nullptr, &m_vkImage);
+ if (res != VK_SUCCESS) {
+ vk_errorf( res, "vkCreateImage failed" );
+@@ -2357,10 +2393,22 @@
+ VkMemoryRequirements memRequirements;
+ g_device.vk.GetImageMemoryRequirements(g_device.device(), m_vkImage, &memRequirements);
+
++ uint32_t memoryType = pDMA
++ ? gamescope::DmabufMemoryType( g_device.memoryProperties(), memRequirements.memoryTypeBits,
++ fdProperties.memoryTypeBits, properties )
++ : uint32_t( g_device.findMemoryType( properties, memRequirements.memoryTypeBits ) );
++ if ( memoryType == UINT32_MAX )
++ {
++ vk_log.errorf( "No compatible image memory type (image=0x%x, fd=0x%x)",
++ memRequirements.memoryTypeBits, fdProperties.memoryTypeBits );
++ g_device.vk.DestroyImage( g_device.device(), m_vkImage, nullptr );
++ m_vkImage = VK_NULL_HANDLE;
++ return false;
++ }
+ VkMemoryAllocateInfo allocInfo = {
+ .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
+ .allocationSize = memRequirements.size,
+- .memoryTypeIndex = uint32_t(g_device.findMemoryType(properties, memRequirements.memoryTypeBits)),
++ .memoryTypeIndex = memoryType,
+ };
+
+ m_size = allocInfo.allocationSize;
+@@ -2453,6 +2501,13 @@
+ if ( res != VK_SUCCESS )
+ {
+ vk_errorf( res, "vkBindImageMemory failed" );
++ if ( pDMA )
++ vk_log.errorf( "DMA-BUF: %ux%u format=%u modifier=0x%" PRIx64
++ " planes=%d stride=%u offset=%u tiling=%u allocation=%" PRIu64
++ " memoryType=%u imageBits=0x%x fdBits=0x%x", width, height, imageInfo.format,
++ pDMA->modifier, pDMA->n_planes, pDMA->stride[0], pDMA->offset[0], imageInfo.tiling,
++ uint64_t( allocInfo.allocationSize ), allocInfo.memoryTypeIndex,
++ memRequirements.memoryTypeBits, fdProperties.memoryTypeBits );
+ return false;
+ }
+
+diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
+--- a/src/rendervulkan.hpp
++++ b/src/rendervulkan.hpp
+@@ -791,6 +791,7 @@
+ VK_FUNC(GetImageMemoryRequirements) \
+ VK_FUNC(GetImageSubresourceLayout) \
+ VK_FUNC(GetMemoryFdKHR) \
++ VK_FUNC(GetMemoryFdPropertiesKHR) \
+ VK_FUNC(GetQueryPoolResults) \
+ VK_FUNC(GetSemaphoreCounterValue) \
+ VK_FUNC(GetSwapchainImagesKHR) \
+@@ -865,6 +866,8 @@
+ inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
+ inline int drmRenderFd() {return m_drmRendererFd;}
+ inline bool supportsModifiers() {return m_bSupportsModifiers;}
++ inline uint32_t vendorID() const {return m_uVendorID;}
++ inline const VkPhysicalDeviceMemoryProperties &memoryProperties() const {return m_memoryProperties;}
+ inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
+ inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
+ inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
+diff --git a/src/dmabuf_import.hpp b/src/dmabuf_import.hpp
+new file mode 100644
+--- /dev/null
++++ b/src/dmabuf_import.hpp
+@@ -0,0 +1,29 @@
++#pragma once
++#include
++
++namespace gamescope
++{
++inline bool RetryPowerVRLinearQuery( uint32_t vendor, VkFormat format, uint64_t modifier,
++ uint32_t planes, VkImageCreateFlags flags, VkResult result )
++{
++ return vendor == 0x1010 && modifier == 0 && planes == 1 &&
++ flags == VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT && result == VK_ERROR_FORMAT_NOT_SUPPORTED &&
++ ( format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_B8G8R8A8_UNORM );
++}
++
++inline uint32_t DmabufMemoryType( const VkPhysicalDeviceMemoryProperties &memory,
++ uint32_t imageBits, uint32_t fdBits, VkMemoryPropertyFlags preferred )
++{
++ uint32_t fallback = UINT32_MAX;
++ const uint32_t compatible = imageBits & fdBits;
++ for ( uint32_t i = 0; i < memory.memoryTypeCount; ++i )
++ {
++ if ( !( compatible & ( 1u << i ) ) ) continue;
++ if ( fallback == UINT32_MAX ) fallback = i;
++ if ( ( memory.memoryTypes[i].propertyFlags & preferred ) == preferred ) return i;
++ }
++ // Device-local is a preference for an existing imported buffer. CPU mapping
++ // properties are requirements and must never be silently relaxed.
++ return preferred == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ? fallback : UINT32_MAX;
++}
++}
diff --git a/tools/gamescope/patches/0123-powervr-rgba-copy-surface.patch b/tools/gamescope/patches/0123-powervr-rgba-copy-surface.patch
new file mode 100644
index 0000000000..72344e6bc6
--- /dev/null
+++ b/tools/gamescope/patches/0123-powervr-rgba-copy-surface.patch
@@ -0,0 +1,61 @@
+diff --git a/src/nested_surface_format.hpp b/src/nested_surface_format.hpp
+new file mode 100644
+--- /dev/null
++++ b/src/nested_surface_format.hpp
+@@ -0,0 +1,31 @@
++#pragma once
++
++#include
++
++namespace gamescope
++{
++// The SDR composition shader declares rgba8, which requires an R8G8B8A8_UNORM
++// storage view. Binding a BGRA view is a format mismatch; a same-format copy
++// cannot correct it. Keep the workaround scoped to the PowerVR SDR copy path
++// where the channel reversal was reproduced, not game-facing texture formats.
++// On success, formatCount means the existing selector should choose the format.
++// On failure, no matching RGBA SDR surface was advertised for this scoped path.
++inline bool ChooseNestedSDRCopySurfaceFormat( uint32_t vendorId, bool copy, bool hdr,
++ const VkSurfaceFormatKHR *formats, uint32_t formatCount, uint32_t &surfaceFormat )
++{
++ surfaceFormat = formatCount;
++ if ( vendorId != 0x1010 || !copy || hdr )
++ return true;
++
++ for ( uint32_t i = 0; i < formatCount; ++i )
++ {
++ if ( formats[i].format == VK_FORMAT_R8G8B8A8_UNORM &&
++ formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR )
++ {
++ surfaceFormat = i;
++ return true;
++ }
++ }
++ return false;
++}
++}
+diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
+--- a/src/rendervulkan.cpp
++++ b/src/rendervulkan.cpp
+@@ -14,6 +14,7 @@
+ #include "vulkan_include.h"
+ #include "nested_swapchain.hpp"
+ #include "dmabuf_import.hpp"
++#include "nested_surface_format.hpp"
+ #include "Utils/Algorithm.h"
+
+ #if defined(__linux__)
+@@ -3330,6 +3331,13 @@
+ uint32_t surfaceFormat = formatCount;
+ VkColorSpaceKHR preferredColorSpace = g_bOutputHDREnabled ? VK_COLOR_SPACE_HDR10_ST2084_EXT : VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
+
++ if ( !gamescope::ChooseNestedSDRCopySurfaceFormat( g_device.vendorID(), config.copy,
++ g_bOutputHDREnabled, pOutput->surfaceFormats.data(), formatCount, surfaceFormat ) )
++ {
++ vk_log.errorf( "PowerVR copy composition requires an RGBA SDR surface" );
++ return false;
++ }
++
+ if ( surfaceFormat == formatCount )
+ {
+ for ( surfaceFormat = 0; surfaceFormat < formatCount; surfaceFormat++ )
diff --git a/tools/gamescope/patches/0124-sdl-preserve-explicit-refresh.patch b/tools/gamescope/patches/0124-sdl-preserve-explicit-refresh.patch
new file mode 100644
index 0000000000..2ec1a18d29
--- /dev/null
+++ b/tools/gamescope/patches/0124-sdl-preserve-explicit-refresh.patch
@@ -0,0 +1,78 @@
+diff --git a/src/sdl_refresh.hpp b/src/sdl_refresh.hpp
+new file mode 100644
+--- /dev/null
++++ b/src/sdl_refresh.hpp
+@@ -0,0 +1,22 @@
++#pragma once
++
++#include
++
++namespace gamescope
++{
++struct SDLRefreshChoice
++{
++ int32_t refresh = 0;
++ bool configured = false;
++};
++
++// SDL reports the desktop mode again when its window is shown, moved or resized. Keep an
++// explicit -r as the rate exposed by nested Gamescope; discover the desktop rate only when the
++// caller did not configure one.
++inline constexpr SDLRefreshChoice ChooseSDLRefresh( int32_t configuredRefresh, int32_t desktopRefresh )
++{
++ return configuredRefresh > 0
++ ? SDLRefreshChoice{ configuredRefresh, true }
++ : SDLRefreshChoice{ desktopRefresh, false };
++}
++}
+diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
+--- a/src/Backends/SDLBackend.cpp
++++ b/src/Backends/SDLBackend.cpp
+@@ -18,14 +18,20 @@
+ #include "steamcompmgr.hpp"
+ #include "Utils/Defer.h"
+ #include "refresh_rate.h"
++#include "log.hpp"
++#include "sdl_refresh.hpp"
+
+ #include "sdlscancodetable.hpp"
+
+ static int g_nOldNestedRefresh = 0;
+ static bool g_bWindowFocused = true;
++static int g_nLastLoggedConfiguredRefresh = -1;
++static int g_nLastLoggedDesktopRefresh = -1;
++static int g_nLastLoggedEffectiveRefresh = -1;
+
+ static int g_nOutputWidthPts = 0;
+ static int g_nOutputHeightPts = 0;
++static LogScope sdl_log( "sdl_backend" );
+
+ extern bool g_bForceHDR10OutputDebug;
+ extern bool steamMode;
+@@ -846,9 +851,25 @@ namespace gamescope
+ SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
+
+ display_index = SDL_GetWindowDisplayIndex( m_Connector.GetSDLWindow() );
+ if ( SDL_GetDesktopDisplayMode( display_index, &mode ) == 0 )
+ {
+- g_nOutputRefresh = ConvertHztomHz( mode.refresh_rate );
++ const int nDesktopRefresh = ConvertHztomHz( mode.refresh_rate );
++ const SDLRefreshChoice refresh = ChooseSDLRefresh( g_nOldNestedRefresh, nDesktopRefresh );
++ g_nOutputRefresh = refresh.refresh;
++
++ if ( g_nLastLoggedConfiguredRefresh != g_nOldNestedRefresh ||
++ g_nLastLoggedDesktopRefresh != nDesktopRefresh ||
++ g_nLastLoggedEffectiveRefresh != refresh.refresh )
++ {
++ sdl_log.infof( "Refresh mode: configured=%.3fHz desktop=%.3fHz effective=%.3fHz source=%s",
++ ConvertmHzToHz( float( g_nOldNestedRefresh ) ),
++ ConvertmHzToHz( float( nDesktopRefresh ) ),
++ ConvertmHzToHz( float( refresh.refresh ) ),
++ refresh.configured ? "configured -r" : "SDL desktop" );
++ g_nLastLoggedConfiguredRefresh = g_nOldNestedRefresh;
++ g_nLastLoggedDesktopRefresh = nDesktopRefresh;
++ g_nLastLoggedEffectiveRefresh = refresh.refresh;
++ }
+ }
+ }
+ break;
diff --git a/tools/gamescope/patches/0125-sdl-wait-before-present.patch b/tools/gamescope/patches/0125-sdl-wait-before-present.patch
new file mode 100644
index 0000000000..d8037df9c4
--- /dev/null
+++ b/tools/gamescope/patches/0125-sdl-wait-before-present.patch
@@ -0,0 +1,23 @@
+diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
+--- a/src/Backends/SDLBackend.cpp
++++ b/src/Backends/SDLBackend.cpp
+@@ -351,14 +351,15 @@ namespace gamescope
+ std::optional oCompositeResult = vulkan_composite( (FrameInfo_t *)pFrameInfo, nullptr, false );
+ if ( !oCompositeResult )
+ return -EINVAL;
+
++ // Present has no render-finished semaphore, so wait before the native consumer can read
++ // the old contents. This serializes composition and present; a future pipelined path must
++ // signal a binary render-finished semaphore and make vkQueuePresentKHR wait on it.
++ vulkan_wait( *oCompositeResult, true );
++
+ vulkan_present_to_window();
+
+ // TODO: Hook up PresentationFeedback.
+-
+- // Wait for the composite result on our side *after* we
+- // commit the buffer to the compositor to avoid a bubble.
+- vulkan_wait( *oCompositeResult, true );
+
+ GetVBlankTimer().UpdateWasCompositing( true );
+ GetVBlankTimer().UpdateLastDrawTime( get_time_in_nanos() - g_SteamCompMgrVBlankTime.ulWakeupTime );
diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env
index 9f895d08d6..04e103bf57 100644
--- a/tools/gamescope/release.env
+++ b/tools/gamescope/release.env
@@ -1,3 +1,3 @@
-GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
-GAMESCOPE_TAG=gamescope-3.16.29-p9
-GAMESCOPE_SHA256=7123a37bdbcd0d76d4bd1d7490e5d2017221e036395fdd48c1e92458594ca769
+GAMESCOPE_REPO=wallentx/DroidDeck
+GAMESCOPE_TAG=gamescope-3.16.29-p13-powervr
+GAMESCOPE_SHA256=39e70fe9d8674da86442805d137f6bb078a83c5fac503d45b50ca66d4d3b7b04
diff --git a/tools/gamescope/tests/nested-swapchain.cpp b/tools/gamescope/tests/nested-swapchain.cpp
new file mode 100644
index 0000000000..a2054aa746
--- /dev/null
+++ b/tools/gamescope/tests/nested-swapchain.cpp
@@ -0,0 +1,156 @@
+#include "nested_swapchain.hpp"
+#include "nested_surface_format.hpp"
+#include "dmabuf_import.hpp"
+#include "sdl_refresh.hpp"
+#include
+#include
+
+int main()
+{
+ using gamescope::ChooseSDLRefresh;
+ constexpr int configured60 = 60'000;
+ constexpr int desktop120 = 120'000;
+ auto capped = ChooseSDLRefresh(configured60, desktop120);
+ assert(capped.configured && capped.refresh == configured60);
+
+ auto discovered = ChooseSDLRefresh(0, desktop120);
+ assert(!discovered.configured && discovered.refresh == desktop120);
+
+ auto configured120 = ChooseSDLRefresh(120'000, 60'000);
+ assert(configured120.configured && configured120.refresh == 120'000);
+
+ VkSurfaceCapabilitiesKHR caps = {};
+ caps.minImageCount = 2;
+ caps.maxImageCount = 3;
+ caps.currentExtent = {UINT32_MAX, UINT32_MAX};
+ caps.minImageExtent = {16, 16};
+ caps.maxImageExtent = {4096, 4096};
+ caps.supportedCompositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
+ caps.supportedUsageFlags = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
+ VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
+ gamescope::NestedSwapchainConfig config;
+
+ // Existing desktop drivers retain direct composition into mutable swapchains.
+ assert(gamescope::ChooseNestedSwapchainConfig(caps, true, 1280, 720, config));
+ assert(!config.copy && config.imageCount == 3 && config.extent.width == 1280);
+
+ // No mutable formats: compose offscreen and request only a copy destination.
+ assert(gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
+ assert(config.copy && config.usage == VK_IMAGE_USAGE_TRANSFER_DST_BIT);
+
+ // The Android bridge exposes transfer usage and inherited alpha, but no storage.
+ caps.supportedUsageFlags &= ~VK_IMAGE_USAGE_STORAGE_BIT;
+ caps.supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
+ caps.maxImageCount = 2;
+ caps.currentExtent = {1602, 720};
+ assert(gamescope::ChooseNestedSwapchainConfig(caps, true, 1920, 1080, config));
+ assert(config.copy && config.alpha == VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR);
+ assert(config.imageCount == 2 && config.extent.width == 1602);
+
+ // Fail rather than submitting unsupported image usage or alpha.
+ caps.supportedUsageFlags &= ~VK_IMAGE_USAGE_TRANSFER_DST_BIT;
+ assert(!gamescope::ChooseNestedSwapchainConfig(caps, true, 1280, 720, config));
+ caps.supportedUsageFlags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
+ caps.supportedCompositeAlpha = 0;
+ assert(!gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
+ caps.supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
+
+ caps.currentExtent = {0, 0};
+ assert(!gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
+ caps.currentExtent = {UINT32_MAX, UINT32_MAX};
+ assert(gamescope::ChooseNestedSwapchainConfig(caps, false, 1, 9000, config));
+ assert(config.extent.width == 16 && config.extent.height == 4096);
+ caps.maxImageCount = 1;
+ assert(!gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
+
+ using gamescope::ChooseNestedSDRCopySurfaceFormat;
+ const VkSurfaceFormatKHR rgba = {
+ VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
+ const VkSurfaceFormatKHR bgra = {
+ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
+ uint32_t surfaceFormat = UINT32_MAX;
+
+ // PowerVR SDR copy output needs the RGBA view matching the rgba8 shader.
+ const VkSurfaceFormatKHR bgraFirst[] = {bgra, rgba, rgba};
+ assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ bgraFirst, 3, surfaceFormat));
+ assert(surfaceFormat == 1);
+ const VkSurfaceFormatKHR rgbaFirst[] = {rgba, bgra};
+ assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ rgbaFirst, 2, surfaceFormat));
+ assert(surfaceFormat == 0);
+ assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ &rgba, 1, surfaceFormat));
+ assert(surfaceFormat == 0);
+
+ // Reusing a successful index must not hide a missing compatible format.
+ assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ &bgra, 1, surfaceFormat));
+ assert(surfaceFormat == 1);
+ const VkSurfaceFormatKHR wrongColorSpace = {
+ VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT};
+ assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ &wrongColorSpace, 1, surfaceFormat));
+ assert(surfaceFormat == 1);
+ const VkSurfaceFormatKHR srgbFormat = {
+ VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
+ assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ &srgbFormat, 1, surfaceFormat));
+ assert(surfaceFormat == 1);
+ const VkSurfaceFormatKHR compatibleLast[] = {wrongColorSpace, srgbFormat, rgba};
+ assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ compatibleLast, 3, surfaceFormat));
+ assert(surfaceFormat == 2);
+ assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
+ nullptr, 0, surfaceFormat));
+ assert(surfaceFormat == 0);
+
+ // The existing selector still owns HDR, direct output, and other vendors.
+ // Each call clears a stale index even when BGRA is the only advertised format.
+ surfaceFormat = 0;
+ assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, true,
+ &bgra, 1, surfaceFormat));
+ assert(surfaceFormat == 1);
+ surfaceFormat = 0;
+ assert(ChooseNestedSDRCopySurfaceFormat(0x1010, false, false,
+ &bgra, 1, surfaceFormat));
+ assert(surfaceFormat == 1);
+ surfaceFormat = 0;
+ assert(ChooseNestedSDRCopySurfaceFormat(0x5143, true, false,
+ &bgra, 1, surfaceFormat));
+ assert(surfaceFormat == 1);
+
+ // Retry only the device/format/layout/flag combination reproduced on PowerVR.
+ using gamescope::RetryPowerVRLinearQuery;
+ assert(RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(RetryPowerVRLinearQuery(0x1010, VK_FORMAT_R8G8B8A8_UNORM, 0, 1,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(!RetryPowerVRLinearQuery(0x5143, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 1, 1,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 2,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_R16G16B16A16_SFLOAT, 0, 1,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
+ 0, VK_ERROR_FORMAT_NOT_SUPPORTED));
+ assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
+ VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_DEVICE_LOST));
+
+ VkPhysicalDeviceMemoryProperties memory = {};
+ memory.memoryTypeCount = 3;
+ memory.memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
+ memory.memoryTypes[1].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
+ VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
+ memory.memoryTypes[2].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
+ using gamescope::DmabufMemoryType;
+ assert(DmabufMemoryType(memory, 7, 6, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 1);
+ assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 2);
+ assert(DmabufMemoryType(memory, 1, 6, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX);
+ assert(DmabufMemoryType(memory, 7, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX);
+ assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
+ VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == UINT32_MAX);
+ std::puts("Gamescope presentation and DMA-BUF import tests passed");
+}
diff --git a/tools/hybris/build_runtime.sh b/tools/hybris/build_runtime.sh
new file mode 100755
index 0000000000..53c7d9481e
--- /dev/null
+++ b/tools/hybris/build_runtime.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# CI-only full libhybris build, using the upstream pinned cross-toolchain recipe.
+set -euo pipefail
+root=$(cd "$(dirname "$0")/../.." && pwd)
+out=${1:?output directory required}
+mkdir -p "$out"
+out=$(cd "$out" && pwd)
+. "$root/tools/hybris/source.env"
+work=$(mktemp -d "${TMPDIR:-/tmp}/droiddeck-hybris.XXXXXX")
+trap 'rm -rf "$work"' EXIT
+fetch() {
+ git init -q "$3"
+ git -C "$3" fetch --depth=1 "$1" "$2"
+ git -C "$3" checkout -q --detach FETCH_HEAD
+ test "$(git -C "$3" rev-parse HEAD)" = "$2"
+}
+fetch https://github.com/taowen/libhybris.git "$HYBRIS_REVISION" "$work/libhybris"
+fetch https://github.com/taowen/arlinux-rootfs.git "$PROTOCOL_REVISION" "$work/rootfs"
+git -C "$work/libhybris" apply --check "$root/tools/hybris/powervr-hal-version.patch"
+git -C "$work/libhybris" apply "$root/tools/hybris/powervr-hal-version.patch"
+for patch in "$root"/tools/hybris/patches/*.patch; do
+ git -C "$work/libhybris" apply --check "$patch"
+ git -C "$work/libhybris" apply "$patch"
+done
+export ARLINUX_WSI_PROTOCOL_DIR="$work/rootfs/graphics-protocols"
+export CONTAINER_ENGINE=podman
+"$work/libhybris/tools/build-aarch64.sh" --out "$work/build"
+
+mkdir -p "$work/package/lib" "$work/package/licenses"
+cp -a "$work/build/install/usr/lib/hybris/." "$work/package/lib/"
+find "$work/package/lib" -name '*.la' -delete
+rm -rf "$work/package/lib/include" "$work/package/lib/pkgconfig" "$work/package/lib/bin"
+# Resolve the wrapper's private dependencies without putting its EGL/Vulkan frontends
+# on the session's LD_LIBRARY_PATH. The Linux runtime keeps owning its Mesa loader.
+while IFS= read -r -d '' library; do
+ patchelf --set-rpath '$ORIGIN:$ORIGIN/../..' "$library"
+done < <(find "$work/package/lib" -type f -name '*.so*' -print0)
+for library in libhybris-vulkan-icd.so.0 libhybris-common.so.1 libVkLayer_hybris_compat.so libhybris/linker/q.so; do
+ test -s "$work/package/lib/$library"
+done
+cp "$work/libhybris"/LICENSE.* "$work/package/licenses/"
+cp "$work/build/manifest.json" "$work/package/build-manifest.json"
+printf '%s\n' "$HYBRIS_REVISION" > "$work/package/source-commit"
+# Ship the exact patched source and protocol license with the runtime.
+git -C "$work/libhybris" diff > "$work/package/licenses/powervr.patch"
+git -C "$work/libhybris" archive HEAD | zstd -T0 -q -o "$work/package/licenses/libhybris-source.tar.zst"
+cp "$ARLINUX_WSI_PROTOCOL_DIR/wayland-android.xml" "$work/package/licenses/"
+(cd "$work/package" && find lib -type f -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS)
+tar --zstd -cf "$out/runtime.tzst" -C "$work/package" .
+sha256sum "$out/runtime.tzst" | cut -d' ' -f1 > "$out/version.txt"
+printf 'Built libhybris %s for Android HAL access from AArch64 Linux\n' "$HYBRIS_REVISION"
diff --git a/tools/hybris/patches/0001-dxvk-bc-profile.patch b/tools/hybris/patches/0001-dxvk-bc-profile.patch
new file mode 100644
index 0000000000..0076f53f87
--- /dev/null
+++ b/tools/hybris/patches/0001-dxvk-bc-profile.patch
@@ -0,0 +1,505 @@
+diff --git a/hybris/vulkan/compat/bc_commands.c b/hybris/vulkan/compat/bc_commands.c
+index 90dac59..cf62d7d 100644
+--- a/hybris/vulkan/compat/bc_commands.c
++++ b/hybris/vulkan/compat/bc_commands.c
+@@ -2,6 +2,7 @@
+ #define VK_NO_PROTOTYPES
+ #include "bc_context.h"
+ #include
++#include
+
+ #define PROC(name) PFN_vk##name name = (PFN_vk##name)device->resolver(device->handle, "vk" #name)
+ static VkResult VKAPI_CALL allocate_commands(VkDevice handle, const VkCommandBufferAllocateInfo *info,
+@@ -76,6 +77,7 @@ static VkResult VKAPI_CALL end_command(VkCommandBuffer handle)
+ PROC(EndCommandBuffer);
+ VkResult result = EndCommandBuffer(handle);
+ VkResult recorded = command->state.error;
++ if (result != VK_SUCCESS || recorded != VK_SUCCESS) fprintf(stderr, "HYBRIS_BC end: native=%d recorded=%d\n", result, recorded);
+ if (recorded == VK_SUCCESS) return result;
+ if (recorded == VK_ERROR_OUT_OF_HOST_MEMORY || recorded == VK_ERROR_OUT_OF_DEVICE_MEMORY ||
+ recorded == VK_ERROR_DEVICE_LOST) return recorded;
+@@ -198,6 +200,37 @@ static void VKAPI_CALL push_constants(VkCommandBuffer handle, VkPipelineLayout l
+ CmdPushConstants(handle, layout, stages, offset, size, values);
+ if (device->format_mask) hybris_bc_save_push(&command->state, layout, stages, offset, size, values);
+ }
++static void bind_descriptors2(VkCommandBuffer handle, const VkBindDescriptorSetsInfo *info, const char *name)
++{
++ struct hybris_bc_device *device;
++ struct hybris_bc_command *command = hybris_bc_command_find(handle, &device);
++ if (!command) return;
++ PFN_vkCmdBindDescriptorSets2 call = (void *)device->resolver(device->handle, name);
++ call(handle, info);
++ if (device->format_mask && (info->stageFlags & VK_SHADER_STAGE_COMPUTE_BIT))
++ hybris_bc_save_descriptors(&command->state, VK_PIPELINE_BIND_POINT_COMPUTE,
++ info->layout, info->firstSet, info->descriptorSetCount, info->pDescriptorSets,
++ info->dynamicOffsetCount, info->pDynamicOffsets);
++}
++static void VKAPI_CALL bind_descriptors2_core(VkCommandBuffer handle, const VkBindDescriptorSetsInfo *info)
++{ bind_descriptors2(handle, info, "vkCmdBindDescriptorSets2"); }
++static void VKAPI_CALL bind_descriptors2_khr(VkCommandBuffer handle, const VkBindDescriptorSetsInfo *info)
++{ bind_descriptors2(handle, info, "vkCmdBindDescriptorSets2KHR"); }
++static void push_constants2(VkCommandBuffer handle, const VkPushConstantsInfo *info, const char *name)
++{
++ struct hybris_bc_device *device;
++ struct hybris_bc_command *command = hybris_bc_command_find(handle, &device);
++ if (!command) return;
++ PFN_vkCmdPushConstants2 call = (void *)device->resolver(device->handle, name);
++ call(handle, info);
++ if (device->format_mask)
++ hybris_bc_save_push(&command->state, info->layout, info->stageFlags,
++ info->offset, info->size, info->pValues);
++}
++static void VKAPI_CALL push_constants2_core(VkCommandBuffer handle, const VkPushConstantsInfo *info)
++{ push_constants2(handle, info, "vkCmdPushConstants2"); }
++static void VKAPI_CALL push_constants2_khr(VkCommandBuffer handle, const VkPushConstantsInfo *info)
++{ push_constants2(handle, info, "vkCmdPushConstants2KHR"); }
+ PFN_vkVoidFunction hybris_bc_commands_proc(const char *name)
+ {
+ static const struct { const char *name; PFN_vkVoidFunction function; } commands[] = {
+@@ -207,7 +240,9 @@ PFN_vkVoidFunction hybris_bc_commands_proc(const char *name)
+ ENTRY(ResetCommandBuffer, reset_command), ENTRY(ResetCommandPool, reset_pool),
+ ENTRY(DestroyCommandPool, destroy_pool), ENTRY(CreatePipelineLayout, create_layout),
+ ENTRY(DestroyPipelineLayout, destroy_layout), ENTRY(CmdBindPipeline, bind_pipeline),
+- ENTRY(CmdBindDescriptorSets, bind_descriptors), ENTRY(CmdPushConstants, push_constants)
++ ENTRY(CmdBindDescriptorSets, bind_descriptors), ENTRY(CmdPushConstants, push_constants),
++ ENTRY(CmdBindDescriptorSets2, bind_descriptors2_core), ENTRY(CmdBindDescriptorSets2KHR, bind_descriptors2_khr),
++ ENTRY(CmdPushConstants2, push_constants2_core), ENTRY(CmdPushConstants2KHR, push_constants2_khr)
+ #undef ENTRY
+ };
+ for (size_t i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i)
+diff --git a/hybris/vulkan/compat/bc_image.c b/hybris/vulkan/compat/bc_image.c
+index fe25344..44faaf6 100644
+--- a/hybris/vulkan/compat/bc_image.c
++++ b/hybris/vulkan/compat/bc_image.c
+@@ -5,6 +5,19 @@
+
+ #define PROC(name) PFN_vk##name name = (PFN_vk##name)image->resolver(image->device, "vk" #name)
+
++int hybris_bc_srgb_family(VkFormat format)
++{
++ return (format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC3_SRGB_BLOCK) ||
++ format == VK_FORMAT_BC7_UNORM_BLOCK || format == VK_FORMAT_BC7_SRGB_BLOCK;
++}
++int hybris_bc_view_compatible(VkFormat image, VkFormat view)
++{
++ if (image == view) return 1;
++ return hybris_bc_srgb_family(image) &&
++ ((image - VK_FORMAT_BC1_RGB_UNORM_BLOCK) / 2 ==
++ (view - VK_FORMAT_BC1_RGB_UNORM_BLOCK) / 2) && hybris_bc_srgb_family(view);
++}
++
+ VkFormat hybris_bc_image_format(VkFormat format, unsigned rgb_mask)
+ {
+ switch (format) {
+@@ -71,19 +84,28 @@ VkResult hybris_bc_image_describe(const VkImageCreateInfo *info, struct hybris_b
+ info->imageType != VK_IMAGE_TYPE_2D || info->tiling != VK_IMAGE_TILING_OPTIMAL ||
+ info->samples != VK_SAMPLE_COUNT_1_BIT ||
+ (info->initialLayout != VK_IMAGE_LAYOUT_UNDEFINED && info->initialLayout != VK_IMAGE_LAYOUT_PREINITIALIZED) ||
+- (info->flags & ~VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) ||
++ (info->flags & ~(VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) ||
++ ((info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) && !hybris_bc_srgb_family(info->format)) ||
+ !info->usage ||
+ (info->usage & ~(VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) ||
+ !info->extent.width || !info->extent.height || info->extent.depth != 1 ||
+ !info->mipLevels || info->mipLevels > 32 || !info->arrayLayers)
+ return VK_ERROR_FORMAT_NOT_SUPPORTED;
++ image->flags = info->flags;
++ image->view_mask = (info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) ? 3 : 1;
+ /* These chains only constrain views or request no external/swapchain
+ * binding. The decoded image has the same view restriction in our wrapper. */
+ for (const VkBaseInStructure *next = info->pNext; next; next = next->pNext) {
+ if (next->sType == VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO) {
+ const VkImageFormatListCreateInfo *list = (const void *)next;
+- for (uint32_t i = 0; i < list->viewFormatCount; ++i)
+- if (list->pViewFormats[i] != info->format) return VK_ERROR_FORMAT_NOT_SUPPORTED;
++ if (list->viewFormatCount) image->view_mask = 0;
++ for (uint32_t i = 0; i < list->viewFormatCount; ++i) {
++ VkFormat view = list->pViewFormats[i];
++ if (!hybris_bc_view_compatible(info->format, view) ||
++ (view != info->format && !(info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)))
++ return VK_ERROR_FORMAT_NOT_SUPPORTED;
++ image->view_mask |= view == info->format ? 1u : 2u;
++ }
+ } else if (next->sType == VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO) {
+ if (((const VkExternalMemoryImageCreateInfo *)next)->handleTypes)
+ return VK_ERROR_FORMAT_NOT_SUPPORTED;
+diff --git a/hybris/vulkan/compat/bc_image.h b/hybris/vulkan/compat/bc_image.h
+index 9e62eb3..c950cc2 100644
+--- a/hybris/vulkan/compat/bc_image.h
++++ b/hybris/vulkan/compat/bc_image.h
+@@ -12,10 +12,14 @@ struct hybris_bc_image {
+ VkMemoryRequirements requirements;
+ VkBool32 requires_dedicated, prefers_dedicated;
+ VkFormat format, decoded_format;
++ VkImageCreateFlags flags;
++ unsigned view_mask;
+ VkExtent3D extent;
+ uint32_t mip_levels, layers, block_bytes;
+ VkDeviceSize mip_offset[32], block_size;
+ };
++int hybris_bc_srgb_family(VkFormat format);
++int hybris_bc_view_compatible(VkFormat image, VkFormat view);
+ VkFormat hybris_bc_image_format(VkFormat format, unsigned rgb_mask);
+ VkResult hybris_bc_image_describe(const VkImageCreateInfo *info, struct hybris_bc_image *image);
+ void hybris_bc_image_backing_info(const struct hybris_bc_image *image,
+diff --git a/hybris/vulkan/compat/bc_policy.c b/hybris/vulkan/compat/bc_policy.c
+index c5856f6..3124a25 100644
+--- a/hybris/vulkan/compat/bc_policy.c
++++ b/hybris/vulkan/compat/bc_policy.c
+@@ -5,6 +5,7 @@
+ #include "bc_context.h"
+ #include "../layer/layer.h"
+ #include
++#include
+ #include
+ #include
+
+@@ -16,12 +17,18 @@ static void initialize_policy(void)
+ const char *value = getenv("HYBRIS_BC_TEXTURES");
+ if (!value || !strcmp(value, "missing") || !strcmp(value, "1")) policy = 1;
+ else if (value && !strcmp(value, "force")) policy = 2;
++ else if (value && !strcmp(value, "dxvk")) policy = 3;
+ }
+ int hybris_bc_enabled(void)
+ {
+ pthread_once(&policy_once, initialize_policy);
+ return policy != 0;
+ }
++static int dxvk_profile(void)
++{
++ pthread_once(&policy_once, initialize_policy);
++ return policy == 3;
++}
+ #define PHYSICAL_PROC(name) PFN_vk##name name = (PFN_vk##name)context.resolver(context.instance, "vk" #name)
+ /* Preserve three-channel border replacement when the native image format
+ * supports the full sampled/transfer domain. Selection is per physical device;
+@@ -52,7 +59,7 @@ unsigned hybris_bc_physical_mask(VkPhysicalDevice physical)
+ VkPhysicalDeviceProperties properties;
+ GetPhysicalDeviceProperties(physical, &properties);
+ /* Core 1.4 includes descriptor-state commands that are not intercepted yet. */
+- if (properties.apiVersion < VK_API_VERSION_1_1 || properties.apiVersion >= VK_MAKE_API_VERSION(0, 1, 4, 0) ||
++ if (properties.apiVersion < VK_API_VERSION_1_1 || (!dxvk_profile() && properties.apiVersion >= VK_MAKE_API_VERSION(0, 1, 4, 0)) ||
+ properties.limits.maxStorageBufferRange < 256 ||
+ properties.limits.minStorageBufferOffsetAlignment >= properties.limits.maxStorageBufferRange) return 0;
+ uint32_t count = 0;
+@@ -72,6 +79,9 @@ unsigned hybris_bc_physical_mask(VkPhysicalDevice physical)
+ unsigned mask = 0;
+ for (unsigned i = 0; i < 16; ++i) {
+ VkFormat format = VK_FORMAT_BC1_RGB_UNORM_BLOCK + i;
++ /* D3D uses BC1 RGBA. Keep RGB-only BC1 unadvertised until absent-alpha
++ * border semantics are implemented on devices without RGB8 images. */
++ if (dxvk_profile() && i < 2) continue;
+ VkFormat backing = hybris_bc_image_format(format, physical_rgb_mask(physical));
+ if (backing == VK_FORMAT_UNDEFINED) continue;
+ VkFormatProperties native, decoded;
+@@ -84,6 +94,33 @@ unsigned hybris_bc_physical_mask(VkPhysicalDevice physical)
+ }
+ return mask;
+ }
++/* The emulation profile implements Vulkan 1.3 plus maintenance6. Do not expose
++ * 1.4 core host-copy/push-descriptor operations that bypass our state tracking. */
++static void cap_properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *out)
++{
++ if (dxvk_profile() && hybris_bc_physical_mask(physical) && out->apiVersion > VK_API_VERSION_1_3)
++ out->apiVersion = VK_API_VERSION_1_3;
++}
++static void VKAPI_CALL properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *out)
++{
++ struct hybris_layer_physical context;
++ if (!hybris_layer_lookup_physical(physical, &context)) return;
++ PHYSICAL_PROC(GetPhysicalDeviceProperties);
++ GetPhysicalDeviceProperties(physical, out);
++ cap_properties(physical, out);
++}
++static void properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *out, const char *name)
++{
++ struct hybris_layer_physical context;
++ if (!hybris_layer_lookup_physical(physical, &context)) return;
++ PFN_vkGetPhysicalDeviceProperties2 query = (void *)context.resolver(context.instance, name);
++ query(physical, out);
++ cap_properties(physical, &out->properties);
++}
++static void VKAPI_CALL properties2_core(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *out)
++{ properties2(physical, out, "vkGetPhysicalDeviceProperties2"); }
++static void VKAPI_CALL properties2_khr(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *out)
++{ properties2(physical, out, "vkGetPhysicalDeviceProperties2KHR"); }
+ static int emulates(VkPhysicalDevice physical, VkFormat format)
+ {
+ return format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC7_SRGB_BLOCK &&
+@@ -109,10 +146,13 @@ int hybris_bc_extension_allowed(const char *name)
+ "VK_KHR_maintenance6", "VK_KHR_maintenance8", "VK_EXT_host_image_copy",
+ "VK_QCOM_rotated_copy_commands", "VK_EXT_device_generated_commands",
+ "VK_NV_device_generated_commands", "VK_NV_device_generated_commands_compute",
+- "VK_NV_dedicated_allocation", "VK_NV_copy_memory_indirect"
++ "VK_NV_dedicated_allocation", "VK_NV_copy_memory_indirect", "VK_NV_per_stage_descriptor_set"
+ };
+ for (size_t i = 0; i < sizeof(unsupported) / sizeof(unsupported[0]); ++i)
+- if (!strcmp(name, unsupported[i])) return 0;
++ if (!strcmp(name, unsupported[i])) {
++ if (dxvk_profile() && !strcmp(name, "VK_KHR_maintenance6")) continue;
++ return 0;
++ }
+ return 1;
+ }
+ /* Extension feature queries must agree with the filtered extension list. Each
+@@ -121,8 +161,12 @@ static unsigned unsupported_feature_count(VkStructureType type)
+ {
+ switch (type) {
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT: return 4;
++ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_4_FEATURES:
++ return dxvk_profile() ? (offsetof(VkPhysicalDeviceVulkan14Features, pushDescriptor) -
++ offsetof(VkPhysicalDeviceVulkan14Features, globalPriorityQuery)) / sizeof(VkBool32) + 1 : 0;
++ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR: return dxvk_profile() ? 0 : 1;
++ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PER_STAGE_DESCRIPTOR_SET_FEATURES_NV: return 2;
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OBJECT_FEATURES_EXT:
+- case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR:
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT:
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COPY_MEMORY_INDIRECT_FEATURES_NV:
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_GENERATED_COMMANDS_FEATURES_NV: return 1;
+@@ -252,11 +296,12 @@ static void VKAPI_CALL sparse_properties2_core(VkPhysicalDevice physical, const
+ static void VKAPI_CALL sparse_properties2_khr(VkPhysicalDevice physical, const VkPhysicalDeviceSparseImageFormatInfo2 *info,
+ uint32_t *count, VkSparseImageFormatProperties2 *out)
+ { sparse_properties2(physical, info, count, out, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR"); }
+-static int image_supported(VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags)
++static int image_supported(VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags)
+ {
+ return type == VK_IMAGE_TYPE_2D && tiling == VK_IMAGE_TILING_OPTIMAL && usage &&
+ !(usage & ~(VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) &&
+- !(flags & ~VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT);
++ !(flags & ~(VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) &&
++ (!(flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) || hybris_bc_srgb_family(format));
+ }
+ static VkResult VKAPI_CALL image_properties(VkPhysicalDevice physical, VkFormat format, VkImageType type,
+ VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties *out)
+@@ -265,7 +310,7 @@ static VkResult VKAPI_CALL image_properties(VkPhysicalDevice physical, VkFormat
+ if (!hybris_layer_lookup_physical(physical, &context)) return VK_ERROR_INITIALIZATION_FAILED;
+ PHYSICAL_PROC(GetPhysicalDeviceImageFormatProperties);
+ if (emulates(physical, format)) {
+- if (!image_supported(type, tiling, usage, flags)) { *out = (VkImageFormatProperties){0}; return VK_ERROR_FORMAT_NOT_SUPPORTED; }
++ if (!image_supported(format, type, tiling, usage, flags)) { *out = (VkImageFormatProperties){0}; return VK_ERROR_FORMAT_NOT_SUPPORTED; }
+ VkResult result = GetPhysicalDeviceImageFormatProperties(physical, hybris_bc_image_format(format, physical_rgb_mask(physical)), type,
+ tiling, usage | VK_IMAGE_USAGE_TRANSFER_DST_BIT, flags, out);
+ if (result == VK_SUCCESS) out->sampleCounts &= VK_SAMPLE_COUNT_1_BIT;
+@@ -282,14 +327,16 @@ static VkResult image_properties2(VkPhysicalDevice physical, const VkPhysicalDev
+ (PFN_vkGetPhysicalDeviceImageFormatProperties2)context.resolver(context.instance, name);
+ if (!emulates(physical, info->format)) return query(physical, info, out);
+ out->imageFormatProperties = (VkImageFormatProperties){0};
+- if (!image_supported(info->type, info->tiling, info->usage, info->flags)) return VK_ERROR_FORMAT_NOT_SUPPORTED;
++ if (!image_supported(info->format, info->type, info->tiling, info->usage, info->flags)) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ for (const VkBaseInStructure *node = info->pNext; node; node = node->pNext) {
+ if (node->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO) {
+ if (((const VkPhysicalDeviceExternalImageFormatInfo *)node)->handleType) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ } else if (node->sType == VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO) {
+ const VkImageFormatListCreateInfo *list = (const void *)node;
+ for (uint32_t i = 0; i < list->viewFormatCount; ++i)
+- if (list->pViewFormats[i] != info->format) return VK_ERROR_FORMAT_NOT_SUPPORTED;
++ if (!hybris_bc_view_compatible(info->format, list->pViewFormats[i]) ||
++ (list->pViewFormats[i] != info->format && !(info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)))
++ return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ } else if (node->sType != VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_IMAGE_FORMAT_INFO_EXT) {
+ return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ }
+@@ -322,6 +369,9 @@ PFN_vkVoidFunction hybris_bc_policy_proc(const char *name)
+ if (!hybris_bc_enabled()) return NULL;
+ static const struct { const char *name; PFN_vkVoidFunction function; } commands[] = {
+ #define ENTRY(name, function) {"vk" #name, (PFN_vkVoidFunction)function}
++ ENTRY(GetPhysicalDeviceProperties, properties),
++ ENTRY(GetPhysicalDeviceProperties2, properties2_core),
++ ENTRY(GetPhysicalDeviceProperties2KHR, properties2_khr),
+ ENTRY(GetPhysicalDeviceQueueFamilyProperties, queue_properties),
+ ENTRY(GetPhysicalDeviceQueueFamilyProperties2, queue_properties2_core),
+ ENTRY(GetPhysicalDeviceQueueFamilyProperties2KHR, queue_properties2_khr),
+diff --git a/hybris/vulkan/compat/bc_resources.c b/hybris/vulkan/compat/bc_resources.c
+index 526c3f1..74cc0c9 100644
+--- a/hybris/vulkan/compat/bc_resources.c
++++ b/hybris/vulkan/compat/bc_resources.c
+@@ -210,8 +210,10 @@ static VkResult VKAPI_CALL create_view(VkDevice handle, const VkImageViewCreateI
+ struct hybris_bc_resource *resource = hybris_bc_resource_find(device, info->image);
+ VkImageViewCreateInfo translated = *info;
+ if (resource && resource->emulated.image) {
+- if (info->format != resource->format) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+- translated.format = resource->emulated.decoded_format;
++ unsigned bit = info->format == resource->format ? 1u : 2u;
++ if (!hybris_bc_view_compatible(resource->format, info->format) ||
++ !(resource->emulated.view_mask & bit)) return VK_ERROR_FORMAT_NOT_SUPPORTED;
++ translated.format = hybris_bc_image_format(info->format, device->rgb_mask);
+ }
+ PROC(CreateImageView);
+ return CreateImageView(handle, &translated, allocator, view);
+diff --git a/hybris/vulkan/compat/bc_transfer.c b/hybris/vulkan/compat/bc_transfer.c
+index 6edb652..799fb62 100644
+--- a/hybris/vulkan/compat/bc_transfer.c
++++ b/hybris/vulkan/compat/bc_transfer.c
+@@ -2,6 +2,7 @@
+ #define VK_NO_PROTOTYPES
+ #include "bc_transfer.h"
+ #include
++#include
+ #include
+
+ #define PROC(name) PFN_vk##name name = (PFN_vk##name)t->decoder->resolver(t->decoder->device, "vk" #name)
+@@ -59,16 +60,29 @@ static VkResult scratch(struct hybris_bc_transfer *t)
+ if (type == t->memory->memoryTypeCount) type = i;
+ if (t->memory->memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { type = i; break; }
+ }
+- if (type == t->memory->memoryTypeCount) { result = VK_ERROR_OUT_OF_DEVICE_MEMORY; goto fail; }
++ if (type == t->memory->memoryTypeCount) {
++ fprintf(stderr, "HYBRIS_BC scratch: no memory type (bits=0x%x count=%u size=%llu)\n",
++ requirements.memoryRequirements.memoryTypeBits, t->memory->memoryTypeCount,
++ (unsigned long long)requirements.memoryRequirements.size);
++ result = VK_ERROR_OUT_OF_DEVICE_MEMORY; goto fail;
++ }
+ VkMemoryDedicatedAllocateInfo owner = {
+ .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, .buffer = buffer};
+ VkMemoryAllocateInfo allocation = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
+ .pNext = dedicated.requiresDedicatedAllocation || dedicated.prefersDedicatedAllocation ? &owner : NULL,
+ .allocationSize = requirements.memoryRequirements.size, .memoryTypeIndex = type};
+ result = AllocateMemory(device, &allocation, NULL, &memory);
+- if (result != VK_SUCCESS) goto fail;
++ if (result != VK_SUCCESS) {
++ fprintf(stderr, "HYBRIS_BC scratch allocation: result=%d size=%llu type=%u bits=0x%x\n",
++ result, (unsigned long long)allocation.allocationSize, type, requirements.memoryRequirements.memoryTypeBits);
++ goto fail;
++ }
+ result = BindBufferMemory(device, buffer, memory, 0);
+- if (result != VK_SUCCESS) goto fail;
++ if (result != VK_SUCCESS) {
++ fprintf(stderr, "HYBRIS_BC scratch bind: result=%d size=%llu type=%u\n",
++ result, (unsigned long long)allocation.allocationSize, type);
++ goto fail;
++ }
+ t->scratch = buffer;
+ t->scratch_memory = memory;
+ t->scratch_size = size;
+@@ -193,7 +207,7 @@ VkResult hybris_bc_decode_image(struct hybris_bc_transfer *t,
+ buffer_barrier(t, command, image->blocks, VK_PIPELINE_STAGE_TRANSFER_BIT,
+ VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
+ VkResult result = decode(t, command, image, layout, region);
+- if (result != VK_SUCCESS) { state->error = result; return result; }
++ if (result != VK_SUCCESS) { fprintf(stderr, "HYBRIS_BC transfer failed: %d\n", result); state->error = result; return result; }
+ buffer_barrier(t, command, image->blocks, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
+ VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
+ VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
+diff --git a/hybris/vulkan/compat/shader_policy.c b/hybris/vulkan/compat/shader_policy.c
+index a1dcf6d..21a4cc7 100644
+--- a/hybris/vulkan/compat/shader_policy.c
++++ b/hybris/vulkan/compat/shader_policy.c
+@@ -92,7 +92,8 @@ static void properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *
+ {
+ struct hybris_layer_physical context;
+ if (!hybris_layer_lookup_physical(physical, &context)) return;
+- PFN_vkGetPhysicalDeviceProperties2 query = (PFN_vkGetPhysicalDeviceProperties2)context.resolver(context.instance, name);
++ PFN_vkGetPhysicalDeviceProperties2 query = (void *)hybris_bc_policy_proc(name);
++ if (!query) query = (void *)context.resolver(context.instance, name);
+ query(physical, out);
+ VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *legacy = NULL;
+ for (VkBaseOutStructure *node = out->pNext; node; node = node->pNext)
+diff --git a/tests/baseline/probe_bc_images.c b/tests/baseline/probe_bc_images.c
+index 85ba6e6..55e069c 100644
+--- a/tests/baseline/probe_bc_images.c
++++ b/tests/baseline/probe_bc_images.c
+@@ -95,9 +95,10 @@ int bc_images_probe(int validate, int route)
+ }
+ free(queues);
+ if (family == UINT32_MAX) return 3;
++ unsigned first_format = getenv("BC_D3D_FORMATS") ? 2 : 0;
+ VkBool32 linear_filter[BC_IMAGE_FORMAT_COUNT] = {0};
+ unsigned unsupported_formats = 0;
+- for (unsigned f = 0; f < BC_IMAGE_FORMAT_COUNT; ++f) {
++ for (unsigned f = first_format; f < BC_IMAGE_FORMAT_COUNT; ++f) {
+ VkFormatProperties format;
+ p_vkGetPhysicalDeviceFormatProperties(physical, bc_formats[f], &format);
+ VkFormatProperties2 format2 = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2};
+@@ -164,19 +165,28 @@ int bc_images_probe(int validate, int route)
+ p_vkGetPhysicalDeviceFeatures2(physical, &queried);
+ maintenance4 = maintenance.maintenance4;
+ }
+- synchronization.pNext = maintenance4 ? &maintenance : NULL;
+- const char *device_extensions[4];
++ int maintenance6 = getenv("BC_MAINTENANCE6") != NULL;
++ VkPhysicalDeviceMaintenance6FeaturesKHR maintenance_six = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR};
++ if (maintenance6) {
++ VkPhysicalDeviceFeatures2 q = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &maintenance_six};
++ p_vkGetPhysicalDeviceFeatures2(physical, &q);
++ if (!maintenance_six.maintenance6) { puts("MISSING maintenance6"); return 3; }
++ }
++ maintenance.pNext = maintenance6 ? &maintenance_six : NULL;
++ synchronization.pNext = maintenance4 ? (void *)&maintenance : maintenance6 ? (void *)&maintenance_six : NULL;
++ const char *device_extensions[5];
+ uint32_t device_extension_count = 0;
+ if (copies2) device_extensions[device_extension_count++] = VK_KHR_COPY_COMMANDS_2_EXTENSION_NAME;
+ if (sync2) device_extensions[device_extension_count++] = VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME;
+ if (maintenance4) device_extensions[device_extension_count++] = VK_KHR_MAINTENANCE_4_EXTENSION_NAME;
+ if (format_list) device_extensions[device_extension_count++] = VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME;
++ if (maintenance6) device_extensions[device_extension_count++] = VK_KHR_MAINTENANCE_6_EXTENSION_NAME;
+ float priority = 1;
+ VkDeviceQueueCreateInfo qc = {.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
+ .queueFamilyIndex = family, .queueCount = 1, .pQueuePriorities = &priority};
+ VkDeviceCreateInfo dc = {.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
+ .queueCreateInfoCount = 1, .pQueueCreateInfos = &qc,
+- .pNext = sync2 ? (void *)&synchronization : maintenance4 ? (void *)&maintenance : NULL,
++ .pNext = sync2 ? (void *)&synchronization : maintenance4 ? (void *)&maintenance : maintenance6 ? (void *)&maintenance_six : NULL,
+ .enabledExtensionCount = device_extension_count, .ppEnabledExtensionNames = device_extensions};
+ VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE;
+ PFN_vkDestroyDebugUtilsMessengerEXT destroy_messenger = NULL;
+@@ -307,8 +317,12 @@ int bc_images_probe(int validate, int route)
+ VkFenceCreateInfo fence_info = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
+ VkFence fence;
+ CHECK(p_vkCreateFence(device, &fence_info, NULL, &fence));
++ PFN_vkCmdBindDescriptorSets2KHR bind2 = (PFN_vkCmdBindDescriptorSets2KHR)p_vkGetDeviceProcAddr(device, "vkCmdBindDescriptorSets2KHR");
++ PFN_vkCmdPushConstants2KHR push2 = (PFN_vkCmdPushConstants2KHR)p_vkGetDeviceProcAddr(device, "vkCmdPushConstants2KHR");
++ if (maintenance6 && (!bind2 || !push2)) return 2;
++ printf("BC_EXTENDED maintenance6=%d mutable=%d\n", maintenance6, getenv("BC_MUTABLE") != NULL);
+ unsigned failures = 0, readbacks = 0, copies2_cases = 0, sync2_cases = 0;
+- for (unsigned f = 0; f < BC_IMAGE_FORMAT_COUNT; ++f) {
++ for (unsigned f = first_format; f < BC_IMAGE_FORMAT_COUNT; ++f) {
+ for (unsigned shape_index = 0; shape_index < 2; ++shape_index) {
+ uint32_t base_width = shape_index ? 32 : 9, base_height = shape_index ? 32 : 7;
+ for (uint32_t mip = 0; mip < 4; ++mip) {
+@@ -337,6 +351,13 @@ int bc_images_probe(int validate, int route)
+ (i != 2 ? VK_IMAGE_USAGE_SAMPLED_BIT : 0), .sharingMode = VK_SHARING_MODE_EXCLUSIVE};
+ VkImageFormatListCreateInfo formats = {.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO,
+ .viewFormatCount = 1, .pViewFormats = &image_info.format};
++ VkFormat paired[2] = {bc_formats[f], bc_formats[f ^ 1]};
++ if (getenv("BC_MUTABLE") && (f < 8 || (f >= 12 && f < 14)) && i < 2) {
++ image_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
++ image_info.format = paired[1];
++ formats.viewFormatCount = 2;
++ formats.pViewFormats = paired;
++ }
+ if (format_list) image_info.pNext = &formats;
+ VkMemoryRequirements2 described = {.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2};
+ if (maintenance4) {
+@@ -414,9 +435,19 @@ int bc_images_probe(int validate, int route)
+ VkCommandBufferBeginInfo begin = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
+ CHECK(p_vkBeginCommandBuffer(command, &begin));
+ p_vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
+- p_vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &descriptors, 1, &dynamic_offset);
++ if (maintenance6) {
++ VkBindDescriptorSetsInfoKHR bind = {.sType = VK_STRUCTURE_TYPE_BIND_DESCRIPTOR_SETS_INFO_KHR,
++ .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, .layout = pipeline_layout,
++ .descriptorSetCount = 1, .pDescriptorSets = &descriptors,
++ .dynamicOffsetCount = 1, .pDynamicOffsets = &dynamic_offset};
++ bind2(command, &bind);
++ } else p_vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &descriptors, 1, &dynamic_offset);
+ uint32_t shape[] = {width, height, LAYERS, f >= 14 ? 3 : f >= 8 && f < 12 ? 1 + (f & 1) : 0, linear_filter[f] != 0};
+- p_vkCmdPushConstants(command, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(shape), shape);
++ if (maintenance6) {
++ VkPushConstantsInfoKHR push = {.sType = VK_STRUCTURE_TYPE_PUSH_CONSTANTS_INFO_KHR,
++ .layout = pipeline_layout, .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, .size = sizeof(shape), .pValues = shape};
++ push2(command, &push);
++ } else p_vkCmdPushConstants(command, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(shape), shape);
+ VkMemoryBarrier before = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
+ .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
+ .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT};
+@@ -614,7 +645,7 @@ int bc_images_probe(int validate, int route)
+ p_vkDestroyDevice(device, NULL);
+ if (destroy_messenger) destroy_messenger(instance, messenger, NULL);
+ p_vkDestroyInstance(instance, NULL); dlclose(h);
+- printf("BC_IMAGES_SUMMARY formats=16 shapes=2 readbacks=%u copy2_cases=%u sync2_cases=%u maintenance4=%u format_list=%u failures=%u validation_errors=%u route=%d\n",
+- readbacks, copies2_cases, sync2_cases, maintenance4, format_list, failures, validation.errors, route);
+- return failures || validation.errors || readbacks != BC_IMAGE_FORMAT_COUNT * 2 * 4 * 3 ? 2 : 0;
++ printf("BC_IMAGES_SUMMARY formats=%u shapes=2 readbacks=%u copy2_cases=%u sync2_cases=%u maintenance4=%u format_list=%u failures=%u validation_errors=%u route=%d\n",
++ (unsigned)BC_IMAGE_FORMAT_COUNT - first_format, readbacks, copies2_cases, sync2_cases, maintenance4, format_list, failures, validation.errors, route);
++ return failures || validation.errors || readbacks != (BC_IMAGE_FORMAT_COUNT - first_format) * 2 * 4 * 3 ? 2 : 0;
+ }
diff --git a/tools/hybris/powervr-hal-version.patch b/tools/hybris/powervr-hal-version.patch
new file mode 100644
index 0000000000..63b72c7599
--- /dev/null
+++ b/tools/hybris/powervr-hal-version.patch
@@ -0,0 +1,12 @@
+--- a/hybris/vulkan/icd/icd.c
++++ b/hybris/vulkan/icd/icd.c
+@@ -71,7 +71,8 @@
+ int result = module->methods->open(module, HWVULKAN_DEVICE_0,
+ (hw_device_t **)&candidate);
+ if (result || !candidate || candidate->common.tag != HARDWARE_DEVICE_TAG ||
+- candidate->common.version != HWVULKAN_DEVICE_API_VERSION_0_1 ||
++ (candidate->common.version != HWVULKAN_DEVICE_API_VERSION_0_1 &&
++ candidate->common.version != HARDWARE_DEVICE_API_VERSION(0, 1)) ||
+ !candidate->CreateInstance || !candidate->GetInstanceProcAddr ||
+ !candidate->EnumerateInstanceExtensionProperties) {
+ fprintf(stderr, "hybris ICD: incompatible Vulkan HAL device (open=%d)\n", result);
diff --git a/tools/hybris/run-proton.py b/tools/hybris/run-proton.py
new file mode 100644
index 0000000000..c8c1b0eb46
--- /dev/null
+++ b/tools/hybris/run-proton.py
@@ -0,0 +1,89 @@
+#!/usr/bin/python3
+"""Select a staged DXVK payload for one DroidDeck Proton game launch.
+
+Place this script beside dxvk/x32/ and dxvk/x64/, then select its absolute
+path with DROIDDECK_PROTON_WRAPPER in the game's environment settings.
+Run `python3 run-proton.py --check /path/to/proton` to check the payload and
+Proton source layout without starting Proton or changing a game prefix.
+
+This wrapper does not install the graphics runtime, select Vulkan layers,
+change synchronization settings, or provide game-specific workarounds.
+"""
+
+import argparse
+import os
+from pathlib import Path
+import sys
+
+
+DLL_NAMES = ("d3d8.dll", "d3d9.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll")
+PREFIX_MARKER = "droiddeck-dxvk-profile-v1"
+
+
+def prepare(proton, dxvk):
+ """Validate all inputs and compile an in-memory copy of the Proton script."""
+ for architecture in ("x32", "x64"):
+ for name in DLL_NAMES:
+ dll = dxvk / architecture / name
+ if not dll.is_file():
+ raise ValueError(f"missing DXVK file: {dll}")
+ with dll.open("rb") as stream:
+ if not stream.read(1):
+ raise ValueError(f"empty DXVK file: {dll}")
+
+ source = proton.read_text(encoding="utf-8")
+ for is32, architecture in (("False", "x64"), ("True", "x32")):
+ needle = f'g_proton.arch_pe_dir("wine/dxvk", {is32}) + f + ".dll"'
+ if source.count(needle) != 1:
+ raise ValueError(f"unsupported Proton layout: expected one {architecture} DXVK copy expression")
+ directory = str(dxvk / architecture) + "/"
+ source = source.replace(needle, repr(directory) + ' + f + ".dll"', 1)
+
+ needle = " # check whether any prefix config has changed"
+ if source.count(needle) != 1:
+ raise ValueError("unsupported Proton layout: expected one prefix configuration marker")
+ # The supported Proton copies DXVK DLLs on every launch. This marker records
+ # profile activation; it does not need changing whenever the payload changes.
+ marker = repr("\n" + PREFIX_MARKER)
+ source = source.replace(needle, f" prefix_info += {marker}\n" + needle, 1)
+ return compile(source, str(proton), "exec")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--check", action="store_true", help="validate inputs without running Proton")
+ parser.add_argument("proton", help="selected Proton Python script")
+ parser.add_argument("proton_args", nargs=argparse.REMAINDER)
+ args = parser.parse_args()
+ if not args.check and (len(args.proton_args) < 2 or args.proton_args[0] != "waitforexitandrun"):
+ parser.error("expected: PROTON waitforexitandrun GAME [ARGUMENTS...]")
+
+ proton = Path(args.proton)
+ # A sibling payload directory by name (dxvk-2.6.2 for Xclipse); never a path.
+ name = os.environ.get("DROIDDECK_HYBRIS_DXVK") or "dxvk"
+ if not name.startswith("dxvk") or "/" in name or name.startswith("."):
+ print(f"DroidDeck DXVK profile: invalid payload name {name!r}", file=sys.stderr)
+ return 1
+ dxvk = Path(__file__).resolve().parent / name
+ try:
+ code = prepare(proton, dxvk)
+ except (OSError, ValueError, SyntaxError) as error:
+ print(f"DroidDeck DXVK profile: {error}", file=sys.stderr)
+ return 1
+
+ if args.check:
+ print(f"DroidDeck DXVK profile: payload present and Proton layout supported ({dxvk})")
+ return 0
+
+ print(f"DROIDDECK_GRAPHICS profile={PREFIX_MARKER} dxvk={dxvk}", flush=True)
+ # Preserve the selected Proton path, including symlinks, and its arguments.
+ # Proton uses argv[0] and sibling Python imports to locate its own depot.
+ sys.argv = [args.proton, *args.proton_args]
+ sys.path.insert(0, str(proton.absolute().parent))
+ exec(code, {"__name__": "__main__", "__file__": args.proton,
+ "__package__": None, "__spec__": None})
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/hybris/source.env b/tools/hybris/source.env
new file mode 100644
index 0000000000..30dd70e1cf
--- /dev/null
+++ b/tools/hybris/source.env
@@ -0,0 +1,2 @@
+HYBRIS_REVISION=bc8cb3586b79d208fd21b925fa0209b3e432e008
+PROTOCOL_REVISION=c6ae3c22a804da3cda017f4c8eaa6c6a3da55457
diff --git a/tools/linuxfs/check-preloads.sh b/tools/linuxfs/check-preloads.sh
index 6e9e1dcff6..f1ae1df911 100644
--- a/tools/linuxfs/check-preloads.sh
+++ b/tools/linuxfs/check-preloads.sh
@@ -31,5 +31,10 @@ SSBS=$(syms "$D/libssbs.so")
for sym in sigaction signal bsd_signal sysv_signal; do
grep -qx "$sym" <<<"$SSBS" || { echo "::error::libssbs.so does not export $sym"; exit 1; }
done
+XCLIPSE=$(syms "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so")
+for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDeviceProcAddr; do
+ grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
+done
+test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
test -f "$D/usr/local/bin/droiddeck-session"
test -f "$D/usr/local/bin/droiddeck-proton-extra"
diff --git a/tools/linuxfs/desktop/droiddeck-gpu b/tools/linuxfs/desktop/droiddeck-gpu
index e68f551782..d220073f05 100644
--- a/tools/linuxfs/desktop/droiddeck-gpu
+++ b/tools/linuxfs/desktop/droiddeck-gpu
@@ -12,7 +12,12 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
fi
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
-args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
+backend=${BL_GAMESCOPE_BACKEND:-wayland}
+case "$backend" in
+ wayland|sdl) ;;
+ *) echo "== unsupported gamescope backend: $backend" >&2; exit 64 ;;
+esac
+args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
@@ -24,6 +29,9 @@ echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on
# through gamescope's own Xwayland, as in a Steam session.
export WAYLAND_DISPLAY=wayland-0
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
+# PowerVR's SDL backend presents to the app's Wayland compositor. Only the
+# program inside gamescope uses its Xwayland display.
+[ "$backend" = sdl ] && export SDL_VIDEODRIVER=wayland
# GL on the GPU again (zink on Turnip, as the session sets it): the desktop itself draws GL in software.
# Qt Quick back on its GPU renderer and KWin's software compositing not passed on, too.
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
@@ -31,7 +39,7 @@ export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=tr
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
# AppImages cannot mount under proot; the menu entries already say so, a hand-typed one may not.
export APPIMAGE_EXTRACT_AND_RUN=1
-gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
+gamescope "${args[@]}" -- env SDL_VIDEODRIVER=x11 /usr/local/bin/droiddeck-gpu-window "$@"
rc=$?
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
exit $rc
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
index 454fb7e743..9db66a1f83 100755
--- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
@@ -305,6 +305,60 @@ def mark_install_scripts(command, env):
print("droiddeck-game-env: install scripts not marked (%s)" % error, file=sys.stderr)
+class SystemGraphicsError(ValueError):
+ pass
+
+
+def system_graphics_launch(command, env):
+ """Use the APK's PowerVR compatibility files only for actual Proton game launches."""
+ runtime = env.get("DROIDDECK_POWERVR_RUNTIME")
+ if not runtime or not game_id(env) or len(command) < 3 or command[1] != "waitforexitandrun":
+ return command, env
+ directory = Path(runtime)
+ if not directory.is_absolute():
+ raise SystemGraphicsError("system Vulkan runtime path is not absolute")
+ # run-proton.py picks the same payload by name; Xclipse needs a DXVK within 128 bytes of push data.
+ payload = env.get("DROIDDECK_HYBRIS_DXVK") or "dxvk"
+ if not payload.startswith("dxvk") or "/" in payload:
+ raise SystemGraphicsError("invalid DXVK payload name: %s" % payload)
+ required = (
+ "run-proton.py", "wsi/libVkLayer_window_system_integration.so",
+ "wsi/VkLayer_window_system_integration.json", "lib/libVkLayer_hybris_compat.so",
+ *("%s/%s/%s.dll" % (payload, arch, name) for arch in ("x32", "x64")
+ for name in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi")),
+ )
+ try:
+ for name in required:
+ path = directory / name
+ if not path.is_file() or not path.stat().st_size:
+ raise SystemGraphicsError("missing system Vulkan component: %s" % name)
+ wrapper = directory / "run-proton.py"
+ if not os.access(wrapper, os.X_OK):
+ raise SystemGraphicsError("system Vulkan Proton wrapper is not executable")
+ except OSError as error:
+ raise SystemGraphicsError("system Vulkan component is unreadable: %s" % error) from error
+ result = dict(env)
+ layers = "VK_LAYER_window_system_integration:" + env.get("DROIDDECK_HYBRIS_LAYERS", "VK_LAYER_HYBRIS_compat")
+ result.update({
+ "HYBRIS_BC_TEXTURES": "dxvk",
+ "VK_LAYER_PATH": ":".join(filter(None, (str(directory / "wsi"), str(directory / "lib"),
+ env.get("DROIDDECK_HYBRIS_LAYER_PATH")))),
+ "VK_INSTANCE_LAYERS": layers,
+ "ENABLE_GAMESCOPE_WSI": "0",
+ "VK_LOADER_LAYERS_DISABLE": "*gamescope*",
+ "DISABLE_VK_LAYER_VALVE_steam_fossilize_1": "1",
+ })
+ for name in ("DISABLE_WSI_LAYER", "PROTON_USE_WINED3D", "ENABLE_VK_LAYER_VALVE_steam_fossilize_1"):
+ result.pop(name, None)
+ return [str(wrapper), *command], result
+
+
+def exec_proton(command, env):
+ # Synchronization selection has already picked the actual Proton executable.
+ command, env = system_graphics_launch(command, env)
+ os.execvpe(command[0], command, env)
+
+
def main():
command = sys.argv[1:]
if not command:
@@ -344,13 +398,17 @@ def main():
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
- os.execvpe(launch[0], launch, launch_env)
+ exec_proton(launch, launch_env)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
- os.execvpe(launch[0], launch, launch_env)
+ exec_proton(launch, launch_env)
if __name__ == "__main__":
- sys.exit(main())
+ try:
+ sys.exit(main())
+ except SystemGraphicsError as error:
+ print("droiddeck-game-env: PowerVR graphics runtime unavailable (%s)" % error, file=sys.stderr)
+ sys.exit(1)
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
index 5ffc2a3881..602f60b11c 100755
--- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
@@ -273,7 +273,13 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
fi
fi
- args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
+ backend=${BL_GAMESCOPE_BACKEND:-wayland}
+ case "$backend" in
+ wayland) ;;
+ sdl) export SDL_VIDEODRIVER=wayland ;;
+ *) echo "== unsupported gamescope backend: $backend"; exit 64 ;;
+ esac
+ args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
# -r is what gamescope advertises as the refresh rate, and what a game reads as the display's.
# Left unset it defaults to 60, so a 120 Hz panel offers only 60 Hz in game settings. The FPS
@@ -823,6 +829,21 @@ BUSCONF
export STEAM_RUNTIME=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
+ bl_steam_path=$PATH
+ bl_steam_angle=vulkan
+ bl_steam_presentation=()
+ if [ "${BL_STEAM_GL_PRESENT:-}" = 1 ]; then
+ bl_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
+ # Keep the system driver for GPU rendering, but present Steam through ordinary DRI3.
+ # The inner compositor has neither android_wlegl nor the bridge's TAWC-DRI extension.
+ export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true
+ bl_steam_angle=gl
+ # CEF renders correctly internally, but its accelerated shared-texture output is
+ # corrupted on this path. Software web compositing avoids that handoff; Gamescope
+ # and the selected game driver still use the system GPU.
+ bl_steam_presentation=(-cef-disable-gpu-compositing)
+ echo "== steam: system PowerVR uses OpenGL/DRI3 through Zink with software CEF compositing"
+ fi
# Decky is optional and session scoped: the app's marker opts in, and this supervisor is
# reaped with the client session. Native ARM64 runs directly. A legacy x86_64 asset is used
# only when its recorded architecture says so and droiddeck-fex has FEX and its runtime ready.
@@ -880,7 +901,9 @@ BUSCONF
# desktop's launchers ask for. KDE owns its windows when BL_DESKTOP=1.
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
- _bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan)
+ # bl_steam_angle / bl_steam_presentation default to the Adreno values (vulkan, none); only
+ # the system-PowerVR path (BL_STEAM_GL_PRESENT=1) changes them.
+ _bl_cef=(-cef-force-gpu "${bl_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=$bl_steam_angle")
if [ "${BL_DESKTOP:-}" = 1 ] && [ "${BL_STEAM_UI:-}" = desktop ]; then
# KDE uses QPainter/shm on Android. CEF's Vulkan buffers cannot be
# presented there; its software path keeps the library and dialogs on KDE.
@@ -1052,6 +1075,9 @@ BUSCONF
/usr/local/bin/droiddeck-steam-desktop-ui &
desktop_ui_pid=$!
fi
+ # Keep Valve's optional webhelper CPU pinning from aborting browser startup.
+ PATH="$bl_steam_path" \
+ BL_STEAM_WEBHELPER="$steam_root/steamrtarm64/steamwebhelper" \
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
rc=$?
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset
new file mode 100644
index 0000000000..8973fc7f51
--- /dev/null
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset
@@ -0,0 +1,17 @@
+#!/bin/bash
+# Staged as taskset in a PATH directory used only by the Steam client.
+# Valve's ARM64 helper uses `taskset 0x7c /path/to/steamwebhelper ...` and exits
+# before starting the browser when Android denies sched_setaffinity.
+set -u
+if [ "$#" -ge 2 ] && [[ "$1" =~ ^(0[xX])?[0-9a-fA-F]+$ ]] &&
+ [ -n "${BL_STEAM_WEBHELPER:-}" ] && [ "$2" -ef "$BL_STEAM_WEBHELPER" ]; then
+ mask=$1
+ shift
+ # Pin this wrapper before exec; never retry a helper that has already run.
+ if ! /usr/bin/taskset -p "$mask" "$$" >/dev/null 2>&1; then
+ echo "droiddeck: Steam helper CPU pinning unavailable; using the allowed CPUs" >&2
+ fi
+ exec -- "$@"
+fi
+# Queries, existing-process changes, and other programs retain taskset's behavior.
+exec /usr/bin/taskset "$@"
diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility
index b64d721b74..1827dd407f 100755
--- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility
+++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility
@@ -198,6 +198,9 @@ bl_components() {
local -A cm_sums=()
while IFS=$'\\t' read -r scope t want comp rel sum src; do
[ -n "$scope" ] || continue
+ # The selected system PowerVR runtime supplies DXVK at launch. Keep saved selections
+ # for a later manual-driver session without rewriting this Proton's bundled files now.
+ [ "$comp" = dxvk ] && [ -n "${DROIDDECK_POWERVR_RUNTIME:-}" ] && continue
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
done <<< "$cm_selected"
diff --git a/tools/linuxfs/preload/drm.c b/tools/linuxfs/preload/drm.c
index bb4374be09..3797883728 100644
--- a/tools/linuxfs/preload/drm.c
+++ b/tools/linuxfs/preload/drm.c
@@ -1,9 +1,10 @@
/*
- * GEM handle emulation for the KGSL device presented as a DRM render node.
+ * GEM handle emulation for KGSL and explicitly enabled system-PowerVR sessions.
*
* Compositors and Mesa validate or convert dma-bufs with PRIME ioctls on the render node; KGSL
* has no GEM. Handles only serve as tokens to these callers, so a table of duplicated dma-buf
- * descriptors stands in for the kernel's, and every other device is left to libdrm.
+ * descriptors stands in for the kernel's. PowerVR's Android driver can import DMA-BUFs
+ * through Vulkan but rejects PRIME-to-GEM conversion; its real handles still go to libdrm.
*/
#define _GNU_SOURCE
#include
@@ -11,6 +12,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -18,6 +20,10 @@
#include
#define MAX_HANDLES 4096
+#ifndef F_DUPFD_QUERY
+#define F_DUPFD_QUERY 1027
+#endif
+#define PVR_HANDLE_BIT UINT32_C(0x80000000)
/* DRM_IOCTL_GEM_CLOSE from drm.h: _IOW('d', 0x09, struct drm_gem_close { u32 handle, pad; }). */
struct gem_close {
@@ -30,11 +36,14 @@ struct handle_entry {
uint32_t handle;
int dma_fd;
int drm_fd;
+ int owned_drm_fd; /* PowerVR: pin the open file description, not its reusable fd number. */
+ int powervr;
};
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static struct handle_entry handle_entries[MAX_HANDLES];
static uint32_t next_handle = 1;
+static uint32_t next_pvr_handle = PVR_HANDLE_BIT;
static dev_t kgsl_dev;
static int kgsl_state; /* 0 unknown, 1 known, -1 absent */
@@ -43,12 +52,40 @@ static int is_kgsl(int fd) {
pthread_mutex_lock(&lock);
if (kgsl_state == 0) {
kgsl_state = stat("/dev/kgsl-3d0", &st) == 0 ? 1 : -1;
- kgsl_dev = st.st_rdev;
+ if (kgsl_state > 0) kgsl_dev = st.st_rdev;
}
pthread_mutex_unlock(&lock);
return kgsl_state > 0 && fstat(fd, &st) == 0 && S_ISCHR(st.st_mode) && st.st_rdev == kgsl_dev;
}
+/* Keep the opt-in separate from GPU detection: manual ICDs must retain native DRM behavior. */
+struct bl_drm_version {
+ int major, minor, patch;
+ size_t name_len;
+ char *name;
+ size_t date_len;
+ char *date;
+ size_t desc_len;
+ char *desc;
+};
+#define BL_DRM_VERSION _IOWR('d', 0x00, struct bl_drm_version)
+
+static int is_powervr(int fd) {
+ const char *enabled = getenv("BL_POWERVR_DRM_HANDLES");
+ if (!enabled || strcmp(enabled, "1")) return 0;
+ const char *path = getenv("BL_POWERVR_RENDER_NODE");
+ if (!path || !*path) return 0;
+ struct stat node, candidate;
+ if (stat(path, &node) || fstat(fd, &candidate) ||
+ !S_ISCHR(candidate.st_mode) || !S_ISCHR(node.st_mode) ||
+ candidate.st_rdev != node.st_rdev) return 0;
+ char name[16] = {0};
+ struct bl_drm_version version = {.name_len = sizeof(name) - 1, .name = name};
+ /* Bypass the preload's ioctl dispatcher to avoid recursively entering this hook. */
+ return syscall(SYS_ioctl, fd, BL_DRM_VERSION, &version) == 0 &&
+ version.name_len == 3 && !memcmp(name, "pvr", 3);
+}
+
static void *real(const char *name) {
void *fn = dlsym(RTLD_NEXT, name);
if (!fn) {
@@ -71,10 +108,20 @@ static int same_file_description(int a, int b) {
#endif
}
+static int same_owned_description(int owned, int fd) {
+ int saved_errno = errno;
+ int result = fcntl(owned, F_DUPFD_QUERY, fd);
+ errno = saved_errno;
+ if (result >= 0) return result == 1;
+ return same_file_description(owned, fd);
+}
+
static int find_handle_locked(int fd, uint32_t handle) {
for (int i = 0; i < MAX_HANDLES; i++) {
if (handle_entries[i].handle == handle &&
- same_file_description(handle_entries[i].drm_fd, fd)) {
+ (handle_entries[i].powervr
+ ? same_owned_description(handle_entries[i].owned_drm_fd, fd)
+ : same_file_description(handle_entries[i].drm_fd, fd))) {
return i;
}
}
@@ -86,11 +133,15 @@ static int find_handle_locked(int fd, uint32_t handle) {
* rapidly recreated swapchains immediately reused those numbers. Keep storage slots reusable but
* make the public token monotonic so a stale handle can fail instead of aliasing a newer buffer.
*/
-static uint32_t alloc_handle_locked(void) {
+static uint32_t alloc_handle_locked(int powervr) {
for (int tries = 0; tries <= MAX_HANDLES; tries++) {
- uint32_t candidate = next_handle++;
- if (next_handle == 0) {
- next_handle = 1;
+ uint32_t candidate;
+ if (powervr) {
+ candidate = next_pvr_handle++;
+ if (!(next_pvr_handle & PVR_HANDLE_BIT)) next_pvr_handle = PVR_HANDLE_BIT;
+ } else {
+ candidate = next_handle++;
+ if (next_handle == PVR_HANDLE_BIT) next_handle = 1;
}
if (candidate == 0) {
continue;
@@ -110,25 +161,45 @@ static uint32_t alloc_handle_locked(void) {
}
int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle) {
- if (!is_kgsl(fd)) {
+ int kgsl = is_kgsl(fd);
+ int powervr = !kgsl && is_powervr(fd);
+ if (!kgsl) {
int (*fn)(int, int, uint32_t *) = (int (*)(int, int, uint32_t *)) real("drmPrimeFDToHandle");
- return fn ? fn(fd, prime_fd, handle) : -ENOSYS;
+ if (!fn) return -ENOSYS;
+ int result = fn(fd, prime_fd, handle);
+ if (!result || !powervr || errno != EINVAL) return result;
+ }
+ if (!handle) { errno = EINVAL; return -EINVAL; }
+ int owner = -1;
+ if (powervr) {
+ owner = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+ if (owner < 0) return -errno;
+ if (!same_owned_description(owner, fd)) {
+ close(owner);
+ errno = EOPNOTSUPP;
+ return -EOPNOTSUPP;
+ }
}
int dup_fd = fcntl(prime_fd, F_DUPFD_CLOEXEC, 0);
if (dup_fd < 0) {
- return -errno;
+ int error = errno;
+ if (owner >= 0) close(owner);
+ errno = error;
+ return -error;
}
int ret = -ENOMEM;
pthread_mutex_lock(&lock);
for (int i = 0; i < MAX_HANDLES; i++) {
if (handle_entries[i].handle == 0) {
- uint32_t token = alloc_handle_locked();
+ uint32_t token = alloc_handle_locked(powervr);
if (!token) {
break;
}
handle_entries[i].handle = token;
handle_entries[i].dma_fd = dup_fd;
handle_entries[i].drm_fd = fd;
+ handle_entries[i].owned_drm_fd = owner;
+ handle_entries[i].powervr = powervr;
*handle = token;
ret = 0;
break;
@@ -137,33 +208,42 @@ int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle) {
pthread_mutex_unlock(&lock);
if (ret) {
close(dup_fd);
+ if (owner >= 0) close(owner);
+ errno = -ret;
}
return ret;
}
int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd) {
- if (!is_kgsl(fd)) {
- int (*fn)(int, uint32_t, uint32_t, int *) = (int (*)(int, uint32_t, uint32_t, int *)) real("drmPrimeHandleToFD");
- return fn ? fn(fd, handle, flags, prime_fd) : -ENOSYS;
- }
+ int kgsl = is_kgsl(fd);
int ret = -EINVAL;
pthread_mutex_lock(&lock);
int index = find_handle_locked(fd, handle);
if (index >= 0) {
- *prime_fd = fcntl(handle_entries[index].dma_fd, F_DUPFD_CLOEXEC, 0);
- ret = *prime_fd < 0 ? -errno : 0;
+ if (!prime_fd || (handle_entries[index].powervr && (flags & ~(O_CLOEXEC | O_RDWR)))) {
+ errno = EINVAL;
+ } else {
+ int command = handle_entries[index].powervr && !(flags & O_CLOEXEC) ? F_DUPFD : F_DUPFD_CLOEXEC;
+ *prime_fd = fcntl(handle_entries[index].dma_fd, command, 0);
+ ret = *prime_fd < 0 ? -errno : 0;
+ }
}
pthread_mutex_unlock(&lock);
- return ret;
+ if (index >= 0 || kgsl) return ret;
+ /* Unknown handles (including real PowerVR GEM handles) retain kernel semantics. */
+ int (*fn)(int, uint32_t, uint32_t, int *) =
+ (int (*)(int, uint32_t, uint32_t, int *)) real("drmPrimeHandleToFD");
+ return fn ? fn(fd, handle, flags, prime_fd) : -ENOSYS;
}
-/* Drops only a handle belonging to this KGSL file description. */
+/* Drops only an emulated handle belonging to this file description. */
static int release_handle(int fd, uint32_t handle) {
int found = 0;
pthread_mutex_lock(&lock);
int index = find_handle_locked(fd, handle);
if (index >= 0) {
close(handle_entries[index].dma_fd);
+ if (handle_entries[index].powervr) close(handle_entries[index].owned_drm_fd);
handle_entries[index] = (struct handle_entry){0};
found = 1;
}
@@ -172,11 +252,10 @@ static int release_handle(int fd, uint32_t handle) {
}
int drmCloseBufferHandle(int fd, uint32_t handle) {
- if (!is_kgsl(fd)) {
- int (*fn)(int, uint32_t) = (int (*)(int, uint32_t)) real("drmCloseBufferHandle");
- return fn ? fn(fd, handle) : -ENOSYS;
- }
- return release_handle(fd, handle) ? 0 : -EINVAL;
+ if (release_handle(fd, handle)) return 0;
+ if (is_kgsl(fd)) { errno = EINVAL; return -EINVAL; }
+ int (*fn)(int, uint32_t) = (int (*)(int, uint32_t)) real("drmCloseBufferHandle");
+ return fn ? fn(fd, handle) : -ENOSYS;
}
/*
@@ -190,14 +269,16 @@ int drmCloseBufferHandle(int fd, uint32_t handle) {
* judder replaying old frames in No Man's Sky on an Adreno 840 even with no handle released.
*/
__attribute__((visibility("hidden"))) int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) {
- if (request != GEM_CLOSE || !arg || !is_kgsl(fd)) {
+ if (request != GEM_CLOSE || !arg) {
return 0;
}
if (release_handle(fd, ((struct gem_close *) arg)->handle)) {
*rc = 0;
- } else {
+ } else if (is_kgsl(fd)) {
errno = EINVAL;
*rc = -1;
+ } else {
+ return 0;
}
return 1;
}
diff --git a/tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json b/tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json
new file mode 100644
index 0000000000..888d0a89de
--- /dev/null
+++ b/tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json
@@ -0,0 +1,11 @@
+{
+ "file_format_version": "1.2.0",
+ "layer": {
+ "name": "VK_LAYER_DROIDDECK_xclipse",
+ "type": "GLOBAL",
+ "library_path": "./libVkLayer_droiddeck_xclipse.so",
+ "api_version": "1.3.0",
+ "implementation_version": "1",
+ "description": "Workarounds for Samsung Xclipse drivers loaded through libhybris"
+ }
+}
diff --git a/tools/linuxfs/xclipse-layer/device_chain.inc b/tools/linuxfs/xclipse-layer/device_chain.inc
new file mode 100644
index 0000000000..e8a1314114
--- /dev/null
+++ b/tools/linuxfs/xclipse-layer/device_chain.inc
@@ -0,0 +1,180 @@
+/* Generated by gen_device_chain.py from Vulkan-Headers 1.3.275; do not edit. */
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_DEVICE_MEMORY_REPORT_CREATE_INFO_EXT, VkDeviceDeviceMemoryReportCreateInfoEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV, VkDeviceDiagnosticsConfigCreateInfoNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO, VkDeviceGroupDeviceCreateInfo)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD, VkDeviceMemoryOverallocationCreateInfoAMD)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_PRIVATE_DATA_CREATE_INFO, VkDevicePrivateDataCreateInfo)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_QUEUE_SHADER_CORE_CONTROL_CREATE_INFO_ARM, VkDeviceQueueShaderCoreControlCreateInfoARM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES, VkPhysicalDevice16BitStorageFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_4444_FORMATS_FEATURES_EXT, VkPhysicalDevice4444FormatsFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES, VkPhysicalDevice8BitStorageFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR, VkPhysicalDeviceAccelerationStructureFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ADDRESS_BINDING_REPORT_FEATURES_EXT, VkPhysicalDeviceAddressBindingReportFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_AMIGO_PROFILING_FEATURES_SEC, VkPhysicalDeviceAmigoProfilingFeaturesSEC)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ASTC_DECODE_FEATURES_EXT, VkPhysicalDeviceASTCDecodeFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_DYNAMIC_STATE_FEATURES_EXT, VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT, VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT, VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BORDER_COLOR_SWIZZLE_FEATURES_EXT, VkPhysicalDeviceBorderColorSwizzleFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, VkPhysicalDeviceBufferDeviceAddressFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, VkPhysicalDeviceBufferDeviceAddressFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CLUSTER_CULLING_SHADER_FEATURES_HUAWEI, VkPhysicalDeviceClusterCullingShaderFeaturesHUAWEI)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COHERENT_MEMORY_FEATURES_AMD, VkPhysicalDeviceCoherentMemoryFeaturesAMD)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COLOR_WRITE_ENABLE_FEATURES_EXT, VkPhysicalDeviceColorWriteEnableFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV, VkPhysicalDeviceComputeShaderDerivativesFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT, VkPhysicalDeviceConditionalRenderingFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR, VkPhysicalDeviceCooperativeMatrixFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_NV, VkPhysicalDeviceCooperativeMatrixFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COPY_MEMORY_INDIRECT_FEATURES_NV, VkPhysicalDeviceCopyMemoryIndirectFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CORNER_SAMPLED_IMAGE_FEATURES_NV, VkPhysicalDeviceCornerSampledImageFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV, VkPhysicalDeviceCoverageReductionModeFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUBIC_CLAMP_FEATURES_QCOM, VkPhysicalDeviceCubicClampFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUBIC_WEIGHTS_FEATURES_QCOM, VkPhysicalDeviceCubicWeightsFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUDA_KERNEL_LAUNCH_FEATURES_NV, VkPhysicalDeviceCudaKernelLaunchFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT, VkPhysicalDeviceCustomBorderColorFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEDICATED_ALLOCATION_IMAGE_ALIASING_FEATURES_NV, VkPhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_BIAS_CONTROL_FEATURES_EXT, VkPhysicalDeviceDepthBiasControlFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLAMP_ZERO_ONE_FEATURES_EXT, VkPhysicalDeviceDepthClampZeroOneFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_CONTROL_FEATURES_EXT, VkPhysicalDeviceDepthClipControlFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT, VkPhysicalDeviceDepthClipEnableFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT, VkPhysicalDeviceDescriptorBufferFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES, VkPhysicalDeviceDescriptorIndexingFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_POOL_OVERALLOCATION_FEATURES_NV, VkPhysicalDeviceDescriptorPoolOverallocationFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_SET_HOST_MAPPING_FEATURES_VALVE, VkPhysicalDeviceDescriptorSetHostMappingFeaturesVALVE)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_GENERATED_COMMANDS_COMPUTE_FEATURES_NV, VkPhysicalDeviceDeviceGeneratedCommandsComputeFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_GENERATED_COMMANDS_FEATURES_NV, VkPhysicalDeviceDeviceGeneratedCommandsFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_MEMORY_REPORT_FEATURES_EXT, VkPhysicalDeviceDeviceMemoryReportFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV, VkPhysicalDeviceDiagnosticsConfigFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES, VkPhysicalDeviceDynamicRenderingFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_UNUSED_ATTACHMENTS_FEATURES_EXT, VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV, VkPhysicalDeviceExclusiveScissorFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT, VkPhysicalDeviceExtendedDynamicState2FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_3_FEATURES_EXT, VkPhysicalDeviceExtendedDynamicState3FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT, VkPhysicalDeviceExtendedDynamicStateFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_SPARSE_ADDRESS_SPACE_FEATURES_NV, VkPhysicalDeviceExtendedSparseAddressSpaceFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_RDMA_FEATURES_NV, VkPhysicalDeviceExternalMemoryRDMAFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT, VkPhysicalDeviceFaultFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, VkPhysicalDeviceFeatures2)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_2_FEATURES_EXT, VkPhysicalDeviceFragmentDensityMap2FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT, VkPhysicalDeviceFragmentDensityMapFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_OFFSET_FEATURES_QCOM, VkPhysicalDeviceFragmentDensityMapOffsetFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR, VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT, VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_ENUMS_FEATURES_NV, VkPhysicalDeviceFragmentShadingRateEnumsFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR, VkPhysicalDeviceFragmentShadingRateFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAME_BOUNDARY_FEATURES_EXT, VkPhysicalDeviceFrameBoundaryFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GLOBAL_PRIORITY_QUERY_FEATURES_KHR, VkPhysicalDeviceGlobalPriorityQueryFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GRAPHICS_PIPELINE_LIBRARY_FEATURES_EXT, VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT, VkPhysicalDeviceHostImageCopyFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES, VkPhysicalDeviceHostQueryResetFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES, VkPhysicalDeviceImagelessFramebufferFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_2D_VIEW_OF_3D_FEATURES_EXT, VkPhysicalDeviceImage2DViewOf3DFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_COMPRESSION_CONTROL_FEATURES_EXT, VkPhysicalDeviceImageCompressionControlFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_COMPRESSION_CONTROL_SWAPCHAIN_FEATURES_EXT, VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_PROCESSING_2_FEATURES_QCOM, VkPhysicalDeviceImageProcessing2FeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_PROCESSING_FEATURES_QCOM, VkPhysicalDeviceImageProcessingFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES, VkPhysicalDeviceImageRobustnessFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT, VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT, VkPhysicalDeviceImageViewMinLodFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT, VkPhysicalDeviceIndexTypeUint8FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INHERITED_VIEWPORT_SCISSOR_FEATURES_NV, VkPhysicalDeviceInheritedViewportScissorFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES, VkPhysicalDeviceInlineUniformBlockFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INVOCATION_MASK_FEATURES_HUAWEI, VkPhysicalDeviceInvocationMaskFeaturesHUAWEI)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LEGACY_DITHERING_FEATURES_EXT, VkPhysicalDeviceLegacyDitheringFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINEAR_COLOR_ATTACHMENT_FEATURES_NV, VkPhysicalDeviceLinearColorAttachmentFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_FEATURES_EXT, VkPhysicalDeviceLineRasterizationFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES, VkPhysicalDeviceMaintenance4Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, VkPhysicalDeviceMaintenance5FeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR, VkPhysicalDeviceMaintenance6FeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_DECOMPRESSION_FEATURES_NV, VkPhysicalDeviceMemoryDecompressionFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT, VkPhysicalDeviceMemoryPriorityFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, VkPhysicalDeviceMeshShaderFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_NV, VkPhysicalDeviceMeshShaderFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTISAMPLED_RENDER_TO_SINGLE_SAMPLED_FEATURES_EXT, VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES, VkPhysicalDeviceMultiviewFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_RENDER_AREAS_FEATURES_QCOM, VkPhysicalDeviceMultiviewPerViewRenderAreasFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_VIEWPORTS_FEATURES_QCOM, VkPhysicalDeviceMultiviewPerViewViewportsFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTI_DRAW_FEATURES_EXT, VkPhysicalDeviceMultiDrawFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MUTABLE_DESCRIPTOR_TYPE_FEATURES_EXT, VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_NESTED_COMMAND_BUFFER_FEATURES_EXT, VkPhysicalDeviceNestedCommandBufferFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_NON_SEAMLESS_CUBE_MAP_FEATURES_EXT, VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT, VkPhysicalDeviceOpacityMicromapFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPTICAL_FLOW_FEATURES_NV, VkPhysicalDeviceOpticalFlowFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PAGEABLE_DEVICE_LOCAL_MEMORY_FEATURES_EXT, VkPhysicalDevicePageableDeviceLocalMemoryFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PERFORMANCE_QUERY_FEATURES_KHR, VkPhysicalDevicePerformanceQueryFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PER_STAGE_DESCRIPTOR_SET_FEATURES_NV, VkPhysicalDevicePerStageDescriptorSetFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES, VkPhysicalDevicePipelineCreationCacheControlFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR, VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_LIBRARY_GROUP_HANDLES_FEATURES_EXT, VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_PROPERTIES_FEATURES_EXT, VkPhysicalDevicePipelinePropertiesFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_PROTECTED_ACCESS_FEATURES_EXT, VkPhysicalDevicePipelineProtectedAccessFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT, VkPhysicalDevicePipelineRobustnessFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_BARRIER_FEATURES_NV, VkPhysicalDevicePresentBarrierFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR, VkPhysicalDevicePresentIdFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR, VkPhysicalDevicePresentWaitFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVES_GENERATED_QUERY_FEATURES_EXT, VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVE_TOPOLOGY_LIST_RESTART_FEATURES_EXT, VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIVATE_DATA_FEATURES, VkPhysicalDevicePrivateDataFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES, VkPhysicalDeviceProtectedMemoryFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT, VkPhysicalDeviceProvokingVertexFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_FEATURES_EXT, VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR, VkPhysicalDeviceRayQueryFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_INVOCATION_REORDER_FEATURES_NV, VkPhysicalDeviceRayTracingInvocationReorderFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MAINTENANCE_1_FEATURES_KHR, VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV, VkPhysicalDeviceRayTracingMotionBlurFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR, VkPhysicalDeviceRayTracingPipelineFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_POSITION_FETCH_FEATURES_KHR, VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RELAXED_LINE_RASTERIZATION_FEATURES_IMG, VkPhysicalDeviceRelaxedLineRasterizationFeaturesIMG)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RENDER_PASS_STRIPED_FEATURES_ARM, VkPhysicalDeviceRenderPassStripedFeaturesARM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV, VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RGBA10X6_FORMATS_FEATURES_EXT, VkPhysicalDeviceRGBA10X6FormatsFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT, VkPhysicalDeviceRobustness2FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES, VkPhysicalDeviceSamplerYcbcrConversionFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES, VkPhysicalDeviceScalarBlockLayoutFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCHEDULING_CONTROLS_FEATURES_ARM, VkPhysicalDeviceSchedulingControlsFeaturesARM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SEPARATE_DEPTH_STENCIL_LAYOUTS_FEATURES, VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_2_FEATURES_EXT, VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT, VkPhysicalDeviceShaderAtomicFloatFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES, VkPhysicalDeviceShaderAtomicInt64Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR, VkPhysicalDeviceShaderClockFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_BUILTINS_FEATURES_ARM, VkPhysicalDeviceShaderCoreBuiltinsFeaturesARM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES, VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES, VkPhysicalDeviceShaderDrawParametersFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_EARLY_AND_LATE_FRAGMENT_TESTS_FEATURES_AMD, VkPhysicalDeviceShaderEarlyAndLateFragmentTestsFeaturesAMD)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES, VkPhysicalDeviceShaderFloat16Int8Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT, VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_FOOTPRINT_FEATURES_NV, VkPhysicalDeviceShaderImageFootprintFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES, VkPhysicalDeviceShaderIntegerDotProductFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_FUNCTIONS_2_FEATURES_INTEL, VkPhysicalDeviceShaderIntegerFunctions2FeaturesINTEL)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MODULE_IDENTIFIER_FEATURES_EXT, VkPhysicalDeviceShaderModuleIdentifierFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OBJECT_FEATURES_EXT, VkPhysicalDeviceShaderObjectFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SM_BUILTINS_FEATURES_NV, VkPhysicalDeviceShaderSMBuiltinsFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES, VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_FEATURES_KHR, VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TERMINATE_INVOCATION_FEATURES, VkPhysicalDeviceShaderTerminateInvocationFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TILE_IMAGE_FEATURES_EXT, VkPhysicalDeviceShaderTileImageFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV, VkPhysicalDeviceShadingRateImageFeaturesNV)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES, VkPhysicalDeviceSubgroupSizeControlFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBPASS_MERGE_FEEDBACK_FEATURES_EXT, VkPhysicalDeviceSubpassMergeFeedbackFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBPASS_SHADING_FEATURES_HUAWEI, VkPhysicalDeviceSubpassShadingFeaturesHUAWEI)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT, VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES, VkPhysicalDeviceSynchronization2Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_FEATURES_EXT, VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXTURE_COMPRESSION_ASTC_HDR_FEATURES, VkPhysicalDeviceTextureCompressionASTCHDRFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TILE_PROPERTIES_FEATURES_QCOM, VkPhysicalDeviceTilePropertiesFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES, VkPhysicalDeviceTimelineSemaphoreFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT, VkPhysicalDeviceTransformFeedbackFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES, VkPhysicalDeviceUniformBufferStandardLayoutFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES, VkPhysicalDeviceVariablePointersFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR, VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_INPUT_DYNAMIC_STATE_FEATURES_EXT, VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_MAINTENANCE_1_FEATURES_KHR, VkPhysicalDeviceVideoMaintenance1FeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, VkPhysicalDeviceVulkan11Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, VkPhysicalDeviceVulkan12Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, VkPhysicalDeviceVulkan13Features)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES, VkPhysicalDeviceVulkanMemoryModelFeatures)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_WORKGROUP_MEMORY_EXPLICIT_LAYOUT_FEATURES_KHR, VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_2_PLANE_444_FORMATS_FEATURES_EXT, VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_DEGAMMA_FEATURES_QCOM, VkPhysicalDeviceYcbcrDegammaFeaturesQCOM)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT, VkPhysicalDeviceYcbcrImageArraysFeaturesEXT)
+DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ZERO_INITIALIZE_WORKGROUP_MEMORY_FEATURES, VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures)
diff --git a/tools/linuxfs/xclipse-layer/gen_device_chain.py b/tools/linuxfs/xclipse-layer/gen_device_chain.py
new file mode 100755
index 0000000000..3ef47693c6
--- /dev/null
+++ b/tools/linuxfs/xclipse-layer/gen_device_chain.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""Generate device_chain.inc: the structures a VkDeviceCreateInfo chain may hold, with their sizes.
+
+The Xclipse layer copies the chain ahead of the VkPhysicalDeviceFeatures2 it edits, and copying a
+structure needs its size. Run against the Vulkan-Headers release the build compiles with (Ubuntu
+24.04's libvulkan-dev is 1.3.275):
+
+ gen_device_chain.py Vulkan-Headers/registry/vk.xml Vulkan-Headers/include/vulkan/vulkan_core.h
+"""
+import re
+import sys
+import xml.etree.ElementTree as ElementTree
+from pathlib import Path
+
+
+def main(registry, core_header, output):
+ core = Path(core_header).read_text()
+ root = ElementTree.parse(registry).getroot()
+ entries = []
+ for struct in root.iter("type"):
+ if struct.get("category") != "struct" or struct.get("alias"):
+ continue
+ if "VkDeviceCreateInfo" not in (struct.get("structextends") or "").split(","):
+ continue
+ name = struct.get("name")
+ stype = next((member.get("values") for member in struct.findall("member")
+ if member.findtext("name") == "sType"), None)
+ # Platform and provisional structures live outside vulkan_core.h; the layer never builds them.
+ if not stype or not re.search(r"\}\s*" + re.escape(name) + r"\s*;", core):
+ continue
+ entries.append((stype, name))
+ version = re.search(r"#define VK_HEADER_VERSION (\d+)", core).group(1)
+ lines = ["/* Generated by gen_device_chain.py from Vulkan-Headers 1.3.%s; do not edit. */" % version]
+ lines += ["DEVICE_CHAIN(%s, %s)" % entry for entry in sorted(entries)]
+ Path(output).write_text("\n".join(lines) + "\n")
+ print("%d structures" % len(entries))
+
+
+if __name__ == "__main__":
+ if len(sys.argv) not in (3, 4):
+ sys.exit(__doc__)
+ main(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) == 4 else
+ Path(__file__).with_name("device_chain.inc"))
diff --git a/tools/linuxfs/xclipse-layer/xclipse_layer.c b/tools/linuxfs/xclipse-layer/xclipse_layer.c
new file mode 100644
index 0000000000..68c3379dd4
--- /dev/null
+++ b/tools/linuxfs/xclipse-layer/xclipse_layer.c
@@ -0,0 +1,493 @@
+/*
+ * VK_LAYER_DROIDDECK_xclipse: workarounds for Samsung's Xclipse driver loaded through libhybris.
+ *
+ * 1. bionic environ. A glibc process never initializes bionic's `environ`; the driver's
+ * AMD-derived shader compiler walks it for AMD_SC_* settings and crashed on the NULL.
+ * Once instance creation has loaded the driver, point it at a snapshot of ours.
+ * 2. YCbCr immutable samplers in compute. Compute pipelines whose layout binds an array of
+ * immutable YCbCr-conversion samplers fail to compile (VK_ERROR_UNKNOWN); gamescope's
+ * composite shaders all bind one. Such bindings get a plain linear sampler instead, so only
+ * multi-planar (NV12) layers sample incorrectly.
+ * 3. Calibrated timestamps. The driver has only VK_EXT_calibrated_timestamps, but the bridge
+ * lists the KHR names too, and Wine calls those; the loader then aborts (it took down Wine's
+ * explorer.exe and with it every game window). The KHR entry points forward to the EXT ones.
+ * 4. BC4/BC5 filtering. The libhybris compat layer emulates BC textures; BC4/BC5 decode into
+ * R16/R16G16 images, for which this driver advertises no linear filtering, so DXVK would
+ * treat them as unfilterable. The layer reports linear filtering for BC4/BC5 where they are
+ * sampled at all (RDNA filters 16-bit normalized formats; at worst they sample unfiltered).
+ * 5. textureCompressionBC. The compat layer emulates BC formats but keeps the feature bit off;
+ * DXVK before 3.0 (the last that fits this driver's 128 bytes of push constants) requires
+ * it. The layer reports it while BC formats are sampleable and clears it at device creation.
+ * Everything else passes straight through.
+ */
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define EXPORT __attribute__((visibility("default")))
+#define MAX_OBJECTS 64
+
+extern char **environ;
+
+/* The loader's dispatch table pointer heads every dispatchable object: an instance shares it
+ * with its physical devices, a device with its queues and command buffers. */
+typedef void *dispatch_key;
+static dispatch_key key_of(const void *object) { return *(dispatch_key *)object; }
+
+static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+static int debug;
+
+struct instance_data {
+ dispatch_key key;
+ VkInstance handle;
+ PFN_vkGetInstanceProcAddr next;
+ PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT time_domains;
+ PFN_vkGetPhysicalDeviceFeatures features;
+ PFN_vkGetPhysicalDeviceFeatures2 features2;
+ PFN_vkGetPhysicalDeviceFormatProperties format_properties;
+ PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2;
+};
+struct device_data {
+ dispatch_key key;
+ VkDevice handle;
+ PFN_vkGetDeviceProcAddr next;
+ PFN_vkCreateSampler create_sampler;
+ PFN_vkDestroySampler destroy_sampler;
+ PFN_vkCreateDescriptorSetLayout create_set_layout;
+ PFN_vkDestroyDevice destroy_device;
+ PFN_vkGetCalibratedTimestampsEXT timestamps;
+ VkSampler fallback;
+};
+static struct instance_data instances[MAX_OBJECTS];
+static struct device_data devices[MAX_OBJECTS];
+/* The live YCbCr samplers each device created, so set layouts can recognise them. Guarded by lock. */
+static struct ycbcr_sampler { VkDevice device; VkSampler sampler; } *ycbcr_samplers;
+static size_t ycbcr_count, ycbcr_capacity;
+
+static struct instance_data *instance_by_key(dispatch_key key) {
+ for (int i = 0; i < MAX_OBJECTS; i++)
+ if (instances[i].handle && instances[i].key == key) return &instances[i];
+ return NULL;
+}
+
+static struct device_data *device_by_key(dispatch_key key) {
+ for (int i = 0; i < MAX_OBJECTS; i++)
+ if (devices[i].handle && devices[i].key == key) return &devices[i];
+ return NULL;
+}
+
+/* Entries are never freed while their object lives, so a looked-up copy of the pointers is safe. */
+static struct instance_data instance_of(const void *object) {
+ struct instance_data copy = {0};
+ pthread_mutex_lock(&lock);
+ struct instance_data *data = instance_by_key(key_of(object));
+ if (data) copy = *data;
+ pthread_mutex_unlock(&lock);
+ return copy;
+}
+
+static struct device_data device_of(const void *object) {
+ struct device_data copy = {0};
+ pthread_mutex_lock(&lock);
+ struct device_data *data = device_by_key(key_of(object));
+ if (data) copy = *data;
+ pthread_mutex_unlock(&lock);
+ return copy;
+}
+
+static void fix_bionic_environ(void) {
+ void *common = dlopen("libhybris-common.so.1", RTLD_NOW | RTLD_NOLOAD);
+ if (!common) return; /* not a libhybris driver */
+ void *(*h_dlopen)(const char *, int) = (void *(*)(const char *, int))dlsym(common, "hybris_dlopen");
+ void *(*h_dlsym)(void *, const char *) = (void *(*)(void *, const char *))dlsym(common, "hybris_dlsym");
+ if (!h_dlopen || !h_dlsym) return;
+ void *libc = h_dlopen("libc.so", RTLD_NOW);
+ char ***bionic_environ = libc ? (char ***)h_dlsym(libc, "environ") : NULL;
+ if (!bionic_environ || *bionic_environ) return;
+ size_t count = 0;
+ while (environ && environ[count]) count++;
+ char **snapshot = calloc(count + 1, sizeof(*snapshot));
+ if (!snapshot) return;
+ for (size_t i = 0; i < count; i++) snapshot[i] = strdup(environ[i]);
+ *bionic_environ = snapshot;
+ if (debug) fprintf(stderr, "xclipse layer: bionic environ set (%zu entries)\n", count);
+}
+
+/* ---- instance ---- */
+
+static VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
+ VkInstance *instance) {
+ VkLayerInstanceCreateInfo *chain = (VkLayerInstanceCreateInfo *)info->pNext;
+ while (chain && !(chain->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain->function == VK_LAYER_LINK_INFO))
+ chain = (VkLayerInstanceCreateInfo *)chain->pNext;
+ if (!chain || !chain->u.pLayerInfo) return VK_ERROR_INITIALIZATION_FAILED;
+ PFN_vkGetInstanceProcAddr next = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
+ chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
+ PFN_vkCreateInstance next_create = (PFN_vkCreateInstance)next(NULL, "vkCreateInstance");
+ if (!next_create) return VK_ERROR_INITIALIZATION_FAILED;
+ VkResult result = next_create(info, allocator, instance);
+ if (result != VK_SUCCESS) return result;
+ fix_bionic_environ();
+ struct instance_data data = {
+ .key = key_of(*instance),
+ .handle = *instance,
+ .next = next,
+ .time_domains = (PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT)
+ next(*instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT"),
+ .features = (PFN_vkGetPhysicalDeviceFeatures)next(*instance, "vkGetPhysicalDeviceFeatures"),
+ .features2 = (PFN_vkGetPhysicalDeviceFeatures2)next(*instance, "vkGetPhysicalDeviceFeatures2"),
+ .format_properties = (PFN_vkGetPhysicalDeviceFormatProperties)next(*instance, "vkGetPhysicalDeviceFormatProperties"),
+ .format_properties2 = (PFN_vkGetPhysicalDeviceFormatProperties2)next(*instance, "vkGetPhysicalDeviceFormatProperties2"),
+ };
+ pthread_mutex_lock(&lock);
+ for (int i = 0; i < MAX_OBJECTS; i++)
+ if (!instances[i].handle) { instances[i] = data; break; }
+ pthread_mutex_unlock(&lock);
+ return result;
+}
+
+static void VKAPI_CALL destroy_instance(VkInstance instance, const VkAllocationCallbacks *allocator) {
+ PFN_vkGetInstanceProcAddr next = instance_of(instance).next;
+ pthread_mutex_lock(&lock);
+ struct instance_data *data = instance_by_key(key_of(instance));
+ if (data) memset(data, 0, sizeof(*data));
+ pthread_mutex_unlock(&lock);
+ PFN_vkDestroyInstance next_destroy = next ? (PFN_vkDestroyInstance)next(instance, "vkDestroyInstance") : NULL;
+ if (next_destroy) next_destroy(instance, allocator);
+}
+
+static VkResult VKAPI_CALL time_domains_khr(VkPhysicalDevice physical, uint32_t *count, VkTimeDomainEXT *domains) {
+ PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT ext = instance_of(physical).time_domains;
+ if (!ext) { *count = 0; return VK_SUCCESS; }
+ return ext(physical, count, domains);
+}
+
+/* BC formats sampleable below us although the driver's feature bit is off: the compat layer emulates them. */
+static int bc_emulated(VkPhysicalDevice physical) {
+ struct instance_data data = instance_of(physical);
+ if (!data.features || !data.format_properties) return 0;
+ VkPhysicalDeviceFeatures native;
+ data.features(physical, &native);
+ if (native.textureCompressionBC) return 0;
+ VkFormatProperties bc1, bc7;
+ data.format_properties(physical, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, &bc1);
+ data.format_properties(physical, VK_FORMAT_BC7_UNORM_BLOCK, &bc7);
+ return (bc1.optimalTilingFeatures & bc7.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0;
+}
+
+static void VKAPI_CALL get_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features) {
+ PFN_vkGetPhysicalDeviceFeatures next = instance_of(physical).features;
+ if (next) next(physical, features);
+ if (bc_emulated(physical)) features->textureCompressionBC = VK_TRUE;
+}
+
+static void VKAPI_CALL get_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features) {
+ PFN_vkGetPhysicalDeviceFeatures2 next = instance_of(physical).features2;
+ if (next) next(physical, features);
+ if (bc_emulated(physical)) features->features.textureCompressionBC = VK_TRUE;
+}
+
+static int bc45(VkFormat format) {
+ return format >= VK_FORMAT_BC4_UNORM_BLOCK && format <= VK_FORMAT_BC5_SNORM_BLOCK;
+}
+
+static void VKAPI_CALL get_format_properties(VkPhysicalDevice physical, VkFormat format, VkFormatProperties *out) {
+ PFN_vkGetPhysicalDeviceFormatProperties next = instance_of(physical).format_properties;
+ if (next) next(physical, format, out);
+ if (bc45(format) && (out->optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
+ out->optimalTilingFeatures |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
+}
+
+static void VKAPI_CALL get_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out) {
+ PFN_vkGetPhysicalDeviceFormatProperties2 next = instance_of(physical).format_properties2;
+ if (next) next(physical, format, out);
+ if (!bc45(format)) return;
+ if (out->formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)
+ out->formatProperties.optimalTilingFeatures |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
+ for (VkBaseOutStructure *p = (VkBaseOutStructure *)out->pNext; p; p = p->pNext) {
+ if (p->sType != VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) continue;
+ VkFormatProperties3 *f3 = (VkFormatProperties3 *)p;
+ if (f3->optimalTilingFeatures & VK_FORMAT_FEATURE_2_SAMPLED_IMAGE_BIT)
+ f3->optimalTilingFeatures |= VK_FORMAT_FEATURE_2_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
+ }
+}
+
+/* ---- device ---- */
+
+/* The size of each structure a VkDeviceCreateInfo chain may hold (device_chain.inc, generated from the
+ * Vulkan registry), plus the loader's own; 0 for anything else. */
+static size_t chain_size(VkStructureType type) {
+ switch (type) {
+#define DEVICE_CHAIN(stype, name) case stype: return sizeof(name);
+#include "device_chain.inc"
+#undef DEVICE_CHAIN
+ case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: return sizeof(VkLayerDeviceCreateInfo);
+ default: return 0;
+ }
+}
+
+struct chain_copy { void **nodes; size_t count; };
+
+static void free_chain_copy(struct chain_copy *copy) {
+ for (size_t i = 0; i < copy->count; i++) free(copy->nodes[i]);
+ free(copy->nodes);
+ copy->nodes = NULL;
+ copy->count = 0;
+}
+
+/* The chain with textureCompressionBC cleared in a copy of the VkPhysicalDeviceFeatures2 that enables
+ * it: every structure up to it is copied into [copy], the rest is shared. The caller's structures are
+ * never written. *head_out stays [head] when nothing needs clearing, or when a structure ahead of it
+ * is unknown to this build (newer than its Vulkan headers); the compat layer then refuses the bit. */
+static VkResult chain_without_bc(const void *head, struct chain_copy *copy, const void **head_out) {
+ *head_out = head;
+ const VkBaseInStructure *target = NULL;
+ size_t count = 0;
+ for (const VkBaseInStructure *p = head; p && !target; p = p->pNext) {
+ if (!chain_size(p->sType)) return VK_SUCCESS;
+ count++;
+ if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
+ ((const VkPhysicalDeviceFeatures2 *)p)->features.textureCompressionBC) target = p;
+ }
+ if (!target) return VK_SUCCESS;
+ if (!(copy->nodes = calloc(count, sizeof(*copy->nodes)))) return VK_ERROR_OUT_OF_HOST_MEMORY;
+ VkBaseOutStructure *first = NULL, *last = NULL;
+ for (const VkBaseInStructure *p = head; ; p = p->pNext) {
+ size_t size = chain_size(p->sType);
+ VkBaseOutStructure *node = malloc(size);
+ if (!node) { free_chain_copy(copy); return VK_ERROR_OUT_OF_HOST_MEMORY; }
+ copy->nodes[copy->count++] = node;
+ memcpy(node, p, size);
+ if (last) last->pNext = node; else first = node;
+ last = node;
+ if (p == target) {
+ ((VkPhysicalDeviceFeatures2 *)node)->features.textureCompressionBC = VK_FALSE;
+ *head_out = first; /* its pNext still leads to the caller's remaining structures */
+ return VK_SUCCESS;
+ }
+ }
+}
+
+static VkResult VKAPI_CALL create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
+ const VkAllocationCallbacks *allocator, VkDevice *device) {
+ VkLayerDeviceCreateInfo *chain = (VkLayerDeviceCreateInfo *)info->pNext;
+ while (chain && !(chain->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain->function == VK_LAYER_LINK_INFO))
+ chain = (VkLayerDeviceCreateInfo *)chain->pNext;
+ if (!chain || !chain->u.pLayerInfo) return VK_ERROR_INITIALIZATION_FAILED;
+ PFN_vkGetInstanceProcAddr next_gipa = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
+ PFN_vkGetDeviceProcAddr next_gdpa = chain->u.pLayerInfo->pfnNextGetDeviceProcAddr;
+ chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
+ PFN_vkCreateDevice next_create = (PFN_vkCreateDevice)next_gipa(NULL, "vkCreateDevice");
+ if (!next_create) return VK_ERROR_INITIALIZATION_FAILED;
+
+ VkDeviceCreateInfo patched = *info;
+ /* An emulated textureCompressionBC never reaches the compat layer, which refuses the bit. */
+ int strip_bc = bc_emulated(physical);
+ VkPhysicalDeviceFeatures plain_features;
+ if (strip_bc && info->pEnabledFeatures && info->pEnabledFeatures->textureCompressionBC) {
+ plain_features = *info->pEnabledFeatures;
+ plain_features.textureCompressionBC = VK_FALSE;
+ patched.pEnabledFeatures = &plain_features;
+ }
+ struct chain_copy copy = {0};
+ if (strip_bc) {
+ VkResult copied = chain_without_bc(info->pNext, ©, &patched.pNext);
+ if (copied != VK_SUCCESS) return copied;
+ }
+ VkResult result = next_create(physical, &patched, allocator, device);
+ free_chain_copy(©);
+ if (result != VK_SUCCESS) return result;
+
+ PFN_vkCreateSampler create_sampler = (PFN_vkCreateSampler)next_gdpa(*device, "vkCreateSampler");
+ VkSamplerCreateInfo plain = {
+ .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
+ .magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR,
+ .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
+ .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
+ .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
+ .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
+ };
+ VkSampler fallback = VK_NULL_HANDLE;
+ if (create_sampler) create_sampler(*device, &plain, NULL, &fallback);
+ struct device_data data = {
+ .key = key_of(*device),
+ .handle = *device,
+ .next = next_gdpa,
+ .create_sampler = create_sampler,
+ .destroy_sampler = (PFN_vkDestroySampler)next_gdpa(*device, "vkDestroySampler"),
+ .create_set_layout = (PFN_vkCreateDescriptorSetLayout)next_gdpa(*device, "vkCreateDescriptorSetLayout"),
+ .destroy_device = (PFN_vkDestroyDevice)next_gdpa(*device, "vkDestroyDevice"),
+ .timestamps = (PFN_vkGetCalibratedTimestampsEXT)next_gdpa(*device, "vkGetCalibratedTimestampsEXT"),
+ .fallback = fallback,
+ };
+ pthread_mutex_lock(&lock);
+ for (int i = 0; i < MAX_OBJECTS; i++)
+ if (!devices[i].handle) { devices[i] = data; break; }
+ pthread_mutex_unlock(&lock);
+ return result;
+}
+
+static void VKAPI_CALL destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {
+ struct device_data data = device_of(device);
+ pthread_mutex_lock(&lock);
+ struct device_data *entry = device_by_key(key_of(device));
+ if (entry) memset(entry, 0, sizeof(*entry));
+ for (size_t k = 0; k < ycbcr_count;)
+ if (ycbcr_samplers[k].device == device) ycbcr_samplers[k] = ycbcr_samplers[--ycbcr_count];
+ else k++;
+ pthread_mutex_unlock(&lock);
+ if (data.fallback && data.destroy_sampler) data.destroy_sampler(device, data.fallback, NULL);
+ if (data.destroy_device) data.destroy_device(device, allocator);
+}
+
+static VkResult VKAPI_CALL timestamps_khr(VkDevice device, uint32_t count, const VkCalibratedTimestampInfoEXT *infos,
+ uint64_t *timestamps, uint64_t *deviation) {
+ PFN_vkGetCalibratedTimestampsEXT ext = device_of(device).timestamps;
+ return ext ? ext(device, count, infos, timestamps, deviation) : VK_ERROR_FEATURE_NOT_PRESENT;
+}
+
+static VkResult VKAPI_CALL create_sampler(VkDevice device, const VkSamplerCreateInfo *info,
+ const VkAllocationCallbacks *allocator, VkSampler *sampler) {
+ PFN_vkCreateSampler next = device_of(device).create_sampler;
+ if (!next) return VK_ERROR_INITIALIZATION_FAILED;
+ VkResult result = next(device, info, allocator, sampler);
+ if (result != VK_SUCCESS) return result;
+ int ycbcr = 0;
+ for (const VkBaseInStructure *p = info->pNext; p && !ycbcr; p = p->pNext)
+ ycbcr = p->sType == VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO;
+ if (!ycbcr) return result;
+ pthread_mutex_lock(&lock);
+ if (ycbcr_count == ycbcr_capacity) {
+ size_t capacity = ycbcr_capacity ? ycbcr_capacity * 2 : 16;
+ struct ycbcr_sampler *grown = realloc(ycbcr_samplers, capacity * sizeof(*grown));
+ if (!grown) {
+ pthread_mutex_unlock(&lock);
+ /* An untracked YCbCr sampler would reach a compute layout unreplaced: fail instead. */
+ PFN_vkDestroySampler destroy = device_of(device).destroy_sampler;
+ if (destroy) destroy(device, *sampler, allocator);
+ *sampler = VK_NULL_HANDLE;
+ return VK_ERROR_OUT_OF_HOST_MEMORY;
+ }
+ ycbcr_samplers = grown;
+ ycbcr_capacity = capacity;
+ }
+ ycbcr_samplers[ycbcr_count++] = (struct ycbcr_sampler){device, *sampler};
+ pthread_mutex_unlock(&lock);
+ return result;
+}
+
+static void VKAPI_CALL destroy_sampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *allocator) {
+ pthread_mutex_lock(&lock);
+ for (size_t k = 0; k < ycbcr_count; k++)
+ if (ycbcr_samplers[k].device == device && ycbcr_samplers[k].sampler == sampler) {
+ ycbcr_samplers[k] = ycbcr_samplers[--ycbcr_count];
+ break;
+ }
+ pthread_mutex_unlock(&lock);
+ PFN_vkDestroySampler next = device_of(device).destroy_sampler;
+ if (next) next(device, sampler, allocator);
+}
+
+/* Called with lock held. */
+static int is_ycbcr(VkDevice device, VkSampler sampler) {
+ for (size_t k = 0; sampler && k < ycbcr_count; k++)
+ if (ycbcr_samplers[k].device == device && ycbcr_samplers[k].sampler == sampler) return 1;
+ return 0;
+}
+
+static VkResult VKAPI_CALL create_set_layout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *info,
+ const VkAllocationCallbacks *allocator, VkDescriptorSetLayout *layout) {
+ struct device_data data = device_of(device);
+ if (!data.create_set_layout) return VK_ERROR_INITIALIZATION_FAILED;
+ int replace = 0;
+ pthread_mutex_lock(&lock);
+ for (uint32_t b = 0; data.fallback && b < info->bindingCount && !replace; b++) {
+ const VkDescriptorSetLayoutBinding *binding = &info->pBindings[b];
+ if (!(binding->stageFlags & VK_SHADER_STAGE_COMPUTE_BIT) || !binding->pImmutableSamplers) continue;
+ for (uint32_t s = 0; s < binding->descriptorCount; s++)
+ if (is_ycbcr(device, binding->pImmutableSamplers[s])) { replace = 1; break; }
+ }
+ pthread_mutex_unlock(&lock);
+ if (!replace) return data.create_set_layout(device, info, allocator, layout);
+
+ VkResult result = VK_ERROR_OUT_OF_HOST_MEMORY;
+ VkDescriptorSetLayoutBinding *bindings = calloc(info->bindingCount, sizeof(*bindings));
+ VkSampler **arrays = calloc(info->bindingCount, sizeof(*arrays));
+ if (!bindings || !arrays) goto done;
+ for (uint32_t b = 0; b < info->bindingCount; b++) {
+ bindings[b] = info->pBindings[b];
+ if (!(bindings[b].stageFlags & VK_SHADER_STAGE_COMPUTE_BIT) || !bindings[b].pImmutableSamplers) continue;
+ /* Without the replacement the driver would see the samplers it cannot compile: fail instead. */
+ if (!(arrays[b] = malloc(bindings[b].descriptorCount * sizeof(VkSampler)))) goto done;
+ pthread_mutex_lock(&lock);
+ for (uint32_t s = 0; s < bindings[b].descriptorCount; s++) {
+ VkSampler original = bindings[b].pImmutableSamplers[s];
+ arrays[b][s] = is_ycbcr(device, original) ? data.fallback : original;
+ }
+ pthread_mutex_unlock(&lock);
+ bindings[b].pImmutableSamplers = arrays[b];
+ }
+ VkDescriptorSetLayoutCreateInfo patched = *info;
+ patched.pBindings = bindings;
+ result = data.create_set_layout(device, &patched, allocator, layout);
+ if (debug) fprintf(stderr, "xclipse layer: compute YCbCr immutable samplers replaced (%d)\n", result);
+done:
+ for (uint32_t b = 0; arrays && b < info->bindingCount; b++) free(arrays[b]);
+ free(arrays);
+ free(bindings);
+ return result;
+}
+
+/* ---- dispatch ---- */
+
+static PFN_vkVoidFunction device_hook(const char *name) {
+ if (!strcmp(name, "vkGetDeviceProcAddr")) return NULL; /* handled by the caller */
+ if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)destroy_device;
+ if (!strcmp(name, "vkCreateSampler")) return (PFN_vkVoidFunction)create_sampler;
+ if (!strcmp(name, "vkDestroySampler")) return (PFN_vkVoidFunction)destroy_sampler;
+ if (!strcmp(name, "vkCreateDescriptorSetLayout")) return (PFN_vkVoidFunction)create_set_layout;
+ if (!strcmp(name, "vkGetCalibratedTimestampsKHR")) return (PFN_vkVoidFunction)timestamps_khr;
+ return NULL;
+}
+
+EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *name) {
+ if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
+ PFN_vkVoidFunction hook = device_hook(name);
+ if (hook) return hook;
+ struct device_data data = device ? device_of(device) : (struct device_data){0};
+ return data.next ? data.next(device, name) : NULL;
+}
+
+EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *name) {
+ if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)vkGetInstanceProcAddr;
+ if (!strcmp(name, "vkCreateInstance")) return (PFN_vkVoidFunction)create_instance;
+ if (!strcmp(name, "vkDestroyInstance")) return (PFN_vkVoidFunction)destroy_instance;
+ if (!strcmp(name, "vkCreateDevice")) return (PFN_vkVoidFunction)create_device;
+ if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
+ if (!strcmp(name, "vkGetPhysicalDeviceFeatures")) return (PFN_vkVoidFunction)get_features;
+ if (!strcmp(name, "vkGetPhysicalDeviceFeatures2") || !strcmp(name, "vkGetPhysicalDeviceFeatures2KHR"))
+ return (PFN_vkVoidFunction)get_features2;
+ if (!strcmp(name, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR")) return (PFN_vkVoidFunction)time_domains_khr;
+ if (!strcmp(name, "vkGetPhysicalDeviceFormatProperties")) return (PFN_vkVoidFunction)get_format_properties;
+ if (!strcmp(name, "vkGetPhysicalDeviceFormatProperties2") || !strcmp(name, "vkGetPhysicalDeviceFormatProperties2KHR"))
+ return (PFN_vkVoidFunction)get_format_properties2;
+ PFN_vkVoidFunction hook = device_hook(name);
+ if (hook) return hook;
+ PFN_vkGetInstanceProcAddr next = instance ? instance_of(instance).next : NULL;
+ return next ? next(instance, name) : NULL;
+}
+
+EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *negotiate) {
+ if (!negotiate || negotiate->loaderLayerInterfaceVersion < 2) return VK_ERROR_INITIALIZATION_FAILED;
+ debug = getenv("DROIDDECK_XCLIPSE_LAYER_DEBUG") != NULL;
+ negotiate->loaderLayerInterfaceVersion = 2;
+ negotiate->pfnGetInstanceProcAddr = vkGetInstanceProcAddr;
+ negotiate->pfnGetDeviceProcAddr = vkGetDeviceProcAddr;
+ negotiate->pfnGetPhysicalDeviceProcAddr = NULL;
+ return VK_SUCCESS;
+}
diff --git a/tools/local-cross.Dockerfile b/tools/local-cross.Dockerfile
index 8d143e7caa..c448d02386 100644
--- a/tools/local-cross.Dockerfile
+++ b/tools/local-cross.Dockerfile
@@ -10,6 +10,7 @@ RUN apt-get update \
g++ \
gcc-aarch64-linux-gnu \
g++-aarch64-linux-gnu \
+ libvulkan-dev \
python3 \
zstd \
unzip \
diff --git a/tools/powervr/fetch.py b/tools/powervr/fetch.py
new file mode 100644
index 0000000000..75c8b539e0
--- /dev/null
+++ b/tools/powervr/fetch.py
@@ -0,0 +1,366 @@
+#!/usr/bin/env python3
+"""Assemble the pinned PowerVR components into the APK's isolated Linux runtime.
+
+Like DirectAudio, APK builds download published components rather than compile
+them. Their source, licenses and patches travel with the payload. Build recipes
+remain in tools/{hybris,dxvk,vulkan-wsi}; release.json pins their reviewed inputs.
+"""
+import argparse
+import hashlib
+import io
+import json
+import os
+from pathlib import Path, PurePosixPath
+import posixpath
+import re
+import stat
+import subprocess
+import tarfile
+import tempfile
+from urllib.parse import urlparse
+from urllib.request import urlopen
+from zipfile import ZipFile
+
+
+ROOT = Path(__file__).resolve().parents[2]
+ASSETS = Path("app/src/main/assets/hybris")
+REQUIRED_LIBRARIES = (
+ "lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
+ "lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
+ "wsi/libVkLayer_window_system_integration.so",
+)
+MAX_UNPACKED = 256 * 1024 * 1024
+BUNDLED_LICENSES = {
+ 'tools/vulkan-wsi/licenses/Vulkan-Headers/' + name: 'licenses/Vulkan-Headers/' + name
+ for name in ('LICENSE.md', 'MIT.txt')
+}
+
+
+def sha256(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def json_bytes(value):
+ return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode()
+
+
+def safe_name(name):
+ path = PurePosixPath(name)
+ if not name or path.is_absolute() or ".." in path.parts or "\\" in name:
+ raise ValueError("unsafe archive path: " + name)
+ return str(path)
+
+
+def check_tree(entries):
+ # Never extract through a symlink, even one pointing inside the tree.
+ for name, entry in entries.items():
+ for parent in PurePosixPath(name).parents:
+ if str(parent) in entries:
+ raise ValueError("archive member below a file or symlink: " + name)
+ if entry[0] == "symlink":
+ read(entries, name)
+
+
+def read(entries, name, seen=()):
+ if name in seen or len(seen) > 16:
+ raise ValueError("runtime symlink cycle: " + name)
+ if name not in entries:
+ raise ValueError("missing runtime file: " + name)
+ kind, mode, data = entries[name]
+ if kind == "symlink":
+ if PurePosixPath(data).is_absolute() or "\\" in data:
+ raise ValueError("unsafe runtime symlink: " + name)
+ target = safe_name(posixpath.normpath(posixpath.join(posixpath.dirname(name), data)))
+ return read(entries, target, (*seen, name))
+ return data
+
+
+def read_tar(data):
+ unpacked = subprocess.run(["zstd", "-q", "-dc"], input=data,
+ capture_output=True, check=True).stdout
+ if len(unpacked) > MAX_UNPACKED:
+ raise ValueError("runtime archive exceeds size limit")
+ entries, seen = {}, set()
+ with tarfile.open(fileobj=io.BytesIO(unpacked)) as package:
+ for member in package:
+ name = safe_name(member.name)
+ if name in seen:
+ raise ValueError("duplicate archive path: " + name)
+ seen.add(name)
+ if member.isdir():
+ continue
+ if name == ".":
+ raise ValueError("archive root must be a directory")
+ if member.issym():
+ entries[name] = ("symlink", 0o777, member.linkname)
+ elif member.isfile():
+ entries[name] = ("file", 0o755 if member.mode & 0o111 else 0o644,
+ package.extractfile(member).read())
+ else:
+ raise ValueError("unsupported archive entry type: " + name)
+ check_tree(entries)
+ return entries
+
+
+def tree_digest(entries):
+ return sha256(json_bytes({name: [kind, mode, sha256(data) if kind == "file" else data]
+ for name, (kind, mode, data) in sorted(entries.items())}))
+
+
+def load_release(root):
+ release = json.loads((root / "tools/powervr/release.json").read_bytes())
+ if release.get("format") != 1:
+ raise ValueError("unsupported PowerVR release pins")
+ # These identify the reviewed recipe, not a new attestation from the old
+ # producer. The original build metadata is preserved inside the runtime.
+ for component in [release["hybris"], *release["archives"]]:
+ for name, expected in component["recipe_inputs"].items():
+ if sha256((root / name).read_bytes()) != expected:
+ raise ValueError("PowerVR component recipe changed; update its release pin: " + name)
+ return release
+
+
+def assembly_inputs(root):
+ return {"format": 1, "inputs": {
+ name: sha256((root / name).read_bytes()) for name in
+ ("tools/powervr/release.json", "tools/powervr/fetch.py", "tools/hybris/run-proton.py", *BUNDLED_LICENSES)}}
+
+
+def fetch(component, cache):
+ url = component["url"]
+ if urlparse(url).scheme != "https":
+ raise ValueError("component URL must use HTTPS")
+ cache.mkdir(parents=True, exist_ok=True)
+ target = cache / (component["sha256"] + "-" + PurePosixPath(urlparse(url).path).name)
+
+ def valid(path):
+ return (path.is_file() and path.stat().st_size == component["size"]
+ and sha256(path.read_bytes()) == component["sha256"])
+
+ if valid(target):
+ return target.read_bytes()
+ # No unverified response is ever parsed or promoted into the cache.
+ with tempfile.NamedTemporaryFile(dir=cache, prefix=".download-", delete=False) as output:
+ temporary = Path(output.name)
+ try:
+ with urlopen(url, timeout=60) as response:
+ remaining = component["size"]
+ while block := response.read(min(1024 * 1024, remaining + 1)):
+ remaining -= len(block)
+ if remaining < 0:
+ raise ValueError("component download exceeds pinned size")
+ output.write(block)
+ output.flush()
+ if not valid(temporary):
+ raise ValueError("component download checksum mismatch: " + url)
+ os.replace(temporary, target)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return target.read_bytes()
+
+
+def read_zip(data, component):
+ entries, seen = {}, set()
+ expected = {item["name"]: item for item in component["files"]}
+ allowed = set(expected) | set(component["ignored"])
+ total = 0
+ with ZipFile(io.BytesIO(data)) as archive:
+ for member in archive.infolist():
+ name = safe_name(member.filename)
+ if name in seen:
+ raise ValueError("duplicate archive path: " + name)
+ seen.add(name)
+ mode = member.external_attr >> 16
+ kind = stat.S_IFMT(mode)
+ if member.is_dir() and kind in (0, stat.S_IFDIR):
+ continue
+ if kind not in (0, stat.S_IFREG) or name not in allowed:
+ raise ValueError("unexpected component archive entry: " + name)
+ total += member.file_size
+ if total > MAX_UNPACKED:
+ raise ValueError("component archive exceeds size limit")
+ if name not in expected:
+ continue
+ pin = expected[name]
+ content = archive.read(member)
+ if len(content) != pin["size"] or sha256(content) != pin["sha256"]:
+ raise ValueError("component member checksum mismatch: " + name)
+ path = safe_name(pin["path"])
+ if path in entries:
+ raise ValueError("duplicate component destination: " + path)
+ entries[path] = ("file", pin["mode"], content)
+ if set(expected) - seen:
+ raise ValueError("component archive missing files: " + ", ".join(sorted(set(expected) - seen)))
+ check_tree(entries)
+ return entries
+
+
+def read_tar_gz(data, component):
+ """An upstream release tarball, held to the same per-file pins as a CI archive."""
+ entries, seen = {}, set()
+ expected = {item["name"]: item for item in component["files"]}
+ allowed = set(expected) | set(component["ignored"])
+ total = 0
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
+ for member in archive:
+ name = safe_name(member.name)
+ if name in seen:
+ raise ValueError("duplicate archive path: " + name)
+ seen.add(name)
+ if member.isdir():
+ continue
+ if not member.isfile() or name not in allowed:
+ raise ValueError("unexpected component archive entry: " + name)
+ total += member.size
+ if total > MAX_UNPACKED:
+ raise ValueError("component archive exceeds size limit")
+ if name not in expected:
+ continue
+ pin = expected[name]
+ content = archive.extractfile(member).read()
+ if len(content) != pin["size"] or sha256(content) != pin["sha256"]:
+ raise ValueError("component member checksum mismatch: " + name)
+ path = safe_name(pin["path"])
+ if path in entries:
+ raise ValueError("duplicate component destination: " + path)
+ entries[path] = ("file", pin["mode"], content)
+ if set(expected) - seen:
+ raise ValueError("component archive missing files: " + ", ".join(sorted(set(expected) - seen)))
+ check_tree(entries)
+ return entries
+
+
+def read_component(data, component):
+ kind = component.get("format", "zip")
+ if kind == "zip":
+ return read_zip(data, component)
+ if kind == "tar.gz":
+ return read_tar_gz(data, component)
+ raise ValueError("unsupported component archive format: " + kind)
+
+
+def check_bundle(entries, release, root):
+ check_tree(entries)
+ if read(entries, "assembly-inputs.json") != json_bytes(assembly_inputs(root)):
+ raise ValueError("PowerVR assembly inputs changed; run tools/powervr/fetch.py")
+ if entries["run-proton.py"] != ("file", 0o755, (root / "tools/hybris/run-proton.py").read_bytes()):
+ raise ValueError("PowerVR Proton wrapper is stale or not executable")
+ compile(read(entries, "run-proton.py"), "run-proton.py", "exec")
+ bridge = dict(entries)
+ del bridge["assembly-inputs.json"], bridge["run-proton.py"]
+ for source, target in BUNDLED_LICENSES.items():
+ if entries.get(target) != ("file", 0o644, (root / source).read_bytes()):
+ raise ValueError("Vulkan-Headers license missing or stale: " + target)
+ for component in release["archives"]:
+ for pin in component["files"]:
+ content = read(entries, pin["path"])
+ if (entries[pin["path"]][:2] != ("file", pin["mode"])
+ or len(content) != pin["size"] or sha256(content) != pin["sha256"]):
+ raise ValueError("PowerVR component mismatch: " + pin["path"])
+ del bridge[pin["path"]]
+ for target in BUNDLED_LICENSES.values():
+ bridge.pop(target, None)
+ if tree_digest(bridge) != release["hybris"]["tree_sha256"]:
+ raise ValueError("PowerVR bridge differs from the pinned archive")
+ for name in REQUIRED_LIBRARIES:
+ content = read(entries, name)
+ if content[:6] != b"\x7fELF\x02\x01" or content[18:20] != b"\xb7\x00":
+ raise ValueError("runtime library is not ELF64 AArch64: " + name)
+ # dxvk/ is the default payload; run-proton.py can select another dxvk-* sibling by name.
+ payloads = sorted({name.split("/")[0] for name in entries if re.fullmatch(r"dxvk[^/]*/x(32|64)/[^/]+\.dll", name)})
+ if "dxvk" not in payloads:
+ raise ValueError("default DXVK payload missing")
+ for payload in payloads:
+ for architecture, machine, magic in (("x32", b"\x4c\x01", b"\x0b\x01"),
+ ("x64", b"\x64\x86", b"\x0b\x02")):
+ for name in ("d3d8.dll", "d3d9.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll"):
+ path = payload + "/" + architecture + "/" + name
+ content = read(entries, path)
+ pe = int.from_bytes(content[60:64], "little")
+ if (content[:2] != b"MZ" or pe < 64 or content[pe:pe + 4] != b"PE\0\0"
+ or content[pe + 4:pe + 6] != machine or content[pe + 24:pe + 26] != magic):
+ raise ValueError("DXVK library has wrong PE architecture: " + path)
+
+
+def pack(entries):
+ stream = io.BytesIO()
+ directories = {str(parent) for name in entries for parent in PurePosixPath(name).parents
+ if str(parent) != "."}
+ with tarfile.open(fileobj=stream, mode="w", format=tarfile.USTAR_FORMAT) as archive:
+ for name in sorted(directories | set(entries)):
+ info = tarfile.TarInfo(name)
+ info.mtime = info.uid = info.gid = 0
+ if name in directories:
+ info.type, info.mode = tarfile.DIRTYPE, 0o755
+ archive.addfile(info)
+ continue
+ kind, info.mode, data = entries[name]
+ if kind == "symlink":
+ info.type, info.linkname = tarfile.SYMTYPE, data
+ archive.addfile(info)
+ else:
+ info.size = len(data)
+ archive.addfile(info, io.BytesIO(data))
+ return subprocess.run(["zstd", "-q", "-10", "-T1", "-c"], input=stream.getvalue(),
+ capture_output=True, check=True).stdout
+
+
+def verify_archive(archive, version, root=ROOT):
+ release = load_release(root)
+ if sha256(archive) != version.strip():
+ raise ValueError("PowerVR runtime archive checksum mismatch")
+ check_bundle(read_tar(archive), release, root)
+
+
+def verify(root=ROOT):
+ verify_archive((root / ASSETS / "runtime.tzst").read_bytes(),
+ (root / ASSETS / "version.txt").read_text(), root)
+
+
+def assemble(root, cache):
+ release = load_release(root)
+ entries = read_tar(fetch(release["hybris"], cache))
+ if tree_digest(entries) != release["hybris"]["tree_sha256"]:
+ raise ValueError("PowerVR bridge tree checksum mismatch")
+ for component in release["archives"]:
+ additions = read_component(fetch(component, cache), component)
+ if set(entries) & set(additions):
+ raise ValueError("component overwrites existing runtime files")
+ entries.update(additions)
+ for source, target in BUNDLED_LICENSES.items():
+ license_entry = ("file", 0o644, (root / source).read_bytes())
+ if target in entries and entries[target] != license_entry:
+ raise ValueError("bundled license overwrites component file: " + target)
+ entries[target] = license_entry
+ entries["run-proton.py"] = ("file", 0o755, (root / "tools/hybris/run-proton.py").read_bytes())
+ entries["assembly-inputs.json"] = ("file", 0o644, json_bytes(assembly_inputs(root)))
+ check_bundle(entries, release, root)
+ archive = pack(entries)
+ assets = root / ASSETS
+ assets.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=assets.parent, prefix=".hybris-") as directory:
+ stage = Path(directory)
+ (stage / "runtime.tzst").write_bytes(archive)
+ (stage / "version.txt").write_text(sha256(archive) + "\n")
+ # version.txt is the readiness marker; an interrupted replacement fails
+ # closed instead of presenting a partially updated payload as ready.
+ (assets / "version.txt").unlink(missing_ok=True)
+ os.replace(stage / "runtime.tzst", assets / "runtime.tzst")
+ os.replace(stage / "version.txt", assets / "version.txt")
+ print("PowerVR runtime prepared: " + sha256(archive))
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--verify", action="store_true")
+ parser.add_argument("--cache-dir", type=Path, default=Path(os.environ.get(
+ "DROIDDECK_BUILD_CACHE", str(Path.home() / ".cache/droiddeck-build"))))
+ args = parser.parse_args()
+ if args.verify:
+ verify()
+ else:
+ assemble(ROOT, args.cache_dir)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/powervr/release.json b/tools/powervr/release.json
new file mode 100644
index 0000000000..dd5496a372
--- /dev/null
+++ b/tools/powervr/release.json
@@ -0,0 +1,335 @@
+{
+ "archives": [
+ {
+ "files": [
+ {
+ "mode": 493,
+ "name": "x32/d3d8.dll",
+ "path": "dxvk/x32/d3d8.dll",
+ "sha256": "c9612be6aac99390156cdcd3b22054fba62cf68bfc948d753cc39282d37f67ab",
+ "size": 1658894
+ },
+ {
+ "mode": 493,
+ "name": "x32/d3d9.dll",
+ "path": "dxvk/x32/d3d9.dll",
+ "sha256": "fbd0e7d7aae39d5d623757ead228930c4be78cb3b16db6f352796577831ce36e",
+ "size": 7598094
+ },
+ {
+ "mode": 493,
+ "name": "x32/d3d10core.dll",
+ "path": "dxvk/x32/d3d10core.dll",
+ "sha256": "cd6052b1f6a02ab94fea5bfa3519e556fb353f585da4b64e3c810ef4cc37c808",
+ "size": 192526
+ },
+ {
+ "mode": 493,
+ "name": "x32/d3d11.dll",
+ "path": "dxvk/x32/d3d11.dll",
+ "sha256": "9bf51b5ab913e1bd84513b2b1608586bc0a651788df9e664b8135840b8c8c54d",
+ "size": 7942158
+ },
+ {
+ "mode": 493,
+ "name": "x32/dxgi.dll",
+ "path": "dxvk/x32/dxgi.dll",
+ "sha256": "d3772dc86267fe94eee7afc30c993f44297fd43b50210f1691f3d03ebf4d4402",
+ "size": 5738510
+ },
+ {
+ "mode": 493,
+ "name": "x64/d3d8.dll",
+ "path": "dxvk/x64/d3d8.dll",
+ "sha256": "cd870a8f5cdbfef33e7ccf7884d6f1c442e2c8ec22d6adea60fea3dbe83c32e2",
+ "size": 1499136
+ },
+ {
+ "mode": 493,
+ "name": "x64/d3d9.dll",
+ "path": "dxvk/x64/d3d9.dll",
+ "sha256": "4f80af96991073bb3dc25f3b93ec2c07ba25fcabb8a6e30ffd5eaae38c8465c7",
+ "size": 6934528
+ },
+ {
+ "mode": 493,
+ "name": "x64/d3d10core.dll",
+ "path": "dxvk/x64/d3d10core.dll",
+ "sha256": "4950e952ca291b13c0645322f1831414e77df87183ed2f81d5dde02c1fd43ff9",
+ "size": 978944
+ },
+ {
+ "mode": 493,
+ "name": "x64/d3d11.dll",
+ "path": "dxvk/x64/d3d11.dll",
+ "sha256": "3497d5f7dc78fa7affdba6777d3ab4aac7ec744d7e2c795fbf07dbff54058e6c",
+ "size": 7143424
+ },
+ {
+ "mode": 493,
+ "name": "x64/dxgi.dll",
+ "path": "dxvk/x64/dxgi.dll",
+ "sha256": "d6e0ca242dba6cb8606106a7fcb65268225520f03c68e36a365f44d65f863e74",
+ "size": 5230592
+ },
+ {
+ "mode": 420,
+ "name": "LICENSE",
+ "path": "licenses/dxvk-LICENSE",
+ "sha256": "a5cb1a6ded7d2d7e92d550ba28edd21be2d1d4044662b399887351023e30ce64",
+ "size": 1074
+ },
+ {
+ "mode": 420,
+ "name": "source-commit",
+ "path": "provenance/dxvk-source-commit",
+ "sha256": "cb748e54f2fcdca516189435647ea001dbd14f97e2df5b36fd2f13fc185a5dbf",
+ "size": 41
+ },
+ {
+ "mode": 420,
+ "name": "SHA256SUMS",
+ "path": "provenance/dxvk-SHA256SUMS",
+ "sha256": "8a106cb90288052cc91768b569980ed7381c89591fb7cea3bc6d0312c6f30a47",
+ "size": 802
+ },
+ {
+ "mode": 420,
+ "name": "downstream.patch",
+ "path": "licenses/dxvk-downstream.patch",
+ "sha256": "e44b8d656a37c3b1059bbf3dcbcf11922a00634301f2509024fb263a45e9f50e",
+ "size": 3604
+ },
+ {
+ "mode": 420,
+ "name": "source.tar.zst",
+ "path": "licenses/dxvk-source.tar.zst",
+ "sha256": "dfdebe8aa71b85af638f2565c1d5abe31417c6db643a827bcf0988e29ded55e7",
+ "size": 6043001
+ },
+ {
+ "mode": 420,
+ "name": "submodules.txt",
+ "path": "provenance/dxvk-submodules.txt",
+ "sha256": "01e74c750ca473590e17f1ca33f204b8272f84898ee6e8a8509be9740919092c",
+ "size": 472
+ }
+ ],
+ "id": "dxvk",
+ "ignored": [
+ "x32/d3d10core.dll.a",
+ "x32/d3d11.dll.a",
+ "x32/d3d8.dll.a",
+ "x32/d3d9.dll.a",
+ "x32/dxgi.dll.a",
+ "x64/d3d10core.dll.a",
+ "x64/d3d11.dll.a",
+ "x64/d3d8.dll.a",
+ "x64/d3d9.dll.a",
+ "x64/dxgi.dll.a"
+ ],
+ "provenance": {
+ "ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38119192562",
+ "repository_commit": "aee0ebd43557ef9964ba7f6a11d7d30efaf983ac"
+ },
+ "recipe_inputs": {
+ "tools/dxvk/build.sh": "f37efdc1dbcc511b0399e1027d582dfd09f689bddb434eed31c33d88867460ad",
+ "tools/dxvk/check_present_sync.py": "42e2a590e17c1f53e5cd4100ef3d19a5bdcce31a6d7a18fbf9961f4ef27d5063",
+ "tools/dxvk/patches/0001-check-direct3d-bc-formats.patch": "d38fc4d773b7974498dcb377dbaa883c9bba36aefa3235b39bca69d6dd220c77",
+ "tools/dxvk/patches/0002-present-semaphore-per-swapchain-image.patch": "c802789a33099d3efc3413a297e2b752f8eb84c18cbfbdfc04e188f4090410d0",
+ "tools/dxvk/source.env": "e49b0757f203f88783360c06118f60945242fde8738419e0b27cf2531bf3a365"
+ },
+ "sha256": "d08dd962ced3482883ad9e9eb4903a4d27a3756b4f989a97ecdfcccb53fbee66",
+ "size": 24063241,
+ "url": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261011.3/dxvk-aee0ebd.zip"
+ },
+ {
+ "files": [
+ {
+ "mode": 420,
+ "name": "libVkLayer_window_system_integration.so",
+ "path": "wsi/libVkLayer_window_system_integration.so",
+ "sha256": "d07b961181b9547fd48ad9f05cc6d3b808b824676eb5a186fe3feb8caa013f19",
+ "size": 436888
+ },
+ {
+ "mode": 420,
+ "name": "VkLayer_window_system_integration.json",
+ "path": "wsi/VkLayer_window_system_integration.json",
+ "sha256": "a1df8b1cee7315015d8fe82534451e373ae4d9cb2adfc232c68346ecbf2818ee",
+ "size": 3683
+ },
+ {
+ "mode": 420,
+ "name": "LICENSE",
+ "path": "licenses/wsi-LICENSE",
+ "sha256": "5eb8d2da52230d2d66ce078a89ae0173aac63e2e73bed5f907a34736d114ea30",
+ "size": 1086
+ },
+ {
+ "mode": 420,
+ "name": "source-commit",
+ "path": "provenance/wsi-source-commit",
+ "sha256": "8367150b20502af36c472651850694a15a3e2a1fd6b6beb1f6e12a85a97824f5",
+ "size": 41
+ },
+ {
+ "mode": 420,
+ "name": "SHA256SUMS",
+ "path": "provenance/wsi-SHA256SUMS",
+ "sha256": "fda6f61028659648801de0e3a6fe1676efd99e1551881a5db8630970eae86158",
+ "size": 108
+ },
+ {
+ "mode": 420,
+ "name": "downstream.patch",
+ "path": "licenses/wsi-downstream.patch",
+ "sha256": "e2ed113d22f05563248ef606c774c22658b184fbc05912229007cd5281027e78",
+ "size": 769
+ },
+ {
+ "mode": 420,
+ "name": "source.tar.zst",
+ "path": "licenses/wsi-source.tar.zst",
+ "sha256": "22ae7c2d8aa3dfffdda601c3442d1966ab53ad225acdfadee69ba38974d0c4c5",
+ "size": 209468
+ },
+ {
+ "mode": 420,
+ "name": "vulkan-headers-commit",
+ "path": "provenance/wsi-vulkan-headers-commit",
+ "sha256": "16706d6cdbeb788426a90d66574dfd71068c4d993d39e76ec5c281b1f30dc7a6",
+ "size": 41
+ }
+ ],
+ "id": "wsi",
+ "ignored": [],
+ "provenance": {
+ "ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38047627963",
+ "repository_commit": "abe58618a5194f1f15499cbd5f9ec75503782556",
+ "vulkan_headers_licenses": {
+ "note": "Added from tracked assembly inputs; the original WSI archive and compiled library are unchanged.",
+ "revision": "8d6039a455a7ecc7d2a592ff97f62db4e59b70bf",
+ "source_urls": [
+ "https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/8d6039a455a7ecc7d2a592ff97f62db4e59b70bf/LICENSE.md",
+ "https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/8d6039a455a7ecc7d2a592ff97f62db4e59b70bf/LICENSES/MIT.txt"
+ ]
+ }
+ },
+ "recipe_inputs": {
+ "tools/vulkan-wsi/build.sh": "9e403151c58e6b2ee15241f525c4bacb2495f072191da6a63065e7fcc25b3b3c",
+ "tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md": "95ad366d23fadf701d355bc45fb8b82ae2d700239471d35d41286ac3b08ff903",
+ "tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt": "1ca3502222d967f3be5751c55f6b7ee735b5383909c3b501495f54b216dbf227",
+ "tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch": "e2ed113d22f05563248ef606c774c22658b184fbc05912229007cd5281027e78",
+ "tools/vulkan-wsi/source.env": "71a88087265a09b4ce06e7c9b98ef6799c6a7657cc6ef9084de663e96f5cfe63"
+ },
+ "sha256": "348f9ec42159c1ee6e2baba4312a5e845d26687238f29e3f4a1b0c3c97e13b3c",
+ "size": 362717,
+ "url": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261010.4/wsi-abe5861.zip"
+ },
+ {
+ "files": [
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x32/d3d10core.dll",
+ "path": "dxvk-2.6.2/x32/d3d10core.dll",
+ "sha256": "b34b479fa0bce29eba6dcff5b1f8584c2ae699d53a123668590f8a2b84e84094",
+ "size": 176142
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x32/d3d11.dll",
+ "path": "dxvk-2.6.2/x32/d3d11.dll",
+ "sha256": "858d1a848dd5023191cb16cd986e0f00008faf5df8a87b5c835b56cf4b646910",
+ "size": 4845582
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x32/d3d8.dll",
+ "path": "dxvk-2.6.2/x32/d3d8.dll",
+ "sha256": "617459c8d1239f98687f8157bdaec85738ee4699885ed7d1ff13deb32609c759",
+ "size": 1658894
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x32/d3d9.dll",
+ "path": "dxvk-2.6.2/x32/d3d9.dll",
+ "sha256": "00bc142e98ddad1e334a4d88fa630038e092b0758b3d79e295172b181a4c772d",
+ "size": 4460558
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x32/dxgi.dll",
+ "path": "dxvk-2.6.2/x32/dxgi.dll",
+ "sha256": "67d7ca4a4f8f66baabd381c73b52a8e85870083e868ed474a4bc58b7da486883",
+ "size": 3137550
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x64/d3d10core.dll",
+ "path": "dxvk-2.6.2/x64/d3d10core.dll",
+ "sha256": "565154a0763c6460843fe47e5aaec62e609163d9995a922d5e19e85027fe2f88",
+ "size": 155662
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x64/d3d11.dll",
+ "path": "dxvk-2.6.2/x64/d3d11.dll",
+ "sha256": "5b63515a432d19302f7dc81dd2ee5bf40043683b5064a2bce03a2b6d27dcce5d",
+ "size": 4399118
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x64/d3d8.dll",
+ "path": "dxvk-2.6.2/x64/d3d8.dll",
+ "sha256": "dfd837c3467eeb15f69a773e18bbc0550cb69c9e33d5d57b4ea42c5f63bfdc4b",
+ "size": 1544206
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x64/d3d9.dll",
+ "path": "dxvk-2.6.2/x64/d3d9.dll",
+ "sha256": "01e7ae2b0544b6031fe695fd16fbc76786ded57fdbe3f6bd11eee7c98d2c370d",
+ "size": 4108302
+ },
+ {
+ "mode": 493,
+ "name": "dxvk-2.6.2/x64/dxgi.dll",
+ "path": "dxvk-2.6.2/x64/dxgi.dll",
+ "sha256": "074616e1af172edf175f3fc6ed7ca30f6c685a70875eed3af10797a10840ed39",
+ "size": 2891790
+ }
+ ],
+ "format": "tar.gz",
+ "id": "dxvk-xclipse",
+ "ignored": [],
+ "provenance": {
+ "note": "Unmodified upstream release, selected on Samsung Xclipse: its 128 bytes of push constants predate DXVK 3's 256-byte requirement. Covered by the zlib license already shipped as licenses/dxvk-LICENSE.",
+ "upstream_release": "https://github.com/doitsujin/dxvk/releases/tag/v2.6.2"
+ },
+ "recipe_inputs": {},
+ "sha256": "17761876556afd55736cb895d184f5a1c55d43350f1b1e3b129f8d28706d7992",
+ "size": 10107492,
+ "url": "https://github.com/doitsujin/dxvk/releases/download/v2.6.2/dxvk-2.6.2.tar.gz"
+ }
+ ],
+ "format": 1,
+ "hybris": {
+ "provenance": {
+ "apk_ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38123715308",
+ "extracted_from_apk": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261011.3/DroidDeck-0.3.2-1b6185b.apk",
+ "note": "APK build reused a cached bridge. Original source and compiler metadata are preserved in build-manifest.json; no APK commit is claimed as the bridge producer.",
+ "upstream_source_commit": "bc8cb3586b79d208fd21b925fa0209b3e432e008"
+ },
+ "recipe_inputs": {
+ "tools/hybris/build_runtime.sh": "bc83472ecfd886841c8c2c436080cdee0a27ce0d860ffbffe45a75fbc6b2b21d",
+ "tools/hybris/patches/0001-dxvk-bc-profile.patch": "b90605e51256595de4453352865aa198e59bd2d392ac6b7c2a60f38c57727c9d",
+ "tools/hybris/powervr-hal-version.patch": "d3ed8ca03e5a874b9dc46651983117760c7490b96127335625d0480a2b85e66f",
+ "tools/hybris/source.env": "9ae7985f2052dbcc8b9666494bc8a711ec85013f6a27d6d72d9729c32b919dd8"
+ },
+ "sha256": "f4f12c26ed21003c2c98a7cececd76c8a3b332d79ece9d1f963cf3b9e8943978",
+ "size": 5552486,
+ "tree_sha256": "de9cc2c4107bf396e4f963d7e91f936a966593fb1df680a0b5d43db0f9fef4e1",
+ "url": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261011.3/hybris-runtime-f4f12c26.tzst"
+ }
+}
diff --git a/tools/release/check_session_assets.py b/tools/release/check_session_assets.py
index 89d05f01b3..11564e894a 100644
--- a/tools/release/check_session_assets.py
+++ b/tools/release/check_session_assets.py
@@ -1,5 +1,6 @@
"""Reject an APK with missing or stale session helpers, including cached local bundles."""
from pathlib import Path
+import importlib.util
import sys
from zipfile import ZipFile
@@ -33,6 +34,16 @@ def check(apk, overlay=OVERLAY):
continue
if content != source.read_bytes():
errors.append('stale ' + asset)
+ if overlay == OVERLAY:
+ spec = importlib.util.spec_from_file_location('powervr_fetch',
+ OVERLAY.parents[1] / 'powervr/fetch.py')
+ runtime = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(runtime)
+ try:
+ runtime.verify_archive(package.read('assets/hybris/runtime.tzst'),
+ package.read('assets/hybris/version.txt').decode('ascii'))
+ except (KeyError, ValueError, OSError) as error:
+ errors.append('invalid PowerVR runtime: ' + str(error))
return errors
diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py
index eaccde51ee..6c2dfb461e 100644
--- a/tools/release/runtime_inputs.py
+++ b/tools/release/runtime_inputs.py
@@ -1,6 +1,7 @@
"""Attest prepared runtime inputs and reject stale local or CI APK payloads."""
import hashlib
import gzip
+import importlib.util
import json
from pathlib import Path
import subprocess
@@ -16,6 +17,7 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/comet', 'tools/build_local.sh',
+ 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
@@ -42,7 +44,7 @@ def sources(root):
def outputs(root):
result = {}
- for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal']:
+ for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']:
base = root / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
@@ -67,6 +69,8 @@ def required():
paths += ['assets/linuxfs/i386/libfaultreport.so']
paths += ['assets/linuxfs/usr/local/lib/droiddeck-msitools/' + name for name in
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
+ paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in
+ ['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']]
paths += ['assets/linuxfs/usr/local/lib/mangoapp/' + name for name in
['mangoapp', 'libfmt.so.10', 'libspdlog.so.1.13', 'libglfw.so.3', 'libtraceevent.so.1', 'libtracefs.so.1']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-comet/' + name for name in
@@ -81,9 +85,17 @@ def required():
paths += ['assets/desktop-removal/' + name for name in
['lxqt-r1.tsv.gzip', 'kde-remove.tsv.gzip', 'kde-keep.txt.gzip',
'emulators-keep.txt.gzip', 'versions.txt', 'sources.json']]
+ paths += ['assets/hybris/runtime.tzst', 'assets/hybris/version.txt']
return paths
+def verify_powervr(root):
+ spec = importlib.util.spec_from_file_location('powervr_fetch', ROOT / 'tools/powervr/fetch.py')
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module.verify(root)
+
+
def record(root=ROOT):
# Refresh scripts even on a CI native-cache hit; these are source, not cached binaries.
if root == ROOT:
@@ -96,6 +108,7 @@ def record(root=ROOT):
missing = [name for name in required() if name not in paths or not (root / paths[name]).is_file()]
if missing:
raise ValueError('Missing runtime inputs:\n' + '\n'.join(missing))
+ verify_powervr(root)
for name, path in paths.items():
if name.startswith('assets/desktop-removal/') and name.endswith('.gzip'):
try:
diff --git a/tools/test_local.sh b/tools/test_local.sh
index a2a69da629..8cd05467c0 100755
--- a/tools/test_local.sh
+++ b/tools/test_local.sh
@@ -6,7 +6,7 @@ cd "$repo_root"
if [[ $(uname -s) == Linux ]]; then
exec python3 -m unittest discover -s tools/tests "$@"
fi
-image=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
+image=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v4}
python3 tools/docker_preflight.py "$image"
exec docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" \
-v "$repo_root:/src:ro" -w /src "$image" python3 -m unittest discover -s tools/tests "$@"
diff --git a/tools/tests/drm_handles_test.c b/tools/tests/drm_handles_test.c
new file mode 100644
index 0000000000..2e5ce8c8f8
--- /dev/null
+++ b/tools/tests/drm_handles_test.c
@@ -0,0 +1,277 @@
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+/* 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");
+}
diff --git a/tools/tests/test_drm_handles.py b/tools/tests/test_drm_handles.py
new file mode 100644
index 0000000000..5f638a2b4c
--- /dev/null
+++ b/tools/tests/test_drm_handles.py
@@ -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()
diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py
index 6b2362faa6..9c31d2aae4 100644
--- a/tools/tests/test_game_environment.py
+++ b/tools/tests/test_game_environment.py
@@ -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)
diff --git a/tools/tests/test_gamescope_backend.py b/tools/tests/test_gamescope_backend.py
new file mode 100644
index 0000000000..f995d1f60b
--- /dev/null
+++ b/tools/tests/test_gamescope_backend.py
@@ -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)
diff --git a/tools/tests/test_powervr_runtime.py b/tools/tests/test_powervr_runtime.py
new file mode 100644
index 0000000000..475f899279
--- /dev/null
+++ b/tools/tests/test_powervr_runtime.py
@@ -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()
diff --git a/tools/tests/test_proton_wrapper.py b/tools/tests/test_proton_wrapper.py
new file mode 100644
index 0000000000..175d4600a5
--- /dev/null
+++ b/tools/tests/test_proton_wrapper.py
@@ -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()
diff --git a/tools/tests/test_runtime_inputs.py b/tools/tests/test_runtime_inputs.py
index 92c045314e..8820983f11 100644
--- a/tools/tests/test_runtime_inputs.py
+++ b/tools/tests/test_runtime_inputs.py
@@ -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')
diff --git a/tools/tests/test_steam_helper_affinity.py b/tools/tests/test_steam_helper_affinity.py
new file mode 100644
index 0000000000..97549ac05d
--- /dev/null
+++ b/tools/tests/test_steam_helper_affinity.py
@@ -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()
diff --git a/tools/tests/test_steam_presentation.py b/tools/tests/test_steam_presentation.py
new file mode 100644
index 0000000000..21ce81b0d4
--- /dev/null
+++ b/tools/tests/test_steam_presentation.py
@@ -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()
diff --git a/tools/tests/test_vk_external_image_sync.py b/tools/tests/test_vk_external_image_sync.py
new file mode 100644
index 0000000000..a82dac25de
--- /dev/null
+++ b/tools/tests/test_vk_external_image_sync.py
@@ -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()
diff --git a/tools/tests/test_xclipse_layer.py b/tools/tests/test_xclipse_layer.py
new file mode 100644
index 0000000000..36042c9c7e
--- /dev/null
+++ b/tools/tests/test_xclipse_layer.py
@@ -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()
diff --git a/tools/tests/vk_external_image_sync_test.c b/tools/tests/vk_external_image_sync_test.c
new file mode 100644
index 0000000000..c6114d2572
--- /dev/null
+++ b/tools/tests/vk_external_image_sync_test.c
@@ -0,0 +1,63 @@
+#include
+#include
+#include
+
+#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;
+}
diff --git a/tools/tests/xclipse_layer_test.c b/tools/tests/xclipse_layer_test.c
new file mode 100644
index 0000000000..26105d69f2
--- /dev/null
+++ b/tools/tests/xclipse_layer_test.c
@@ -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
+
+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;
+}
diff --git a/tools/vulkan-wsi/build.sh b/tools/vulkan-wsi/build.sh
new file mode 100755
index 0000000000..cf5a1c3560
--- /dev/null
+++ b/tools/vulkan-wsi/build.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+# CI build of a vendor-neutral X11 surface/swapchain layer.
+set -euo pipefail
+root=$(cd "$(dirname "$0")/../.." && pwd)
+. "$root/tools/vulkan-wsi/source.env"
+mkdir -p "${1:?output directory required}"
+out=$(cd "$1" && pwd)
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+fetch() {
+ git init -q "$3"
+ git -C "$3" fetch --depth=1 "$1" "$2"
+ git -C "$3" checkout -q --detach FETCH_HEAD
+ test "$(git -C "$3" rev-parse HEAD)" = "$2"
+}
+fetch https://github.com/ginkage/vulkan-wsi-layer.git "$WSI_REVISION" "$work/source"
+fetch https://github.com/KhronosGroup/Vulkan-Headers.git "$VULKAN_HEADERS_REVISION" "$work/headers"
+git -C "$work/source" apply --check "$root/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch"
+git -C "$work/source" apply "$root/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch"
+cmake -S "$work/source" -B "$work/build" -G Ninja -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_INSTALL_PREFIX=/usr -DVULKAN_CXX_INCLUDE="$work/headers/include" \
+ -DBUILD_WSI_HEADLESS=OFF -DBUILD_WSI_WAYLAND=OFF -DBUILD_WSI_DISPLAY=OFF -DBUILD_WSI_X11=ON \
+ -DSELECT_EXTERNAL_ALLOCATOR=dma_buf_heaps -DWSIALLOC_MEMORY_HEAP_NAME=system -DKERNEL_HEADER_DIR=/usr/include
+cmake --build "$work/build" --parallel 4
+DESTDIR="$work/stage" cmake --install "$work/build"
+cp "$work/stage/usr/share/vulkan/implicit_layer.d/"* "$out/"
+cp "$root/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch" "$out/downstream.patch"
+cp "$work/source/LICENSE" "$out/LICENSE"
+mkdir -p "$out/licenses/Vulkan-Headers"
+cp "$root/tools/vulkan-wsi/licenses/Vulkan-Headers/"* "$out/licenses/Vulkan-Headers/"
+printf '%s\n' "$WSI_REVISION" > "$out/source-commit"
+printf '%s\n' "$VULKAN_HEADERS_REVISION" > "$out/vulkan-headers-commit"
+tar --exclude-vcs --zstd -cf "$out/source.tar.zst" -C "$work/source" .
+(cd "$out" && sha256sum ./*.so > SHA256SUMS)
diff --git a/tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md b/tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md
new file mode 100644
index 0000000000..17cf4a17d6
--- /dev/null
+++ b/tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md
@@ -0,0 +1,19 @@
+Copyright 2015-2026 The Khronos Group Inc.
+
+Files in this repository fall under one of these licenses:
+
+- `Apache-2.0`
+- `MIT`
+
+Note: With the exception of `parse_dependency.py`, which is based on an
+external file, files using the `MIT` license also fall under `Apache-2.0`.
+Example:
+
+```
+SPDX-License-Identifier: Apache-2.0 OR MIT
+```
+
+Full license text of these licenses is available at:
+
+ * Apache-2.0: https://opensource.org/licenses/Apache-2.0
+ * MIT: https://opensource.org/licenses/MIT
diff --git a/tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt b/tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt
new file mode 100644
index 0000000000..8495fe9e90
--- /dev/null
+++ b/tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2015-2023 The Khronos Group Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch b/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch
new file mode 100644
index 0000000000..da605feaaa
--- /dev/null
+++ b/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch
@@ -0,0 +1,16 @@
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -421,6 +421,13 @@
+ cp ${PROJECT_SOURCE_DIR}/layer/VkLayer_window_system_integration.json ${CMAKE_CURRENT_BINARY_DIR}
+ ${JSON_COMMANDS})
+
++# X11 DRI3 uses these shared sources even when Wayland and display are disabled.
++if(BUILD_WSI_X11 AND NOT BUILD_WSI_WAYLAND AND NOT BUILD_WSI_DISPLAY)
++ target_sources(${PROJECT_NAME} PRIVATE
++ wsi/extensions/external_memory_extension.cpp
++ wsi/image_backing_memory_external.cpp)
++endif()
++
+ # Install the layer and its manifest into a Vulkan implicit layer directory. Upstream leaves this to
+ # manual copying; the fork adds install rules so the Debian package picks up the .so and JSON.
+ install(TARGETS ${PROJECT_NAME} DESTINATION share/vulkan/implicit_layer.d/)
diff --git a/tools/vulkan-wsi/source.env b/tools/vulkan-wsi/source.env
new file mode 100644
index 0000000000..4c6e9f7a3b
--- /dev/null
+++ b/tools/vulkan-wsi/source.env
@@ -0,0 +1,2 @@
+WSI_REVISION=40cfec09d0e2d42c5e1f2642cf4cba11e7008112
+VULKAN_HEADERS_REVISION=8d6039a455a7ecc7d2a592ff97f62db4e59b70bf