Merge main into playstore for 0.6.9.2 (version code 20)

Brings the main fixes and features since 8a8bb2053 to the Play line.
Main's new code keeps the Play gates: bundled PRoot, AddonPack and
ComponentDownloads gates, the SDK guards, PackageInfoCompat and the
accessibility consent check, which now also covers system-key capture.
The accessibility disclosure is rewritten in every locale to describe
the hardware-keyboard keys it keeps in a session. The MaliBridge server
task uses the AGP NDK provider. Review notes are in tools/playstore/POLICY.md.
This commit is contained in:
maxjivi05 committed 2026-11-06 06:15:35 -05:00
commit 95cb9159de
517 files changed
+46804 -2489

No files matched your search

+16 -2
View File
@@ -41,6 +41,10 @@ if [[ ! -x "${java_dir}/bin/java" ]]; then
echo "Java 17 not found at ${java_dir}; set JAVA_HOME." >&2
exit 1
fi
if [[ ! -f "${repo_root}/external/MaliBridge/scripts/build-client-linux.sh" ]]; then
echo "external/MaliBridge is empty; run: git submodule update --init" >&2
exit 1
fi
if ! command -v docker >/dev/null 2>&1; then
echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2
exit 1
@@ -111,9 +115,10 @@ image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
docker run --rm --platform "${docker_platform}" \
--user "$(id -u):$(id -g)" \
-v "${repo_root}:/src" -w /src "${image_name}" bash -lc '
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
set -euo pipefail
d=app/src/main/assets/linuxfs
mkdir -p "$d"
@@ -134,7 +139,15 @@ docker run --rm --platform "${docker_platform}" \
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"
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
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"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
@@ -158,7 +171,7 @@ x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
docker run --rm --platform linux/amd64 \
-v "${repo_root}:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
@@ -411,6 +424,7 @@ if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
fi
python3 tools/powervr/fetch.py
bash tools/packs/build.sh app/build/packs
python3 tools/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
+2 -1
View File
@@ -6,7 +6,8 @@ image=${DROIDDECK_BUILD_IMAGE}
platform=${DROIDDECK_DOCKER_PLATFORM}
rust_cache="${HOME}/.cache/droiddeck-comet-rust${platform#linux/amd64}"
rust_cache=${rust_cache/\/arm64/-arm64}
docker run --rm --platform "$platform" -v "$repo:/src" \
git_common=$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir)
docker run --rm --platform "$platform" -v "$repo:/src" -v "$git_common:$git_common" \
-v "${rust_cache}:/rust" -w /src \
-e CARGO_HOME=/rust/cargo -e RUSTUP_HOME=/rust/rustup "$image" bash -lc '
set -euo pipefail
+3
View File
@@ -34,6 +34,9 @@ def identity(name, root=ROOT):
for name_ in sorted(set(paths)):
if '__pycache__' in name_ or name_.endswith(('.pyc', '.md')):
continue
if (root / name_).is_dir():
values[name_] = subprocess.check_output(['git', 'ls-files', '--stage', '--', name_], cwd=root, text=True).split()[1]
continue
content = (root / name_).read_bytes()
if b'\0' not in content:
content = content.replace(b'\r\n', b'\n')
+17 -1
View File
@@ -23,7 +23,8 @@
"outputs": [
"app/src/main/assets/linuxfs/usr/local/bin/gamescope",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so"
],
"ndk": true,
"packages": [
@@ -225,6 +226,21 @@
"xz-utils"
]
},
"vkbridge": {
"script": "tools/components/recipes/vkbridge.sh",
"inputs": [
"external/MaliBridge",
"tools/components/recipes/vkbridge.sh"
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"app/src/main/assets/linuxfs/usr/local/share/vkbridge/droidbridge_icd.json",
"app/src/main/assets/linuxfs/usr/local/bin/droiddeck-vkbridge-smoke"
],
"packages": [
"gcc-aarch64-linux-gnu"
]
},
"dirt-ws2": {
"script": "tools/components/recipes/dirt-ws2.sh",
"inputs": [
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
test -f external/MaliBridge/scripts/build-client-linux.sh
bash external/MaliBridge/scripts/build-client-linux.sh app/src/main/assets/linuxfs aarch64-linux-gnu-gcc
+1 -1
View File
@@ -4,7 +4,7 @@ if [[ -z "${docker_platform}" ]]; then
fi
case "${docker_platform}" in linux/arm64|linux/arm64/*) docker_platform=linux/arm64 ;; esac
if [[ -z "${DROIDDECK_BUILD_IMAGE:-}" ]]; then
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v3
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v4
[[ "${docker_platform}" == linux/arm64 ]] && DROIDDECK_BUILD_IMAGE+=-arm64
fi
export DROIDDECK_DOCKER_PLATFORM=${docker_platform} DROIDDECK_BUILD_IMAGE
+221 -5
View File
@@ -16,8 +16,9 @@ import sys
import tempfile
import time
import uuid
import zipfile
import zlib
from pathlib import Path
from pathlib import Path, PurePosixPath
sys.path.insert(0, str(Path(__file__).resolve().parent))
from adb_device import DeviceResolutionError, resolve_serial
@@ -362,6 +363,54 @@ def pacing(adb: str, serial: str, seconds: float) -> dict:
return {"ok": True, "command": "pacing", "seconds": round(elapsed, 1), **summary}
THERMAL_STATUS = ["NONE", "LIGHT", "MODERATE", "SEVERE", "CRITICAL", "EMERGENCY", "SHUTDOWN"]
CPUFREQ = "/sys/devices/system/cpu/cpufreq"
def thermal_summary(battery: str, service: str, cpufreq: str) -> dict:
tenths = re.search(r"^\s*temperature:\s*(-?\d+)", battery, re.M)
status = re.search(r"^\s*Thermal Status:\s*(\d+)", service, re.M)
level = int(status.group(1)) if status else None
cpu: dict[str, dict] = {}
for policy, name, khz in re.findall(r"/(policy\d+)/(scaling_max_freq|cpuinfo_max_freq):(\d+)", cpufreq):
cpu.setdefault(policy, {})["maxKHz" if name == "scaling_max_freq" else "hardwareMaxKHz"] = int(khz)
for limits in cpu.values():
if "maxKHz" in limits and "hardwareMaxKHz" in limits:
limits["capped"] = limits["maxKHz"] < limits["hardwareMaxKHz"]
return {
"batteryC": int(tenths.group(1)) / 10 if tenths else None,
"status": level,
"statusName": THERMAL_STATUS[level] if level is not None and level < len(THERMAL_STATUS) else None,
"cpu": dict(sorted(cpu.items(), key=lambda item: int(item[0][6:]))),
}
def thermal(adb: str, serial: str) -> dict:
def shell(*command: str) -> str:
return run_adb(adb, serial, "shell", *command).stdout.decode(errors="replace")
summary = thermal_summary(shell("dumpsys", "battery"), shell("dumpsys", "thermalservice"),
shell("grep", ".", f"{CPUFREQ}/policy*/scaling_max_freq", f"{CPUFREQ}/policy*/cpuinfo_max_freq"))
return {"ok": True, "command": "thermal", **summary}
def wait_sleep(seconds: float) -> None:
time.sleep(seconds)
def wait_cool(adb: str, serial: str, below: float, timeout: float) -> dict:
started = time.monotonic()
while True:
reading = thermal(adb, serial)
if reading["batteryC"] is None:
raise ControlError("dumpsys battery reports no temperature", "THERMAL_FAILED")
if reading["batteryC"] < below:
return {**reading, "command": "wait", "waitedSeconds": round(time.monotonic() - started, 1)}
remaining = started + timeout - time.monotonic()
if remaining <= 0:
raise ControlError(f"Battery still at {reading['batteryC']:g} °C after {timeout:g} s, wanted below {below:g}",
"TIMEOUT")
wait_sleep(min(10.0, remaining))
def start_session(adb: str, serial: str, request: dict) -> dict:
if request.get("mode") == "run":
@@ -373,6 +422,112 @@ def start_session(adb: str, serial: str, request: dict) -> dict:
return confirm_start(adb, serial, request, current["session"])
def unpack_logs(archive: Path, destination: Path, session_id: str) -> None:
"""Unpack a Share logs zip so the session's own files sit at the top of destination."""
destination = destination.resolve()
try:
destination.mkdir(parents=True, exist_ok=True)
except OSError as exc:
raise ControlError(f"Could not unpack the session logs: {exc}", "LOG_PULL_FAILED") from exc
manifest = destination / ".droiddeckctl-managed-logs.json"
try:
previous = json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(previous, list) or any(not isinstance(name, str) for name in previous):
previous = []
except (OSError, ValueError):
previous = []
previous = set(previous)
previous.discard(manifest.name)
extracted = set()
def managed_target(name: str) -> Path | None:
relative = Path(name)
if relative.is_absolute() or not relative.parts or any(part in {".", ".."} for part in relative.parts):
return None
target = destination
for part in relative.parts:
target = target / part
if target.is_symlink():
return None
return target if target.resolve().is_relative_to(destination) else None
try:
with tempfile.TemporaryDirectory(prefix=".droiddeckctl-logs-", dir=destination) as temp, zipfile.ZipFile(archive) as z:
staged = Path(temp)
staged_files = staged / "new"
backups = staged / "old"
staged_files.mkdir()
for entry in z.infolist():
name = entry.filename
if name.startswith(session_id + "/"):
name = name[len(session_id) + 1:]
target = managed_target(name)
if entry.is_dir() or target is None or target == manifest:
continue
relative = target.relative_to(destination).as_posix()
staged_file = staged_files / relative
staged_file.parent.mkdir(parents=True, exist_ok=True)
with z.open(entry) as source, staged_file.open("wb") as copy:
shutil.copyfileobj(source, copy)
extracted.add(relative)
for name in extracted - previous:
target = managed_target(name)
if target is None or target.exists():
raise ControlError(f"Refusing to overwrite an unrelated file: {name}", "LOG_PULL_FAILED")
if manifest.is_symlink() or (manifest.exists() and not manifest.is_file()):
raise ControlError("The managed log list is not a regular file", "LOG_PULL_FAILED")
backed_up = {}
installed = set()
manifest_backup = backups / manifest.name
manifest_fd, manifest_path = tempfile.mkstemp(
prefix=".droiddeckctl-managed-logs-", suffix=".tmp", dir=destination
)
temp_manifest = Path(manifest_path)
try:
with os.fdopen(manifest_fd, "w", encoding="utf-8") as manifest_file:
manifest_file.write(json.dumps(sorted(extracted), indent=2) + "\n")
except Exception:
temp_manifest.unlink(missing_ok=True)
raise
try:
for name in sorted(previous):
target = managed_target(name)
if target is not None and target.is_file():
backup = backups / name
backup.parent.mkdir(parents=True, exist_ok=True)
os.replace(target, backup)
backed_up[name] = backup
if manifest.is_file():
manifest_backup.parent.mkdir(parents=True, exist_ok=True)
os.replace(manifest, manifest_backup)
for name in sorted(extracted):
target = managed_target(name)
if target is None:
raise ControlError(f"A log destination became unsafe: {name}", "LOG_PULL_FAILED")
target.parent.mkdir(parents=True, exist_ok=True)
os.replace(staged_files / name, target)
installed.add(name)
os.replace(temp_manifest, manifest)
except Exception:
temp_manifest.unlink(missing_ok=True)
for name in installed:
target = managed_target(name)
if target is not None and target.is_file():
target.unlink()
if manifest_backup.is_file() and manifest.exists() and not manifest.is_symlink():
manifest.unlink()
for name, backup in backed_up.items():
target = managed_target(name)
if target is not None:
target.parent.mkdir(parents=True, exist_ok=True)
os.replace(backup, target)
if manifest_backup.is_file():
os.replace(manifest_backup, manifest)
raise
except (OSError, zipfile.BadZipFile) as exc:
raise ControlError(f"Could not unpack the session logs: {exc}", "LOG_PULL_FAILED") from exc
def require_commands(adb: str, serial: str) -> dict:
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
if access.get("commands") is not True:
@@ -531,6 +686,10 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
"sessionId": session.get("id"), "phase": session.get("phase")}, serial)
if command == "wait":
if args.phase == "cool":
if args.below is None:
raise ControlError("wait cool needs --below <°C>", "INVALID_ARGUMENTS")
return add_serial(wait_cool(adb, serial, args.below, args.timeout), serial)
if args.phase == "focused":
if args.app_id is None:
raise ControlError("wait focused needs an app id", "INVALID_ARGUMENTS")
@@ -689,10 +848,62 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if not remote_dir or not session.get("id") or not session.get("artifactsAvailable"):
raise ControlError("No session artifact directory is available", "NO_SESSION_LOGS")
destination = Path(args.destination or session["id"]).expanduser().resolve()
result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120)
exported = provider_call(adb, serial, "logs", timeout=args.timeout + 40)
cleanup_error = None
if (exported.get("error") or {}).get("code") == "UNKNOWN_COMMAND":
# Older builds have no logs method; their private folder only pulls on a rooted device.
result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120)
else:
zip_path = checked(exported, "LOG_PULL_FAILED")["zip"]
remote_zip = PurePosixPath(zip_path)
if (not remote_zip.is_absolute() or ".." in remote_zip.parts or
not re.fullmatch(r"/[A-Za-z0-9_./-]+", zip_path)):
raise ControlError("The exported logs path is invalid", "LOG_PULL_FAILED")
requested_dir = exported.get("cleanupDir")
request_dir = PurePosixPath(requested_dir) if isinstance(requested_dir, str) else None
cleanup = ["shell", "rm", "-f", zip_path]
if (request_dir and request_dir.is_absolute() and ".." not in request_dir.parts and
request_dir == remote_zip.parent and request_dir.parent.name == "agent-logs" and
re.fullmatch(r"[0-9a-fA-F-]{36}", request_dir.name)):
cleanup = ["shell", "rm", "-rf", str(request_dir)]
def cleanup_export():
try:
cleaned = run_adb(adb, serial, *cleanup, timeout=30)
if cleaned.returncode == 0:
return None
detail = (cleaned.stderr or cleaned.stdout).decode(errors="replace").strip()
except Exception as error:
detail = str(error)
return ControlError(
"Could not remove the exported log archive; it may remain in shared storage" +
(f": {detail}" if detail else ""),
"LOG_CLEANUP_FAILED",
)
try:
if exported.get("sessionId", session["id"]) != session["id"]:
raise ControlError("A new session started while the logs were exported; run logs again",
"LOG_PULL_FAILED")
with tempfile.TemporaryDirectory() as temp:
local_zip = Path(temp) / "logs.zip"
result = run_adb(adb, serial, "pull", zip_path, str(local_zip), timeout=120)
if result.returncode != 0:
detail = (result.stderr or result.stdout).decode(errors="replace").strip()
raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED")
unpack_logs(local_zip, destination, session["id"])
except Exception:
cleanup_error = cleanup_export()
if cleanup_error:
print(cleanup_error, file=sys.stderr)
raise
else:
# The copy sits in shared storage, so it does not outlive the pull.
cleanup_error = cleanup_export()
if result.returncode != 0:
detail = (result.stderr or result.stdout).decode(errors="replace").strip()
raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED")
if cleanup_error:
raise cleanup_error
return add_serial({"ok": True, "command": "logs", "sessionId": session["id"], "path": str(destination)}, serial)
if command == "screenshot":
@@ -704,6 +915,9 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if command == "pacing":
return add_serial(pacing(adb, serial, args.seconds), serial)
if command == "thermal":
return add_serial(thermal(adb, serial), serial)
if command == "wake":
run_adb(adb, serial, "shell", "input", "keyevent", "KEYCODE_WAKEUP")
run_adb(adb, serial, "shell", "wm", "dismiss-keyguard")
@@ -739,9 +953,10 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("program")
run.add_argument("arguments", nargs=argparse.REMAINDER)
wait = commands.add_parser("wait", help="wait for a session phase, or for a game to have focus")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game"])
wait = commands.add_parser("wait", help="wait for a session phase, for a game to have focus, or for the battery to cool")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game", "cool"])
wait.add_argument("app_id", nargs="?", type=int, help="with focused: the Steam app id")
wait.add_argument("--below", type=float, help="with cool: the battery temperature to get under, in °C")
wait.add_argument("--timeout", type=float, default=90)
stop = commands.add_parser("stop", help="stop the session and wait for IDLE")
@@ -906,6 +1121,7 @@ def build_parser() -> argparse.ArgumentParser:
pace = commands.add_parser("pacing", help="frames that reached the screen and their intervals (SurfaceFlinger)")
pace.add_argument("--seconds", type=float, default=30)
commands.add_parser("thermal", help="battery temperature, thermal status and CPU frequency caps")
commands.add_parser("displays", help="the device's displays and their capture ids")
commands.add_parser("wake", help="wake the device and dismiss the keyguard")
return parser
@@ -918,7 +1134,7 @@ EXIT_SESSION = {
"NO_STEAM_SESSION", "SESSION_NOT_READY", "AGENT_UNAVAILABLE", "LAUNCH_REJECTED", "NO_PAD", "NO_FRAMES",
}
EXIT_TIMEOUT = {"TIMEOUT", "ARTIFACT_TIMEOUT"}
EXIT_FILE = {"NO_SESSION_LOGS", "LOG_PULL_FAILED", "SCREENSHOT_FAILED", "FILE_IO", "RECORD_FAILED", "PUSH_FAILED",
EXIT_FILE = {"NO_SESSION_LOGS", "LOG_PULL_FAILED", "LOG_CLEANUP_FAILED", "SCREENSHOT_FAILED", "FILE_IO", "RECORD_FAILED", "PUSH_FAILED",
"PACING_FAILED", "XR_CAPTURE_FAILED"}
EXIT_DENIED = {"AGENT_COMMANDS_DISABLED", "PROTECTED_PREFS", "PROTECTED_CONTROL"}
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# CI component build; this does not change the APK or an installed Proton depot.
set -euo pipefail
root=$(cd "$(dirname "$0")/../.." && pwd)
. "$root/tools/dxvk/source.env"
mkdir -p "${1:?output directory required}"
out=$(cd "$1" && pwd)
# Refuse to mix a pinned build with prior DLLs or an incomplete previous build.
# Include dotfiles in the check and leave all existing contents untouched.
shopt -s nullglob dotglob
existing=("$out"/*)
if ((${#existing[@]})); then
printf '%s\n' 'output directory must be empty; use a fresh build directory' >&2
exit 1
fi
shopt -u nullglob dotglob
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
git init -q "$work/source"
git -C "$work/source" fetch --depth=1 https://github.com/doitsujin/dxvk.git "$DXVK_REVISION"
git -C "$work/source" checkout -q --detach FETCH_HEAD
test "$(git -C "$work/source" rev-parse HEAD)" = "$DXVK_REVISION"
git -C "$work/source" submodule update --init --recursive --depth=1
for patch in "$root"/tools/dxvk/patches/*.patch; do
git -C "$work/source" apply --check "$patch"
git -C "$work/source" apply "$patch"
done
python3 "$root/tools/dxvk/check_present_sync.py" "$work/source/src/dxvk/dxvk_presenter.cpp"
python3 "$root/tools/dxvk/check_hud_storage_format.py" "$work/source/src/dxvk/hud/shaders/hud_frame_time_eval.comp"
python3 "$root/tools/dxvk/check_d3d9_single_sample.py" "$work/source"
for arch in 32 64; do
meson setup "$work/build$arch" "$work/source" --cross-file "$work/source/build-win$arch.txt" \
--buildtype release --prefix "$out" --bindir "x$arch" --libdir "x$arch" -Db_ndebug=if-release --strip
meson compile -C "$work/build$arch" -j 4
meson install -C "$work/build$arch"
done
cp "$work/source/LICENSE" "$out/LICENSE"
printf '%s\n' "$DXVK_REVISION" > "$out/source-commit"
git -C "$work/source" submodule status --recursive > "$out/submodules.txt"
git -C "$work/source" diff > "$out/downstream.patch"
tar --exclude-vcs --zstd -cf "$out/source.tar.zst" -C "$work/source" .
(cd "$out" && find x32 x64 -name '*.dll' -type f -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS)
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Compile pinned DXVK's actual descriptor paths against a controlled backend.
This checks CPU control flow, not GPU rendering. No Wine/game/device is started.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
CASES = ('forced_msaa_depth', 'default_msaa_depth', 'forced_nonmaskable',
'default_nonmaskable', 'forced_already_single', 'forced_no_depth',
'forced_unsupported', 'forced_invalid_type', 'forced_lockable_msaa',
'forced_lockable_single', 'forced_allocation_failure',
'default_allocation_failure', 'forced_recreate', 'ordinary_surface',
'ordinary_invalid_lockable')
def function(text, signature):
start = text.index(signature)
opening = text.index('{', start)
# Ignore braces in comments and strings while preserving source positions.
stripped = re.sub(r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'',
lambda m: ' ' * len(m.group()), text, flags=re.S)
depth = 0
for index in range(opening, len(stripped)):
depth += (stripped[index] == '{') - (stripped[index] == '}')
if depth == 0:
return text[start:index + 1]
raise ValueError('Unterminated source function: ' + signature)
def production(source):
base = source / 'src/d3d9'
common = (base / 'd3d9_common_texture.cpp').read_text()
header = (base / 'd3d9_common_texture.h').read_text()
swap = (base / 'd3d9_swapchain.cpp').read_text()
device = (base / 'd3d9_device.cpp').read_text()
util = (base / 'd3d9_util.cpp').read_text()
pieces = {
'decode': function(util, 'HRESULT DecodeMultiSampleType('),
'normalize': function(common, 'HRESULT D3D9CommonTexture::NormalizeTextureProperties('),
'backbuffers': function(swap, 'HRESULT D3D9SwapChainEx::CreateBackBuffers('),
'uses_image': function(header, 'static bool TextureUsesImage('),
}
reset = function(device, 'HRESULT D3D9DeviceEx::ResetSwapChain(')
begin = reset.index('D3D9_COMMON_TEXTURE_DESC desc;', reset.index('if (pPresentationParameters->EnableAutoDepthStencil)'))
end = reset.index('m_autoDepthStencil =', begin)
pieces['auto_depth'] = reset[begin:end].rstrip()
framebuffer = function(device, 'void D3D9DeviceEx::BindFramebuffer(')
begin = framebuffer.index('const bool mismatch =')
end = framebuffer.index(';', framebuffer.index('const bool bindDS =', begin)) + 1
pieces['depth_binding'] = framebuffer[begin:end]
return pieces
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('source', type=Path, help='Pinned DXVK tree with downstream patches applied')
parser.add_argument('--cxx', default=os.environ.get('CXX', 'c++'))
parser.add_argument('--sanitize', action='store_true', help='Enable ASan/UBSan on the CPU harness')
args = parser.parse_args()
pieces = production(args.source)
harness = (Path(__file__).parent / 'tests/d3d9_single_sample.cpp').read_text()
harness = harness.replace('/* PRODUCTION_USES_IMAGE */', pieces['uses_image'])
with tempfile.TemporaryDirectory(prefix='dxvk-d3d9-') as directory:
out = Path(directory)
(out / 'harness.cpp').write_text(harness)
include = '\n\n'.join(pieces[key] for key in ('decode', 'normalize', 'backbuffers'))
include += '\nHRESULT auto_depth(D3D9DeviceEx* device, D3DPRESENT_PARAMETERS* pPresentationParameters, D3D9_COMMON_TEXTURE_DESC* output) {\n'
include += 'auto* self = device;\n' + pieces['auto_depth'].replace('(this,', '(self,')
include += '\n*output = desc; return D3D_OK;\n}\n'
include += '\nbool depth_binds(const ImageInfo& color, const ImageInfo& dsInfo) {\n'
include += 'auto sampleCount = color.sampleCount; auto renderArea = color.extent;\n'
include += 'const bool noRT0Bound = false, ignoreRT0 = false;\n'
include += pieces['depth_binding'] + '\nreturn bindDS;\n}\n'
(out / 'd3d9_production.inc').write_text(include)
command = [args.cxx, '-std=c++17', '-Wall', '-Wextra', '-Werror',
'-Wno-unused-parameter', str(out / 'harness.cpp'), '-o', str(out / 'check')]
# The original CreateBackBuffers does not use Flags; that known baseline
# warning must not turn a negative control into a compiler-fixture error.
if args.sanitize:
command[1:1] = ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
compilation = subprocess.run(command, capture_output=True, text=True)
if compilation.returncode:
raise SystemExit(compilation.stderr)
results = []
for case in CASES:
process = subprocess.run([str(out / 'check'), case], capture_output=True,
text=True, timeout=10, cwd=out,
env={'ASAN_OPTIONS': 'detect_leaks=' +
('0' if sys.platform == 'darwin' else '1')})
results.append({'case': case, 'passed': process.returncode == 0,
'exit': process.returncode, 'detail': process.stderr.strip()[-800:]})
result = {'cases': results, 'passed': sum(row['passed'] for row in results),
'failed': sum(not row['passed'] for row in results),
'production_sha256': {key: hashlib.sha256(value.encode()).hexdigest()
for key, value in pieces.items()},
'backend_and_adapter_mocked': True, 'GPU_test': False,
'sanitizers': args.sanitize,
'leak_detection': args.sanitize and sys.platform != 'darwin'}
print(json.dumps(result, indent=2))
return bool(result['failed'])
if __name__ == '__main__':
raise SystemExit(main())
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Compile the actual HUD shader and verify its binding-3 R8_UINT contract.
The frame-time HUD binds an R8_UINT texel-buffer view. An Unknown SPIR-V image
format requires STORAGE_WRITE_WITHOUT_FORMAT, which PowerVR does not report
for that buffer format. Static spirv-val alone accepts both declarations;
this check validates the shader against the known host-side binding contract.
"""
import argparse
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
def check(shader):
compiler = shutil.which('glslangValidator')
validator = shutil.which('spirv-val')
if not compiler or not validator:
raise RuntimeError('glslangValidator and spirv-val required')
with tempfile.TemporaryDirectory(prefix='dxvk-hud-contract-') as directory:
output = Path(directory) / 'hud.spv'
for command in ([compiler, '-V', '--target-env', 'vulkan1.3', str(shader), '-o', str(output)],
[validator, '--target-env', 'vulkan1.3', str(output)]):
process = subprocess.run(command, capture_output=True, text=True, timeout=30)
if process.returncode:
raise RuntimeError('HUD shader compilation/SPIR-V validation failed')
raw = output.read_bytes()
if len(raw) < 20 or len(raw) % 4:
raise RuntimeError('Malformed SPIR-V')
words = struct.unpack('<' + str(len(raw) // 4) + 'I', raw)
if words[0] != 0x07230203:
raise RuntimeError('Unexpected SPIR-V magic')
bindings, sets, variables, pointers, images = {}, {}, {}, {}, {}
offset = 5
while offset < len(words):
size, opcode = words[offset] >> 16, words[offset] & 0xffff
if not size or size > len(words) - offset:
raise RuntimeError('Malformed SPIR-V instruction')
instruction = words[offset:offset + size]
if opcode == 71 and size == 4: # OpDecorate
if instruction[2] == 33:
bindings[instruction[1]] = instruction[3]
elif instruction[2] == 34:
sets[instruction[1]] = instruction[3]
elif opcode == 59 and size >= 4: # OpVariable
variables[instruction[2]] = instruction[1]
elif opcode == 32 and size == 4: # OpTypePointer
pointers[instruction[1]] = instruction[3]
elif opcode == 25 and size >= 9: # OpTypeImage
images[instruction[1]] = (instruction[3], instruction[7], instruction[8])
offset += size
targets = [images.get(pointers.get(variables.get(identifier)))
for identifier, binding in bindings.items()
if binding == 3 and sets.get(identifier) == 0]
if targets != [(5, 2, 39)]: # DimBuffer, storage image, ImageFormatR8ui
raise RuntimeError('HUD binding 3 must compile to a storage texel buffer with ImageFormatR8ui')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('shader', type=Path)
args = parser.parse_args()
try:
check(args.shader)
except RuntimeError as error:
parser.exit(1, str(error) + '\n')
print('HUD binding 3: SPIR-V valid, explicit R8ui storage texel-buffer format')
if __name__ == '__main__':
main()
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Replay asynchronous WSI ownership using the pinned presenter's actual selections.
This checks semaphore selection, not the full Vulkan presenter. Real Vulkan
validation and device testing remain separate gates. Requires a native C++ compiler.
"""
import argparse
import os
from pathlib import Path
import re
import subprocess
import tempfile
def selection_code(source):
match = re.search(
r"// Return relevant Vulkan objects for the acquired image\s*"
r"(?P<acquire>.*?)\s*m_presentPending = true;", source, re.S)
wait = re.search(r"info\.pWaitSemaphores\s*=.*?;", source, re.S)
if not match or not wait:
raise ValueError("unsupported pinned presenter layout")
return match["acquire"], wait[0]
HARNESS = r'''
#include <array>
#include <cstdint>
#include <cstdio>
#include <vector>
using VkSemaphore = uint64_t;
struct Sync { VkSemaphore acquire, present; };
struct Info { const VkSemaphore* pWaitSemaphores; };
struct Presenter {
std::vector<Sync> m_semaphores;
std::vector<unsigned> m_images = {0, 1, 2, 3};
unsigned m_frameIndex = 0, m_imageIndex = 0;
bool m_hasSwapchainMaintenance1;
explicit Presenter(bool maintenance): m_hasSwapchainMaintenance1(maintenance) {
for (unsigned i = 0; i < (maintenance ? 4u : 8u); ++i)
m_semaphores.push_back({100 + i, 1 + i});
}
Sync acquire() {
Sync sync{}; unsigned image;
ACQUIRE_SELECTION
(void)image;
return sync;
}
VkSemaphore present() {
auto& currSync = m_semaphores.at(m_frameIndex);
Info info{};
PRESENT_SELECTION
return *info.pWaitSemaphores;
}
};
int replay(bool maintenance) {
Presenter p(maintenance);
std::array<VkSemaphore, 4> outstandingByImage{};
std::array<VkSemaphore, 4> outstandingByFence{};
// Deliberately delay reacquisition of image 2 beyond a full frame-ring cycle.
const std::array<unsigned, 21> imageOrder = {
2,0,3,0,1,3,0,1,1,2,3,1,0,3,2,2,0,1,3,0,2
};
for (unsigned iteration = 0; iteration < 200; ++iteration) {
p.m_imageIndex = imageOrder[iteration % imageOrder.size()];
if (maintenance) {
// The existing fence path waits this frame's previous present fence.
const auto completed = outstandingByFence.at(p.m_frameIndex);
for (auto& pending : outstandingByImage)
if (pending == completed) pending = 0;
}
// Acquisition and its GPU wait complete the last present of THIS image.
outstandingByImage.at(p.m_imageIndex) = 0;
const auto signal = p.acquire().present;
const auto wait = p.present();
if (signal != wait) {
std::fprintf(stderr, "FAIL: render signal differs from present wait\n");
return 2;
}
for (auto pending : outstandingByImage) {
if (pending == signal) {
std::fprintf(stderr, "FAIL: semaphore reused before presentation completion at frame %u\n", iteration);
return 2;
}
}
outstandingByImage.at(p.m_imageIndex) = signal;
if (maintenance) outstandingByFence.at(p.m_frameIndex) = signal;
p.m_frameIndex = (p.m_frameIndex + 1) % p.m_semaphores.size();
}
std::printf("PASS: %s, 200 out-of-order acquisitions\n", maintenance ? "present-fence path" : "no-present-fence path");
return 0;
}
int main() {
if (int status = replay(false)) return status;
return replay(true);
}
'''
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path, help="pinned dxvk_presenter.cpp, after patching")
args = parser.parse_args()
acquire, present = selection_code(args.source.read_text())
code = HARNESS.replace("ACQUIRE_SELECTION", acquire).replace("PRESENT_SELECTION", present)
with tempfile.TemporaryDirectory(prefix="dxvk-present-sync-") as directory:
cpp = Path(directory) / "replay.cpp"
exe = Path(directory) / "replay"
cpp.write_text(code)
subprocess.run([os.environ.get("HOST_CXX", "c++"), "-std=c++17", "-Wall", "-Wextra", str(cpp), "-o", str(exe)], check=True)
return subprocess.run([str(exe)]).returncode
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,53 @@
diff --git a/src/dxvk/dxvk_device_info.cpp b/src/dxvk/dxvk_device_info.cpp
index db09fba..8e9a76e 100644
--- a/src/dxvk/dxvk_device_info.cpp
+++ b/src/dxvk/dxvk_device_info.cpp
@@ -118,6 +118,17 @@ namespace dxvk {
initQueueProperties(instance, adapter, deviceInfo);
initMemoryProperties(instance, adapter);
+ m_hasBcFormats = true;
+ for (uint32_t value = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; value <= VK_FORMAT_BC7_SRGB_BLOCK; value++) {
+ VkFormatProperties properties = { };
+ vk->vkGetPhysicalDeviceFormatProperties(adapter, VkFormat(value), &properties);
+ constexpr VkFormatFeatureFlags required = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT
+ | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT
+ | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
+ if ((properties.optimalTilingFeatures & required) != required)
+ m_hasBcFormats = false;
+ }
+
disableUnusedFeatures(instance, safeMode);
enableFeaturesAndExtensions();
@@ -785,6 +796,9 @@ namespace dxvk {
}
}
+ if (!m_hasBcFormats)
+ return std::string("Device does not support the BC formats required by Direct3D");
+
if (!m_featuresEnabled.extDescriptorHeap.descriptorHeap && m_properties.core.properties.limits.maxPushConstantsSize < MaxTotalPushDataSize)
return str::format("Device does not support ", MaxTotalPushDataSize, " of push data");
@@ -886,7 +900,7 @@ namespace dxvk {
ENABLE_FEATURE(core.features, shaderResourceResidency, false),
ENABLE_FEATURE(core.features, shaderResourceMinLod, false),
ENABLE_FEATURE(core.features, tessellationShader, false),
- ENABLE_FEATURE(core.features, textureCompressionBC, true),
+ ENABLE_FEATURE(core.features, textureCompressionBC, false),
ENABLE_FEATURE(core.features, variableMultisampleRate, false),
ENABLE_FEATURE(core.features, vertexPipelineStoresAndAtomics, false),
ENABLE_FEATURE(core.features, wideLines, false),
diff --git a/src/dxvk/dxvk_device_info.h b/src/dxvk/dxvk_device_info.h
index 0a55f90..8bbc770 100644
--- a/src/dxvk/dxvk_device_info.h
+++ b/src/dxvk/dxvk_device_info.h
@@ -394,6 +394,7 @@ namespace dxvk {
DxvkDeviceQueueMapping m_queueMapping = { };
+ bool m_hasBcFormats = false;
bool m_hasMeshShader = false;
bool m_hasFmask = false;
@@ -0,0 +1,26 @@
diff --git a/src/dxvk/dxvk_presenter.cpp b/src/dxvk/dxvk_presenter.cpp
index 643f7c5..4dc8c4d 100644
--- a/src/dxvk/dxvk_presenter.cpp
+++ b/src/dxvk/dxvk_presenter.cpp
@@ -161,6 +161,10 @@ namespace dxvk {
// Return relevant Vulkan objects for the acquired image
sync = m_semaphores.at(m_frameIndex);
+ // Without a present fence, reacquiring this image is the only guarantee
+ // that its previous presentation has consumed the wait semaphore.
+ if (!m_hasSwapchainMaintenance1)
+ sync.present = m_semaphores.at(m_imageIndex).present;
image = m_images.at(m_imageIndex);
m_presentPending = true;
@@ -239,7 +243,9 @@ namespace dxvk {
VkPresentInfoKHR info = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
info.waitSemaphoreCount = 1;
- info.pWaitSemaphores = &currSync.present;
+ info.pWaitSemaphores = m_hasSwapchainMaintenance1
+ ? &currSync.present
+ : &m_semaphores.at(m_imageIndex).present;
info.swapchainCount = 1;
info.pSwapchains = &m_swapchain;
info.pImageIndices = &m_imageIndex;
@@ -0,0 +1,12 @@
--- a/src/dxvk/hud/shaders/hud_frame_time_eval.comp
+++ b/src/dxvk/hud/shaders/hud_frame_time_eval.comp
@@ -41,7 +41,8 @@
draw_info_t draw_infos[];
};
-layout(binding = 3)
+// The bound text view is VK_FORMAT_R8_UINT; do not require formatless writes.
+layout(binding = 3, r8ui)
uniform writeonly uimageBuffer text_buffer;
layout(push_constant)
@@ -0,0 +1,86 @@
diff --git a/dxvk.conf b/dxvk.conf
index ba4bc20..26d3127 100644
--- a/dxvk.conf
+++ b/dxvk.conf
@@ -336,6 +336,15 @@
# d3d11.disableMsaa = False
+# Forces D3D9 surfaces to single-sample after validating the original request.
+# The effective surface description reports D3DMULTISAMPLE_NONE; MSAA quality,
+# alpha-to-coverage and per-sample masks are consequently disabled. This is an
+# opt-in compatibility override for games with broken MSAA rendering.
+#
+# Supported values: True, False
+
+# d3d9.forceSingleSample = False
+
# Forces insertion of memory and control barriers after writes to group-shared
# memory in compute shaders. This is only intended to be used as a workaround
diff --git a/src/d3d9/d3d9_common_texture.cpp b/src/d3d9/d3d9_common_texture.cpp
index 9d5fe38..629fea3 100644
--- a/src/d3d9/d3d9_common_texture.cpp
+++ b/src/d3d9/d3d9_common_texture.cpp
@@ -212,6 +212,15 @@ namespace dxvk {
return D3DERR_INVALIDCALL;
}
+ // Keep original request validation above. This opt-in override changes
+ // the effective surface description as well as the backing image.
+ // All surface descriptors and resolves then see the actual sample count.
+ if (ResourceType == D3DRTYPE_SURFACE && options->forceSingleSample
+ && sampleCount != VK_SAMPLE_COUNT_1_BIT) {
+ pDesc->MultiSample = D3DMULTISAMPLE_NONE;
+ pDesc->MultisampleQuality = 0;
+ }
+
// Using MANAGED pool with DYNAMIC usage is illegal
if (IsPoolManaged(pDesc->Pool) && (pDesc->Usage & D3DUSAGE_DYNAMIC))
return D3DERR_INVALIDCALL;
diff --git a/src/d3d9/d3d9_options.cpp b/src/d3d9/d3d9_options.cpp
index e46864e..0cab7dc 100644
--- a/src/d3d9/d3d9_options.cpp
+++ b/src/d3d9/d3d9_options.cpp
@@ -59,6 +59,7 @@ namespace dxvk {
this->memoryTrackTest = config.getOption<bool> ("d3d9.memoryTrackTest", false);
this->forceSamplerTypeSpecConstants = config.getOption<bool> ("d3d9.forceSamplerTypeSpecConstants", false);
this->forceSampleRateShading = config.getOption<bool> ("d3d9.forceSampleRateShading", false);
+ this->forceSingleSample = config.getOption<bool> ("d3d9.forceSingleSample", false);
this->forceAspectRatio = config.getOption<std::string> ("d3d9.forceAspectRatio", "");
this->forceRefreshRate = config.getOption<int32_t> ("d3d9.forceRefreshRate", 0u);
this->modeCountCompatibility = config.getOption<bool> ("d3d9.modeCountCompatibility", false);
diff --git a/src/d3d9/d3d9_options.h b/src/d3d9/d3d9_options.h
index e69a39a..4478420 100644
--- a/src/d3d9/d3d9_options.h
+++ b/src/d3d9/d3d9_options.h
@@ -113,6 +113,9 @@ namespace dxvk {
/// Forces sample rate shading
bool forceSampleRateShading;
+ /// Optional compatibility override: report and render surfaces as single-sample.
+ bool forceSingleSample;
+
/// Allow D3DLOCK_DISCARD
bool allowDiscard;
diff --git a/src/d3d9/d3d9_swapchain.cpp b/src/d3d9/d3d9_swapchain.cpp
--- a/src/d3d9/d3d9_swapchain.cpp
+++ b/src/d3d9/d3d9_swapchain.cpp
@@ -1055,1 +1055,16 @@ namespace dxvk {
+ if (m_parent->GetOptions()->forceSingleSample) {
+ // Backbuffers bypass the normal surface-creation entry points. Validate
+ // the application's request, then apply the same effective sample count.
+ // IsLockable above is an internal GDI fallback requirement, not the
+ // application's lockability request used by MSAA validation.
+ auto requestedDesc = desc;
+ requestedDesc.IsLockable = (Flags & D3DPRESENTFLAG_LOCKABLE_BACKBUFFER) != 0;
+ HRESULT hr = D3D9CommonTexture::NormalizeTextureProperties(
+ m_parent, D3DRTYPE_SURFACE, &requestedDesc);
+ if (FAILED(hr))
+ return hr;
+ desc.MultiSample = requestedDesc.MultiSample;
+ desc.MultisampleQuality = requestedDesc.MultisampleQuality;
+ }
+
const bool isExtended = m_parent->IsD3DCompatibile(D3DCompatibility::D3D9Ex);
+1
View File
@@ -0,0 +1 @@
DXVK_REVISION=25ca63f17f34bdc05a39873ee63907d3cbbfa030
+214
View File
@@ -0,0 +1,214 @@
// Backend/adapter fixture for the verbatim DXVK functions in d3d9_production.inc.
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
using HRESULT = int32_t;
using DWORD = uint32_t;
using UINT = uint32_t;
using VkSampleCountFlagBits = uint32_t;
constexpr HRESULT D3D_OK = 0, D3DERR_INVALIDCALL = -1,
D3DERR_NOTAVAILABLE = -2, D3DERR_OUTOFVIDEOMEMORY = -3;
constexpr uint32_t VK_SAMPLE_COUNT_1_BIT = 1, VK_IMAGE_ASPECT_COLOR_BIT = 1;
constexpr bool FALSE = false, TRUE = true;
#define FAILED(x) ((x) < 0)
#define unlikely(x) (x)
enum D3DMULTISAMPLE_TYPE { D3DMULTISAMPLE_NONE, D3DMULTISAMPLE_NONMASKABLE,
D3DMULTISAMPLE_16_SAMPLES = 16 };
enum D3DRESOURCETYPE { D3DRTYPE_SURFACE, D3DRTYPE_CUBETEXTURE, D3DRTYPE_VOLUMETEXTURE };
enum D3DPOOL { D3DPOOL_DEFAULT, D3DPOOL_MANAGED, D3DPOOL_SYSTEMMEM, D3DPOOL_SCRATCH };
enum class D3DCompatibility { D3D9Ex };
enum class D3D9Format { X8R8G8B8, D24S8, A8, NULL_FORMAT, ATI2,
D32_LOCKABLE, D32F_LOCKABLE, D16_LOCKABLE, S8_LOCKABLE };
constexpr DWORD D3DUSAGE_RENDERTARGET = 1, D3DUSAGE_DEPTHSTENCIL = 2,
D3DUSAGE_DYNAMIC = 4, D3DUSAGE_WRITEONLY = 8, D3DUSAGE_AUTOGENMIPMAP = 16;
constexpr DWORD D3DPRESENTFLAG_LOCKABLE_BACKBUFFER = 1, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL = 2;
constexpr int D3DDEVTYPE_HAL = 1, VK_IMAGE_LAYOUT_UNDEFINED = 0;
struct Extent { uint32_t width, height, depth = 1; };
namespace util {
uint32_t computeMipLevelCount(Extent e) {
uint32_t n = std::max({e.width, e.height, e.depth}), levels = 0;
do { ++levels; n >>= 1; } while (n);
return levels;
}
}
bool IsPoolManaged(D3DPOOL pool) { return pool == D3DPOOL_MANAGED; }
bool IsDXTFormat(D3D9Format) { return false; }
bool IsDepthStencilFormat(D3D9Format format) { return format == D3D9Format::D24S8; }
bool IsLockableDepthStencilFormat(D3D9Format) { return false; }
struct D3D9_FORMAT_BLOCK_SIZE { uint32_t Width, Height; };
D3D9_FORMAT_BLOCK_SIZE GetFormatAlignedBlockSize(D3D9Format) { return {1, 1}; }
D3D9Format EnumerateFormat(D3D9Format format) { return format; }
struct D3D9_COMMON_TEXTURE_DESC {
uint32_t Width = 1280, Height = 720, Depth = 1, MipLevels = 1, ArraySize = 1;
D3D9Format Format = D3D9Format::X8R8G8B8;
D3DMULTISAMPLE_TYPE MultiSample = D3DMULTISAMPLE_NONE;
DWORD MultisampleQuality = 0;
D3DPOOL Pool = D3DPOOL_DEFAULT;
DWORD Usage = D3DUSAGE_RENDERTARGET;
bool Discard = false, IsBackBuffer = false, IsAttachmentOnly = false, IsLockable = false;
};
struct D3DPRESENT_PARAMETERS {
uint32_t BackBufferWidth = 1280, BackBufferHeight = 720;
D3D9Format BackBufferFormat = D3D9Format::X8R8G8B8;
D3DMULTISAMPLE_TYPE MultiSampleType = D3DMULTISAMPLE_TYPE(4);
DWORD MultiSampleQuality = 0, Flags = 0;
D3D9Format AutoDepthStencilFormat = D3D9Format::D24S8;
};
struct Options {
bool forceSingleSample = false, extraFrontbuffer = false,
disableA8RT = false, supportCubeDepthFormats = false;
};
struct FormatMapping {
uint32_t Aspect;
bool IsValid() const { return true; }
};
struct Adapter {
bool supported = true;
std::vector<D3DMULTISAMPLE_TYPE> checked;
HRESULT CheckDeviceMultiSampleType(int, D3D9Format, bool, D3DMULTISAMPLE_TYPE samples, void*) {
checked.push_back(samples);
return supported ? D3D_OK : D3DERR_NOTAVAILABLE;
}
};
struct ImageInfo { Extent extent; VkSampleCountFlagBits sampleCount; };
struct DxvkImage { ImageInfo info; };
template<typename T> using Rc = std::shared_ptr<T>;
template<typename T, unsigned N> using small_vector = std::vector<T>;
struct DxvkContext {
unsigned initialized = 0;
void initImage(const Rc<DxvkImage>&, int) { ++initialized; }
};
struct D3D9DeviceEx {
Options options;
Adapter adapter;
DxvkContext context;
unsigned attempts = 0, failAt = 0, losable = 0, live = 0, injected = 0;
std::vector<D3D9_COMMON_TEXTURE_DESC> created;
Options* GetOptions() { return &options; }
Adapter* GetAdapter() { return &adapter; }
FormatMapping LookupFormat(D3D9Format format) { return {IsDepthStencilFormat(format) ? 2u : 1u}; }
struct Unsupported { unsigned elementSize = 0; };
Unsupported unsupported;
const Unsupported* UnsupportedFormatInfo(D3D9Format) { return &unsupported; }
bool IsD3DCompatibile(D3DCompatibility) { return false; }
void IncrementLosableCounter() { ++losable; }
template<typename F> void InjectCs(F function) { ++injected; function(&context); }
};
HRESULT DecodeMultiSampleType(D3DMULTISAMPLE_TYPE, DWORD, VkSampleCountFlagBits*);
struct D3D9CommonTexture {
Rc<DxvkImage> image;
const Rc<DxvkImage>& GetImage() const { return image; }
static HRESULT NormalizeTextureProperties(D3D9DeviceEx*, D3DRESOURCETYPE, D3D9_COMMON_TEXTURE_DESC*);
/* PRODUCTION_USES_IMAGE */
};
class DxvkError : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
std::string message() const { return what(); }
};
struct Logger { static void err(const std::string&) {} };
struct D3D9SwapChainEx;
struct D3D9Surface {
D3D9CommonTexture texture;
D3D9DeviceEx* device;
D3D9Surface(D3D9DeviceEx* d, D3D9_COMMON_TEXTURE_DESC* desc, bool, D3D9SwapChainEx*, void*) : device(d) {
if (++d->attempts == d->failAt) throw DxvkError("controlled allocation failure");
VkSampleCountFlagBits samples;
if (FAILED(DecodeMultiSampleType(desc->MultiSample, desc->MultisampleQuality, &samples)))
throw DxvkError("invalid backend sample count");
texture.image = std::make_shared<DxvkImage>(DxvkImage{{{desc->Width, desc->Height}, samples}});
d->created.push_back(*desc); ++d->live;
}
~D3D9Surface() { --device->live; }
D3D9CommonTexture* GetCommonTexture() { return &texture; }
};
struct D3D9SwapChainEx {
D3D9DeviceEx* m_parent;
D3DPRESENT_PARAMETERS m_presentParams;
std::vector<std::unique_ptr<D3D9Surface>> m_backBuffers;
bool flip = false;
unsigned destroys = 0;
bool SwapWithFrontBuffer() { return flip; }
void DestroyBackBuffers() { ++destroys; m_backBuffers.clear(); }
HRESULT CreateBackBuffers(uint32_t, DWORD);
};
#include "d3d9_production.inc"
void paired(bool enabled, D3DMULTISAMPLE_TYPE type, DWORD quality) {
D3D9DeviceEx device; device.options.forceSingleSample = enabled;
device.options.extraFrontbuffer = true;
D3D9SwapChainEx chain{&device, {}, {}};
chain.m_presentParams.MultiSampleType = type; chain.m_presentParams.MultiSampleQuality = quality;
assert(chain.CreateBackBuffers(2, 0) == D3D_OK);
D3D9_COMMON_TEXTURE_DESC depth;
assert(auto_depth(&device, &chain.m_presentParams, &depth) == D3D_OK);
VkSampleCountFlagBits requested, dsSamples;
assert(DecodeMultiSampleType(type, quality, &requested) == D3D_OK);
assert(DecodeMultiSampleType(depth.MultiSample, depth.MultisampleQuality, &dsSamples) == D3D_OK);
assert(chain.m_backBuffers.size() == 3 && device.context.initialized == 3);
for (const auto& surface : chain.m_backBuffers) {
const auto& image = surface->GetCommonTexture()->GetImage()->info;
assert(image.sampleCount == (enabled ? 1u : requested));
assert(depth_binds(image, {{depth.Width, depth.Height}, dsSamples}));
}
for (const auto& desc : device.created) {
assert(desc.IsLockable && desc.IsBackBuffer && !desc.IsAttachmentOnly);
assert(desc.MultiSample == (enabled ? D3DMULTISAMPLE_NONE : type));
assert(desc.MultisampleQuality == (enabled ? 0u : quality));
}
// Original presentation parameters remain available for reset/auto-depth validation.
assert(chain.m_presentParams.MultiSampleType == type && chain.m_presentParams.MultiSampleQuality == quality);
if (enabled && requested > 1) assert(device.adapter.checked.front() == D3DMULTISAMPLE_TYPE(requested));
}
int main(int argc, char** argv) {
assert(argc == 2); std::string name = argv[1];
if (name == "forced_msaa_depth") paired(true, D3DMULTISAMPLE_TYPE(4), 0);
else if (name == "default_msaa_depth") paired(false, D3DMULTISAMPLE_TYPE(4), 0);
else if (name == "forced_nonmaskable") paired(true, D3DMULTISAMPLE_NONMASKABLE, 2);
else if (name == "default_nonmaskable") paired(false, D3DMULTISAMPLE_NONMASKABLE, 2);
else if (name == "forced_already_single") paired(true, D3DMULTISAMPLE_NONE, 0);
else if (name == "forced_no_depth" || name == "forced_lockable_single") {
D3D9DeviceEx d; d.options.forceSingleSample = true;
D3D9SwapChainEx c{&d, {}, {}};
if (name == "forced_lockable_single") c.m_presentParams.MultiSampleType = D3DMULTISAMPLE_NONE;
assert(c.CreateBackBuffers(1, name == "forced_lockable_single" ? D3DPRESENTFLAG_LOCKABLE_BACKBUFFER : 0) == D3D_OK);
assert(c.m_backBuffers.size() == 1 && d.created[0].MultiSample == D3DMULTISAMPLE_NONE);
assert(d.created[0].IsLockable && d.context.initialized == 1);
} else if (name == "forced_unsupported" || name == "forced_invalid_type" || name == "forced_lockable_msaa") {
D3D9DeviceEx d; d.options.forceSingleSample = true;
D3D9SwapChainEx c{&d, {}, {}};
if (name == "forced_unsupported") d.adapter.supported = false;
if (name == "forced_invalid_type") c.m_presentParams.MultiSampleType = D3DMULTISAMPLE_TYPE(17);
HRESULT expected = name == "forced_unsupported" ? D3DERR_NOTAVAILABLE : D3DERR_INVALIDCALL;
assert(c.CreateBackBuffers(2, name == "forced_lockable_msaa" ? D3DPRESENTFLAG_LOCKABLE_BACKBUFFER : 0) == expected);
assert(d.attempts == 0 && d.losable == 0 && d.injected == 0 && c.m_backBuffers.empty());
} else if (name == "forced_allocation_failure" || name == "default_allocation_failure") {
D3D9DeviceEx d; d.options.forceSingleSample = name == "forced_allocation_failure"; d.failAt = 2;
D3D9SwapChainEx c{&d, {}, {}};
assert(c.CreateBackBuffers(3, 0) == D3DERR_OUTOFVIDEOMEMORY);
assert(d.attempts == 2 && d.losable == 1 && d.live == 0 && d.injected == 0 && c.m_backBuffers.empty());
} else if (name == "forced_recreate") {
D3D9DeviceEx d; d.options.forceSingleSample = true;
D3D9SwapChainEx c{&d, {}, {}};
assert(c.CreateBackBuffers(3, 0) == D3D_OK);
c.m_presentParams.MultiSampleType = D3DMULTISAMPLE_TYPE(8);
assert(c.CreateBackBuffers(1, 0) == D3D_OK);
assert(d.live == 1 && c.m_backBuffers.size() == 1 && c.destroys == 2);
assert(d.adapter.checked.size() == 2 && d.adapter.checked.back() == D3DMULTISAMPLE_TYPE(8));
assert(c.m_backBuffers[0]->GetCommonTexture()->GetImage()->info.sampleCount == 1);
} else if (name == "ordinary_surface" || name == "ordinary_invalid_lockable") {
D3D9DeviceEx d; d.options.forceSingleSample = true;
D3D9_COMMON_TEXTURE_DESC desc; desc.MultiSample = D3DMULTISAMPLE_TYPE(4);
desc.IsLockable = name == "ordinary_invalid_lockable";
assert(D3D9CommonTexture::NormalizeTextureProperties(&d, D3DRTYPE_SURFACE, &desc)
== (desc.IsLockable ? D3DERR_INVALIDCALL : D3D_OK));
if (!desc.IsLockable) assert(desc.MultiSample == D3DMULTISAMPLE_NONE && desc.MultisampleQuality == 0);
} else assert(false);
return 0;
}
+202
View File
@@ -0,0 +1,202 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#ifndef UFFD_USER_MODE_ONLY
#define UFFD_USER_MODE_ONLY 1
#endif
static unsigned char *arena, *store;
static size_t page, size, *offsets;
static int *lengths, uffd;
static atomic_int finished;
static unsigned faults;
static int (*decode)(const char *, char *, int, int);
static void fail(const char *name) {
perror(name);
exit(1);
}
static double milliseconds(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1000.0 + t.tv_nsec / 1000000.0;
}
static long resident_kb(void) {
FILE *f = fopen("/proc/self/status", "r");
if (!f) fail("status");
char line[256];
long value = -1;
while (fgets(line, sizeof(line), f)) {
if (sscanf(line, "VmRSS: %ld", &value) == 1) break;
}
fclose(f);
return value;
}
static int open_pager(void) {
int fd = (int)syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY);
if (fd < 0) fail("userfaultfd");
struct uffdio_api api = {.api = UFFD_API};
if (ioctl(fd, UFFDIO_API, &api)) fail("UFFDIO_API");
return fd;
}
static void register_range(int fd, void *address, size_t bytes) {
struct uffdio_register range = {
.range = {.start = (uintptr_t)address, .len = bytes},
.mode = UFFDIO_REGISTER_MODE_MISSING,
};
if (ioctl(fd, UFFDIO_REGISTER, &range)) fail("UFFDIO_REGISTER");
}
static void *serve(void *unused) {
(void)unused;
unsigned char *scratch = mmap(NULL, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (scratch == MAP_FAILED) fail("scratch");
struct pollfd p = {.fd = uffd, .events = POLLIN};
while (!atomic_load(&finished)) {
int ready = poll(&p, 1, 100);
if (ready < 0 && errno == EINTR) continue;
if (ready < 0 || (p.revents & (POLLERR | POLLHUP | POLLNVAL))) fail("pager poll");
if (!ready) continue;
struct uffd_msg msg;
ssize_t n = read(uffd, &msg, sizeof(msg));
if (n < 0 && errno == EAGAIN) continue;
if (n != sizeof(msg) || msg.event != UFFD_EVENT_PAGEFAULT) fail("pager event");
uintptr_t address = msg.arg.pagefault.address & ~(page - 1);
if (address < (uintptr_t)arena || address >= (uintptr_t)arena + size) fail("pager address");
size_t index = (address - (uintptr_t)arena) / page;
if (lengths[index] == 0) memcpy(scratch, store + offsets[index], page);
else if (decode((char *)store + offsets[index], (char *)scratch, lengths[index], (int)page) != (int)page)
fail("decompression");
struct uffdio_copy copy = {.dst = address, .src = (uintptr_t)scratch, .len = page};
if (ioctl(uffd, UFFDIO_COPY, &copy)) fail("UFFDIO_COPY");
faults++;
}
munmap(scratch, page);
return NULL;
}
static uint64_t checksum(void) {
uint64_t sum = 0;
for (size_t i = 0; i < size; i++) sum = sum * 31 + arena[i];
return sum;
}
static void kernel_access_probe(void) {
pid_t child = fork();
if (child < 0) fail("fork");
if (!child) {
alarm(2);
int fd = open_pager(), pipefd[2];
unsigned char *buffer = mmap(NULL, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buffer == MAP_FAILED || pipe(pipefd)) _exit(1);
memset(buffer, 0x5a, page);
register_range(fd, buffer, page);
if (madvise(buffer, page, MADV_DONTNEED)) _exit(1);
errno = 0;
ssize_t n = write(pipefd[1], buffer, page);
_exit(n < 0 && errno == EFAULT ? 42 : 1);
}
int status;
if (waitpid(child, &status, 0) < 0) fail("waitpid");
if (WIFSIGNALED(status)) printf("kernel_access_signal=%d\n", WTERMSIG(status));
else printf("kernel_access_exit=%d (42=EFAULT)\n", WEXITSTATUS(status));
}
int main(int argc, char **argv) {
if (argc > 2) return 2;
char *end = NULL;
long mb = argc == 2 ? strtol(argv[1], &end, 10) : 64;
if (mb < 1 || mb > 256 || (end && (*end || end == argv[1]))) return 2;
alarm(30);
page = (size_t)sysconf(_SC_PAGESIZE);
size = (size_t)mb << 20;
if (!page || size % page) return 2;
void *codec = dlopen("liblz4.so.1", RTLD_NOW | RTLD_LOCAL);
if (!codec) { fprintf(stderr, "%s\n", dlerror()); return 1; }
int (*encode)(const char *, char *, int, int) = dlsym(codec, "LZ4_compress_default");
int (*bound)(int) = dlsym(codec, "LZ4_compressBound");
decode = dlsym(codec, "LZ4_decompress_safe");
if (!encode || !decode || !bound) return 1;
arena = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
store = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (arena == MAP_FAILED || store == MAP_FAILED) fail("arena");
size_t count = size / page;
offsets = calloc(count, sizeof(*offsets));
lengths = calloc(count, sizeof(*lengths));
char *scratch = malloc((size_t)bound((int)page));
if (!offsets || !lengths || !scratch) fail("metadata");
uint32_t random = 123456789;
for (size_t i = 0; i < size; i++) {
if ((i / page) % 2) {
random ^= random << 13; random ^= random >> 17; random ^= random << 5;
arena[i] = (unsigned char)random;
} else arena[i] = (unsigned char)(i / page);
}
double start = milliseconds();
uint64_t before = checksum();
double baseline_ms = milliseconds() - start;
long before_kb = resident_kb();
uffd = open_pager();
register_range(uffd, arena, size);
start = milliseconds();
size_t used = 0;
for (size_t i = 0; i < count; i++) {
int n = encode((char *)arena + i * page, scratch, (int)page, bound((int)page));
if (n <= 0) fail("compression");
offsets[i] = used;
if ((size_t)n >= page) {
memcpy(store + used, arena + i * page, page);
used += page;
} else {
lengths[i] = n;
memcpy(store + used, scratch, (size_t)n);
used += (size_t)n;
}
}
if (madvise(arena, size, MADV_DONTNEED)) fail("eviction");
double compress_ms = milliseconds() - start;
long compressed_kb = resident_kb();
pthread_t pager;
if (pthread_create(&pager, NULL, serve, NULL)) fail("pthread_create");
start = milliseconds();
uint64_t after = checksum();
double restore_ms = milliseconds() - start;
int writable = 1;
for (size_t i = 0; i < size; i += page) {
unsigned char value = arena[i] ^ 0xff;
arena[i] = value;
if (*(volatile unsigned char *)(arena + i) != value) writable = 0;
}
atomic_store(&finished, 1);
pthread_join(pager, NULL);
printf("arena_mb=%ld compressed_bytes=%zu rss_before_kb=%ld rss_compressed_kb=%ld faults=%u intact=%d writable=%d\n",
mb, used, before_kb, compressed_kb, faults, before == after, writable);
printf("baseline_scan_ms=%.3f compress_ms=%.3f restore_scan_ms=%.3f\n", baseline_ms, compress_ms, restore_ms);
close(uffd);
munmap(arena, size); munmap(store, size);
free(offsets); free(lengths); free(scratch);
dlclose(codec);
kernel_access_probe();
return before == after && writable && faults == count ? 0 : 1;
}
+8 -1
View File
@@ -36,7 +36,14 @@ CONF
fi
rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src
for p in tools/fex/patches/*.patch; do patch -d fex-src -p1 --no-backup-if-mismatch < "$p"; done
for p in tools/fex/patches/*.patch; do
upstream=$(sed -n 's/^Fixed-upstream: FEX-\([0-9]\{4\}\)$/\1/p' "$p")
if [ -n "$upstream" ] && [ "${VERSION#FEX-}" -ge "$upstream" ]; then
echo "$(basename "$p"): already in FEX-$upstream, skipped for $VERSION"
continue
fi
patch -d fex-src -p1 --no-backup-if-mismatch < "$p"
done
if [ "$THUNKS" = 1 ]; then
for t in fex-src/Data/CMake/toolchain_x86_64.cmake fex-src/Data/CMake/toolchain_x86_32.cmake; do
printf '\nif (X86_DEV_ROOTFS AND NOT X86_DEV_ROOTFS STREQUAL "/")\n set(CMAKE_SYSROOT "${X86_DEV_ROOTFS}")\nendif()\n' >> "$t"
@@ -1,3 +1,4 @@
Fixed-upstream: FEX-2611
--- a/ThunkLibs/Generator/gen.cpp
+++ b/ThunkLibs/Generator/gen.cpp
@@ -840,6 +840,5 @@
+127 -5
View File
@@ -64,14 +64,79 @@ library list, before anything is published.
refresh output they now wait for it too, for at most `external_overlay_hold_cycles` refreshes (4,
so 30 fps at 120 Hz still merges), and are painted on their own after that.
The non-Adreno test branch's own patches are numbered 0920-0935 (0120-0135 until main took
0121-0125), so they apply after DroidDeck's. Applied in either order the tree is the same.
The system PowerVR driver uses the existing SDL/Wayland swapchain backend. Its additional patches are:
- `0920-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.
- `0921-powervr-single-pixel-rcas.patch`: use the existing single-pixel RCAS shader on PowerVR,
where the quad variant fails compilation.
- `0922-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.
- `0923-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.
- `0924-sdl-preserve-explicit-refresh.patch` and `0925-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.
- `0926-explicit-sync-switch.patch`: `GAMESCOPE_DISABLE_EXPLICIT_SYNC=1` makes the nested
(Wayland and SDL) backends report no explicit sync, so gamescope does not offer
wp_linux_drm_syncobj_manager_v1 and clients use implicit sync. The app sets it on a GPU that is
not an Adreno when the kernel is older than 6.6 (no DRM_IOCTL_SYNCOBJ_EVENTFD: an Exynos 2400e
on 6.1 logged hundreds of "timeline: DRM_IOCTL_SYNCOBJ_EVENTFD failed" and a game hung at a
black screen) or when the render node is Mali's stand-in (/dev/mali0 has no DRM syncobjs).
- `0927-shm-buffers-upload-every-commit.patch` (David Cimo, for Mali through Venus; his `0114`): with
no DRM node, Xwayland has no glamor and commits a few wl_shm buffers over and over with new pixels.
gamescope memoizes one texture per `wlr_buffer`, and a shm buffer's texture is a copy taken at
import, so the screen cycled through the first few frames forever while Steam ran on behind them.
Only dma-buf textures are memoized now; a shm buffer is uploaded on every commit. Adreno never
takes this path, since its Xwayland hands over dma-bufs. Also what XWAYLAND_NO_GLAMOR sessions need.
- `0929-log-failing-compute-pipeline.patch`: when `vkCreateComputePipelines` fails, one extra line
per shader type names the pipeline (shader type, layer count, ycbcr/colorspace masks, fp16) and the
SPIR-V capabilities its shader declares. A Mali-G615 through Venus refused all 119 composite
pipelines with VK_ERROR_INITIALIZATION_FAILED and nothing said which feature it objected to.
- `0930-composite-without-immutable-ycbcr-samplers.patch`: one composite pipeline is compiled at
start-up; when the driver refuses it, the descriptor layout is rebuilt without binding 4's immutable
YCbCr samplers (that binding then takes the slot's ordinary sampler) and the probe tried again, with
both outcomes in the log. `GAMESCOPE_NO_YCBCR_SAMPLERS=1` forces it. A Mali-G615 through Venus
refused every composite shader (blit, blur, RCAS: SPIR-V capabilities Shader, Sampled1D,
ImageQuery, no Float16) while EASU, NIS and the NV12 converter, which share the layout but never
touch binding 4, compiled.
- `0931-memory-type-fallback-keep-probe.patch`: `findMemoryType` asked for DEVICE_LOCAL|HOST_VISIBLE
memory falls back to host-visible memory without DEVICE_LOCAL, and a failure logs the requested
properties, the type bits and every memory type. The Mali bridge models a unified-memory GPU like a
discrete one (host-visible types without DEVICE_LOCAL), so the upload buffer found nothing and the
backend failed. Also: 0930's probe pipeline is kept instead of destroyed, and skipped when
`GAMESCOPE_NO_YCBCR_SAMPLERS=1` (destroying a pipeline the Venus host had refused killed the
render server).
- `0932-name-hung-up-waitable.patch`: "IWaitable hung up. Aborting." now names the waitable's class,
its fd and what the fd is (`/proc/self/fd`), and the Wayland backend's input thread says why the
compositor connection ended (protocol error or errno) first. An S24 FE aborted there after 60/120 Hz
flips and after a resume with nothing else in the log.
- `0933-flippable-image-unexportable-modifiers.patch`: a flippable (dma-buf exported) image whose
modifiers the driver supports but does not report EXPORTABLE uses them anyway, and an image with no
usable modifier fails with a log line instead of asserting in `CVulkanTexture::BInit`. The Mali
bridge forwards the phone driver's answer, which leaves EXPORTABLE out, though it exports dma-bufs.
- `0934-flippable-image-no-backend-modifiers.patch`: when the nested backend offers no modifier at all
for a flippable image's format, `CVulkanTexture::BInit` tries linear and logs it instead of asserting
`!modifiers.empty()`. NieR Replicant ended the session there on a Pixel 9a under Venus.
- `0935-flippable-image-linear-when-driver-rejects-all.patch`: when the driver answers every offered
modifier with `VK_ERROR_FORMAT_NOT_SUPPORTED` and linear was among them, the flippable image tries
linear anyway; if it cannot be made, `BInit` fails as before. An r32p1 Mali-G610 (Vulkan 1.1) behind
the Mali bridge rejected both of the backend's modifiers for AR24, so the session ended at start
(0933's "no usable modifier"); the bridge makes such images without the handle type and exports
them through a dma-heap.
- `0116-release-cursor-shm-buffers.patch` - this app: pointer cursor surfaces have no
X11/xdg window association, so routing their commits through `g_PendingCommits`
retained every old SHM buffer until the surface was destroyed. Ignore cursor-role
commits before taking the buffer lock; X11 cursor images still follow the existing
MouseCursor path. Window commits awaiting association are unchanged.
The shared DroidDeck patch also includes `0116-release-cursor-shm-buffers.patch`: pointer cursor
surfaces have no X11/xdg window association, so routing their commits through `g_PendingCommits`
retained every old SHM buffer until the surface was destroyed. It ignores cursor-role commits before
taking the buffer lock; X11 cursor images still follow the existing MouseCursor path. Window commits
awaiting association are unchanged.
The live regression probe is `tools/tests/test_gamescope_cursor_shm.py`. Run it
inside an active Gamescope session with access to that process's `/proc` fd
@@ -209,3 +274,60 @@ the connector's windows (`mangoapp_nudge_app_frame`). With `DROIDDECK_HUD_FRAMES
sets `/run/droiddeck-hud/frames`), gamescope maps that file and writes the same commits of connector 0,
whether or not a mangoapp runs, plus the focused pid, output size, refresh, Steam focus and engine name.
The layout is in the comment above `droiddeck_hud_frames_map`; the app reads it in `hudframes.c`.
## 0126 steamcompmgr: a topmost focus window keeps other processes' windows beneath it
EA games on Steam start through the EA app. Its Steam launcher (`EASteamLauncher.exe`) shows the
game's splash as a layered tool window, and the EA app (`EADesktop.exe`, another process) opens its
sign-in window `WS_EX_TOPMOST`. gamescope took the splash as the sign-in's override window, so it was
painted over most of the sign-in and became gamescope's keyboard focus window (Burnout Paradise
Remastered, `gamescopectl focus_info`). On Windows a topmost window stays above every window that is neither topmost nor
owned by it, so a window from another process that is neither is no longer an override candidate for
a topmost focus window. Both windows' pids must be known; gamescope keeps -1 when XRes cannot name the
client, which says nothing about the process. Same-process popups, topmost popups (WebView2 and CEF menus) and windows
transient for the focus window are unchanged. gamescope read `_WINE_HWND_EXSTYLE` only from a
PropertyNotify, and it listens for those from map on, so the style Wine sets before mapping a window
was never known; `map_win` now reads it with the other properties, which the layered-launcher and
Xalia rules rely on too. `tools/tests/test_gamescope_override_stacking.py` compiles the rule from
this patch.
## 0127 steamcompmgr: a three way relative mouse switch
`relative_mouse` is read where the decision is made: 0 leaves it to the rule below, 1 forces relative
motion for the focused game except Steam's own windows and composites the cursor, 2 never goes relative.
For games that confine a visible cursor and warp it, which the automatic rule cannot see.
## 0128 steamcompmgr: a hidden cursor under any pointer constraint is relative
The rule only counted a lock with a cursor position hint. A game that hides the cursor and confines the
pointer through a grab (Wine's ClipCursor) has a constraint with no hint, so the nested pointer stayed
absolute, the constraint held the X pointer still and no raw motion was produced: the camera froze.
## 0129 steamcompmgr, wayland: release a pointer lock at the game's pointer
A game can move the X pointer while it holds the lock (Wine's ClipCursor recentres it), and the nested host
never hears about it. On unlock the host's next absolute motion dropped the pointer back at its old position,
often near a corner. The unlock now sends the X pointer as a cursor position hint and commits it first. A cursor
forced On by `relative_mouse` also stays visible while idle, since the host cursor is hidden during the lock.
## 0130 steamcompmgr: fit the X screen to a larger fullscreen window
A game can open a fullscreen window larger than its X screen (Valheim at 1366x768 on 1280x720). The X server
keeps the pointer inside the screen, so the outer part of the window could not be reached and motion past the
edge had to be undone. The server's mode now follows such a window, and returns once the focused window fits,
focus moves to Steam or no window has focus.
## 0131 steamcompmgr, wlserver: follow a game's pointer warps
Under a nested host the seat's absolute position came from the host, so a game that warped a visible X pointer
to the screen centre read the distance back to the host's position on the next motion, and the view spun. When
the X pointer stays far from the seat position while input moves, gamescope takes the host's lock and applies
each frame's motion to the X pointer itself until the game stops warping. Absolute motion also sends relative
motion, as a real compositor does, so XInput2 raw motion reaches games that read only that. A touch moves the
pointer without relative motion, so tapping the screen does not turn the camera.
## 0132 sdl, steamcompmgr: follow a game's window mode
With `--follow-game-window-mode`, the outer window of a nested SDL gamescope follows the focused game window. A window
asking for `_NET_WM_STATE_FULLSCREEN`, or a Steam game covering the X screen without minimise or maximise functions or
decorations in `_MOTIF_WM_HINTS`, makes the outer window fullscreen on the desktop. Anything else makes it a normal window of the
game window's size, or a maximised one when that size does not fit the desktop with its title bar and panel. A change is applied only when the wanted mode changes, so a manual resize or Super+F stays.
+4 -1
View File
@@ -43,9 +43,12 @@ meson test -C src/build --no-rebuild --print-errorlogs cursor_routing wayland_sc
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
@@ -0,0 +1,43 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -4220,6 +4220,21 @@ static bool is_same_app_override_decorat
( candidate->hwndStyleEx & uDecorationStyle ) == uDecorationStyle;
}
+// Windows keeps a topmost window above every window that is neither topmost nor owned by it,
+// so another process's splash cannot cover a topmost sign-in (the EA app's, over its Steam launcher).
+static bool is_stacked_below_focus( steamcompmgr_win_t *candidate, steamcompmgr_win_t *focus )
+{
+ if ( candidate->pid <= 0 || focus->pid <= 0 || candidate->pid == focus->pid ||
+ !candidate->hasHwndStyleEx || !focus->hasHwndStyleEx )
+ return false;
+
+ if ( candidate->type == steamcompmgr_win_type_t::XWAYLAND && focus->type == steamcompmgr_win_type_t::XWAYLAND &&
+ candidate->xwayland().transientFor == focus->xwayland().id )
+ return false;
+
+ return ( focus->hwndStyleEx & WS_EX_TOPMOST ) && !( candidate->hwndStyleEx & WS_EX_TOPMOST );
+}
+
static bool is_good_override_candidate( steamcompmgr_win_t *override, steamcompmgr_win_t* focus )
{
// Some Chrome/Edge dropdowns (ie. FH5 xbox login) will automatically close themselves if you
@@ -4235,6 +4250,9 @@ static bool is_good_override_candidate(
if ( is_same_app_override_decoration( override, focus ) )
return false;
+ if ( is_stacked_below_focus( override, focus ) )
+ return false;
+
if ( override->pid != focus->pid && !windows_share_app( override, focus ) )
return false;
@@ -5836,6 +5854,7 @@ map_win(xwayland_ctx_t* ctx, Window id,
w->isSteamStreamingClient = get_prop(ctx, w->xwayland().id, ctx->atoms.steamStreamingClientAtom, 0);
w->isSteamStreamingClientVideo = get_prop(ctx, w->xwayland().id, ctx->atoms.steamStreamingClientVideoAtom, 0);
w->steamAppID = get_prop(ctx, w->xwayland().id, ctx->atoms.gameAtom, 0);
+ w->hwndStyleEx = get_prop(ctx, w->xwayland().id, ctx->atoms.wineHwndStyleEx, 0, &w->hasHwndStyleEx);
if ( steamMode == true )
{
@@ -0,0 +1,30 @@
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -3062,8 +3062,13 @@
#endif
gamescope::ConVar<int> cv_cursor_composite{ "cursor_composite", 1, "0 = Never composite a cursor. 1 = Composite cursor when not nested. 2 = Always composite a cursor manually" };
+static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
+"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
bool ShouldDrawCursor()
{
+ if ( cv_relative_mouse.Get() == 1 )
+ return true;
+
global_focus_t *pFocus = GetCurrentFocus();
gamescope::INestedHints *pNestedHints = pFocus ? pFocus->GetNestedHints() : nullptr;
return gamescope::CursorShouldBeComposited( cv_cursor_composite.Get(), g_bForceRelativeMouse,
@@ -10810,7 +10815,12 @@
const bool bExcludedAppId = uAppId && gamescope::Algorithm::Contains( s_uRelativeMouseFilteredAppids, uAppId );
- const bool bRelativeMouseMode = bImageEmpty && bHasPointerConstraint && !bExcludedAppId;
+ const int nRelativeMouse = cv_relative_mouse.Get();
+ const bool bForcedRelativeMouse = nRelativeMouse == 1 && !window_is_steam( pPaintFocus->inputFocusWindow );
+
+ const bool bRelativeMouseMode = nRelativeMouse == 2
+ ? false
+ : ( bForcedRelativeMouse || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
pPaintFocus->GetNestedHints()->SetRelativeMouseMode( bRelativeMouseMode );
}
@@ -0,0 +1,12 @@
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -10804,7 +10804,8 @@
( pPaintFocus->cursor && pPaintFocus->cursor->imageEmpty() ) &&
( !window_is_steam( pPaintFocus->inputFocusWindow ) );
- const bool bHasPointerConstraint = pPaintFocus->cursor && pPaintFocus->cursor->IsConstrained();
+ const bool bHasPointerConstraint = pPaintFocus->cursor &&
+ ( pPaintFocus->cursor->IsConstrained() || wlserver.HasMouseConstraint() );
uint32_t uAppId = pPaintFocus->inputFocusWindow
? pPaintFocus->inputFocusWindow->appID
@@ -0,0 +1,145 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 953765a..572fb0e 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -464,6 +464,7 @@ namespace gamescope
virtual void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info ) override;
virtual void SetRelativeMouseMode( bool bRelative ) override;
+ virtual void SetCursorPositionHint( double flX, double flY ) override;
virtual void SetVisible( bool bVisible ) override;
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) override;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) override;
@@ -719,6 +720,7 @@ namespace gamescope
void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info );
void SetRelativeMouseMode( wl_surface *pSurface, bool bRelative );
+ void SetCursorPositionHint( wl_fixed_t fSurfaceX, wl_fixed_t fSurfaceY );
void UpdateCursor();
friend CWaylandConnector;
@@ -1270,6 +1272,16 @@ namespace gamescope
// TODO: Do more tracking across multiple connectors, and activity here if we ever want to use this.
m_pBackend->SetRelativeMouseMode( m_Planes[0].GetSurface(), bRelative );
}
+ void CWaylandConnector::SetCursorPositionHint( double flX, double flY )
+ {
+ auto oState = m_Planes[0].GetCurrentState();
+ if ( !oState || !oState->uFractionalScale )
+ return;
+
+ const double flSurfaceX = ( flX * g_nOutputWidth - oState->nDestX ) * 120.0 / oState->uFractionalScale;
+ const double flSurfaceY = ( flY * g_nOutputHeight - oState->nDestY ) * 120.0 / oState->uFractionalScale;
+ m_pBackend->SetCursorPositionHint( wl_fixed_from_double( flSurfaceX ), wl_fixed_from_double( flSurfaceY ) );
+ }
void CWaylandConnector::SetVisible( bool bVisible )
{
if ( m_bVisible == bVisible )
@@ -2484,6 +2496,15 @@ namespace gamescope
UpdateCursor();
}
+ void CWaylandBackend::SetCursorPositionHint( wl_fixed_t fSurfaceX, wl_fixed_t fSurfaceY )
+ {
+ if ( !m_pLockedPointer )
+ return;
+
+ zwp_locked_pointer_v1_set_cursor_position_hint( m_pLockedPointer, fSurfaceX, fSurfaceY );
+ wl_surface_commit( m_pLockedSurface );
+ }
+
void CWaylandBackend::SetRelativeMouseMode( wl_surface *pSurface, bool bRelative )
{
if ( !m_pPointer )
diff --git a/src/backend.h b/src/backend.h
index d264917..37b936e 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -271,6 +271,7 @@ namespace gamescope
virtual void SetCursorImage( std::shared_ptr<CursorInfo> info ) = 0;
virtual void SetRelativeMouseMode( bool bRelative ) = 0;
+ virtual void SetCursorPositionHint( double flX, double flY ) {}
virtual void SetVisible( bool bVisible ) = 0;
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) = 0;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) = 0;
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index f1346e5..2c92afe 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -2078,6 +2078,18 @@ void MouseCursor::UpdatePosition()
}
}
+void MouseCursor::QueryRootPosition( int *pX, int *pY )
+{
+ Window root_ret, child_ret;
+ int win_x = 0, win_y = 0;
+ unsigned int mask;
+ *pX = m_x;
+ *pY = m_y;
+ XQueryPointer( m_ctx->dpy, DefaultRootWindow( m_ctx->dpy ), &root_ret, &child_ret, pX, pY, &win_x, &win_y, &mask );
+}
+
+static bool relative_mouse_forced();
+
void MouseCursor::checkSuspension()
{
getTexture();
@@ -2085,7 +2097,12 @@ void MouseCursor::checkSuspension()
if ( ShouldDrawCursor() )
{
const bool suspended = int64_t( get_time_in_nanos() ) - int64_t( wlserver.ulLastMovedCursorTime ) > int64_t( cursorHideTime );
- if (!wlserver.bCursorHidden && suspended) {
+ if ( relative_mouse_forced() && wlserver.bCursorHidden )
+ {
+ wlserver.bCursorHidden = false;
+ hasRepaintNonBasePlane = true;
+ }
+ if (!wlserver.bCursorHidden && suspended && !relative_mouse_forced()) {
wlserver.bCursorHidden = true;
steamcompmgr_win_t *window = m_ctx->focus.inputFocusWindow;
@@ -3064,6 +3081,11 @@ static void paint_pipewire()
gamescope::ConVar<int> cv_cursor_composite{ "cursor_composite", 1, "0 = Never composite a cursor. 1 = Composite cursor when not nested. 2 = Always composite a cursor manually" };
static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
+static bool relative_mouse_forced()
+{
+ return cv_relative_mouse.Get() == 1;
+}
+
bool ShouldDrawCursor()
{
if ( cv_relative_mouse.Get() == 1 )
@@ -10828,6 +10850,18 @@ steamcompmgr_main(int argc, char **argv)
? false
: ( bForcedRelativeMouse || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
+ static bool s_bRelativeMouseMode = false;
+ if ( s_bRelativeMouseMode && !bRelativeMouseMode && pPaintFocus->cursor &&
+ g_nOutputWidth && g_nOutputHeight && focusedWindowScaleX > 0.0f && focusedWindowScaleY > 0.0f )
+ {
+ int nRootX, nRootY;
+ pPaintFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
+ pPaintFocus->GetNestedHints()->SetCursorPositionHint(
+ ( nRootX / focusedWindowScaleX - focusedWindowOffsetX ) / g_nOutputWidth,
+ ( nRootY / focusedWindowScaleY - focusedWindowOffsetY ) / g_nOutputHeight );
+ }
+ s_bRelativeMouseMode = bRelativeMouseMode;
+
pPaintFocus->GetNestedHints()->SetRelativeMouseMode( bRelativeMouseMode );
}
diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp
index 7a7119f..ff54d8e 100644
--- a/src/steamcompmgr.hpp
+++ b/src/steamcompmgr.hpp
@@ -85,6 +85,7 @@ public:
}
void UpdatePosition();
+ void QueryRootPosition( int *pX, int *pY );
bool isHidden() { return wlserver.bCursorHidden || m_imageEmpty; }
bool imageEmpty() const { return m_imageEmpty; }
@@ -0,0 +1,94 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 2c92afe..17bae3a 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -4662,6 +4662,49 @@ static void set_wm_state( xwayland_ctx_t *ctx, Window win, uint32_t state )
sizeof(wmState) / sizeof(wmState[0]));
}
+static void
+fit_root_to_focus_window( xwayland_ctx_t *ctx )
+{
+ steamcompmgr_win_t *w = ctx->focus.focusWindow;
+ const bool bGame = w && !window_is_steam( w );
+ const int nWindowX = bGame ? w->xwayland().a.x : 0;
+ const int nWindowY = bGame ? w->xwayland().a.y : 0;
+ const int nWindowWidth = bGame ? w->xwayland().a.width : 0;
+ const int nWindowHeight = bGame ? w->xwayland().a.height : 0;
+ const int nBaseWidth = ctx->nFitRestoreWidth ? ctx->nFitRestoreWidth : ctx->root_width;
+ const int nBaseHeight = ctx->nFitRestoreWidth ? ctx->nFitRestoreHeight : ctx->root_height;
+ const bool bCoversBase = nWindowX == 0 && nWindowY == 0 && nWindowWidth >= nBaseWidth && nWindowHeight >= nBaseHeight;
+ const bool bPlausible = nWindowWidth <= 8192 && nWindowHeight <= 8192;
+
+ int nWidth = 0;
+ int nHeight = 0;
+ if ( bGame && bCoversBase && bPlausible && ( nWindowWidth > nBaseWidth || nWindowHeight > nBaseHeight ) )
+ {
+ if ( !ctx->nFitRestoreWidth )
+ {
+ ctx->nFitRestoreWidth = ctx->root_width;
+ ctx->nFitRestoreHeight = ctx->root_height;
+ }
+ nWidth = nWindowWidth;
+ nHeight = nWindowHeight;
+ }
+ else if ( ctx->nFitRestoreWidth && nWindowWidth <= ctx->nFitRestoreWidth && nWindowHeight <= ctx->nFitRestoreHeight )
+ {
+ nWidth = ctx->nFitRestoreWidth;
+ nHeight = ctx->nFitRestoreHeight;
+ ctx->nFitRestoreWidth = 0;
+ ctx->nFitRestoreHeight = 0;
+ }
+
+ if ( !nWidth || ( nWidth == ctx->root_width && nHeight == ctx->root_height ) )
+ return;
+
+ ctx->bFitPending = true;
+ wlserver_lock();
+ wlserver_set_xwayland_server_mode( ctx->xwayland_server->get_index(), nWidth, nHeight, g_nOutputRefresh );
+ wlserver_unlock();
+}
+
void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win_t* > &vecPossibleFocusWindows )
{
xwayland_ctx_t *ctx = this;
@@ -4736,6 +4779,8 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
inputFocus = ctx->focus.focusWindow;
}
+ fit_root_to_focus_window( ctx );
+
if ( ctx->focus.focusWindow )
{
if ( prevFocusWindow != ctx->focus.focusWindow )
@@ -5001,7 +5046,7 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
fs_width = ctx->root_width * steam_height_scale;
}
- if ( w->GetGeometry().nWidth != fs_width || w->GetGeometry().nHeight != fs_height || globalScaleRatio != 1.0f )
+ if ( !ctx->bFitPending && ( w->GetGeometry().nWidth != fs_width || w->GetGeometry().nHeight != fs_height || globalScaleRatio != 1.0f ) )
XResizeWindow(ctx->dpy, ctx->focus.focusWindow->xwayland().id, fs_width, fs_height);
}
else
@@ -6232,6 +6277,7 @@ configure_win(xwayland_ctx_t *ctx, XConfigureEvent *ce)
{
if (ce->window == ctx->root)
{
+ ctx->bFitPending = false;
ctx->root_width = ce->width;
ctx->root_height = ce->height;
MakeFocusDirty();
diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp
index 3a75650..15c2e6b 100644
--- a/src/xwayland_ctx.hpp
+++ b/src/xwayland_ctx.hpp
@@ -87,6 +87,9 @@ struct xwayland_ctx_t final : public gamescope::IWaitable
Window ourWindow;
focus_t focus;
+ int nFitRestoreWidth = 0;
+ int nFitRestoreHeight = 0;
+ bool bFitPending = false;
Window currentKeyboardFocusWindow;
Window focusControlWindow;
@@ -0,0 +1,216 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 17bae3a..c468fb3 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -32,6 +32,7 @@
#include "backend.h"
#include "gamescope_shared.h"
#include "xwayland_ctx.hpp"
+#include <cmath>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
@@ -2088,6 +2089,7 @@ void MouseCursor::QueryRootPosition( int *pX, int *pY )
XQueryPointer( m_ctx->dpy, DefaultRootWindow( m_ctx->dpy ), &root_ret, &child_ret, pX, pY, &win_x, &win_y, &mask );
}
+static bool s_bFollowClientPointer = false;
static bool relative_mouse_forced();
void MouseCursor::checkSuspension()
@@ -3083,12 +3085,89 @@ static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
static bool relative_mouse_forced()
{
- return cv_relative_mouse.Get() == 1;
+ return cv_relative_mouse.Get() == 1 || s_bFollowClientPointer;
+}
+
+static void update_client_pointer_follow( global_focus_t *pFocus, bool bAllowed )
+{
+ static int s_nAwayFrames = 0;
+ static int s_nQuietFrames = 0;
+ static uint64_t s_ulLastAway = 0;
+ static double s_flLastX = 0.0;
+ static double s_flLastY = 0.0;
+
+ int nRootX = 0;
+ int nRootY = 0;
+ if ( bAllowed && pFocus->cursor )
+ pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
+ else
+ bAllowed = false;
+
+ wlserver_lock();
+ const double flX = wlserver.mouse_surface_cursorx;
+ const double flY = wlserver.mouse_surface_cursory;
+ if ( !bAllowed )
+ {
+ s_nAwayFrames = 0;
+ s_bFollowClientPointer = false;
+ wlserver.bFollowClientPointer = false;
+ }
+ else if ( !s_bFollowClientPointer )
+ {
+ const bool bMoved = flX != s_flLastX || flY != s_flLastY;
+ if ( bMoved && ( std::abs( nRootX - flX ) > 48.0 || std::abs( nRootY - flY ) > 48.0 ) )
+ {
+ const uint64_t ulNow = get_time_in_nanos();
+ if ( ulNow - s_ulLastAway > 500'000'000ul )
+ s_nAwayFrames = 0;
+ s_ulLastAway = ulNow;
+ s_nAwayFrames++;
+ }
+
+ if ( s_nAwayFrames >= 3 )
+ {
+ s_nAwayFrames = 0;
+ s_nQuietFrames = 0;
+ s_bFollowClientPointer = true;
+ wlserver.bFollowClientPointer = true;
+ wlserver.flFollowDX = 0.0;
+ wlserver.flFollowDY = 0.0;
+ wlserver_mousewarp( nRootX, nRootY, 0, true );
+ }
+ }
+ else
+ {
+ const bool bWarped = std::abs( nRootX - flX ) > 2.0 || std::abs( nRootY - flY ) > 2.0;
+ const double flDX = std::trunc( wlserver.flFollowDX );
+ const double flDY = std::trunc( wlserver.flFollowDY );
+ if ( bWarped )
+ s_nQuietFrames = 0;
+ else if ( flDX != 0.0 || flDY != 0.0 )
+ s_nQuietFrames++;
+
+ if ( flDX != 0.0 || flDY != 0.0 || bWarped )
+ {
+ wlserver.flFollowDX -= flDX;
+ wlserver.flFollowDY -= flDY;
+ wlserver_mousewarp( nRootX, nRootY, 0, true );
+ if ( flDX != 0.0 || flDY != 0.0 )
+ wlserver_mousewarp( nRootX + flDX, nRootY + flDY, 0, true );
+ }
+
+ if ( s_nQuietFrames >= 60 )
+ {
+ s_bFollowClientPointer = false;
+ wlserver.bFollowClientPointer = false;
+ }
+ }
+ s_flLastX = wlserver.mouse_surface_cursorx;
+ s_flLastY = wlserver.mouse_surface_cursory;
+ wlserver_unlock();
}
bool ShouldDrawCursor()
{
- if ( cv_relative_mouse.Get() == 1 )
+ if ( relative_mouse_forced() )
return true;
global_focus_t *pFocus = GetCurrentFocus();
@@ -10892,9 +10971,15 @@ steamcompmgr_main(int argc, char **argv)
const int nRelativeMouse = cv_relative_mouse.Get();
const bool bForcedRelativeMouse = nRelativeMouse == 1 && !window_is_steam( pPaintFocus->inputFocusWindow );
+ if ( vblank )
+ {
+ update_client_pointer_follow( pPaintFocus,
+ nRelativeMouse != 2 && !bExcludedAppId && !bHasPointerConstraint && !window_is_steam( pPaintFocus->inputFocusWindow ) );
+ }
+
const bool bRelativeMouseMode = nRelativeMouse == 2
? false
- : ( bForcedRelativeMouse || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
+ : ( bForcedRelativeMouse || s_bFollowClientPointer || ( bImageEmpty && bHasPointerConstraint && !bExcludedAppId ) );
static bool s_bRelativeMouseMode = false;
if ( s_bRelativeMouseMode && !bRelativeMouseMode && pPaintFocus->cursor &&
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 5733871..cc75f8a 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -1,3 +1,4 @@
+#include <cmath>
#include <xkbcommon/xkbcommon-keysyms.h>
#define _GNU_SOURCE 1
@@ -3086,6 +3087,16 @@ void wlserver_mousemotion( double dx, double dy, uint32_t time )
wlserver_perform_rel_pointer_motion( dx, dy );
+ if ( wlserver.bFollowClientPointer )
+ {
+ wlserver.flFollowDX += dx;
+ wlserver.flFollowDY += dy;
+ wlserver.ulLastMovedCursorTime = get_time_in_nanos();
+ wlserver.bCursorHidden = !wlserver.bCursorHasImage;
+ wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ return;
+ }
+
if ( !wlserver_apply_constraint( &dx, &dy ) )
{
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
@@ -3110,10 +3121,18 @@ void wlserver_mousemotion( double dx, double dy, uint32_t time )
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
}
-void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic )
+void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic, bool bFromTouch )
{
assert( wlserver_is_lock_held() );
+ if ( !bSynthetic && wlserver.bFollowClientPointer )
+ return;
+
+ const double flStepX = x - wlserver.mouse_surface_cursorx;
+ const double flStepY = y - wlserver.mouse_surface_cursory;
+ if ( !bSynthetic && !bFromTouch && ( flStepX != 0.0 || flStepY != 0.0 ) && std::abs( flStepX ) < 256.0 && std::abs( flStepY ) < 256.0 )
+ wlserver_perform_rel_pointer_motion( flStepX, flStepY );
+
wlserver.mouse_surface_cursorx = x;
wlserver.mouse_surface_cursory = y;
@@ -3304,7 +3323,7 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
{
g_bPendingTouchMovement = true;
- wlserver_mousewarp( tx, ty, time, false );
+ wlserver_mousewarp( tx, ty, time, false, !bAlwaysWarpCursor );
}
}
@@ -3352,7 +3371,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
if ( eMode != gamescope::TouchClickModes::Trackpad )
{
- wlserver_mousewarp( tx, ty, time, false );
+ wlserver_mousewarp( tx, ty, time, false, true );
}
uint32_t button = TouchClickModeToLinuxButton( eMode );
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
index 79a0723..ca8d015 100644
--- a/src/wlserver.hpp
+++ b/src/wlserver.hpp
@@ -168,6 +168,9 @@ struct wlserver_t {
uint64_t ulLastMovedCursorTime = 0;
bool bCursorHidden = true;
bool bCursorHasImage = true;
+ bool bFollowClientPointer = false;
+ double flFollowDX = 0.0;
+ double flFollowDY = 0.0;
bool button_held[ WLSERVER_BUTTON_COUNT ];
std::set <uint32_t> touch_down_ids;
@@ -271,7 +274,7 @@ void wlserver_clear_dropdowns();
void wlserver_notify_dropdown( struct wlr_surface *wlrsurface, int nX, int nY );
void wlserver_mousemotion( double x, double y, uint32_t time );
void wlserver_mousehide();
-void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic );
+void wlserver_mousewarp( double x, double y, uint32_t time, bool bSynthetic, bool bFromTouch = false );
void wlserver_mousebutton( int button, bool press, uint32_t time );
void wlserver_mousewheel( double x, double y, uint32_t time );
bool wlserver_input_held();
@@ -0,0 +1,254 @@
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
index 58af150..b050183 100644
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -51,6 +51,7 @@ namespace gamescope
GAMESCOPE_SDL_EVENT_VISIBLE,
GAMESCOPE_SDL_EVENT_GRAB,
GAMESCOPE_SDL_EVENT_CURSOR,
+ GAMESCOPE_SDL_EVENT_WINDOW_MODE,
GAMESCOPE_SDL_EVENT_COUNT,
};
@@ -114,6 +115,7 @@ namespace gamescope
virtual void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info ) override;
virtual void SetRelativeMouseMode( bool bRelative ) override;
virtual void SetVisible( bool bVisible ) override;
+ virtual void SetWindowMode( bool bFullscreen, int nWidth, int nHeight ) override;
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) override;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) override;
virtual void SetSelection( std::shared_ptr<std::string> szContents, GamescopeSelection eSelection ) override;
@@ -179,6 +181,7 @@ namespace gamescope
void SetCursorImage( std::shared_ptr<INestedHints::CursorInfo> info );
void SetRelativeMouseMode( bool bRelative );
void SetVisible( bool bVisible );
+ void SetWindowMode( bool bFullscreen, int nWidth, int nHeight );
void SetTitle( std::shared_ptr<std::string> szTitle );
void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels );
void SetSelection( std::shared_ptr<std::string> szContents, GamescopeSelection eSelection );
@@ -193,6 +196,12 @@ namespace gamescope
bool m_bShown = false;
CSDLConnector m_Connector; // Window.
uint32_t m_uUserEventIdBase = 0u;
+ std::atomic<bool> m_bWantFullscreen = { false };
+ std::atomic<int> m_nWantWidth = { 0 };
+ std::atomic<int> m_nWantHeight = { 0 };
+ bool m_bAppliedFullscreen = false;
+ int m_nAppliedWidth = 0;
+ int m_nAppliedHeight = 0;
std::vector<const char *> m_pszInstanceExtensions;
std::thread m_SDLThread;
@@ -372,6 +381,10 @@ namespace gamescope
{
m_pBackend->SetVisible( bVisible );
}
+ void CSDLConnector::SetWindowMode( bool bFullscreen, int nWidth, int nHeight )
+ {
+ m_pBackend->SetWindowMode( bFullscreen, nWidth, nHeight );
+ }
void CSDLConnector::SetTitle( std::shared_ptr<std::string> szTitle )
{
m_pBackend->SetTitle( std::move( szTitle ) );
@@ -544,6 +557,13 @@ namespace gamescope
m_bApplicationVisible = bVisible;
PushUserEvent( GAMESCOPE_SDL_EVENT_VISIBLE );
}
+ void CSDLBackend::SetWindowMode( bool bFullscreen, int nWidth, int nHeight )
+ {
+ m_bWantFullscreen = bFullscreen;
+ m_nWantWidth = nWidth;
+ m_nWantHeight = nHeight;
+ PushUserEvent( GAMESCOPE_SDL_EVENT_WINDOW_MODE );
+ }
void CSDLBackend::SetTitle( std::shared_ptr<std::string> szTitle )
{
m_pApplicationTitle = szTitle;
@@ -894,6 +914,38 @@ namespace gamescope
}
}
}
+ else if ( event.type == GetUserEventIndex( GAMESCOPE_SDL_EVENT_WINDOW_MODE ) )
+ {
+ const bool bFullscreen = m_bWantFullscreen;
+ const int nWidth = bFullscreen ? 0 : m_nWantWidth.load();
+ const int nHeight = bFullscreen ? 0 : m_nWantHeight.load();
+
+ if ( bFullscreen != m_bAppliedFullscreen || nWidth != m_nAppliedWidth || nHeight != m_nAppliedHeight )
+ {
+ m_bAppliedFullscreen = bFullscreen;
+ m_nAppliedWidth = nWidth;
+ m_nAppliedHeight = nHeight;
+ g_bFullscreen = bFullscreen;
+ SDL_SetWindowFullscreen( m_Connector.GetSDLWindow(), bFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0 );
+ if ( !bFullscreen )
+ {
+ static constexpr int k_nDesktopChromeHeight = 96;
+
+ SDL_Rect usable = {};
+ const int nDisplay = SDL_GetWindowDisplayIndex( m_Connector.GetSDLWindow() );
+ const bool bKnown = SDL_GetDisplayUsableBounds( nDisplay, &usable ) == 0;
+ if ( bKnown && ( nWidth > usable.w || nHeight + k_nDesktopChromeHeight > usable.h ) )
+ {
+ SDL_MaximizeWindow( m_Connector.GetSDLWindow() );
+ }
+ else
+ {
+ SDL_RestoreWindow( m_Connector.GetSDLWindow() );
+ SDL_SetWindowSize( m_Connector.GetSDLWindow(), nWidth, nHeight );
+ }
+ }
+ }
+ }
else if ( event.type == GetUserEventIndex( GAMESCOPE_SDL_EVENT_TITLE ) )
{
std::shared_ptr<std::string> pAppTitle = m_pApplicationTitle;
diff --git a/src/backend.h b/src/backend.h
index 37b936e..fbfa7c7 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -273,6 +273,7 @@ namespace gamescope
virtual void SetRelativeMouseMode( bool bRelative ) = 0;
virtual void SetCursorPositionHint( double flX, double flY ) {}
virtual void SetVisible( bool bVisible ) = 0;
+ virtual void SetWindowMode( bool bFullscreen, int nWidth, int nHeight ) {}
virtual void SetTitle( std::shared_ptr<std::string> szTitle ) = 0;
virtual void SetIcon( std::shared_ptr<std::vector<uint32_t>> uIconPixels ) = 0;
virtual void SetSelection( std::shared_ptr<std::string> szContents, GamescopeSelection eSelection ) = 0;
diff --git a/src/main.cpp b/src/main.cpp
index eef4264..8f0ddd3 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -73,6 +73,7 @@ const struct option *gamescope_options = (struct option[]){
{ "rt", no_argument, nullptr, 0 },
{ "prefer-vk-device", required_argument, 0 },
{ "expose-wayland", no_argument, 0 },
+ { "follow-game-window-mode", no_argument, 0 },
{ "mouse-sensitivity", required_argument, nullptr, 's' },
{ "mangoapp", no_argument, nullptr, 0 },
{ "adaptive-sync", no_argument, nullptr, 0 },
@@ -700,6 +701,7 @@ static void UpdateCompatEnvVars()
int g_nPreferredOutputWidth = 0;
int g_nPreferredOutputHeight = 0;
bool g_bExposeWayland = false;
+bool g_bFollowGameWindowMode = false;
const char *g_sOutputName = nullptr;
bool g_bDebugLayers = false;
bool g_bForceDisableColorMgmt = false;
@@ -838,6 +840,8 @@ int main(int argc, char **argv)
cv_adaptive_sync = true;
} else if (strcmp(opt_name, "expose-wayland") == 0) {
g_bExposeWayland = true;
+ } else if (strcmp(opt_name, "follow-game-window-mode") == 0) {
+ g_bFollowGameWindowMode = true;
} else if (strcmp(opt_name, "backend") == 0) {
eCurrentBackend = parse_backend_name( optarg );
} else if (strcmp(opt_name, "cursor-scale-height") == 0) {
diff --git a/src/main.hpp b/src/main.hpp
index b2a169f..48929f2 100644
--- a/src/main.hpp
+++ b/src/main.hpp
@@ -134,6 +134,7 @@ extern int g_upscaleFilterSharpness;
extern bool g_bBorderlessOutputWindow;
extern bool g_bExposeWayland;
+extern bool g_bFollowGameWindowMode;
extern bool g_bRt;
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index c468fb3..3188b74 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -4741,6 +4741,54 @@ static void set_wm_state( xwayland_ctx_t *ctx, Window win, uint32_t state )
sizeof(wmState) / sizeof(wmState[0]));
}
+static bool
+window_offers_frame_controls( xwayland_ctx_t *ctx, steamcompmgr_win_t *w )
+{
+ static constexpr unsigned long k_ulMotifFunctions = 1ul << 0;
+ static constexpr unsigned long k_ulMotifMinimize = 1ul << 3;
+ static constexpr unsigned long k_ulMotifMaximize = 1ul << 4;
+ static constexpr unsigned long k_ulMotifDecorations = 1ul << 1;
+
+ Atom type;
+ int format;
+ unsigned long nitems;
+ unsigned long bytesAfter;
+ unsigned char *data = nullptr;
+ if ( XGetWindowProperty( ctx->dpy, w->xwayland().id, ctx->atoms.motifWMHintsAtom, 0, 3, false,
+ AnyPropertyType, &type, &format, &nitems, &bytesAfter, &data ) != Success )
+ return false;
+
+ bool bControls = false;
+ if ( data && format == 32 && nitems >= 3 )
+ {
+ const long *hints = (const long *)data;
+ bControls = ( ( hints[0] & k_ulMotifFunctions ) && ( hints[1] & ( k_ulMotifMinimize | k_ulMotifMaximize ) ) ) ||
+ ( ( hints[0] & k_ulMotifDecorations ) && hints[2] );
+ }
+ if ( data )
+ XFree( data );
+ return bControls;
+}
+
+static void
+apply_game_window_mode( global_focus_t *pFocus )
+{
+ static constexpr int k_nSmallestFollowedWindow = 64;
+
+ steamcompmgr_win_t *w = pFocus->focusWindow;
+ if ( !g_bFollowGameWindowMode || !pFocus->GetNestedHints() || !w || w->type != steamcompmgr_win_type_t::XWAYLAND )
+ return;
+
+ xwayland_ctx_t *ctx = w->xwayland().ctx;
+ const XWindowAttributes &a = w->xwayland().a;
+ if ( a.width < k_nSmallestFollowedWindow || a.height < k_nSmallestFollowedWindow )
+ return;
+
+ const bool bCoversScreen = a.x == 0 && a.y == 0 && a.width >= ctx->root_width && a.height >= ctx->root_height;
+ const bool bFullscreen = w->isFullscreen || ( w->appID && bCoversScreen && !window_offers_frame_controls( ctx, w ) );
+ pFocus->GetNestedHints()->SetWindowMode( bFullscreen, a.width, a.height );
+}
+
static void
fit_root_to_focus_window( xwayland_ctx_t *ctx )
{
@@ -5739,6 +5787,7 @@ determine_and_apply_focus( global_focus_t *pFocus )
if ( pFocus->focusWindow )
{
pFocus->GetNestedHints()->SetVisible( true );
+ apply_game_window_mode( pFocus );
if ( previousLocalFocus.focusWindow != pFocus->focusWindow )
{
pFocus->GetNestedHints()->SetTitle( pFocus->focusWindow->title );
@@ -7083,6 +7132,8 @@ static inline float santitize_float( float f )
static void
handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev)
{
+ if (ev->atom == ctx->atoms.motifWMHintsAtom)
+ MakeFocusDirty();
/* check if Trans property was changed */
if (ev->atom == ctx->atoms.opacityAtom)
{
@@ -9216,6 +9267,7 @@ void init_xwayland_ctx(uint32_t serverId, gamescope_xwayland_server_t *xwayland_
ctx->atoms.winNormalAtom = XInternAtom(ctx->dpy, "_NET_WM_WINDOW_TYPE_NORMAL", false);
ctx->atoms.sizeHintsAtom = XInternAtom(ctx->dpy, "WM_NORMAL_HINTS", false);
ctx->atoms.netWMStateFullscreenAtom = XInternAtom(ctx->dpy, "_NET_WM_STATE_FULLSCREEN", false);
+ ctx->atoms.motifWMHintsAtom = XInternAtom(ctx->dpy, "_MOTIF_WM_HINTS", false);
ctx->atoms.netActiveWindowAtom = XInternAtom(ctx->dpy, "_NET_ACTIVE_WINDOW", false);
ctx->atoms.netWMStateAtom = XInternAtom(ctx->dpy, "_NET_WM_STATE", false);
ctx->atoms.WMTransientForAtom = XInternAtom(ctx->dpy, "WM_TRANSIENT_FOR", false);
diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp
index 15c2e6b..525b155 100644
--- a/src/xwayland_ctx.hpp
+++ b/src/xwayland_ctx.hpp
@@ -128,6 +128,7 @@ struct xwayland_ctx_t final : public gamescope::IWaitable
Atom winNormalAtom;
Atom sizeHintsAtom;
Atom netWMStateFullscreenAtom;
+ Atom motifWMHintsAtom;
Atom netActiveWindowAtom;
Atom netWMStateAtom;
Atom WMTransientForAtom;
@@ -0,0 +1,333 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 953765a..73ab9cc 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -14,2 +14,3 @@
#include "Utils/WaylandScaling.h"
+#include "droiddeck_frame_trace.hpp"
@@ -1002,2 +1003,4 @@ namespace gamescope
+ droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputRelease );
+
xdg_log.debugf( "buffer_release: %p", pBuffer );
@@ -1079,2 +1082,3 @@ namespace gamescope
{
+ droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputPresent );
UpdateFullscreenState();
@@ -1485,2 +1489,3 @@ namespace gamescope
{
+ droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputAttach );
assert( oState->pBuffer );
@@ -1633,2 +1638,3 @@ namespace gamescope
{
+ droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputDetach );
wl_surface_attach( m_pSurface, nullptr, 0, 0 );
@@ -1650,2 +1656,3 @@ namespace gamescope
{
+ droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputCommit );
if ( m_bNeedsDecorCommit )
diff --git a/src/droiddeck_frame_trace.hpp b/src/droiddeck_frame_trace.hpp
new file mode 100644
index 0000000..2c57f65
--- /dev/null
+++ b/src/droiddeck_frame_trace.hpp
@@ -0,0 +1,191 @@
+#pragma once
+
+#include <atomic>
+#include <chrono>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+
+#ifndef DROIDDECK_FRAME_TRACE_FAST_INTERVAL_MS
+#define DROIDDECK_FRAME_TRACE_FAST_INTERVAL_MS 2000
+#endif
+#ifndef DROIDDECK_FRAME_TRACE_SLOW_INTERVAL_MS
+#define DROIDDECK_FRAME_TRACE_SLOW_INTERVAL_MS 15000
+#endif
+#ifndef DROIDDECK_FRAME_TRACE_FAST_DURATION_MS
+#define DROIDDECK_FRAME_TRACE_FAST_DURATION_MS 120000
+#endif
+#ifndef DROIDDECK_FRAME_TRACE_DURATION_MS
+#define DROIDDECK_FRAME_TRACE_DURATION_MS 86400000
+#endif
+
+namespace droiddeck::frame_trace
+{
+
+enum class Event : uint32_t
+{
+ X11Damage,
+ X11DamageCurrent,
+ X11DamageOther,
+ SurfaceCommit,
+ SurfaceCommitBuffer,
+ SurfaceCommitNoBuffer,
+ CommitDequeued,
+ CommitDequeuedCurrent,
+ CommitDequeuedOther,
+ ImportSucceeded,
+ ImportSucceededCurrent,
+ ImportSucceededOther,
+ ImportFailed,
+ ImportFailedCurrent,
+ ImportFailedOther,
+ FenceReady,
+ FenceWaited,
+ CommitDone,
+ CommitDoneCurrent,
+ CommitDoneOther,
+ BaseLatched,
+ BaseLatchedCurrent,
+ BaseLatchedOther,
+ OutputPresent,
+ OutputAttach,
+ OutputDetach,
+ OutputCommit,
+ OutputRelease,
+ Count,
+};
+
+class State
+{
+public:
+ State()
+ : m_enabled( EnabledByEnvironment() )
+ {
+ }
+
+ void Start()
+ {
+ if ( !m_enabled || m_started.exchange( true, std::memory_order_relaxed ) )
+ return;
+
+ m_startedAt = std::chrono::steady_clock::now();
+ m_nextSummaryMs = kFastIntervalMs;
+ std::fprintf( stderr,
+ "DROIDDECK_FRAME_TRACE schema=1 fast_interval_ms=%ld slow_interval_ms=%ld "
+ "fast_duration_ms=%ld duration_ms=%ld\n",
+ kFastIntervalMs, kSlowIntervalMs, kFastDurationMs, kDurationMs );
+ PrintSummary( 0 );
+ }
+
+ void Record( Event event )
+ {
+ if ( !m_enabled || !m_started.load( std::memory_order_relaxed ) ||
+ !m_active.load( std::memory_order_relaxed ) )
+ return;
+ m_counts[static_cast<uint32_t>( event )].fetch_add( 1, std::memory_order_relaxed );
+ }
+
+ void Tick()
+ {
+ if ( !m_enabled || !m_started.load( std::memory_order_relaxed ) ||
+ !m_active.load( std::memory_order_relaxed ) )
+ return;
+
+ const int64_t elapsed = ElapsedMs();
+ if ( elapsed >= kDurationMs )
+ {
+ PrintSummary( kDurationMs );
+ m_active.store( false, std::memory_order_relaxed );
+ return;
+ }
+ if ( elapsed < m_nextSummaryMs )
+ return;
+
+ PrintSummary( elapsed );
+ m_nextSummaryMs = elapsed + ( elapsed < kFastDurationMs ? kFastIntervalMs : kSlowIntervalMs );
+ }
+
+private:
+ static constexpr int64_t kFastIntervalMs = DROIDDECK_FRAME_TRACE_FAST_INTERVAL_MS;
+ static constexpr int64_t kSlowIntervalMs = DROIDDECK_FRAME_TRACE_SLOW_INTERVAL_MS;
+ static constexpr int64_t kFastDurationMs = DROIDDECK_FRAME_TRACE_FAST_DURATION_MS;
+ static constexpr int64_t kDurationMs = DROIDDECK_FRAME_TRACE_DURATION_MS;
+
+ static bool EnabledByEnvironment()
+ {
+ const char *value = std::getenv( "DROIDDECK_ENHANCED_DIAGNOSTICS" );
+ return value != nullptr && std::strcmp( value, "1" ) == 0;
+ }
+
+ int64_t ElapsedMs() const
+ {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - m_startedAt ).count();
+ }
+
+ uint64_t Count( Event event ) const
+ {
+ return m_counts[static_cast<uint32_t>( event )].load( std::memory_order_relaxed );
+ }
+
+ void PrintSummary( int64_t elapsed ) const
+ {
+ std::fprintf( stderr,
+ "DROIDDECK_FRAME_TRACE t_ms=%ld x11_damage=%lu x11_damage_current=%lu x11_damage_other=%lu "
+ "surface_commit=%lu surface_buffer=%lu surface_no_buffer=%lu dequeued=%lu dequeued_current=%lu "
+ "dequeued_other=%lu import_ok=%lu import_ok_current=%lu import_ok_other=%lu import_failed=%lu "
+ "import_failed_current=%lu import_failed_other=%lu fence_ready=%lu fence_waited=%lu commit_done=%lu "
+ "commit_done_current=%lu commit_done_other=%lu base_latched=%lu base_latched_current=%lu "
+ "base_latched_other=%lu output_present=%lu output_attach=%lu "
+ "output_detach=%lu output_commit=%lu output_release=%lu\n",
+ elapsed,
+ Count( Event::X11Damage ), Count( Event::X11DamageCurrent ), Count( Event::X11DamageOther ),
+ Count( Event::SurfaceCommit ), Count( Event::SurfaceCommitBuffer ), Count( Event::SurfaceCommitNoBuffer ),
+ Count( Event::CommitDequeued ), Count( Event::CommitDequeuedCurrent ), Count( Event::CommitDequeuedOther ),
+ Count( Event::ImportSucceeded ), Count( Event::ImportSucceededCurrent ), Count( Event::ImportSucceededOther ),
+ Count( Event::ImportFailed ), Count( Event::ImportFailedCurrent ), Count( Event::ImportFailedOther ),
+ Count( Event::FenceReady ), Count( Event::FenceWaited ), Count( Event::CommitDone ),
+ Count( Event::CommitDoneCurrent ), Count( Event::CommitDoneOther ), Count( Event::BaseLatched ),
+ Count( Event::BaseLatchedCurrent ), Count( Event::BaseLatchedOther ), Count( Event::OutputPresent ),
+ Count( Event::OutputAttach ), Count( Event::OutputDetach ), Count( Event::OutputCommit ),
+ Count( Event::OutputRelease ) );
+ std::fflush( stderr );
+ }
+
+ bool m_enabled;
+ std::atomic<bool> m_started{ false };
+ std::atomic<bool> m_active{ true };
+ std::chrono::steady_clock::time_point m_startedAt{};
+ int64_t m_nextSummaryMs = 0;
+ std::atomic<uint64_t> m_counts[static_cast<uint32_t>( Event::Count )]{};
+};
+
+inline State &GetState()
+{
+ static State state;
+ return state;
+}
+
+inline void Start()
+{
+ GetState().Start();
+}
+
+inline void Record( Event event )
+{
+ GetState().Record( event );
+}
+
+inline void RecordWindow( Event total, Event focused, Event other, bool isFocused )
+{
+ Record( total );
+ Record( isFocused ? focused : other );
+}
+
+inline void Tick()
+{
+ GetState().Tick();
+}
+
+}
diff --git a/src/main.cpp b/src/main.cpp
index eef4264..1d22ba4 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -35,2 +35,3 @@
#include "Utils/Version.h"
+#include "droiddeck_frame_trace.hpp"
@@ -718,2 +719,3 @@ int main(int argc, char **argv)
g_argv = argv;
+ droiddeck::frame_trace::Start();
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index b4c6830..46e7a6c 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -32,2 +32,3 @@
#include "backend.h"
+#include "droiddeck_frame_trace.hpp"
#include "gamescope_shared.h"
@@ -6419,2 +6420,9 @@ damage_win(xwayland_ctx_t *ctx, XDamageNotifyEvent *de)
+ global_focus_t *pTraceFocus = GetCurrentFocus();
+ droiddeck::frame_trace::RecordWindow(
+ droiddeck::frame_trace::Event::X11Damage,
+ droiddeck::frame_trace::Event::X11DamageCurrent,
+ droiddeck::frame_trace::Event::X11DamageOther,
+ pTraceFocus != nullptr && pTraceFocus->focusWindow == w );
+
if (w->IsAnyOverlay() && !w->opacity)
@@ -7999,2 +8007,8 @@ bool handle_done_commit( steamcompmgr_win_t *w, xwayland_ctx_t *ctx, uint64_t co
{
+ global_focus_t *pTraceFocus = GetCurrentFocus();
+ droiddeck::frame_trace::RecordWindow(
+ droiddeck::frame_trace::Event::CommitDone,
+ droiddeck::frame_trace::Event::CommitDoneCurrent,
+ droiddeck::frame_trace::Event::CommitDoneOther,
+ pTraceFocus != nullptr && pTraceFocus->focusWindow == w );
gpuvis_trace_printf( "commit %lu done", w->commit_queue[ j ]->commitID );
@@ -8049,3 +8063,10 @@ bool handle_done_commit( steamcompmgr_win_t *w, xwayland_ctx_t *ctx, uint64_t co
if ( !cv_paint_debug_pause_base_plane )
+ {
pFocus->HeldCommits[ HELD_COMMIT_BASE ] = w->commit_queue[ j ];
+ droiddeck::frame_trace::RecordWindow(
+ droiddeck::frame_trace::Event::BaseLatched,
+ droiddeck::frame_trace::Event::BaseLatchedCurrent,
+ droiddeck::frame_trace::Event::BaseLatchedOther,
+ pFocus == GetCurrentFocus() );
+ }
hasRepaint = true;
@@ -8397,2 +8418,4 @@ static void note_commit_fence( bool bReadyAtImport )
{
+ droiddeck::frame_trace::Record( bReadyAtImport ? droiddeck::frame_trace::Event::FenceReady
+ : droiddeck::frame_trace::Event::FenceWaited );
static uint64_t s_ulReady = 0, s_ulWaited = 0, s_ulLastLog = 0;
@@ -8412,2 +8435,9 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
{
+ global_focus_t *pTraceFocus = GetCurrentFocus();
+ const bool bTraceCurrent = pTraceFocus != nullptr && pTraceFocus->focusWindow == w;
+ droiddeck::frame_trace::RecordWindow(
+ droiddeck::frame_trace::Event::CommitDequeued,
+ droiddeck::frame_trace::Event::CommitDequeuedCurrent,
+ droiddeck::frame_trace::Event::CommitDequeuedOther,
+ bTraceCurrent );
struct wlr_buffer *buf = reslistentry.buf;
@@ -8501,2 +8531,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
{
+ droiddeck::frame_trace::RecordWindow(
+ droiddeck::frame_trace::Event::ImportFailed,
+ droiddeck::frame_trace::Event::ImportFailedCurrent,
+ droiddeck::frame_trace::Event::ImportFailedOther,
+ bTraceCurrent );
// Import failed to import, early exit.
@@ -8504,2 +8539,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
}
+ droiddeck::frame_trace::RecordWindow(
+ droiddeck::frame_trace::Event::ImportSucceeded,
+ droiddeck::frame_trace::Event::ImportSucceededCurrent,
+ droiddeck::frame_trace::Event::ImportSucceededOther,
+ bTraceCurrent );
@@ -8679,3 +8719,2 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
}
-
gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 );
@@ -10256,2 +10295,3 @@ steamcompmgr_main(int argc, char **argv)
{
+ droiddeck::frame_trace::Tick();
{
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 5733871..ed4dbc3 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -24,2 +24,3 @@
#include "WaylandServer/GamescopeLimiter.h"
+#include "droiddeck_frame_trace.hpp"
@@ -210,2 +211,8 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
+ droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::SurfaceCommit );
+ droiddeck::frame_trace::Record(
+ ( wlr_surface->current.committed & WLR_SURFACE_STATE_BUFFER )
+ ? droiddeck::frame_trace::Event::SurfaceCommitBuffer
+ : droiddeck::frame_trace::Event::SurfaceCommitNoBuffer );
+
wlr_surface->current.committed = 0;
@@ -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 <algorithm>
+#include <vulkan/vulkan_core.h>
+
+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 <deque>
#include <dlfcn.h>
#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<void *>( &presentIdFeatures ) : static_cast<void *>( &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<CVulkanTexture> 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<uint64_t> 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<gamescope::IBackendFb> 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<gamescope::BackendBlob> swapchainHDRMetadata;
VkSwapchainKHR swapChain;
- VkFence acquireFence;
+ VkFence acquireFence = VK_NULL_HANDLE;
+ bool copyToSwapchain = false;
+ std::vector<gamescope::OwningRc<CVulkanTexture>> presentationImages;
uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs
std::vector<gamescope::OwningRc<CVulkanTexture>> 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;
@@ -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);
}
@@ -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 <dlfcn.h>
#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 <vulkan/vulkan_core.h>
+
+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;
+}
+}
@@ -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 <vulkan/vulkan_core.h>
+
+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++ )
@@ -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 <cstdint>
+
+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;
@@ -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 );
@@ -0,0 +1,29 @@
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -2309,7 +2309,10 @@
bool CWaylandBackend::SupportsExplicitSync() const
{
- return true;
+ // GAMESCOPE_DISABLE_EXPLICIT_SYNC=1: a kernel without DRM_IOCTL_SYNCOBJ_EVENTFD (before
+ // Linux 6.6) cannot signal the timelines, so clients use implicit sync instead.
+ const char *pszDisable = getenv( "GAMESCOPE_DISABLE_EXPLICIT_SYNC" );
+ return !( pszDisable && *pszDisable == '1' );
}
bool CWaylandBackend::IsPaused() const
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -506,8 +506,10 @@
bool CSDLBackend::SupportsExplicitSync() const
{
- // We use a Vulkan swapchain, so yes.
- return true;
+ // We use a Vulkan swapchain, so yes - unless the kernel cannot signal the timelines
+ // (no DRM_IOCTL_SYNCOBJ_EVENTFD before Linux 6.6): GAMESCOPE_DISABLE_EXPLICIT_SYNC=1.
+ const char *pszDisable = getenv( "GAMESCOPE_DISABLE_EXPLICIT_SYNC" );
+ return !( pszDisable && *pszDisable == '1' );
}
bool CSDLBackend::IsPaused() const
@@ -0,0 +1,44 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 18b799e..b803ee0 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -1850,16 +1850,23 @@ import_commit (
commit->fifo = false;
}
- if ( gamescope::OwningRc<CVulkanTexture> pTexture = s_BufferMemos.LookupVulkanTexture( buf ) )
+ struct wlr_dmabuf_attributes dmabuf = {0};
+ const bool bDmabuf = wlr_buffer_get_dmabuf( buf, &dmabuf );
+
+ // Only a dma-buf's texture shows the buffer itself. A shm buffer's texture is a copy taken at
+ // import, and Xwayland without glamor commits the same shm buffers again with new pixels.
+ if ( bDmabuf )
{
- // Going from OwningRc -> Rc now.
- commit->vulkanTex = pTexture;
- return commit;
+ if ( gamescope::OwningRc<CVulkanTexture> pTexture = s_BufferMemos.LookupVulkanTexture( buf ) )
+ {
+ // Going from OwningRc -> Rc now.
+ commit->vulkanTex = pTexture;
+ return commit;
+ }
}
- struct wlr_dmabuf_attributes dmabuf = {0};
gamescope::OwningRc<gamescope::IBackendFb> pBackendFb;
- if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) )
+ if ( bDmabuf )
{
pBackendFb = GetBackend()->ImportDmabufToBackend( &dmabuf );
}
@@ -1873,7 +1880,8 @@ import_commit (
commit->vulkanTex = pOwnedTexture;
- s_BufferMemos.MemoizeBuffer( buf, std::move( pOwnedTexture ) );
+ if ( bDmabuf )
+ s_BufferMemos.MemoizeBuffer( buf, std::move( pOwnedTexture ) );
return commit;
}
@@ -0,0 +1,96 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 41294f7..42b2ec6 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -435,6 +435,9 @@ bool CVulkanDevice::selectPhysDev(VkSurfaceKHR surface)
return true;
}
+// Stands in for VK_NULL_HANDLE in descriptor slots when the device has no nullDescriptor.
+static gamescope::OwningRc<CVulkanTexture> s_nullDescriptorFallback;
+
bool CVulkanDevice::createDevice()
{
uint32_t supportedExtensionCount;
@@ -459,6 +462,9 @@ bool CVulkanDevice::createDevice()
if ( strcmp(ext.extensionName, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0 )
m_bSupportsModifiers = true;
+ if ( strcmp(ext.extensionName, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME) == 0 )
+ m_bSupportsNullDescriptor = true;
+
if ( strcmp(ext.extensionName, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME) == 0 )
supportsForeignQueue = true;
@@ -622,7 +628,10 @@ bool CVulkanDevice::createDevice()
enabledExtensions.push_back( VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME );
- enabledExtensions.push_back( VK_EXT_ROBUSTNESS_2_EXTENSION_NAME );
+ if ( m_bSupportsNullDescriptor )
+ enabledExtensions.push_back( VK_EXT_ROBUSTNESS_2_EXTENSION_NAME );
+ else
+ vk_log.infof( "no VK_EXT_robustness2: unused descriptor slots use a 1x1 texture" );
#if 0
enabledExtensions.push_back( VK_KHR_MAINTENANCE_5_EXTENSION_NAME );
#endif
@@ -711,9 +720,10 @@ bool CVulkanDevice::createDevice()
VkPhysicalDeviceRobustness2FeaturesEXT robustness2Features = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT,
- .pNext = std::exchange(features2.pNext, &robustness2Features),
.nullDescriptor = VK_TRUE,
};
+ if ( m_bSupportsNullDescriptor )
+ robustness2Features.pNext = std::exchange(features2.pNext, &robustness2Features);
VkResult res = vk.CreateDevice(physDev(), &deviceCreateInfo, nullptr, &m_device);
if ( res == VK_ERROR_NOT_PERMITTED_KHR && useRealtimeVulkanQueue )
@@ -1861,6 +1871,15 @@ void CVulkanCmdBuffer::dispatch(uint32_t x, uint32_t y, uint32_t z)
lut3DDescriptor[i].imageView = m_lut3D[i] ? m_lut3D[i]->srgbView() : VK_NULL_HANDLE;
}
+ if ( !m_device->supportsNullDescriptor() && s_nullDescriptorFallback != nullptr )
+ {
+ VkImageView fallback = s_nullDescriptorFallback->srgbView();
+ for (auto &d : imageDescriptors) if (d.imageView == VK_NULL_HANDLE) d.imageView = fallback;
+ for (auto &d : ycbcrImageDescriptors) if (d.imageView == VK_NULL_HANDLE) d.imageView = fallback;
+ for (auto &d : shaperLutDescriptor) if (d.imageView == VK_NULL_HANDLE) d.imageView = fallback;
+ for (auto &d : lut3DDescriptor) if (d.imageView == VK_NULL_HANDLE) d.imageView = fallback;
+ }
+
if (!m_target->isYcbcr())
{
targetDescriptors[0].imageView = m_target->srgbView();
@@ -3546,6 +3565,9 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
// Oh no.
pOutput->temporaryHackyBlankImage = vulkan_create_debug_blank_texture();
+ if ( !g_device.supportsNullDescriptor() && s_nullDescriptorFallback == nullptr )
+ s_nullDescriptorFallback = vulkan_create_flat_texture( 1, 1, 0, 0, 0, 0 );
+
if ( pOutput->uOutputFormatOverlay != VK_FORMAT_UNDEFINED && !kDisablePartialComposition )
{
uint32_t uPartialDRMFormat = pOutput->uOutputFormatOverlay;
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index 5ffec4a..901e6a6 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -866,6 +866,9 @@ public:
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
inline int drmRenderFd() {return m_drmRendererFd;}
inline bool supportsModifiers() {return m_bSupportsModifiers;}
+ // VK_EXT_robustness2's nullDescriptor. A Mali driver through Venus has no robustness2: unused
+ // descriptor slots then point at a 1x1 texture instead of VK_NULL_HANDLE.
+ inline bool supportsNullDescriptor() {return m_bSupportsNullDescriptor;}
inline uint32_t vendorID() const {return m_uVendorID;}
inline const VkPhysicalDeviceMemoryProperties &memoryProperties() const {return m_memoryProperties;}
inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
@@ -938,6 +941,7 @@ protected:
uint32_t m_uVendorID = 0;
bool m_bHasDrmPrimaryDevId = false;
bool m_bSupportsModifiers = false;
+ bool m_bSupportsNullDescriptor = false;
bool m_bSupportsMutableSwapchain = false;
bool m_bSupportsPresentWait = false;
bool m_bInitialized = false;
@@ -0,0 +1,55 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 42b2ec6..103baee 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -994,6 +994,8 @@ bool CVulkanDevice::createPools()
return true;
}
+static std::string s_shaderCaps[SHADER_TYPE_COUNT];
+
bool CVulkanDevice::createShaders()
{
struct ShaderInfo_t
@@ -1040,6 +1042,25 @@ bool CVulkanDevice::createShaders()
.pCode = shaderInfos[i].spirv,
};
+ // The SPIR-V capabilities each shader declares, for the log when its pipeline is refused.
+ {
+ const uint32_t *pWords = shaderInfos[i].spirv;
+ size_t nWords = shaderInfos[i].size / sizeof(uint32_t);
+ std::string &sCaps = s_shaderCaps[i];
+ sCaps.clear();
+ for ( size_t w = 5; w < nWords; )
+ {
+ uint32_t uLen = pWords[w] >> 16;
+ if ( !uLen )
+ break;
+ if ( ( pWords[w] & 0xffffu ) == 17 /* OpCapability */ && w + 1 < nWords )
+ sCaps += " " + std::to_string( pWords[w + 1] );
+ else if ( ( pWords[w] & 0xffffu ) == 54 /* OpFunction: past the header */ )
+ break;
+ w += uLen;
+ }
+ }
+
VkResult res = vk.CreateShaderModule(device(), &shaderCreateInfo, nullptr, &m_shaderModules[i]);
if ( res != VK_SUCCESS )
{
@@ -1240,6 +1261,15 @@ VkPipeline CVulkanDevice::compilePipeline(uint32_t layerCount, uint32_t ycbcrMas
VkResult res = vk.CreateComputePipelines(device(), VK_NULL_HANDLE, 1, &computePipelineCreateInfo, nullptr, &result);
if (res != VK_SUCCESS) {
vk_errorf( res, "vkCreateComputePipelines failed" );
+ // Which pipeline, once per shader type: a vendor driver through Venus may refuse one variant only.
+ static uint32_t s_uLoggedTypes = 0;
+ if ( !( s_uLoggedTypes & ( 1u << ( (uint32_t)type & 31u ) ) ) )
+ {
+ s_uLoggedTypes |= 1u << ( (uint32_t)type & 31u );
+ vk_log.errorf( " failing compute pipeline: shader type %u, layers %u, ycbcr mask 0x%x, blur layers %u, colorspace mask 0x%x, output eotf %u, itm %u, fp16 %d, SPIR-V capabilities:%s",
+ (uint32_t)type, layerCount, ycbcrMask, blur_layer_count, colorspace_mask, (uint32_t)output_eotf, (uint32_t)itm_enable, m_bSupportsFp16 ? 1 : 0,
+ (uint32_t)type < SHADER_TYPE_COUNT ? s_shaderCaps[type].c_str() : "" );
+ }
return VK_NULL_HANDLE;
}
@@ -0,0 +1,78 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 103baee..d344a99 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -319,6 +319,33 @@ bool CVulkanDevice::BInit(VkInstance instance, VkSurfaceKHR surface)
return false;
if (!createShaders())
return false;
+ {
+ // One composite pipeline up front: a driver that refuses it with the immutable YCbCr
+ // samplers gets the layout without them (NV12 textures then sample without conversion).
+ if ( getenv( "GAMESCOPE_NO_YCBCR_SAMPLERS" ) && *getenv( "GAMESCOPE_NO_YCBCR_SAMPLERS" ) == '1' )
+ {
+ vk_log.infof( "GAMESCOPE_NO_YCBCR_SAMPLERS=1: composite layout without immutable YCbCr samplers" );
+ vk.DestroyPipelineLayout( device(), m_pipelineLayout, nullptr );
+ vk.DestroyDescriptorSetLayout( device(), m_descriptorSetLayout, nullptr );
+ m_bYcbcrImmutableSamplers = false;
+ if ( !createLayouts() )
+ return false;
+ }
+ VkPipeline probe = compilePipeline( 1, 0, SHADER_TYPE_BLIT, 1, 0, 0, 0, false );
+ if ( probe == VK_NULL_HANDLE && m_bYcbcrImmutableSamplers )
+ {
+ vk_log.errorf( "composite pipeline refused; retrying without immutable YCbCr samplers" );
+ vk.DestroyPipelineLayout( device(), m_pipelineLayout, nullptr );
+ vk.DestroyDescriptorSetLayout( device(), m_descriptorSetLayout, nullptr );
+ m_bYcbcrImmutableSamplers = false;
+ if ( !createLayouts() )
+ return false;
+ probe = compilePipeline( 1, 0, SHADER_TYPE_BLIT, 1, 0, 0, 0, false );
+ vk_log.infof( "composite pipeline without immutable YCbCr samplers: %s", probe ? "accepted" : "STILL refused" );
+ }
+ if ( probe != VK_NULL_HANDLE )
+ vk.DestroyPipeline( device(), probe, nullptr );
+ }
if (!createScratchResources())
return false;
@@ -869,7 +896,7 @@ bool CVulkanDevice::createLayouts()
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = VKR_SAMPLER_SLOTS,
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT,
- .pImmutableSamplers = ycbcrSamplers.data(),
+ .pImmutableSamplers = m_bYcbcrImmutableSamplers ? ycbcrSamplers.data() : nullptr,
},
VkDescriptorSetLayoutBinding {
.binding = 5,
@@ -1870,6 +1897,8 @@ void CVulkanCmdBuffer::dispatch(uint32_t x, uint32_t y, uint32_t z)
imageDescriptors[i].sampler = m_device->sampler(m_samplerState[i]);
imageDescriptors[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
ycbcrImageDescriptors[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
+ if ( !m_device->ycbcrImmutableSamplers() )
+ ycbcrImageDescriptors[i].sampler = imageDescriptors[i].sampler;
if (m_boundTextures[i] == nullptr)
continue;
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index 901e6a6..e0ede11 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -876,6 +876,7 @@ public:
inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
inline dev_t primaryDevId() {return m_drmPrimaryDevId;}
inline bool supportsFp16() {return m_bSupportsFp16;}
+ inline bool ycbcrImmutableSamplers() {return m_bYcbcrImmutableSamplers;}
inline std::vector<VkExtensionProperties>& supportedExtensions() {return m_supportedExts;}
inline std::pair<void *, uint32_t> uploadBufferData(uint32_t size)
@@ -925,6 +926,9 @@ protected:
VkQueue m_generalQueue = nullptr;
VkSamplerYcbcrConversion m_ycbcrConversion = VK_NULL_HANDLE;
VkSampler m_ycbcrSampler = VK_NULL_HANDLE;
+ // Binding 4 carries immutable YCbCr samplers; off when the driver refuses every composite
+ // pipeline with them (Mali-G615 through Venus: VK_ERROR_INITIALIZATION_FAILED).
+ bool m_bYcbcrImmutableSamplers = true;
VkDescriptorSetLayout m_descriptorSetLayout = VK_NULL_HANDLE;
VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE;
VkDescriptorPool m_descriptorPool = VK_NULL_HANDLE;
@@ -0,0 +1,55 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index d344a99..e699c85 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -331,7 +331,10 @@ bool CVulkanDevice::BInit(VkInstance instance, VkSurfaceKHR surface)
if ( !createLayouts() )
return false;
}
- VkPipeline probe = compilePipeline( 1, 0, SHADER_TYPE_BLIT, 1, 0, 0, 0, false );
+ // Forced off: no probe. Through Venus a pipeline the host refused can still come back as a
+ // handle, and destroying it later is a command the render server rejects - it killed the
+ // whole vtest context (Mali-G615: "vkDestroyPipeline resulted in CS error", exit 137).
+ VkPipeline probe = m_bYcbcrImmutableSamplers ? compilePipeline( 1, 0, SHADER_TYPE_BLIT, 1, 0, 0, 0, false ) : VK_NULL_HANDLE;
if ( probe == VK_NULL_HANDLE && m_bYcbcrImmutableSamplers )
{
vk_log.errorf( "composite pipeline refused; retrying without immutable YCbCr samplers" );
@@ -343,8 +346,8 @@ bool CVulkanDevice::BInit(VkInstance instance, VkSurfaceKHR surface)
probe = compilePipeline( 1, 0, SHADER_TYPE_BLIT, 1, 0, 0, 0, false );
vk_log.infof( "composite pipeline without immutable YCbCr samplers: %s", probe ? "accepted" : "STILL refused" );
}
- if ( probe != VK_NULL_HANDLE )
- vk.DestroyPipeline( device(), probe, nullptr );
+ // The probe is kept, never destroyed (see above): one pipeline.
+ (void)probe;
}
if (!createScratchResources())
return false;
@@ -1380,7 +1383,26 @@ int32_t CVulkanDevice::findMemoryType( VkMemoryPropertyFlags properties, uint32_
return i;
}
-
+
+ // A device that lists its host-visible memory without DEVICE_LOCAL (the Mali bridge models a
+ // unified-memory GPU that way, as a discrete one would) still has it all on the GPU: settle for
+ // host-visible memory rather than fail ("findMemoryType failed", then no backend).
+ if ( properties & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT && properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT )
+ {
+ int32_t nFallback = findMemoryType( properties & ~VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, requiredTypeBits );
+ static bool s_bLogged = false;
+ if ( !s_bLogged )
+ {
+ s_bLogged = true;
+ vk_log.infof( "no memory type with properties 0x%x in type bits 0x%x; without DEVICE_LOCAL: %d", properties, requiredTypeBits, nFallback );
+ }
+ if ( nFallback >= 0 )
+ return nFallback;
+ }
+
+ vk_log.errorf( "findMemoryType: no memory type with properties 0x%x in type bits 0x%x (%u types)", properties, requiredTypeBits, m_memoryProperties.memoryTypeCount );
+ for ( uint32_t i = 0; i < m_memoryProperties.memoryTypeCount; i++ )
+ vk_log.errorf( " memory type %u: flags 0x%x heap %u", i, m_memoryProperties.memoryTypes[ i ].propertyFlags, m_memoryProperties.memoryTypes[ i ].heapIndex );
return -1;
}
@@ -0,0 +1,57 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index a927f69..2c9bd73 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -2882,7 +2882,22 @@ namespace gamescope
abort();
}
- CFunctionWaitable waitable( nFD );
+ // The compositor's connection: a hang-up says why (the protocol error, if one was posted).
+ class CDisplayWaitable final : public IWaitable
+ {
+ public:
+ CDisplayWaitable( int nFD, wl_display *pDisplay ) : m_nFD{ nFD }, m_pDisplay{ pDisplay } {}
+ int GetFD() final { return m_nFD; }
+ void OnPollHangUp() final
+ {
+ LogDisplayError( "The Wayland compositor closed gamescope's connection (input thread)", m_pDisplay );
+ IWaitable::OnPollHangUp();
+ }
+ private:
+ int m_nFD;
+ wl_display *m_pDisplay;
+ };
+ CDisplayWaitable waitable( nFD, m_pBackend->GetDisplay() );
m_Waiter.AddWaitable( &waitable );
int nRet = 0;
diff --git a/src/waitable.h b/src/waitable.h
index be54d46..b9116fe 100644
--- a/src/waitable.h
+++ b/src/waitable.h
@@ -9,6 +9,8 @@
#include <functional>
#include <mutex>
+#include <typeinfo>
+#include <stdio.h>
#include "log.hpp"
@@ -30,7 +32,14 @@ namespace gamescope
virtual void OnPollPri() {}
virtual void OnPollHangUp()
{
- g_WaitableLog.errorf( "IWaitable hung up. Aborting." );
+ // Which one: its class and what its descriptor is (a socket, a pipe, an eventfd...).
+ int nFD = GetFD();
+ char szPath[64], szTarget[256] = "?";
+ snprintf( szPath, sizeof( szPath ), "/proc/self/fd/%d", nFD );
+ ssize_t nLen = nFD >= 0 ? readlink( szPath, szTarget, sizeof( szTarget ) - 1 ) : -1;
+ if ( nLen >= 0 )
+ szTarget[nLen] = '\0';
+ g_WaitableLog.errorf( "IWaitable hung up: %s, fd %d -> %s. Aborting.", typeid( *this ).name(), nFD, szTarget );
abort();
}
@@ -0,0 +1,44 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index e699c85..0ddd249 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -2372,6 +2372,7 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
}
std::vector<uint64_t> modifiers = {};
+ std::vector<uint64_t> unexportable = {};
// TODO(JoshA): Move this code to backend for making flippable image.
if ( GetBackend()->UsesModifiers() && flags.bFlippable && g_device.supportsModifiers() && !pDMA )
{
@@ -2410,12 +2411,30 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
}
if ( !( externalFormatProps.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT ) )
+ {
+ vk_log.infof( "flippable image: modifier 0x%" PRIx64 " for DRM format 0x%x supported but not reported exportable (features 0x%x)",
+ modifier, drmFormat, externalFormatProps.externalMemoryProperties.externalMemoryFeatures );
+ unexportable.push_back( modifier );
continue;
+ }
modifiers.push_back( modifier );
}
- assert( modifiers.size() > 0 );
+ // A driver that supports the modifier but leaves EXPORTABLE out (the Mali bridge forwards the
+ // phone's own driver's answer) can still export the memory as a dma-buf: the bridge's
+ // swapchains do exactly that. Try those rather than assert (rendervulkan.cpp, CVulkanTexture::BInit).
+ if ( modifiers.empty() && !unexportable.empty() )
+ {
+ vk_log.errorf( "flippable image: no modifier reported exportable for DRM format 0x%x; trying %zu supported one(s) anyway",
+ drmFormat, unexportable.size() );
+ modifiers = unexportable;
+ }
+ if ( modifiers.empty() )
+ {
+ vk_log.errorf( "flippable image: no usable modifier for DRM format 0x%x (%zu offered by the backend)", drmFormat, numPossibleModifiers );
+ return false;
+ }
modifierListInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT,
@@ -0,0 +1,26 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -2235,9 +2235,19 @@
else
{
std::span<const uint64_t> modifiers = GetBackend()->GetSupportedModifiers( drmFormat );
- assert( !modifiers.empty() );
- possibleModifiers = modifiers.data();
- numPossibleModifiers = modifiers.size();
+ if ( modifiers.empty() )
+ {
+ // The nested backend offered no modifier for this format (a game's buffer on Venus,
+ // NieR Replicant on a Pixel 9a): linear instead of the assert that ended the session.
+ vk_log.errorf( "flippable image: the backend offers no modifier for DRM format 0x%x; trying linear", drmFormat );
+ possibleModifiers = &linear;
+ numPossibleModifiers = 1;
+ }
+ else
+ {
+ possibleModifiers = modifiers.data();
+ numPossibleModifiers = modifiers.size();
+ }
}
for ( size_t i = 0; i < numPossibleModifiers; i++ )
@@ -0,0 +1,38 @@
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -2373,6 +2373,7 @@
std::vector<uint64_t> modifiers = {};
std::vector<uint64_t> unexportable = {};
+ bool linearRejected = false;
// TODO(JoshA): Move this code to backend for making flippable image.
if ( GetBackend()->UsesModifiers() && flags.bFlippable && g_device.supportsModifiers() && !pDMA )
{
@@ -2414,7 +2415,10 @@
};
res = getModifierProps( &imageInfo, modifier, &externalFormatProps );
if ( res == VK_ERROR_FORMAT_NOT_SUPPORTED )
+ {
+ linearRejected |= modifier == DRM_FORMAT_MOD_LINEAR;
continue;
+ }
else if ( res != VK_SUCCESS ) {
vk_errorf( res, "getModifierProps failed" );
return false;
@@ -2440,6 +2444,16 @@
drmFormat, unexportable.size() );
modifiers = unexportable;
}
+ // An r32p1 Mali driver (G610, Vulkan 1.1) behind the Mali bridge answers every modifier query
+ // with VK_ERROR_FORMAT_NOT_SUPPORTED, yet the bridge makes such an image without the handle type
+ // and exports it through a dma-heap. Linear, when the backend offered it, is tried rather than
+ // giving up; if the image cannot be made, BInit fails as before (Xiaomi 13T, AR24).
+ if ( modifiers.empty() && linearRejected )
+ {
+ vk_log.errorf( "flippable image: the driver supports none of the %zu modifier(s) offered for DRM format 0x%x; trying linear anyway",
+ numPossibleModifiers, drmFormat );
+ modifiers.push_back( DRM_FORMAT_MOD_LINEAR );
+ }
if ( modifiers.empty() )
{
vk_log.errorf( "flippable image: no usable modifier for DRM format 0x%x (%zu offered by the backend)", drmFormat, numPossibleModifiers );
+3 -3
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p19
GAMESCOPE_SHA256=e7333c6a2b95708b199c2c5bd0973e3f0e711e2dc746950cc648c2515ea2926b
GAMESCOPE_REPO=Droid-Deck/DroidDeck
GAMESCOPE_TAG=gamescope-3.16.29-pr2029-22b50d182
GAMESCOPE_SHA256=d6bf0fe2ebb98e1fc7c9a09fccce7d7916c9cc6a10016018040cda01a940b781
+156
View File
@@ -0,0 +1,156 @@
#include "nested_swapchain.hpp"
#include "nested_surface_format.hpp"
#include "dmabuf_import.hpp"
#include "sdl_refresh.hpp"
#include <cassert>
#include <cstdio>
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");
}
+10 -4
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Builds VK_LAYER_DROIDDECK_gpu_load for the arm64 guest: tools/gpuload/build.sh [--native] OUT
# OUT gets libVkLayer_droiddeck_gpuload.so and its implicit-layer manifest.
# OUT gets libVkLayer_droiddeck_gpuload.so, libVkLayer_droiddeck_vramcap.so and their implicit-layer manifests.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
@@ -36,10 +36,15 @@ cmd=(sh -c '
build/gpuload/test_gpuload_busy
cc -std=c11 -O2 -Wall -Wextra -Werror -Ibuild/gpuload/include -Itools/gpuload/src -o build/gpuload/test_gpuload_ring tools/gpuload/tests/test_gpuload_ring.c
build/gpuload/test_gpuload_ring
cc -std=c11 -O2 -Wall -Wextra -Werror -Ibuild/gpuload/include -Itools/gpuload/src -pthread -Wno-unused-parameter -Wno-missing-field-initializers -o build/gpuload/test_vramcap_budget tools/gpuload/tests/test_vramcap_budget.c
build/gpuload/test_vramcap_budget
aarch64-linux-gnu-gcc -std=c11 -shared -fPIC -O2 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers \
-fvisibility=hidden -pthread -Wl,-z,defs -Ibuild/gpuload/include -Itools/gpuload/src \
-o build/gpuload/out/libVkLayer_droiddeck_gpuload.so tools/gpuload/src/vk_layer_droiddeck_gpuload.c
aarch64-linux-gnu-strip --strip-unneeded build/gpuload/out/libVkLayer_droiddeck_gpuload.so')
aarch64-linux-gnu-gcc -std=c11 -shared -fPIC -O2 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers \
-fvisibility=hidden -pthread -Wl,-z,defs -Ibuild/gpuload/include -Itools/gpuload/src \
-o build/gpuload/out/libVkLayer_droiddeck_vramcap.so tools/gpuload/src/vk_layer_droiddeck_vramcap.c
aarch64-linux-gnu-strip --strip-unneeded build/gpuload/out/libVkLayer_droiddeck_gpuload.so build/gpuload/out/libVkLayer_droiddeck_vramcap.so')
if [ "$native" = 1 ]; then
(cd "$repo" && "${cmd[@]}")
else
@@ -47,7 +52,8 @@ else
"${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}" "${cmd[@]}"
fi
cp "$here/layer/VK_LAYER_DROIDDECK_gpu_load.json" "$work/out/"
cp "$here/layer/VK_LAYER_DROIDDECK_gpu_load.json" "$here/layer/VK_LAYER_DROIDDECK_vram_cap.json" "$work/out/"
mkdir -p "$out"
cp "$work/out/libVkLayer_droiddeck_gpuload.so" "$work/out/VK_LAYER_DROIDDECK_gpu_load.json" "$out/"
cp "$work/out/libVkLayer_droiddeck_gpuload.so" "$work/out/libVkLayer_droiddeck_vramcap.so" \
"$work/out/VK_LAYER_DROIDDECK_gpu_load.json" "$work/out/VK_LAYER_DROIDDECK_vram_cap.json" "$out/"
echo "built $out"
@@ -0,0 +1,20 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_vram_cap",
"type": "GLOBAL",
"library_path": "/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"api_version": "1.3.0",
"implementation_version": "1",
"description": "Reports a smaller video memory budget to DXVK and vkd3d-proton",
"functions": {
"vkNegotiateLoaderLayerInterfaceVersion": "DroidDeckVramCap_NegotiateLoaderLayerInterfaceVersion"
},
"enable_environment": {
"DROIDDECK_VRAM_CAP": "1"
},
"disable_environment": {
"DROIDDECK_VRAM_CAP_DISABLE": "1"
}
}
}
@@ -0,0 +1,206 @@
#define _GNU_SOURCE
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "vramcap_budget.h"
#define EXPORT __attribute__((visibility("default")))
static uint64_t g_cap;
__attribute__((constructor)) static void init(void) {
g_cap = vramcap_parse_mb(getenv("DROIDDECK_VRAM_CAP_MB"));
}
struct inst {
struct inst *next_in_list;
VkInstance handle;
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance destroy;
PFN_vkGetPhysicalDeviceMemoryProperties2 mem2;
PFN_vkGetPhysicalDeviceMemoryProperties2 mem2_khr;
};
struct dev {
struct dev *next_in_list;
VkDevice handle;
PFN_vkGetDeviceProcAddr gdpa;
PFN_vkDestroyDevice destroy;
};
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct inst *g_insts;
static struct dev *g_devs;
static int g_announced;
static void *key(const void *obj) { return *(void *const *)obj; }
static struct inst *inst_for(const void *obj) {
struct inst *r;
pthread_mutex_lock(&g_lock);
for (r = g_insts; r && key(r->handle) != key(obj); r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static struct dev *dev_for(const void *obj) {
struct dev *r;
pthread_mutex_lock(&g_lock);
for (r = g_devs; r && key(r->handle) != key(obj); r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static void say(const char *what) {
fprintf(stderr, "[droiddeck-vram-cap] pid %d: %s\n", (int)getpid(), what);
}
static void announce(void) {
if (__atomic_exchange_n(&g_announced, 1, __ATOMIC_RELAXED)) return;
char line[96];
snprintf(line, sizeof(line), "reported device memory budget %llu MB", (unsigned long long)(g_cap >> 20));
say(line);
}
static void clamp_properties2(PFN_vkGetPhysicalDeviceMemoryProperties2 next, VkPhysicalDevice pd,
VkPhysicalDeviceMemoryProperties2 *out) {
next(pd, out);
for (VkBaseOutStructure *s = out->pNext; s; s = s->pNext)
if (s->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT) {
vramcap_budget(&out->memoryProperties, (VkPhysicalDeviceMemoryBudgetPropertiesEXT *)s, g_cap);
if (g_cap) announce();
}
}
static void VKAPI_CALL GetMemoryProperties2(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *out) {
struct inst *in = inst_for(pd);
if (in) clamp_properties2(in->mem2, pd, out);
}
static void VKAPI_CALL GetMemoryProperties2KHR(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *out) {
struct inst *in = inst_for(pd);
if (in) clamp_properties2(in->mem2_khr, pd, out);
}
static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *alloc, VkInstance *out) {
VkLayerInstanceCreateInfo *link = (VkLayerInstanceCreateInfo *)ci->pNext;
while (link && !(link->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && link->function == VK_LAYER_LINK_INFO))
link = (VkLayerInstanceCreateInfo *)link->pNext;
if (!link) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = link->u.pLayerInfo->pfnNextGetInstanceProcAddr;
link->u.pLayerInfo = link->u.pLayerInfo->pNext;
PFN_vkCreateInstance create = (PFN_vkCreateInstance)next_gipa(VK_NULL_HANDLE, "vkCreateInstance");
if (!create) return VK_ERROR_INITIALIZATION_FAILED;
struct inst *in = calloc(1, sizeof(*in));
if (!in) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkResult r = create(ci, alloc, out);
if (r != VK_SUCCESS) { free(in); return r; }
in->handle = *out;
in->gipa = next_gipa;
in->destroy = (PFN_vkDestroyInstance)next_gipa(*out, "vkDestroyInstance");
in->mem2 = (PFN_vkGetPhysicalDeviceMemoryProperties2)next_gipa(*out, "vkGetPhysicalDeviceMemoryProperties2");
in->mem2_khr = (PFN_vkGetPhysicalDeviceMemoryProperties2)next_gipa(*out, "vkGetPhysicalDeviceMemoryProperties2KHR");
pthread_mutex_lock(&g_lock);
in->next_in_list = g_insts;
g_insts = in;
pthread_mutex_unlock(&g_lock);
return VK_SUCCESS;
}
static void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCallbacks *alloc) {
struct inst *in = inst_for(instance);
if (!in) return;
PFN_vkDestroyInstance destroy = in->destroy;
pthread_mutex_lock(&g_lock);
for (struct inst **p = &g_insts; *p; p = &(*p)->next_in_list)
if (*p == in) { *p = in->next_in_list; break; }
pthread_mutex_unlock(&g_lock);
free(in);
if (destroy) destroy(instance, alloc);
}
static VkLayerDeviceCreateInfo *device_chain(const VkDeviceCreateInfo *ci, VkLayerFunction function) {
VkLayerDeviceCreateInfo *c = (VkLayerDeviceCreateInfo *)ci->pNext;
while (c && !(c->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && c->function == function))
c = (VkLayerDeviceCreateInfo *)c->pNext;
return c;
}
static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci, const VkAllocationCallbacks *alloc,
VkDevice *out) {
VkLayerDeviceCreateInfo *link = device_chain(ci, VK_LAYER_LINK_INFO);
if (!link) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = link->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr next_gdpa = link->u.pLayerInfo->pfnNextGetDeviceProcAddr;
link->u.pLayerInfo = link->u.pLayerInfo->pNext;
struct inst *in = inst_for(pd);
PFN_vkCreateDevice create = (PFN_vkCreateDevice)next_gipa(in ? in->handle : VK_NULL_HANDLE, "vkCreateDevice");
if (!create) return VK_ERROR_INITIALIZATION_FAILED;
struct dev *d = calloc(1, sizeof(*d));
if (!d) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkResult r = create(pd, ci, alloc, out);
if (r != VK_SUCCESS) { free(d); return r; }
d->handle = *out;
d->gdpa = next_gdpa;
d->destroy = (PFN_vkDestroyDevice)next_gdpa(*out, "vkDestroyDevice");
pthread_mutex_lock(&g_lock);
d->next_in_list = g_devs;
g_devs = d;
pthread_mutex_unlock(&g_lock);
return VK_SUCCESS;
}
static void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallbacks *alloc) {
struct dev *d = dev_for(device);
if (!d) return;
pthread_mutex_lock(&g_lock);
for (struct dev **p = &g_devs; *p; p = &(*p)->next_in_list)
if (*p == d) { *p = d->next_in_list; break; }
pthread_mutex_unlock(&g_lock);
PFN_vkDestroyDevice destroy = d->destroy;
free(d);
if (destroy) destroy(device, alloc);
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVramCap_GetDeviceProcAddr(VkDevice device, const char *name);
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVramCap_GetInstanceProcAddr(VkInstance instance, const char *name) {
if (!strcmp(name, "vkCreateInstance")) return (PFN_vkVoidFunction)CreateInstance;
if (!strcmp(name, "vkDestroyInstance")) return (PFN_vkVoidFunction)DestroyInstance;
if (!strcmp(name, "vkCreateDevice")) return (PFN_vkVoidFunction)CreateDevice;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)DestroyDevice;
if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)DroidDeckVramCap_GetInstanceProcAddr;
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)DroidDeckVramCap_GetDeviceProcAddr;
if (!instance) return NULL;
struct inst *in = inst_for(instance);
if (!in) return NULL;
if (g_cap) {
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties2") && in->mem2) return (PFN_vkVoidFunction)GetMemoryProperties2;
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties2KHR") && in->mem2_khr)
return (PFN_vkVoidFunction)GetMemoryProperties2KHR;
}
return in->gipa(instance, name);
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVramCap_GetDeviceProcAddr(VkDevice device, const char *name) {
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)DroidDeckVramCap_GetDeviceProcAddr;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)DestroyDevice;
struct dev *d = dev_for(device);
if (!d) return NULL;
return d->gdpa(device, name);
}
EXPORT VKAPI_ATTR VkResult VKAPI_CALL DroidDeckVramCap_NegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *v) {
if (v->loaderLayerInterfaceVersion > 2) v->loaderLayerInterfaceVersion = 2;
v->pfnGetInstanceProcAddr = DroidDeckVramCap_GetInstanceProcAddr;
v->pfnGetDeviceProcAddr = DroidDeckVramCap_GetDeviceProcAddr;
v->pfnGetPhysicalDeviceProcAddr = NULL;
return VK_SUCCESS;
}
+32
View File
@@ -0,0 +1,32 @@
#ifndef VRAMCAP_BUDGET_H
#define VRAMCAP_BUDGET_H
#include <stdint.h>
#include <vulkan/vulkan.h>
static inline uint64_t vramcap_parse_mb(const char *text) {
if (!text || !*text) return 0;
uint64_t value = 0, limit = UINT64_MAX >> 20;
for (; *text; text++) {
if (*text < '0' || *text > '9') return 0;
unsigned digit = (unsigned)(*text - '0');
if (value > (limit - digit) / 10) return 0;
value = value * 10 + digit;
}
return value << 20;
}
static inline VkDeviceSize vramcap_clamp(VkDeviceSize value, uint64_t cap) {
return cap && value > cap ? cap : value;
}
static inline void vramcap_budget(const VkPhysicalDeviceMemoryProperties *p,
VkPhysicalDeviceMemoryBudgetPropertiesEXT *budget, uint64_t cap) {
for (uint32_t i = 0; i < p->memoryHeapCount && i < VK_MAX_MEMORY_HEAPS; i++)
if (p->memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
budget->heapBudget[i] = vramcap_clamp(budget->heapBudget[i], cap);
budget->heapBudget[i] = vramcap_clamp(budget->heapBudget[i], p->memoryHeaps[i].size);
}
}
#endif
+154
View File
@@ -0,0 +1,154 @@
#include <assert.h>
#include <inttypes.h>
#include "../src/vk_layer_droiddeck_vramcap.c"
static int instance_dispatch, device_dispatch;
static void *instance_object = &instance_dispatch, *physical_object = &instance_dispatch;
static void *device_object = &device_dispatch;
static VkInstance instance;
static VkPhysicalDevice physical;
static VkDevice device;
static unsigned allocations, frees, destroyed_devices, destroyed_instances;
static void VKAPI_CALL memory_properties(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties *out) {
assert(pd == physical);
*out = (VkPhysicalDeviceMemoryProperties){
.memoryHeapCount = 3,
.memoryHeaps = {{8ULL << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}, {4ULL << 30, 0},
{512ULL << 20, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}},
.memoryTypeCount = 1,
.memoryTypes = {{VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0}},
};
}
static void VKAPI_CALL memory_properties2(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *out) {
memory_properties(pd, &out->memoryProperties);
for (VkBaseOutStructure *p = out->pNext; p; p = p->pNext)
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT) {
VkPhysicalDeviceMemoryBudgetPropertiesEXT *b = (void *)p;
b->heapBudget[0] = 6ULL << 30;
b->heapBudget[1] = 3ULL << 30;
b->heapBudget[2] = 256ULL << 20;
b->heapUsage[0] = 3ULL << 30;
}
}
static VkResult VKAPI_CALL allocate(VkDevice d, const VkMemoryAllocateInfo *info,
const VkAllocationCallbacks *a, VkDeviceMemory *out) {
assert(d == device && info->allocationSize == (3ULL << 30));
*out = (VkDeviceMemory)(uintptr_t)++allocations;
return VK_SUCCESS;
}
static void VKAPI_CALL release(VkDevice d, VkDeviceMemory m, const VkAllocationCallbacks *a) {
assert(d == device && m);
frees++;
}
static void VKAPI_CALL destroy_device(VkDevice d, const VkAllocationCallbacks *a) {
assert(d == device);
destroyed_devices++;
}
static void VKAPI_CALL destroy_instance(VkInstance in, const VkAllocationCallbacks *a) {
assert(in == instance);
destroyed_instances++;
}
static PFN_vkVoidFunction VKAPI_CALL gdpa(VkDevice d, const char *name) {
assert(d == device);
if (!strcmp(name, "vkAllocateMemory")) return (PFN_vkVoidFunction)allocate;
if (!strcmp(name, "vkFreeMemory")) return (PFN_vkVoidFunction)release;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)destroy_device;
return NULL;
}
static VkResult VKAPI_CALL create_device(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci,
const VkAllocationCallbacks *a, VkDevice *out) {
assert(pd == physical);
*out = device;
return VK_SUCCESS;
}
static VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *a, VkInstance *out) {
*out = instance;
return VK_SUCCESS;
}
static PFN_vkVoidFunction VKAPI_CALL gipa(VkInstance in, const char *name) {
assert(in == instance || in == VK_NULL_HANDLE);
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, "vkGetPhysicalDeviceMemoryProperties")) return (PFN_vkVoidFunction)memory_properties;
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties2") || !strcmp(name, "vkGetPhysicalDeviceMemoryProperties2KHR"))
return (PFN_vkVoidFunction)memory_properties2;
return NULL;
}
int main(void) {
assert(vramcap_parse_mb("2048") == (2ULL << 30));
assert(vramcap_parse_mb(NULL) == 0 && vramcap_parse_mb("") == 0 && vramcap_parse_mb("0") == 0);
const char *bad[] = {"-1", "+1", " 1024", "1024 ", "1GB", "18446744073709551616", "17592186044416"};
for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) assert(vramcap_parse_mb(bad[i]) == 0);
assert(vramcap_parse_mb("17592186044415") == ((UINT64_MAX >> 20) << 20));
instance = (VkInstance)&instance_object;
physical = (VkPhysicalDevice)&physical_object;
device = (VkDevice)&device_object;
g_cap = 2ULL << 30;
VkLayerInstanceLink il = {.pfnNextGetInstanceProcAddr = gipa};
VkLayerInstanceCreateInfo ic = {.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO,
.function = VK_LAYER_LINK_INFO, .u.pLayerInfo = &il};
VkInstanceCreateInfo ici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &ic};
VkInstance got_instance;
assert(CreateInstance(&ici, NULL, &got_instance) == VK_SUCCESS && got_instance == instance);
VkPhysicalDeviceMemoryProperties p;
PFN_vkGetPhysicalDeviceMemoryProperties get = (void *)DroidDeckVramCap_GetInstanceProcAddr(instance, "vkGetPhysicalDeviceMemoryProperties");
assert(get == memory_properties);
get(physical, &p);
assert(p.memoryHeaps[0].size == (8ULL << 30) && p.memoryHeaps[1].size == (4ULL << 30));
assert(p.memoryHeaps[2].size == (512ULL << 20));
assert(p.memoryTypes[0].propertyFlags == (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT));
const char *names[] = {"vkGetPhysicalDeviceMemoryProperties2", "vkGetPhysicalDeviceMemoryProperties2KHR"};
for (size_t i = 0; i < 2; i++) {
VkPhysicalDeviceMemoryBudgetPropertiesEXT b = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT};
VkPhysicalDeviceIDProperties id = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES, .pNext = &b};
VkPhysicalDeviceMemoryProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, .pNext = &id};
PFN_vkGetPhysicalDeviceMemoryProperties2 get2 = (void *)DroidDeckVramCap_GetInstanceProcAddr(instance, names[i]);
get2(physical, &p2);
assert(p2.memoryProperties.memoryHeaps[0].size == (8ULL << 30));
assert(b.heapBudget[0] == g_cap && b.heapBudget[1] == (3ULL << 30));
assert(b.heapBudget[2] == (256ULL << 20));
assert(b.heapUsage[0] == (3ULL << 30));
assert(p2.pNext == &id && id.pNext == &b);
}
VkLayerDeviceLink dl = {.pfnNextGetInstanceProcAddr = gipa, .pfnNextGetDeviceProcAddr = gdpa};
VkLayerDeviceCreateInfo dc = {.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO,
.function = VK_LAYER_LINK_INFO, .u.pLayerInfo = &dl};
VkDeviceCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = &dc};
VkDevice got_device;
assert(CreateDevice(physical, &dci, NULL, &got_device) == VK_SUCCESS && got_device == device);
PFN_vkAllocateMemory next_allocate = (void *)DroidDeckVramCap_GetDeviceProcAddr(device, "vkAllocateMemory");
PFN_vkFreeMemory next_free = (void *)DroidDeckVramCap_GetDeviceProcAddr(device, "vkFreeMemory");
assert(next_allocate == allocate && next_free == release);
VkMemoryAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = 3ULL << 30};
VkDeviceMemory blocks[2];
for (unsigned i = 0; i < 2; i++) assert(next_allocate(device, &ai, NULL, &blocks[i]) == VK_SUCCESS);
assert(allocations == 2);
for (unsigned i = 0; i < 2; i++) next_free(device, blocks[i], NULL);
assert(frees == 2);
g_cap = 0;
assert(DroidDeckVramCap_GetInstanceProcAddr(instance, names[0]) == (PFN_vkVoidFunction)memory_properties2);
assert(DroidDeckVramCap_GetInstanceProcAddr(instance, "vkGetPhysicalDeviceMemoryProperties") == (PFN_vkVoidFunction)memory_properties);
PFN_vkDestroyDevice destroy = (void *)DroidDeckVramCap_GetInstanceProcAddr(instance, "vkDestroyDevice");
assert(destroy == DestroyDevice);
destroy(device, NULL);
DestroyInstance(instance, NULL);
assert(destroyed_devices == 1 && destroyed_instances == 1 && !g_devs && !g_insts);
puts("test_vramcap_budget: ok");
return 0;
}
+51
View File
@@ -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"
+99
View File
@@ -0,0 +1,99 @@
# Opt-in device-backed low mappings for Wine WoW64
On the tested Pixel PowerVR stack, Vulkan maps host-visible GPU allocations
above 4 GiB. Wine's 32-bit WoW64 Vulkan bridge rejects those pointers. This
caused American Nightmare (202750) to stop at D3D9 vertex-buffer creation even
after the separate PowerVR BC texture profile passed device initialization.
`low32.c` is an experimental native Linux/glibc preload adapter. It is off by
default. It applies only to anonymous-address, non-executable `MAP_SHARED`
mappings of one explicitly selected character device. It retains the original
device FD, offset, protection, flags, and actual GPU backing, and searches low
address space with `MAP_FIXED_NOREPLACE`. It never truncates a pointer, copies
into shadow storage, replaces existing mappings, or disables Wine's guard.
Caller-specified/fixed mappings, regular files, private/anonymous memory and
other devices retain their original behavior. Failure to find a suitable low
hole fails with ENOMEM. The mmap and mmap64 preload chains are independently
resolved and called through their respective RTLD_NEXT symbols;
only resolver bootstrap uses the raw syscall. A compact atomic cursor avoids
wasting large address slots on thousands of small driver control allocations.
If the compact probe collides, a bounded address-range walk of
/proc/self/maps finds page-sized holes and uses NOREPLACE again to handle races.
The walk runs before coarse fallback, so small allocations do not fragment
large available ranges. A game load had 2.3 GB free below 4 GiB but no hole as large as 4 MiB; the
coarse-only version falsely failed even 4 KiB mappings. Mapping failures are
reported even after the ordinary 256-event trace limit.
## Build and verify
Use a native 64-bit Linux/glibc compiler, not the Android NDK or macOS compiler:
```sh
tools/hybris/low32/build.sh /absolute/build-dir /path/to/Vulkan-Headers/include
```
The native library and unit test are always built. GPU probes are optional when
headers are provided; `gpu-copy-native` uses the selected native host compiler
and has the host's architecture, while the Windows x86 probe also needs
i686-w64-mingw32-gcc. Copy a native probe to a device only when their architectures match.
The unit test uses /dev/zero and proves CPU data integrity, collision handling,
concurrency, 2000 simultaneous small mappings, invalid offsets, forwarding and
opt-out. A fragmented-address-space regression reserves the low region, opens
64 off-grid page holes, and verifies all 64 mappings and their data. The old
coarse adapter fails that regression; the address-range fallback passes. An
additional density regression fills 64 existing page holes while preserving a
separate contiguous 16 MiB interval for a later complete data-readback map; the
prior gap-after-coarse implementation fails and the gap-first strategy passes. These
CPU tests do not by themselves prove GPU correctness.
The build also tests both preload orders with a second library that hooks mmap
and mmap64 independently. Opt-out, tracing and adaptation must each preserve
the selected symbol's chain, invalid-offset errno and file offsets above 4 GiB.
`gpu-copy.c` tests actual Vulkan transfer operations on vendor 0x1010. It maps
two 32 MiB device allocations, runs four copies of full deterministic patterns,
including offset/unmap/remap, uses flush/invalidate and barriers/fences, and
compares every word. It can require each full CPU range to fit below 4 GiB:
```sh
./gpu-copy-native 32 --require-low32
# Through a separate Proton ARM64/WoW64 test prefix:
proton run gpu-copy-x86.exe 32 --require-low32 'Z:\path\probe-output.txt'
```
The Windows output file avoids Wine's detached console hiding probe results.
Run with Khronos synchronization validation. Keep raw Steam/account logs local;
export only controlled PROBE results, validation IDs and counts. The tested
memory type was device-local, host-visible and coherent; noncoherent physical
memory is not covered by that run.
## Activation scope
Set only the target game's overrides, after identifying the render device's
`st_rdev` and validating the installed library's hash:
```text
LD_PRELOAD=/absolute/guest/path/libdroiddeck-low32.so
DROIDDECK_LOW32_MODE=low32
DROIDDECK_LOW32_RDEV=<verified decimal st_rdev>
```
Preserve any existing target-game preload rather than replacing it. The tested
Pixel's /dev/dri/renderD128 was character device major 226/minor 128, st_rdev 57984.
Do not hardcode that value for other machines. BC emulation and the repaired
DXVK presentation component remain separate prerequisites; this adapter does
not implement them. No global Steam profile, managed graphics pack, Android
security setting or unrelated game's overrides should change.
Before activating, back up the exact game-environment bytes and only the target
prefix's graphics DLLs, preserving symlinks. Rollback must check for concurrent
edits. Keep original backups in the app; do not copy account files or an entire
Steam prefix to a report. Removing these three overrides disables the adapter.
## Compatibility limits
This initial binary was built on Ubuntu 24.04 ARM64 and needs glibc 2.38. The
tested guest supports it. This is not yet a universal runtime component; other
glibc versions, page sizes, drivers, GPU families, native 32-bit processes and
general game stability require their own tests. Bounded native and Windows GPU
copies prove data integrity for those workloads, not unrestricted gameplay.
Never enable globally based on successful testing of one game.
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
set -eu
# Run on native 64-bit Linux/glibc. This is not an Android/Bionic library.
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
output=${1:?usage: build.sh /absolute/build-directory [Vulkan-header-directory]}
mkdir -p "$output"
cc=${CC:-cc}
"$cc" -std=gnu11 -Wall -Wextra -Werror -O2 -fPIC -shared -s \
"$base/low32.c" -ldl -o "$output/libdroiddeck-low32.so"
"$cc" -std=gnu11 -Wall -Wextra -Werror -O2 "$base/test-low32.c" -pthread -o "$output/test-low32"
LD_PRELOAD="$output/libdroiddeck-low32.so" "$output/test-low32"
"$cc" -std=gnu11 -Wall -Wextra -Werror -O2 -fPIC -shared \
"$base/test-chain-hook.c" -ldl -o "$output/test-chain-hook.so"
"$cc" -std=gnu11 -Wall -Wextra -Werror -O2 "$base/test-preload-chain.c" -ldl -o "$output/test-preload-chain"
for preloads in "$output/libdroiddeck-low32.so:$output/test-chain-hook.so" \
"$output/test-chain-hook.so:$output/libdroiddeck-low32.so"; do
for mode in off trace low32; do
LD_PRELOAD="$preloads" "$output/test-preload-chain" "$mode"
done
done
if [ "$#" -ge 2 ]; then
"$cc" -std=gnu11 -Wall -Wextra -Werror -O2 -s -I"$2" "$base/gpu-copy.c" -ldl -o "$output/gpu-copy-native"
if command -v i686-w64-mingw32-gcc >/dev/null 2>&1; then
i686-w64-mingw32-gcc -std=gnu11 -Wall -Wextra -Werror -O2 -s -I"$2" \
"$base/gpu-copy.c" -o "$output/gpu-copy-x86.exe"
fi
fi
+166
View File
@@ -0,0 +1,166 @@
/* Same standalone GPU-copy probe built as Linux AArch64 and Windows x86.
* Tests actual Vulkan buffers, complete data comparison, noncoherent cache
* operations, remapping with an offset and queue completion. No Steam API.
*/
#define VK_NO_PROTOTYPES
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vulkan/vulkan.h>
#define IFNS(X) X(DestroyInstance) X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
X(GetPhysicalDeviceMemoryProperties) X(GetPhysicalDeviceQueueFamilyProperties) X(CreateDevice) X(GetDeviceProcAddr)
#define DFNS(X) X(DestroyDevice) X(GetDeviceQueue) X(CreateBuffer) X(DestroyBuffer) \
X(GetBufferMemoryRequirements) X(AllocateMemory) X(FreeMemory) X(BindBufferMemory) \
X(MapMemory) X(UnmapMemory) X(FlushMappedMemoryRanges) X(InvalidateMappedMemoryRanges) \
X(CreateCommandPool) X(DestroyCommandPool) X(AllocateCommandBuffers) X(ResetCommandBuffer) \
X(BeginCommandBuffer) X(EndCommandBuffer) X(CmdCopyBuffer) X(CmdPipelineBarrier) \
X(CreateFence) X(DestroyFence) X(ResetFences) X(QueueSubmit) X(WaitForFences)
#define DECL(n) static PFN_vk##n p##n;
IFNS(DECL)
DFNS(DECL)
#undef DECL
#define CHECK(x) do { VkResult rc=(x); if(rc!=VK_SUCCESS){printf("PROBE_FAIL stage=%s vk_result=%d\n",#x,rc);goto cleanup;} }while(0)
#define REQUIRE(x,msg) do {if(!(x)){puts("PROBE_FAIL " msg);goto cleanup;}}while(0)
int main(int argc,char **argv)
{
#ifdef _WIN32
/* Wine/Proton can detach the Windows console from the Linux pipe. */
if(argc>3 && !freopen(argv[3],"w",stdout)) return 4;
#endif
setvbuf(stdout,NULL,_IONBF,0);
puts("PROBE_STAGE main");
unsigned mib=argc>1?(unsigned)strtoul(argv[1],NULL,10):32;
int require_low=argc>2&&!strcmp(argv[2],"--require-low32");
if(mib<1||mib>256)return 2;
const VkDeviceSize bytes=(VkDeviceSize)mib*1024*1024;
VkInstance instance=VK_NULL_HANDLE;VkDevice device=VK_NULL_HANDLE;
VkBuffer buffers[2]={0};VkDeviceMemory memories[2]={0};
VkDeviceSize allocated[2]={0};void *mapped[2]={0};
VkCommandPool pool=VK_NULL_HANDLE;VkFence fence=VK_NULL_HANDLE;
int success=0,pending=0;uint64_t mismatches=0;unsigned iterations=0;
int low_all=1;uint32_t memory_flags[2]={0};
PFN_vkGetInstanceProcAddr gipa;
#ifdef _WIN32
HMODULE loader=LoadLibraryA("vulkan-1.dll");
REQUIRE(loader,"load_vulkan_failed");
gipa=(PFN_vkGetInstanceProcAddr)(void *)GetProcAddress(loader,"vkGetInstanceProcAddr");
#else
void *loader=dlopen("libvulkan.so.1",RTLD_NOW|RTLD_LOCAL);
REQUIRE(loader,"load_vulkan_failed");
gipa=(PFN_vkGetInstanceProcAddr)dlsym(loader,"vkGetInstanceProcAddr");
#endif
REQUIRE(gipa,"missing_gipa");
puts("PROBE_STAGE vulkan_loader");
PFN_vkCreateInstance create=(PFN_vkCreateInstance)gipa(NULL,"vkCreateInstance");
REQUIRE(create,"missing_create_instance");
VkApplicationInfo app={.sType=VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pApplicationName="DroidDeck low32 buffer integrity probe",.apiVersion=VK_API_VERSION_1_1};
VkInstanceCreateInfo ici={.sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,.pApplicationInfo=&app};
CHECK(create(&ici,NULL,&instance));
puts("PROBE_STAGE instance_created");
#define LOADI(n) p##n=(PFN_vk##n)gipa(instance,"vk" #n);REQUIRE(p##n,"missing_" #n);
IFNS(LOADI)
#undef LOADI
uint32_t count=0;CHECK(pEnumeratePhysicalDevices(instance,&count,NULL));
puts("PROBE_STAGE physical_device_enumeration");
REQUIRE(count&&count<=16,"physical_device_count");
VkPhysicalDevice physicals[16],physical=VK_NULL_HANDLE;
CHECK(pEnumeratePhysicalDevices(instance,&count,physicals));
VkPhysicalDeviceProperties properties;
for(uint32_t i=0;i<count;i++){
pGetPhysicalDeviceProperties(physicals[i],&properties);
if(properties.vendorID==0x1010&&properties.deviceType!=VK_PHYSICAL_DEVICE_TYPE_CPU){physical=physicals[i];break;}
}
REQUIRE(physical,"no_real_powervr");
printf("PROBE_DEVICE vendor=%x device=%x api=%x pointer_bits=%zu\n",
properties.vendorID,properties.deviceID,properties.apiVersion,sizeof(void *)*8);
uint32_t qcount=0;pGetPhysicalDeviceQueueFamilyProperties(physical,&qcount,NULL);
REQUIRE(qcount&&qcount<=64,"queue_count");
VkQueueFamilyProperties qp[64];pGetPhysicalDeviceQueueFamilyProperties(physical,&qcount,qp);
uint32_t family=UINT32_MAX;
for(uint32_t i=0;i<qcount;i++)if(qp[i].queueCount&&(qp[i].queueFlags&VK_QUEUE_GRAPHICS_BIT)){family=i;break;}
REQUIRE(family!=UINT32_MAX,"no_graphics_queue");float priority=1.0f;
VkDeviceQueueCreateInfo qci={.sType=VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,.queueFamilyIndex=family,.queueCount=1,.pQueuePriorities=&priority};
VkDeviceCreateInfo dci={.sType=VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,.queueCreateInfoCount=1,.pQueueCreateInfos=&qci};
CHECK(pCreateDevice(physical,&dci,NULL,&device));
#define LOADD(n) p##n=(PFN_vk##n)pGetDeviceProcAddr(device,"vk" #n);REQUIRE(p##n,"missing_" #n);
DFNS(LOADD)
#undef LOADD
VkPhysicalDeviceMemoryProperties mp;pGetPhysicalDeviceMemoryProperties(physical,&mp);
for(unsigned j=0;j<2;j++){
VkBufferCreateInfo bci={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.size=bytes,
.usage=VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT,.sharingMode=VK_SHARING_MODE_EXCLUSIVE};
CHECK(pCreateBuffer(device,&bci,NULL,&buffers[j]));VkMemoryRequirements mr;
pGetBufferMemoryRequirements(device,buffers[j],&mr);
uint32_t type=UINT32_MAX;
for(uint32_t i=0;i<mp.memoryTypeCount;i++)if((mr.memoryTypeBits&(1u<<i))&&(mp.memoryTypes[i].propertyFlags&VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)){type=i;break;}
REQUIRE(type!=UINT32_MAX,"no_host_visible_memory");memory_flags[j]=mp.memoryTypes[type].propertyFlags;
VkMemoryAllocateInfo mai={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=mr.size,.memoryTypeIndex=type};
allocated[j]=mr.size;CHECK(pAllocateMemory(device,&mai,NULL,&memories[j]));
CHECK(pBindBufferMemory(device,buffers[j],memories[j],0));
}
VkCommandPoolCreateInfo pci={.sType=VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.flags=VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,.queueFamilyIndex=family};
CHECK(pCreateCommandPool(device,&pci,NULL,&pool));VkCommandBuffer command;
VkCommandBufferAllocateInfo cai={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.commandPool=pool,.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY,.commandBufferCount=1};
CHECK(pAllocateCommandBuffers(device,&cai,&command));
VkFenceCreateInfo fci={.sType=VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
CHECK(pCreateFence(device,&fci,NULL,&fence));VkQueue queue;pGetDeviceQueue(device,family,0,&queue);
for(unsigned k=0;k<4;k++){
/* Alternate full mapping and a 64KiB aligned offset, preserving every word. */
VkDeviceSize offset=(k&1)?65536:0,span=bytes-offset;
for(unsigned j=0;j<2;j++){
CHECK(pMapMemory(device,memories[j],offset,VK_WHOLE_SIZE,0,&mapped[j]));
int low=(uint64_t)(uintptr_t)mapped[j]+(allocated[j]-offset)<=UINT64_C(0x100000000);
low_all&=low;
printf("PROBE_MAP iteration=%u buffer=%u offset=%" PRIu64 " bytes=%" PRIu64 " ptr=%p low32=%d flags=%x\n",
k,j,(uint64_t)offset,(uint64_t)(allocated[j]-offset),mapped[j],low,memory_flags[j]);
REQUIRE(!require_low||low,"mapping_not_low32");
}
uint32_t *src=mapped[0],*dst=mapped[1];size_t words=(size_t)(span/4);
for(size_t i=0;i<words;i++){src[i]=((uint32_t)i*2654435761u)^(0xa5a50000u+k);dst[i]=0;}
VkMappedMemoryRange ranges[2];memset(ranges,0,sizeof(ranges));
for(unsigned j=0;j<2;j++)ranges[j]=(VkMappedMemoryRange){.sType=VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,.memory=memories[j],.offset=offset,.size=VK_WHOLE_SIZE};
CHECK(pFlushMappedMemoryRanges(device,2,ranges));
if(k){CHECK(pResetFences(device,1,&fence));CHECK(pResetCommandBuffer(command,0));}
VkCommandBufferBeginInfo cbi={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,.flags=VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
CHECK(pBeginCommandBuffer(command,&cbi));
VkMemoryBarrier before={.sType=VK_STRUCTURE_TYPE_MEMORY_BARRIER,.srcAccessMask=VK_ACCESS_HOST_WRITE_BIT,.dstAccessMask=VK_ACCESS_TRANSFER_READ_BIT|VK_ACCESS_TRANSFER_WRITE_BIT};
pCmdPipelineBarrier(command,VK_PIPELINE_STAGE_HOST_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,1,&before,0,NULL,0,NULL);
VkBufferCopy copy={.srcOffset=offset,.dstOffset=offset,.size=span};pCmdCopyBuffer(command,buffers[0],buffers[1],1,&copy);
VkMemoryBarrier after={.sType=VK_STRUCTURE_TYPE_MEMORY_BARRIER,.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT,.dstAccessMask=VK_ACCESS_HOST_READ_BIT};
pCmdPipelineBarrier(command,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_HOST_BIT,0,1,&after,0,NULL,0,NULL);
CHECK(pEndCommandBuffer(command));VkSubmitInfo si={.sType=VK_STRUCTURE_TYPE_SUBMIT_INFO,.commandBufferCount=1,.pCommandBuffers=&command};
CHECK(pQueueSubmit(queue,1,&si,fence));pending=1;
VkResult waited=pWaitForFences(device,1,&fence,VK_TRUE,UINT64_C(10000000000));
if(waited!=VK_SUCCESS){printf("PROBE_FAIL GPU_COMPLETION_UNCONFIRMED result=%d\n",waited);goto cleanup;}
pending=0;CHECK(pInvalidateMappedMemoryRanges(device,1,&ranges[1]));
for(size_t i=0;i<words;i++)if(dst[i]!=(((uint32_t)i*2654435761u)^(0xa5a50000u+k)))mismatches++;
for(unsigned j=0;j<2;j++){pUnmapMemory(device,memories[j]);mapped[j]=NULL;}
iterations++;REQUIRE(!mismatches,"data_mismatch");
}
success=1;
cleanup:
printf("PROBE_RESULT success=%d mib=%u iterations=%u mismatches=%" PRIu64 " all_mappings_low32=%d\n",success,mib,iterations,mismatches,low_all);
if(pending)return 3; /* Do not explicitly destroy objects with unknown GPU completion. */
if(device){
if(pUnmapMemory)for(unsigned j=0;j<2;j++)if(mapped[j])pUnmapMemory(device,memories[j]);
if(fence&&pDestroyFence)pDestroyFence(device,fence,NULL);
if(pool&&pDestroyCommandPool)pDestroyCommandPool(device,pool,NULL);
for(unsigned j=0;j<2;j++)if(buffers[j]&&pDestroyBuffer)pDestroyBuffer(device,buffers[j],NULL);
for(unsigned j=0;j<2;j++)if(memories[j]&&pFreeMemory)pFreeMemory(device,memories[j],NULL);
if(pDestroyDevice)pDestroyDevice(device,NULL);
}
if(instance&&pDestroyInstance)pDestroyInstance(instance,NULL);
return success?0:1;
}
+256
View File
@@ -0,0 +1,256 @@
/* Experimental per-process PowerVR device-backed low-address mmap adapter.
* No copied/shadow memory, changed device offset or MAP_FIXED replacement.
* Default is off. Enable only for the identified render-device rdev and the
* target x86/WoW64 game. Native 64-bit Linux/glibc preload, not an Android ABI DLL.
*/
#define _GNU_SOURCE
#define _LARGEFILE64_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <inttypes.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef MAP_FIXED_NOREPLACE
#define MAP_FIXED_NOREPLACE 0x100000
#endif
static _Atomic uint64_t cursor;
static _Atomic unsigned logged;
typedef void *(*map_function)(void *,size_t,int,int,int,off_t);
typedef void *(*map64_function)(void *,size_t,int,int,int,off64_t);
static _Atomic(map_function) next_map;
static _Atomic(map64_function) next_map64;
_Static_assert(sizeof(off_t) == sizeof(off64_t) && sizeof(off_t) == 8,
"64-bit host required");
static __thread int resolving __attribute__((tls_model("initial-exec")));
static __thread int active __attribute__((tls_model("initial-exec")));
static void *native_map(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{
map_function next=atomic_load(&next_map);
if (!next && !resolving) {
resolving=1;
next=(map_function)dlsym(RTLD_NEXT,"mmap");
atomic_store(&next_map,next);
resolving=0;
}
/* Bootstrap only while resolving; otherwise preserve existing preload hooks. */
if (next) return next(addr,length,prot,flags,fd,offset);
return (void *)syscall(SYS_mmap, addr, length, prot, flags, fd, offset);
}
static void *native_map64(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{
map64_function next=atomic_load(&next_map64);
if (!next && !resolving) {
resolving=1;
next=(map64_function)dlsym(RTLD_NEXT,"mmap64");
atomic_store(&next_map64,next);
resolving=0;
}
if (next) return next(addr,length,prot,flags,fd,(off64_t)offset);
return (void *)syscall(SYS_mmap, addr, length, prot, flags, fd, offset);
}
static void trace_map(const char *kind, size_t n, int prot, int flags, int fd,
off_t off, const struct stat *st, void *p, int error)
{
int saved = errno;
unsigned count = atomic_fetch_add(&logged, 1);
if (count < 256 || error != 0) {
char text[320];
int nbytes = snprintf(text, sizeof(text),
"DD_LOW32 %s pid=%ld len=%zu prot=%x flags=%x fd=%d off=%jd mode=%o rdev=%ju ptr=%p errno=%d\n",
kind, (long)getpid(), n, prot, flags, fd, (intmax_t)off, st ? st->st_mode : 0,
st ? (uintmax_t)st->st_rdev : 0, p, error);
if (nbytes > 0) {
ssize_t written = write(STDERR_FILENO, text,
(size_t)nbytes < sizeof(text) ? (size_t)nbytes : sizeof(text)-1);
(void)written;
}
}
errno = saved;
}
static int target_device(int fd, struct stat *st)
{
const char *value = getenv("DROIDDECK_LOW32_RDEV");
char *end = NULL;
if (!value || !*value || fd < 0) return 0;
int saved = errno;
errno = 0;
uintmax_t expected = strtoumax(value, &end, 10);
int valid = !errno && end && !*end && expected > 0 &&
fstat(fd, st) == 0 && S_ISCHR(st->st_mode) &&
(uintmax_t)st->st_rdev == expected;
errno = saved;
return valid;
}
static void *adapted_map(map_function forward, void *addr, size_t length, int prot,
int flags, int fd, off_t offset)
{
const char *mode = getenv("DROIDDECK_LOW32_MODE");
struct stat st = {0};
if (mode && !strcmp(mode, "trace")) {
void *p = forward(addr, length, prot, flags, fd, offset);
if (fd >= 0 && (prot & PROT_WRITE) && !(prot & PROT_EXEC) &&
(flags & MAP_TYPE) == MAP_SHARED) {
int saved=errno;
(void)fstat(fd,&st);
errno=saved;
trace_map("trace", length, prot, flags, fd, offset, &st, p,
p == MAP_FAILED ? errno : 0);
}
return p;
}
if (!mode || strcmp(mode, "low32") || addr || !length ||
(flags & (MAP_ANONYMOUS | MAP_FIXED | MAP_FIXED_NOREPLACE)) ||
(prot & PROT_EXEC) || (flags & MAP_TYPE) != MAP_SHARED ||
!target_device(fd, &st))
return forward(addr, length, prot, flags, fd, offset);
const uintptr_t lower = 0x10000000u, upper = 0xffff0000u;
const uintptr_t step = 0x00400000u;
if (length > upper-lower) {
errno = ENOMEM;
trace_map("too_large", length, prot, flags, fd, offset, &st, MAP_FAILED, errno);
return MAP_FAILED;
}
long page_value=sysconf(_SC_PAGESIZE);
uintptr_t page=page_value>0?(uintptr_t)page_value:4096;
uintptr_t rounded=(length+page-1)&~(page-1);
uintptr_t span=upper-lower;
uintptr_t compact=(uintptr_t)(atomic_fetch_add(&cursor,rounded)%span);
if (rounded>span-compact) compact=0;
unsigned slots = (unsigned)((span-length)/step)+1;
unsigned start = (unsigned)(compact/step)%slots;
int original_errno = errno;
for (unsigned i = 0; i < 1; i++) {
/* Compact first: hundreds of small driver mappings must not waste a
* 4MiB address slot each. Coarse search is only for existing Wine holes. */
uintptr_t hint = lower + (i==0?compact:(uintptr_t)((start+i-1)%slots)*step);
void *p = forward((void *)hint, length, prot,
flags|MAP_FIXED_NOREPLACE, fd, offset);
if (p != MAP_FAILED) {
uintptr_t first = (uintptr_t)p;
if (first >= lower && first < upper && length <= upper-first) {
errno = original_errno;
trace_map("mapped", length, prot, flags, fd, offset, &st, p, 0);
return p;
}
/* Older kernels can ignore NOREPLACE; never return a high mapping. */
int saved = errno;
(void)syscall(SYS_munmap, p, length);
errno = saved;
} else if (errno != EEXIST && errno != ENOMEM && errno != EAGAIN) {
trace_map("rejected", length, prot, flags, fd, offset, &st, p, errno);
return p;
}
}
/* Pack small allocations into address holes before coarse probing can
* fragment large holes. Walk
* this process's current mappings, then use NOREPLACE to tolerate races.
* No pointer paths or contents are read; only address ranges are used. */
for (unsigned pass = 0; pass < 2; ++pass) {
FILE *maps = fopen("/proc/self/maps", "r");
if (!maps) break;
char line[512];
uintptr_t gap_start = lower;
unsigned lines = 0;
while (fgets(line, sizeof(line), maps) && ++lines < 65536) {
uintptr_t first, last;
if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR, &first, &last) != 2) continue;
if (last <= gap_start) continue;
uintptr_t gap_end = first < upper ? first : upper;
if (gap_end > gap_start && rounded <= gap_end - gap_start) {
void *p = forward((void *)gap_start, length, prot,
flags | MAP_FIXED_NOREPLACE, fd, offset);
if (p != MAP_FAILED) {
uintptr_t address = (uintptr_t)p;
if (address >= lower && address < upper && length <= upper - address) {
fclose(maps);
errno = original_errno;
trace_map("mapped_gap", length, prot, flags, fd, offset, &st, p, 0);
return p;
}
(void)syscall(SYS_munmap, p, length);
} else if (errno != EEXIST && errno != ENOMEM && errno != EAGAIN) {
int saved = errno;
fclose(maps);
errno = saved;
trace_map("rejected", length, prot, flags, fd, offset, &st, MAP_FAILED, errno);
return MAP_FAILED;
}
}
if (last > gap_start) gap_start = last;
if (gap_start >= upper) break;
}
if (gap_start < upper && rounded <= upper - gap_start) {
void *p = forward((void *)gap_start, length, prot,
flags | MAP_FIXED_NOREPLACE, fd, offset);
if (p != MAP_FAILED) {
uintptr_t address = (uintptr_t)p;
if (address >= lower && address < upper && length <= upper - address) {
fclose(maps);
errno = original_errno;
trace_map("mapped_gap", length, prot, flags, fd, offset, &st, p, 0);
return p;
}
(void)syscall(SYS_munmap, p, length);
}
}
fclose(maps);
}
for (unsigned i = 1; i <= slots; i++) {
/* Last resort if address walking was unavailable or raced. */
uintptr_t hint = lower + (i==0?compact:(uintptr_t)((start+i-1)%slots)*step);
void *p = forward((void *)hint, length, prot,
flags|MAP_FIXED_NOREPLACE, fd, offset);
if (p != MAP_FAILED) {
uintptr_t first = (uintptr_t)p;
if (first >= lower && first < upper && length <= upper-first) {
errno = original_errno;
trace_map("mapped", length, prot, flags, fd, offset, &st, p, 0);
return p;
}
/* Older kernels can ignore NOREPLACE; never return a high mapping. */
int saved = errno;
(void)syscall(SYS_munmap, p, length);
errno = saved;
} else if (errno != EEXIST && errno != ENOMEM && errno != EAGAIN) {
trace_map("rejected", length, prot, flags, fd, offset, &st, p, errno);
return p;
}
}
errno = ENOMEM;
trace_map("no_low_hole", length, prot, flags, fd, offset, &st, MAP_FAILED, errno);
return MAP_FAILED;
}
static void *intercept_map(map_function forward, void *addr, size_t length,
int prot, int flags, int fd, off_t offset)
{
if (active) return forward(addr,length,prot,flags,fd,offset);
active=1;
void *p=adapted_map(forward,addr,length,prot,flags,fd,offset);
active=0;
return p;
}
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{
return intercept_map(native_map,addr,length,prot,flags,fd,offset);
}
void *mmap64(void *addr, size_t length, int prot, int flags, int fd, off64_t offset)
{
return intercept_map(native_map64,addr,length,prot,flags,fd,(off_t)offset);
}
+37
View File
@@ -0,0 +1,37 @@
/* Controlled second preload: distinct mmap/mmap64 counters and 64-bit offsets. */
#define _GNU_SOURCE
#define _LARGEFILE64_SOURCE
#include <dlfcn.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/types.h>
static int selected_fd = -2;
static unsigned calls[2];
static int64_t offsets[2];
void chain_clear(int fd)
{
selected_fd = fd;
calls[0] = calls[1] = 0;
offsets[0] = offsets[1] = -1;
}
unsigned chain_calls(unsigned channel) { return calls[channel]; }
int64_t chain_offset(unsigned channel) { return offsets[channel]; }
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off)
{
static void *(*next)(void *, size_t, int, int, int, off_t);
if (!next) next = dlsym(RTLD_NEXT, "mmap");
if (fd == selected_fd) { ++calls[0]; offsets[0] = off; }
return next(addr, len, prot, flags, fd, off);
}
void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off64_t off)
{
static void *(*next)(void *, size_t, int, int, int, off64_t);
if (!next) next = dlsym(RTLD_NEXT, "mmap64");
if (fd == selected_fd) { ++calls[1]; offsets[1] = off; }
return next(addr, len, prot, flags, fd, off);
}
+119
View File
@@ -0,0 +1,119 @@
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#define N (32u*1024u*1024u)
static int zero_fd;
static void *thread_test(void *arg)
{
unsigned seed = (unsigned)(uintptr_t)arg;
uint32_t *p = mmap(NULL,N,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(p != MAP_FAILED && (uintptr_t)p+N <= 0x100000000ull);
for (size_t i=0;i<N/4;i++) p[i]=(uint32_t)i^seed;
for (size_t i=0;i<N/4;i++) assert(p[i]==((uint32_t)i^seed));
assert(!munmap(p,N));
return NULL;
}
int main(void)
{
zero_fd=open("/dev/zero",O_RDWR|O_CLOEXEC); assert(zero_fd>=0);
struct stat st; assert(!fstat(zero_fd,&st)); char value[48];
snprintf(value,sizeof(value),"%ju",(uintmax_t)st.st_rdev);
assert(!setenv("DROIDDECK_LOW32_RDEV",value,1));
assert(!setenv("DROIDDECK_LOW32_MODE","low32",1));
/* Existing low-address memory must survive device mappings. */
uint32_t *guard=mmap((void *)0x10000000,128u*1024u*1024u,PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE,-1,0);
assert(guard==(void *)0x10000000);guard[0]=0xdeadbeef;guard[32767]=0xcafef00d;
pthread_t threads[8];
for (uintptr_t i=0;i<8;i++) assert(!pthread_create(&threads[i],NULL,thread_test,(void *)i));
for (unsigned i=0;i<8;i++) assert(!pthread_join(threads[i],NULL));
assert(guard[0]==0xdeadbeef && guard[32767]==0xcafef00d);
puts("PASS concurrent 32MiB mappings, full pattern readback and occupied-memory preservation");
assert(!munmap(guard,128u*1024u*1024u));
/* Caller-specified address and MAP_FIXED semantics are preserved. */
void *explicit=mmap((void *)0x30000000,4096,PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_FIXED_NOREPLACE,zero_fd,0);
assert(explicit==(void *)0x30000000); assert(!munmap(explicit,4096));
int mem=memfd_create("low32-nontarget",0);assert(mem>=0);assert(!ftruncate(mem,N));
uint32_t *q=mmap((void *)0x500000000ull,N,PROT_READ|PROT_WRITE,MAP_SHARED,mem,0);
assert(q==(void *)0x500000000ull);q[0]=123;assert(q[0]==123);assert(!munmap(q,N));close(mem);
puts("PASS unrelated regular-file mapping and explicit-address forwarding");
errno=0;
void *bad=mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,1);
assert(bad==MAP_FAILED && errno==EINVAL);
puts("PASS invalid device offset retains EINVAL");
/* Real game initialization creates many small control/buffer mappings. */
void *small[2000];
for(unsigned i=0;i<2000;i++) {
small[i]=mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(small[i]!=MAP_FAILED && (uintptr_t)small[i]+4096<=0x100000000ull);
*(uint32_t *)small[i]=i;
}
for(unsigned i=0;i<2000;i++){
assert(*(uint32_t *)small[i]==i);assert(!munmap(small[i],4096));
}
puts("PASS 2000 simultaneous small mappings without address-slot exhaustion");
/* A fragmented Wine address space has usable holes away from every
* 4MiB probe location. The mapping walk must find them without clobbering. */
const uintptr_t lo=0x10000000u, hi=0xffff0000u;
void *reservation=mmap((void *)lo,hi-lo,PROT_NONE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE|MAP_FIXED_NOREPLACE,-1,0);
assert(reservation==(void *)lo);
void *holes[64], *fragmented[64];
for (unsigned i=0;i<64;i++) {
holes[i]=(void *)(lo+0x12345000u+(uintptr_t)i*0x10000u);
assert(!munmap(holes[i],4096));
}
for (unsigned i=0;i<64;i++) {
fragmented[i]=mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(fragmented[i]!=MAP_FAILED);
int found=0;for(unsigned j=0;j<64;j++)found|=fragmented[i]==holes[j];assert(found);
*(uint32_t *)fragmented[i]=i+77;
}
for (unsigned i=0;i<64;i++) assert(*(uint32_t *)fragmented[i]==i+77);
for (unsigned i=0;i<64;i++) assert(!munmap(fragmented[i],4096));
assert(!munmap(reservation,hi-lo));
puts("PASS fragmented low32 mappings find 64 page holes beyond coarse probes");
/* Small allocations must consume existing page holes rather than punch
* coarse-grid holes into the only large interval needed by a later map. */
reservation=mmap((void *)lo,hi-lo,PROT_NONE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE|MAP_FIXED_NOREPLACE,-1,0);
assert(reservation==(void *)lo);
for (unsigned i=0;i<64;i++) assert(!munmap(holes[i],4096));
const uintptr_t large_address=0x70000000u;
const size_t large_size=16u*1024u*1024u;
assert(!munmap((void *)large_address,large_size));
for (unsigned i=0;i<64;i++) {
fragmented[i]=mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(fragmented[i]!=MAP_FAILED);
int found=0;for(unsigned j=0;j<64;j++)found|=fragmented[i]==holes[j];assert(found);
*(uint32_t *)fragmented[i]=i+99;
}
uint32_t *large=mmap(NULL,large_size,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(large==(void *)large_address);
for(size_t i=0;i<large_size/4;i++)large[i]=(uint32_t)i^0xa5a5a5a5u;
for(size_t i=0;i<large_size/4;i++)assert(large[i]==((uint32_t)i^0xa5a5a5a5u));
for(unsigned i=0;i<64;i++){
assert(*(uint32_t *)fragmented[i]==i+99);assert(!munmap(fragmented[i],4096));
}
assert(!munmap(large,large_size));assert(!munmap(reservation,hi-lo));
puts("PASS page-sized mapping density preserves subsequent contiguous 16MiB allocation");
assert(!setenv("DROIDDECK_LOW32_RDEV","999999999",1));
q=mmap((void *)0x510000000ull,4096,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(q==(void *)0x510000000ull);assert(!munmap(q,4096));
puts("PASS mismatched device remains untouched");
assert(!unsetenv("DROIDDECK_LOW32_MODE"));
q=mmap((void *)0x520000000ull,4096,PROT_READ|PROT_WRITE,MAP_SHARED,zero_fd,0);
assert(q==(void *)0x520000000ull);assert(!munmap(q,4096));
puts("PASS opt-in disabled by default");
close(zero_fd);return 0;
}
+62
View File
@@ -0,0 +1,62 @@
#define _GNU_SOURCE
#define _LARGEFILE64_SOURCE
#include <assert.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv)
{
assert(argc == 2);
void (*clear)(int) = dlsym(RTLD_DEFAULT, "chain_clear");
unsigned (*calls)(unsigned) = dlsym(RTLD_DEFAULT, "chain_calls");
int64_t (*offset)(unsigned) = dlsym(RTLD_DEFAULT, "chain_offset");
assert(clear && calls && offset);
if (strcmp(argv[1], "off")) assert(!setenv("DROIDDECK_LOW32_MODE", argv[1], 1));
else assert(!unsetenv("DROIDDECK_LOW32_MODE"));
int fd = open("/dev/zero", O_RDWR | O_CLOEXEC);
assert(fd >= 0);
struct stat st;
assert(!fstat(fd, &st));
char rdev[48];
snprintf(rdev, sizeof(rdev), "%ju", (uintmax_t)st.st_rdev);
assert(!setenv("DROIDDECK_LOW32_RDEV", rdev, 1));
for (unsigned channel = 0; channel < 2; ++channel) {
clear(fd);
void *p = channel ? mmap64(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)
: mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(p != MAP_FAILED);
assert(calls(channel) == 1 && calls(1 - channel) == 0 && offset(channel) == 0);
if (!strcmp(argv[1], "low32")) assert((uintptr_t)p + 4096 <= UINT64_C(0x100000000));
*(unsigned *)p = 0xcafef00d;
assert(*(unsigned *)p == 0xcafef00d && !munmap(p, 4096));
clear(fd);
errno = 0;
p = channel ? mmap64(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 1)
: mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 1);
assert(p == MAP_FAILED && errno == EINVAL);
assert(calls(channel) == 1 && calls(1 - channel) == 0 && offset(channel) == 1);
}
close(fd);
/* Regular-file forwarding must preserve an mmap64 offset above 4 GiB. */
fd = memfd_create("preload-chain-test", 0);
const off64_t large_offset = INT64_C(0x200001000);
assert(fd >= 0 && !ftruncate64(fd, large_offset + 4096));
unsigned value = 0x1234abcd;
assert(pwrite64(fd, &value, sizeof(value), large_offset) == (ssize_t)sizeof(value));
clear(fd);
unsigned *p = mmap64(NULL, 4096, PROT_READ, MAP_SHARED, fd, large_offset);
assert(p != MAP_FAILED && *p == value);
assert(calls(1) == 1 && calls(0) == 0 && offset(1) == large_offset);
assert(!munmap(p, 4096));
close(fd);
printf("PASS separate mmap/mmap64 chains (%s), EINVAL and >4GiB offset readback\n", argv[1]);
return 0;
}
@@ -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 <string.h>
+#include <stdio.h>
#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 <stdlib.h>
+#include <stddef.h>
#include <string.h>
#include <sys/auxv.h>
@@ -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 <stdlib.h>
+#include <stdio.h>
#include <string.h>
#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;
}
+12
View File
@@ -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);
+89
View File
@@ -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())
+2
View File
@@ -0,0 +1,2 @@
HYBRIS_REVISION=bc8cb3586b79d208fd21b925fa0209b3e432e008
PROTOCOL_REVISION=c6ae3c22a804da3cda017f4c8eaa6c6a3da55457
+5
View File
@@ -26,5 +26,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"
+12 -2
View File
@@ -31,6 +31,14 @@ export BL_DESKTOP=1
ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /'
python3 /usr/local/bin/droiddeck-desktop-programs 2>&1 | sed 's/^/[programs] /'
# startplasma applies this file over the session environment, and keeps what an earlier session wrote.
kwriteconfig6 --file plasma-localerc --group Formats --key LANG "${LANG:-C.UTF-8}"
if [ -n "${LANGUAGE:-}" ]; then
kwriteconfig6 --file plasma-localerc --group Translations --key LANGUAGE "$LANGUAGE"
else
kwriteconfig6 --file plasma-localerc --group Translations --key LANGUAGE --delete
fi
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
[Desktop Entry]
Type=Application
@@ -107,8 +115,10 @@ fi
if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND
export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
if [ -z "${KWIN_RENDER_NODES:-}" ] && [ -c /dev/dri/renderD0 ]; then
export KWIN_RENDER_NODES=/dev/dri/renderD0
if [ -z "${KWIN_RENDER_NODES:-}" ]; then
for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do
if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi
done
fi
mkdir -p /run/droiddeck/kwin
printf '#!/bin/sh\nGALLIUM_THREAD=0 exec /usr/bin/kwin_wayland "$@"\n' > /run/droiddeck/kwin/kwin_wayland
+10 -4
View File
@@ -6,13 +6,18 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
fi
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
backend=${BL_GAMESCOPE_BACKEND:-wayland}
case "$backend" in
wayland|sdl) ;;
*) echo "== unsupported gamescope backend: $backend" >&2; exit 64 ;;
esac
window=0
if [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then
if [ "$backend" = wayland ] && [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then
window=1
parent=$WAYLAND_DISPLAY
args=(--backend sdl --expose-wayland -W "$width" -H "$height" -w "$width" -h "$height")
args=(--backend sdl --expose-wayland --follow-game-window-mode -W "$width" -H "$height" -w "$width" -h "$height")
else
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
fi
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
@@ -27,6 +32,7 @@ else
export WAYLAND_DISPLAY=wayland-0
fi
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
[ "$backend" = sdl ] && export SDL_VIDEODRIVER=wayland
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
wsi=",${MESA_VK_WSI_DEBUG:-},"
while [[ $wsi == *,sw,* ]]; do wsi=${wsi//,sw,/,}; done
@@ -40,7 +46,7 @@ if [ "$window" = 1 ]; then
export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-}
SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
else
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
gamescope "${args[@]}" -- env SDL_VIDEODRIVER=x11 /usr/local/bin/droiddeck-gpu-window "$@"
fi
rc=$?
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
@@ -52,7 +52,7 @@ CLIENT_WAIT = 300
GAME_GRACE = 15
LAUNCH_WAIT = 15
LAUNCH_ASKS = 3
CLIENT_PATH = re.compile(r"[a-z]:\\(program files \(x86\)|programdata)\\battle\.net\\")
CLIENT_PATH = re.compile(r"[a-z]:\\(program files \(x86\)\\battle\.net\\([^\\]+$|battle\.net\.\d+\\)|programdata\\battle\.net\\)")
IDLE = {"agent.exe", "conhost.exe", "explorer.exe", "lsass.exe", "plugplay.exe", "rpcss.exe", "services.exe",
"start.exe", "steam.exe", "svchost.exe", "tabtip.exe", "winedevice.exe", "wineserver"}
NOT_GAME = IDLE | {"rundll32.exe", "wineboot.exe", "winemenubuilder.exe"}
@@ -113,7 +113,9 @@ function field(text, name) {
}
function install() {
var form = call("POST", "/install", '{"uid":"' + uid + '","instructions_patch_url":"http://' + zone + '.patch.battle.net:1119/' +
// Blizzard's China repository moved to cn.patch.battlenet.com.cn; cn.patch.battle.net only redirects away from it.
var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";
var form = call("POST", "/install", '{"uid":"' + uid + '","instructions_patch_url":"http://' + patch + ':1119/' +
product + '","instructions_product":"NGDP","monitor_pid":12345,"priority":{"insert_at_head":true,"value":900}}');
save(".form", form);
if (form.indexOf('"' + lang + '"') < 0) lang = "enUS";
@@ -0,0 +1,317 @@
#!/usr/bin/python3
import fcntl
import glob
import os
import re
import runpy
import stat
import struct
import subprocess
import sys
import zlib
HOME = os.environ.get("HOME", "/root")
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam")
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
OPEN = os.path.join(BIN_DIR, "droiddeck-open")
APPS_DIR = os.path.join(HOME, ".local/share/applications")
PLACED = os.path.join(HOME, ".local/share/droiddeck/desktop-programs-placed")
PREFIX = "droiddeck-program-"
SHORTCUT_BIT = 0x80000000
WINDOWS_DESKTOPS = ("users/Public/Desktop", "users/steamuser/Desktop")
NOT_PROGRAMS = re.compile(r"(?i)^unins")
ABSENT = (FileNotFoundError, NotADirectoryError, IsADirectoryError)
_run = None
def present(path, regular=False):
try:
mode = os.stat(path).st_mode
except ABSENT:
return False
return stat.S_ISREG(mode) if regular else True
def read(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
except ABSENT:
return None
def proton_run():
global _run
if _run is None:
_run = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-proton-run"))
return _run
def shortcut_ids(root):
tool = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-steam-shortcuts"))
# account_dir takes either of these as missing when it cannot be read.
read(os.path.join(root, "config", "loginusers.vdf"))
listing(os.path.join(root, "userdata"))
account = tool["account_dir"](root)
if account:
try:
with open(os.path.join(account, "config", "shortcuts.vdf"), "rb") as f:
tool["parse"](f.read())
except ABSENT:
pass
except (ValueError, IndexError, KeyError, struct.error) as error:
raise OSError("Steam's shortcuts.vdf cannot be read: %s" % error) from error
return {appid for appid, _, _ in proton_run()["shortcut_entries"](root)}
def runs_here(pfx, exe):
target = proton_run()["prefix_of"](exe)
return target is not None and os.path.realpath(target.compatdata) == os.path.realpath(os.path.dirname(pfx))
def listing(folder, suffix=""):
try:
names = os.listdir(folder)
except ABSENT:
return None
return sorted(os.path.join(folder, name) for name in names if name.lower().endswith(suffix))
def prefixes(root):
compatdata = os.path.join(root, "steamapps", "compatdata")
names = listing(compatdata)
if names is None:
return []
owned = shortcut_ids(root)
found = []
for name in (os.path.basename(path) for path in names):
if not re.fullmatch(r"-?[0-9]+", name):
continue
appid = int(name) % 2 ** 32
pfx = os.path.join(compatdata, name, "pfx")
if appid & SHORTCUT_BIT and appid not in owned and listing(os.path.join(pfx, "drive_c", "proton_shortcuts")) is not None:
found.append((appid, pfx))
return found
def zero_terminated(data, start, wide):
if wide:
end = start
while data[end:end + 2] not in (b"\0\0", b""):
end += 2
return data[start:end].decode("utf-16-le", "replace")
end = data.find(b"\0", start)
return data[start:end if end >= 0 else len(data)].decode("cp1252", "replace")
def link_target(path):
try:
with open(path, "rb") as f:
data = f.read(1 << 16)
size, = struct.unpack_from("<I", data, 0)
flags, = struct.unpack_from("<I", data, 0x14)
pos, target = size, None
if flags & 0x1:
pos += 2 + struct.unpack_from("<H", data, pos)[0]
if flags & 0x2:
info_size, header, info_flags, _, local, _, suffix = struct.unpack_from("<7I", data, pos)
if info_flags & 0x1:
if header >= 0x24:
local_wide, suffix_wide = struct.unpack_from("<2I", data, pos + 0x1C)
target = zero_terminated(data, pos + local_wide, True) + zero_terminated(data, pos + suffix_wide, True)
else:
target = zero_terminated(data, pos + local, False) + zero_terminated(data, pos + suffix, False)
pos += info_size
args = ""
wide = bool(flags & 0x80)
for bit in (0x4, 0x8, 0x10, 0x20, 0x40):
if flags & bit:
count, = struct.unpack_from("<H", data, pos)
end = pos + 2 + count * (2 if wide else 1)
if bit == 0x20:
args = data[pos + 2:end].decode("utf-16-le" if wide else "cp1252", "replace").rstrip("\0")
pos = end
return target, args
except ABSENT + (struct.error, ValueError):
return None, ""
def host_path(pfx, windows):
found = re.fullmatch(r"([A-Za-z]):\\?(.*)", windows or "")
if not found:
return None
path = os.path.realpath(os.path.join(pfx, "dosdevices", found.group(1).lower() + ":"))
for part in (p for p in found.group(2).split("\\") if p):
exact = os.path.join(path, part)
if not os.path.lexists(exact):
try:
exact = next((os.path.join(path, name) for name in os.listdir(path) if name.lower() == part.lower()), exact)
except ABSENT:
return None
path = exact
return path if present(path) else None
def value(text, key):
found = re.search(r"^%s=(.*)$" % re.escape(key), text, re.M)
return found.group(1).strip() if found else ""
def windows_link(exec_value):
if len(exec_value) >= 2 and exec_value[0] == exec_value[-1] == '"':
exec_value = exec_value[1:-1]
# A desktop file escapes a backslash once for the key and again inside a quoted Exec argument.
return exec_value.replace("\\\\", "\\").replace("\\\\", "\\")
def icon(shortcuts, name):
best, size = "system-run", 0
for apps in glob.glob(os.path.join(glob.escape(shortcuts), "icons", "*", "apps")):
found = re.fullmatch(r"(\d+)x\d+", os.path.basename(os.path.dirname(apps)))
path = os.path.join(apps, name + ".png")
if name and found and int(found.group(1)) > size and os.path.isfile(path):
best, size = path, int(found.group(1))
return best
def program(pfx, link):
target, args = link_target(link)
exe = host_path(pfx, target)
if (exe and exe.lower().endswith(".exe") and not NOT_PROGRAMS.match(os.path.basename(exe)) and present(exe, regular=True)
and runs_here(pfx, exe)):
return exe, args
return None, ""
def programs(pfx):
shortcuts = os.path.join(pfx, "drive_c", "proton_shortcuts")
found = {}
for entry in listing(shortcuts, ".desktop") or []:
text = read(entry) or ""
link = host_path(pfx, windows_link(value(text, "Exec")))
if not link or not link.lower().endswith(".lnk"):
continue
exe, args = program(pfx, link)
if exe:
found[exe] = dict(name=value(text, "Name") or os.path.splitext(os.path.basename(entry))[0], args=args,
icon=icon(shortcuts, value(text, "Icon")), wm_class=value(text, "StartupWMClass"))
return found
def on_windows_desktop(pfx):
found = set()
for folder in WINDOWS_DESKTOPS:
for link in listing(os.path.join(pfx, "drive_c", folder), ".lnk") or []:
exe, _ = program(pfx, link)
if exe:
found.add(exe)
return found
def windows_args(text):
args, current, started, quoted, slashes = [], "", False, False, 0
for ch in text:
if ch == "\\":
slashes += 1
started = True
elif ch == '"':
current += "\\" * (slashes // 2) + ('"' if slashes % 2 else "")
if slashes % 2 == 0:
quoted = not quoted
slashes, started = 0, True
else:
current += "\\" * slashes
slashes = 0
if ch in " \t" and not quoted:
if started:
args.append(current)
current, started = "", False
else:
current += ch
started = True
if started:
args.append(current + "\\" * slashes)
return args
def quoted(arg):
escaped = re.sub(r'([\\"`$])', r"\\\1", arg).replace("%", "%%")
return '"%s"' % escaped.replace("\\", "\\\\")
def entry(exe, found):
args = windows_args(found["args"])
lines = ["[Desktop Entry]", "Type=Application", "Name=%s" % found["name"].replace("\n", " "),
"Comment=Windows program installed from the desktop",
"Exec=%s" % " ".join(quoted(arg) for arg in [OPEN, exe] + args),
"Icon=%s" % found["icon"], "Terminal=false", "Categories=Game;"]
if found["wm_class"]:
lines.append("StartupWMClass=%s" % found["wm_class"])
return "\n".join(lines) + "\n"
def desktop_dir():
try:
path = subprocess.run(["xdg-user-dir", "DESKTOP"], capture_output=True, text=True, timeout=5).stdout.strip()
except (OSError, subprocess.SubprocessError):
path = ""
return path if path and path != HOME else os.path.join(HOME, "Desktop")
def sync(directory, wanted, mode=0o644):
os.makedirs(directory, exist_ok=True)
for name in os.listdir(directory):
if name.startswith(PREFIX) and name.endswith(".desktop") and name not in wanted:
os.unlink(os.path.join(directory, name))
for name, body in wanted.items():
path = os.path.join(directory, name)
if read(path) != body:
try:
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write(body)
os.chmod(path + ".tmp", mode)
os.replace(path + ".tmp", path)
except OSError:
if os.path.lexists(path + ".tmp"):
os.unlink(path + ".tmp")
raise
def main():
os.makedirs(os.path.dirname(PLACED), exist_ok=True)
with open(PLACED + ".lock", "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
try:
refresh()
except OSError as error:
print("droiddeck-desktop-programs: the menu is left as it was (%s)" % error)
def refresh():
menu, desktop_wanted = {}, set()
for appid, pfx in prefixes(STEAM_ROOT):
on_desktop = on_windows_desktop(pfx)
for exe, found in programs(pfx).items():
name = "%s%d-%08x.desktop" % (PREFIX, appid, zlib.crc32(exe.encode("utf-8")))
menu[name] = entry(exe, found)
if exe in on_desktop:
desktop_wanted.add(name)
placed = set((read(PLACED) or "").split())
sync(APPS_DIR, menu)
desktop = desktop_dir()
shown = {name: menu[name] for name in sorted(desktop_wanted)
if name not in placed or present(os.path.join(desktop, name), regular=True)}
try:
sync(desktop, shown, 0o755)
finally:
written = {name for name in shown if present(os.path.join(desktop, name), regular=True)}
with open(PLACED + ".tmp", "w", encoding="utf-8") as f:
f.write("".join(name + "\n" for name in sorted((placed | written) & set(menu))))
os.replace(PLACED + ".tmp", PLACED)
print("droiddeck-desktop-programs: %d program%s in the menu, %d on the desktop" % (
len(menu), "" if len(menu) == 1 else "s", len(shown)))
if __name__ == "__main__":
main()
@@ -0,0 +1,446 @@
#!/usr/bin/env python3
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import sys
import time
PREFIX = "DROIDDECK_PROCESS_TRACE "
SCHEMA = 1
DEFAULT_INTERVAL_MS = 5_000
DEFAULT_DURATION_MS = 86_400_000
DEFAULT_MAX_RECORDS = 512
HEARTBEAT_MS = 300_000
MAX_PROCESSES = 256
MAX_MAP_BYTES = 8 * 1024 * 1024
MAX_MAP_LINES = 65_536
MAX_LIBRARIES = 128
MAX_CMDLINE_BYTES = 16 * 1024
MAX_ENUMERATED_PROCESSES = 4_096
MAX_CHILDREN_BYTES = 64 * 1024
SAFE_LIBRARY = re.compile(r"[A-Za-z0-9._+-]{1,128}")
WINDOWS_GRAPHICS_LIBRARIES = {
"d3d8.dll", "d3d9.dll", "d3d10.dll", "d3d10_1.dll", "d3d10core.dll",
"d3d11.dll", "d3d12.dll", "dxgi.dll", "vulkan-1.dll",
}
KNOWN_GRAPHICS_SONAMES = {
"libvulkan.so", "libvulkan_freedreno.so", "libvulkan_panfrost.so", "libvulkan_lvp.so",
"libvulkan_virtio.so", "libvulkan_dzn.so", "libvulkan_broadcom.so",
"libEGL.so", "libEGL_mesa.so", "libGLESv1_CM.so", "libGLESv2.so", "libGLESv3.so",
"libGL.so", "libGLX.so", "libGLX_mesa.so", "libgbm.so", "libwayland-client.so",
"libX11.so", "libX11-xcb.so", "libdrm.so", "libdrm_amdgpu.so", "libdrm_freedreno.so",
"libdrm_intel.so", "libdrm_nouveau.so", "libdrm_radeon.so", "libxcb.so", "libxcb-dri2.so",
"libxcb-dri3.so", "libxcb-glx.so", "libxcb-present.so", "libxcb-randr.so", "libxcb-render.so",
"libxcb-shm.so", "libxcb-sync.so", "libxcb-xfixes.so", "libhybris-vulkan-icd.so",
"libVkLayer_hybris_compat.so", "libVkLayer_DROIDDECK_placed_memory.so",
"libVkLayer_KHRONOS_validation.so", "libVkLayer_FROG_gamescope_wsi_aarch64.so",
"libVkLayer_MESA_device_select.so", "libVkLayer_MESA_overlay.so", "libvkd3d.so",
"libvkd3d-shader.so", "libvkd3d-utils.so",
}
def emit(payload, output=sys.stdout):
output.write(PREFIX + json.dumps(payload, separators=(",", ":"), sort_keys=True) + "\n")
output.flush()
def process_stat(path):
text = path.read_text(errors="replace")
end = text.rfind(") ")
if end < 0:
raise ValueError("invalid process stat")
fields = text[end + 2:].split()
if len(fields) < 20:
raise ValueError("short process stat")
return int(fields[1]), fields[19]
def bounded_bytes(path, limit):
with path.open("rb") as source:
return source.read(limit)
def process_role(comm, cmdline):
probe = (comm + "\0" + cmdline.decode("utf-8", "replace")).lower()
if "steamwebhelper" in probe:
return "steam-webhelper"
if "gamescope" in probe:
return "gamescope"
if "xwayland" in probe:
return "xwayland"
if "mangoapp" in probe:
return "mangoapp"
if "pressure-vessel" in probe or "steam-runtime" in probe:
return "steam-runtime"
if "steamrtarm64/steam" in probe or "steamrt64/steam" in probe or comm.lower() == "steam":
return "steam-client"
if "fexinterpreter" in probe or comm.lower() == "fex":
return "fex"
if "wineserver" in probe:
return "wineserver"
if any(name in probe for name in ("wine64", "wine-preloader", "/wine ")):
return "wine"
if "pipewire" in probe or "pulseaudio" in probe:
return "audio-server"
if "dbus-daemon" in probe:
return "dbus"
if "droiddeck-session" in probe:
return "session"
return "game-or-helper"
def is_graphics_library(name):
lower = name.lower()
return (
lower in WINDOWS_GRAPHICS_LIBRARIES or
lower.startswith(("libvulkan", "libvklayer", "vulkan.", "libegl", "libgles", "libglx",
"libgl.so", "libgbm", "libdrm", "libwayland", "libxcb", "libx11")) or
"vkd3d" in lower or "dxvk" in lower or "zink" in lower or "mangohud" in lower
)
def origin_class(path):
lower = path.lower()
if lower.startswith("/vendor/"):
return "android-vendor"
if lower.startswith(("/system/", "/apex/")):
return "android-system"
if "/files/components/" in lower or "/files/system_vulkan/" in lower:
return "droiddeck-component"
if "/steamapps/common/" in lower:
return "steam-tool"
if lower.startswith(("/usr/", "/lib/", "/opt/")):
return "guest-runtime"
if lower.startswith("/tmp/"):
return "temporary"
return "other"
def library_identity(name, origin):
if origin in {"android-vendor", "android-system"}:
return name
base = name
while True:
head, separator, tail = base.rpartition(".")
if not separator or not tail.isdigit():
break
base = head
if name.lower() in WINDOWS_GRAPHICS_LIBRARIES or base in KNOWN_GRAPHICS_SONAMES:
return name
return "sha256:" + hashlib.sha256(name.encode()).hexdigest()[:16]
def graphics_libraries(maps_path):
libraries = set()
total = 0
lines = 0
with maps_path.open("rb") as source:
while lines < MAX_MAP_LINES and total < MAX_MAP_BYTES:
raw = source.readline(min(64 * 1024, MAX_MAP_BYTES - total + 1))
if not raw:
break
total += len(raw)
lines += 1
if total > MAX_MAP_BYTES:
return libraries, "capped"
parts = raw.decode("utf-8", "replace").rstrip("\n").split(None, 5)
if len(parts) < 6 or not parts[5].startswith("/"):
continue
mapped = parts[5].removesuffix(" (deleted)")
name = os.path.basename(mapped)
if SAFE_LIBRARY.fullmatch(name) and is_graphics_library(name):
origin = origin_class(mapped)
libraries.add((library_identity(name, origin), origin))
if len(libraries) >= MAX_LIBRARIES:
return libraries, "capped"
return libraries, "readable"
class Collector:
def __init__(self, proc_root, root_pid):
self.proc_root = Path(proc_root)
self.root_pid = int(root_pid)
self.known = {}
self.tokens = {}
self.next_token = 1
self.self_pid = os.getpid()
self.root_identity = None
self.last_maps_state = None
self.last_provider_error = None
def _scan_fallback(self, result):
capped = False
try:
entries = self.proc_root.iterdir()
except OSError:
return capped, "proc-unavailable"
examined = 0
for entry in entries:
if not entry.name.isdigit():
continue
examined += 1
if examined > MAX_ENUMERATED_PROCESSES:
capped = True
break
pid = int(entry.name)
if pid == self.self_pid or pid in result:
continue
try:
result[pid] = process_stat(entry / "stat")
except (OSError, ValueError):
continue
return capped, None
def _stats(self):
result = {}
capped = False
try:
ppid, start = process_stat(self.proc_root / str(self.root_pid) / "stat")
if self.root_pid != self.self_pid:
result[self.root_pid] = (ppid, start)
except (OSError, ValueError):
return result, capped, "proc-unavailable", "children", True
queue = [self.root_pid]
fallback = False
while queue and len(result) < MAX_PROCESSES:
parent = queue.pop(0)
try:
raw = bounded_bytes(
self.proc_root / str(parent) / "task" / str(parent) / "children", MAX_CHILDREN_BYTES + 1,
)
except OSError:
fallback = True
continue
if len(raw) > MAX_CHILDREN_BYTES:
capped = True
fallback = True
continue
for value in raw.split():
if not value.isdigit():
continue
pid = int(value)
if pid == self.self_pid or pid in result:
continue
if len(result) >= MAX_PROCESSES:
capped = True
break
try:
identity = process_stat(self.proc_root / str(pid) / "stat")
except (OSError, ValueError):
continue
if identity[0] != parent:
continue
result[pid] = identity
queue.append(pid)
if queue:
capped = True
if fallback:
fallback_capped, error = self._scan_fallback(result)
capped = capped or fallback_capped
return result, capped, error, "children+scan-fallback", True
return result, capped, None, "children", capped
def scan(self):
stats, enumeration_capped, provider_error, scope_method, scope_incomplete = self._stats()
descendants = set()
root = stats.get(self.root_pid)
if self.root_identity is None and root is not None:
self.root_identity = root
if root is not None and self.root_identity != root:
provider_error = "root-reused"
elif root is not None:
descendants.add(self.root_pid)
changed = True
while changed and len(descendants) < MAX_PROCESSES:
changed = False
for pid, (ppid, _) in stats.items():
if pid not in descendants and ppid in descendants:
descendants.add(pid)
changed = True
if len(descendants) >= MAX_PROCESSES:
break
if provider_error is None and root is None:
provider_error = "root-unavailable"
scope_capped = len(descendants) >= MAX_PROCESSES or enumeration_capped
current = {}
maps_state = {"readable": 0, "unavailable": 0, "capped": 0}
for pid in sorted(descendants):
process = self.proc_root / str(pid)
try:
expected = stats[pid]
if process_stat(process / "stat") != expected:
continue
ppid, start = expected
comm = (process / "comm").read_text(errors="replace")[:128].strip()
cmdline = bounded_bytes(process / "cmdline", MAX_CMDLINE_BYTES)
except (OSError, ValueError):
continue
key = (pid, start)
try:
libraries, state = graphics_libraries(process / "maps")
except (OSError, ValueError):
libraries, state = set(), "unavailable"
maps_state[state] = maps_state.get(state, 0) + 1
current[key] = {
"ppid": ppid,
"role": process_role(comm, cmdline),
"libraries": libraries,
"identity": expected,
"mapState": state,
}
stable = {}
for key, process in current.items():
pid = key[0]
try:
if process_stat(self.proc_root / str(pid) / "stat") != process["identity"]:
continue
except (OSError, ValueError):
continue
stable[key] = process
final = {}
valid_pids = {self.root_pid} if any(key[0] == self.root_pid for key in stable) else set()
changed = True
while changed:
changed = False
for key, process in stable.items():
pid = key[0]
if key not in final and (pid == self.root_pid or process["ppid"] in valid_pids):
final[key] = process
valid_pids.add(pid)
changed = True
current = final
try:
root_final = process_stat(self.proc_root / str(self.root_pid) / "stat")
except (OSError, ValueError):
root_final = None
if root_final is None:
if provider_error is None:
provider_error = "root-unavailable"
current = {}
elif self.root_identity != root_final:
provider_error = "root-reused"
current = {}
maps_state = {"readable": 0, "unavailable": 0, "capped": 0}
for process in current.values():
state = process["mapState"]
maps_state[state] = maps_state.get(state, 0) + 1
started = sorted(set(current) - set(self.known))
exited = sorted(set(self.known) - set(current))
roles_changed = any(
key in self.known and current[key]["role"] != self.known[key]["role"] for key in current
)
for key in started:
self.tokens[key] = self.next_token
self.next_token += 1
state_changed = maps_state != self.last_maps_state or provider_error != self.last_provider_error
payload = self._snapshot(
current, started, exited, maps_state, scope_capped, provider_error, scope_method, scope_incomplete,
)
for key in exited:
self.tokens.pop(key, None)
self.known = current
self.last_maps_state = maps_state
self.last_provider_error = provider_error
return payload, bool(started or exited or roles_changed or payload["librariesChanged"] or state_changed)
def _snapshot(self, current, started, exited, maps_state, scope_capped, provider_error,
scope_method, scope_incomplete):
previous_libraries = {item for process in self.known.values() for item in process["libraries"]}
libraries = {item for process in current.values() for item in process["libraries"]}
role_counts = {}
for process in current.values():
role = process["role"]
role_counts[role] = role_counts.get(role, 0) + 1
started_rows = [{"token": self.tokens[key], "role": current[key]["role"]} for key in started[:32]]
exited_rows = [{"token": self.tokens.get(key, 0), "role": self.known[key]["role"]} for key in exited[:32]]
library_rows = [{"name": name, "origin": origin} for name, origin in sorted(libraries)[:MAX_LIBRARIES]]
return {
"schema": SCHEMA,
"event": "snapshot",
"scope": "root-descendants",
"scopeMethod": scope_method,
"scopeIncomplete": scope_incomplete,
"procView": "guest-visible",
"alive": len(current),
"roles": role_counts,
"started": started_rows,
"startedOmitted": max(0, len(started) - len(started_rows)),
"exited": exited_rows,
"exitedOmitted": max(0, len(exited) - len(exited_rows)),
"libraries": library_rows,
"librariesOmitted": max(0, len(libraries) - len(library_rows)),
"librariesChanged": libraries != previous_libraries,
"maps": maps_state,
"scopeCapped": scope_capped,
"providerStatus": provider_error or "available",
}
def parse_args(argv):
parser = argparse.ArgumentParser()
parser.add_argument("--once", action="store_true")
parser.add_argument("--watch", action="store_true")
parser.add_argument("--root-pid", type=int, default=os.getppid())
parser.add_argument("--proc-root", default="/proc")
parser.add_argument("--interval-ms", type=int, default=DEFAULT_INTERVAL_MS)
parser.add_argument("--duration-ms", type=int, default=DEFAULT_DURATION_MS)
parser.add_argument("--max-records", type=int, default=DEFAULT_MAX_RECORDS)
args = parser.parse_args(argv)
if args.once == args.watch:
parser.error("choose exactly one of --once or --watch")
if args.root_pid <= 0:
parser.error("--root-pid must be positive")
args.interval_ms = min(60_000, max(250, args.interval_ms))
args.duration_ms = min(DEFAULT_DURATION_MS, max(0, args.duration_ms))
args.max_records = min(1_024, max(3, args.max_records))
return args
def main(argv=None, environ=None, output=sys.stdout):
environ = os.environ if environ is None else environ
if environ.get("DROIDDECK_ENHANCED_DIAGNOSTICS") != "1":
return 0
args = parse_args(sys.argv[1:] if argv is None else argv)
collector = Collector(args.proc_root, args.root_pid)
emit({
"schema": SCHEMA,
"event": "provider",
"mode": "once" if args.once else "watch",
"intervalMs": args.interval_ms,
"durationMs": 0 if args.once else args.duration_ms,
"maxRecords": args.max_records,
"scope": "root-descendants",
"procView": "guest-visible",
}, output)
records = 1
started = time.monotonic()
last_heartbeat = started
ended_normally = False
while records < args.max_records - 1:
payload, changed = collector.scan()
now = time.monotonic()
if changed or records == 1 or (now - last_heartbeat) * 1000 >= HEARTBEAT_MS:
if not changed and records > 1:
payload["event"] = "heartbeat"
payload.pop("libraries", None)
payload["librariesUnchanged"] = True
payload["elapsedMs"] = int((now - started) * 1000)
emit(payload, output)
records += 1
last_heartbeat = now
if args.once or payload["providerStatus"] in {"root-unavailable", "root-reused"} or \
(now - started) * 1000 >= args.duration_ms:
ended_normally = True
break
time.sleep(args.interval_ms / 1000)
if not ended_normally:
emit({"schema": SCHEMA, "event": "limit", "reason": "max-records"}, output)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -14,7 +14,7 @@ install)
droiddeck-root /usr/bin/apt-get install -y -q retroarch retroarch-assets $cores || { echo "== FAIL apt-get install"; exit 1; }
echo "== STEP PPSSPP"
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || { echo "== FAIL flathub"; exit 1; }
flatpak install --user -y --noninteractive flathub org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
/usr/bin/python3 /usr/local/bin/droiddeck-flatpak install org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
printf '#!/bin/sh\nexec /usr/local/bin/droiddeck-flatpak-run org.ppsspp.PPSSPP "$@"\n' > /usr/local/bin/PPSSPPSDL.new &&
chmod 755 /usr/local/bin/PPSSPPSDL.new && mv -f /usr/local/bin/PPSSPPSDL.new /usr/local/bin/PPSSPPSDL || { echo "== FAIL PPSSPPSDL"; exit 1; }
;;
@@ -111,6 +111,12 @@ def d3dgear_hook(game):
return {"WINEDLLOVERRIDES": "d3dgear64=d"}, [], "D3DGear capture hook off (it stops the game drawing)"
@fix
def supergiant_dotnet_reporter(game):
if "basecampbugreporter.native.dll" in game.files:
return {"WINEDLLOVERRIDES": "mscoree=n,b"}, [], "Supergiant: allow the builtin mscoree"
@fix
def deep_rock_gdk_raytracing(game):
if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")):
@@ -153,32 +159,6 @@ def little_nightmares_threads(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
@fix
def caravan_sandwitch_feature_level(game):
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Caravan SandWitch: D3D12 feature level 12_1 (12_2 hands it mesh shader pipelines vkd3d-proton cannot build)"
@fix
def robocop_rogue_city_feature_level(game):
if "robocop.exe" in game.files or game.stem == "robocop-win64-shipping":
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1"
@fix
def reskate_feature_level(game):
if "skate.exe" in game.files and "reskate.dll" in game.files:
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "ReSkate (skate.): D3D12 feature level 12_1"
@fix
def cyberpunk_feature_level(game):
if game.stem == "cyberpunk2077" or (
game.stem == "redprelauncher"
and os.path.isfile(os.path.join(os.path.dirname(game.exe), "bin", "x64", "Cyberpunk2077.exe"))
):
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Cyberpunk 2077: D3D12 feature level 12_1"
def skip_red_launcher(command):
if len(command) > 2 and os.path.basename(command[2]).lower() == "redprelauncher.exe":
game = os.path.join(os.path.dirname(command[2]), "bin", "x64", "Cyberpunk2077.exe")
@@ -243,6 +223,20 @@ def ubisoft_overlay_off(env):
print("droiddeck-game-env: Ubisoft Connect overlay left as is (%s)" % error, file=sys.stderr)
def ubisoft_composition_off(proton, env):
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
if not (prefix / UBISOFT_LAUNCHER).is_dir() or not (prefix / "user.reg").is_file():
return
try:
for program in ("upc.exe", "UplayWebCore.exe"):
key = r"HKCU\Software\Wine\AppDefaults\%s\DllOverrides" % program
subprocess.run([proton, "runinprefix", "reg.exe", "add", key,
"/v", "dcomp", "/t", "REG_SZ", "/d", "", "/f"], env=env, check=True)
print("droiddeck-game-env: Ubisoft Connect uses CEF without DirectComposition", file=sys.stderr)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
print("droiddeck-game-env: Ubisoft Connect composition configuration failed (%s)" % error, file=sys.stderr)
PZ_JVM_FLAGS = ("-XX:+UseG1GC", "-XX:TieredStopAtLevel=1")
@@ -372,6 +366,8 @@ def vram_cap(env):
cap = "dxgi.maxDeviceMemory = %d" % int(value)
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
result["DROIDDECK_VRAM_CAP"] = "1"
result["DROIDDECK_VRAM_CAP_MB"] = value
return result
@@ -528,9 +524,51 @@ def apply_config(env, config, app_id, fixes=None):
if dxvk:
own = result.get("DXVK_CONFIG", "").strip().rstrip(";").strip()
result["DXVK_CONFIG"] = own + "; " + dxvk if own else dxvk
# An open driver pair (PanVK, RADV) on a GPU that is not an Adreno: vkd3d-proton reports the
# driver's own feature level and shader model. The app-wide 12_2 / 6_9 over-promised what PanVK
# has, and an Unreal DX12 game took paths that crashed. A game's own setting still wins.
if env.get("BL_OPEN_DRIVER") == "1":
game = config.get("games", {}).get(app_id, {}) or {}
for name in ("VKD3D_FEATURE_LEVEL", "VKD3D_SHADER_MODEL"):
if name not in game and name in result:
result.pop(name)
result["DROIDDECK_VKD3D_CAPS"] = "driver"
return result
def render_path_defaults(command, env):
if len(command) < 3 or command[1] != "waitforexitandrun" or Path(command[2]).name.lower() != "spintires.exe":
return None
own = env.get("DXVK_CONFIG", "")
if re.search(r"(?:^|;)\s*dxvk\.tilerMode\s*=", own) or env.get("DXVK_CONFIG_FILE"):
return None
if Path("dxvk.conf").is_file() or Path(command[2]).with_name("dxvk.conf").is_file():
return None
driver = env.get("VK_DRIVER_FILES", env.get("VK_ICD_FILENAMES", ""))
if Path(driver).parent.name != "DD-Turnip_v0.4.0":
return None
try:
if Path("/sys/class/kgsl/kgsl-3d0/gpu_model").read_text().strip() != "Adreno722":
return None
with open(driver, encoding="utf-8") as source:
library = json.load(source)["ICD"]["library_path"]
if Path(library).name != "libvulkan_freedreno.so":
return None
except (OSError, ValueError, KeyError, TypeError):
return None
own = own.strip().rstrip(";").strip()
env["DXVK_CONFIG"] = own + "; dxvk.tilerMode = False" if own else "dxvk.tilerMode = False"
return "Spintires: DXVK tiler heuristics off on Adreno 722"
def bridge_feature_level(env):
if env.get("BL_VKBRIDGE") != "1" or env.get("VKD3D_FEATURE_LEVEL") not in ("12_1", "12_2"):
return None
was = env["VKD3D_FEATURE_LEVEL"]
env["VKD3D_FEATURE_LEVEL"] = "12_0"
return "Mali bridge: VKD3D_FEATURE_LEVEL %s capped at 12_0 (no ray tracing or mesh shaders)" % was
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
@@ -923,7 +961,7 @@ def ego_core_plan(command, env):
return "%s had no thread plan for %d cores; added a copy of its %s-core plan" % (EGO_RESTRICTIONS, count, source.group(2))
def wait_forwarding_signals(process):
def wait_forwarding_signals_raw(process):
def forward(signum, frame):
try:
process.send_signal(signum)
@@ -936,20 +974,56 @@ def wait_forwarding_signals(process):
finally:
for signum, handler in previous.items():
signal.signal(signum, handler)
return code
def wait_forwarding_signals(process):
code = wait_forwarding_signals_raw(process)
return 128 - code if code < 0 else code
def start(launch, launch_env, digest, after=None):
if after:
def diagnostic_game_event(event, app_id, values=None):
fields = ["event=" + event, "app_id=" + app_id]
fields.extend("%s=%s" % item for item in (values or {}).items())
print("DROIDDECK_DIAGNOSTICS " + " ".join(fields), file=sys.stderr, flush=True)
def diagnostic_game_exit(app_id, raw_code, source=None, wrapper_status=None):
normalized = 128 - raw_code if raw_code < 0 else raw_code
values = {
"raw_status": raw_code,
"normalized_status": normalized,
"wrapper_status": normalized if wrapper_status is None else wrapper_status,
"signal": -raw_code if raw_code < 0 else 0,
}
if source is not None:
values["source"] = source
diagnostic_game_event("game_exit", app_id, values)
def start(launch, launch_env, digest, after=None, diagnostic_app_id=None):
if len(launch) > 1 and launch[1] == "waitforexitandrun":
ubisoft_composition_off(launch[0], launch_env)
launch, launch_env = system_graphics_launch(launch, launch_env)
if after or diagnostic_app_id is not None:
process = subprocess.Popen(launch, env=launch_env)
if diagnostic_app_id is not None:
diagnostic_game_event("game_start", diagnostic_app_id)
try:
return wait_forwarding_signals(process)
raw_code = wait_forwarding_signals_raw(process)
finally:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
if after:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
code = 128 - raw_code if raw_code < 0 else raw_code
if digest and after is None and code == 0:
record_install_scripts(digest, launch_env)
if diagnostic_app_id is not None:
diagnostic_game_exit(diagnostic_app_id, raw_code)
return code
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
@@ -958,6 +1032,110 @@ def start(launch, launch_env, digest, after=None):
return os.execvpe(launch[0], launch, launch_env)
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 game_logs(command, env, app_id, now=None):
"""Detailed graphics logs for one game launch, in the session's log folder: Proton's own log,
DXVK's and vkd3d-proton's, and the Vulkan driver's startup messages. The app turns this on
(BL_GAME_LOGS=1) on a GPU that is not an Adreno, or with Setup's "Detailed graphics logs"."""
if env.get("BL_GAME_LOGS") != "1" or not env.get("BL_DEBUG_DIR") or len(command) < 3 \
or command[1] != "waitforexitandrun":
return env
import time
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
name = app_id or re.sub(r"[^A-Za-z0-9._-]+", "_", Path(command[2]).stem)[:40] or "game"
parent = Path(env["BL_DEBUG_DIR"]) / "games"
try:
parent.mkdir(parents=True, exist_ok=True)
folder = Path(tempfile.mkdtemp(prefix=stamp + "-", suffix="-" + name, dir=parent))
except OSError as error:
print("droiddeck-game-env: no game log folder (%s)" % error, file=sys.stderr)
return env
result = dict(env)
result.update({
"PROTON_LOG": "1",
"PROTON_LOG_DIR": str(folder),
"DXVK_LOG_PATH": str(folder),
"DXVK_LOG_LEVEL": env.get("DXVK_LOG_LEVEL", "info"),
"VKD3D_LOG_FILE": str(folder / "vkd3d.log"),
"VKD3D_DEBUG": env.get("VKD3D_DEBUG", "warn"),
"VKD3D_SHADER_DEBUG": env.get("VKD3D_SHADER_DEBUG", "none"),
"MESA_LOG_FILE": str(folder / "mesa.log"),
"PANVK_DEBUG": env.get("PANVK_DEBUG", "startup"),
})
try:
(folder / "launch.txt").write_text("\n".join([
"app: %s" % (app_id or "-"),
"exe: %s" % command[2],
"proton: %s" % command[0],
"started: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now)),
] + ["%s=%s" % (key, env[key]) for key in sorted(env)
if key.startswith(("VK_", "BL_VK", "BL_DRM", "BL_OPEN", "MESA_", "PANVK", "DXVK_", "VKD3D", "ZINK", "TU_", "DROIDDECK_VKD3D"))]) + "\n")
except OSError:
pass
# Whether the game's sound reaches PulseAudio: the streams 20 s and 60 s in, without waiting.
try:
subprocess.Popen(["sh", "-c", 'for t in 20 40; do sleep $t; { echo "== $(date +%T)"; '
'pactl list sink-inputs 2>&1 | head -80; } >> "$1/audio-streams.txt"; done', "audio", str(folder)],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
except OSError:
pass
return 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:
@@ -974,10 +1152,11 @@ def main():
except OSError:
digest = None
app_id = game_id(env)
waiting = bool(app_id and len(command) > 1 and command[1] == "waitforexitandrun")
diagnostic_app_id = app_id if waiting and os.environ.get("DROIDDECK_ENHANCED_DIAGNOSTICS") == "1" else None
dirt_prefix = None
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
if waiting:
game_images(env)
fixes = {}
@@ -1024,10 +1203,17 @@ def main():
print("droiddeck-game-env: OpenGL does not wait for the screen refresh (vblank_mode=0)", file=sys.stderr)
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
env = game_logs(command, env, app_id)
if mic_enabled == "0":
env["AUDIO_DIRECT_MIC"] = "0"
env = directaudio_settings(env)
env = vram_cap(env)
note = render_path_defaults(command, env) if app_id else None
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
note = bridge_feature_level(env)
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env, command)
@@ -1049,6 +1235,8 @@ def main():
print("droiddeck-game-env: Xbox launch could not start (%s)" % error, file=sys.stderr)
return 1
if xbox_result is not None:
if diagnostic_app_id is not None and isinstance(xbox_result, int):
diagnostic_game_exit(diagnostic_app_id, xbox_result, "xbox", xbox_result % 256)
return xbox_result
after = None
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
@@ -1074,13 +1262,13 @@ def main():
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
return start(launch, launch_env, digest, after)
return start(launch, launch_env, digest, after, diagnostic_app_id)
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)
try:
return start(launch, launch_env, digest, after)
return start(launch, launch_env, digest, after, diagnostic_app_id)
except OSError:
if after:
try:
@@ -1092,4 +1280,8 @@ def main():
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)
@@ -17,6 +17,7 @@ PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run")
APPIMAGE_RUN = os.path.join(BIN, "droiddeck-appimage-run")
SCRIPT_RUN = os.path.join(BIN, "droiddeck-script-run")
STEAM_LAUNCH = os.path.join(BIN, "droiddeck-steam-launch")
PROGRAMS = os.path.join(BIN, "droiddeck-desktop-programs")
CACHE = os.path.join(HOME, ".cache", "droiddeck")
IMPORTS = {"appimage": ("/opt/appimages/user", "app"), "folder": ("/opt/droiddeck-apps", "entry")}
SHARED_FOLDERS = ("alarms", "android", "audiobooks", "dcim", "documents", "download", "movies", "music",
@@ -395,6 +396,11 @@ def main(argv):
if status != 0 and time.monotonic() - started < QUICK_FAILURE:
notify("%s did not start" % os.path.basename(path),
"It exited with status %d; the session's desktop.log says why." % status)
if what == "windows":
try:
subprocess.call([sys.executable, PROGRAMS])
except OSError as error:
say("%s: %s" % (PROGRAMS, error))
return status
@@ -351,7 +351,7 @@ def steam_launch(appid, root):
library, install = steam_install(appid, root)
if not install or not os.path.isdir(install):
return None
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf")).get(str(appid), {})
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf"), wanted={str(appid)}).get(str(appid), {})
options = [option for option in entry.get("launch_options", ())
if not option["betakey"] and (not option["oslist"] or "windows" in option["oslist"])]
options.sort(key=lambda option: (option["type"] not in ("", "default", "none"),
@@ -376,7 +376,7 @@ def shortcut_target(appid, program, start, root):
def steam_launches(target, program, root):
if target.kind != "steam":
return False
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf")).get(target.appid, {})
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf"), wanted={target.appid}).get(target.appid, {})
return os.path.relpath(program, target.install).replace(os.sep, "/").lower() in entry.get("launch", ())
@@ -24,7 +24,7 @@ read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
proc[depth] = 1
program = tolower(part[4])
sub(/.*[\\\/]/, "", program)
if (program ~ /vulkan|uplay|ubisoft/) vulkan[depth] = 1
if (program ~ /vulkan|uplay|ubisoft|eaapp/) vulkan[depth] = 1
next
}
if (n == 3) pending = part[2]
@@ -245,7 +245,7 @@ for system in "${regs[@]}"; do
had=()
for line in "${kept[@]}"; do had[$line]=1; done
printf '%s\n' "${other[@]}" "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime and Ubisoft Connect markers out of $reg"
echo "== took Vulkan runtime, Ubisoft Connect and EA app markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
declare -A held=()
@@ -1,5 +1,15 @@
#!/bin/bash
set -u
# A GPU that is not an Adreno (BL_RAISE_NOFILE=1): the open-files limit goes up to the hard limit
# for the whole session tree (gamescope, Steam, games). A Mali PanVK session ran out after ten
# minutes ("Too many open files" importing sync files and dma-bufs) and froze.
if [ "${BL_RAISE_NOFILE:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ]; then
bl_nofile_was="$(ulimit -Sn)/$(ulimit -Hn)"
ulimit -Sn "$(ulimit -Hn)" 2>/dev/null || true
echo "== open files: soft/hard $bl_nofile_was -> soft $(ulimit -Sn)"
[ -n "${BL_DEBUG_DIR:-}" ] && echo "soft/hard $bl_nofile_was -> soft $(ulimit -Sn) (session tree)" > "$BL_DEBUG_DIR/limits.txt" 2>/dev/null
unset bl_nofile_was
fi
export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
@@ -22,6 +32,19 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
fi
start_diagnostic_inventory() {
[ "${DROIDDECK_ENHANCED_DIAGNOSTICS:-0}" = 1 ] || return 0
[ -z "${BL_INSIDE:-}" ] || return 0
if ! command -v droiddeck-diagnostic-inventory >/dev/null 2>&1; then
printf '%s\n' 'DROIDDECK_PROCESS_TRACE {"schema":1,"event":"provider","status":"unavailable"}'
return 0
fi
droiddeck-diagnostic-inventory --watch --root-pid "$$" &
_bl_diagnostic_inventory=$!
trap 'kill "$_bl_diagnostic_inventory" 2>/dev/null || true; wait "$_bl_diagnostic_inventory" 2>/dev/null || true' EXIT
}
start_diagnostic_inventory
sync_timezone() {
local zone=${TZ:-}
case "$zone" in ''|/*|*..*) return 0 ;; esac
@@ -141,8 +164,13 @@ run_gamescope() (
BL_STEAM_EXIT_FILE="$status_file" gamescope "$@"
compositor_status=$?
if read -r child_status < "$status_file" && [[ $child_status =~ ^[0-9]{1,3}$ ]] \
&& [ "$child_status" -gt 0 ] && [ "$child_status" -le 255 ]; then
exit "$child_status"
&& [ "$child_status" -le 255 ]; then
if [ "${DROIDDECK_ENHANCED_DIAGNOSTICS:-0}" = 1 ]; then
printf 'DROIDDECK_DIAGNOSTICS event=session_exit compositor_status=%s steam_status=%s\n' "$compositor_status" "$child_status"
fi
[ "$child_status" -eq 0 ] || exit "$child_status"
elif [ "${DROIDDECK_ENHANCED_DIAGNOSTICS:-0}" = 1 ]; then
printf 'DROIDDECK_DIAGNOSTICS event=session_exit compositor_status=%s steam_status=unavailable\n' "$compositor_status"
fi
exit "$compositor_status"
)
@@ -160,7 +188,7 @@ collect_steam_logs() {
cp "$fex_state/status.json" "$fex_state/config/Config.json" "$BL_DEBUG_DIR/droiddeck-fex/" 2>/dev/null
fi
}
trap 'collect_steam_logs 2>/dev/null || true' TERM INT HUP
trap 'bl_stopping=1; collect_steam_logs 2>/dev/null || true' TERM INT HUP
if [ -n "${BL_VK_DRIVER:-}" ]; then
bl_icd_lib=$(sed -n 's/.*"library_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$BL_VK_DRIVER" 2>/dev/null | head -1)
bl_icd_lib=$(printf '%s' "$bl_icd_lib" | sed 's|\\/|/|g')
@@ -177,6 +205,143 @@ if [ -n "${BL_VK_DRIVER:-}" ]; then
fi
unset bl_icd_lib
fi
bl_webhelper_layout() {
if [ -n "${BL_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then
printf '%s\n' "$BL_VKBRIDGE_WEBHELPER_ARGS"
elif [ -z "${BL_VKBRIDGE_CEF_ANGLE:-}" ]; then
echo stock
elif [ "$BL_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${BL_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
echo "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
else
echo "--use-gl=angle --use-angle=$BL_VKBRIDGE_CEF_ANGLE"
fi
}
bl_now_ms() {
if [ -n "${EPOCHREALTIME:-}" ]; then
local t=${EPOCHREALTIME/[.,]/}
echo $((10#$t / 1000))
else
date +%s%3N
fi
}
vkbridge_wait_socket() {
local sock=$1 limit=${2:-10000} start now waited
[ -n "$sock" ] || return 1
if [ -S "$sock" ]; then
echo "== vkbridge: server socket ready (waited 0 ms)"
return 0
fi
start=$(bl_now_ms)
while :; do
now=$(bl_now_ms)
waited=$((now - start))
if [ -S "$sock" ]; then
echo "== vkbridge: server socket ready (waited $waited ms; the server listens after its startup probe)"
return 0
fi
if [ -n "${bl_stopping:-}" ]; then
echo "== vkbridge: no server socket after $waited ms; the session is stopping"
return 1
fi
if [ "$waited" -ge "$limit" ]; then
echo "== vkbridge: no server socket after $waited ms (gave up at $limit ms)"
return 1
fi
sleep 0.05
done
}
if [ "${BL_VKBRIDGE:-0}" = 1 ]; then
bl_vkb_icd=/usr/local/share/vkbridge/droidbridge_icd.json
[ -z "${BL_INSIDE:-}" ] && vkbridge_wait_socket "${VKBRIDGE_SOCKET:-}" "${BL_VKBRIDGE_WAIT_MS:-10000}"
bl_vkb_missing=
[ -r "$bl_vkb_icd" ] || bl_vkb_missing="$bl_vkb_missing icd"
[ -r /usr/local/lib/vkbridge/libvulkan_droidbridge.so ] || bl_vkb_missing="$bl_vkb_missing library"
[ -S "${VKBRIDGE_SOCKET:-}" ] || bl_vkb_missing="$bl_vkb_missing socket"
if [ -z "$bl_vkb_missing" ]; then
export VK_DRIVER_FILES=$bl_vkb_icd VK_ICD_FILENAMES=$bl_vkb_icd
export VKBRIDGE_SOCKET VKBRIDGE_CLIENT_LOG
if [ -r /root/.vkbridge-env ]; then
while IFS='=' read -r _k _v; do
case "$_k" in VKBRIDGE_*|BL_VKBRIDGE_*) export "$_k=$_v" ;; esac
done < /root/.vkbridge-env
[ -z "${BL_INSIDE:-}" ] && echo "== vkbridge: development settings from /root/.vkbridge-env: $(cut -d= -f1 /root/.vkbridge-env | tr '\n' ' ')"
fi
export VKD3D_FEATURE_LEVEL=${VKD3D_FEATURE_LEVEL:-12_0}
unset TU_DEBUG
if [ -z "${BL_INSIDE:-}" ]; then
step "vkbridge self-test"
bl_vkb_smoke=$(timeout 60 /usr/local/bin/droiddeck-vkbridge-smoke 2>&1)
printf '%s\n' "$bl_vkb_smoke" | sed 's/^/== vkbridge: /'
bl_vkb_why=
if printf '%s\n' "$bl_vkb_smoke" | grep -qE '^FAIL memory sharing'; then
bl_vkb_why=memory
elif printf '%s\n' "$bl_vkb_smoke" | grep -qE '^FAIL (image clear|draw)'; then
bl_vkb_why=draw
fi
if [ -n "$bl_vkb_why" ] && [ -r "${BL_VKBRIDGE_FALLBACK_ICD:-}" ]; then
export VK_DRIVER_FILES=$BL_VKBRIDGE_FALLBACK_ICD VK_ICD_FILENAMES=$BL_VKBRIDGE_FALLBACK_ICD BL_VKBRIDGE=0
export BL_OPEN_DRIVER=1 BL_DRM_STANDIN=/dev/mali0
[ "${BL_STEAM_GPU_COMPOSITING:-0}" = 1 ] || export BL_STEAM_SOFT_COMPOSITING=1
if [ "$bl_vkb_why" = memory ]; then
echo "== vkbridge: memory sharing = none (no method passed the server's self-test); this session uses the PanVK pair instead ($BL_VKBRIDGE_FALLBACK_ICD)"
else
echo "== vkbridge: self-test failed images or draws; this session uses the PanVK pair instead ($BL_VKBRIDGE_FALLBACK_ICD)"
fi
[ -n "${BL_DEBUG_DIR:-}" ] && printf '%s\n%s\n' "$BL_VKBRIDGE_FALLBACK_ICD" "$bl_vkb_why" > "$BL_DEBUG_DIR/vkbridge-fallback" 2>/dev/null
elif [ -n "$bl_vkb_why" ]; then
echo "== vkbridge: self-test failed ($bl_vkb_why) and no PanVK pair is installed to fall back on; expect a black screen or a lost device - set a Mali driver pair in Setup"
fi
unset bl_vkb_why
unset bl_vkb_smoke
if command -v vulkaninfo >/dev/null 2>&1; then
timeout 30 vulkaninfo --summary 2>&1 | sed -n '/^Devices:/,$p' | head -40 | sed 's/^/== vulkaninfo: /'
fi
fi
[ "${BL_VKBRIDGE:-0}" = 1 ] && echo "== vulkan driver: Mali bridge ($bl_vkb_icd, server at $VKBRIDGE_SOCKET)"
else
echo "== vulkan driver: Mali bridge requested but NOT usable (icd $bl_vkb_icd, socket ${VKBRIDGE_SOCKET:-unset}; missing:$bl_vkb_missing)"
[ -n "${BL_INSIDE:-}" ] || exit 69
fi
unset bl_vkb_icd bl_vkb_missing
fi
if [ "${BL_VENUS:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && command -v vulkaninfo >/dev/null 2>&1; then
if bl_vn_info=$(timeout 30 vulkaninfo 2>/dev/null); then
case $(printf '%s\n' "$bl_vn_info" | grep -m1 'nullDescriptor') in
*true*) echo "== venus: nullDescriptor present (Zink keeps the GPU)" ;;
*)
export GALLIUM_DRIVER=llvmpipe LIBGL_ALWAYS_SOFTWARE=1
unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2
echo "== venus: no nullDescriptor on this device even with the Mali compatibility layer; Steam's GL and Xwayland use llvmpipe (software)"
;;
esac
else
echo "== venus: vulkaninfo failed or timed out; GL left on Zink"
fi
unset bl_vn_info
fi
if [ "${BL_GAME_LOGS:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && [ -n "${BL_DEBUG_DIR:-}" ]; then
(
{
echo "== VK_DRIVER_FILES=${VK_DRIVER_FILES:-} VK_ICD_FILENAMES=${VK_ICD_FILENAMES:-} BL_DRM_STANDIN=${BL_DRM_STANDIN:-}"
if command -v vulkaninfo >/dev/null 2>&1; then
timeout 10 vulkaninfo --summary
echo "== vulkaninfo exit: $?"
if timeout 20 vulkaninfo > "$BL_DEBUG_DIR/vulkan-full.txt" 2>&1; then
echo "== device extensions (full list in vulkan-full.txt):"
sed -n '/^Device Extensions:/,/^$/p' "$BL_DEBUG_DIR/vulkan-full.txt" | grep -o 'VK_[A-Za-z0-9_]*' | sort -u | tr '\n' ' ' | fold -s -w 200
echo
echo "== key features:"
grep -E '^[[:space:]]+(robustBufferAccess2?|robustImageAccess2?|nullDescriptor|logicOp|fillModeNonSolid|shaderClipDistance|shaderCullDistance|dualSrcBlend|geometryShader|scalarBlockLayout|timelineSemaphore|dynamicRendering|synchronization2|maintenance4|maintenance5|maintenance6|shaderDrawParameters|descriptorIndexing|bufferDeviceAddress|vulkanMemoryModel|hostQueryReset|imagelessFramebuffer|samplerYcbcrConversion|shaderInt64|shaderFloat64|shaderInt16|shaderFloat16|storageBuffer16BitAccess|extendedDynamicState[23]?|vertexInputDynamicState|customBorderColors|customBorderColorWithoutFormat|depthClipEnable|multiViewport|textureCompressionBC|indexTypeUint8|rectangularLines|bresenhamLines|transformFeedback|geometryStreams|graphicsPipelineLibrary|pushDescriptor|primitiveTopologyListRestart|dynamicRenderingLocalRead|shaderDemoteToHelperInvocation|subgroupSizeControl|computeFullSubgroups|inlineUniformBlock|pipelineCreationCacheControl) = ' "$BL_DEBUG_DIR/vulkan-full.txt" | sed 's/^[[:space:]]*/ /' | sort -u
else
echo "== full vulkaninfo failed or timed out (exit $?)"
fi
else
echo "== vulkaninfo is not in this runtime; GPU nodes:"
ls -l /dev/kgsl-3d0 /dev/mali0 /dev/dri 2>&1
fi
} > "$BL_DEBUG_DIR/vulkan-summary.txt" 2>&1
) &
fi
export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0}
rm -rf /tmp/.droiddeck-rx
@@ -189,6 +354,38 @@ nap() {
[ -n "${bl_nap_fd:-}" ] || exec {bl_nap_fd}<> <(:)
read -r -t "$1" -u "$bl_nap_fd" _ 2>/dev/null || :
}
# Which program a driver error came from: Mesa's lines ("radv/amdgpu: The CS has been rejected",
# "ZINK: vkQueueWaitIdle failed") carry no process name. For the first three minutes of an open
# driver pair's session, every process that appears goes into processes.txt with the session log's
# line count at that moment, so an error's line number in session.log points at what had just
# started. Pure bash over /proc (no execs: see nap).
watch_processes() {
local out=$BL_DEBUG_DIR/processes.txt log=$BL_DEBUG_DIR/session.log i p pid comm lines
local -a argv new
local -A seen=()
echo "# seconds session.log-lines pid name command line" > "$out" 2>/dev/null || return 0
for ((i = 0; i < 360; i++)); do
new=()
for p in /proc/[0-9]*; do
pid=${p#/proc/}
[ -n "${seen[$pid]:-}" ] && continue
seen[$pid]=1
read -r comm < "$p/comm" 2>/dev/null || continue
argv=()
mapfile -d '' -t argv < "$p/cmdline" 2>/dev/null
new+=("$pid"$'\t'"$comm"$'\t'"${argv[*]:0:8}")
done
if [ ${#new[@]} -gt 0 ]; then
lines=0
[ -r "$log" ] && { mapfile -t argv < "$log"; lines=${#argv[@]}; argv=(); }
for p in "${new[@]}"; do printf '%s\t%s\t%.200s\n' "$SECONDS" "$lines" "$p"; done >> "$out"
fi
nap 0.5
done
}
if [ "${BL_OPEN_DRIVER:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && [ -n "${BL_DEBUG_DIR:-}" ]; then
watch_processes &
fi
export XDG_DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share}
export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
@@ -222,6 +419,7 @@ program_cores() {
[ "${BL_PIN_CORES:-1}" = 0 ] && return 0
command -v taskset >/dev/null 2>&1 || return 0
if [ -n "${BL_GAME_CPUS:-}" ]; then echo "$BL_GAME_CPUS"; return 0; fi
[ "$mode" = run ] && return 0
local f n max min= list=
for f in /sys/devices/system/cpu/cpu[0-9]*/cpufreq/cpuinfo_max_freq; do
max=$(cat "$f" 2>/dev/null) || continue
@@ -305,10 +503,23 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output"
fi
fi
backend=${BL_GAMESCOPE_BACKEND:-wayland}
case "$backend" in
wayland) ;;
sdl) export SDL_VIDEODRIVER=wayland ;;
*) echo "== unsupported gamescope backend: $backend"; exit 64 ;;
esac
if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then
export gamescope_cursor_composite=2
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
# Through the Mali bridge, Steam's UI flickered while gamescope handed its layers to the phone's
# compositor as separate planes, for a reason not yet found; one composited image does not
# (Mali-G76 MC4: 145 footer flips in 6 s at rest, 0 composited).
if [ "$mode" = steam ] && [ "${BL_VKBRIDGE:-0}" = 1 ] && [ -z "${gamescope_composite_force:-}" ]; then
export gamescope_composite_force=1
echo "== gamescope: composites every frame (Mali bridge: the Steam UI flickers on separate planes)"
fi
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
args+=(-S stretch)
export BL_STRETCHED=1
@@ -609,8 +820,75 @@ case $mode in
done 2>/dev/null < "/proc/$_p/status"
done
_bl_rss=$_rss
_bl_swap=$_swap
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
}
bl_memory_read() {
local _k _v _u _kind _fields _avg
_bl_mem_total=0 _bl_available=-1 _bl_swap_total=0 _bl_swap_free=-1 _bl_psi=0
while read -r _k _v _u; do
case $_v in ''|*[!0-9]*) continue ;; esac
case $_k in
MemTotal:) _bl_mem_total=$_v ;;
MemAvailable:) _bl_available=$_v ;;
SwapTotal:) _bl_swap_total=$_v ;;
SwapFree:) _bl_swap_free=$_v ;;
esac
done 2>/dev/null < /proc/meminfo
if [ -r /proc/pressure/memory ]; then
while read -r _kind _fields; do
[ "$_kind" = some ] || continue
_avg=${_fields#avg10=} _avg=${_avg%% *} _avg=${_avg%%.*}
case $_avg in ''|*[!0-9]*) ;; *) _bl_psi=$((10#$_avg)) ;; esac
done 2>/dev/null < /proc/pressure/memory
fi
_bl_headroom=$((_bl_mem_total / 5))
[ "$_bl_headroom" -ge $((512 * 1024)) ] || _bl_headroom=$((512 * 1024))
[ "$_bl_headroom" -le $((1536 * 1024)) ] || _bl_headroom=$((1536 * 1024))
_bl_swap_reserve=$((_bl_swap_total / 5))
[ "$_bl_swap_reserve" -ge $((256 * 1024)) ] || _bl_swap_reserve=$((256 * 1024))
}
bl_memory_tight() {
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] &&
{ [ "$_bl_available" -lt "$_bl_headroom" ] ||
{ [ "$_bl_psi" -ge 1 ] && [ "$_bl_available" -lt $((_bl_mem_total / 3)) ]; }; }
}
bl_client_can_pageout() {
bl_memory_read
bl_zram_usage "${_bl_pids[@]}" > /dev/null
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_swap_total" -gt 0 ] &&
[ $((_bl_swap_free - _bl_rss)) -ge "$_bl_swap_reserve" ]
}
bl_client_can_readback() {
bl_memory_read
bl_zram_usage "${_bl_pids[@]}" > /dev/null
[ "$_bl_mem_total" -gt 0 ] && ! bl_memory_tight &&
[ "$_bl_available" -ge $((_bl_swap * 2)) ] &&
[ $((_bl_available - _bl_swap)) -ge "$_bl_headroom" ]
}
bl_client_pressure() {
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ "$_bl_game" = 1 ] &&
[ "${#_bl_pids[@]}" -gt 0 ] && bl_memory_tight || return 0
[ "$_bl_pressure_at" -lt 0 ] ||
[ $((SECONDS - _bl_pressure_at)) -ge "$_bl_pressure_backoff" ] || return 0
[ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 30 ] || return 0
_bl_pressure_at=$SECONDS
if ! bl_client_can_pageout; then
step "zRAM: pressure reclaim skipped, swap headroom too small ($((_bl_swap_free / 1024)) MB free)"
return 0
fi
[ "$_bl_rss" -ge $((128 * 1024)) ] || return 0
local _before=$_bl_rss
bl_zram_send 1 "memory pressure, compressing the client (available $((_bl_available / 1024)) MB, swap free $((_bl_swap_free / 1024)) MB)" client
_bl_packed=$SECONDS
[ "${_bl_pageout_complete:-0}" = 1 ] || return 0
bl_zram_usage "${_bl_pids[@]}" > /dev/null
if [ $((_before - _bl_rss)) -lt $((16 * 1024)) ]; then
_bl_pressure_backoff=$((_bl_pressure_backoff * 2 > 300 ? 300 : _bl_pressure_backoff * 2))
else
_bl_pressure_backoff=30
fi
}
bl_session_others() {
local _p
_bl_session=()
@@ -639,7 +917,11 @@ case $mode in
[ "$_left" = 1 ] || break
nap 0.2
done
for _p in "$@"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
_bl_pageout_complete=1
for _p in "$@"; do
if [ -d "/proc/$_p" ] && [ ! -s "/tmp/.bl-zram.ack.$_p" ]; then _bl_pageout_complete=0; fi
rm -f "/tmp/.bl-zram.ack.$_p"
done
}
bl_zram_send() {
local _mode=$1 _what=$2 _which=$3 _pids _p
@@ -677,8 +959,10 @@ case $mode in
[ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; }
}
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
_bl_pressure_at=-1 _bl_pressure_backoff=30
while kill -0 $$ 2>/dev/null; do
bl_zram_scan
bl_memory_read
if bl_cap_due; then
if bl_over_cap; then
if [ "$_bl_capped" -lt 0 ] || [ $((SECONDS - _bl_capped)) -ge "$_bl_backoff" ]; then
@@ -700,29 +984,30 @@ case $mode in
fi
else
_bl_backoff=30
if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ]; then
bl_zram_send 0 "back under the RAM cap, reading the client back" client
_bl_unpack=0
fi
fi
fi
bl_client_pressure
if [ "$_bl_game" = 1 ] && bl_game_focused; then
if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then
_bl_since=$SECONDS _bl_since_apps=$_bl_apps
fi
if [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
{ [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; }; then
{ [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; } && bl_client_can_pageout; then
bl_zram_send 1 "compressing the client" client
_bl_packed=$SECONDS
fi
elif [ "$_bl_game" != 1 ]; then
if [ "$_bl_packed" -ge 0 ]; then
if bl_over_cap; then _bl_unpack=1; else bl_zram_send 0 "game closed, reading the client back" client; _bl_unpack=0; fi
_bl_unpack=1
fi
_bl_since=-1 _bl_packed=-1
else
_bl_since=-1
fi
if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ] && ! bl_over_cap && bl_client_can_readback; then
bl_zram_send 0 "memory recovered, reading the client back" client
_bl_unpack=0
fi
nap 5
done
) &
@@ -973,6 +1258,20 @@ case $mode in
export STEAM_STEAMRT_RECURSION_GUARD=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"
export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true
bl_steam_angle=gl
bl_steam_presentation=(-cef-disable-gpu-compositing)
echo "== steam: system PowerVR uses OpenGL/DRI3 through Zink with software CEF compositing"
elif [ "${BL_STEAM_SOFT_COMPOSITING:-}" = 1 ]; then
bl_steam_presentation=(-cef-disable-gpu-compositing)
echo "== steam: open driver pair - software CEF compositing, GPU raster"
fi
_bl_cef=(-cef-force-gpu "${bl_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=$bl_steam_angle")
decky_loader=$HOME/homebrew/services/PluginLoader
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
@@ -1022,12 +1321,36 @@ case $mode in
fi
_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 (set above) 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:-vulkan}")
[ "${steam_cef_gpu:-1}" = 1 ] || _bl_cef=(-cef-disable-gpu)
if [ "${BL_DESKTOP:-}" = 1 ] && [ "${BL_STEAM_UI:-}" = desktop ]; then
_bl_cef=(-cef-disable-gpu)
_bl_ui=(-nobigpicture)
fi
if [ "${BL_VKBRIDGE:-0}" = 1 ]; then
# On the GPU the Steam UI held about 400 MB through the bridge (Mali-G76 MC4, 3 GB of RAM); with
# a game loading beside it, Android's low-memory killer took the whole session down.
if [ -z "${BL_VKBRIDGE_CEF_GPU:-}" ]; then
_bl_mem_kb=$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null)
if [ "${_bl_mem_kb:-0}" -gt 0 ] && [ "$_bl_mem_kb" -lt 4194304 ]; then
BL_VKBRIDGE_CEF_GPU=0
echo "== steam: $((_bl_mem_kb / 1024)) MB of RAM: the browser UI draws in software to leave games the memory"
fi
fi
if [ "${BL_VKBRIDGE_CEF_GPU:-1}" = 0 ]; then
_bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing)
echo "== steam: browser UI in software (Mali bridge)"
elif [ "${_bl_cef[0]}" = -cef-force-gpu ]; then
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle="${BL_VKBRIDGE_CEF_ANGLE:-vulkan}")
fi
[ "${BL_VKBRIDGE_CEF_LOG:-0}" = 1 ] && _bl_cef+=(-cef-enable-logging=stderr -cef-v=1)
[ -n "${BL_VKBRIDGE_CEF_EXTRA:-}" ] && read -r -a _bl_cef_extra <<<"$BL_VKBRIDGE_CEF_EXTRA" && _bl_cef+=("${_bl_cef_extra[@]}")
BL_WEBHELPER_ARGS=$(bl_webhelper_layout)
export BL_WEBHELPER_ARGS
echo "== steam: web helper process layout: $BL_WEBHELPER_ARGS (Mali bridge)"
fi
if [ "${BL_STEAM_UI:-}" != desktop ]; then
if [ "$steam_x64" = 0 ] || [ "${BL_X64_DECK:-1}" != 0 ]; then
_bl_ui+=(-steamdeck -steamos3)
@@ -1353,6 +1676,36 @@ case $mode in
done
) &
stop_watcher=$!
if [ "${BL_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then
LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /'
if [ "${PIPESTATUS[0]}" = 1 ]; then
VK_LOADER_DEBUG=error,warn timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -40 | sed 's/^/== glprobe (loader): /'
DROIDDECK_MALI_COMPAT_TRACE=1 MESA_DEBUG=1 MESA_LOG_LEVEL=debug LIBGL_DEBUG=verbose ZINK_DEBUG=mem VN_DEBUG=init,result,log_ctx_info \
timeout 30 /usr/local/bin/droiddeck-glprobe > "${BL_DEBUG_DIR:-/tmp}/glprobe-trace.txt" 2>&1
grep -v drirc "${BL_DEBUG_DIR:-/tmp}/glprobe-trace.txt" | head -120 | sed 's/^/== glprobe (trace): /'
echo "== glprobe (trace): last pre-device query before Zink gave up: $(grep 'droiddeck-mali-compat: trace:' "${BL_DEBUG_DIR:-/tmp}/glprobe-trace.txt" | grep -v 'trace: extensions:' | tail -1)"
command -v vulkaninfo >/dev/null 2>&1 && DROIDDECK_MALI_COMPAT_TRACE=1 timeout 20 vulkaninfo --summary 2>&1 | head -40 | sed 's/^/== glprobe (vulkaninfo): /'
bl_gl_ok=
for bl_variant in "ZINK_DEBUG=" "ZINK_DEBUG= ZINK_DESCRIPTORS=auto" "ZINK_DEBUG= LIBGL_KOPPER_DISABLE=true" "ZINK_DEBUG= DROIDDECK_MALI_COMPAT=0"; do
if env $bl_variant timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -20 | sed "s/^/== glprobe ($bl_variant): /"; [ "${PIPESTATUS[0]}" = 0 ]; then
bl_gl_ok=$bl_variant
break
fi
done
if [ -n "$bl_gl_ok" ] && [ "$bl_gl_ok" != "ZINK_DEBUG= DROIDDECK_MALI_COMPAT=0" ]; then
for bl_kv in $bl_gl_ok; do
case $bl_kv in *=) unset "${bl_kv%=}" ;; *) export "$bl_kv" ;; esac
done
echo "== venus: GL through Zink starts with: $bl_gl_ok (the Steam client gets that)"
else
[ -n "$bl_gl_ok" ] && echo "== venus: Zink starts only without the Mali compatibility layer (then without nullDescriptor); not used"
export GALLIUM_DRIVER=llvmpipe LIBGL_ALWAYS_SOFTWARE=1
unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2
echo "== venus: GL through Zink did not start (see glprobe above); the Steam client's GL uses llvmpipe (software)"
fi
unset bl_gl_ok bl_variant bl_kv
fi
fi
rm -f "$HOME/.bl-restart-game" "$HOME/.bl-restarted-for"
while :; do
rm -f "$HOME/.bl-restart-once" "$HOME/.bl-restart-lost"
@@ -1378,6 +1731,8 @@ case $mode in
desktop_ui_pid=$!
fi
steam_started=$SECONDS
PATH="$bl_steam_path" \
BL_STEAM_WEBHELPER="$steam_root/steamrtarm64/steamwebhelper" \
"${steam_client[@]}" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
rc=$?
@@ -1387,6 +1742,9 @@ case $mode in
wait "$desktop_ui_pid" 2>/dev/null || true
fi
echo "== steam exited rc=$rc"
if [ "${DROIDDECK_ENHANCED_DIAGNOSTICS:-0}" = 1 ]; then
printf 'DROIDDECK_DIAGNOSTICS event=steam_exit shell_status=%s elapsed_seconds=%s\n' "$rc" "$steam_ran"
fi
collect_steam_logs
if [ -f "$HOME/.config/droiddeck/fex-wanted" ] && [ -x /usr/local/bin/droiddeck-fex ]; then
/usr/local/bin/droiddeck-fex status >/dev/null 2>&1 || true
@@ -317,6 +317,74 @@ FRAME_LIMIT_JS = r"""
return "installed";
})()
"""
WINDOW_BINDING = "droiddeckWindowAction"
WINDOW_TARGET = "createflags=18"
WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8}
WINDOW_JS = r"""
(() => {
if (window.__droiddeckWindow) return "present";
const EDGE = 5, CORNER = 10, THRESHOLD = 3;
const CURSORS = { n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize",
ne: "nesw-resize", sw: "nesw-resize", nw: "nwse-resize", se: "nwse-resize" };
const send = action => window.droiddeckWindowAction(action);
const filled = () => innerWidth >= screen.availWidth && innerHeight >= screen.availHeight - 60;
const side = e => {
if (filled()) return "";
const right = innerWidth - e.clientX, bottom = innerHeight - e.clientY;
const near = (a, b) => a < EDGE || (a < CORNER && b < CORNER);
const across = Math.min(e.clientX, right), along = Math.min(e.clientY, bottom);
const v = near(e.clientY, across) ? "n" : near(bottom, across) ? "s" : "";
const h = near(e.clientX, along) ? "w" : near(right, along) ? "e" : "";
return v + h;
};
const dragging = (x, y) => {
for (const node of document.elementsFromPoint(x, y)) {
const region = getComputedStyle(node).webkitAppRegion;
if (region === "drag") return true;
if (region === "no-drag") return false;
}
return [...document.querySelectorAll("*")].some(node => {
if (getComputedStyle(node).webkitAppRegion !== "drag") return false;
const box = node.getBoundingClientRect();
return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
});
};
const style = document.createElement("style");
document.documentElement.append(style);
let press = null, shown = "";
addEventListener("pointermove", e => {
if (press) {
if (Math.hypot(e.clientX - press.x, e.clientY - press.y) >= THRESHOLD) {
const hit = dragging(press.x, press.y);
press = null;
if (hit) send("move");
}
return;
}
const cursor = e.buttons ? shown : side(e);
if (cursor !== shown) {
shown = cursor;
style.textContent = cursor ? `* { cursor: ${CURSORS[cursor]} !important; }` : "";
}
}, true);
addEventListener("pointerdown", e => {
if (e.button !== 0) return;
const edge = side(e);
if (edge) {
e.stopPropagation();
e.preventDefault();
send(edge);
} else {
press = { x: e.clientX, y: e.clientY };
}
}, true);
addEventListener("pointerup", () => { press = null; }, true);
addEventListener("dblclick", e => { if (dragging(e.clientX, e.clientY) && !side(e)) send("maximize"); }, true);
SteamClient.Window.ToggleMaximize = () => send("maximize");
window.__droiddeckWindow = true;
return "installed";
})()
"""
FILE_BINDING = "droiddeckOpenFileDialog"
FILE_JS = r"""
(() => {
@@ -739,6 +807,71 @@ class Watcher:
return any(n in wanted or n.startswith("appmanifest_") for n in names)
class XMessage(ctypes.Structure):
_fields_ = [("type", ctypes.c_int), ("serial", ctypes.c_ulong), ("send_event", ctypes.c_int),
("display", ctypes.c_void_p), ("window", ctypes.c_ulong), ("message_type", ctypes.c_ulong),
("format", ctypes.c_int), ("data", ctypes.c_long * 5), ("pad", ctypes.c_long * 20)]
X_ERRORS = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p)(lambda display, error: 0)
def window_action(action):
if action != "maximize" and action not in WINDOW_MOVES:
return False
x11 = ctypes.CDLL("libX11.so.6")
x11.XOpenDisplay.restype = ctypes.c_void_p
x11.XOpenDisplay.argtypes = [ctypes.c_char_p]
x11.XDefaultRootWindow.restype = ctypes.c_ulong
x11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
x11.XInternAtom.restype = ctypes.c_ulong
x11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
x11.XGetWindowProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long,
ctypes.c_int, ctypes.c_ulong] + [ctypes.c_void_p] * 5
x11.XQueryPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + [ctypes.c_void_p] * 7
x11.XSendEvent.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_long, ctypes.c_void_p]
x11.XFree.argtypes = [ctypes.c_void_p]
x11.XFlush.argtypes = [ctypes.c_void_p]
x11.XCloseDisplay.argtypes = [ctypes.c_void_p]
x11.XSetErrorHandler(X_ERRORS)
display = x11.XOpenDisplay(None)
if not display:
return False
try:
root = x11.XDefaultRootWindow(display)
atom = lambda name: x11.XInternAtom(display, name, 0)
kind, width, count, after = ctypes.c_ulong(), ctypes.c_int(), ctypes.c_ulong(), ctypes.c_ulong()
data = ctypes.c_void_p()
if x11.XGetWindowProperty(display, root, atom(b"_NET_ACTIVE_WINDOW"), 0, 1, 0, 33, ctypes.byref(kind),
ctypes.byref(width), ctypes.byref(count), ctypes.byref(after),
ctypes.byref(data)) != 0 or not data.value:
return False
window = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong))[0] if count.value else 0
x11.XFree(data)
if not window:
return False
if action == "maximize":
kind_name = b"_NET_WM_STATE"
values = [2, atom(b"_NET_WM_STATE_MAXIMIZED_VERT"), atom(b"_NET_WM_STATE_MAXIMIZED_HORZ"), 1, 0]
else:
ignored = ctypes.c_ulong()
x, y, inner, mask = ctypes.c_int(), ctypes.c_int(), ctypes.c_int(), ctypes.c_uint()
if not x11.XQueryPointer(display, root, ctypes.byref(ignored), ctypes.byref(ignored), ctypes.byref(x),
ctypes.byref(y), ctypes.byref(inner), ctypes.byref(inner), ctypes.byref(mask)):
return False
if not mask.value & 0x100:
return False
kind_name = b"_NET_WM_MOVERESIZE"
values = [x.value, y.value, WINDOW_MOVES[action], 1, 1]
message = XMessage(type=33, window=window, message_type=atom(kind_name), format=32)
message.data[:] = values
sent = x11.XSendEvent(display, root, 0, (1 << 19) | (1 << 20), ctypes.byref(message))
x11.XFlush(display)
return bool(sent)
finally:
x11.XCloseDisplay(display)
class Helper:
def __init__(self, steam_root, port, steamos=False, files_only=False):
self.steam_root = steam_root
@@ -757,6 +890,8 @@ class Helper:
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.windows = {}
self.windows_retry = 0
def sync_controls(self):
try:
@@ -780,6 +915,41 @@ class Helper:
except (OSError, ValueError, TypeError):
pass
def sync_windows(self):
if os.environ.get("XDG_CURRENT_DESKTOP") != "KDE":
return
if time.monotonic() >= self.windows_retry:
self.windows_retry = time.monotonic() + 2
try:
targets = http_get(self.port, "/json/list")
except (OSError, ValueError):
targets = []
seen = set()
for target in targets:
url = target.get("webSocketDebuggerUrl")
if WINDOW_TARGET not in target.get("url", "").split("&")[0] or not url:
continue
seen.add(target.get("id"))
try:
page = self.windows.get(target.get("id"))
if page is None:
page = Page(self.port, "/" + url.split("/", 3)[3])
page.call("Runtime.addBinding", {"name": WINDOW_BINDING}, timeout=5)
self.windows[target.get("id")] = page
page.evaluate(WINDOW_JS, timeout=5)
except (Closed, OSError, RuntimeError, ValueError) as e:
say("window controls: %s" % e)
self.windows.pop(target.get("id"), None)
for ident in set(self.windows) - seen:
del self.windows[ident]
for ident, page in list(self.windows.items()):
try:
for event in page.drain():
if called(event, WINDOW_BINDING):
window_action(event.get("params", {}).get("payload"))
except (Closed, OSError, ValueError):
del self.windows[ident]
def sync_frame_limit(self):
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
return
@@ -1025,7 +1195,9 @@ class Helper:
say("attached to the client on port %d for its file dialogs" % self.port)
while True:
self.sync_controls()
self.sync_windows()
sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else [])
sources += [page.ws for page in self.windows.values()]
queued = self.page.ws.pending() or bool(self.page.events)
ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
@@ -1044,7 +1216,9 @@ class Helper:
while True:
self.sync_controls()
self.sync_frame_limit()
self.sync_windows()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
sources += [page.ws for page in self.windows.values()]
if self.chooser is not None:
sources.append(self.chooser[1].stdout)
queued = self.page.ws.pending() or bool(self.page.events)
@@ -11,6 +11,7 @@ import time
import unicodedata
import urllib.parse
import urllib.request
import zlib
STATE = ".droiddeck-games.json"
TRIED = ".droiddeck-import-tried.json"
@@ -301,15 +302,76 @@ def installed_build(folder, appid, installdir):
if not (folder / ".download_complete").is_file():
return None
try:
ids = json.loads((folder / ".DepotDownloader/depot.config").read_text())["installedManifestIDs"]
depots = sorted((int(depot), int(gid)) for depot, gid in ids.items())
except (OSError, ValueError, KeyError, TypeError, AttributeError):
return None
depots = config_depots((folder / ".DepotDownloader/depot.config").read_bytes())
except OSError:
depots = None
if not depots:
depots = completed_depots(folder / ".DepotDownloader/completed")
if not depots or not all(0 < depot < 0x80000000 and 0 < gid < 0x7FFFFFFFFFFFFFFF for depot, gid in depots):
return None
return "".join(f' "{depot}"\n {{\n "manifest" "{gid}"\n }}\n' for depot, gid in depots)
def varint(data, i):
value = shift = 0
while True:
byte = data[i]
i += 1
value |= (byte & 0x7F) << shift
shift += 7
if byte < 0x80:
return value, i
def proto_fields(data):
i = 0
while i < len(data):
key, i = varint(data, i)
kind = key & 7
if kind == 0:
value, i = varint(data, i)
elif kind == 2:
size, i = varint(data, i)
value, i = data[i:i + size], i + size
elif kind in (1, 5):
value, i = None, i + (8 if kind == 1 else 4)
else:
raise ValueError
yield key >> 3, kind, value
def config_depots(data):
try:
ids = json.loads(data.decode())["installedManifestIDs"]
return sorted((int(depot), int(gid)) for depot, gid in ids.items())
except (ValueError, KeyError, TypeError, AttributeError):
pass
try:
depots = {}
for number, kind, entry in proto_fields(zlib.decompress(data, -15)):
if number == 1 and kind == 2:
fields = {n: v for n, k, v in proto_fields(entry) if k == 0}
if 1 in fields and 2 in fields:
depots[fields[1]] = fields[2]
return sorted(depots.items()) or None
except (zlib.error, ValueError, IndexError):
return None
def completed_depots(completed):
newest = {}
try:
for manifest in completed.iterdir():
match = re.fullmatch(r"(\d+)_(\d+)\.manifest", manifest.name)
if match and manifest.is_file():
depot, gid, mtime = int(match[1]), int(match[2]), manifest.stat().st_mtime
if depot not in newest or mtime > newest[depot][0]:
newest[depot] = (mtime, gid)
except OSError:
return []
return sorted((depot, gid) for depot, (_, gid) in newest.items())
def update_not_started(text, steamapps, appid, installdir):
fields = dict(re.findall(r'^\s*"(\w+)"\s*"([^"]*)"', text, re.M))
return (fields.get("installdir") == installdir and fields.get("buildid", "0") == "0"
@@ -318,6 +380,13 @@ def update_not_started(text, steamapps, appid, installdir):
and not (steamapps / "downloading" / str(appid)).exists())
def update_on_launch(text):
if re.search(r'^\s*"AutoUpdateBehavior"', text, re.M):
return re.sub(r'^(\s*"AutoUpdateBehavior"\s*")0(")', r"\g<1>1\2", text, count=1, flags=re.M)
end = text.rstrip().rfind("}")
return text[:end] + '\t"AutoUpdateBehavior"\t\t"1"\n' + text[end:]
def libraries(steam_root):
try:
text = (Path(steam_root) / "steamapps/libraryfolders.vdf").read_text(errors="replace")
@@ -374,9 +443,11 @@ def seed_install(steam_root, game, appid):
minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
+ f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n')
legacy = minimal.replace(' "Universe" "1"\n', '')
# Steam checks every file of an import with no build before updating it, from scratch each time it is interrupted.
bare = minimal[:-2] + ' "AutoUpdateBehavior" "1"\n}\n'
build = installed_build(source, appid, name)
if build is None:
content = minimal
content = bare
elif build.lstrip().startswith('"AppState"'):
content = build
else:
@@ -390,13 +461,21 @@ def seed_install(steam_root, game, appid):
for root in libraries(steam_root):
existing = root / "steamapps" / manifest.name
if existing.is_file():
if (existing == manifest and source.is_dir() and target.is_symlink()
and os.readlink(target) == str(source)
and existing.read_text() != content
and (existing.read_text() in (minimal, legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"'))
or (build is not None and update_not_started(existing.read_text(), steamapps, appid, name)))):
if not (existing == manifest and source.is_dir() and target.is_symlink()
and os.readlink(target) == str(source)):
return True
text = existing.read_text()
staging = (steamapps / "downloading" / str(appid)).exists()
if build is None and update_not_started(text, steamapps, appid, name):
wanted = update_on_launch(text)
elif ((text in (minimal, bare, legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"')) and not staging)
or (build is not None and update_not_started(text, steamapps, appid, name))):
wanted = content
else:
wanted = text
if wanted != text:
temp = manifest.with_suffix(".droiddeck")
temp.write_text(content)
temp.write_text(wanted)
os.replace(temp, manifest)
return True
if not source.is_dir():
@@ -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 "$@"
@@ -730,7 +730,7 @@ if x64_gpu; then
echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'"
echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER"
for v in $gpu_vars; do
eval "val=\${$v-}"; [ -n "$val" ] && printf "export %s='%s'\n" "$v" "$val"
eval "val=\${$v-}"; [ -n "$val" ] && printf "export %s='%s'\n" "$v" "${val//\'/\'\\\'\'}"
done
} > "$X64_HOME/game-gpu.env"
fi
@@ -829,7 +829,7 @@ x64_exec() {
mkdir -p "$STEAM_X64/logs"
touch "$STEAM_X64/logs/bootstrap_log.txt"
( tail -n0 -F --pid=$$ "$STEAM_X64/logs/bootstrap_log.txt" 2>/dev/null |
grep --line-buffered -oE 'Downloading update \([0-9,]+ of [0-9,]+ KB\)' | sed -u 's/,//g' >&2 ) &
grep --line-buffered -oE 'Downloading update \([0-9,]+ of [0-9,]+ KB\)|^[[:space:]]*(\[[^]]+\][[:space:]]*)*(Extracting package|Installing update)\.\.\.[[:space:]]*$' | sed -u 's/,//g' >&2 ) &
echo "== x86-64 client: steamrt64 $(x64_manifest_version steamrt64) (the client may update itself)" >&2
x64_webhelper_gpu && { x64_gpu_watch >&2 & }
exec "${BL_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@"
@@ -357,6 +357,27 @@ GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MAC
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
WINE_USER = "C:\\users\\steamuser"
# GOG completes some installs by running a support installer from the game folder (the
# goggame-<id>.script "Execute" action). Under ARM64 FEX that 32-bit self-extractor stops at
# "Path not found", so the values it would write are applied here instead. Only products GOG
# ships no setRegistry action for are listed; a script's own entries always win.
# The Witcher: Enhanced Edition (#694) exits during startup unless the installer's
# HKLM\Software\CD Projekt Red\The Witcher keys exist - the same ones The Witcher's own
# setup writes (InstallFolder, RegionVersion, IsDjinniInstalled) plus its language.
GOG_INSTALL_REGISTRY = {
"1207658924": [
("HKLM", "Software\\CD Projekt Red\\The Witcher", "InstallFolder", "string", "{app}\\"),
("HKLM", "Software\\CD Projekt Red\\The Witcher", "RegionVersion", "string", "US"),
("HKLM", "Software\\CD Projekt Red\\The Witcher", "IsDjinniInstalled", "dword", 1),
("HKLM", "Software\\CD Projekt Red\\The Witcher", "Language", "string", "{language}"),
("HKCU", "Software\\CD Projekt RED\\Witcher\\Settings", "TextLanguage", "string", "{language}"),
("HKCU", "Software\\CD Projekt RED\\Witcher\\Settings", "VoiceLanguage", "string", "{language}"),
],
}
# The Witcher's text and voice language IDs, from its installer's registry data.
GOG_LANGUAGE_IDS = {"en": 3, "fr": 11, "de": 10, "es": 12, "it": 13, "ru": 14, "cs": 15, "hu": 16,
"zh": 21, "pl": 5}
def gog_paths(folder, product):
app = windows_path(str(folder))
@@ -416,8 +437,94 @@ def gog_entry(arguments, paths):
return None
def gog_registry(folder):
entries, skipped = [], 0
def gog_installed_products(folder):
products = {}
for info in sorted(Path(folder).glob("goggame-*.info")):
product = info.name[len("goggame-"):-len(".info")]
if not product.isdigit():
continue
try:
products[product] = json.loads(info.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
products[product] = {}
return products
def gog_language_id(info):
languages = info.get("languages") if isinstance(info, dict) else None
if isinstance(languages, str):
languages = [languages]
code = str(languages[0]).lower()[:2] if isinstance(languages, list) and languages else ""
return GOG_LANGUAGE_IDS.get(code, GOG_LANGUAGE_IDS["en"])
GOG_VALUE_HIVES = {"hklm": "local_machine", "hkey_local_machine": "local_machine",
"hkcu": "current_user", "hkey_current_user": "current_user",
"hkcr": "classes_root", "hkey_classes_root": "classes_root"}
def gog_value_key(root, section, name, view32=True):
"""A registry value's identity, keeping the root and the 32-bit view apart.
The fallback import always targets the 32-bit view (`/reg:32`), which Wine keeps under
`Software\\Wow6432Node` for HKLM: a native HKLM value must not pass for the 32-bit one.
HKCU\\Software is shared by both views, so its values read the same either way.
"""
text = section.replace("\\\\", "\\").strip("\\").lower()
hive = GOG_VALUE_HIVES.get(root.lower(), root.lower())
if text.startswith("software\\wow6432node\\"):
text = text[len("software\\wow6432node\\"):]
elif hive == "local_machine" and not view32 and text.startswith("software\\"):
text = "native\\" + text
elif text.startswith("software\\"):
text = text[len("software\\"):]
return "%s|%s|%s" % (hive, text, name.lower())
def gog_registry_values(pfx):
"""Values already in the prefix, so install defaults never overwrite a player's choice."""
values = set()
for file, root in (("system.reg", "hklm"), ("user.reg", "hkcu")):
try:
lines = (pfx / file).read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
continue
section = ""
for line in lines:
if line.startswith("["):
end = line.find("]")
section = line[1:end] if end > 0 else line[1:]
continue
match = re.match(r'^"([^"]+)"=', line)
if match and section:
values.add(gog_value_key(root, section, match.group(1), view32=False))
return values
def gog_scripted_products(folder):
products = set()
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
try:
actions = json.loads(script.read_text(encoding="utf-8-sig")).get("actions")
except (OSError, ValueError, AttributeError):
continue
if isinstance(actions, list) and any(
isinstance(action, dict) and isinstance(action.get("install"), dict)
and action["install"].get("action") == "setRegistry" for action in actions):
products.add(script.name[len("goggame-"):-len(".script")])
return products
def gog_expected_values(folder):
"""The fallback values a launch must find, so the marker never hides one that was deleted."""
scripted = gog_scripted_products(folder)
return [gog_value_key(root, subkey, name) for product in gog_installed_products(folder)
if product in GOG_INSTALL_REGISTRY and product not in scripted
for root, subkey, name, _kind, _value in GOG_INSTALL_REGISTRY[product]]
def gog_registry(folder, existing=()):
entries, skipped, scripted = [], 0, set()
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
try:
@@ -434,11 +541,28 @@ def gog_registry(folder):
skipped += 1
else:
entries.append(entry)
scripted.add(product)
for product, info in gog_installed_products(folder).items():
if product in scripted or product not in GOG_INSTALL_REGISTRY:
continue
paths = dict(gog_paths(folder, product), language=str(gog_language_id(info)))
for root, subkey, name, kind, value in GOG_INSTALL_REGISTRY[product]:
if gog_value_key(root, subkey, name) in existing:
continue
entry = gog_entry({"root": root, "subkey": subkey, "valueName": name,
"valueType": kind, "valueData": value}, paths)
if entry is None:
skipped += 1
else:
entries.append(entry)
return entries, skipped
def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=None):
entries, skipped = gog_registry(folder)
pfx = Path(compat_data) / "pfx" if compat_data else None
existing = gog_registry_values(pfx) if pfx else set()
entries, skipped = gog_registry(folder, existing)
expected = gog_expected_values(folder)
if installation:
product = str(installation["id"])
if not product.isdigit():
@@ -465,10 +589,10 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=Non
return "no-proton" + note
text = "Windows Registry Editor Version 5.00\r\n\r\n" + "".join(entry + "\r\n\r\n" for entry in entries)
stamp = hashlib.sha256(text.encode("utf-8")).hexdigest()
pfx = Path(compat_data) / "pfx"
marker = pfx / GOG_REGISTRY_MARK
try:
if marker.is_file() and marker.read_text() == stamp and (pfx / "system.reg").is_file():
if (marker.is_file() and marker.read_text() == stamp and (pfx / "system.reg").is_file()
and set(expected) <= existing):
return "ready" + note
Path(compat_data).mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
@@ -476,15 +476,30 @@ def save_state(compat, state):
def pending_for(app_id, pending=PENDING):
try:
with open(pending, encoding="utf-8") as source:
ids = json.load(source).get("games", {}).get(str(app_id), [])
config = json.load(source)
ids = config.get("games", {}).get(str(app_id), [])
revisions = config.get("revisions", {})
except (OSError, ValueError, AttributeError):
return []
return [i for i in ids if valid_id(i)] if isinstance(ids, list) else []
return {}
revisions = revisions if isinstance(revisions, dict) else {}
return {i: max(0, revisions[i]) if type(revisions.get(i)) is int else 0
for i in ids if valid_id(i)} if isinstance(ids, list) else {}
def wait_for_pending(app_id, pending=PENDING, store=STORE, timeout=PENDING_WAIT, sleep=time.sleep, clock=time.monotonic):
def missing():
return [cid for cid in pending_for(app_id, pending) if component(store, cid) is None]
left = []
for cid, revision in pending_for(app_id, pending).items():
try:
with open(Path(store) / cid / "component.json", encoding="utf-8") as source:
meta = json.load(source)
installed = meta.get("revision", 0)
ready = type(installed) is int and installed >= revision
except (OSError, ValueError, AttributeError):
ready = False
if not ready:
left.append(cid)
return left
left = missing()
if not left:
return None
@@ -585,6 +600,8 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
written, registry_notes = apply_registry(pfx, values, new_state, held)
notes += registry_notes
save_state(compat, new_state)
overrides, fallback = reachable_overrides(pfx, overrides)
notes += fallback
if copied or removed or restored or written:
note = "components %s: %d file(s) placed, %d removed" % (",".join(ids) or "none", copied, removed)
note += ", %d put back as they were" % restored if restored else ""
@@ -592,6 +609,26 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
return overrides, notes
def native_dll(pfx, name):
for arch in ARCH_DIRS:
path = existing(pfx / "drive_c/windows" / arch / (name + ".dll"))
if path is None or builtin(path) or not os.access(path, os.R_OK):
return False
return True
def reachable_overrides(pfx, names):
kept, notes = [], []
for entry in names:
name, sep, mode = entry.partition("=")
name = name.strip().lower()
if sep and mode.strip().lower() == "n" and not native_dll(pfx, name):
entry = name + "=n,b"
notes.append("%s=n has no native DLL in the prefix; using n,b" % name)
kept.append(entry)
return kept, notes
def overrides_value(names):
modes = {}
for entry in names:
@@ -26,6 +26,9 @@ SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
# Linux builds that bundle an arm64 binary their launcher starts; Steamworks offers no arm64
# launch-option architecture, so appinfo cannot say so (#1774).
FEX_DEFAULT_APPS = frozenset({"4385780"})
FULLY_INSTALLED = 4
UPDATE_REQUIRED = 2
REQUEST_HANDOFF_SECONDS = 30
@@ -173,6 +176,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"
@@ -779,20 +785,32 @@ def launch_options(config):
return found
def appinfo_entries(path):
def appinfo_entries(path, wanted=None):
"""Read metadata for all apps, or only the requested app-id strings."""
import struct
if wanted is not None:
wanted = set(wanted)
if not wanted:
return {}
try:
stamp = os.stat(path).st_mtime_ns
except OSError:
return {}
cached = APPINFO_CACHE.get(path)
if cached and cached[0] == stamp:
return cached[1]
try:
with open(path, "rb") as f:
data = f.read()
except OSError:
return {}
covered = cached[2]
if covered is None or (wanted is not None and wanted <= covered):
return cached[1] if wanted is None else {app: cached[1][app] for app in wanted if app in cached[1]}
data = cached[3]
needed = None if wanted is None else wanted - covered
else:
cached = None
needed = wanted
try:
with open(path, "rb") as f:
data = f.read()
except OSError:
return {}
if len(data) < 8:
return {}
magic = struct.unpack_from("<I", data, 0)[0]
@@ -854,6 +872,8 @@ def appinfo_entries(path):
break
start = offset + 8
offset = start + size
if needed is not None and str(app) not in needed:
continue
try:
info = section(start + header)[0].get("appinfo", {})
except (ValueError, IndexError, struct.error):
@@ -878,8 +898,14 @@ def appinfo_entries(path):
entry["app_mappings"] = {str(m.get("appid", key)): str(m.get("tool", "")) for key, m in mappings.items()
if isinstance(m, dict)} if isinstance(mappings, dict) else {}
found[str(app)] = entry
APPINFO_CACHE[path] = (stamp, found)
return found
covered = wanted
if cached is not None and wanted is not None:
cached[1].update(found)
found = cached[1]
covered = cached[2] | wanted
# None coverage is complete; partial entries keep one immutable file snapshot.
APPINFO_CACHE[path] = (stamp, found, covered, data if covered is not None else None)
return found if wanted is None else {app: found[app] for app in wanted if app in found}
def appinfo_platforms(path, wanted):
@@ -912,7 +938,7 @@ def native_targets(steam_root, apps):
if "arm64" in osarch or "aarch64" in osarch:
targets[app] = None
continue
if "windows" in oslist:
if "windows" in oslist and app not in FEX_DEFAULT_APPS:
targets[app] = NATIVE_CHOICE
continue
targets[app] = FEX_TOOL
@@ -1063,7 +1089,7 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
continue
mine = auto.get(app)
target = native.get(app, default)
if not name and app in native_choices:
if not name and (app in native_choices or (app in current and app in FEX_DEFAULT_APPS)):
target = NATIVE_CHOICE
stale = unrunnable(name, runnable)
if name and not stale and (mine is None or name != mine):
@@ -1360,6 +1386,20 @@ def read_config_mapping(config_path):
return read_mapping(tokens, mapping + steam + 1) if mapping is not None else {}
def mapping_entry(app, tool):
return ['"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""',
'"priority"', '"75"' if app == "0" else '"250"', "}"]
def set_mapping_tool(tokens, block, tool):
end = block_end(tokens, block)
for i in range(block + 1, end):
if tokens[i] == '"name"':
tokens[i + 1] = '"%s"' % tool
return
tokens[block + 1:block + 1] = ['"name"', '"%s"' % tool]
def set_mapping(tokens, mapping, app, tool):
block = find_block(tokens[mapping + 1:], [app])
if tool is None:
@@ -1368,16 +1408,40 @@ def set_mapping(tokens, mapping, app, tool):
del tokens[block - 1:block_end(tokens, block) + 1]
return
if block is None:
tokens[mapping + 1:mapping + 1] = [
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"' if app == "0" else '"250"', "}"]
tokens[mapping + 1:mapping + 1] = mapping_entry(app, tool)
return
block += mapping + 1
end = block_end(tokens, block)
for i in range(block + 1, end):
if tokens[i] == '"name"':
tokens[i + 1] = '"%s"' % tool
return
tokens[block + 1:block + 1] = ['"name"', '"%s"' % tool]
set_mapping_tool(tokens, block + mapping + 1, tool)
def set_mappings(tokens, mapping, changes):
"""Apply a batch with one traversal of the affected mapping entries."""
pending = {('"%s"' % app).lower(): (app, tool) for app, tool in changes.items()}
# Non-string or aliased keys retain the single writer's sequential semantics.
if len(changes) < 2 or len(pending) != len(changes) or any(not isinstance(app, str) for app in changes):
for app, tool in changes.items():
set_mapping(tokens, mapping, app, tool)
return
updated = []
i = mapping + 1
while pending and i < len(tokens) and tokens[i] != "}":
if i + 1 < len(tokens) and tokens[i + 1] == "{":
end = block_end(tokens, i + 1)
change = pending.pop(tokens[i].lower(), None)
if change is None:
updated.extend(tokens[i:end + 1])
elif change[1] is not None:
entry = tokens[i:end + 1]
set_mapping_tool(entry, 1, change[1])
updated.extend(entry)
i = end + 1
else:
updated.append(tokens[i])
i += 1
added = []
for app, tool in reversed(list(pending.values())):
if tool is not None:
added.extend(mapping_entry(app, tool))
tokens[mapping + 1:i] = added + updated
def steam_running():
@@ -1450,10 +1514,9 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
if settle and newest:
state["own_proton"] = True
if newest:
for app, name in list(current.items()):
if app != "0" and name in gone:
set_mapping(tokens, mapping, app, newest)
current[app] = newest
replacements = {app: newest for app, name in current.items() if app != "0" and name in gone}
set_mappings(tokens, mapping, replacements)
current.update(replacements)
if isinstance(state.get("auto"), dict):
state["auto"] = {app: newest if name in gone else name for app, name in state["auto"].items()}
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
@@ -1469,8 +1532,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices)
for app, tool in changes.items():
set_mapping(tokens, mapping, app, tool)
set_mappings(tokens, mapping, changes)
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config_path, text)
@@ -1562,16 +1624,16 @@ def x64_repoint(steam_root, tool, live=False):
keep = local_tools(steam_root)
moved = []
current = read_mapping(tokens, mapping)
if "0" not in current:
set_mapping(tokens, mapping, "0", tool)
changes = {} if "0" in current else {"0": tool}
for app, name in current.items():
named = name.lower()
legacy = named == "droiddeck-proton-arm64"
if (named.startswith("proton") or legacy) and named != tool.lower() \
and (legacy or named not in keep):
set_mapping(tokens, mapping, app, tool)
changes[app] = tool
if app != "0":
moved.append(app)
set_mappings(tokens, mapping, changes)
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config, text)
+192 -31
View File
@@ -4,13 +4,19 @@
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#define MAX_HANDLES 4096
#ifndef F_DUPFD_QUERY
#define F_DUPFD_QUERY 1027
#endif
#define PVR_HANDLE_BIT UINT32_C(0x80000000)
struct gem_close {
uint32_t handle;
@@ -22,11 +28,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;
@@ -34,13 +43,42 @@ static int is_kgsl(int fd) {
struct stat st;
pthread_mutex_lock(&lock);
if (kgsl_state == 0) {
kgsl_state = stat("/dev/kgsl-3d0", &st) == 0 ? 1 : -1;
kgsl_dev = st.st_rdev;
const char *standin = getenv("BL_DRM_STANDIN");
kgsl_state = stat("/dev/kgsl-3d0", &st) == 0 || (standin && *standin && stat(standin, &st) == 0) ? 1 : -1;
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) {
@@ -49,35 +87,124 @@ static void *real(const char *name) {
return fn;
}
static int same_by_flock(int a, int b) {
struct stat sa, sb;
if (fstat(a, &sa) || fstat(b, &sb) || sa.st_dev != sb.st_dev || sa.st_ino != sb.st_ino ||
flock(a, LOCK_EX | LOCK_NB)) {
return 0;
}
int same = flock(b, LOCK_EX | LOCK_NB) == 0;
flock(a, LOCK_UN);
return same;
}
static int same_file_description(int a, int b) {
if (a == b) {
return 1;
}
#ifdef SYS_kcmp
int saved_errno = errno;
long ret = syscall(SYS_kcmp, getpid(), getpid(), 0 , a, b);
errno = saved_errno;
return ret == 0;
#else
return 0;
int ret = -1;
#ifdef SYS_kcmp
static int kcmp_missing;
if (!kcmp_missing) {
long k = syscall(SYS_kcmp, getpid(), getpid(), 0, a, b);
if (k >= 0) {
ret = k == 0;
} else if (errno == ENOSYS || errno == EPERM) {
kcmp_missing = 1;
} else {
ret = 0;
}
}
#endif
if (ret < 0) {
const char *standin = getenv("BL_DRM_STANDIN");
ret = standin && *standin ? same_by_flock(a, b) : 0;
}
errno = saved_errno;
return ret;
}
/*
* Android kernels before 6.10 have no F_DUPFD_QUERY, while the app seccomp policy blocks kcmp.
* F_SETOWN_EX updates the open file description, so a duplicate observes a temporary owner marker
* and an independent open of the same render node does not. Restore the original owner before
* returning; no signal is armed because these DRM descriptors do not have O_ASYNC set.
*/
static int same_owner_description(int owned, int fd) {
struct f_owner_ex original_owned, original_fd, observed;
if (fcntl(owned, F_GETOWN_EX, &original_owned) < 0 ||
fcntl(fd, F_GETOWN_EX, &original_fd) < 0) {
return -1;
}
const struct f_owner_ex candidates[] = {
{.type = F_OWNER_TID, .pid = getpid()},
{.type = F_OWNER_PID, .pid = getpid()},
{.type = F_OWNER_PGRP, .pid = getpgrp()},
};
const struct f_owner_ex *marker = NULL;
for (size_t i = 0; i < sizeof(candidates) / sizeof(candidates[0]); i++) {
if (candidates[i].type != original_fd.type || candidates[i].pid != original_fd.pid) {
marker = &candidates[i];
break;
}
}
if (!marker || fcntl(owned, F_SETOWN_EX, marker) < 0) return -1;
int observed_result = fcntl(fd, F_GETOWN_EX, &observed);
int observed_errno = errno;
int restore_result = fcntl(owned, F_SETOWN_EX, &original_owned);
int restore_errno = errno;
if (restore_result < 0) {
errno = restore_errno;
return -1;
}
if (observed_result < 0) {
errno = observed_errno;
return -1;
}
return observed.type == marker->type && observed.pid == marker->pid;
}
static int same_owned_description(int owned, int fd) {
int saved_errno = errno;
int result = fcntl(owned, F_DUPFD_QUERY, fd);
if (result >= 0) {
errno = saved_errno;
return result == 1;
}
#ifdef SYS_kcmp
long compared = syscall(SYS_kcmp, getpid(), getpid(), 0 /* KCMP_FILE */, owned, fd);
if (compared >= 0) {
errno = saved_errno;
return compared == 0;
}
#endif
int owner_match = same_owner_description(owned, fd);
errno = saved_errno;
return owner_match == 1;
}
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;
}
}
return -1;
}
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;
@@ -97,25 +224,49 @@ 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;
/* The old-kernel owner probe mutates shared OFD state briefly; serialize it with lookups. */
pthread_mutex_lock(&lock);
int owner_matches = same_owned_description(owner, fd);
pthread_mutex_unlock(&lock);
if (!owner_matches) {
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;
@@ -124,24 +275,32 @@ 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;
}
static int release_handle(int fd, uint32_t handle) {
@@ -150,6 +309,7 @@ static int release_handle(int fd, uint32_t handle) {
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;
}
@@ -158,22 +318,23 @@ 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;
}
__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;
}
+100 -16
View File
@@ -1,28 +1,112 @@
#define _GNU_SOURCE
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#define KGSL_IOC_TYPE 0x09
#define KGSL_TIMESTAMP_RETIRED 0x00000002
#include "../../quest/kgsl_compat.h"
struct kgsl_device_waittimestamp_ctxtid {
unsigned int context_id;
unsigned int timestamp;
unsigned int timeout;
};
#define KGSL_CONTEXTS 1024
struct kgsl_cmdstream_readtimestamp_ctxtid {
unsigned int context_id;
unsigned int type;
unsigned int timestamp;
};
static struct {
uint32_t submitted;
uint32_t retired;
int owner;
} contexts[KGSL_CONTEXTS];
#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID \
_IOW(KGSL_IOC_TYPE, 0x7, struct kgsl_device_waittimestamp_ctxtid)
#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID \
_IOWR(KGSL_IOC_TYPE, 0x16, struct kgsl_cmdstream_readtimestamp_ctxtid)
static void report_denied(unsigned long request, int error) {
static unsigned reports;
int saved = errno;
if (__atomic_fetch_add(&reports, 1, __ATOMIC_RELAXED) < 8)
fprintf(stderr, "[QuestKGSL] ioctl 0x%lx refused, errno=%d\n", request & 0xff, error);
errno = saved;
}
static void note_submit(unsigned int context_id, unsigned int timestamp) {
uint32_t known;
if (context_id >= KGSL_CONTEXTS) return;
known = __atomic_load_n(&contexts[context_id].submitted, __ATOMIC_RELAXED);
while ((int32_t)(timestamp - known) > 0 &&
!__atomic_compare_exchange_n(&contexts[context_id].submitted, &known, timestamp, 1,
__ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
}
}
static int wait_retired(int (*real)(int, unsigned long, void *), int fd, uint32_t id, uint32_t timestamp) {
/* KGSL reads a timeout of 0 as wait forever. */
struct kgsl_device_waittimestamp_ctxtid wait = {.context_id = id, .timestamp = timestamp, .timeout = 1};
if (real(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait) == 0) return 0;
return errno == ETIMEDOUT || errno == ETIME || errno == EINTR || errno == EAGAIN ? 1 : -1;
}
/* shortcut: an unfinished timestamp sleeps a jiffy per poll, read the memstore instead if Quest's mmap of it is proven */
static int read_retired(int (*real)(int, unsigned long, void *), int fd,
struct kgsl_cmdstream_readtimestamp_ctxtid *read) {
uint32_t id = read->context_id;
uint32_t timestamp, submitted;
int result;
if (read->type != KGSL_TIMESTAMP_RETIRED || id >= KGSL_CONTEXTS ||
__atomic_load_n(&contexts[id].owner, __ATOMIC_RELAXED) != fd + 1)
return -1;
timestamp = __atomic_load_n(&contexts[id].retired, __ATOMIC_RELAXED);
submitted = __atomic_load_n(&contexts[id].submitted, __ATOMIC_RELAXED);
/* KGSL checks a context's owner on every wait, which catches one that died with a reused descriptor. */
if (timestamp == submitted && wait_retired(real, fd, id, timestamp) < 0) return -1;
while (timestamp != submitted) {
result = wait_retired(real, fd, id, timestamp + 1);
if (result < 0) return -1;
if (result > 0) break;
timestamp++;
__atomic_store_n(&contexts[id].retired, timestamp, __ATOMIC_RELAXED);
}
read->timestamp = timestamp;
return 0;
}
/* Quest refuses some KGSL ioctls, and Mesa 27 turns a failed timestamp read into VK_ERROR_UNKNOWN. */
__attribute__((visibility("hidden"))) void bl_kgsl_track(int (*real)(int, unsigned long, void *),
int fd, unsigned long request, void *arg,
int *rc) {
int saved = errno;
if (arg == NULL) return;
if (*rc == 0) {
if (request == IOCTL_KGSL_GPU_COMMAND) {
const struct kgsl_gpu_command *submit = arg;
note_submit(submit->context_id, submit->timestamp);
} else if (request == IOCTL_KGSL_GPU_AUX_COMMAND) {
const struct kgsl_gpu_aux_command *submit = arg;
note_submit(submit->context_id, submit->timestamp);
} else if (request == IOCTL_KGSL_DRAWCTXT_CREATE) {
const struct kgsl_drawctxt_create *create = arg;
if (create->drawctxt_id < KGSL_CONTEXTS) {
__atomic_store_n(&contexts[create->drawctxt_id].submitted, 0, __ATOMIC_RELAXED);
__atomic_store_n(&contexts[create->drawctxt_id].retired, 0, __ATOMIC_RELAXED);
/* User timestamps can leave gaps that would take one wait per integer, so their reads stay failed. */
__atomic_store_n(&contexts[create->drawctxt_id].owner,
create->flags & KGSL_CONTEXT_USER_GENERATED_TS ? 0 : fd + 1, __ATOMIC_RELAXED);
}
} else if (request == IOCTL_KGSL_DRAWCTXT_DESTROY) {
const struct kgsl_drawctxt_destroy *destroy = arg;
if (destroy->drawctxt_id < KGSL_CONTEXTS)
__atomic_store_n(&contexts[destroy->drawctxt_id].owner, 0, __ATOMIC_RELAXED);
}
return;
}
if (_IOC_TYPE(request) == KGSL_IOC_TYPE && (saved == EACCES || saved == EPERM ||
request == IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID))
report_denied(request, saved);
if (request != IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID || saved == EBADF) return;
if (read_retired(real, fd, arg) == 0)
*rc = 0;
else if (errno != saved)
report_denied(IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, errno);
}
static int enabled(void) {
static int cached = -1;
+7
View File
@@ -54,6 +54,9 @@ static int is_lock_query(int cmd) {
}
}
int bl_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden")));
void bl_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden")));
int fcntl(int fd, int cmd, ...) {
static int (*real_fcntl)(int, int, ...);
va_list ap;
@@ -69,7 +72,11 @@ int fcntl(int fd, int cmd, ...) {
errno = ENOSYS;
return -1;
}
void *nl_state = NULL;
int duplicate = cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC;
if (duplicate && bl_nl_before_dup(fd, &nl_state) != 0) return -1;
result = real_fcntl(fd, cmd, arg);
if (duplicate) bl_nl_after_dup(nl_state, result);
if (result >= 0 || !unsupported(errno)) return result;
if (is_lock_command(cmd)) return 0;
if (is_lock_query(cmd) && arg != NULL) {
+8
View File
@@ -111,10 +111,16 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
static unsigned guarded_port(void);
__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd);
__attribute__((visibility("hidden"))) int bl_nl_bind(int fd, const struct sockaddr *addr,
socklen_t len, int *rc);
__attribute__((visibility("hidden"))) int bl_nl_connect(int fd, const struct sockaddr *addr,
socklen_t len, int *rc);
int bind(int fd, const struct sockaddr *addr, socklen_t len) {
static bind_fn real;
int nl_rc;
if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind");
if (bl_nl_bind(fd, addr, len, &nl_rc)) return nl_rc;
if (bl_udevmon_stand_in(fd)) {
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) {
errno = EINVAL;
@@ -223,6 +229,8 @@ static int guest_peer(int fd) {
int connect(int fd, const struct sockaddr *addr, socklen_t len) {
static connect_fn real;
int nl_rc;
if (bl_nl_connect(fd, addr, len, &nl_rc)) return nl_rc;
if (!real) real = (connect_fn)dlsym(RTLD_NEXT, "connect");
bind_before_loopback_connect(fd, addr, len);
unsigned peer = loopback_family(addr, len) ? addr_port(addr, len) : 0;
File diff suppressed because it is too large. Load diff
+31 -6
View File
@@ -1442,16 +1442,25 @@ static void ns_received(struct msghdr *msg) {
int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int),
ssize_t *result) __attribute__((visibility("hidden")));
int bl_nl_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int),
ssize_t *result) __attribute__((visibility("hidden")));
void bl_nl_received(struct msghdr *msg) __attribute__((visibility("hidden")));
void bl_nl_closed(int fd) __attribute__((visibility("hidden")));
void bl_nl_range_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
int bl_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden")));
void bl_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden")));
ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
static ssize_t (*real)(int, struct msghdr *, int);
if (!real) real = (ssize_t (*)(int, struct msghdr *, int))dlsym(RTLD_NEXT, "recvmsg");
ssize_t answered;
if (msg && bl_nl_recvmsg(fd, msg, flags, real, &answered)) return answered;
if (msg && bl_udevmon_recvmsg(fd, msg, flags, real, &answered)) return answered;
ssize_t r = real(fd, msg, flags);
if (r >= 0 && msg && msg->msg_control && msg->msg_controllen && ns_on()) {
if (r >= 0 && msg && msg->msg_control && msg->msg_controllen) {
int saved = errno;
ns_received(msg);
bl_nl_received(msg);
if (ns_on()) ns_received(msg);
errno = saved;
}
return r;
@@ -1465,6 +1474,7 @@ int close(int fd) {
if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd);
bl_venc_closed(fd);
bl_vdec_closed(fd);
bl_nl_closed(fd);
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd);
int saved = errno;
@@ -1480,19 +1490,29 @@ int close(int fd) {
int dup2(int oldfd, int newfd) {
static int (*real)(int, int);
if (!real) real = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
if (oldfd == newfd) return real(oldfd, newfd);
void *nl_state;
if (bl_nl_before_dup(oldfd, &nl_state) != 0) return -1;
if (oldfd != newfd && newfd >= 0) bl_fsync_fds_closed((unsigned int)newfd, (unsigned int)newfd);
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
if (t && oldfd != newfd && newfd >= 0 && newfd < NS_FDS && __atomic_load_n(&t[newfd], __ATOMIC_ACQUIRE)) ns_forget(newfd);
return real(oldfd, newfd);
int result = real(oldfd, newfd);
bl_nl_after_dup(nl_state, result);
return result;
}
int dup3(int oldfd, int newfd, int flags) {
static int (*real)(int, int, int);
if (!real) real = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
if (oldfd == newfd) return real(oldfd, newfd, flags);
void *nl_state;
if (bl_nl_before_dup(oldfd, &nl_state) != 0) return -1;
if (oldfd != newfd && newfd >= 0) bl_fsync_fds_closed((unsigned int)newfd, (unsigned int)newfd);
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
if (t && oldfd != newfd && newfd >= 0 && newfd < NS_FDS && __atomic_load_n(&t[newfd], __ATOMIC_ACQUIRE)) ns_forget(newfd);
return real(oldfd, newfd, flags);
int result = real(oldfd, newfd, flags);
bl_nl_after_dup(nl_state, result);
return result;
}
static void ns_forget_range(unsigned int first, unsigned int last) {
@@ -1513,7 +1533,9 @@ int close_range(unsigned int first, unsigned int last, int flags) {
errno = ENOSYS;
return -1;
}
return real(first, last, flags);
int result = real(first, last, flags);
if (result == 0 && !(flags & CLOSE_RANGE_CLOEXEC)) bl_nl_range_closed(first, last);
return result;
}
void closefrom(int lowfd) {
@@ -1523,7 +1545,10 @@ void closefrom(int lowfd) {
bl_fsync_fds_closed((unsigned int)lowfd, ~0u);
ns_forget_range((unsigned int)lowfd, ~0u);
}
if (real) real(lowfd);
if (real) {
real(lowfd);
if (lowfd >= 0) bl_nl_range_closed((unsigned int)lowfd, ~0u);
}
}
static void ns_fork_prepare(void) {
+47
View File
@@ -0,0 +1,47 @@
/*
* Based on jdmg28's DroidDeck-Mali fork (commit 6be00e00, GPL-3.0): steam-launch-wrapper runs every
* game with --oom-score-adjust 900. Android's lmkd reads 900 as CACHED_APP_MIN_ADJ and kills the
* foreground game first when memory runs short; on Linux 6.1 the raise also becomes the process's
* permanent minimum. An app's processes cannot go below the score they inherit, so the only writes
* that succeed from in here are raises: every write-open of an oom_score_adj file goes to /dev/null.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <string.h>
#include <unistd.h>
static int is_oom_score_adj(const char *path) {
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return 0;
const char *p = path + 6;
if (strncmp(p, "self/", 5) == 0) {
p += 5;
} else if (strncmp(p, "thread-self/", 12) == 0) {
p += 12;
} else {
const char *digits = p;
while (*p >= '0' && *p <= '9') p++;
if (p == digits || *p != '/') return 0;
p++;
if (strncmp(p, "task/", 5) == 0) {
p += 5;
digits = p;
while (*p >= '0' && *p <= '9') p++;
if (p == digits || *p != '/') return 0;
p++;
}
}
return strcmp(p, "oom_score_adj") == 0 || strcmp(p, "oom_adj") == 0;
}
__attribute__((visibility("hidden"))) const char *bl_oom_adj_redirect(const char *path, int writing) {
static int logged;
if (!writing || !is_oom_score_adj(path)) return path;
if (!__atomic_exchange_n(&logged, 1, __ATOMIC_RELAXED)) {
static const char msg[] = "droiddeck: an oom_score_adj raise was dropped (Android would treat this program as a cached app)\n";
int saved = errno;
ssize_t ignored = write(STDERR_FILENO, msg, sizeof(msg) - 1);
(void)ignored;
errno = saved;
}
return "/dev/null";
}
+3
View File
@@ -14,6 +14,7 @@
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
const char *bl_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_vdec_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
@@ -53,6 +54,7 @@ int open(const char *path, int flags, ...) {
errno = EACCES;
return -1;
}
path = bl_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY);
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
@@ -80,6 +82,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
errno = EACCES;
return -1;
}
path = bl_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY);
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
+32 -2
View File
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
@@ -8,6 +9,8 @@
#define FUSE_MAGIC 0x65735546
#define SDCARDFS_MAGIC 0x5dca2df5
#define FAT_MAGIC 0x4d44
#define EXFAT_MAGIC 0x2011bab0
static int is_wineserver(void) {
static int cached = -1;
@@ -27,15 +30,42 @@ static int is_wineserver(void) {
return cached;
}
static int has_no_unix_owner(int fd) {
struct statfs fs;
if (fstatfs(fd, &fs) != 0) return 0;
return fs.f_type == FUSE_MAGIC || fs.f_type == SDCARDFS_MAGIC || fs.f_type == FAT_MAGIC ||
(unsigned int)fs.f_type == EXFAT_MAGIC;
}
__attribute__((visibility("hidden")))
void bl_storage_owner(int fd, struct stat *st) {
struct statfs fs;
int saved = errno;
uid_t uid;
if (st != NULL && is_wineserver()) {
uid = getuid();
if (st->st_uid != uid && fstatfs(fd, &fs) == 0 && (fs.f_type == FUSE_MAGIC || fs.f_type == SDCARDFS_MAGIC)) st->st_uid = uid;
if (st->st_uid != uid && has_no_unix_owner(fd)) st->st_uid = uid;
}
errno = saved;
}
int fchmod(int fd, mode_t mode) {
static int (*next_fchmod)(int, mode_t);
int saved = errno, result;
if (next_fchmod == NULL) next_fchmod = dlsym(RTLD_NEXT, "fchmod");
if (next_fchmod == NULL) {
errno = ENOSYS;
return -1;
}
result = next_fchmod(fd, mode);
if (result != 0 && errno == EPERM && is_wineserver()) {
if (has_no_unix_owner(fd)) {
errno = saved;
return 0;
}
errno = EPERM;
}
return result;
}
+24
View File
@@ -0,0 +1,24 @@
/* tools/linuxfs/preload/subreaper.c
*
* Mark every process that loads libblsession.so as a child subreaper.
*
* wlroots starts Xwayland with a double fork: gamescope -> middle process
* (exits immediately) -> Xwayland. With no subreaper in the tree, Xwayland
* is reparented to pid 1 and becomes an orphan. On some vendor kernels
* (observed on Meizu / Flyme 12) an orphan reaper SIGKILLs it in that window,
* which makes gamescope wait forever in wlserver_init() and the UI hangs on
* "Starting display and audio".
*
* With PR_SET_CHILD_SUBREAPER the reparent target becomes the nearest marked
* ancestor instead of init, so the orphan event never happens.
*
* Harmless for processes that do not fork, and cheap (one syscall at load).
*/
#define _GNU_SOURCE
#include <sys/prctl.h>
__attribute__((constructor))
static void bl_session_set_subreaper(void)
{
(void)prctl(PR_SET_CHILD_SUBREAPER, 1);
}
+47 -3
View File
@@ -102,6 +102,21 @@ static int make_stand_in(int type) {
return -1;
}
__attribute__((visibility("hidden"))) int bl_nl_socket(int type, int *fd);
__attribute__((visibility("hidden"))) int bl_nl_owns(int fd);
__attribute__((visibility("hidden"))) int bl_nl_getsockname(int fd, struct sockaddr *addr,
socklen_t *len, int *rc);
__attribute__((visibility("hidden"))) int bl_nl_getpeername(int fd, struct sockaddr *addr,
socklen_t *len, int *rc);
__attribute__((visibility("hidden"))) int bl_nl_setsockopt(int fd, int level, int option,
const void *value, socklen_t len,
int (*real)(int, int, int, const void *, socklen_t),
int *rc);
__attribute__((visibility("hidden"))) int bl_nl_getsockopt(int fd, int level, int option,
void *value, socklen_t *len,
int (*real)(int, int, int, void *, socklen_t *),
int *rc);
int socket(int domain, int type, int protocol) {
static int (*real_socket)(int, int, int);
int fd;
@@ -111,6 +126,11 @@ int socket(int domain, int type, int protocol) {
errno = ENOSYS;
return -1;
}
if (domain == AF_NETLINK && protocol == NETLINK_ROUTE) {
int route_fd;
bl_nl_socket(type, &route_fd);
return route_fd;
}
fd = real_socket(domain, type, protocol);
if (fd >= 0 || domain != AF_NETLINK || protocol != NETLINK_KOBJECT_UEVENT)
return fd;
@@ -129,7 +149,9 @@ __attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd) {
int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
struct sockaddr_nl nl;
int route_rc;
if (bl_nl_getsockname(fd, addr, len, &route_rc)) return route_rc;
if (is_stand_in(fd)) {
if (addr == NULL || len == NULL) {
errno = EFAULT;
@@ -150,21 +172,43 @@ int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
return real_getsockname(fd, addr, len);
}
int getpeername(int fd, struct sockaddr *addr, socklen_t *len) {
static int (*real)(int, struct sockaddr *, socklen_t *);
int route_rc;
if (bl_nl_getpeername(fd, addr, len, &route_rc)) return route_rc;
if (real == NULL) real = dlsym(RTLD_NEXT, "getpeername");
return real(fd, addr, len);
}
int setsockopt(int fd, int level, int optname, const void *optval, socklen_t optlen) {
static int (*real_setsockopt)(int, int, int, const void *, socklen_t);
int route_rc;
if (real_setsockopt == NULL) real_setsockopt = dlsym(RTLD_NEXT, "setsockopt");
if (real_setsockopt == NULL) {
errno = ENOSYS;
return -1;
}
if (bl_nl_setsockopt(fd, level, optname, optval, optlen, real_setsockopt, &route_rc)) return route_rc;
if (is_stand_in(fd)) {
if (level == SOL_NETLINK)
return 0;
if (level == SOL_SOCKET && (optname == SO_ATTACH_FILTER || optname == SO_DETACH_FILTER))
return 0;
}
if (real_setsockopt == NULL) real_setsockopt = dlsym(RTLD_NEXT, "setsockopt");
if (real_setsockopt == NULL) {
return real_setsockopt(fd, level, optname, optval, optlen);
}
int getsockopt(int fd, int level, int option, void *value, socklen_t *len) {
static int (*real)(int, int, int, void *, socklen_t *);
int route_rc;
if (real == NULL) real = dlsym(RTLD_NEXT, "getsockopt");
if (real == NULL) {
errno = ENOSYS;
return -1;
}
return real_setsockopt(fd, level, optname, optval, optlen);
if (bl_nl_getsockopt(fd, level, option, value, len, real, &route_rc)) return route_rc;
return real(fd, level, option, value, len);
}
struct monitor_netlink_header {
+18
View File
@@ -0,0 +1,18 @@
/*
* Zink keeps kopper when the session draws through Venus.
*
* On Mali the session reaches the GPU through Venus over vtest, and Xwayland has no DRM node to
* build glamor on, so it offers no DRI3. Without DRI3, Zink can only present through kopper (its
* Vulkan WSI path). Steam's steamwebhelper.sh exports LIBGL_KOPPER_DISABLE=true for the client
* interface unconditionally, so on Mali every GL context the interface asked for failed and the
* webhelper restarted until Steam gave up on GPU acceleration. Steam restores that script when
* it verifies its install, so the variable is dropped here instead, before Mesa reads it.
*/
#define _GNU_SOURCE 1
#include <stdlib.h>
#include <string.h>
__attribute__((constructor)) static void bl_venus_keep_kopper(void) {
const char *debug = getenv("VN_DEBUG");
if (debug && strstr(debug, "vtest")) unsetenv("LIBGL_KOPPER_DISABLE");
}
@@ -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"
}
}
@@ -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)
+43
View File
@@ -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"))
+493
View File
@@ -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 <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <dlfcn.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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, &copy, &patched.pNext);
if (copied != VK_SUCCESS) return copied;
}
VkResult result = next_create(physical, &patched, allocator, device);
free_chain_copy(&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;
}
Loaded 100 of 517 files, more files were not shown because too many files have changed in this diff. Show more