chore: merge main to resolve conflicts with the API 36 target

This commit is contained in:
xXJsonDeruloXx committed 2026-10-18 16:09:55 -04:00
commit 4a93663d14
793 files changed
+103885 -10000

No files matched your search

+3 -3
View File
@@ -29,9 +29,9 @@ def _device_list(adb: str) -> list[str]:
raise DeviceResolutionError(result.stderr.strip() or "adb devices failed")
devices = []
for line in result.stdout.splitlines()[1:]:
fields = line.split()
if len(fields) >= 2 and fields[1] == "device":
devices.append(fields[0])
match = re.match(r"^(.+?)\s+device(?:\s+\S+:\S+)*\s*$", line)
if match:
devices.append(match.group(1))
return devices
+69
View File
@@ -0,0 +1,69 @@
"""Build the pinned lite-palm/lite-landmark MediaPipe bundle (mediapipe==0.10.21)."""
import argparse
import hashlib
import io
from pathlib import Path
import zipfile
FULL_SHA = 'fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1'
LITE_SHA = 'd7fde8ac11f8ce03f8663775bfc323f4fc9f2a38062b4f4efa142874ef5b2a48'
PALM_SHA = 'e9a4aaddf90dda56a87235303cf00e4c2d3fb28725f68fd88772997dac905c18'
def write_entry(archive, name, data):
entry = zipfile.ZipInfo(name, (1980, 1, 1, 0, 0, 0))
entry.create_system = 3
entry.external_attr = 0o100644 << 16
archive.writestr(entry, data)
def canonicalize_associated_files(data):
with zipfile.ZipFile(io.BytesIO(data)) as archive:
entries = archive.infolist()
if not entries:
return data
prefix = data[:min(entry.header_offset for entry in entries)]
files = {entry.filename: archive.read(entry) for entry in entries}
output = io.BytesIO(prefix)
with zipfile.ZipFile(output, 'a', compression=zipfile.ZIP_STORED) as archive:
for name in sorted(files):
write_entry(archive, name, files[name])
return output.getvalue()
def build(full, lite, palm, output):
import mediapipe
from mediapipe.tasks.python.metadata import metadata
from mediapipe.tasks.metadata import schema_py_generated as schema
if mediapipe.__version__ != '0.10.21':
raise ValueError('Use mediapipe==0.10.21 for reproducible metadata')
for path, expected in [(full, FULL_SHA), (lite, LITE_SHA), (palm, PALM_SHA)]:
if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
raise ValueError(f'Model source checksum mismatch: {path}')
with zipfile.ZipFile(full) as task:
references = {name: task.read(name) for name in ['hand_detector.tflite', 'hand_landmarks_detector.tflite']}
def contract(data):
graph = schema.Model.GetRootAsModel(data, 0).Subgraphs(0)
return [[(graph.Tensors(int(i)).Name(), graph.Tensors(int(i)).ShapeAsNumpy().tolist(), graph.Tensors(int(i)).Type())
for i in indices] for indices in (graph.InputsAsNumpy(), graph.OutputsAsNumpy())]
models = {}
for name, path in [('hand_detector.tflite', palm), ('hand_landmarks_detector.tflite', lite)]:
data = path.read_bytes()
reference = references[name]
if contract(data) != contract(reference):
raise ValueError(f'Lite tensor contract differs: {name}')
populator = metadata.MetadataPopulator.with_model_buffer(data)
populator.load_metadata_and_associated_files(reference)
populator.populate()
models[name] = canonicalize_associated_files(populator.get_model_buffer())
output.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_STORED) as task:
for name, data in models.items():
write_entry(task, name, data)
print(hashlib.sha256(output.read_bytes()).hexdigest())
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--full', type=Path, default=Path('app/src/main/assets/models/hand_landmarker.task'))
parser.add_argument('--lite', type=Path, required=True, help='Pinned hand_landmark_lite.tflite from storage.googleapis.com/mediapipe-assets/')
parser.add_argument('--palm', type=Path, required=True, help='Pinned palm_detection_lite.tflite from storage.googleapis.com/mediapipe-assets/')
parser.add_argument('--output', type=Path, default=Path('app/src/main/assets/models/hand_landmarker_lite.task'))
args = parser.parse_args()
build(args.full, args.lite, args.palm, args.output)
+62 -14
View File
@@ -72,7 +72,33 @@ trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
cache_dir=${DROIDDECK_BUILD_CACHE:-"${HOME}/.cache/droiddeck-build"}
mkdir -p "${cache_dir}"
# Steps whose output depends only on tracked sources are kept per input hash in the
# shared cache, so a rerun or a fresh worktree copies them instead of rebuilding.
inputs_hash() {
(cd "${repo_root}" && { printf '%s\n' "$1"; shift; find "$@" -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256; }) \
| shasum -a 256 | cut -d' ' -f1
}
restore_step() {
local stored="${cache_dir}/steps/$1/$2"
[[ -f "${stored}/.complete" ]] || return 1
mkdir -p "$3"
(cd "${stored}" && tar -cf - --exclude .complete .) | tar -xf - -C "$3" || return 1
echo "$1: inputs unchanged, reused ${stored}"
}
save_step() {
local stored="${cache_dir}/steps/$1/$2" part
mkdir -p "${cache_dir}/steps/$1"
part=$(mktemp -d "${stored}.part.XXXXXX")
(cd "$3" && tar -cf - .) | tar -xf - -C "${part}"
touch "${part}/.complete"
# Another checkout may have published the same key meanwhile; its copy is equivalent.
if [[ -e "${stored}" ]]; then rm -rf "${part}"; else mv "${part}" "${stored}" || rm -rf "${part}"; fi
}
python3 "${repo_root}/tools/docker_preflight.py" "${image_name}"
image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
@@ -118,17 +144,30 @@ docker run --rm --platform linux/amd64 \
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
'
docker run --rm --platform linux/amd64 \
-v "${repo_root}:/src" -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
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
app/src/main/cpp/fakeinput_steam.cpp)
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 '
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
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
mkdir -p "${x86_stage}"
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
save_step x86-preloads "${x86_key}" "${x86_stage}"
fi
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${linuxfs_dir}/usr/local/lib/droiddeck-vr"
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
if ! restore_step vr "${vr_key}" "${vr_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
save_step vr "${vr_key}" "${vr_out}"
fi
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
if [[ -z "${github_repo}" ]]; then
@@ -146,8 +185,6 @@ if [[ -z "${github_repo}" ]]; then
github_repo=${github_repo%.git}
fi
cache_dir=${DROIDDECK_BUILD_CACHE:-"${HOME}/.cache/droiddeck-build"}
mkdir -p "${cache_dir}"
cached() {
local sha=$1 name=$2 out
shift 2
@@ -268,7 +305,12 @@ if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
else
"${repo_root}/tools/proot/build.sh" "${proot_out}"
proot_stage="${staging_dir}/proot"
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
save_step proot "${proot_inputs}" "${proot_stage}"
fi
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
fi
@@ -301,6 +343,7 @@ else
fi
done
rustup target add --toolchain stable aarch64-linux-android
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-${cache_dir}/stores-target}"
if ! command -v cargo-ndk >/dev/null 2>&1; then
cargo install cargo-ndk --locked
fi
@@ -308,7 +351,12 @@ fi
cd "${repo_root}"
python3 tools/quest/build-driver.py "${NDK}"
bash tools/comet/build-local.sh
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
comet_key=$(inputs_hash "${image_id}" tools/comet)
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/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
+179
View File
@@ -0,0 +1,179 @@
"""Build checksum-pinned Android RGB UVC libraries and their fault-injection test."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import tarfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
RECIPES = ROOT / 'tools/uvc'
PACKAGES = (
{'name': 'libusb', 'version': '1.0.30', 'license': 'LGPL-2.1-or-later',
'url': 'https://github.com/libusb/libusb/releases/download/v1.0.30/libusb-1.0.30.tar.bz2',
'archive': 'libusb-1.0.30.tar.bz2',
'sha256': 'fea36f34f9156400209595e300840767ab1a385ede1dc7ee893015aea9c6dbaf'},
{'name': 'libuvc', 'version': '0.0.8', 'license': 'BSD-3-Clause',
'url': 'https://github.com/libuvc/libuvc/archive/refs/tags/v0.0.8.zip',
'archive': 'libuvc-0.0.8.zip',
'sha256': '67922938ad81eb82b8ce14576f15a68ac75e30af738728a1f3070b6bbc938bce'},
)
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def download(package, cache):
archive = cache / package['archive']
if not archive.exists():
request = urllib.request.Request(package['url'], headers={'User-Agent': 'DroidDeckXR-UVC-Build'})
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read()
if hashlib.sha256(payload).hexdigest() != package['sha256']:
raise ValueError(f"Downloaded checksum mismatch: {package['archive']}")
archive.write_bytes(payload)
if sha256(archive) != package['sha256']:
raise ValueError(f'Cached checksum mismatch: {archive}')
return archive
def extract(archive, destination):
if archive.suffix == '.zip':
with zipfile.ZipFile(archive) as bundle:
for item in bundle.infolist():
(destination / item.filename).resolve().relative_to(destination.resolve())
if (item.external_attr >> 16) & 0o170000 == 0o120000:
raise ValueError('Symlink in ZIP archive')
bundle.extractall(destination)
else:
with tarfile.open(archive) as bundle:
bundle.extractall(destination, filter='data')
def patch_source(source, patch):
old, new = [], []
content = source.read_text(encoding='utf-8')
hunks = []
for line in patch.read_text(encoding='utf-8').splitlines(keepends=True):
if line.startswith(('--- ', '+++ ')):
continue
if line.startswith('@@ '):
if old or new:
hunks.append((''.join(old), ''.join(new)))
old, new = [], []
elif line.startswith(' '):
old.append(line[1:])
new.append(line[1:])
elif line.startswith('-'):
old.append(line[1:])
elif line.startswith('+'):
new.append(line[1:])
else:
raise ValueError(f'Unsupported patch line: {line!r}')
hunks.append((''.join(old), ''.join(new)))
for before, after in hunks:
if not before or content.count(before) != 1:
raise ValueError(f'Patch context mismatch: {source}')
content = content.replace(before, after, 1)
source.write_text(content, encoding='utf-8', newline='\n')
def run(command, log):
result = subprocess.run([str(part) for part in command], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, encoding='utf-8')
log.write_text(result.stdout, encoding='utf-8')
print(result.stdout, end='')
result.check_returncode()
def build(args):
output, cache = args.output.resolve(), args.cache.resolve()
source, binary, dist = output / 'src', output / 'android-arm64', output / 'dist'
for folder in (output, cache, source):
folder.mkdir(parents=True, exist_ok=True)
for package in PACKAGES:
extract(download(package, cache), source)
patch = RECIPES / 'libuvc-submit-failure.patch'
stream = source / 'libuvc-0.0.8/src/stream.c'
patch_source(stream, patch)
ndk, cmake = args.ndk.resolve(), args.cmake.resolve()
ninja = args.ninja.resolve() if args.ninja else cmake.parent / ('ninja.exe' if os.name == 'nt' else 'ninja')
configure = [cmake, '-S', RECIPES, '-B', binary, '-G', 'Ninja',
f'-DCMAKE_MAKE_PROGRAM={ninja.as_posix()}',
f'-DCMAKE_TOOLCHAIN_FILE={(ndk / "build/cmake/android.toolchain.cmake").as_posix()}',
f'-DRGB_UVC_SOURCE_ROOT={source.as_posix()}', '-DANDROID_ABI=arm64-v8a',
'-DANDROID_PLATFORM=android-26', '-DANDROID_STL=c++_static',
'-DCMAKE_BUILD_TYPE=RelWithDebInfo']
compile_command = [cmake, '--build', binary, '--parallel', str(args.jobs)]
run(configure, output / 'configure.log')
run(compile_command, output / 'build.log')
copies = {
binary / 'libusb.so': dist / 'arm64-v8a/libusb.so',
binary / 'libuvc.a': dist / 'arm64-v8a/libuvc.a',
binary / 'uvc_submit_failure_test': dist / 'arm64-v8a/uvc_submit_failure_test',
source / 'libusb-1.0.30/libusb/libusb.h': dist / 'include/libusb.h',
source / 'libuvc-0.0.8/include/libuvc/libuvc.h': dist / 'include/libuvc/libuvc.h',
binary / 'generated/libuvc/libuvc_config.h': dist / 'include/libuvc/libuvc_config.h',
source / 'libusb-1.0.30/COPYING': dist / 'licenses/libusb-COPYING',
source / 'libuvc-0.0.8/LICENSE.txt': dist / 'licenses/libuvc-LICENSE.txt',
}
for original, target in copies.items():
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(original, target)
prebuilt = list((ndk / 'toolchains/llvm/prebuilt').iterdir())
if len(prebuilt) != 1:
raise ValueError(f'Expected one NDK host toolchain: {prebuilt}')
readelf = prebuilt[0] / 'bin' / ('llvm-readelf.exe' if os.name == 'nt' else 'llvm-readelf')
reports = []
for name in ('libusb.so', 'uvc_submit_failure_test'):
result = subprocess.check_output([str(readelf), '-h', '-l', '-d', str(binary / name)],
text=True, encoding='utf-8')
if 'AArch64' not in result or 'TEXTREL' in result:
raise ValueError(f'Unexpected ELF ABI or text relocations: {name}')
loads = [line for line in result.splitlines() if line.lstrip().startswith('LOAD')]
if not loads or any(not line.rstrip().endswith('0x4000') for line in loads):
raise ValueError(f'ELF must use 16 KiB LOAD alignment: {name}')
if name == 'uvc_submit_failure_test' and ('[libusb.so]' not in result or 'libglasses' in result):
raise ValueError('Fault test must depend on standalone libusb')
reports.append(result)
(output / 'elf-validation.txt').write_text('\n'.join(reports), encoding='utf-8')
manifest = {
'packages': PACKAGES,
'patch': {'path': str(patch.relative_to(ROOT)), 'sha256': sha256(patch),
'sourceSha256': sha256(stream),
'reason': 'Preserve USB submission errors; remove unsubmitted transfers under cb_mutex, then cancel/drain submitted transfers and join the callback thread.'},
'build': {'ndk': str(ndk), 'ndkSourceProperties': (ndk / 'source.properties').read_text(encoding='utf-8'),
'configure': [str(part) for part in configure], 'compile': [str(part) for part in compile_command],
'api': 26, 'abi': 'arm64-v8a', 'pic': True, 'queueBuffers': 8,
'isoPacketsPerTransferMaximum': 32, 'jpegConversion': False,
'libusbShared': True, 'libuvcStatic': True,
'recipeHashes': {str(path.relative_to(ROOT)): sha256(path) for path in
(Path(__file__), RECIPES / 'CMakeLists.txt', RECIPES / 'submit_failure_test.cpp')}},
'validation': {'nativeBuild': 'passed', 'linkNoUndefined': 'passed', 'machine': 'AArch64',
'loadAlignmentBytes': 16384, 'textRelocations': False,
'deviceRuntimeTest': 'not run by build script'},
'artifacts': [{'path': str(path.relative_to(output)), 'sha256': sha256(path), 'size': path.stat().st_size}
for path in copies.values()],
}
(output / 'provenance.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
print(f'Libraries and headers: {dist}')
print(f'Provenance: {output / "provenance.json"}')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ndk', type=Path, required=True)
parser.add_argument('--cmake', type=Path, required=True)
parser.add_argument('--ninja', type=Path)
parser.add_argument('--output', type=Path, default=ROOT / 'build/rgb-uvc')
parser.add_argument('--cache', type=Path, default=ROOT / 'build/uvc-source-cache')
parser.add_argument('--jobs', type=int, default=4)
build(parser.parse_args())
+70
View File
@@ -1,6 +1,7 @@
#include "cardboard.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
static int failures;
#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); failures++; } } while (0)
@@ -35,9 +36,78 @@ int main(void) {
q.source = CARDBOARD_SOURCE_SBS;
cardboard_push_constants(&q, pose, 3840, 1080, 2400, 1080, pc);
CHECK(near(pc[17], 1920.0f / 1080.0f) && near(pc[18], 1.0f));
q.mono = 1;
cardboard_push_constants(&q, pose, 3840, 1080, 1920, 1080, pc);
CHECK(near(pc[3], 0.0f) && near(pc[19], 1920.0f / 1080.0f) && near(pc[20], 1.0f));
q.mono = 0;
cardboard_push_constants(&q, pose, 3840, 1080, 1920, 1080, pc);
CHECK(near(pc[3], 0.032f) && near(pc[19], 960.0f / 1080.0f) && near(pc[20], 0.0f));
cardboard_push_constants(&q, pose, 0, 0, 0, 0, pc);
CHECK(isfinite(pc[17]) && isfinite(pc[19]));
// Narrow optical profiles and the lower SteamVR slider values must reach
// the projection unchanged, rather than all becoming a 30-degree view.
const float glasses_fovs[] = {22.0f, 23.3f, 24.0f, 25.8f, 29.0f};
for (unsigned i = 0; i < sizeof(glasses_fovs) / sizeof(glasses_fovs[0]); i++) {
q.fov_deg = glasses_fovs[i];
cardboard_clamp(&q);
CHECK(near(q.fov_deg, glasses_fovs[i]));
cardboard_push_constants(&q, pose, 3840, 1080, 3840, 1080, pc);
CHECK(near(pc[14], tanf(glasses_fovs[i] * 0.5f * (float)M_PI / 180.0f)));
}
const struct cardboard_params screen = {
.enabled = 1, .source = CARDBOARD_SOURCE_SCREEN, .ipd_m = 0.064f,
.screen_dist_m = 3.0f, .screen_width_m = 2.0f, .fov_deg = 25.8f,
};
const int source_sizes[][2] = {{1280, 720}, {1600, 900}, {1920, 1080}};
const int panel_heights[] = {1080, 1200};
for (unsigned panel = 0; panel < sizeof(panel_heights) / sizeof(panel_heights[0]); panel++) {
float native[24];
const int height = panel_heights[panel];
cardboard_push_constants(&screen, pose, 1920, 1080, 3840, height, native);
for (unsigned size = 0; size < sizeof(source_sizes) / sizeof(source_sizes[0]); size++) {
cardboard_push_constants(&screen, pose, source_sizes[size][0], source_sizes[size][1], 3840, height, pc);
for (unsigned field = 0; field < 24; field++) CHECK(near(pc[field], native[field]));
CHECK(near(pc[17], 16.0f / 9.0f));
CHECK(near(pc[18], CARDBOARD_SOURCE_SCREEN));
CHECK(near(pc[19], 1920.0f / height));
CHECK(near(pc[20], 0.0f));
}
}
q.source = CARDBOARD_SOURCE_FLAT;
cardboard_clamp(&q);
CHECK(q.source == CARDBOARD_SOURCE_FLAT);
for (unsigned panel = 0; panel < sizeof(panel_heights) / sizeof(panel_heights[0]); panel++) {
for (unsigned size = 0; size < sizeof(source_sizes) / sizeof(source_sizes[0]); size++) {
cardboard_push_constants(&q, pose, source_sizes[size][0], source_sizes[size][1], 3840, panel_heights[panel], pc);
CHECK(near(pc[17], 16.0f / 9.0f));
CHECK(near(pc[18], CARDBOARD_SOURCE_FLAT));
CHECK(near(pc[19], 1920.0f / panel_heights[panel]));
CHECK(near(pc[20], 0.0f));
}
}
q.fov_deg = 0.0f;
cardboard_clamp(&q);
CHECK(q.fov_deg > 0.0f && q.fov_deg < glasses_fovs[0]);
const float translation[3] = {0.25f, -0.3f, 0.5f};
q.source = CARDBOARD_SOURCE_SCREEN;
cardboard_push_constants(&q, pose, 1920, 1080, 3840, 1200, pc);
float original[24]; memcpy(original, pc, sizeof(pc));
cardboard_push_translation(&q, translation, pc);
for (int i = 0; i < 21; ++i) CHECK(near(pc[i], original[i]));
for (int i = 0; i < 3; ++i) CHECK(near(pc[21+i], translation[i]));
q.source = CARDBOARD_SOURCE_SBS;
cardboard_push_translation(&q, translation, pc);
CHECK(near(pc[21], 0) && near(pc[22], 0) && near(pc[23], 0));
q.source = CARDBOARD_SOURCE_FLAT;
cardboard_push_translation(&q, translation, pc);
CHECK(near(pc[21], 0) && near(pc[22], 0) && near(pc[23], 0));
q.source = CARDBOARD_SOURCE_SCREEN;
const float zero[3] = {0};
cardboard_push_translation(&q, zero, pc);
for (int i = 0; i < 24; ++i) CHECK(near(pc[i], original[i]));
if (failures) return 1;
printf("PASS: cardboard params\n");
return 0;
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""Compile and render the tracked-menu GLES shaders with headless Mesa (opt-in)."""
import argparse
import ctypes as c
import hashlib
import json
import math
import os
import pathlib
import re
import struct
import zlib
def main():
os.environ.setdefault('EGL_PLATFORM', 'surfaceless')
os.environ.setdefault('LIBGL_ALWAYS_SOFTWARE', '1')
os.environ.setdefault('MESA_GLES_VERSION_OVERRIDE', '2.0')
root = pathlib.Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir', type=pathlib.Path, default=root / 'build/glasses-menu-shader')
args = parser.parse_args()
out = args.output_dir.resolve()
out.mkdir(parents=True, exist_ok=True)
source_path = root / 'app/src/main/java/com/droiddeck/launcher/glasses/GlassesMenuSurface.kt'
source = source_path.read_text()
shaders = {name: re.search(r'private const val '+name+r' = """(.*?)"""', source, re.S).group(1).encode()
for name in ('VERTEX', 'FRAGMENT')}
try:
egl = c.CDLL('libEGL.so.1')
gl = c.CDLL('libGLESv2.so.2')
except OSError as error:
raise SystemExit('This opt-in check needs Linux EGL/GLES and Mesa software rendering. '
'On Debian/Ubuntu install libegl1 libegl-mesa0 libgles2 libgl1-mesa-dri. '
f'Library load failed: {error}') from error
def bind(lib, name, result, *args):
fn = getattr(lib, name)
fn.restype, fn.argtypes = result, args
return fn
P, I, U, F = c.c_void_p, c.c_int, c.c_uint, c.c_float
eglGetDisplay = bind(egl, 'eglGetDisplay', P, P)
eglInitialize = bind(egl, 'eglInitialize', U, P, c.POINTER(I), c.POINTER(I))
eglChooseConfig = bind(egl, 'eglChooseConfig', U, P, c.POINTER(I), c.POINTER(P), I, c.POINTER(I))
eglCreatePbufferSurface = bind(egl, 'eglCreatePbufferSurface', P, P, P, c.POINTER(I))
eglCreateContext = bind(egl, 'eglCreateContext', P, P, P, P, c.POINTER(I))
eglMakeCurrent = bind(egl, 'eglMakeCurrent', U, P, P, P, P)
eglQueryString = bind(egl, 'eglQueryString', c.c_char_p, P, I)
eglGetProcAddress = bind(egl, 'eglGetProcAddress', P, c.c_char_p)
display = eglGetDisplay(None)
major, minor = I(), I()
assert eglInitialize(display, c.byref(major), c.byref(minor))
attrs = (I * 15)(0x3033, 1, 0x3040, 4, 0x3024, 8, 0x3023, 8, 0x3022, 8, 0x3021, 8, 0x3025, 0, 0x3038)
config, count = P(), I()
assert eglChooseConfig(display, attrs, c.byref(config), 1, c.byref(count)) and count.value
surface = eglCreatePbufferSurface(display, config, (I * 5)(0x3057, 512, 0x3056, 256, 0x3038))
context = eglCreateContext(display, config, None, (I * 3)(0x3098, 2, 0x3038))
assert surface and context and eglMakeCurrent(display, surface, surface, context)
getString = bind(gl, 'glGetString', c.c_char_p, U)
getError = bind(gl, 'glGetError', U)
metadata = {'source_sha256': hashlib.sha256(source.encode()).hexdigest(),
'shader_sha256': {key: hashlib.sha256(value).hexdigest() for key, value in shaders.items()},
'egl': eglQueryString(display, 0x3054).decode(),
'gles': getString(0x1F02).decode(), 'renderer': getString(0x1F01).decode(),
'assumption': 'External texture contains top-row-first Canvas buffer pixels; consumer transform flips Y, as Android GLConsumer does. Device SurfaceTexture/Canvas integration still needs validation.'}
assert b'GL_OES_EGL_image_external' in getString(0x1F03)
createShader = bind(gl, 'glCreateShader', U, U)
shaderSource = bind(gl, 'glShaderSource', None, U, I, c.POINTER(c.c_char_p), c.POINTER(I))
compileShader = bind(gl, 'glCompileShader', None, U)
getShaderiv = bind(gl, 'glGetShaderiv', None, U, U, c.POINTER(I))
getShaderLog = bind(gl, 'glGetShaderInfoLog', None, U, I, c.POINTER(I), c.c_char_p)
compiled = []
for name, kind in [('VERTEX', 0x8B31), ('FRAGMENT', 0x8B30)]:
shader = createShader(kind)
text = c.c_char_p(shaders[name])
shaderSource(shader, 1, c.byref(text), None)
compileShader(shader)
status, log = I(), c.create_string_buffer(8192)
getShaderiv(shader, 0x8B81, c.byref(status))
getShaderLog(shader, len(log), None, log)
assert status.value, name + ': ' + log.value.decode()
compiled.append(shader)
createProgram = bind(gl, 'glCreateProgram', U)
attachShader = bind(gl, 'glAttachShader', None, U, U)
linkProgram = bind(gl, 'glLinkProgram', None, U)
getProgramiv = bind(gl, 'glGetProgramiv', None, U, U, c.POINTER(I))
getProgramLog = bind(gl, 'glGetProgramInfoLog', None, U, I, c.POINTER(I), c.c_char_p)
program = createProgram()
for shader in compiled:
attachShader(program, shader)
linkProgram(program)
status, log = I(), c.create_string_buffer(8192)
getProgramiv(program, 0x8B82, c.byref(status))
getProgramLog(program, len(log), None, log)
assert status.value, log.value.decode()
useProgram = bind(gl, 'glUseProgram', None, U)
useProgram(program)
getUniform = bind(gl, 'glGetUniformLocation', I, U, c.c_char_p)
uniform1i = bind(gl, 'glUniform1i', None, I, I)
uniform3f = bind(gl, 'glUniform3f', None, I, F, F, F)
uniform4f = bind(gl, 'glUniform4f', None, I, F, F, F, F)
uniformMatrix4 = bind(gl, 'glUniformMatrix4fv', None, I, I, U, c.POINTER(F))
loc = lambda name: getUniform(program, name.encode())
uniform1i(loc('uTexture'), 0)
flip = (F * 16)(1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1)
uniformMatrix4(loc('uTextureMatrix'), 1, 0, flip)
genTextures = bind(gl, 'glGenTextures', None, I, c.POINTER(U))
bindTexture = bind(gl, 'glBindTexture', None, U, U)
texParameteri = bind(gl, 'glTexParameteri', None, U, U, I)
texImage2D = bind(gl, 'glTexImage2D', None, U, I, I, I, I, I, U, U, P)
names = (U * 2)()
genTextures(2, names)
bindTexture(0x0DE1, names[0])
pixels = bytes(value for y in range(256) for x in range(256) for value in (x, y, 37, 255))
pixel_data = (c.c_ubyte * len(pixels)).from_buffer_copy(pixels)
texImage2D(0x0DE1, 0, 0x1908, 256, 256, 0, 0x1908, 0x1401, pixel_data)
for param, value in [(0x2801,0x2601),(0x2800,0x2601),(0x2802,0x812F),(0x2803,0x812F)]:
texParameteri(0x0DE1, param, value)
createImage = c.CFUNCTYPE(P, P, P, U, P, c.POINTER(I))(eglGetProcAddress(b'eglCreateImageKHR'))
imageTarget = c.CFUNCTYPE(None, U, P)(eglGetProcAddress(b'glEGLImageTargetTexture2DOES'))
image = createImage(display, context, 0x30B1, P(names[0]), (I * 3)(0x30BC, 0, 0x3038))
assert image
bindTexture(0x8D65, names[1])
imageTarget(0x8D65, image)
for param, value in [(0x2801,0x2601),(0x2800,0x2601),(0x2802,0x812F),(0x2803,0x812F)]:
texParameteri(0x8D65, param, value)
assert getError() == 0
getAttrib = bind(gl, 'glGetAttribLocation', I, U, c.c_char_p)
enableAttrib = bind(gl, 'glEnableVertexAttribArray', None, U)
attribPointer = bind(gl, 'glVertexAttribPointer', None, U, I, U, U, I, P)
vertices = (F * 8)(-1,-1, 1,-1, -1,1, 1,1)
position = getAttrib(program, b'aPosition')
enableAttrib(position)
attribPointer(position, 2, 0x1406, 0, 0, vertices)
viewport = bind(gl, 'glViewport', None, I, I, I, I)
draw = bind(gl, 'glDrawArrays', None, U, I, I)
read = bind(gl, 'glReadPixels', None, I, I, I, I, U, U, P)
finish = bind(gl, 'glFinish', None)
cases = []
def render(name, mono=True, position=(0,0,0), yaw=0, width=512, height=256, coords=((64,32),(448,32),(64,224),(448,224)), backdrop=False):
viewport(0, 0, width, height)
cs, sn = math.cos(yaw), math.sin(yaw)
for row, values in enumerate(((cs,0,sn),(0,1,0),(-sn,0,cs))):
uniform3f(loc('uRotation'+str(row)), *values)
uniform3f(loc('uHead'), *position)
uniform3f(loc('uScreen'), 1, 1, 2)
uniform4f(loc('uOptics'), .5, width/height/(1 if mono else 2), 0 if mono else .032, 1 if mono else 0)
draw(0x0005, 0, 4)
finish()
assert getError() == 0
actual = (c.c_ubyte * (width*height*4))()
read(0,0,width,height,0x1908,0x1401,actual)
samples = []
for x, y in coords:
# Readback is GL bottom-up; coordinates below are image top-left.
offset = ((height-1-y)*width+x)*4
rgb = list(actual[offset:offset+3])
eye = 0 if mono or x < width/2 else 1
ux = (x+.5)/width if mono else (x+.5)/(width/2)-eye
vy = (y+.5)/height
rayx = (ux-.5)*(width/height/(1 if mono else 2))
rayy = .5-vy
dx, dy, dz = cs*rayx-sn, rayy, -sn*rayx-cs
eo = 0 if mono else (-.032 if eye == 0 else .032)
ox, oy, oz = position[0]+cs*eo, position[1], position[2]-sn*eo
t = (-1-oz)/dz if dz else -1
uv = ((ox+dx*t)*.5+.5, -(oy+dy*t)+.5)
valid = dz < -.0001 and t > 0 and all(0 <= v <= 1 for v in uv) and not backdrop
expected = [round(max(0,min(255,v*256-.5))) for v in uv]+[37] if valid else [4,4,5]
assert all(abs(a-b) <= 2 for a,b in zip(rgb,expected)), (name,x,y,rgb,expected,uv)
samples.append({'at':[x,y],'rgb':rgb,'expected':expected})
cases.append({'name':name,'samples':samples})
if name == 'mono_upright':
rows = bytearray()
for y in range(height-1,-1,-1):
for x in range(width):
start=(y*width+x)*4
rows.extend(actual[start:start+3])
(out/'menu-shader-mono.ppm').write_bytes(f'P6\n{width} {height}\n255\n'.encode()+rows)
def chunk(name, data):
return struct.pack('>I',len(data))+name+data+struct.pack('>I',zlib.crc32(name+data)&0xffffffff)
scanlines=b''.join(b'\x00'+rows[y*width*3:(y+1)*width*3] for y in range(height))
(out/'menu-shader-mono.png').write_bytes(b'\x89PNG\r\n\x1a\n'+
chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,2,0,0,0))+
chunk(b'IDAT',zlib.compress(scanlines))+chunk(b'IEND',b''))
render('mono_upright')
render('sbs_both_eyes', mono=False, width=512, height=128,
coords=((32,16),(224,16),(32,112),(224,112),(288,16),(480,16),(288,112),(480,112),(128,64),(384,64)))
render('six_dof_translation', position=(.2,.1,.1), coords=((256,128),(200,96),(300,160)))
render('row_major_yaw', yaw=math.radians(10), coords=((256,128),(200,96),(300,160)))
render('behind_plane', position=(0,0,-2), coords=((256,128),), backdrop=True)
render('back_facing', yaw=math.pi, coords=((256,128),), backdrop=True)
metadata['cases'] = cases
metadata['result'] = 'PASS'
(out/'menu-shader-validation.json').write_text(json.dumps(metadata, indent=2)+'\n')
print(json.dumps(metadata, indent=2), flush=True)
if __name__ == '__main__':
main()
+1
View File
@@ -6,6 +6,7 @@ docker run --rm --platform linux/amd64 -v "$repo:/src" \
-v "${HOME}/.cache/droiddeck-comet-rust:/rust" -w /src \
-e CARGO_HOME=/rust/cargo -e RUSTUP_HOME=/rust/rustup "$image" bash -lc '
set -euo pipefail
trap "chown -R '"$(id -u):$(id -g)"' app/build/comet app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet /rust 2>/dev/null || true" EXIT
apt-get update -qq
apt-get install -y -qq curl git unzip ca-certificates pkg-config >/dev/null
export PATH=/rust/cargo/bin:$PATH
+11 -4
View File
@@ -9,11 +9,18 @@ done
work=$(mktemp -d)
trap 'rm -rf "${work}"' EXIT
cache=${DROIDDECK_BUILD_CACHE:-"${HOME}/.cache/droiddeck-build"}
mkdir -p "${cache}"
fetch() {
local name=$1 sha=$2
curl -fsSL --retry 3 -o "${work}/${name}" \
"https://github.com/${DIRECTAUDIO_REPO}/releases/download/${DIRECTAUDIO_TAG}/${name}"
echo "${sha} ${work}/${name}" | sha256sum -c - >/dev/null || { echo "${name}: checksum mismatch" >&2; exit 1; }
local name=$1 sha=$2 kept="${cache}/$2-$1" part
if ! echo "${sha} ${kept}" | sha256sum -c - >/dev/null 2>&1; then
part=$(mktemp "${kept}.part.XXXXXX")
curl -fsSL --retry 3 -o "${part}" \
"https://github.com/${DIRECTAUDIO_REPO}/releases/download/${DIRECTAUDIO_TAG}/${name}"
echo "${sha} ${part}" | sha256sum -c - >/dev/null || { echo "${name}: checksum mismatch" >&2; rm -f "${part}"; exit 1; }
mv "${part}" "${kept}"
fi
cp "${kept}" "${work}/${name}"
}
fetch directaudio-linux-wine11.zip "${DIRECTAUDIO_WINE11_SHA256}"
fetch directaudio-linux-wine11-systhread.zip "${DIRECTAUDIO_SYSTHREAD_SHA256}"
+249 -5
View File
@@ -5,21 +5,28 @@ from __future__ import annotations
import argparse
import base64
import gzip
import json
import os
import re
import shutil
import subprocess
import struct
import sys
import tempfile
import time
import uuid
import zlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from adb_device import DeviceResolutionError, resolve_serial
AUTHORITY = "content://com.droiddeck.launcher.agent"
PACKAGE = "com.droiddeck.launcher"
# tools/release/variants.txt: the same app also ships as other packages (e.g. com.antutu.benchmark.full).
PACKAGE = os.environ.get("DROIDDECK_PACKAGE", "com.droiddeck.launcher")
AUTHORITY = f"content://{PACKAGE}.agent"
PACKAGE_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+")
STEAM_CLIENT_APP = 769
REQUEST_CAP = 256 * 1024
@@ -117,7 +124,7 @@ def start_agent_activity(adb: str, serial: str, request: dict) -> None:
"start",
"-W",
"-n",
f"{PACKAGE}/.agent.AgentStartActivity",
f"{PACKAGE}/com.droiddeck.launcher.agent.AgentStartActivity",
"--es",
"request",
encoded,
@@ -284,6 +291,85 @@ def record(adb: str, serial: str, path: str, seconds: float, display: int | None
return {"ok": True, "command": "record", "path": str(destination), "seconds": seconds, "display": display}
def pacing_summary(text: str, package: str = PACKAGE) -> dict:
"""What reached the panel, from a `dumpsys SurfaceFlinger --timestats -dump`.
The game is on the compositor's own layer (droiddeck_wayland_game) when it has one, otherwise on
the session's SurfaceView. SurfaceFlinger keeps one record per layer AND refresh rate, so a panel
that switches between 60 and 120 Hz mid-capture splits the same layer into several records: they
are summed. A game's own fps counter does not show any of this - it counts frames handed over, not
frames shown, and 60 handed over can be 48 on screen with one in four held for two refreshes.
"""
records = {"game": [], "surface": []}
for part in re.split(r"^displayRefreshRate = ", text, flags=re.M)[1:]:
rate = re.match(r"(\d+)", part)
layer = re.search(r"^layerName = (.*)$", part, re.M)
frames = re.search(r"^totalFrames = (\d+)", part, re.M)
hist = re.search(r"^present2present histogram is as below:\n(.*)", part, re.M)
if not (rate and layer and frames and hist):
continue
name = layer.group(1)
kind = ("game" if "droiddeck_wayland_game" in name
else "surface" if f"SurfaceView[{package}/" in name else None)
if kind and int(frames.group(1)):
bins = {int(ms): int(n) for ms, n in re.findall(r"(\d+)ms=(\d+)", hist.group(1)) if int(n)}
records[kind].append((re.sub(r"#\d+$", "", name.strip()), int(frames.group(1)), bins, int(rate.group(1))))
chosen = records["game"] or records["surface"]
histogram: dict[int, int] = {}
off = 0
for _, _, bins, _ in chosen:
for ms, count in bins.items():
histogram[ms] = histogram.get(ms, 0) + count
if bins:
# SurfaceFlinger bins by whole milliseconds, so one cadence spans two buckets (16.7 ms: 16 and 17).
mode = max(bins, key=bins.get)
off += sum(count for ms, count in bins.items() if abs(ms - mode) > 1)
intervals = sum(histogram.values())
cadence = max(histogram, key=histogram.get) if histogram else None
return {
"layers": sorted({name for name, _, _, _ in chosen}),
"frames": sum(frames for _, frames, _, _ in chosen),
"refreshRates": sorted({rate for _, _, _, rate in chosen}),
"presentToPresentMs": {str(ms): histogram[ms] for ms in sorted(histogram)},
"cadenceMs": cadence,
"offCadence": off,
"offCadencePercent": round(100.0 * off / intervals, 1) if intervals else None,
}
def pacing(adb: str, serial: str, seconds: float) -> dict:
"""Frames on screen and their intervals over `seconds`, from SurfaceFlinger's timestats."""
seconds = max(1.0, min(600.0, seconds))
timestats = ("shell", "dumpsys", "SurfaceFlinger", "--timestats")
try:
enabled = run_adb(adb, serial, *timestats, "-clear", "-enable")
except ControlError as exc:
raise ControlError(str(exc), "PACING_FAILED") from exc
if enabled.returncode != 0:
raise ControlError("could not enable SurfaceFlinger timestats", "PACING_FAILED")
started = time.monotonic()
try:
time.sleep(seconds)
dump = run_adb(adb, serial, *timestats, "-dump", timeout=60)
except ControlError as exc:
raise ControlError(str(exc), "PACING_FAILED") from exc
finally:
elapsed = time.monotonic() - started
try:
disabled = run_adb(adb, serial, *timestats, "-disable").returncode == 0
except ControlError:
disabled = False
if dump.returncode != 0:
raise ControlError(dump.stderr.decode(errors="replace").strip() or "timestats dump failed", "PACING_FAILED")
if not disabled:
raise ControlError("could not turn SurfaceFlinger timestats off", "PACING_FAILED")
summary = pacing_summary(dump.stdout.decode(errors="replace"))
if not summary["layers"] or not summary["frames"]:
raise ControlError("No DroidDeck layer drew during the capture: is a session on screen?", "NO_FRAMES")
summary["fpsOnScreen"] = round(summary["frames"] / elapsed, 1)
return {"ok": True, "command": "pacing", "seconds": round(elapsed, 1), **summary}
def start_session(adb: str, serial: str, request: dict) -> dict:
if request.get("mode") == "run":
@@ -323,8 +409,101 @@ def input_request(args: argparse.Namespace) -> dict:
raise ControlError(f"Unknown input type {kind}", "INVALID_INPUT")
def xr_ppm_to_png(data: bytes, linear: bool = False) -> bytes:
header = re.match(rb"P6\n([0-9]+) ([0-9]+)\n255\n", data)
if not header:
raise ControlError("Invalid XR image header", "XR_CAPTURE_FAILED")
width, height = map(int, header.groups())
pixels = data[header.end():]
if not (0 < width <= 16384 and 0 < height <= 16384) or len(pixels) != width * height * 3:
raise ControlError("Invalid XR image dimensions or incomplete pixels", "XR_CAPTURE_FAILED")
def chunk(kind: bytes, value: bytes) -> bytes:
return struct.pack('>I', len(value)) + kind + value + struct.pack('>I', zlib.crc32(kind + value))
stride = width * 3
rows = b''.join(b'\0' + pixels[start:start + stride] for start in range(0, len(pixels), stride))
transfer = chunk(b'gAMA', struct.pack('>I', 100000)) if linear else chunk(b'sRGB', b'\0')
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) + transfer +
chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b''))
def xr_capture(adb: str, serial: str, destination: Path, timeout: float) -> dict:
if not 0 < timeout <= 120:
raise ControlError("XR capture timeout must be between 0 and 120 seconds", "INVALID_TIMEOUT")
remote = f'/sdcard/Android/data/{PACKAGE}/files/xr-capture'
token = uuid.uuid4().hex
with tempfile.TemporaryDirectory() as temporary:
request = Path(temporary) / 'request'
request.write_text(token, encoding='ascii')
pushed = run_adb(adb, serial, 'push', str(request), remote + '.request.tmp')
if pushed.returncode:
raise ControlError(pushed.stderr.decode(errors='replace'), 'XR_CAPTURE_FAILED')
moved = run_adb(adb, serial, 'shell', 'mv', remote + '.request.tmp', remote + '.request')
if moved.returncode:
raise ControlError(moved.stderr.decode(errors='replace'), 'XR_CAPTURE_FAILED')
deadline = time.monotonic() + timeout
metadata = None
while time.monotonic() < deadline:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
result = run_adb(adb, serial, 'shell', 'cat', remote + '.json', timeout=remaining)
except ControlError as error:
if not isinstance(error.__cause__, subprocess.TimeoutExpired):
raise
break
try:
answer = json.loads(result.stdout)
if answer.get('id') == token:
metadata = answer
break
except (ValueError, AttributeError):
pass
time.sleep(0.2)
if metadata is None:
try:
run_adb(adb, serial, 'shell', 'rm', '-f', remote + '.request', timeout=1)
except ControlError:
pass
raise ControlError('No fresh XR capture. Enter SteamVR using a build with XR capture support.', 'TIMEOUT')
if not metadata.get('ok'):
detail = 'No valid XR projection layer is being submitted' if not metadata.get('validLayer') else 'GPU readback or image write failed'
raise ControlError(detail, 'XR_CAPTURE_FAILED')
images = {}
for eye in (('left', 'right', 'source') if metadata.get('sourceImage') else ('left', 'right')):
pulled = run_adb(adb, serial, 'exec-out', 'gzip', '-c', remote + '-' + eye + '.ppm', timeout=120)
if pulled.returncode:
raise ControlError(pulled.stderr.decode(errors='replace'), 'XR_CAPTURE_FAILED')
try:
pixels = gzip.decompress(pulled.stdout)
except (OSError, EOFError, zlib.error) as error:
raise ControlError('Incomplete compressed XR image', 'XR_CAPTURE_FAILED') from error
images[eye] = xr_ppm_to_png(pixels, linear=eye == 'source' and metadata.get('sourceColorSpace') == 'linear')
# Detect overlapping captures before publishing images with another request's metadata.
check = run_adb(adb, serial, 'shell', 'cat', remote + '.json')
try:
unchanged = json.loads(check.stdout).get('id') == token
except (ValueError, AttributeError):
unchanged = False
if not unchanged:
raise ControlError('XR capture was replaced by another request; retry', 'XR_CAPTURE_FAILED')
try:
destination.mkdir(parents=True, exist_ok=True)
for eye, image in images.items():
(destination / (eye + '.png')).write_bytes(image)
(destination / 'capture.json').write_text(json.dumps(metadata, indent=2), encoding='utf-8')
except OSError as error:
raise ControlError(str(error), 'FILE_IO') from error
return {'ok': True, 'command': 'xr-frame', 'deviceSerial': serial, 'capture': metadata,
'left': str((destination / 'left.png').resolve()), 'right': str((destination / 'right.png').resolve()),
**({'source': str((destination / 'source.png').resolve())} if 'source' in images else {}),
'scope': 'App eye textures before headset compositor reprojection; excludes Meta system overlays'}
def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
command = args.command
if command == 'xr-frame':
return xr_capture(adb, serial, Path(args.path), args.timeout)
if command == "state":
return add_serial(get_state(adb, serial), serial)
@@ -338,6 +517,8 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if not args.url.startswith("steam://"):
raise ControlError("Steam URL must start with steam://", "INVALID_STEAM_URL")
request["steamUrl"] = args.url
if args.steamvr:
request["steamVr"] = True
if args.reuse:
current = get_state(adb, serial)["session"]
wanted = {"steam": "steam", "desktop": "lxqt"}[args.mode]
@@ -481,6 +662,28 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if command == "access":
return add_serial(checked(provider_call(adb, serial, "access"), "ACCESS_FAILED"), serial)
if command == "glasses":
request = {"op": args.glasses_op or "status"}
if args.glasses_op == "set":
request.update(key=args.key, value=args.value)
elif args.glasses_op == "simulate":
request["seconds"] = args.seconds
if args.yaw is not None:
request["yaw"] = args.yaw
if args.pitch is not None:
request["pitch"] = args.pitch
elif args.glasses_op == "mode":
request["mode"] = args.mode
elif args.glasses_op == "imu":
request["ms"] = args.ms
elif args.glasses_op == "spatial-diagnostics":
request["enabled"] = not args.off
elif args.glasses_op == "spatial-recenter":
request["screen"] = args.screen
elif args.glasses_op == "raw":
request.update(msgId=args.msg_id, payload=args.payload or "")
return add_serial(checked(provider_call(adb, serial, "glasses", request=request), "GLASSES_FAILED"), serial)
if command == "logs":
state = get_state(adb, serial)
session = state.get("session", {})
@@ -503,6 +706,9 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if command == "record":
return add_serial(record(adb, serial, args.path, args.seconds, args.display), serial)
if command == "pacing":
return add_serial(pacing(adb, serial, args.seconds), serial)
if command == "wake":
run_adb(adb, serial, "shell", "input", "keyevent", "KEYCODE_WAKEUP")
run_adb(adb, serial, "shell", "wm", "dismiss-keyguard")
@@ -528,6 +734,7 @@ def build_parser() -> argparse.ArgumentParser:
start = commands.add_parser("start", help="start Steam or the desktop")
start.add_argument("mode", choices=["steam", "desktop"])
start.add_argument("--ui", choices=["bigpicture", "desktop"], default="bigpicture")
start.add_argument("--steamvr", action="store_true", help="start SteamVR with the session (VITURE glasses)")
start.add_argument("--url", help="steam:// URL to pass to the client")
start.add_argument("--wait", action="store_true", help="wait for READY after starting")
start.add_argument("--reuse", action="store_true", help="keep a running session of this mode instead of failing")
@@ -646,6 +853,33 @@ def build_parser() -> argparse.ArgumentParser:
commands.add_parser("access", help="whether debugging tools are enabled on the device")
glasses = commands.add_parser("glasses", help="VITURE glasses: status, settings, head tracking test")
glasses_ops = glasses.add_subparsers(dest="glasses_op")
glasses_ops.add_parser("status")
glasses_ops.add_parser("allow", help="ask for USB control of the glasses again")
glasses_set = glasses_ops.add_parser("set", help="refreshHz, sbsHz, resolution2d, resolution3d, resolutionVr (auto or WIDTHxHEIGHT per eye), brightness, volume, sunblock, 3d, 3dof, gameOnGlasses, headTracking, auto3d, picture3d, screenWidthDm, screenDistanceDm, vrFovDeg")
glasses_set.add_argument("key")
glasses_set.add_argument("value")
glasses_sim = glasses_ops.add_parser("simulate", help="feed a moving head pose (yaw, pitch and roll sweeps), or hold one")
glasses_sim.add_argument("--seconds", type=int, default=20)
glasses_sim.add_argument("--yaw", type=float, help="hold this yaw (degrees, left positive) instead of sweeping")
glasses_sim.add_argument("--pitch", type=float, help="hold this pitch (degrees, down positive) instead of sweeping")
glasses_ops.add_parser("stop-simulate")
glasses_ops.add_parser("query", help="ask the glasses for their display mode, brightness, volume and IMU state")
spatial_diagnostics = glasses_ops.add_parser("spatial-diagnostics", help="start stereo diagnostics without saving images")
spatial_diagnostics.add_argument("--off", action="store_true")
spatial_recenter = glasses_ops.add_parser("spatial-recenter", help="recenter the current spatial origin")
spatial_recenter.add_argument("--screen", action="store_true")
glasses_ops.add_parser("spatial-floor", help="set floor using configured eye height")
glasses_ops.add_parser("spatial-restart", help="restart the provider for explicit tracking recovery")
glasses_mode = glasses_ops.add_parser("mode", help="send a display mode byte, e.g. 0x31 (1080p60), 0x34 (1080p120), 0x32 (3D)")
glasses_mode.add_argument("mode")
glasses_imu = glasses_ops.add_parser("imu", help="stream the glasses' IMU for a moment and show what it reports")
glasses_imu.add_argument("--ms", type=int, default=2000)
glasses_raw = glasses_ops.add_parser("raw", help="send one MCU command (debugging tools)")
glasses_raw.add_argument("msg_id", help="hex message id, e.g. 0x0007")
glasses_raw.add_argument("payload", nargs="?", help="hex bytes")
logs = commands.add_parser("logs", help="pull the latest session artifact directory")
logs.add_argument("which", choices=["latest"])
logs.add_argument("destination", nargs="?")
@@ -655,11 +889,18 @@ def build_parser() -> argparse.ArgumentParser:
shot.add_argument("path")
shot.add_argument("--display", type=int, help="logical display id (see displays); default the default display")
xr = commands.add_parser('xr-frame', help='capture both submitted XR eyes and pose metadata')
xr.add_argument('path', help='output directory for left.png, right.png and capture.json')
xr.add_argument('--timeout', type=float, default=15)
rec = commands.add_parser("record", help="record the screen to an mp4")
rec.add_argument("path")
rec.add_argument("--seconds", type=float, default=10)
rec.add_argument("--display", type=int)
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("displays", help="the device's displays and their capture ids")
commands.add_parser("wake", help="wake the device and dismiss the keyguard")
return parser
@@ -669,10 +910,11 @@ EXIT_ADB = {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE"}
EXIT_SESSION = {
"SESSION_ACTIVE", "NO_ACTIVE_SESSION", "SESSION_NOT_SUSPENDED", "SESSION_FAILED", "GUEST_EXIT",
"GUEST_START_FAILED", "RUNTIME_INSTALL_FAILED", "DESKTOP_INSTALL_FAILED", "ACTIVITY_START_FAILED",
"NO_STEAM_SESSION", "SESSION_NOT_READY", "AGENT_UNAVAILABLE", "LAUNCH_REJECTED", "NO_PAD",
"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", "SCREENSHOT_FAILED", "FILE_IO", "RECORD_FAILED", "PUSH_FAILED",
"PACING_FAILED", "XR_CAPTURE_FAILED"}
EXIT_DENIED = {"AGENT_COMMANDS_DISABLED", "PROTECTED_PREFS", "PROTECTED_CONTROL"}
@@ -697,6 +939,8 @@ def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
serial = None
try:
if not PACKAGE_NAME.fullmatch(PACKAGE): # it reaches the device shell through `am start` and `content call`
raise ControlError(f"DROIDDECK_PACKAGE is not an Android package name: {PACKAGE!r}", "INVALID_REQUEST")
adb = adb_path(args.adb)
serial = resolve_serial(adb, args.serial, log=True)
result = execute(args, adb, serial)
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/bash
# Runs inside an Arch Linux ARM container (menci/archlinuxarm:base-devel) on an arm64 runner. Arch Linux ARM ships
# no FEX package and FEX publishes no Linux binaries.
set -euxo pipefail
VERSION=${FEX_VERSION:-FEX-2610}
WORK=/work
cd "$WORK"
grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf
{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do echo "Server = $m/\$arch/\$repo"; done; cat /etc/pacman.d/mirrorlist; } > /etc/pacman.d/mirrorlist.new
mv /etc/pacman.d/mirrorlist.new /etc/pacman.d/mirrorlist
pacman -Syu --noconfirm --needed git zstd binutils cmake ninja clang lld llvm python squashfs-tools file patchelf xxhash
# The x86 sysroot is Arch x86_64 and multilib i686 packages unpacked by pacman, never run: no scriptlets or signature checks.
THUNKS=${FEX_THUNKS:-0}
X86ROOT=$WORK/x86root
if [ "$THUNKS" = 1 ]; then
pacman -S --noconfirm --needed pkgconf libx11 libxcb libxrandr libxrender libxext xorgproto \
libglvnd mesa wayland libdrm alsa-lib libxshmfence vulkan-headers vulkan-icd-loader
rm -rf "$X86ROOT" && mkdir -p "$X86ROOT/var/lib/pacman" "$WORK/x86-cache"
cat > "$WORK/x86-pacman.conf" <<'CONF'
[options]
Architecture = x86_64
SigLevel = Never
DisableSandbox
[core]
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch
[extra]
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch
[multilib]
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch
CONF
pacman --config "$WORK/x86-pacman.conf" --root "$X86ROOT" --dbpath "$X86ROOT/var/lib/pacman" \
--cachedir "$WORK/x86-cache" --noscriptlet --noconfirm --overwrite '*' -Sy \
glibc linux-api-headers gcc gcc-libs libx11 libxcb xorgproto libxrandr libxrender libxext libxau \
libxdmcp libglvnd mesa wayland libdrm alsa-lib libxshmfence \
lib32-glibc lib32-gcc-libs lib32-libx11 lib32-libxcb lib32-libxrandr lib32-libxrender \
lib32-libxext lib32-libglvnd lib32-mesa lib32-wayland lib32-libdrm lib32-alsa-lib lib32-libxshmfence
ls "$X86ROOT/usr/include" | head -5
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
# FEX's x86 toolchain files assume an x86 build machine; here the guest thunks need the x86 sysroot too.
# Arch's clang adds stack protection; its canary load in a guest thunk's prologue clobbered r11 (the host function).
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"
printf '\nset(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-stack-protector")\nset(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-stack-protector")\n' >> "$t"
done
fi
# TUNE_CPU none: the default (native) would tune for the runner's Neoverse cores, not the device.
cmake -S fex-src -B fex-build -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local \
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DUSE_LINKER=lld \
-DTUNE_CPU=none -DTUNE_ARCH=armv8-a \
-DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \
$( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
# The Linux runtime has no xxhash and no ld.so.cache: the library goes beside libFEXCore and the programs
# that need it find it through RUNPATH.
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
for f in out/usr/local/bin/*; do
[ -L "$f" ] && continue
file "$f" | grep -q ELF || continue
readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }' | grep -qxF "$bundled" \
&& patchelf --set-rpath '$ORIGIN/../lib' "$f"
done
# Every NEEDED soname must resolve in a stock guest: bundled here or provided by the runtime (runtime-libs.txt).
for f in out/usr/local/bin/* out/usr/local/lib/*.so* out/usr/local/lib/fex-emu/HostThunks*/*.so; do
[ -f "$f" ] && file "$f" | grep -q ELF || continue
readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }'
done | sort -u | tee fex-needed.txt
missing=$(printf '%s\n' "$bundled" | cat - tools/fex/runtime-libs.txt | sort -u | comm -23 fex-needed.txt -)
[ -z "$missing" ] || { echo "not in the Linux runtime or this package:" $missing >&2; exit 1; }
for f in out/usr/local/bin/*; do
[ -L "$f" ] || ! file "$f" | grep -q ELF && continue
if readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }' | grep -qxF "$bundled"; then
readelf -d "$f" | grep -q 'RUNPATH.*\$ORIGIN/\.\./lib' || { echo "$f needs a bundled library but has no RUNPATH" >&2; exit 1; }
fi
done
(cd out && find . -type f -o -type l | sort) | tee fex-files.txt
tar -C out -c . | zstd -19 -T0 -o fex.tzst
sha256sum fex.tzst | tee fex.tzst.sha256
@@ -0,0 +1,203 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
index 7172460..2c80dca 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
@@ -29,6 +29,7 @@ $end_info$
#include <algorithm>
#include <errno.h>
#include <cstring>
+#include <linux/magic.h>
#include <linux/openat2.h>
#include <fcntl.h>
#include <filesystem>
@@ -632,6 +633,163 @@ static bool ShouldSkipOpenInEmu(int flags) {
return false;
}
+static bool IsOnProcFS(int DirFD, const char* Pathname) {
+ int FD = ::openat(DirFD, Pathname, O_PATH | O_NOFOLLOW | O_CLOEXEC);
+ if (FD == -1) {
+ return false;
+ }
+
+ struct statfs Buffer {};
+ const bool Result = fstatfs(FD, &Buffer) == 0 && Buffer.f_type == PROC_SUPER_MAGIC;
+ close(FD);
+ return Result;
+}
+
+// openat2() with RESOLVE_IN_ROOT, walked one component at a time: PRoot has no openat2 and fails it with ENOSYS.
+// DirFD is AT_FDCWD only for thunk overlays, which never resolve in the root.
+static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint32_t Mode) {
+ if (DirFD == AT_FDCWD) {
+ return ::syscall(SYSCALL_DEF(openat), DirFD, Pathname, Flags, Mode);
+ }
+
+ // The kernel's MAXSYMLINKS.
+ constexpr uint32_t MaxSymlinks = 40;
+ uint32_t Symlinks {};
+ std::optional<dev_t> RootDev {};
+
+ // O_NOFOLLOW and O_CREAT | O_EXCL leave a final symlink alone, unless a trailing slash follows it.
+ const bool NoFollow = (Flags & O_NOFOLLOW) || (Flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
+
+ char Resolved[PATH_MAX];
+ size_t ResolvedLen {};
+
+ std::array<char[PATH_MAX], 2> Pending;
+ uint32_t PendingIndex {};
+ const char* Remaining = Pathname;
+
+ for (;;) {
+ while (*Remaining == '/') {
+ ++Remaining;
+ }
+
+ if (*Remaining == 0) {
+ break;
+ }
+
+ const char* Component = Remaining;
+ const char* ComponentEnd = Component;
+ while (*ComponentEnd != 0 && *ComponentEnd != '/') {
+ ++ComponentEnd;
+ }
+ const size_t ComponentLen = ComponentEnd - Component;
+
+ Remaining = ComponentEnd;
+ while (*Remaining == '/') {
+ ++Remaining;
+ }
+ const bool Last = *Remaining == 0;
+ const bool TrailingSlash = Last && Remaining != ComponentEnd;
+
+ if (ComponentLen == 1 && Component[0] == '.') {
+ continue;
+ }
+
+ if (ComponentLen == 2 && Component[0] == '.' && Component[1] == '.') {
+ while (ResolvedLen > 0 && Resolved[ResolvedLen - 1] != '/') {
+ --ResolvedLen;
+ }
+ if (ResolvedLen > 0) {
+ --ResolvedLen;
+ }
+ continue;
+ }
+
+ const size_t Separator = ResolvedLen > 0 ? 1 : 0;
+ const size_t CandidateLen = ResolvedLen + Separator + ComponentLen;
+ if (CandidateLen + 1 >= PATH_MAX) {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
+ if (Separator) {
+ Resolved[ResolvedLen] = '/';
+ }
+ memcpy(&Resolved[ResolvedLen + Separator], Component, ComponentLen);
+ Resolved[CandidateLen] = 0;
+
+ struct stat Buffer {};
+ const bool Follow = !Last || TrailingSlash || !NoFollow;
+ const int StatResult = Follow ? fstatat(DirFD, Resolved, &Buffer, AT_SYMLINK_NOFOLLOW) : -1;
+
+ if (StatResult == 0 && S_ISLNK(Buffer.st_mode)) {
+ if (++Symlinks > MaxSymlinks) {
+ errno = ELOOP;
+ return -1;
+ }
+
+ if (!RootDev) {
+ struct stat Root {};
+ if (fstat(DirFD, &Root) != 0) {
+ return -1;
+ }
+ RootDev = Root.st_dev;
+ }
+
+ if (Buffer.st_dev != *RootDev && IsOnProcFS(DirFD, Resolved)) {
+ // Only procfs has magic links. RESOLVE_IN_ROOT fails them with EXDEV and the callers then open without it.
+ return ::syscall(SYSCALL_DEF(openat), DirFD, Pathname, Flags, Mode);
+ }
+
+ char* Target = Pending[PendingIndex];
+ const ssize_t TargetLen = readlinkat(DirFD, Resolved, Target, PATH_MAX);
+ if (TargetLen <= 0) {
+ if (TargetLen == 0) {
+ errno = ENOENT;
+ }
+ return -1;
+ }
+
+ const size_t RestLen = strlen(ComponentEnd);
+ if (static_cast<size_t>(TargetLen) + RestLen >= PATH_MAX) {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
+ memcpy(&Target[TargetLen], ComponentEnd, RestLen + 1);
+
+ if (Target[0] == '/') {
+ ResolvedLen = 0;
+ }
+ Remaining = Target;
+ PendingIndex ^= 1;
+ continue;
+ }
+
+ if (Last) {
+ // openat reports on the final component, which O_CREAT may create.
+ ResolvedLen = CandidateLen;
+ if (TrailingSlash) {
+ Resolved[ResolvedLen++] = '/';
+ }
+ break;
+ }
+
+ if (StatResult != 0) {
+ return -1;
+ }
+
+ if (!S_ISDIR(Buffer.st_mode)) {
+ errno = ENOTDIR;
+ return -1;
+ }
+ ResolvedLen = CandidateLen;
+ }
+
+ if (ResolvedLen == 0) {
+ Resolved[ResolvedLen++] = '.';
+ }
+ Resolved[ResolvedLen] = 0;
+ return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode);
+}
+
bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
char Tmp[PATH_MAX + 1];
@@ -678,6 +836,8 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
// This means a magic symlink (/proc/foo) was involved. In this case we
// just punt and do the access without RESOLVE_IN_ROOT.
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
+ } else if (fd == -1 && errno == ENOSYS) {
+ fd = OpenatWithoutOpenat2(Path.FD, Path.Path, flags, mode);
}
}
@@ -931,6 +1091,8 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
// This means a magic symlink (/proc/foo) was involved. In this case we
// just punt and do the access without RESOLVE_IN_ROOT.
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
+ } else if (fd == -1 && errno == ENOSYS) {
+ fd = OpenatWithoutOpenat2(Path.FD, Path.Path, flags, mode);
}
}
@@ -967,6 +1129,8 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
// This means a magic symlink (/proc/foo) was involved. In this case we
// just punt and do the access without RESOLVE_IN_ROOT.
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, how, usize);
+ } else if (fd == -1 && errno == ENOSYS && how->resolve == 0) {
+ fd = OpenatWithoutOpenat2(Path.FD, Path.Path, how->flags, how->mode);
}
}
@@ -0,0 +1,9 @@
--- a/ThunkLibs/Generator/gen.cpp
+++ b/ThunkLibs/Generator/gen.cpp
@@ -840,6 +840,5 @@
const bool Success = Compiler.ExecuteAction(Action);
- Files->clearStatCache();
return Success;
}
@@ -0,0 +1,103 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp
index 60b0ef1..4a94009 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp
@@ -2,6 +2,7 @@
#include "LinuxSyscalls/LinuxAllocator.h"
#include "LinuxSyscalls/Syscalls.h"
+#include <FEXCore/Utils/Allocator.h>
#include <FEXCore/Utils/MathUtils.h>
#include <FEXCore/Utils/TypeDefines.h>
#include <FEXHeaderUtils/Syscalls.h>
@@ -9,6 +10,7 @@
#include <FEXCore/fextl/memory.h>
#include <bitset>
+#include <fcntl.h>
#include <linux/mman.h>
#include <unistd.h>
#include <sys/user.h>
@@ -82,6 +84,7 @@ private:
std::mutex AllocMutex {};
uint64_t FindPageRange(uint64_t Start, size_t Pages) const;
uint64_t FindPageRange_TopDown(uint64_t Start, size_t Pages) const;
+ bool SetHostMappedPages(uint64_t PageAddr, size_t PagesLength);
using FindHandler = uint64_t (MemAllocator32Bit::*)(uint64_t Start, size_t Pages) const;
FindHandler FindPageRangePtr {};
};
@@ -132,6 +135,37 @@ uint64_t MemAllocator32Bit::FindPageRange_TopDown(uint64_t Start, size_t Pages)
return 0;
}
+// Marks each run of host mappings that overlaps the range as used, in full. Returns false if none overlaps.
+bool MemAllocator32Bit::SetHostMappedPages(uint64_t PageAddr, size_t PagesLength) {
+ const int MapsFD = ::open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
+ if (MapsFD == -1) {
+ return false;
+ }
+
+ const auto Gaps =
+ FEXCore::Allocator::CollectMemoryGaps(BASE_KEY << FEXCore::Utils::FEX_PAGE_SHIFT, TOP_KEY << FEXCore::Utils::FEX_PAGE_SHIFT, MapsFD);
+ close(MapsFD);
+
+ const uint64_t EndPage = PageAddr + PagesLength;
+ uint64_t MappedBegin = BASE_KEY;
+ bool Marked = false;
+ auto MarkIfOverlapping = [&](uint64_t MappedEnd) {
+ if (MappedBegin < MappedEnd && MappedBegin < EndPage && PageAddr < MappedEnd) {
+ SetUsedPages(MappedBegin, MappedEnd - MappedBegin);
+ Marked = true;
+ }
+ };
+
+ for (const auto& Gap : Gaps) {
+ const uintptr_t GapBegin = reinterpret_cast<uintptr_t>(Gap.Ptr);
+ MarkIfOverlapping(GapBegin >> FEXCore::Utils::FEX_PAGE_SHIFT);
+ MappedBegin = (GapBegin + Gap.Size) >> FEXCore::Utils::FEX_PAGE_SHIFT;
+ }
+ MarkIfOverlapping(TOP_KEY);
+
+ return Marked;
+}
+
void* MemAllocator32Bit::Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) {
std::scoped_lock<std::mutex> lk {AllocMutex};
size_t PagesLength = FEXCore::AlignUp(length, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT;
@@ -175,11 +209,17 @@ void* MemAllocator32Bit::Mmap(void* addr, size_t length, int prot, int flags, in
auto AllocateNoHint = [&]() -> void* {
bool Wrapped = false;
+ bool Restarted = false;
uint64_t BottomPage = Map32Bit && (LastScanLocation >= LastKeyLocation32Bit) ? LastKeyLocation32Bit : LastScanLocation;
restart: {
// Linear range scan
uint64_t LowerPage = (this->*FindPageRangePtr)(BottomPage, PagesLength);
if (LowerPage == 0) {
+ // A second scan from the start found nothing either: the range is full, as the kernel would say.
+ if (Restarted) {
+ return reinterpret_cast<void*>(-ENOMEM);
+ }
+ Restarted = true;
// Try again but this time from the start
BottomPage = Map32Bit ? LastKeyLocation32Bit : LastKeyLocation;
LowerPage = (this->*FindPageRangePtr)(BottomPage, PagesLength);
@@ -206,7 +246,17 @@ restart: {
return (void*)(uintptr_t)-errno;
} else {
// Try again
- if (SearchDown) {
+ if (Map32Bit) {
+ // MAP_32BIT from a 64-bit guest, whose other mappings bypass this allocator: once Counter-Strike 2 had reserved the
+ // low 2GB, stepping one page at a time scanned for ever. Record what the host holds there and rescan the range, or
+ // move past it if that mapping is gone.
+ const bool Marked = SetHostMappedPages(LowerPage, PagesLength);
+ if (SearchDown) {
+ BottomPage = Marked ? UpperPage - 1 : LowerPage - 1;
+ } else {
+ BottomPage = Marked ? LowerPage : UpperPage;
+ }
+ } else if (SearchDown) {
--BottomPage;
} else {
++BottomPage;
+12
View File
@@ -0,0 +1,12 @@
ld-linux-aarch64.so.1
libGLX.so.0
libOpenGL.so.0
libc.so.6
libgcc_s.so.1
liblz4.so.1
liblzma.so.5
liblzo2.so.2
libm.so.6
libstdc++.so.6
libz.so.1
libzstd.so.1
+5
View File
@@ -19,6 +19,11 @@ library list, before anything is published.
moves (it sat frozen). The X pointer is asked for only while a cursor image is drawn - every
vblank while shown, every 50 ms while hidden for inactivity - since each ask is a blocking round
trip to Xwayland on the paint thread; with no image, wlserver's position is used as upstream does.
- `0101-nested-wayland-cursor-routing.patch` - this app: `gamescope_cursor_composite=2` lets the
nested Wayland session paint its cursor in the output using the real X pointer position; client
cursor surfaces are cleared to prevent a duplicate at the host pointer, while Gamescope's original
default host-cursor fallback is preserved when its no-keyboard-focus policy selects it. Empty
client cursor images and Gamescope's hidden flag still suppress the painted cursor.
- `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's
pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds
`wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` /
+1
View File
@@ -39,6 +39,7 @@ else
fi
PREP
makepkg -A -s --noconfirm --skipchecksums --skippgpcheck
meson test -C src/build --no-rebuild --print-errorlogs cursor_routing
ls -l *.pkg.tar.*
"
cd "$WORK"
@@ -0,0 +1,202 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index d74268b..f49ef59 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -10,6 +10,7 @@
#include "refresh_rate.h"
#include "waitable.h"
#include "Utils/TempFiles.h"
+#include "Utils/CursorRouting.h"
#include <cstring>
#include <unordered_map>
@@ -114,6 +115,7 @@ static bool IsGamescopeToplevel( wl_surface *pSurface ) {
#define LIBDECOR_USERDATA_TO_THIS(type, name) []<typename... Args> ( Args... args ) { type *pThing = (type *)std::get<sizeof...(Args)-1>(std::forward_as_tuple(args...)); CallWithAllButLast([&]<typename... Args2>(Args2... args2){ pThing->name(std::forward<Args2>(args2)...); }, std::forward<Args>(args)...); }
extern gamescope::ConVar<bool> cv_hdr_enabled;
+extern gamescope::ConVar<int> cv_cursor_composite;
namespace gamescope
{
@@ -2462,11 +2464,16 @@ namespace gamescope
if ( !m_pPointer )
return;
- if ( cv_wayland_mouse_warp_without_keyboard_focus )
- bUseHostCursor = m_bPointerLocked && !m_bKeyboardEntered && m_pDefaultCursorSurface;
- else
- bUseHostCursor = !m_bKeyboardEntered && m_pDefaultCursorSurface;
-
+ bUseHostCursor = CursorShouldUseHostFallback(
+ cv_wayland_mouse_warp_without_keyboard_focus.Get(), m_bPointerLocked,
+ m_bKeyboardEntered, m_pDefaultCursorSurface != nullptr );
+
+ if ( !CursorShouldBeForwardedToHost( cv_cursor_composite.Get(), bUseHostCursor ) )
+ {
+ wl_pointer_set_cursor( m_pPointer, m_uPointerEnterSerial, nullptr, 0, 0 );
+ return;
+ }
+
if ( bUseHostCursor )
{
wl_pointer_set_cursor( m_pPointer, m_uPointerEnterSerial, m_pDefaultCursorSurface, m_pDefaultCursorInfo->uXHotspot, m_pDefaultCursorInfo->uYHotspot );
diff --git a/src/Utils/CursorRouting.h b/src/Utils/CursorRouting.h
new file mode 100644
index 0000000..d7c21da
--- /dev/null
+++ b/src/Utils/CursorRouting.h
@@ -0,0 +1,36 @@
+#pragma once
+
+namespace gamescope
+{
+ constexpr bool CursorShouldBeComposited( int cursorCompositeMode, bool forceRelativeMouse,
+ bool hasFocus, bool hasNestedHints, bool nestedPaintsCursor )
+ {
+ if ( cursorCompositeMode == 2 )
+ return true;
+ if ( cursorCompositeMode == 0 )
+ return false;
+ if ( forceRelativeMouse )
+ return true;
+ if ( !hasFocus )
+ return false;
+ return !hasNestedHints || nestedPaintsCursor;
+ }
+
+ constexpr bool CursorShouldUseHostFallback( bool warpWithoutKeyboardFocus, bool pointerLocked,
+ bool keyboardEntered, bool hasDefaultCursor )
+ {
+ if ( warpWithoutKeyboardFocus )
+ return pointerLocked && !keyboardEntered && hasDefaultCursor;
+ return !keyboardEntered && hasDefaultCursor;
+ }
+
+ constexpr bool CursorShouldBeForwardedToHost( int cursorCompositeMode, bool useHostCursorFallback )
+ {
+ return cursorCompositeMode != 2 || useHostCursorFallback;
+ }
+
+ constexpr bool CursorImageShouldBePainted( bool imageEmpty, bool cursorHidden )
+ {
+ return !imageEmpty && !cursorHidden;
+ }
+}
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 18b799e..2e90466 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -99,6 +99,7 @@
#include "BufferMemo.h"
#include "vrclient_detect.h"
#include "Utils/Process.h"
+#include "Utils/CursorRouting.h"
#include "wlr_begin.hpp"
#include "wlr/types/wlr_pointer_constraints_v1.h"
@@ -2353,7 +2354,7 @@ void MouseCursor::GetDesiredSize( int& nWidth, int &nHeight )
void MouseCursor::paint(steamcompmgr_win_t *window, steamcompmgr_win_t *fit, struct FrameInfo_t *frameInfo)
{
- if ( m_imageEmpty || wlserver.bCursorHidden )
+ if ( !gamescope::CursorImageShouldBePainted( m_imageEmpty, wlserver.bCursorHidden ) )
return;
int winX = x();
@@ -3025,23 +3026,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" };
bool ShouldDrawCursor()
{
- if ( cv_cursor_composite == 2 )
- return true;
-
- if ( cv_cursor_composite == 0 )
- return false;
-
- if ( g_bForceRelativeMouse )
- return true;
-
global_focus_t *pFocus = GetCurrentFocus();
- if ( !pFocus )
- return false;
-
- if ( !pFocus->GetNestedHints() )
- return true;
-
- return pFocus->GetNestedHints()->ShouldPaintCursor();
+ gamescope::INestedHints *pNestedHints = pFocus ? pFocus->GetNestedHints() : nullptr;
+ return gamescope::CursorShouldBeComposited( cv_cursor_composite.Get(), g_bForceRelativeMouse,
+ pFocus != nullptr, pNestedHints != nullptr,
+ pNestedHints && pNestedHints->ShouldPaintCursor() );
}
static void ForwardVROverlayTargets()
diff --git a/tests/meson.build b/tests/meson.build
index 9f73a33..1ccdf7d 100644
--- a/tests/meson.build
+++ b/tests/meson.build
@@ -8,7 +8,7 @@ endforeach
gamescope_tests = executable(
'gamescope_tests',
- unittest_src + ['test_convar.cpp', 'test_focus_placement.cpp', 'test_mangoapp_config.cpp', 'test_mangoapp_control.cpp', 'test_process.cpp', 'test_upscale.cpp', 'test_utils_parsers.cpp', 'test_utils_string.cpp', 'test_vrclient_detect.cpp'],
+ unittest_src + ['test_convar.cpp', 'test_cursor_routing.cpp', 'test_focus_placement.cpp', 'test_mangoapp_config.cpp', 'test_mangoapp_control.cpp', 'test_process.cpp', 'test_upscale.cpp', 'test_utils_parsers.cpp', 'test_utils_string.cpp', 'test_vrclient_detect.cpp'],
include_directories: [srcdir, sol2_include],
dependencies: [catch2_dep, luajit_dep, cap_dep, drm_dep, glm_dep, wlroots_dep],
cpp_args: gamescope_cpp_args,
@@ -17,6 +17,7 @@ gamescope_tests = executable(
reaper_test_helper = executable('reaper_test_helper', 'reaper_test_helper.cpp')
test('convar', gamescope_tests, args: ['[convar]'])
+test('cursor_routing', gamescope_tests, args: ['[cursor_routing]'])
test('focus_placement', gamescope_tests, args: ['[focus_placement]'])
test('mangoapp_config', gamescope_tests, args: ['[mangoapp_config]'])
test('mangoapp_control', gamescope_tests, args: ['[mangoapp_control]'])
diff --git a/tests/test_cursor_routing.cpp b/tests/test_cursor_routing.cpp
new file mode 100644
index 0000000..9c622db
--- /dev/null
+++ b/tests/test_cursor_routing.cpp
@@ -0,0 +1,42 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include "Utils/CursorRouting.h"
+
+using namespace gamescope;
+
+TEST_CASE("nested cursor composition can be forced without changing the default", "[cursor_routing]")
+{
+ REQUIRE_FALSE( CursorShouldBeComposited( 1, false, true, true, false ) );
+ REQUIRE( CursorShouldBeComposited( 2, false, true, true, false ) );
+
+ REQUIRE( CursorShouldBeComposited( 1, true, true, true, false ) );
+ REQUIRE( CursorShouldBeComposited( 1, false, true, false, false ) );
+ REQUIRE_FALSE( CursorShouldBeComposited( 0, true, true, false, true ) );
+ REQUIRE_FALSE( CursorShouldBeComposited( 1, false, false, false, false ) );
+ REQUIRE( CursorShouldBeComposited( 2, false, false, true, false ) );
+}
+
+TEST_CASE("manual composition retains only the no-focus default cursor fallback", "[cursor_routing]")
+{
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, false ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 2, true ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 1, false ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 0, false ) );
+}
+
+TEST_CASE("host cursor fallback follows the keyboard-focus and lock defaults", "[cursor_routing]")
+{
+ REQUIRE( CursorShouldUseHostFallback( true, true, false, true ) );
+ REQUIRE_FALSE( CursorShouldUseHostFallback( true, false, false, true ) );
+ REQUIRE_FALSE( CursorShouldUseHostFallback( true, true, true, true ) );
+ REQUIRE_FALSE( CursorShouldUseHostFallback( true, true, false, false ) );
+ REQUIRE( CursorShouldUseHostFallback( false, false, false, true ) );
+ REQUIRE_FALSE( CursorShouldUseHostFallback( false, true, true, true ) );
+}
+
+TEST_CASE("an empty or hidden client cursor stays hidden when composition is forced", "[cursor_routing]")
+{
+ REQUIRE_FALSE( CursorImageShouldBePainted( true, false ) );
+ REQUIRE_FALSE( CursorImageShouldBePainted( false, true ) );
+ REQUIRE( CursorImageShouldBePainted( false, false ) );
+}
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p10
GAMESCOPE_SHA256=e8e2433ae618458135ec271a30af7e80b282ff41f9931286e9bbad614838eca0
GAMESCOPE_TAG=gamescope-3.16.29-cursor-045e5a31-qa
GAMESCOPE_SHA256=76929e93804450e7352421b76a457c825a6251de8b704d942c363a211bd99424
+17 -6
View File
@@ -26,7 +26,7 @@ for arch in x86_64 i386; do
fi
done
done
for target in x86_64/faultreport i386/faultreport x86_64/thunkaudit; do
for target in x86_64/faultreport i386/faultreport; do
arch=${target%/*} name=${target#*/}
case $arch in
x86_64) bits=-m64 ;;
@@ -41,13 +41,24 @@ for target in x86_64/faultreport i386/faultreport x86_64/thunkaudit; do
exit 1
fi
done
lib=$out/x86_64/libwebkitinput.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/webkitinput.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
exit 1
fi
stub=$(mktemp -d)
gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
gcc -m64 -shared -nostdlib -Wl,-z,nodelete -Wl,--no-as-needed \
-o "$out/x86_64/libvulkan-thunk.so" -x c /dev/null -x none "$stub/libvulkan.so.1"
lib=$out/x86_64/libvulkan-thunk.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
-o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl
rm -rf "$stub"
if ! objdump -p "$out/x86_64/libvulkan-thunk.so" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! objdump -p "$out/x86_64/libvulkan-thunk.so" | grep -q 'FLAGS_1 *0x0*8$'; then
echo "$out/x86_64/libvulkan-thunk.so must be nodelete and need only the Vulkan thunk" >&2
strip --strip-unneeded "$lib"
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2
exit 1
fi
+9
View File
@@ -27,6 +27,15 @@ 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] /'
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
[Desktop Entry]
Type=Application
Name=Steam x86-64 (FEX, experimental)
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
Exec=qterminal -e /usr/local/bin/droiddeck-steam-x64
Icon=steam
Categories=System;
ENTRY
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
-40
View File
@@ -1,40 +0,0 @@
#if !defined(__x86_64__)
#error thunkaudit is built for x86_64 guests only
#endif
#define LA_SER_ORIG 0x01
static const char vulkan_thunk[] = "/usr/lib/x86_64-linux-gnu/libvulkan.so.1";
static const char vulkan_pin[] = "/usr/lib/x86_64-linux-gnu/droiddeck/libvulkan-thunk.so";
static int same(const char *a, const char *b)
{
while (*a && *a == *b) {
a++;
b++;
}
return *a == *b;
}
static const char *base_name(const char *path)
{
const char *name = path;
for (; *path; path++)
if (*path == '/')
name = path + 1;
return name;
}
__attribute__((visibility("default"))) unsigned int la_version(unsigned int version)
{
return version;
}
__attribute__((visibility("default"))) char *la_objsearch(const char *name, unsigned long *cookie, unsigned int flag)
{
const char *file = base_name(name);
(void)cookie;
if (flag == LA_SER_ORIG && !same(name, vulkan_thunk) && (same(file, "libvulkan.so.1") || same(file, "libvulkan.so")))
return (char *)vulkan_pin;
return (char *)name;
}
+88
View File
@@ -0,0 +1,88 @@
#include <dlfcn.h>
#include <stddef.h>
#include <string.h>
#ifndef VULKAN_THUNK
#define VULKAN_THUNK "/usr/lib/x86_64-linux-gnu/libvulkan.so.1"
#endif
#define VK_INCOMPLETE 5
#define VK_ERROR_INITIALIZATION_FAILED (-3)
#define EXTENSIONS 128
typedef int VkResult;
typedef void (*Function)(void);
typedef struct {
char extensionName[256];
unsigned int specVersion;
} VkExtensionProperties;
typedef VkResult (*Enumerate)(const char *, unsigned int *, VkExtensionProperties *);
typedef Function (*ProcAddr)(void *, const char *);
/* The driver cannot enumerate devices for an instance with VK_KHR_display, and gamescope's WSI layer aborts on that. */
static const char *const hidden_extensions[] = {
"VK_KHR_display",
"VK_KHR_get_display_properties2",
"VK_EXT_direct_mode_display",
"VK_EXT_acquire_xlib_display",
"VK_EXT_acquire_drm_display",
"VK_EXT_display_surface_counter",
};
static void *thunk(const char *name)
{
void *library = dlopen(VULKAN_THUNK, RTLD_NOW | RTLD_NOLOAD);
void *found = library ? dlsym(library, name) : NULL;
if (library)
dlclose(library);
return found;
}
static int hidden(const char *name)
{
for (size_t i = 0; i < sizeof(hidden_extensions) / sizeof(hidden_extensions[0]); i++)
if (!strcmp(name, hidden_extensions[i]))
return 1;
return 0;
}
__attribute__((visibility("default"))) VkResult vkEnumerateInstanceExtensionProperties(const char *layer, unsigned int *count,
VkExtensionProperties *properties)
{
static Enumerate real;
VkExtensionProperties all[EXTENSIONS];
unsigned int total = EXTENSIONS, kept = 0, room = properties ? *count : 0;
VkResult result;
if (!real)
real = (Enumerate)thunk("vkEnumerateInstanceExtensionProperties");
if (!real)
return VK_ERROR_INITIALIZATION_FAILED;
result = real(layer, &total, all);
if (result < 0)
return result;
for (unsigned int i = 0; i < total; i++) {
if (hidden(all[i].extensionName))
continue;
if (properties && kept < room)
memcpy(&properties[kept], &all[i], sizeof(all[i]));
kept++;
}
if (!properties) {
*count = kept;
return result;
}
*count = kept < room ? kept : room;
return kept > room ? VK_INCOMPLETE : result;
}
__attribute__((visibility("default"))) Function vkGetInstanceProcAddr(void *instance, const char *name)
{
static ProcAddr real;
if (!strcmp(name, "vkGetInstanceProcAddr"))
return (Function)vkGetInstanceProcAddr;
if (!strcmp(name, "vkEnumerateInstanceExtensionProperties"))
return (Function)vkEnumerateInstanceExtensionProperties;
if (!real)
real = (ProcAddr)thunk("vkGetInstanceProcAddr");
return real ? real(instance, name) : NULL;
}
+198
View File
@@ -0,0 +1,198 @@
#if !defined(__x86_64__)
#error webkitinput is built for x86_64 guests only
#endif
typedef struct _WebKitSettings WebKitSettings;
typedef struct _WebKitUserContentManager WebKitUserContentManager;
typedef struct _WebKitUserScript WebKitUserScript;
extern void g_object_set(void *object, const char *first_property, ...) __attribute__((weak));
extern void *g_object_get_data(void *object, const char *key) __attribute__((weak));
extern void g_object_set_data(void *object, const char *key, void *data) __attribute__((weak));
extern void *dlsym(void *handle, const char *symbol) __attribute__((weak));
extern unsigned gtk_key_snooper_install(int (*snooper)(void *, void *, void *), void *data) __attribute__((weak));
extern void *gtk_widget_get_toplevel(void *widget) __attribute__((weak));
extern void gtk_container_forall(void *container, void (*callback)(void *, void *), void *data) __attribute__((weak));
extern unsigned long gtk_container_get_type(void) __attribute__((weak));
extern unsigned long webkit_web_view_get_type(void) __attribute__((weak));
extern int g_type_check_instance_is_a(void *instance, unsigned long type) __attribute__((weak));
extern const char *webkit_web_view_get_uri(void *view) __attribute__((weak));
extern void webkit_web_view_run_javascript(void *view, const char *script, void *cancellable, void *callback,
void *data) __attribute__((weak));
extern WebKitUserScript *webkit_user_script_new(const char *source, int frames, int time,
const char *const *allow, const char *const *block) __attribute__((weak));
extern void webkit_user_script_unref(WebKitUserScript *script) __attribute__((weak));
static const char NAV_SCRIPT[] =
"(()=>{let open=-1e9,arrowAt=-1e9,ringed=null,ringOutline='',ringOffset='',settleTimer=0,settling=false,redirecting=false;"
"const shown=()=>[...document.querySelectorAll('[role=dialog],[role=alertdialog],[aria-modal=true],[role=menu]')]"
".some(e=>e.getClientRects().length);"
"const hidden=e=>{const r=e.getBoundingClientRect();if(!r.width||!r.height)return true;"
"for(let n=e;n&&n.nodeType===1;n=n.parentElement){const s=getComputedStyle(n);"
"if(s.visibility==='hidden'||+s.opacity<0.1)return true;}return false;};"
"const windowButton=e=>/^(Minimize|Maximize|Restore|Close) window$/.test(e.getAttribute('aria-label')||'');"
"const editing=e=>!!e&&e.nodeType===1&&(e.isContentEditable||"
"e.matches('input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]),textarea,select'));"
"const mainNav=()=>[...document.querySelectorAll('nav')].filter(n=>n.querySelectorAll('a[href]').length>1&&!hidden(n))"
".sort((a,b)=>a.getBoundingClientRect().y-b.getBoundingClientRect().y)[0];"
"const first=nav=>{const below=nav?nav.getBoundingClientRect().bottom:0,all=[];"
"for(const e of document.querySelectorAll('a[href],button,input,[role=button],[tabindex]')){"
"if(e.tabIndex<0||(nav&&nav.contains(e)))continue;const r=e.getBoundingClientRect();"
"if(r.top<below||r.bottom>innerHeight||windowButton(e)||hidden(e))continue;all.push({e,r});}"
"const big=all.filter(c=>c.r.width*c.r.height>=12000),list=big.length?big:all;"
"const key=c=>Math.round(c.r.top/8)*1e5+c.r.left;"
"list.sort((a,b)=>key(a)-key(b));return list.length?list[0].e:null;};"
"const big=e=>{const r=e.getBoundingClientRect();return r.width*r.height>=12000;};"
"const toward=(from,key,nav,small)=>{const r=from.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;let best=null,score=1e9;"
"for(const c of document.querySelectorAll('a[href],button,[role=button],[tabindex]')){if(c===from||c.tabIndex<0||(nav&&nav.contains(c))||from.contains(c)||c.contains(from))continue;"
"const q=c.getBoundingClientRect();if(!small&&q.width*q.height<12000)continue;const qx=q.left+q.width/2,qy=q.top+q.height/2;let along,across;"
"if(key==='ArrowDown'){along=q.top-r.bottom;across=qx-cx;}else if(key==='ArrowUp'){along=r.top-q.bottom;across=qx-cx;}"
"else if(key==='ArrowRight'){along=q.left-r.right;across=qy-cy;}else{along=r.left-q.right;across=qy-cy;}"
"if(along<-4)continue;const d=Math.max(along,0)+2*Math.abs(across);if(d<score&&!windowButton(c)&&!hidden(c)){score=d;best=c;}}return best;};"
"const settle=()=>{const a=document.activeElement;if(editing(a)||shown())return;const nav=mainNav(),list=[];"
"for(const c of document.querySelectorAll('a[href],button,[role=button],[tabindex]')){if(c.tabIndex<0||(nav&&nav.contains(c)))continue;"
"const r=c.getBoundingClientRect();if(r.width*r.height>=12000&&r.top>=0&&r.left>=0&&r.bottom<=innerHeight&&r.right<=innerWidth)list.push({c,r});}"
"const key=x=>Math.round(x.r.top/8)*1e5+x.r.left;list.sort((x,y)=>key(x)-key(y));"
"for(const {c,r} of list){const hit=document.elementFromPoint(r.left+r.width/2,r.top+8);"
"if(hit&&(hit===c||c.contains(hit))&&!hidden(c)){arrowAt=performance.now();c.focus({preventScroll:true});return;}}};"
"const arm=()=>{clearTimeout(settleTimer);settleTimer=setTimeout(()=>{settling=false;settle();},200);};"
"addEventListener('scroll',()=>{if(settling)arm();},true);"
"const unring=()=>{if(ringed){ringed.style.outline=ringOutline;ringed.style.outlineOffset=ringOffset;ringed=null;}};"
"addEventListener('keydown',e=>{const k=e.key||'';if(k.startsWith('Arrow')){arrowAt=e.timeStamp;const a=document.activeElement;"
"if(!editing(a)&&!shown()){const nav=mainNav();"
"if(!a||a===document.body||hidden(a)||(k==='ArrowDown'&&nav&&nav.contains(a))){const f=first(nav);"
"if(f){e.preventDefault();e.stopImmediatePropagation();f.focus();f.scrollIntoView({block:'nearest'});}}"
"else if(big(a)&&!e.ctrlKey&&!e.altKey){let t=toward(a,k,nav);"
"if(!t&&(k==='ArrowUp'||k==='ArrowDown'))t=toward(a,k,nav,true);"
"if(t){e.preventDefault();e.stopImmediatePropagation();t.focus({preventScroll:true});t.scrollIntoView({block:'nearest',inline:'nearest'});}}}}"
"if(k==='Escape')open=shown()?e.timeStamp:-1e9;"
"if(e.code==='F13'){e.preventDefault();e.stopImmediatePropagation();settling=true;arm();}},true);"
"addEventListener('keydown',e=>{if(e.key!=='BrowserBack')return;e.preventDefault();e.stopImmediatePropagation();"
"const a=document.activeElement;if(editing(a)){a.blur();return;}"
"if(e.timeStamp-open>500)history.back();},true);"
"window.droiddeckTab=step=>{"
"const nav=mainNav();if(!nav)return;"
"const tabs=[...nav.querySelectorAll('a[href]')].filter(a=>!hidden(a)),part=p=>p.split('/')[1]||'';"
"const at=tabs.findIndex(a=>part(new URL(a.href).pathname)===part(location.pathname));"
"const to=tabs[Math.min(tabs.length-1,Math.max(0,at+step))];"
"if(at>=0&&to!==tabs[at]){to.click();to.blur();}};"
"const redirect=n=>{redirecting=true;try{n.focus();}finally{redirecting=false;}};"
"addEventListener('focusout',unring,true);"
"addEventListener('focusin',e=>{const t=e.target;if(!(t instanceof Element)||e.timeStamp-arrowAt>1000)return;"
"const back=e.relatedTarget instanceof Element&&e.relatedTarget.focus?e.relatedTarget:null;"
"if(!redirecting&&windowButton(t)){if(back)redirect(back);return;}"
"if(!redirecting&&hidden(t)){let a=t.parentElement;"
"while(a&&!(a.matches('a[href],button,[role=button],[tabindex]')&&!hidden(a)))a=a.parentElement;"
"if(a)redirect(a);else if(back)redirect(back);return;}"
"unring();ringed=(t.matches('input,textarea')&&t.closest('label'))||t;"
"ringOutline=ringed.style.outline;ringOffset=ringed.style.outlineOffset;"
"ringed.style.outline='3px solid #fff';ringed.style.outlineOffset='2px';},true);})();";
typedef struct {
int type;
void *window;
signed char send_event;
unsigned time;
unsigned state;
unsigned keyval;
} KeyEvent;
static void *launcher_view;
static void find_launcher_view(void *widget, void *data)
{
(void)data;
if (launcher_view)
return;
if (g_type_check_instance_is_a(widget, webkit_web_view_get_type())) {
const char *uri = webkit_web_view_get_uri(widget);
const char *prefix = "tauri:";
while (uri && *prefix && *uri == *prefix) {
uri++;
prefix++;
}
if (uri && !*prefix)
launcher_view = widget;
} else if (g_type_check_instance_is_a(widget, gtk_container_get_type())) {
gtk_container_forall(widget, find_launcher_view, 0);
}
}
static int switch_tab(void *grab, void *event_data, void *data)
{
KeyEvent *event = event_data;
(void)data;
if (!grab || event->type != 8 || !(event->state & 4) || (event->keyval != 0xff55 && event->keyval != 0xff56))
return 0;
launcher_view = 0;
find_launcher_view(gtk_widget_get_toplevel(grab), 0);
if (!launcher_view)
return 0;
webkit_web_view_run_javascript(launcher_view, event->keyval == 0xff56 ? "window.droiddeckTab&&droiddeckTab(1)"
: "window.droiddeckTab&&droiddeckTab(-1)",
0, 0, 0);
return 1;
}
static void watch_tab_keys(void)
{
static int watching;
if (watching || !gtk_key_snooper_install || !gtk_widget_get_toplevel || !gtk_container_forall ||
!gtk_container_get_type || !webkit_web_view_get_type || !g_type_check_instance_is_a ||
!webkit_web_view_get_uri || !webkit_web_view_run_javascript)
return;
watching = 1;
gtk_key_snooper_install(switch_tab, 0);
}
static void set(WebKitSettings *settings, const char *setter, const char *property, int value)
{
static int setting;
if (setting) {
void (*next)(WebKitSettings *, int) = dlsym ? (void (*)(WebKitSettings *, int))dlsym((void *)-1l, setter) : 0;
if (next)
next(settings, value);
return;
}
if (!g_object_set)
return;
setting = 1;
g_object_set(settings, property, value, "enable-smooth-scrolling", 0, "enable-spatial-navigation", 1, (const char *)0);
setting = 0;
}
#define SETTER(name, property) \
__attribute__((visibility("default"))) void webkit_settings_set_##name(WebKitSettings *settings, int value) \
{ \
set(settings, "webkit_settings_set_" #name, property, value); \
}
SETTER(enable_javascript, "enable-javascript")
SETTER(enable_developer_extras, "enable-developer-extras")
SETTER(enable_webgl, "enable-webgl")
SETTER(enable_webaudio, "enable-webaudio")
SETTER(enable_page_cache, "enable-page-cache")
SETTER(javascript_can_access_clipboard, "javascript-can-access-clipboard")
SETTER(javascript_can_open_windows_automatically, "javascript-can-open-windows-automatically")
SETTER(enable_back_forward_navigation_gestures, "enable-back-forward-navigation-gestures")
__attribute__((visibility("default"))) void webkit_user_content_manager_add_script(WebKitUserContentManager *manager,
WebKitUserScript *script)
{
static void (*next)(WebKitUserContentManager *, WebKitUserScript *);
if (!next && dlsym)
next = (void (*)(WebKitUserContentManager *, WebKitUserScript *))dlsym((void *)-1l, "webkit_user_content_manager_add_script");
if (!next)
return;
watch_tab_keys();
if (g_object_get_data && g_object_set_data && webkit_user_script_new && webkit_user_script_unref &&
!g_object_get_data(manager, "droiddeck-nav")) {
g_object_set_data(manager, "droiddeck-nav", (void *)1);
WebKitUserScript *nav = webkit_user_script_new(NAV_SCRIPT, 1, 0, 0, 0);
if (nav) {
next(manager, nav);
webkit_user_script_unref(nav);
}
}
next(manager, script);
}
@@ -21,6 +21,7 @@ Requests: ping, exec, focus, cdp, quit. Each answer is {"ok": true, ...} or
import base64
import json
import math
import re
import os
import selectors
import signal
@@ -177,6 +178,11 @@ class X:
return list(struct.unpack("<%dI" % n, data))
return data
def cardinals(self, window, name, values):
self.s.sendall(struct.pack("<BBHIIIB3xI", 18, 0, 6 + len(values), window,
self.atom(name), self.atom("CARDINAL"), 32, len(values))
+ struct.pack("<%dI" % len(values), *values))
def windows(x):
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
@@ -249,6 +255,67 @@ def focus_snapshot():
return snap
STEAM_APP_CLASS = re.compile(r"steam_app_(\d+)$")
def tag_game_windows(snap):
if os.environ.get("BL_STEAM_CLIENT_ARCH") != "x86_64":
return False
tagged = False
for display, wins in snap.get("displays", {}).items():
if display == os.environ.get("DISPLAY"):
continue
for win in wins:
match = STEAM_APP_CLASS.match(win.get("class") or "")
if not match or win.get("appId") or win.get("map") != "viewable" or win.get("overrideRedirect"):
continue
try:
done = subprocess.run(["xprop", "-display", display, "-id", str(win["window"]), "-f", "STEAM_GAME", "32c",
"-set", "STEAM_GAME", match.group(1)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5).returncode == 0
except (OSError, subprocess.TimeoutExpired):
done = False
log("game window %s on %s tagged STEAM_GAME=%s: %s" % (win["window"], display, match.group(1), "ok" if done else "failed"))
tagged = tagged or done
return tagged
def vr_scene_app(path=Path('/run/droiddeck/droiddeck-steamvr/scene-focus.json'), proc=Path('/proc')):
"""Only a live SteamVR scene with its dashboard hidden may claim game focus."""
try:
state = json.loads(path.read_text())
server, scene = int(state['serverPid']), int(state['scenePid'])
if server <= 0 or scene <= 0 or state['dashboard'] is not False:
return None
if (proc / str(server) / 'comm').read_text().strip() != 'vrserver':
return None
for entry in (proc / str(scene) / 'environ').read_bytes().split(b'\0'):
if entry.startswith(b'SteamAppId='):
app = int(entry.split(b'=', 1)[1])
return app if 0 < app < 2**32 else None
except (OSError, ValueError, TypeError, KeyError):
pass
return None
class VrSceneFocus:
def __init__(self):
self.original = None
self.written = None
def order(self, current, focusable, app):
if app is None or app not in focusable:
restore = self.original if self.written == current else None
self.original = self.written = None
return restore
if current and current[0] == app:
return None
if self.original is None:
self.original = list(current)
self.written = [app] + [item for item in current if item != app]
return self.written
class FocusWatcher(threading.Thread):
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
the windows do (a window can change without any root property moving)."""
@@ -259,19 +326,35 @@ class FocusWatcher(threading.Thread):
self.changed = threading.Event()
self.last = None
self.seq = 0
self.vr_focus = VrSceneFocus()
def run(self):
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
last_app, last_snapshot = None, 0
while True:
self.changed.wait(timeout=5)
notified = self.changed.wait(timeout=0.5)
self.changed.clear()
app = vr_scene_app()
if not notified and app == last_app and time.monotonic() - last_snapshot < 5:
continue
last_app, last_snapshot = app, time.monotonic()
time.sleep(0.2)
try:
snap = focus_snapshot()
order = self.vr_focus.order(snap.get('baselayerAppIds', []), snap.get('focusableApps', []), app)
if order is not None:
x = X(os.environ['DISPLAY'])
try:
x.cardinals(x.root, 'GAMESCOPECTRL_BASELAYER_APPID', order)
finally:
x.close()
except (OSError, AgentError) as e:
log("focus snapshot failed: %s" % e)
time.sleep(2)
continue
if tag_game_windows(snap):
self.changed.set()
continue
body = {k: v for k, v in snap.items() if k != "t"}
if body == self.last:
continue
@@ -477,6 +560,80 @@ def steam_selection(agent_dir, timeout=5):
return {"appId": int(value)}
def steam_shortcut_app_id(game_id):
"""Return the 32-bit app id in Steam's shortcut CGameID form, or None for other ids.
DroidDeck's shortcut IDs are `(appid << 32) | 0x02000000`. The URL still needs that full
CGameID for RunGame; the app-details API separately needs the unsigned 32-bit app id.
"""
if not isinstance(game_id, str) or not game_id.isascii() or not game_id.isdigit():
return None
try:
game_id_value = int(game_id)
except ValueError:
return None
if str(game_id_value) != game_id or not 0 < game_id_value <= 0xFFFFFFFFFFFFFFFF:
return None
if game_id_value <= 0xFFFFFFFF or game_id_value & 0xFFFFFFFF != 0x02000000:
return None
app_id = game_id_value >> 32
return app_id if 0 < app_id <= 0xFFFFFFFF else None
def wait_for_steam_shortcut_overview(agent_dir, game_id, timeout=45):
"""Wait until Steam can map a shortcut CGameID to its 32-bit app overview."""
app_id = steam_shortcut_app_id(game_id)
if app_id is None:
return {"supported": False, "ready": False}
timeout = request_timeout({"timeout": timeout}, 45)
deadline = time.monotonic() + timeout
expression = """(() => {
const store = globalThis.appStore;
if (typeof store?.GetAppOverviewByGameID !== 'function') return null;
const overview = store.GetAppOverviewByGameID(%s);
return overview == null ? null : String(overview.appid);
})()""" % json.dumps(game_id)
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
result = cdp_eval(agent_dir, expression, await_promise=False,
timeout=min(5, max(0.25, remaining)))
if result.get("value") == str(app_id):
return {"supported": True, "ready": True, "appId": app_id}
except AgentError as error:
if error.code not in ("NO_DEVTOOLS", "DEVTOOLS_UNREACHABLE", "NO_TARGET", "TIMEOUT"):
raise
time.sleep(min(0.25, max(0, deadline - time.monotonic())))
raise AgentError("STEAM_OVERVIEW_TIMEOUT", "Steam did not load shortcut app overview %d" % app_id)
def steam_shortcut_state(agent_dir, game_id, timeout=6):
if steam_shortcut_app_id(game_id) is None:
return "not-shortcut"
timeout = request_timeout({"timeout": timeout}, 6)
deadline = time.monotonic() + timeout
expression = """(() => {
const store = globalThis.appStore;
if (typeof store?.GetAppOverviewByGameID !== 'function' || !store.m_bIsInitialized) return 'loading';
if (store.GetAppOverviewByGameID(%s) != null) return 'ready';
return store.allApps.some(app => app.app_type == 1073741824) ? 'missing' : 'loading';
})()""" % json.dumps(game_id)
state = "loading"
while True:
try:
state = cdp_eval(agent_dir, expression, await_promise=False,
timeout=min(5, max(0.25, deadline - time.monotonic()))).get("value") or "loading"
except AgentError as error:
if error.code not in ("NO_DEVTOOLS", "DEVTOOLS_UNREACHABLE", "NO_TARGET", "TIMEOUT"):
raise
state = "loading"
if state == "ready" or time.monotonic() >= deadline:
return state
time.sleep(min(0.5, max(0, deadline - time.monotonic())))
def game_pids(app_id):
"""Our processes started for this Steam app (Steam sets SteamAppId / SteamGameId in their
@@ -740,6 +897,43 @@ def main(argv):
if not base:
print("BL_LAUNCH_DIR is not set", file=sys.stderr)
return 2
if argv and argv[0] == "--wait-steam-shortcut-overview":
if len(argv) not in (2, 3):
print("usage: droiddeck-agent --wait-steam-shortcut-overview <cgameid> [timeout-seconds]", file=sys.stderr)
return 2
timeout = argv[2] if len(argv) == 3 else 45
try:
prepared = wait_for_steam_shortcut_overview(Path(base) / "agent", argv[1], timeout)
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: shortcut overview was not ready: %s" % error, file=sys.stderr)
return 1
if not prepared["supported"]:
print("droiddeck-agent: id is not a DroidDeck shortcut CGameID")
return 3
print("droiddeck-agent: Steam overview is ready for shortcut app %d" % prepared["appId"])
return 0
if argv and argv[0] == "--steam-asleep":
expression = """(() => {
const store = globalThis.SuspendResumeStore;
return store ? (store.m_bSuspending ? 'yes' : 'no') : 'unknown';
})()"""
try:
state = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=3).get("value") or "unknown"
except (AgentError, OSError, ValueError):
state = "unknown"
print(state)
return {"yes": 0, "no": 5}.get(state, 1)
if argv and argv[0] == "--steam-shortcut-state":
if len(argv) not in (2, 3):
print("usage: droiddeck-agent --steam-shortcut-state <cgameid> [timeout-seconds]", file=sys.stderr)
return 2
try:
state = steam_shortcut_state(Path(base) / "agent", argv[1], argv[2] if len(argv) == 3 else 6)
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: could not ask the client about the shortcut: %s" % error, file=sys.stderr)
return 1
print(state)
return {"ready": 0, "missing": 4, "not-shortcut": 3}.get(state, 1)
serve(Path(base) / "agent", focus="--no-focus" not in argv)
return 0
@@ -4,8 +4,10 @@ import re
import sys
HOME = os.environ.get("HOME", "/root")
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam")
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd", "SD Games"))
X64 = os.environ.get("BL_STEAM_CLIENT_ARCH") == "x86_64"
CLIENT_HOME = (os.environ.get("BL_X64_HOME") or os.path.join(HOME, ".droiddeck-x64")) if X64 else HOME
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(CLIENT_HOME, ".local/share/Steam")
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd/x86-64" if X64 else "/mnt/droiddeck-sd", "SD Games"))
NOT_GAMES = {228980, 1070560, 1391110, 1493710, 1628350, 3127680, 4183110, 4185400, 4427310, 4628740}
APPS_DIR = os.path.join(HOME, ".local/share/applications")
PREFIX = "droiddeck-game-"
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
[ -n "${LD_PRELOAD:-}" ] && export DROIDDECK_STEAM_PRELOAD="$LD_PRELOAD"
unset LD_PRELOAD LD_LIBRARY_PATH
exec /usr/bin/python3 -I /usr/local/bin/droiddeck-epic run
+152 -23
View File
@@ -28,15 +28,25 @@ URUNTIME = "/usr/local/lib/droiddeck/uruntime"
HOST_PRELOAD = "/etc/ld.so.preload"
FEX_APPID = "3127680"
SNIPER_APPID = "1628350"
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper"}
SLR4_APPID = "4183110"
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"}
MARKER = ".droiddeck-fex"
LAYOUT = 1
ROOTFS_LAYOUT = 1
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
PROVIDED = frozenset((
"ld-linux-x86-64.so.2", "ld-linux.so.2", "libc.so.6", "libm.so.6", "libmvec.so.1", "libpthread.so.0", "libdl.so.2",
"librt.so.1", "libutil.so.1", "libresolv.so.2", "libanl.so.1", "libBrokenLocale.so.1", "libnsl.so.1",
"libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1",
"libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1",
))
GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$")
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so")
FAULT_REPORT = "libfaultreport.so"
THUNK_AUDIT = "libthunkaudit.so"
THUNK_AUDIT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + THUNK_AUDIT
VULKAN_PIN = "libvulkan-thunk.so"
VULKAN_PIN_DIR = "lib/x86_64-linux-gnu/droiddeck/vulkan"
VULKAN_THUNK = "libvulkan-guest.so"
RUNTIME_LIBRARIES = (("libc.so.6", b"GLIBC_"), ("libstdc++.so.6", b"GLIBCXX_"))
VERSION_NAME = re.compile(rb"GLIBC(?:XX)?_[0-9][0-9.]*[0-9]")
@@ -164,15 +174,15 @@ def platform_version(path):
return tuple(int(part) for part in re.findall(r"\d+", os.path.basename(path)))
def runtime_platform():
runtime = app_dir(SNIPER_APPID)
def runtime_platform(appid=SNIPER_APPID, prefix="sniper_platform_"):
runtime = app_dir(appid)
if not runtime:
return None
try:
entries = os.listdir(runtime)
except OSError:
return None
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith("sniper_platform_")]
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith(prefix)]
platforms = [path for path in platforms if os.path.isdir(os.path.join(path, "files"))
and os.path.isfile(os.path.join(path, "usr-mtree.txt.gz"))]
return max(platforms, key=platform_version, default=None)
@@ -234,6 +244,75 @@ def materialize(platform):
return True
def graphics_platform():
return runtime_platform(SLR4_APPID, "steamrt4_platform_")
def provides_newer(base, provider):
for name, prefix in RUNTIME_LIBRARIES:
ours = {v for v in version_names(os.path.join(base, "files/lib/x86_64-linux-gnu", name)) if v.startswith(prefix)}
theirs = {v for v in version_names(os.path.join(provider, "files/lib/x86_64-linux-gnu", name)) if v.startswith(prefix)}
if not ours or not theirs or not ours < theirs:
return False
return True
def mirror(source, provider, name, target):
if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)):
os.symlink(os.path.realpath(os.path.join(provider, name)), os.path.join(target, name))
return
path = os.path.join(source, name)
link = os.readlink(path) if os.path.islink(path) else None
if link and GLIBC_BUILD.match(os.path.basename(link)):
if name not in INTERPRETERS:
return
link = os.path.join(os.path.dirname(link), name)
if provider and GLIBC_BUILD.match(name):
return
if link and not link.startswith("/"):
os.symlink(link, os.path.join(target, name))
else:
os.symlink(os.path.realpath(path), os.path.join(target, name))
def build_rootfs(base, provider):
"""The runtime with glibc and libstdc++ taken from a newer one, which FEX's GL and Vulkan thunks are built against."""
base_files, provider_files = os.path.join(base, "files"), os.path.join(provider, "files")
rootfs = os.path.join(STATE, "rootfs")
stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "",
os.path.realpath(provider), read_text(os.path.join(provider_files, MARKER)) or "")
if read_text(os.path.join(rootfs, MARKER)) == stamp:
return False
for entry in os.listdir(STATE):
if entry.startswith("rootfs."):
shutil.rmtree(os.path.join(STATE, entry), ignore_errors=True)
tmp = "%s.%d.tmp" % (rootfs, os.getpid())
os.makedirs(tmp)
for entry in os.listdir(base_files):
if entry not in ("lib", "lib64", "usr", MARKER):
os.symlink(os.path.realpath(os.path.join(base_files, entry)), os.path.join(tmp, entry))
os.symlink(".", os.path.join(tmp, "usr"))
for top in ("lib", "lib64"):
source = os.path.join(base_files, top)
os.makedirs(os.path.join(tmp, top))
for entry in os.listdir(source) if os.path.isdir(source) else ():
path = os.path.join(source, entry)
if entry in ARCH_DIRS and os.path.isdir(path) and not os.path.islink(path):
provided = os.path.join(provider_files, top, entry)
os.makedirs(os.path.join(tmp, top, entry))
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}:
mirror(path, provided, name, os.path.join(tmp, top, entry))
else:
mirror(source, None, entry, os.path.join(tmp, top))
write_if_changed(os.path.join(tmp, MARKER), stamp)
old = "%s.%d.old" % (rootfs, os.getpid())
if os.path.lexists(rootfs):
os.rename(rootfs, old)
os.rename(tmp, rootfs)
shutil.rmtree(old, ignore_errors=True)
return True
def host_preloads():
listed = read_text(HOST_PRELOAD) or ""
return [name for name in PRELOAD_NAMES if name in listed]
@@ -247,10 +326,14 @@ def install_preloads(root):
if os.path.isfile(source):
copy_if_changed(source, os.path.join(root, libdir, "droiddeck", name))
shipped.setdefault(name, set()).add(arch)
for name in (THUNK_AUDIT, VULKAN_PIN):
source = os.path.join(PRELOADS, "x86_64", name)
if os.path.isfile(source):
copy_if_changed(source, os.path.join(root, "lib/x86_64-linux-gnu/droiddeck", name))
pin = os.path.join(PRELOADS, "x86_64", VULKAN_PIN)
if os.path.isfile(pin):
copy_if_changed(pin, os.path.join(root, VULKAN_PIN_DIR, "libvulkan.so.1"))
alias = os.path.join(root, VULKAN_PIN_DIR, "libvulkan.so")
if not os.path.islink(alias) or os.readlink(alias) != "libvulkan.so.1":
if os.path.lexists(alias):
os.unlink(alias)
os.symlink("libvulkan.so.1", alias)
wanted = [name for name in host_preloads() if name in shipped]
if len(shipped.get(FAULT_REPORT, ())) == len(GUEST_LIBDIRS):
wanted.append(FAULT_REPORT)
@@ -270,14 +353,16 @@ def write_config(fex, root):
def link_steam_sdk():
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
link = os.path.join(HOME, ".steam", sdk)
if os.path.lexists(link):
continue
want = "x86_64" if sdk == "sdk64" else "i386"
if elf_arch(os.path.join(link, "steamclient.so")) == want:
continue
for candidate in candidates:
directory = os.path.join(STEAM_ROOT, candidate)
if elf_arch(os.path.join(directory, "steamclient.so")) == want:
os.makedirs(os.path.dirname(link), exist_ok=True)
os.symlink(directory, link)
tmp = "%s.%d.tmp" % (link, os.getpid())
os.symlink(directory, tmp)
os.replace(tmp, link)
break
@@ -308,7 +393,7 @@ def request_install():
return []
def describe(fex, platform):
def describe(fex, platform, graphics=None):
return {
"fex": fex["bin"] if fex else None,
"server": fex["server"] if fex else None,
@@ -317,6 +402,7 @@ def describe(fex, platform):
"steamclient64": os.path.realpath(os.path.join(HOME, ".steam", "sdk64", "steamclient.so"))
if elf_arch(os.path.join(HOME, ".steam", "sdk64", "steamclient.so")) == "x86_64" else None,
"ready": bool(fex and fex["server"] and platform),
"graphics": graphics,
}
@@ -346,13 +432,27 @@ def prepare():
if materialize(platform):
say("prepared %s as the x86 runtime" % os.path.basename(platform))
install_preloads(root)
provider = graphics_platform()
if provider and materialize(provider):
say("prepared %s for the x86 runtime's C and C++ libraries" % os.path.basename(provider))
if not provider:
say("Steam Linux Runtime 4.0 (Steam app %s) is not installed yet; x86 games may not find their graphics drivers"
% SLR4_APPID)
elif not provides_newer(platform, provider):
say("%s has no newer C and C++ libraries than %s" % (os.path.basename(provider), os.path.basename(platform)))
provider = None
else:
if build_rootfs(platform, provider):
say("built the x86 runtime from %s with the C and C++ libraries of %s"
% (os.path.basename(platform), os.path.basename(provider)))
root = os.path.join(STATE, "rootfs")
write_config(fex, root)
fex["rootfs"] = root
try:
link_steam_sdk()
except OSError:
pass
status = describe(fex, platform)
status = describe(fex, platform, provider)
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
with contextlib.suppress(OSError):
os.unlink(WANTED)
@@ -422,8 +522,16 @@ def guest_environment(fex, env):
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
result["FEX_APP_DATA_LOCATION"] = data + "/"
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
# Valve's FEX-Emu binds its server socket under $STEAM_COMPAT_DATA_PATH/fex-emu whatever FEX_APP_DATA_LOCATION or
# FEX_SERVERSOCKETPATH say, and sun_path is 108 bytes: compatdata under the app's data folder is too long.
if result.get("STEAM_COMPAT_DATA_PATH"):
short = data if data != DATA_DIR else "/tmp/fex"
os.makedirs(short, exist_ok=True)
result["STEAM_COMPAT_DATA_PATH"] = short
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
# Mono's incremental Boehm collector corrupts its heap under FEX, so Unity games crash at their first collections.
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
else:
@@ -439,7 +547,7 @@ def guest_environment(fex, env):
result["FEX_THUNKCONFIG"] = os.path.join(CONFIG_DIR, "ThunksConfig.json")
preload = [part for part in split_paths(result.get("LD_PRELOAD")) if os.path.exists(part) and not is_arm(part)]
library_path = [part for part in (result.get("LD_LIBRARY_PATH") or "").split(":")
if part and "steamrtarm64" not in part and "aarch64" not in part]
if part and "arm64" not in part and "aarch64" not in part]
for name, parts in (("LD_PRELOAD", preload), ("LD_LIBRARY_PATH", library_path)):
if parts:
result[name] = ":".join(parts)
@@ -477,6 +585,7 @@ def vulkan_thunk_loads(fex, folder):
needed = version_names(os.path.join(fex["guest_thunks"], VULKAN_THUNK))
if not needed:
return False
needed |= version_names(os.path.join(PRELOADS, "x86_64", VULKAN_PIN))
found = bundled_libraries(folder)
for name, prefix in RUNTIME_LIBRARIES:
library = found.get(name) or os.path.join(fex["rootfs"], "lib/x86_64-linux-gnu", name)
@@ -503,9 +612,10 @@ def launch(command, env, mode, decide=None):
x86_64 = elf_arch(program) != "i386"
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
if thunks == "on" and x86_64 and all(os.path.isfile(os.path.join(PRELOADS, "x86_64", name)) for name in (THUNK_AUDIT, VULKAN_PIN)) \
if thunks == "on" and x86_64 and os.path.isfile(os.path.join(PRELOADS, "x86_64", VULKAN_PIN)) \
and vulkan_thunk_loads(fex, folder):
guest["LD_AUDIT"] = ":".join([THUNK_AUDIT_GUEST] + split_paths(guest.get("LD_AUDIT")))
# Any LD_AUDIT module makes Mono's garbage collector crash under FEX, so the Vulkan thunk is pinned by search path.
guest["LD_LIBRARY_PATH"] = ":".join(["/usr/" + VULKAN_PIN_DIR] + split_paths(guest.get("LD_LIBRARY_PATH")))
thunks = "on, its own Vulkan loader too"
say("running %s with %s (runtime %s, thunks %s)" % (program, fex["bin"], guest.get("FEX_ROOTFS", "none"), thunks))
return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest)
@@ -557,19 +667,38 @@ def extracted():
def want_fex():
with locked():
status = describe(fex_install(), runtime_platform())
status = describe(fex_install(), runtime_platform(), graphics_platform())
if not status["ready"]:
request_install()
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
XATTR_ONLY_NOISE = re.compile(r"^(proot (error|warning)|Failed to exec memfd|Further error messages of this type are suppressed)")
def only_xattrs_failed(errors):
seen = False
for line in errors.splitlines():
if "write_xattr" in line:
seen = True
elif re.search(r"fail|could not|cannot|error", line, re.I) and not XATTR_ONLY_NOISE.match(line):
return False
return seen
def extract(image):
image = os.path.abspath(image)
clear_extracted()
x86 = elf_arch(image) in X86.values()
if os.access(URUNTIME, os.X_OK):
status = subprocess.call([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL,
env=dict(os.environ, TARGET_APPIMAGE=image))
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=image))
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
if status == 2 and only_xattrs_failed(errors) and extracted() and os.path.lexists("squashfs-root/AppRun"):
say("uruntime could not keep the image's extended attributes; the files are unpacked")
status = 0
if status == 0 and extracted():
if x86:
want_fex()
@@ -586,7 +715,7 @@ def extract(image):
unsquashfs = shutil.which("unsquashfs")
if unsquashfs:
clear_extracted()
status = subprocess.call([unsquashfs, "-q", "-n", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
status = subprocess.call([unsquashfs, "-q", "-n", "-no-xattrs", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
stdout=subprocess.DEVNULL)
if status == 0:
if x86:
@@ -654,7 +783,7 @@ def main(argv):
return 0 if prepare() else 1
if action == "status":
with locked():
status = describe(fex_install(), runtime_platform())
status = describe(fex_install(), runtime_platform(), graphics_platform())
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
print(json.dumps(status, indent=2))
return 0 if status["ready"] else 1
@@ -181,6 +181,27 @@ def uninstall(app_id):
return rc
def prune():
inst = installation()
try:
unused = inst.list_unused_refs(None, None)
except GLib.Error as err:
emit(e="error", message=err.message)
return 1
if unused:
t, state = transaction(inst)
for r in unused:
t.add_uninstall(r.format_ref())
if run(t, state, report_done=False):
return 1
try:
inst.prune_local_repo(None)
except GLib.Error as err:
emit(e="warning", message=err.message)
emit(e="done", removed=len(unused))
return 0
def updatable(inst):
try:
return inst.list_installed_refs_for_update(None)
@@ -216,7 +237,7 @@ def updates():
def main():
if len(sys.argv) < 2:
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates|prune [app-id|file]\n")
return 2
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "install-bundle", "update"):
@@ -231,7 +252,9 @@ def main():
return update(args[0] if args else None)
if cmd == "updates":
return updates()
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
if cmd == "prune":
return prune()
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates|prune [app-id|file]\n")
return 2
@@ -25,8 +25,15 @@ WORK=/var/cache/droiddeck-flatpak
CONF=$WORK/pacman.conf
mkdir -p "$WORK/pkg" "$WORK/db" || fail "cannot create $WORK"
{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org \
https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do
OVERSEAS="https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org"
MAINLAND=""
for m in https://mirrors.tuna.tsinghua.edu.cn/archlinuxarm https://mirrors.ustc.edu.cn/archlinuxarm \
https://mirrors.bfsu.edu.cn/archlinuxarm https://mirrors.sjtug.sjtu.edu.cn/archlinuxarm; do
if curl -fsS -r 0-0 --connect-timeout 4 --max-time 8 -o /dev/null "$m/aarch64/core/core.db" 2>/dev/null; then
MAINLAND="$MAINLAND $m"
fi
done
{ for m in $MAINLAND $OVERSEAS; do
echo "Server = $m/\$arch/\$repo"; done
grep '^Server' /etc/pacman.d/mirrorlist 2>/dev/null; } > "$WORK/mirrorlist"
sed -e 's/^DownloadUser/#DownloadUser/' \
@@ -7,7 +7,7 @@ import subprocess
import sys
from pathlib import Path
SYNC_KEYS = ("BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
@@ -98,6 +98,14 @@ def godot_sentry(game):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def arkham_city_x87(game):
"""Batman: Arkham City (BatmanAC.exe, also started through BmLauncher.exe beside it) leans on x87
and stops with Unreal's "Fatal error!" right after start when FEX reduces its precision."""
if "batmanac.exe" in game.files:
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
def skip_red_launcher(command):
"""Cyberpunk 2077's prelauncher opens REDlauncher, a Qt WebEngine window that hands over to the
game half a minute later and then stays up beside it, well over a core busy for as long as the
@@ -243,36 +251,6 @@ def force_ssbs(command, env):
return env
def umu_capable(proton):
"""Whether this Proton's script has umu's launch without Steam: GE-Proton, Proton-CachyOS and
DroidDeck-Proton run umu.exe in place of steam.exe when UMU_ID is set; Valve's Proton does not."""
try:
with open(proton, encoding="utf-8", errors="replace") as source:
text = source.read()
except OSError:
return False
return "UMU_ID" in text and "umu.exe" in text
def start_without_steam(command, env, app_id):
"""DROIDDECK_NO_STEAM=1 (a game's Start without Steam): launch the game without Proton's
steam.exe, for games that close right away because of what it sets up. A Proton with umu's
launch gets UMU_ID - Proton still sets up the prefix, and a Steam game keeps its protonfixes
under its own id; any other Proton runs the game straight in the prefix (runinprefix)."""
if env.get("DROIDDECK_NO_STEAM", "").lower() not in ("1", "on", "true", "yes"):
return command, env
if len(command) < 3 or command[1] != "waitforexitandrun":
return command, env
if umu_capable(command[0]):
if not env.get("UMU_ID"):
steam_game = app_id is not None and int(app_id) < 2**31
env = dict(env, UMU_ID=app_id if steam_game else "0")
print("droiddeck-game-env: starting without Steam (umu.exe in place of steam.exe, UMU_ID=%s)" % env["UMU_ID"], file=sys.stderr)
return command, env
print("droiddeck-game-env: starting without Steam (this Proton has no umu launch: runinprefix)", file=sys.stderr)
return [command[0], "runinprefix"] + command[2:], env
EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGNORECASE)
@@ -283,7 +261,7 @@ def mark_install_scripts(command, env):
ones stop with an error."""
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
return
root = env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)]
scripts = [path for path in scripts if os.path.isfile(path)]
if not scripts:
@@ -300,6 +278,7 @@ def main():
if not command:
return 2
env = os.environ.copy()
mic_enabled = env.get("BL_MIC_ENABLED")
mark_install_scripts(command, env)
app_id = game_id(env)
if app_id:
@@ -328,8 +307,9 @@ def main():
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env = force_ssbs(command, env)
command, env = start_without_steam(command, env, app_id)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
@@ -5,10 +5,14 @@ Android owns device power. Suspend here pauses the guest through SessionService;
the app's Resume action thaws it and completes PrepareForSleep(false). Steam
must see this service before startup or it can stay black after its idle timer.
"""
import importlib.machinery
import importlib.util
import os
from pathlib import Path
import re
import subprocess
import sys
import threading
import uuid
import gi
@@ -22,6 +26,8 @@ INTERFACE = NAME + ".Manager"
UPOWER = "org.freedesktop.UPower"
UPOWER_ROOT = "/org/freedesktop/UPower"
NATIVE_PREPARE_MS = 1500
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
ASLEEP_WAIT = 6
INTROSPECTION = """
<node>
<interface name="org.freedesktop.login1.Manager">
@@ -78,6 +84,7 @@ class LoginManager:
if name == "CanSuspend":
reply.return_value(GLib.Variant("(s)", ("yes",)))
elif name in ("Suspend", "SuspendWithFlags"):
print("== login1: %s.%s asked by %s" % (interface.rsplit(".", 1)[-1], name, sender), flush=True)
if self.pending:
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
return
@@ -147,7 +154,7 @@ class LoginManager:
if file.get_basename() == self.wake.name or (other and other.get_basename() == self.wake.name):
if self.wake.exists():
self.wake.unlink(missing_ok=True)
self.resume(force=True)
self.woken()
if file.get_basename() == self.state.name or (other and other.get_basename() == self.state.name):
self.check_state()
@@ -169,6 +176,19 @@ class LoginManager:
self.resume()
return False
def woken(self):
if self.pending is not None:
self.resume(force=True)
return
threading.Thread(target=lambda: GLib.idle_add(self.replay_unless_awake, steam_asleep()), daemon=True).start()
def replay_unless_awake(self, asleep):
if asleep is False and self.pending is None:
print("== login1: Steam is awake; no sleep/wake replay", flush=True)
return False
self.resume(force=True)
return False
def resume(self, force=False):
if self.pending is None:
if force:
@@ -193,6 +213,24 @@ class LoginManager:
self.notify(False)
def steam_asleep():
try:
code = subprocess.run([str(AGENT), "--steam-asleep"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=ASLEEP_WAIT).returncode
except (OSError, subprocess.SubprocessError):
return None
return {0: True, 5: False}.get(code)
def load_netmanager():
path = Path(__file__).resolve().with_name("droiddeck-netmanager")
loader = importlib.machinery.SourceFileLoader("droiddeck_netmanager", str(path))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
def main():
directory = os.environ.get("BL_LAUNCH_DIR")
if not directory or not Path(directory).is_dir():
@@ -218,6 +256,8 @@ def main():
owners = [Gio.bus_own_name(Gio.BusType.SYSTEM, name, Gio.BusNameOwnerFlags.NONE, connected, acquired, lost)
for name in (NAME, UPOWER)]
if "--with-netmanager" in sys.argv[1:]:
owners.append(load_netmanager().own(loop))
try:
loop.run()
finally:
@@ -408,8 +408,7 @@ class NetworkManager:
self.bus.emit_signal(None, path, OBJECT_MANAGER, signal, body)
def main():
loop = GLib.MainLoop()
def own(loop):
state = {}
def acquired(bus, name):
@@ -419,7 +418,12 @@ def main():
print("== netmanager: the system bus is gone", file=sys.stderr)
loop.quit()
Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lost)
return Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lost)
def main():
loop = GLib.MainLoop()
own(loop)
loop.run()
@@ -13,7 +13,7 @@ RELEASES = "https://api.github.com/repos/%s/releases"
SOURCES = {
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
"droiddeck": ("The412Banner/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
}
USER_AGENT = "droiddeck-proton-extra"
NEED_BYTES = 4 * 1024 * 1024 * 1024
@@ -2,6 +2,7 @@
"""Runs a Windows program with the Proton the Steam client has chosen for it.
droiddeck-proton-run [--window] PROGRAM [ARGS...]
droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]]
The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it
sits in one's drive_c, or to a non-Steam shortcut that names it; any other program gets a prefix of
@@ -10,11 +11,15 @@ config.vdf picks the tool, else the client's default for all other titles ("0").
started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and
the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio.
--window keeps the program in the desktop's own window, drawn with WineD3D.
--app starts one game without the Steam client (its Start without Steam): a Steam game's default
Windows launch option from appinfo.vdf when no program is given, else the program in that
shortcut's own prefix, started in --dir with the shortcut's launch options (--options).
"""
import json
import os
import re
import runpy
import shlex
import struct
import sys
import zlib
@@ -249,6 +254,81 @@ def locate(program, root):
os.path.dirname(program), root, "own")
def split_words(text):
try:
return shlex.split(text or "")
except ValueError:
return (text or "").split()
def split_options(text):
"""A shortcut's launch options: NAME=value words before %command% go to the environment, the words
after it - or all of them, without %command% - are the program's arguments."""
words = split_words(text)
if "%command%" not in words:
return {}, words
at = words.index("%command%")
env = {}
for word in words[:at]:
name, equals, value = word.partition("=")
if equals and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
env[name] = value
return env, words[at + 1:]
def find_file(base, relative):
"""base/relative, matching each part without regard to case as Windows does."""
path = base
for part in [p for p in relative.replace("\\", "/").split("/") if p and p != "."]:
exact = os.path.join(path, part)
if part == ".." or os.path.exists(exact):
path = exact
continue
try:
match = next((name for name in sorted(os.listdir(path)) if name.lower() == part.lower()), None)
except OSError:
return None
if match is None:
return None
path = os.path.join(path, match)
return os.path.normpath(path)
def steam_install(appid, root):
for library in libraries(root):
found = re.search(r'"installdir"\s+"([^"]+)"',
read_text(os.path.join(library, "steamapps", "appmanifest_%s.acf" % appid)) or "")
if found:
return library, os.path.join(library, "steamapps", "common", found.group(1))
return None, None
def steam_launch(appid, root):
"""(target, program, arguments) for a Steam game's default Windows launch option, or None."""
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), {})
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"),
int(option["key"]) if option["key"].isdigit() else 0))
for option in options:
program = find_file(install, option["executable"])
if not program or not os.path.isfile(program):
continue
start = find_file(install, option["workingdir"]) if option["workingdir"] else None
target = Target(appid, os.path.join(library, "steamapps", "compatdata", str(appid)), install, library, "steam",
start if start and os.path.isdir(start) else os.path.dirname(program))
return target, program, split_words(option["arguments"])
return None
def shortcut_target(appid, program, start, root):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root,
"shortcut", start if start and os.path.isdir(start) else None)
def steam_launches(target, program, root):
"""Whether a launch option of the Steam game starts [program]: then Steam should start it."""
if target.kind != "steam":
@@ -292,24 +372,52 @@ def arguments(program, args):
def main(argv):
window = False
app, start, options = None, None, ""
while argv and argv[0].startswith("--"):
option = argv.pop(0)
if option == "--window":
window = True
elif option in ("--app", "--dir", "--options") and argv:
value = argv.pop(0)
if option == "--app":
app = value
elif option == "--dir":
start = value
else:
options = value
elif option == "--":
break
else:
say("unknown option %s" % option)
return 2
if not argv:
if app is not None and not (app.isdigit() and 0 < int(app) < 2 ** 32):
say("%s is not an app id" % app)
return 2
if not argv and app is None:
say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]")
return 2
program = os.path.abspath(argv[0])
if not os.path.isfile(program):
say("%s does not exist" % program)
return 2
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
target = locate(program, root)
extra, args = split_options(options)
if not argv:
if int(app) >= STEAM_APP_LIMIT:
say("shortcut %s needs its program" % app)
return 2
found = steam_launch(app, root)
if found is None:
say("Steam game %s is not installed, or has no Windows launch option" % app)
return 2
target, program, own = found
args = own + args
else:
program = os.path.abspath(argv[0])
if not os.path.isfile(program):
say("%s does not exist" % program)
return 2
args = args + argv[1:]
if app is not None and int(app) >= STEAM_APP_LIMIT:
target = shortcut_target(app, program, start, root)
else:
target = locate(program, root)
available = tools(root)
name, why = choose_tool(target.appid, mapping(root), available)
if name is None:
@@ -318,13 +426,15 @@ def main(argv):
folder, command = available[name]
os.makedirs(target.compatdata, exist_ok=True)
env = environment(os.environ, target, folder, root, window)
say("%s with %s (%s), %s prefix %s" % (program, name, why, target.kind, target.compatdata))
env.update(extra)
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
", without the Steam client" if app is not None else ""))
try:
os.chdir(target.start)
except OSError:
os.chdir(os.path.dirname(program))
entry = os.path.join(folder, command)
os.execve(entry, [entry, VERB] + arguments(program, argv[1:]), env)
os.execve(entry, [entry, VERB] + arguments(program, args), env)
if __name__ == "__main__":
@@ -6,9 +6,11 @@ LIBRARIES=${DROIDDECK_LIBRARIES-/mnt/droiddeck /mnt/droiddeck-sd}
redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
FNR == 1 { depth = 0; pending = "" }
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; pending = ""; next }
FNR == 1 { depth = 0; pending = ""; appid = "" }
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; proc[depth] = 0; pending = ""; next }
/^[[:space:]]*\}/ {
if (depth > 0 && key[depth] == "" && proc[depth] && appid != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
printf "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\%s\t%s\n", appid, name[depth]
if (depth > 0 && key[depth] != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
printf "%s\t%s\n", key[depth], name[depth]
if (depth > 0) depth--
@@ -16,8 +18,10 @@ read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
}
{
n = split($0, part, "\"")
if (n >= 5 && tolower(part[2]) == "appid" && part[4] ~ /^[0-9]+$/) { appid = part[4]; next }
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key[depth] = part[4]; next }
if (n >= 5 && tolower(part[2]) ~ /^process [0-9]+$/) {
proc[depth] = 1
program = tolower(part[4])
sub(/.*[\\\/]/, "", program)
if (program ~ /vulkan/) vulkan[depth] = 1
@@ -139,6 +143,51 @@ unseed() {
return 1
}
# The ledger lines whose values the registry still holds, in both views where we wrote both. A Proton
# update replaces its default_pfx system.reg but not our ledger beside it, and new prefixes copy both.
present() { awk -F'\t' '
NR == FNR {
path = $1
if (path != "vcrt") {
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
if (path == $1)
next
}
n++
line[n] = $0
need[n] = 0
if (path == "vcrt") {
for (a = split("x86 x64 arm64", arch, " "); a > 0; a--) {
runtime = "microsoft\\\\visualstudio\\\\14.0\\\\vc\\\\runtimes\\\\" arch[a]
key[n, ++need[n]] = "[software\\\\" runtime "]" SUBSEP "installed"
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" runtime "]" SUBSEP "installed"
}
} else {
both = substr(path, 1, 10) == "Software\\\\"
path = tolower(path)
key[n, ++need[n]] = "[" path "]" SUBSEP tolower($2)
if (both)
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)
}
for (j = 1; j <= need[n]; j++) wanted[key[n, j]] = 1
next
}
/^\[/ { section = tolower(substr($0, 1, index($0, "]"))) }
/^"/ {
value = substr($0, 2)
value = tolower(substr(value, 1, index(value, "\"=") - 1))
if ((section SUBSEP value) in wanted)
seen[section SUBSEP value] = 1
}
END {
for (i = 1; i <= n; i++) {
ok = 1
for (j = 1; j <= need[i]; j++) if (!(key[i, j] in seen)) ok = 0
if (ok) print line[i]
}
}
' - "$1"; }
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
@@ -166,6 +215,17 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
printf '%s\n' "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ]; then
declare -A held=()
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
if [ ${#held[@]} -lt ${#had[@]} ]; then
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
had=()
for line in "${!held[@]}"; do had[$line]=1; done
printf '%s\n' "${!had[@]}" >"$seeded"
fi
unset held
fi
missing=()
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
[ ${#missing[@]} -eq 0 ] && continue
@@ -33,9 +33,9 @@ prepare_locale() {
clear_stale_tmp() {
local running names=() n
running=$(pgrep -af 'steamwebhelper|steamrtarm64/steam|--type=|droiddeck-appimage-run|dbus-run-session|dbus-daemon.*--session|dbus-launch|kwin|plasmashell' 2>/dev/null)
running=$(pgrep -af 'steamwebhelper|steamrtarm64/steam|steamrt64/steam|--type=|droiddeck-appimage-run|dbus-run-session|dbus-daemon.*--session|dbus-launch|kwin|plasmashell' 2>/dev/null)
case $running in
*steamwebhelper* | *steamrtarm64/steam*) ;;
*steamwebhelper* | *steamrtarm64/steam* | *steamrt64/steam*) ;;
*) names+=(-o -name 'mangohud.????????' -o -name '.com.valvesoftware.Steam.??????'
-o -name 'steam_chrome_shmem_uid*' -o \( -type d -empty -name 'steam??????' \)) ;;
esac
@@ -56,13 +56,34 @@ clear_stale_tmp() {
}
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
steam_update_stuck() {
[ "$1" -lt 60 ] || steam_updates=0
steam_updates=$((steam_updates + 1))
[ "$steam_updates" -ge 3 ]
}
run_gamescope() (
local status_file child_status compositor_status
status_file=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steam-exit.XXXXXX") || exit 73
trap 'rm -f "$status_file"' EXIT
# Gamescope can return success when its primary child crashed.
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"
fi
exit "$compositor_status"
)
collect_steam_logs() {
[ -n "${BL_DEBUG_DIR:-}" ] || return 0
local steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
[ "${steam_x64:-0}" = 1 ] && steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
mkdir -p "$BL_DEBUG_DIR/steam" 2>/dev/null || return 0
[ -d "$steam_root/logs" ] && find "$steam_root/logs" -maxdepth 1 -type f -size -8192k \
-exec cp {} "$BL_DEBUG_DIR/steam/" \; 2>/dev/null
[ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
[ "${steam_x64:-0}" = 0 ] && [ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
local sync_store=$HOME/.local/share/droiddeck-esync sync_file
if [ -d "$sync_store" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-esync" 2>/dev/null; then
for sync_file in launches.log tools.tsv wanted.tsv prefixes.json; do
@@ -197,6 +218,9 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
fi
fi
if [ "$mode" = steam ]; then
export gamescope_cursor_composite=2
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
if [ "${BL_FPS:-0}" -gt 0 ]; then
@@ -221,6 +245,10 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
export BL_INSIDE=1
if [ "$mode" = steam ]; then
run_gamescope "${args[@]}" -- "$0" "$mode" "$@"
exit $?
fi
exec gamescope "${args[@]}" -- "$0" "$mode" "$@"
fi
@@ -275,6 +303,24 @@ case $mode in
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
fi
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
run_program() {
local rc=0 child sig forwarded=0
{ trap - INT QUIT; exec "$@"; } <&0 &
child=$!
for sig in TERM HUP INT; do
trap "kill -$sig $child 2>/dev/null; forwarded=1" "$sig"
done
while :; do
forwarded=0
rc=0
wait "$child" || rc=$?
[ "$forwarded" = 1 ] || break
done
if [ -n "${BL_LAUNCH_DIR:-}" ]; then
printf '%s\n' "$rc" > "$BL_LAUNCH_DIR/run-status.tmp" && mv -f "$BL_LAUNCH_DIR/run-status.tmp" "$BL_LAUNCH_DIR/run-status"
fi
exit "$rc"
}
fex=()
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $(od -An -tu2 -j18 -N2 "$target" 2>/dev/null | tr -d ' ') in
@@ -285,32 +331,67 @@ case $mode in
*.appimage)
export APPIMAGE_EXTRACT_AND_RUN=1
chmod +x "$target" 2>/dev/null
exec "${fex[@]}" "$target" "$@"
run_program "${fex[@]}" "$target" "$@"
;;
*.sh)
if [ -x /usr/local/bin/droiddeck-fex ]; then
exec /usr/local/bin/droiddeck-fex run --for "$target" -- bash "$target" "$@"
run_program /usr/local/bin/droiddeck-fex run --for "$target" -- bash "$target" "$@"
fi
exec bash "$target" "$@"
run_program bash "$target" "$@"
;;
*)
chmod +x "$target" 2>/dev/null
cd "$(dirname "$target")" && exec "${fex[@]}" "$target" "$@"
cd "$(dirname "$target")" && run_program "${fex[@]}" "$target" "$@"
;;
esac
;;
steam)
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
droiddeck-steam-install || exit $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
steam_x64=0
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
steam_cef_gpu=1
if [ "$steam_x64" = 1 ]; then
step "checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)"
# droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients.
_bl_x64_repair=0
[ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1
droiddeck-steam-install || exit $?
droiddeck-steam-install --sync steamdeck_publicbeta || step "could not update the arm64 client's parts; the x86-64 client keeps its own web helper"
step "checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)"
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || exit $?
step "x86-64 Steam client ready"
steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
steam_client=(droiddeck-steam-x64 --exec)
if [ "${BL_X64_X86_WEBHELPER:-0}" = 1 ] &&
! droiddeck-steam-x64 --webhelper-gpu; then
steam_cef_gpu=0
fi
else
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
droiddeck-steam-install || exit $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
if [ -f "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then
droiddeck-steam-x64 --sync-login || true
fi
steam_client=("$steam_root/steamrtarm64/steam")
fi
_bl_proton_root=$steam_root
if [ "$steam_x64" = 1 ]; then
_bl_proton_root=$XDG_DATA_HOME/Steam
if ! ls -d "$_bl_proton_root"/compatibilitytools.d/GE-Proton*-aarch64 >/dev/null 2>&1 &&
! grep -q '^ge' "$HOME/.bl-proton-extra" 2>/dev/null; then
echo ge >> "$HOME/.bl-proton-extra"
fi
fi
if [ -s "$HOME/.bl-proton-extra" ]; then
_bl_left=$HOME/.bl-proton-extra.left
: > "$_bl_left"
_bl_got_proton=0
while read -r _bl_extra || [ -n "$_bl_extra" ]; do
case ${_bl_extra# } in ""|"#"*) continue ;; esac
step "installing Proton '$_bl_extra' (large download, several minutes)"
if droiddeck-proton-extra "$steam_root" $_bl_extra; then
if droiddeck-proton-extra "$_bl_proton_root" $_bl_extra; then
_bl_got_proton=1
step "installed Proton '$_bl_extra'"
else
step "Proton '$_bl_extra' failed; will retry next session"
@@ -318,6 +399,9 @@ case $mode in
fi
done < "$HOME/.bl-proton-extra"
mv -f "$_bl_left" "$HOME/.bl-proton-extra"
if [ "$steam_x64" = 1 ] && [ "$_bl_got_proton" = 1 ]; then
droiddeck-steam-x64 --prepare || true
fi
fi
if [ -s "$HOME/.bl-steam-urls" ]; then
while read -r _bl_url || [ -n "$_bl_url" ]; do
@@ -329,23 +413,6 @@ case $mode in
fi
if [ -n "${BL_CLIENT_CPUS:-}" ]; then
step "client cores: $BL_CLIENT_CPUS"
(
declare -A _bl_pinned=()
for ((_i = 0; _i < 720; _i++)); do
for _d in /proc/[0-9]*; do
IFS= read -r -d '' _c < "$_d/cmdline" 2>/dev/null || continue
case $_c in *steamwebhelper*|*steamrtarm64/steam|*gamescope*) ;; *) continue ;; esac
_t=("$_d"/task/*)
_p=${_d#/proc/}
if [ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$BL_CLIENT_CPUS" "${_t[@]}"; then
continue
fi
taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true
_bl_pinned[$_p]=${#_t[@]}
done
nap 5
done
) &
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
printf 0 > /tmp/.bl-zram
@@ -354,7 +421,9 @@ case $mode in
bl_zram_scan() {
_bl_game=0 _bl_pids=()
for _d in /proc/[0-9]*; do
IFS= read -r -d '' _c 2>/dev/null < "$_d/cmdline" || continue
# Under FEX the program is FEX's first argument.
{ IFS= read -r -d '' _c && case ${_c##*/} in FEX|FEXInterpreter) IFS= read -r -d '' _c ;; esac; } \
2>/dev/null < "$_d/cmdline" || continue
case ${_c##*/} in
reaper) _bl_game=1 ;;
steam|steamwebhelper) _bl_pids+=("${_d#/proc/}") ;;
@@ -403,6 +472,7 @@ case $mode in
/usr/local/bin/droiddeck-launcher-cores "$BL_LAUNCH_DIR/agent/focus.json" 2>&1 &
fi
if [ "$steam_x64" = 0 ]; then
step "registering the app's game library with Steam"
droiddeck-steam-library "$steam_root" || true
step "setting up the ARM64 Proton compatibility tool"
@@ -415,7 +485,22 @@ case $mode in
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
droiddeck-seed-redists "$steam_root" || true
if [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
else
_bl_x64_tool=$(droiddeck-steam-x64 --default-tool)
if [ -n "$_bl_x64_tool" ]; then
if [ -n "${BL_ADDED_GAMES:-}" ]; then
step "adding the app's own games to the x86-64 client's library"
BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
step "pointing the x86-64 client's Windows titles at $_bl_x64_tool"
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 || true
fi
if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
fi
droiddeck-seed-redists "$steam_root" || true
fi
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
step "asking the client to fetch the ARM64 Proton"
set -- "$@" steam://install/4427310
(
@@ -427,7 +512,7 @@ case $mode in
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
step "compatibility layer installed: restarting the Steam client once"
: > "$HOME/.bl-restart-once"
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
exit 0
fi
done
@@ -451,7 +536,7 @@ case $mode in
sleep 10
[ -f "$_bl_acf" ] && exit 0
step "signed in: asking the client again for the ARM64 Proton (try $_bl_try of 3)"
"$steam_root/steamrtarm64/steam" steam://install/4427310 >/dev/null 2>&1 || true
"${steam_client[@]}" steam://install/4427310 >/dev/null 2>&1 || true
sleep 50
done
exit 0
@@ -460,116 +545,104 @@ case $mode in
) &
fi
fi
[ -z "${BL_DESKTOP:-}" ] && [ "${BL_STRETCHED:-0}" = 1 ] && (
while :; do
nap 1
cur=$(xprop -root GAMESCOPE_NEW_SCALING_SCALER 2>/dev/null) || continue
case $cur in *" = "*) cur=${cur##* = } ;; *) cur=0 ;; esac
[ "$cur" = 0 ] || continue
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
done
) &
[ -z "${BL_DESKTOP:-}" ] && [ "${BL_RESTORE_ON_RESUME:-1}" = 1 ] && (
prev=
xprop -spy -root GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do
app=${line##*= }
case $app in ''|*[!0-9]*) prev=; continue ;; esac
if [ "$prev" = 769 ] && [ "$app" != 769 ]; then
nap 1
bl_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \
&& echo "== resume: asked gamescope to restore the game window (app $app)"
fi
prev=$app
done
) &
[ -z "${BL_DESKTOP:-}" ] && (
xprop_value() {
case $1 in *'not found'*|*=) echo "$2"; return ;; esac
local v=${1#*=}
v=${v# }
echo "${v:-$2}"
stretch=0 restore=0
[ "${BL_STRETCHED:-0}" = 1 ] && stretch=1
[ "${BL_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP)
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER)
prop_value() {
case $1 in *'not found'*|*=) pv=$2; return ;; esac
pv=${1#*=}
pv=${pv# }
pv=${pv:-$2}
}
tmode= app=
xprop -spy -root STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do
tmode= app= prev=
while read -r line; do
case $line in
STEAM_TOUCH_CLICK_MODE*)
v=$(xprop_value "$line" unset)
[ "$v" = "$tmode" ] && continue
tmode=$v
prop_value "$line" unset
[ "$pv" = "$tmode" ] && continue
tmode=$pv
echo "== touch mode: $tmode (focused app ${app:-?}) at $(date +%T)"
;;
GAMESCOPE_FOCUSED_APP*)
v=$(xprop_value "$line" none)
[ "$v" = "$app" ] && continue
app=$v
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
prop_value "$line" none
if [ "$pv" != "$app" ]; then
app=$pv
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
if [ -n "${BL_LAUNCH_DIR:-}" ]; then
printf '%s\n' "$app" > "$BL_LAUNCH_DIR/steam-focused-app.tmp" && mv -f "$BL_LAUNCH_DIR/steam-focused-app.tmp" "$BL_LAUNCH_DIR/steam-focused-app"
fi
fi
[ "$restore" = 1 ] || continue
case $pv in ''|*[!0-9]*) prev=; continue ;; esac
if [ "$prev" = 769 ] && [ "$pv" != 769 ]; then
nap 1
bl_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \
&& echo "== resume: asked gamescope to restore the game window (app $pv)"
fi
prev=$pv
;;
GAMESCOPE_NEW_SCALING_SCALER*)
prop_value "$line" 0
[ "$pv" = 0 ] || continue
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
;;
esac
done
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
) &
(
beat=0
compat_stamp=$HOME/.bl-compat-beat
seed_stamp=$HOME/.bl-seed-beat
rm -f "$compat_stamp" "$seed_stamp"
changed_since() {
local d
for d in "${@:2}"; do
[ "$d" -nt "$1" ] && return 0
done
return 1
}
compat_due() {
[ -e "$compat_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$compat_stamp" "${libraries[@]}" "$steam_root/steamapps/common" "$steam_root/config" \
"$steam_root/compatibilitytools.d"
}
seed_due() {
local reg
[ -e "$seed_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$seed_stamp" "${libraries[@]}" && return 0
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] && [ ! -f "${reg%/*}/.droiddeck-redists" ] && return 0
done
return 1
}
for ((_i = 0; _i < 720; _i++)); do
nap 5
beat=$((beat + 1))
[ "$((beat % 3))" -eq 0 ] || continue
libraries=("$steam_root/steamapps" /mnt/droiddeck/steamapps /mnt/droiddeck-sd/steamapps /root/Games/*/steamapps)
seed=; compat=
seed_due && seed=1
compat_due && compat=1
[ -n "$seed$compat" ] || continue
pgrep -x wineserver >/dev/null 2>&1 && continue
if [ -n "$seed" ]; then
: > "$seed_stamp"
droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true
fi
if [ -n "$compat" ]; then
: > "$compat_stamp"
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
fi
steam_hold_launch() {
_bl_launch_ready=
_bl_end=$((SECONDS + 120))
until [ "$(xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p')" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do
sleep 1
done
) &
# With a large library the overview can stay missing for 30+ minutes while Steam already takes the launch URL.
_bl_overview_status=1
_bl_overview_tries=0
while [ "$_bl_overview_tries" -lt 2 ]; do
if /usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$1" 45; then
_bl_overview_status=0
else
_bl_overview_status=$?
fi
if [ "$_bl_overview_status" -ne 1 ]; then
break
fi
_bl_overview_tries=$((_bl_overview_tries + 1))
echo "== steam: shortcut overview not ready yet (attempt $_bl_overview_tries of 2)"
sleep 2
done
if [ "$_bl_overview_status" -eq 0 ]; then
echo "== steam: shortcut overview ready; launching the requested game $1"
_bl_launch_ready=1
elif [ "$_bl_overview_status" -eq 3 ]; then
echo "== steam: not a shortcut CGameID; keeping the existing launch path"
sleep 4
_bl_launch_ready=1
else
echo "== steam: shortcut overview not ready after about 90 s; launching the requested game anyway $1"
_bl_launch_ready=1
fi
if [ "$_bl_launch_ready" = 1 ]; then
echo "== steam: interface up; launching the requested game $1"
printf '%s\n' "$1" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
fi
}
if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then
_bl_held=
_bl_uninstall=
_bl_rest=()
for _bl_arg in "$@"; do
case $_bl_arg in
steam://rungameid/*) _bl_held=${_bl_arg#steam://rungameid/} ;;
steam://uninstall/*) _bl_uninstall=${_bl_arg#steam://uninstall/} ;;
*) _bl_rest+=("$_bl_arg") ;;
esac
done
if [ -n "$_bl_held" ]; then
if [ -n "$_bl_uninstall" ]; then
set -- "${_bl_rest[@]}"
(
_bl_end=$((SECONDS + 120))
@@ -577,10 +650,14 @@ case $mode in
sleep 1
done
sleep 4
echo "== steam: interface up; launching the requested game $_bl_held"
printf '%s\n' "$_bl_held" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
echo "== steam: interface up; asking to uninstall $_bl_uninstall"
printf '%s\n' "$_bl_uninstall" > "$BL_LAUNCH_DIR/steam-uninstall.tmp" && mv -f "$BL_LAUNCH_DIR/steam-uninstall.tmp" "$BL_LAUNCH_DIR/steam-uninstall"
) &
fi
if [ -n "$_bl_held" ]; then
set -- "${_bl_rest[@]}"
steam_hold_launch "$_bl_held" &
fi
fi
if [ -s "$HOME/.bl-autolaunch" ]; then
_bl_app=$(cat "$HOME/.bl-autolaunch")
@@ -616,11 +693,9 @@ BUSCONF
sleep 0.1
done
if [ -S /run/dbus/system_bus_socket ]; then
droiddeck-netmanager &
netmanager=$!
echo "== network: system bus up, NetworkManager stand-in running"
rm -f "$BL_LAUNCH_DIR/steam-sleep-ready"
droiddeck-login1 &
droiddeck-login1 --with-netmanager &
login_manager=$!
for ((_i = 0; _i < 50; _i++)); do
[ -f "$BL_LAUNCH_DIR/steam-sleep-ready" ] && break
@@ -641,6 +716,10 @@ BUSCONF
exit 69
fi
# The UI bridge launches SteamVR, which needs the guest agent's library environment.
_bl_compat_env=(env -u LD_LIBRARY_PATH -u STEAM_RUNTIME)
[ "${LD_LIBRARY_PATH+x}" ] && _bl_compat_env+=("LD_LIBRARY_PATH=$LD_LIBRARY_PATH")
[ "${STEAM_RUNTIME+x}" ] && _bl_compat_env+=("STEAM_RUNTIME=$STEAM_RUNTIME")
export STEAM_RUNTIME=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
@@ -691,23 +770,26 @@ BUSCONF
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
droiddeck-steam-compat "$steam_root" 2>&1 &
[ "$steam_x64" = 1 ] || "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 &
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-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_STEAM_UI:-}" != desktop ]; then
_bl_ui+=(-steamdeck -steamos3)
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
export STEAM_GAMESCOPE_FANCY_SCALING_SUPPORT=1
echo "== steam: Deck mode on (-steamdeck -steamos3)"
if [ "$steam_x64" = 0 ] || [ "${BL_X64_DECK:-1}" != 0 ]; then
_bl_ui+=(-steamdeck -steamos3)
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
export STEAM_GAMESCOPE_FANCY_SCALING_SUPPORT=1
echo "== steam: Deck mode on (-steamdeck -steamos3)"
fi
fi
export STEAMOS_STEAM_SHUTDOWN_SENTINEL="$HOME/.bl-steam-shutdown"
export STEAMOS_STEAM_REBOOT_SENTINEL="$HOME/.bl-steam-reboot"
if ! pgrep -f 'steamwebhelper|steamrtarm64/steam' >/dev/null 2>&1; then
if ! pgrep -f 'steamwebhelper|steamrtarm64/steam|steamrt64/steam' >/dev/null 2>&1; then
_stale=""
for _f in "$steam_root/.crash" "$steam_root/steam.pid" \
"$steam_root/config/htmlcache/SingletonLock" "$steam_root/config/htmlcache/SingletonCookie" \
@@ -722,28 +804,93 @@ BUSCONF
[ -n "${BL_STEAM_LANGUAGE:-}" ] && _bl_lang=(-language "$BL_STEAM_LANGUAGE")
steam_beta=$steam_root/package/beta
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
if [ "$steam_x64" = 0 ]; then
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
else
BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so \
BL_STEAM_SHUTDOWN="droiddeck-steam-x64 --exec -shutdown" \
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
fi
games_watcher=$!
fi
if [ "${BL_LOSSLESS_OWNED:-0}" != 1 ]; then
(
owned=$HOME/.config/droiddeck/lossless-owned
for ((_i = 0; _i < 60; _i++)); do
nap 30
[ -e "$owned" ] && exit 0
pgrep -x wineserver >/dev/null 2>&1 && continue
answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || continue
case $answer in
*'"993090": true'*) mkdir -p "${owned%/*}" && : > "$owned" && echo "== Lossless Scaling: owned" ;;
*) echo "== Lossless Scaling: not owned by this account" ;;
esac
exit 0
done
) &
fi
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*"
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
steam_updates=0
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
steam_other_game_running() {
local line value n open
open=$(cat "$BL_LAUNCH_DIR/epic-open" 2>/dev/null)
case $open in ?|*[!0-9]*) open=${BL_EPIC_APP_ID:-$open} ;; esac
line=$(xprop -root GAMESCOPE_FOCUSABLE_APPS 2>/dev/null) || return 1
case $line in *=*) value=${line#*= } ;; *) return 1 ;; esac
for n in ${value//,/ }; do
[ "$n" = 769 ] || [ "$n" = "$open" ] || return 0
done
return 1
}
steam_restart_for() {
if [ "$(cat "$HOME/.bl-restarted-for" 2>/dev/null)" = "$1" ]; then
echo "== steam: $2, but Steam was already restarted for it; launching it anyway"
return 1
fi
printf '%s\n' "$1" > "$HOME/.bl-restarted-for"
echo "== steam: $2; restarting Steam to launch it"
printf '%s\n' "$1" > "$HOME/.bl-restart-game"
"${steam_client[@]:-$steam_root/steamrtarm64/steam}" -shutdown >/dev/null 2>&1
}
steam_launch_game() {
local state=0 tries
/usr/local/bin/droiddeck-agent --steam-shortcut-state "$1" 6 >/dev/null 2>&1 || state=$?
[ "$state" -eq 0 ] && rm -f "$HOME/.bl-restarted-for"
if [ "$state" -eq 4 ]; then
if steam_other_game_running; then
echo "== steam: the client lost shortcut $1, but a game is running; launching it anyway"
elif steam_restart_for "$1" "the client lost shortcut $1"; then
return
fi
fi
"${steam_client[@]:-$steam_root/steamrtarm64/steam}" "steam://rungameid/$1" >/dev/null 2>&1
[ "$state" -eq 3 ] && return
for tries in 1 2 3 4 5 6 7 8; do
nap 1
state=0
/usr/local/bin/droiddeck-agent --steam-shortcut-state "$1" 1 >/dev/null 2>&1 || state=$?
[ "$state" -eq 4 ] || continue
if steam_other_game_running; then
echo "== steam: the client dropped shortcut $1 while launching it, but a game is running"
else
steam_restart_for "$1" "the client dropped shortcut $1 while launching it"
fi
return 0
done
}
steam_check_exits() {
local ran n state lost=
ran=$(pgrep -a -f 'SteamLaunch AppId=[0-9]' 2>/dev/null | sed -n 's/.* SteamLaunch AppId=\([0-9]*\).*/\1/p')
if [ -n "$ran" ]; then
for n in $ran; do
[ "$n" -ge 2147483648 ] && _bl_ran[$n]=1
done
_bl_exited=
return
fi
[ "${#_bl_ran[@]}" -gt 0 ] || return 0
if [ -z "$_bl_exited" ]; then
_bl_exited=1
return
fi
_bl_exited=
for n in "${!_bl_ran[@]}"; do
state=0
/usr/local/bin/droiddeck-agent --steam-shortcut-state "$(printf '%u' $(((n << 32) | 0x02000000)))" 3 >/dev/null 2>&1 || state=$?
[ "$state" -eq 4 ] && lost="$lost $n"
done
_bl_ran=()
[ -n "$lost" ] || return 0
pgrep -f 'SteamLaunch AppId=[0-9]' >/dev/null 2>&1 && return 0
echo "== steam: the client dropped shortcut(s)$lost when they exited; restarting Steam so it lists them again"
: > "$HOME/.bl-restart-lost"
"${steam_client[@]:-$steam_root/steamrtarm64/steam}" -shutdown >/dev/null 2>&1
}
steam_bring_forward() {
local end=$((SECONDS + 600)) behind=0 line name value focused other n
while [ "$SECONDS" -lt "$end" ]; do
@@ -767,17 +914,95 @@ BUSCONF
return 0
done
}
requests=
if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -d "$BL_LAUNCH_DIR" ]; then
rm -f "$BL_LAUNCH_DIR/steam-stop" "$BL_LAUNCH_DIR/steam-game" "$BL_LAUNCH_DIR/steam-game.tmp"
(
while :; do
requests=1
fi
(
tick=0
beat=0
library_job=
lossless_job=
lossless_left=0
lossless_owned=$HOME/.config/droiddeck/lossless-owned
lossless_asked=$HOME/.bl-lossless-asked
rm -f "$lossless_asked"
[ "${BL_LOSSLESS_OWNED:-0}" != 1 ] && lossless_left=60
declare -A _bl_pinned=()
declare -A _bl_ran=()
_bl_exited=
compat_stamp=$HOME/.bl-compat-beat
seed_stamp=$HOME/.bl-seed-beat
rm -f "$compat_stamp" "$seed_stamp"
changed_since() {
local d
for d in "${@:2}"; do
[ "$d" -nt "$1" ] && return 0
done
return 1
}
compat_due() {
[ -e "$compat_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$compat_stamp" "${libraries[@]}" "$steam_root/steamapps/common" "$steam_root/config" \
"$steam_root/compatibilitytools.d"
}
seed_due() {
local reg
[ -e "$seed_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$seed_stamp" "${libraries[@]}" && return 0
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] && [ ! -f "${reg%/*}/.droiddeck-redists" ] && return 0
done
return 1
}
compat_pending=$HOME/.bl-compat-pending
compat_restarted=$HOME/.bl-compat-restarted
rm -f "$compat_pending"
: > "$compat_restarted"
compat_restarts=0
compat_settled() {
local app m flags r card=/mnt/droiddeck-sd
# The arm64 card library may hold that client's copy of the same title.
[ "$steam_x64" = 1 ] && card=/mnt/droiddeck-sd/x86-64
while read -r app; do
[ -n "$app" ] || continue
m=
for r in "$steam_root" "$card"; do
[ -f "$r/steamapps/appmanifest_$app.acf" ] && { m=$r/steamapps/appmanifest_$app.acf; break; }
done
[ -n "$m" ] || return 1
flags=$(sed -n 's/^[[:space:]]*"StateFlags"[[:space:]]*"\([0-9]*\)".*/\1/p' "$m" | head -n 1)
[ "$flags" = 4 ] || return 1
done < "$compat_pending"
! pgrep -f 'reaper SteamLaunch' >/dev/null 2>&1
}
while :; do
if [ -n "$requests" ]; then
if [ -e "$BL_LAUNCH_DIR/steam-stop" ]; then
rm -f "$BL_LAUNCH_DIR/steam-stop"
: > "$HOME/.bl-stop-requested"
echo "== steam: the app asked for a clean exit"
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
exit 0
fi
if [ -f "$BL_LAUNCH_DIR/steam-uninstall" ]; then
uninstall_id=$(cat "$BL_LAUNCH_DIR/steam-uninstall" 2>/dev/null)
rm -f "$BL_LAUNCH_DIR/steam-uninstall"
case $uninstall_id in
''|0*|*[!0-9]*|???????????*) echo "== steam: ignored invalid uninstall request" ;;
*)
echo "== steam: opening the uninstall dialog for $uninstall_id"
"${steam_client[@]}" "steam://uninstall/$uninstall_id" >/dev/null 2>&1 &
;;
esac
fi
if [ -f "$BL_LAUNCH_DIR/steam-game" ]; then
game_id=$(cat "$BL_LAUNCH_DIR/steam-game" 2>/dev/null)
rm -f "$BL_LAUNCH_DIR/steam-game"
@@ -789,7 +1014,7 @@ BUSCONF
[ "$game_id_length" -eq 20 ] && [[ "$game_id" < "18446744073709551616" ]];
}; then
echo "== steam: launching requested game $game_id in the running client"
"$steam_root/steamrtarm64/steam" "steam://rungameid/$game_id" >/dev/null 2>&1 &
steam_launch_game "$game_id" &
[ -n "${forward_pid:-}" ] && kill "$forward_pid" 2>/dev/null
steam_bring_forward &
forward_pid=$!
@@ -799,13 +1024,86 @@ BUSCONF
;;
esac
fi
nap 0.5
done
) &
stop_watcher=$!
fi
fi
nap 0.5
tick=$((tick + 1))
[ "$((tick % 10))" -eq 0 ] || continue
beat=$((beat + 1))
steam_check_exits
if [ "$beat" -le 720 ] && [ -n "${BL_CLIENT_CPUS:-}" ]; then
for _d in /proc/[0-9]*; do
{ IFS= read -r -d '' _c && { IFS= read -r -d '' _c1 || _c1=; }; } < "$_d/cmdline" 2>/dev/null || continue
case $_c in FEX|*/FEX|FEXInterpreter|*/FEXInterpreter) _c=$_c1 ;; esac
case $_c in *steamwebhelper*|*steamrtarm64/steam|*steamrt64/steam|*gamescope*) ;; *) continue ;; esac
_t=("$_d"/task/*)
_p=${_d#/proc/}
[ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$BL_CLIENT_CPUS" "${_t[@]}" && continue
taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true
_bl_pinned[$_p]=${#_t[@]}
done
fi
if [ "$beat" -le 720 ] && [ "$((beat % 3))" -eq 0 ] && { [ -z "$library_job" ] || ! kill -0 "$library_job" 2>/dev/null; }; then
libraries=("$steam_root/steamapps" /mnt/droiddeck/steamapps /mnt/droiddeck-sd/steamapps /root/Games/*/steamapps)
seed=; compat=
seed_due && seed=1
compat_due && compat=1
if [ -n "$seed$compat" ] && ! pgrep -x wineserver >/dev/null 2>&1; then
[ -n "$seed" ] && : > "$seed_stamp"
[ -n "$compat" ] && : > "$compat_stamp"
(
[ -z "$seed" ] || droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true
if [ -n "$compat" ]; then
if [ "$steam_x64" = 1 ]; then
[ -z "${_bl_x64_tool:-}" ] ||
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 --live >/dev/null 2>&1 || true
droiddeck-steam-x64 --map-direct --live >/dev/null 2>&1 || true
else
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
fi
fi
) &
library_job=$!
fi
fi
if [ "$((beat % 3))" -eq 0 ] && [ -s "$compat_pending" ] && [ "$compat_restarts" -lt 3 ] && compat_settled; then
_bl_new=$(sort -u "$compat_pending" | grep -vxF -f "$compat_restarted" || true)
rm -f "$compat_pending"
if [ -n "$_bl_new" ]; then
compat_restarts=$((compat_restarts + 1))
printf '%s\n' $_bl_new >> "$compat_restarted"
if [ "$steam_x64" = 1 ]; then
step "newly installed title(s) $(echo $_bl_new) set to an ARM64 Proton (Windows builds) or DroidDeck direct (Linux builds): restarting the Steam client once so it takes effect"
else
step "newly installed title(s) $(echo $_bl_new) set to the ARM64 Proton: restarting the Steam client once so it takes effect"
fi
: > "$HOME/.bl-restart-once"
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
fi
fi
if [ "$lossless_left" -gt 0 ] && [ "$((beat % 6))" -eq 0 ] && { [ -z "$lossless_job" ] || ! kill -0 "$lossless_job" 2>/dev/null; }; then
lossless_left=$((lossless_left - 1))
if [ -e "$lossless_owned" ] || [ -e "$lossless_asked" ]; then
lossless_left=0
elif ! pgrep -x wineserver >/dev/null 2>&1; then
(
# The probe reaches the x86-64 client through the arm64 client's steamclient.so, as the import watcher does.
if [ "$steam_x64" = 1 ]; then export BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so; fi
answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || exit 0
case $answer in
*'"993090": true'*) mkdir -p "${lossless_owned%/*}" && : > "$lossless_owned" && echo "== Lossless Scaling: owned" ;;
*) echo "== Lossless Scaling: not owned by this account" ;;
esac
: > "$lossless_asked"
) &
lossless_job=$!
fi
fi
done
) &
stop_watcher=$!
rm -f "$HOME/.bl-restart-game" "$HOME/.bl-restarted-for"
while :; do
rm -f "$HOME/.bl-restart-once"
rm -f "$HOME/.bl-restart-once" "$HOME/.bl-restart-lost"
if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then
echo "== steam: client branch on disk was '$(cat "$steam_beta" 2>/dev/null)', set to '$steam_channel' to match -clientbeta"
echo "$steam_channel" > "$steam_beta"
@@ -815,7 +1113,11 @@ BUSCONF
_bl_counted=1
fi
if [ -n "${BL_STEAM_LANGUAGE:-}" ]; then
droiddeck-steam-language "$HOME" "$BL_STEAM_LANGUAGE" || true
if [ "$steam_x64" = 1 ]; then
droiddeck-steam-language "${BL_X64_HOME:-$HOME/.droiddeck-x64}" "$BL_STEAM_LANGUAGE" || true
else
droiddeck-steam-language "$HOME" "$BL_STEAM_LANGUAGE" || true
fi
fi
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
desktop_ui_pid=
@@ -823,21 +1125,33 @@ BUSCONF
/usr/local/bin/droiddeck-steam-desktop-ui &
desktop_ui_pid=$!
fi
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
steam_started=$SECONDS
"${steam_client[@]}" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
rc=$?
steam_ran=$((SECONDS - steam_started))
if [ -n "$desktop_ui_pid" ]; then
kill "$desktop_ui_pid" 2>/dev/null || true
wait "$desktop_ui_pid" 2>/dev/null || true
fi
echo "== steam exited rc=$rc"
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
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
fi
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
if [ "$steam_x64" = 0 ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
elif [ -n "${_bl_x64_tool:-}" ]; then
BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
fi
# The x86-64 client rewrote config.vdf from memory on exit, over the live passes' mapping.
if [ "$steam_x64" = 1 ]; then
[ -z "${_bl_x64_tool:-}" ] ||
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 >/dev/null 2>&1 || true
droiddeck-steam-x64 --map-direct || true
fi
if [ -f "$HOME/.bl-stop-requested" ]; then
rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once"
break
@@ -854,14 +1168,32 @@ BUSCONF
set --
continue
fi
if [ -s "$HOME/.bl-restart-game" ]; then
_bl_again=$(cat "$HOME/.bl-restart-game" 2>/dev/null)
rm -f "$HOME/.bl-restart-game"
case $_bl_again in
''|0*|*[!0-9]*) ;;
*)
echo "== steam: starting the client again to launch $_bl_again"
set --
steam_hold_launch "$_bl_again" &
continue
;;
esac
fi
if [ -f "$HOME/.bl-restart-lost" ]; then
rm -f "$HOME/.bl-restart-lost"
echo "== steam: starting the client again so it lists every shortcut"
set --
continue
fi
if [ -f "$HOME/.bl-restart-once" ]; then
echo "== steam: restarting once so the new compatibility layer is in the client's lists"
set --
continue
fi
[ "$rc" -eq 42 ] || break
steam_updates=$((steam_updates + 1))
if [ "$steam_updates" -ge 3 ]; then
if steam_update_stuck "$steam_ran"; then
echo "== steam: asked to restart for an update $steam_updates times and it is not installing; the session stops here rather than loop"
break
fi
@@ -894,6 +1226,9 @@ BUSCONF
[ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null
reap_orphans
fi
if [ -n "${BL_STEAM_EXIT_FILE:-}" ]; then
printf '%s\n' "$rc" > "$BL_STEAM_EXIT_FILE"
fi
exit "$rc"
;;
*)
@@ -126,6 +126,29 @@ INSTALL_JS = r"""
return "installed";
})()
""".replace("__BINDING__", BINDING)
TOOLS_JS = r"""
(() => {
if (window.__droiddeckTools) return "present";
const installs = SteamClient.Installs, downloads = SteamClient.Downloads;
if (typeof installs?.OpenInstallWizard !== "function" || typeof installs?.RegisterForShowInstallWizard !== "function" ||
typeof installs?.ContinueInstall !== "function" || typeof downloads?.QueueAppUpdate !== "function")
throw new Error("the client's install calls are not ready");
const self = { asked: new Map() };
installs.RegisterForShowInstallWizard((state) => {
const app = Number(state?.currentAppID);
if (state?.eInstallState === 7 && Date.now() - (self.asked.get(app) || 0) < 120000) {
self.asked.delete(app);
installs.ContinueInstall();
}
});
self.install = (app) => { self.asked.set(app, Date.now()); installs.OpenInstallWizard([app], "0"); return true; };
self.update = (app) => { downloads.QueueAppUpdate(app, "0"); return true; };
window.__droiddeckTools = self;
return "installed";
})()
"""
TOOL_CHECK_SECONDS = 60
TOOL_RETRY_SECONDS = 300
SWITCH_BINDING = "droiddeckSwitchToDesktop"
SWITCH_JS = r"""
(() => {
@@ -153,6 +176,82 @@ SWITCH_JS = r"""
})()
""".replace("__BINDING__", SWITCH_BINDING)
SESSION_SELECT = "/usr/bin/steamos-session-select"
VR_BINDING = "droiddeckLaunchSteamVr"
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
VR_JS = r"""
(() => {
if (window.__droiddeckSteamVr) return "present";
const apps = SteamClient.Apps;
if (!apps || typeof apps.RunGame !== "function") throw new Error("Steam RunGame is not ready");
const run = apps.RunGame;
const self = { running: false, pending: new Map(), lastError: null };
const flush = () => {
if (!self.running) return;
const queued = Array.from(self.pending.values());
self.pending.clear();
for (const item of queued) {
clearTimeout(item.timer);
run.call(item.receiver, item.id, ...item.args);
}
};
if (typeof SteamClient.OpenVR?.RegisterForVRModeChange === "function") {
self.subscription = SteamClient.OpenVR.RegisterForVRModeChange(running => {
self.running = !!running;
flush();
});
}
const wrapped = function (id, ...args) {
const gameid = String(id);
if (typeof window.__BINDING__ !== "function") return run.call(this, id, ...args);
if (gameid === "250820") {
window.__BINDING__(gameid);
return;
}
const overview = window.appStore?.GetAppOverviewByGameID?.(gameid);
const vr = overview?.vr_only === true;
if (vr && self.subscription && /^[1-9][0-9]{0,19}$/.test(gameid)) {
if (self.pending.has(gameid)) return;
self.lastError = null;
const item = { receiver: this, id, args, timer: null };
item.timer = setTimeout(() => {
self.pending.delete(gameid);
self.lastError = "SteamVR did not become ready. Start SteamVR from DroidDeck and try the game again.";
console.error("DroidDeck: " + self.lastError);
}, 600000);
self.pending.set(gameid, item);
try { window.__BINDING__(gameid); }
catch (e) { clearTimeout(item.timer); self.pending.delete(gameid); throw e; }
flush();
return;
}
return run.call(this, id, ...args);
};
apps.RunGame = wrapped;
if (apps.RunGame !== wrapped) throw new Error("Steam RunGame could not be redirected");
if (typeof SteamClient.OpenVR?.StartVR === "function") {
const start = SteamClient.OpenVR.StartVR;
SteamClient.OpenVR.StartVR = function (...args) {
if (typeof window.__BINDING__ === "function") return window.__BINDING__("250820");
return start.apply(this, args);
};
}
window.__droiddeckSteamVr = self;
return "installed";
})()
""".replace("__BINDING__", VR_BINDING)
def launch_steamvr():
"""Keep downloads/startup off the Steam UI bridge's event loop."""
say("SteamVR library launch: using the DroidDeck ARM64 helper")
state = os.path.join(os.environ.get("XDG_RUNTIME_DIR", "/tmp"), "droiddeck-steamvr")
try:
os.makedirs(state, exist_ok=True)
with open(os.path.join(state, "library-launch.log"), "a") as log:
return subprocess.Popen([VR_HELPER, "launch"], stdin=subprocess.DEVNULL,
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
except OSError as e:
say("SteamVR library launch failed: %s" % e)
class Closed(Exception):
@@ -321,6 +420,9 @@ class Page:
raise RuntimeError((details.get("exception") or {}).get("description") or details.get("text") or "script failed")
return result.get("result", {}).get("value")
def tools(self, call):
return self.evaluate("%s;\nwindow.__droiddeckTools.%s" % (TOOLS_JS, call))
def compat(self, call):
return self.evaluate("%s;\nwindow.__droiddeckCompat.%s" % (INSTALL_JS, call))
@@ -405,6 +507,9 @@ class Helper:
self.known = set()
self.installed = None
self.fex_asked = set()
self.tools_asked = {}
self.tools_checked = None
self.vr_launch = None
def attach(self):
path = shared_context(self.port)
@@ -415,6 +520,8 @@ class Helper:
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
raise LookupError("SteamClient is not ready")
page.call("Runtime.addBinding", {"name": BINDING})
page.call("Runtime.addBinding", {"name": VR_BINDING})
page.evaluate(VR_JS)
if not self.steamos:
page.call("Runtime.addBinding", {"name": SWITCH_BINDING})
page.evaluate(SWITCH_JS)
@@ -442,29 +549,77 @@ class Helper:
installed = COMPAT["installed_apps"](self.steam_root)
self.installed = installed
picks = COMPAT["valve_picks"](self.steam_root)
apps = sorted(set(installed) | set(picks) | set(state.get("auto", {})), key=COMPAT["app_order"])
prior_auto = state.get("auto", {})
if not isinstance(prior_auto, dict):
prior_auto = {}
# "native" from earlier builds also lists dual-platform games nobody chose to run natively.
prior_native = state.get("native_choices", ())
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"])
overrides = COMPAT["requested_games"](
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"])
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
current["0"] = top["selected"]
native = COMPAT["native_targets"](self.steam_root, installed)
native = COMPAT["native_targets"](self.steam_root, apps)
raw_mapping = COMPAT["read_config_mapping"](
os.path.join(self.steam_root, "config", "config.vdf"))
if raw_mapping is None:
for app in native_choices:
current[app] = ""
for app in set(native) - native_choices:
if not current.get(app):
current.pop(app, None)
else:
for app in set(native) | native_choices:
if app in raw_mapping:
# The client shows an explicit native choice as the tool it inherits, and writes config.vdf late.
if raw_mapping[app] == "" or current.get(app) not in self.known:
current[app] = raw_mapping[app]
elif app in prior_auto or app in native_choices:
current[app] = ""
elif not current.get(app):
current.pop(app, None)
changes, auto = COMPAT["plan_mapping"](
current, installed, [t["name"] for t in live], default,
COMPAT["followers"](state, current), native, picks, overrides)
COMPAT["followers"](state, current), native, picks, overrides,
prior_auto.keys(), native_choices)
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
page.compat("set(%d, %s)" % (int(app), json.dumps(tool)))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app, tool))
state.update(auto=auto, tools=catalog, live=True)
page.compat("set(%d, %s)" % (int(app), json.dumps(tool if tool is not None else "")))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app,
tool if tool is not None else "Steam native default"))
state.update(
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
native_choices=sorted(app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]),
tools=catalog, live=True)
state.pop("native", None)
if waiting:
state["pending"] = wanted
say("%s is new to the running client; it applies when Steam next starts" % wanted)
else:
state.pop("pending", None)
COMPAT["write_json"](state_file, state)
if native or os.path.exists(COMPAT["fex_wanted_marker"]()):
for app in COMPAT["request_fex"](self.steam_root, self.fex_asked):
say("asked the client to install %s for x86 Linux titles and programs" % app)
def ensure_tools(self):
"""Proton, FEX and the runtimes FEX needs are fetched as soon as the client is up, never left pending."""
now = time.monotonic()
if self.tools_checked is not None and now - self.tools_checked < TOOL_CHECK_SECONDS:
return
self.tools_checked = now
if COMPAT["game_running"]():
return
for app, action in COMPAT["tool_downloads"](self.steam_root):
if now - self.tools_asked.get(app, -TOOL_RETRY_SECONDS) < TOOL_RETRY_SECONDS:
continue
self.tools_asked[app] = now
try:
self.page.tools("%s(%d)" % (action, int(app)))
say("asked the client to %s %s" % (action, app))
except Exception as e:
say("the client could not %s %s (%s)" % (action, app, e))
if action == "install":
for asked in COMPAT["request_fex"](self.steam_root, self.fex_asked):
say("asked the client to install %s through steam://install" % asked)
def request_waiting(self):
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
@@ -476,6 +631,14 @@ class Helper:
events = self.page.drain()
if any(called(e, SWITCH_BINDING) for e in events):
switch_to_desktop()
vr_games = {e.get("params", {}).get("payload") for e in events if called(e, VR_BINDING) and
isinstance(e.get("params", {}).get("payload"), str)}
vr_games = {game for game in vr_games if isinstance(game, str) and game.isascii() and
game.isdecimal() and not game.startswith("0") and len(game) <= 20 and
int(game) <= 0xffffffffffffffff}
if vr_games and (self.vr_launch is None or self.vr_launch.poll() is not None):
say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games)))
self.vr_launch = launch_steamvr()
return events
def serve(self, watcher):
@@ -483,6 +646,7 @@ class Helper:
f.write("%d\n" % os.getpid())
say("attached to the client on port %d" % self.port)
self.reconcile()
self.ensure_tools()
while True:
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0]
@@ -497,6 +661,7 @@ class Helper:
watcher.changed()
self.drain()
self.reconcile()
self.ensure_tools()
def detach():
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path
import re
import shlex
import subprocess
import sys
import time
@@ -62,6 +63,12 @@ def source_stamp(game):
return None
def store_game(game):
"""Games a store client installed belong to that store: the Steam copy of the same title is
another license with its own files, and an import would let Steam update over the store's."""
return bool(game.get("store"))
def manifest_ids(steamapps, name):
matches = []
for manifest in Path(steamapps).glob("appmanifest_*.acf"):
@@ -113,7 +120,7 @@ def method(obj, slot, result, *args):
def probe(steam_root, ids):
library = C.CDLL(str(Path(steam_root) / "steamrtarm64/steamclient.so"))
library = C.CDLL(os.environ.get("BL_STEAMCLIENT") or str(Path(steam_root) / "steamrtarm64/steamclient.so"))
library.CreateInterface.argtypes = [C.c_char_p, C.c_void_p]
library.CreateInterface.restype = C.c_void_p
client = library.CreateInterface(b"SteamClient020", None)
@@ -167,7 +174,8 @@ def request_restart(steam_root):
"""The client reads manifests and shortcuts only at start, so an import needs one restart;
the session's loop runs the importer between the exit and the next start."""
Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch()
subprocess.run([str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"],
command = shlex.split(os.environ.get("BL_STEAM_SHUTDOWN", "")) or [str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"]
subprocess.run(command,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
@@ -178,7 +186,7 @@ def unimported(steam_root, snapshot, candidates):
def watch(steam_root, listing):
games = read_json(listing, [])
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")]
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
return
candidates, sources = {}, {}
@@ -207,9 +215,10 @@ def watch(steam_root, listing):
elif candidates and (key != probed or now >= next_probe):
probed, next_probe = key, now + 300
try:
probe_env = dict(os.environ, HOME=os.environ["BL_STEAM_IPC_HOME"]) if os.environ.get("BL_STEAM_IPC_HOME") else None
result = subprocess.run([sys.executable, __file__, "probe", steam_root,
*map(str, sorted(set(candidates.values())))],
capture_output=True, text=True, timeout=15)
capture_output=True, text=True, timeout=15, env=probe_env)
if result.returncode != 0:
status = "ownership probe failed: " + (result.stderr.strip()[-300:] or str(result.returncode))
failures += 1
@@ -363,6 +372,22 @@ def seed_install(steam_root, game, appid):
return True
def release(steam_root, game):
"""Undoes an import made before store games were skipped. Only our symlink and manifest go;
the store's folder stays where it is."""
steamapps = Path(steam_root) / "steamapps"
sources = {game.get("folder", ""), legacy_path(game.get("folder", ""))}
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources):
continue
for manifest in (steamapps / f"appmanifest_{appid}.acf", steamapps / PARKED / f"appmanifest_{appid}.acf"):
if manifest.is_file() and ours(manifest, appid):
manifest.unlink()
target.unlink()
print(f"droiddeck-steam-games: {game.get('name', appid)} came from {game['store']}; it is a shortcut again, not Steam app {appid}")
def route(steam_root, acct, games):
snapshot = read_json(Path(acct) / "config" / STATE, {})
if not isinstance(snapshot, dict):
@@ -379,6 +404,16 @@ def route(steam_root, acct, games):
except OSError as error:
print(f"droiddeck-steam-games: set-aside installs not restored ({error})")
for game in games:
if store_game(game):
try:
release(steam_root, game)
except OSError as error:
print(f"droiddeck-steam-games: store import not undone ({error})")
shortcuts.append(game)
continue
if game.get("native"):
shortcuts.append(game)
continue
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
@@ -1,6 +1,6 @@
#!/bin/bash
set -eu
cdn=https://client-update.fastly.steamstatic.com
cdn_list="https://client-update.steamstatic.com https://client-update.akamai.steamstatic.com https://client-update.fastly.steamstatic.com"
steam_channel=steamdeck_publicbeta
manifest=steam_client_${steam_channel}_linuxarm64
steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
@@ -33,12 +33,37 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
[ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
curl -fsSL "$cdn/$manifest" -o "$work/manifest"
cdn=""
for candidate in $cdn_list; do
if curl -fsSL --connect-timeout 10 --max-time 30 --retry 2 --retry-connrefused --retry-delay 3 \
"$candidate/$manifest" -o "$work/manifest"; then
cdn=$candidate
break
fi
done
[ -n "$cdn" ] || { echo "droiddeck-steam-install: no Steam client CDN answered for $manifest" >&2; exit 1; }
cdn_order=("$cdn")
for candidate in $cdn_list; do
[ "$candidate" = "$cdn" ] || cdn_order+=("$candidate")
done
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
if [ -n "$sync" ]; then
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
exit 0
fi
echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client"
fi
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
@@ -52,8 +77,16 @@ mkdir -p "$steam_root/package"
while read -r block file sum; do
i=$((${i:-0} + 1))
echo "== STEP $(date -u +%H:%M:%S) downloading Steam: $block ($i/$total)"
curl -fsSL "$cdn/$file" -o "$work/$file"
echo "$sum $work/$file" | sha256sum -c --quiet
fetched=""
for host in "${cdn_order[@]}"; do
if curl -fsSL --connect-timeout 10 --speed-limit 1024 --speed-time 60 --max-time 1800 \
"$host/$file" -o "$work/$file" && echo "$sum $work/$file" | sha256sum -c --quiet; then
fetched=$host
break
fi
rm -f "$work/$file"
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
unzip -qo "$work/$file" -d "$steam_root"
rm -f "$work/$file"
done < "$work/parts"
@@ -66,14 +99,20 @@ find "$steam_root" -depth -name '*\\*' | while read -r odd; do
mv -f "$odd" "$fixed"
fi
done
echo "$steam_channel" > "$steam_root/package/beta"
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
if [ -n "$sync" ]; then
cp -f "$work/manifest" "$steam_root/package/$manifest.manifest"
else
echo "$steam_channel" > "$steam_root/package/beta"
fi
ln -sfn "$steam_root/steamrtarm64" "$steam_root/steamrtarm32"
chmod +x "$steam_root/steamrtarm64/steam" 2>/dev/null || true
mkdir -p "$HOME/.steam"
ln -sfn "$steam_root" "$HOME/.steam/root"
ln -sfn "$steam_root" "$HOME/.steam/steam"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/bin64"
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdk64"
# sdk64 is where x86_64 Steamworks looks for steamclient.so; arm64 builds look in sdkarm64.
ln -sfn "$steam_root/linux64" "$HOME/.steam/sdk64"
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdkarm64"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/binarm64"
ln -sfn "$steam_root/linux32" "$HOME/.steam/sdk32"
@@ -12,15 +12,22 @@ case $target in
esac
if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
if [ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ]; then
client_home=${BL_X64_HOME:-${HOME:-/root}/.droiddeck-x64}
client=(/usr/local/bin/droiddeck-steam-x64 --exec)
else
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
client_home=$HOME
client=("$steam_root/steamrtarm64/steam")
fi
mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck"
exec 9>"${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck/steam-desktop.lock"
if ! flock -n 9; then
for ((attempt = 0; attempt < 180; attempt++)); do
pid=$(cat "$HOME/.steam/steam.pid" 2>/dev/null || true)
if [ -p "$HOME/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
exec "$steam_root/steamrtarm64/steam" -nobigpicture -no-cef-sandbox \
pid=$(cat "$client_home/.steam/steam.pid" 2>/dev/null || true)
if [ -p "$client_home/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
exec "${client[@]}" -nobigpicture -no-cef-sandbox \
-cef-ozone-platform=x11 -cef-disable-gpu "${url:-steam://open/library}"
fi
sleep 0.5
@@ -11,4 +11,5 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
done
exec /usr/local/bin/droiddeck-steam-launch "$ui" ${url:+"$url"}
fi
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && exec /usr/local/bin/droiddeck-steam-x64 --exec "$@"
exec "${HOME:-/root}/.local/share/Steam/steamrtarm64/steam" "$@"
@@ -180,12 +180,14 @@ def merge(fresh, current, state, seen):
def reconcile(existing, wanted, seen, record):
games, away = record["games"], dict(record["away"])
kept, ours, placed = [], [], {}
claimed = {(unquoted(fresh["Exe"]), fresh["AppName"]) for fresh in wanted.values()}
for value in existing.values():
if not isinstance(value, dict):
continue
tags = value.get("tags")
if not isinstance(tags, dict) or TAG not in tags.values():
kept.append(value)
if (unquoted(value.get("Exe")), value.get("AppName")) not in claimed:
kept.append(value)
continue
appid = value.get("appid")
if not isinstance(appid, int) or appid in placed:
@@ -342,9 +344,21 @@ def main():
spec.loader.exec_module(compat)
cfg = os.path.join(steam_root, "config", "config.vdf")
if os.path.isfile(cfg) and (ours or routes):
compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe")] + [str(appid) for appid in set(routes.values())],
protect=compat.adopt_extras(os.path.join(steam_root, "compatibilitytools.d")))
print("droiddeck-steam-shortcuts: mapped them to %s" % compat.TOOL)
tools = os.path.join(steam_root, "compatibilitytools.d")
x64_tool = os.environ.get("BL_COMPAT_TOOL")
own = {}
if x64_tool:
protect = {compat.first_key(os.path.join(tools, e, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or e: e
for e in (os.listdir(tools) if os.path.isdir(tools) else [])}
# Its own state: the arm64 client's state.json lists which of that client's titles follow its default.
own = {"default": x64_tool,
"directory": os.path.join(os.path.dirname(os.path.abspath(steam_root)), "droiddeck-compat"),
"linux_tool": "droiddeck-direct"}
else:
protect = compat.adopt_extras(tools)
used = compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe") and not g.get("native")] + [str(appid) for appid in set(routes.values())],
protect=protect, **own)
print("droiddeck-steam-shortcuts: mapped them to %s" % used)
except Exception as e:
print("droiddeck-steam-shortcuts: compat mapping skipped (%s)" % e)
return 0
File diff suppressed because it is too large. Load diff
+150 -6
View File
@@ -7,13 +7,39 @@ driver=$vrdir/droiddeck
layer=$vrdir/layer
logs=$HOME/.local/share/Steam/logs
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steamvr
umask 077
mkdir -p "$state"
chmod 700 "$state"
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
running() { pgrep -x vrserver >/dev/null 2>&1; }
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
quest_settings() {
backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json
[ "$1" != restore ] || [ -f "$backup" ] || return 0
python3 "${DROIDDECK_VR_SETTINGS_HELPER:-/usr/local/bin/droiddeck-steamvr-settings}" "$1" \
"$HOME/.local/share/Steam/config/steamvr.vrsettings" "$backup"
}
configure_graphics() {
case "$(cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)" in
Adreno840*)
# The session's forced sysmem mode loses the Vulkan device in SteamVR.
export TU_DEBUG="$(
IFS=', '
set -f
separator=
for flag in ${TU_DEBUG:-}; do
case "$flag" in ''|sysmem) continue ;; esac
printf '%s%s' "$separator" "$flag"
separator=,
done
)"
;;
esac
}
stop() {
rm -f "$state/active"
@@ -21,10 +47,29 @@ stop() {
for p in $(pgrep -x "$n"); do kill "$p" 2>/dev/null; done
done
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
return 0
attempts=0
while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do
attempts=$((attempts + 1))
if [ "$attempts" = 10 ]; then
for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done
fi
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
sleep 0.1
done
quest_settings restore
}
case "${1:-status}" in
launch)
# Library/URL entry point: use the same installer and start path as the app.
exec 8>"$state/launch.lock"
flock -n 8 || exit 0
if ! installed; then
"$0" install || exit $?
while [ -f "$state/installing" ]; do sleep 1; done
fi
"$0" start
;;
status)
i=0; installed && i=1
r=0; running && r=1
@@ -34,8 +79,9 @@ status)
echo "installed=$i running=$r installing=$n driver=$d"
;;
install)
exec 7>"$state/install.lock"
flock -n 7 || { echo "already installing"; exit 0; }
installed && { echo "SteamVR is already in $steamvr"; exit 0; }
[ -f "$state/installing" ] && { echo "already installing"; exit 0; }
: > "$state/installing"
trap 'rm -f "$state/installing"' EXIT
cache=$HOME/.cache/droiddeck-vr
@@ -52,14 +98,66 @@ install)
echo "SteamVR installed in $steamvr"
;;
stop)
stop
stop || exit 1
;;
start)
exec 9>"$state/start.lock"
flock -n 9 || { echo "SteamVR start already in progress"; exit 0; }
installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; }
[ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; }
stop
if [ -f "$state/active" ] && { running || pgrep -x vrstartup >/dev/null 2>&1; }; then
echo "DroidDeck SteamVR is already running"
exit 0
fi
stop || exit 1
sleep 1
mkdir -p "$HOME/.config/openvr" "$HOME/.config/openxr/1" "$logs" "$HOME/.local/share/Steam/config"
if [ -S "/run/droiddeck/droiddeck-xr-frames" ] && [ -z "${DROIDDECK_VR_PRESENT:-}" ]; then
export DROIDDECK_VR_PRESENT=questwsi
fi
python3 - "$HOME/.local/share/Steam/config/steamvr.vrsettings" <<'PY'
import json
import os
from pathlib import Path
import sys
import tempfile
path = Path(sys.argv[1])
try:
settings = json.loads(path.read_text()) if path.exists() else {}
section = settings.setdefault("steamvr", {})
defaults = {} if os.environ.get("DROIDDECK_VR_PRESENT", "").startswith("quest") else {"supersampleManualOverride": True, "supersampleScale": 1.0}
changed = any(key not in section for key in defaults)
for key, value in defaults.items():
section.setdefault(key, value)
driver = settings.get("driver_droiddeck")
if isinstance(driver, dict) and driver.get("blocked_by_safe_mode") is True:
driver["blocked_by_safe_mode"] = False
changed = True
print("SteamVR had blocked the DroidDeck driver after a crash; unblocked it")
if changed:
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as output:
temporary = Path(output.name)
try:
json.dump(settings, output, indent=3)
output.write("\n")
except BaseException:
temporary.unlink(missing_ok=True)
raise
try:
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
except (OSError, ValueError, AttributeError, TypeError) as error:
print("Could not set SteamVR resolution defaults: " + str(error), file=sys.stderr)
try:
(path.parent / "vrserver_crash_timestamp.txt").unlink()
print("Removed SteamVR's crash marker so it starts without safe mode")
except FileNotFoundError:
pass
except OSError as error:
print("Could not remove SteamVR's crash marker: " + str(error), file=sys.stderr)
PY
cat > "$HOME/.config/openvr/openvrpaths.vrpath" <<JSON
{
"config": ["$HOME/.local/share/Steam/config"],
@@ -71,10 +169,53 @@ start)
}
JSON
ln -sf "$steamvr/steamxr_linuxarm64.json" "$HOME/.config/openxr/1/active_runtime.json"
chaperone=$HOME/.local/share/Steam/config/chaperone_info.vrchap
[ -s "$chaperone" ] || cat > "$chaperone" <<'JSON'
{
"jsonid" : "chaperone_info",
"universes" : [
{
"collision_bounds" : [
[ [ -1.0, 0.0, -1.0 ], [ -1.0, 2.43, -1.0 ], [ -1.0, 2.43, 1.0 ], [ -1.0, 0.0, 1.0 ] ],
[ [ -1.0, 0.0, 1.0 ], [ -1.0, 2.43, 1.0 ], [ 1.0, 2.43, 1.0 ], [ 1.0, 0.0, 1.0 ] ],
[ [ 1.0, 0.0, 1.0 ], [ 1.0, 2.43, 1.0 ], [ 1.0, 2.43, -1.0 ], [ 1.0, 0.0, -1.0 ] ],
[ [ 1.0, 0.0, -1.0 ], [ 1.0, 2.43, -1.0 ], [ -1.0, 2.43, -1.0 ], [ -1.0, 0.0, -1.0 ] ]
],
"play_area" : [ 2.0, 2.0 ],
"seated" : { "translation" : [ 0.0, -1.6, 0.0 ], "yaw" : 0.0 },
"standing" : { "translation" : [ 0.0, 0.0, 0.0 ], "yaw" : 0.0 },
"universeID" : "2"
}
],
"version" : 5
}
JSON
export VK_LAYER_PATH="$layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
configure_graphics
export LD_PRELOAD="$layer/libdroiddeck_vr_scheduling.so${LD_PRELOAD:+:$LD_PRELOAD}"
if [ "${DROIDDECK_VR_PRESENT:-}" = questwsi ]; then
quest_settings apply || exit 1
startup_handed_off=0
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
# The pinned Frame package's CVP constructor exits on Quest's unsupported SoC.
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
if [ -f "$cvp" ]; then
disabled=$cvp.droiddeck-disabled
if [ -e "$disabled" ]; then disabled=$(mktemp "$disabled.XXXXXX") || exit 1; fi
mv "$cvp" "$disabled" || exit 1
echo "Disabled Frame-only CVP backend for Quest; SteamVR uses its normal compositor"
fi
fi
if [ "${DROIDDECK_VR_PRESENT:-}" = questframes ]; then
export DROIDDECK_VR_PRODUCER_LEASE=${DROIDDECK_VR_PRODUCER_LEASE:-1}
fi
if [ -z "${DROIDDECK_VR_DISPLAY_MODE:-}" ] && [ -x "$driver/bin/linuxarm64/xr-display-mode" ]; then
mode=$("$driver/bin/linuxarm64/xr-display-mode") || mode=
if [ -n "$mode" ]; then export DROIDDECK_VR_DISPLAY_MODE="$mode"; fi
fi
shims=$state/shims
mkdir -p "$shims"
@@ -86,11 +227,14 @@ JSON
: > "$state/active"
cd "$steamvr/bin/linuxarm64" || exit 1
setsid ./vrstartup > "$state/vrstartup.log" 2>&1 < /dev/null &
startup_log=$logs/droiddeck-vrstartup.log
ln -sf "$startup_log" "$state/vrstartup.log"
setsid ./vrstartup 8>&- 9>&- > "$startup_log" 2>&1 < /dev/null &
startup_handed_off=1
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
;;
*)
echo "usage: droiddeck-steamvr status|install|start|stop" >&2
echo "usage: droiddeck-steamvr status|install|start|stop|launch" >&2
exit 2
;;
esac
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
set -eu
[ "$#" -gt 0 ] || { echo 'usage: droiddeck-steamvr-game COMMAND [ARG...]' >&2; exit 2; }
pgrep -x vrserver >/dev/null 2>&1 || {
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
exit 1
}
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
# Quest's guest GPU images use Vulkan sharing rather than DMA-BUF modifiers.
if [ -S "/run/droiddeck/droiddeck-xr-frames" ]; then
export gamescope_vr_use_modifiers=${gamescope_vr_use_modifiers:-false}
fi
export gamescope_vr_nudge_to_visible=${gamescope_vr_nudge_to_visible:-true}
exec gamescope --backend openvr \
--vr-overlay-key "gamescope.droiddeck.game.$$" \
--vr-overlay-default-name 'DroidDeck game' \
--vr-overlay-show-immediately --vr-overlay-physical-width 2.4 -- "$@"
@@ -0,0 +1,80 @@
#!/usr/bin/python3
"""Preserve SteamVR preferences across Quest's required compositor overrides."""
import json
import os
from pathlib import Path
import sys
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}
def read(path):
try:
with path.open() as source:
settings = json.load(source)
except FileNotFoundError:
return {}
if not isinstance(settings, dict) or not isinstance(settings.get('steamvr', {}), dict):
raise ValueError('Invalid SteamVR settings object')
return settings
def write(path, value):
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
temporary = path.with_name(path.name + '.tmp')
with os.fdopen(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), 'w') as destination:
json.dump(value, destination, indent=3)
destination.write('\n')
os.replace(temporary, path)
def saved_preferences(path):
try:
backup = read(path)
if not isinstance(backup.get('section'), bool) or not isinstance(backup.get('values'), dict):
raise ValueError('invalid backup object')
for key in OVERRIDES:
entry = backup['values'].get(key)
if not isinstance(entry, list) or len(entry) != 2 or not isinstance(entry[0], bool):
raise ValueError('invalid saved preference: ' + key)
return backup
except ValueError as error:
raise ValueError(f'Invalid preference backup {path}; repair the saved section/values and retry restore. '
'The backup and current preferences have been preserved.') from error
def update(operation, settings_path, backup_path):
settings = read(settings_path)
if operation == 'apply':
if backup_path.exists():
saved_preferences(backup_path)
else:
section = settings.get('steamvr', {})
write(backup_path, {'section': 'steamvr' in settings,
'values': {key: [key in section, section.get(key)] for key in OVERRIDES}})
settings.setdefault('steamvr', {}).update(OVERRIDES)
write(settings_path, settings)
elif operation == 'restore':
if not backup_path.exists():
return
backup = saved_preferences(backup_path)
section = settings.setdefault('steamvr', {})
for key in OVERRIDES:
present, value = backup['values'][key]
if present:
section[key] = value
else:
section.pop(key, None)
if not section and not backup['section']:
settings.pop('steamvr')
write(settings_path, settings)
backup_path.unlink()
else:
raise ValueError('Expected apply or restore')
if __name__ == '__main__':
try:
update(sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]))
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
sys.exit('Could not update SteamVR settings: ' + str(error))
@@ -6,8 +6,10 @@ whoever started it: the Games tab, a pinned shortcut, or the Steam client's own
looks for the store launcher DroidDeck wrote (.droiddeck-launch.bat) among the arguments; beside it
.droiddeck-store.json says which store and game it is.
For an Epic game the game needs a fresh exchange code to sign in, which only the app can mint. The
request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both
For an Epic game, once the Epic Games Launcher is installed (droiddeck-epic), the game is started
through it: the hidden launcher signs the game in and hands its arguments back in
.droiddeck-epic-args. Without the launcher, or when it cannot, the game needs a fresh exchange code
to sign in, which only the app can mint. The request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both
sides):
req/<id>.json {"op": "epic-code", "store": "epic", "id": "<app name>"} (tmp + rename)
@@ -38,6 +40,11 @@ from pathlib import Path
LAUNCHER = ".droiddeck-launch.bat"
SIDECAR = ".droiddeck-store.json"
EPIC_CODE = ".droiddeck-epic-code"
EPIC_ARGS = ".droiddeck-epic-args"
EPIC_CLIENT = "/usr/local/bin/droiddeck-epic"
EPIC_CLIENT_CURRENT = ".local/share/droiddeck-epic/current.json"
EPIC_HANDLED = "DROIDDECK_EPIC_HANDLED"
CLIENT_TIMEOUT = 150.0
TIMEOUT = 5.0
STALE_SECONDS = 300
SERVER_WAIT = 8.0
@@ -98,6 +105,30 @@ def drop_stale(folder, now=None):
return False
def client_wanted():
home = os.environ.get("HOME") or "/root"
return os.access(EPIC_CLIENT, os.X_OK) and os.path.isfile(os.path.join(home, EPIC_CLIENT_CURRENT))
def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
extra = sidecar.get("extra") if isinstance(sidecar.get("extra"), dict) else {}
namespace, item = str(extra.get("namespace") or ""), str(extra.get("catalogItemId") or "")
if not namespace or not item:
return "no-catalog-ids"
command = [EPIC_CLIENT, "launch", "--app", str(sidecar.get("id")), "--namespace", namespace, "--item", item,
"--folder", str(folder), "--owner", str(os.getppid()), "--timeout", str(int(timeout))]
try:
run = subprocess.run(command, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, timeout=timeout + 30)
answer = json.loads(run.stdout.decode("utf-8", "replace").strip().splitlines()[-1])
except (OSError, ValueError, IndexError, subprocess.TimeoutExpired) as error:
return "error-" + type(error).__name__
if not isinstance(answer, dict):
return "no-answer"
if answer.get("ok") and (folder / EPIC_ARGS).is_file():
return "ok"
return str(answer.get("reason") or "failed")
def ask(channel, request, timeout=TIMEOUT):
"""Writes [request] under channel/req and waits for channel/resp; the answer, or None on timeout."""
req_dir, resp_dir = channel / "req", channel / "resp"
@@ -247,10 +278,16 @@ def cloud_on(sidecar):
return str(sidecar.get("store")) in CLOUD_STORES and sidecar.get("cloud", True) is not False
def exited(argv):
def exited(argv, code=0):
"""After the game: ask the app to upload what changed, without waiting for it."""
found = find_store_game(argv)
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \
and os.access(EPIC_CLIENT, os.X_OK):
try:
subprocess.run([EPIC_CLIENT, "exited", "--code", str(code)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, timeout=10)
except (OSError, subprocess.TimeoutExpired):
pass
if found is None or not launch_dir or not cloud_on(found[1]):
return 0
store, game = str(found[1].get("store")), str(found[1].get("id"))
@@ -329,7 +366,14 @@ def prepare_gog(sidecar, compat_data, launch_dir):
def main(argv):
if argv and argv[0] == "--exited":
return exited(argv[1:])
rest, code = argv[1:], 0
if rest[:1] == ["--code"] and len(rest) > 1:
try:
code = int(rest[1])
except ValueError:
pass
rest = rest[2:]
return exited(rest, code)
found = find_store_game(argv)
if found is None:
return 0
@@ -341,9 +385,27 @@ def main(argv):
if store == "gog":
prepare_gog(sidecar, compat_data, launch_dir)
if store == "epic":
drop_stale(folder)
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
drop_stale(folder)
try:
(folder / EPIC_ARGS).unlink()
except OSError:
pass
choice = options(sidecar)
if not (choice["eos"] and not choice["offline"]):
client = None
if handled:
client = "ok"
elif choice["eos"] and not choice["offline"] and client_wanted():
client = through_client(folder, sidecar)
log("epic launch id=%s client=%s" % (game, client))
if client == "ok":
try:
(folder / EPIC_CODE).unlink()
except OSError:
pass
log("epic launch id=%s through=client" % game)
elif not (choice["eos"] and not choice["offline"]):
try:
(folder / EPIC_CODE).unlink()
except OSError:
@@ -0,0 +1,46 @@
#!/bin/bash
# Runs natively: droiddeck-steam-x64's x86 wrappers start it through an arm64 binary, which FEX hands to the CPU.
tool=$1; shift
x64_home=$HOME
# The game overlay tags the game's windows with the Steam app ID; without it gamescope never shows them.
overlay=0
case ${LD_PRELOAD:-} in *gameoverlayrenderer.so*) overlay=1 ;; esac
for v in $(compgen -e); do
case $v in FEX_*) unset "$v" ;; esac
done
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME_STEAMRT STEAM_STEAMRT_RECURSION_GUARD \
LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER BL_WEBHELPER_HIDE_TRACER PROOT_FP_OFF
game_display=${DISPLAY:-}
if [ -f "$x64_home/arm-session.env" ]; then
. "$x64_home/arm-session.env"
else
export HOME=/root
fi
[ -z "$game_display" ] || export DISPLAY=$game_display
# Proton takes its Steam client parts from the client's install folder; the x86-64 client's are x86.
export BL_X64_STEAM_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-}
export STEAM_COMPAT_CLIENT_INSTALL_PATH=$HOME/.local/share/Steam
arm_overlay=$STEAM_COMPAT_CLIENT_INSTALL_PATH/steamrtarm64/gameoverlayrenderer.so
if [ "$overlay" = 1 ] && [ -f "$arm_overlay" ]; then
export LD_PRELOAD=$arm_overlay${LD_PRELOAD:+:$LD_PRELOAD}
fi
dir=$HOME/.local/share/Steam/compatibilitytools.d/$tool
manifest=$dir/toolmanifest.vdf
[ -f "$manifest" ] || { echo "droiddeck-x64-arm-proton: no tool $dir" >&2; exit 127; }
if ! grep -q droiddeck-proton-wrap "$manifest" 2>/dev/null; then
python3 - "${dir%/*}" <<'PY' >&2 || true
import importlib.machinery, importlib.util, sys
path = "/usr/local/bin/steam-compatibility"
spec = importlib.util.spec_from_file_location("compat", path, loader=importlib.machinery.SourceFileLoader("compat", path))
compat = importlib.util.module_from_spec(spec)
spec.loader.exec_module(compat)
compat.adopt_extras(sys.argv[1])
PY
fi
cmd=$(sed -n 's/^[[:space:]]*"commandline"[[:space:]]*"\([^"]*\)".*/\1/p' "$manifest" | head -n 1)
entry=${cmd%% *}
exec "$dir/${entry#/}" "$@"
@@ -0,0 +1,20 @@
#!/bin/bash
# The arm64 client's web helper for the x86-64 client, run natively: FEX hands this arm64 program to the CPU.
x64_home=$HOME
arm=/root/.local/share/Steam/steamrtarm64
for v in $(compgen -e); do
case $v in FEX_*) unset "$v" ;; esac
done
unset LD_PRELOAD LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE BL_WEBHELPER_HIDE_TRACER BL_X64_ARM_WEBHELPER
if [ -f "$x64_home/arm-session.env" ]; then
eval "$(grep -E '^declare -x (VK_ICD_FILENAMES|VK_DRIVER_FILES|GALLIUM_DRIVER|MESA_LOADER_DRIVER_OVERRIDE|LIBGL_KOPPER_DRI2|TU_DEBUG|ZINK_DEBUG|ZINK_DESCRIPTORS|MESA_NO_ERROR|MESA_DISK_CACHE_DATABASE)=' "$x64_home/arm-session.env")"
fi
export LD_LIBRARY_PATH=$arm:$arm/panorama LIBGL_KOPPER_DISABLE=true
args=()
for a in "$@"; do
case $a in --disable-gpu|--disable-gpu-compositing) ;; *) args+=("$a") ;; esac
done
cd "$arm" || exit 1
exec "$arm/steamwebhelper" "${args[@]}" --ignore-gpu-blocklist
@@ -0,0 +1,10 @@
#!/bin/bash
# Steam's compositor draws each browser window from its X pixmap: frames must reach X, not gamescope's WSI layer.
# gamescope sets vk_xwayland_wait_ready=false for its children; kopper swapchains flashed black even with the wait.
unset BL_X64_ARM_WEBHELPER
# The shim already added the GPU flags (preload/webhelper.c) to these arguments.
export BL_WEBHELPER_ARGS=stock DISABLE_GAMESCOPE_WSI=1 vk_xwayland_wait_ready=true LIBGL_KOPPER_DISABLE=true
if [ -x ./steamwebhelper ]; then
exec ./steamwebhelper "$@"
fi
exec "$HOME/.local/share/Steam/steamrt64/steamwebhelper" "$@"
@@ -21,7 +21,11 @@ FEX_LAUNCHER = "droiddeck-fex-tool"
FEX_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", FEX_LAUNCHER)
FEX_APPID = "3127680"
SNIPER_APPID = "1628350"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID)
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
FULLY_INSTALLED = 4
UPDATE_REQUIRED = 2
REQUEST_HANDOFF_SECONDS = 30
PLAYABLE_TYPES = frozenset(("game", "demo", "application", "beta"))
COMPAT_DIR = os.path.join(os.environ.get("HOME", "/root"), ".local", "share", "droiddeck-compat")
@@ -73,7 +77,7 @@ bl_run() {
if [ -n "${BL_STORE_EXIT:-}" ]; then
"$@"
rc=$?
/usr/local/bin/droiddeck-store-launch --exited "${BL_STORE_ARGS[@]}" || true
/usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}" || true
exit $rc
fi
exec "$@"
@@ -210,8 +214,40 @@ bl_idtech3() {
}
"""
# Source games report VAC-secure or insecure only in their console, written to console.log only with -condebug.
# The app keeps the switch and the records in /root: the x86-64 client runs games with its own HOME.
BL_VACDIAG_SETUP = """
bl_vacdiag() {
[ -f /root/.droiddeck-vac-diagnostics ] || return 0
[ "${verb:-}" = waitforexitandrun ] || return 0
local exe= a dir added=no app=${SteamAppId:-${STEAM_COMPAT_APP_ID:-0}}
for a in "$@"; do case $a in *.exe|*.EXE) exe=$a ;; esac; done
[ -n "$exe" ] || return 0
dir=$(dirname "$exe")
# Source: <mod>/gameinfo.txt beside the exe. Source 2: game/bin/win64/<exe> with game/<mod>/gameinfo.gi.
if ls "$dir"/*/gameinfo.txt >/dev/null 2>&1 || ls "$dir"/../../*/gameinfo.gi >/dev/null 2>&1; then
case " $* " in
*" -condebug "*) echo "droiddeck-proton: vac-diag: app $app already has -condebug" >&2 ;;
*) BL_EXTRA_ARGS+=(-condebug); added=yes
echo "droiddeck-proton: vac-diag: app $app is a Source title; launched with -condebug" >&2 ;;
esac
else
added=not-source
echo "droiddeck-proton: vac-diag: app $app is not a Source title; it keeps no console log to read" >&2
fi
case " $* " in
*" -insecure "*) echo "droiddeck-proton: vac-diag: app $app has -insecure in its launch options - it can never be VAC-secure this way" >&2 ;;
esac
printf '%s\tapp %s\tcondebug %s\t%s\n' "$(date +%s)" "$app" "$added" "${exe##*/}" >> /root/.droiddeck-vac-launches
}
"""
BL_DIRECTAUDIO_SETUP = """
bl_directaudio() {
case "${verb:-}" in
run|waitforexitandrun|runinprefix) ;;
*) return 0 ;;
esac
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
@@ -305,6 +341,7 @@ if [ -n "$depot" ]; then
bl_directaudio "$depot"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
bl_libpath
BL_STORE_PROTON="$depot/proton"; export BL_STORE_PROTON
bl_store_launch "$@"
@@ -320,7 +357,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -359,6 +396,7 @@ bl_components "$here"
bl_directaudio "$here"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
bl_libpath
BL_STORE_PROTON="$here/%s"; export BL_STORE_PROTON
bl_store_launch "$@"
@@ -586,7 +624,7 @@ def adopt_extras(tools):
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
@@ -660,6 +698,26 @@ def launch_programs(config):
return found
def launch_options(config):
"""An app's launch options as Steam lists them: executable, arguments, working folder, type and oslist."""
launch = config.get("launch") if isinstance(config, dict) else None
found = []
for key, option in launch.items() if isinstance(launch, dict) else ():
if not isinstance(option, dict) or not option.get("executable"):
continue
settings = option.get("config") if isinstance(option.get("config"), dict) else {}
found.append({
"key": str(key),
"executable": str(option["executable"]),
"arguments": str(option.get("arguments", "")),
"workingdir": str(option.get("workingdir", "")),
"type": str(option.get("type", "")).lower(),
"oslist": str(settings.get("oslist", "")).lower(),
"betakey": str(settings.get("betakey", "")),
})
return found
def appinfo_entries(path):
import struct
try:
@@ -751,6 +809,7 @@ def appinfo_entries(path):
"type": str(common.get("type", "")).lower(),
"recommended": str(recommended),
"launch": launch_programs(info.get("config")),
"launch_options": launch_options(info.get("config")),
}
if app == STEAM_PLAY_MANIFESTS:
extended = info.get("extended", {})
@@ -787,17 +846,46 @@ def native_targets(steam_root, apps):
return {}
targets = {}
for app, (oslist, osarch, kind) in appinfo_platforms(os.path.join(steam_root, "appcache", "appinfo.vdf"), wanted).items():
if kind not in PLAYABLE_TYPES or "windows" in oslist or "linux" not in oslist:
if kind not in PLAYABLE_TYPES or "linux" not in oslist:
continue
if "arm64" in osarch or "aarch64" in osarch:
targets[app] = None
continue
if "windows" in oslist:
targets[app] = NATIVE_CHOICE
continue
targets[app] = FEX_TOOL
return targets
def linux_runtime_tool(name):
low = name.lower()
return low == "fex" or low.startswith("steamlinuxruntime")
def app_manifest(steam_root, app):
for library in libraries(steam_root):
try:
with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f:
return tokenize(f.read())
except OSError:
continue
return None
def manifest_flags(tokens):
for i in range(len(tokens) - 1):
if tokens[i].lower() == '"stateflags"':
value = tokens[i + 1].strip('"')
return int(value) if value.isdigit() else 0
return 0
def tool_downloads(steam_root):
"""(app, "install" or "update") for each tool the client has yet to install or bring up to date."""
wanted = []
for app in REQUIRED_TOOLS:
tokens = app_manifest(steam_root, app)
if tokens is None:
wanted.append((app, "install"))
elif not manifest_flags(tokens) & FULLY_INSTALLED or manifest_flags(tokens) & UPDATE_REQUIRED:
wanted.append((app, "update"))
return wanted
def fex_missing(steam_root):
@@ -877,18 +965,22 @@ def app_order(app):
DEFERRED_GAME_TOOL = object()
NATIVE_CHOICE = object()
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None):
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
native_choices=()):
runnable = {n.lower() for n in runnable}
installed = set(installed)
picks = set(picks)
native = native or {}
overrides = overrides or {}
managed = set(auto) if managed is None else set(managed)
native_choices = set(native_choices)
changes, kept = {}, {}
if current.get("0", "") != default:
changes["0"] = default
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides)) - {"0"}, key=app_order):
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides) | native_choices) - {"0"}, key=app_order):
name = current.get(app, "")
if app in overrides:
target = overrides[app]
@@ -902,9 +994,26 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
continue
mine = auto.get(app)
target = native.get(app, default)
stale = unrunnable(name, runnable) or (app in native and linux_runtime_tool(name))
if not name and app in native_choices:
target = NATIVE_CHOICE
stale = unrunnable(name, runnable)
if name and not stale and (mine is None or name != mine):
continue
if target is NATIVE_CHOICE:
if not name and (app in native_choices or app in current or app in managed):
kept[app] = NATIVE_CHOICE
continue
target = default
if target is None:
if stale:
target = default
if name != target:
changes[app] = target
continue
else:
if name and app in managed and name == mine:
changes[app] = None
continue
if not name and app not in installed and app not in picks:
continue
if name != target:
@@ -1043,8 +1152,37 @@ def read_mapping(tokens, mapping):
return current
def read_config_mapping(config_path):
"""Read per-app choices without creating or rewriting the client's mapping block."""
try:
with open(config_path, encoding="utf-8", errors="replace") as f:
tokens = tokenize(f.read())
except OSError:
return None
depth = 0
for token in tokens:
if token == "{":
depth += 1
elif token == "}":
depth -= 1
if depth < 0:
return None
if depth != 0:
return None
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
if steam is None:
return None
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
return read_mapping(tokens, mapping + steam + 1) if mapping is not None else {}
def set_mapping(tokens, mapping, app, tool):
block = find_block(tokens[mapping + 1:], [app])
if tool is None:
if block is not None:
block += mapping + 1
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"', "}"]
@@ -1074,6 +1212,21 @@ def steam_running():
return False
def game_running():
try:
pids = [p for p in os.listdir("/proc") if p.isdigit()]
except OSError:
return False
for pid in pids:
try:
with open("/proc/%s/cmdline" % pid, "rb") as f:
if b"\0SteamLaunch\0AppId=" in f.read():
return True
except OSError:
continue
return False
def live_helper_running(directory=None):
try:
with open(state_path("live.pid", directory)) as f:
@@ -1084,7 +1237,8 @@ def live_helper_running(directory=None):
return False
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=()):
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=(),
linux_tool=FEX_TOOL):
"""Writes the mapping: the "0" default and every title that follows it (see plan_mapping).
With settle, the default itself is decided first (see choose_default): before the client
starts, config.vdf holds what the client last kept, menu changes included."""
@@ -1108,14 +1262,22 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
default = state.get("default") if state.get("default") in names else TOOL
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
overrides = requested_games(game_requests(directory), catalog)
managed = state.get("auto", {}).keys() if isinstance(state.get("auto"), dict) else ()
native_choices = state.get("native_choices", ())
native = native_targets(steam_root, set(apps) | set(picks) | set(managed) | set(native_choices))
if linux_tool != FEX_TOOL:
native = {app: linux_tool if tool == FEX_TOOL else tool for app, tool in native.items()}
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks, overrides)
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)
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config_path, text)
state["auto"] = auto
state["auto"] = {app: tool for app, tool in auto.items() if tool is not NATIVE_CHOICE}
state["native_choices"] = sorted(app for app, tool in auto.items() if tool is NATIVE_CHOICE)
state.pop("native", None)
state["tools"] = catalog
state.setdefault("default", default)
write_json(state_path("state.json", directory), state)
@@ -1171,8 +1333,71 @@ def remove_tool(tool_dir):
shutil.rmtree(tool_dir)
def local_tools(steam_root):
"""The names of the compatibility tools installed in steam_root/compatibilitytools.d."""
names = set()
tools = os.path.join(steam_root, "compatibilitytools.d")
try:
entries = os.listdir(tools)
except OSError:
return names
for entry in entries:
try:
with open(os.path.join(tools, entry, "compatibilitytool.vdf"), encoding="utf-8", errors="replace") as f:
m = re.search(r'"compat_tools"\s*\{\s*"([^"]+)"', f.read())
except OSError:
continue
if m:
names.add(m.group(1).lower())
return names
def x64_repoint(steam_root, tool, live=False):
"""The x86-64 client (droiddeck-steam-x64): its tools are arm64 wrappers that script makes and
its Linux titles run as Linux builds (FEX), so only the entries the client aimed at a Proton it
cannot start are repointed, to `tool`. Tools in its own compatibilitytools.d are kept: the
wrappers include proton-cachyos-*-a64, which starts with "proton" like Valve's own.
Returns the app ids repointed."""
config = os.path.join(steam_root, "config", "config.vdf")
if not tool or not os.path.isfile(config):
return []
with open(config, encoding="utf-8", errors="replace") as f:
original = f.read()
tokens = tokenize(original)
mapping = mapping_block(tokens)
if mapping is None:
return []
keep = local_tools(steam_root)
moved = []
current = read_mapping(tokens, mapping)
if "0" not in current:
set_mapping(tokens, mapping, "0", tool)
for app, name in current.items():
named = name.lower()
# A tool named arm64 is never this client's (its wrappers are -a64), so this legacy name is always repointed.
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)
if app != "0":
moved.append(app)
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config, text)
print("steam-compatibility: x86-64 client's Proton entries point at %s" % tool)
# Steam reads a mapping changed while it runs only at its next start; the session restarts it (.bl-compat-pending).
if moved and live:
with open(os.path.join(os.path.expanduser("~"), ".bl-compat-pending"), "a") as f:
f.write("".join("%s\n" % a for a in moved))
print("steam-compatibility: repointed while the client runs: %s" % " ".join(moved))
return moved
def main():
steam_root = sys.argv[1]
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("BL_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
tools = os.path.join(steam_root, "compatibilitytools.d")
os.makedirs(tools, exist_ok=True)
legacy = os.path.join(tools, LEGACY_TOOL)
+4 -2
View File
@@ -91,7 +91,8 @@ static int enabled(void) {
if (cached < 0) {
const char *off = getenv("BL_NO_DIR_CACHE");
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL && !(off && strcmp(off, "1") == 0);
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
strstr(program_invocation_name, "steamrt64") != NULL) && !(off && strcmp(off, "1") == 0);
if (cached) pthread_atfork(NULL, NULL, after_fork);
}
return cached && !forked;
@@ -256,9 +257,10 @@ static void install(struct listing *l) {
int slot = find(l->dev, l->ino);
if (slot >= 0) {
struct listing *old = table[slot];
int old_wd = old->wd;
table[slot] = l;
detach(old);
if (old->wd != l->wd) release(old->wd);
if (old_wd != l->wd) release(old_wd);
return;
}
int victim = -1;
+20
View File
@@ -5,10 +5,12 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <limits.h>
#include <linux/input.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
@@ -176,6 +178,24 @@ static int caller_is_winebus(void *caller) {
return strstr(info.dli_fname, "winebus.so") != NULL;
}
/* Wine's HID haptics give every XInput rumble a 1000 ms cutoff and xinput only writes on a change,
* but XInput motors hold their speed until the next XInputSetState; evdev's length 0 holds until
* stopped. Only this library, preloaded first, sees winebus as the caller. The length is put back
* because winebus compares its copy with the next state to decide whether to upload again. */
__attribute__((visibility("hidden"))) int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd,
unsigned long request, void *arg, void *caller,
int *rc) {
struct ff_effect *effect = arg;
__u16 length;
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE || !caller_is_winebus(caller)) return 0;
length = effect->replay.length;
effect->replay.length = 0;
*rc = real(fd, request, arg);
effect->replay.length = length;
return 1;
}
char *realpath(const char *path, char *resolved) {
static char *(*real_realpath)(const char *, char *);
void *caller = __builtin_return_address(0);
+42 -3
View File
@@ -6,6 +6,7 @@
#include <linux/netlink.h>
#include <netinet/in.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
@@ -262,6 +263,7 @@ __attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, ch
__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]);
__attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
spawn_fn real);
@@ -308,10 +310,39 @@ static int maybe_answer_lsof(const char *path, char *const argv[]) {
_exit(0);
}
int execve(const char *path, char *const argv[], char *const envp[]) {
static char **web_helper_redirect(const char *path, char *const argv[], const char **launcher) {
const char *want = getenv("BL_X64_ARM_WEBHELPER");
if (!want || !*want || !path) return NULL;
const char *base = strrchr(path, '/');
if (strcmp(base ? base + 1 : path, "steamwebhelper") != 0) return NULL;
if (!strstr(path, "/steamrt64/")) {
char cwd[PATH_MAX];
size_t n;
if (path[0] == '/' || !getcwd(cwd, sizeof(cwd))) return NULL;
n = strlen(cwd);
if (n < 10 || strcmp(cwd + n - 10, "/steamrt64") != 0) return NULL;
}
int argc = 0;
while (argv && argv[argc]) argc++;
char **out = calloc((size_t)argc + 2, sizeof(char *));
if (!out) return NULL;
out[0] = (char *)want;
for (int i = 1; i < argc; i++) out[i] = argv[i];
*launcher = want;
return out;
}
int execve(const char *path, char *const argv_in[], char *const envp[]) {
char *const *argv = bl_webhelper_argv(path, argv_in);
static int (*real)(const char *, char *const[], char *const[]);
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execve");
maybe_answer_lsof(path, argv);
const char *launcher = NULL;
char **redirected = web_helper_redirect(path, argv, &launcher);
if (redirected) {
real(launcher, redirected, envp);
free(redirected);
}
bl_binfmt_before(path, argv, envp);
real(path, argv, envp);
return bl_binfmt_retry(path, argv, envp, errno);
@@ -332,7 +363,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
return 0;
}
int execvp(const char *file, char *const argv[]) {
int execvp(const char *file, char *const argv_in[]) {
char *const *argv = bl_webhelper_argv(file, argv_in);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
maybe_answer_lsof(file, argv);
@@ -341,10 +373,17 @@ int execvp(const char *file, char *const argv[]) {
return bl_binfmt_after_search(file, argv, environ, errno);
}
int execv(const char *path, char *const argv[]) {
int execv(const char *path, char *const argv_in[]) {
char *const *argv = bl_webhelper_argv(path, argv_in);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execv");
maybe_answer_lsof(path, argv);
const char *launcher = NULL;
char **redirected = web_helper_redirect(path, argv, &launcher);
if (redirected) {
real(launcher, redirected);
free(redirected);
}
bl_binfmt_before(path, argv, environ);
real(path, argv);
return bl_binfmt_retry(path, argv, environ, errno);
+8 -5
View File
@@ -406,6 +406,8 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long
void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
int ioctl(int fd, unsigned long request, ...) {
typedef int (*ioctl_fn)(int, unsigned long, void *);
@@ -419,6 +421,7 @@ int ioctl(int fd, unsigned long request, ...) {
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
bl_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
@@ -535,11 +538,11 @@ static FILE *synthesize(const char *table) {
return out;
}
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
static FILE *open_stream(fopen_fn real, const char *path, const char *mode) {
static FILE *open_stream(fopen_fn real, const char *path, const char *mode, const void *caller) {
int status = mode && mode[0] == 'r' && !strchr(mode, '+')
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC) : -1;
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC, caller) : -1;
if (status >= 0) {
FILE *copy = fdopen(status, "r");
if (copy == NULL) close(status);
@@ -557,11 +560,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode) {
FILE *fopen(const char *path, const char *mode) {
static fopen_fn real;
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen");
return open_stream(real, path, mode);
return open_stream(real, path, mode, __builtin_return_address(0));
}
FILE *fopen64(const char *path, const char *mode) {
static fopen_fn real;
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen64");
return open_stream(real, path, mode);
return open_stream(real, path, mode, __builtin_return_address(0));
}
+3 -3
View File
@@ -11,7 +11,7 @@
#include <string.h>
#include <sys/types.h>
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
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")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
@@ -51,7 +51,7 @@ int open(const char *path, int flags, ...) {
errno = EACCES;
return -1;
}
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
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 (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
if (real_open == NULL) {
@@ -76,7 +76,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
errno = EACCES;
return -1;
}
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
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 (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
if (real_openat == NULL) {
+2 -1
View File
@@ -42,7 +42,8 @@ static int enabled(void) {
if (cached >= 0) return cached;
off = getenv("BL_NO_PATH_CACHE");
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL &&
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
strstr(program_invocation_name, "steamrt64") != NULL) &&
!(off != NULL && off[0] == '1');
return cached;
}
+1 -1
View File
@@ -7,7 +7,7 @@
#include <unistd.h>
static int in_steam_dirs(const char *path) {
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL || strstr(path, "/Steam/steamrt64/") != NULL
|| strstr(path, "/Steam/ubuntu12_64/") != NULL || strstr(path, "/Steam/linuxarm64/") != NULL);
}
+55
View File
@@ -0,0 +1,55 @@
/* In Deck mode (-steamos3) the x86-64 client's SteamOS audio manager passes libpulse the NULL operation of a
* failed request, and libpulse aborts on it ("Assertion 'o' failed ... pa_operation_get_state()"). */
#if defined(__x86_64__) || defined(__i386__)
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stddef.h>
typedef struct pa_operation pa_operation;
#define PA_OPERATION_CANCELLED 2
/* A libpulse loaded with RTLD_LOCAL (Wine's winepulse.so) is not in RTLD_NEXT's scope. */
static void *libpulse(const char *name) {
void *fn = dlsym(RTLD_NEXT, name);
if (!fn) {
void *handle = dlopen("libpulse.so.0", RTLD_LAZY | RTLD_NOLOAD);
if (handle) {
fn = dlsym(handle, name);
dlclose(handle);
}
}
return fn;
}
int pa_operation_get_state(pa_operation *o) {
static int (*next)(pa_operation *);
if (!o)
return PA_OPERATION_CANCELLED;
if (!next)
next = (int (*)(pa_operation *))libpulse("pa_operation_get_state");
return next ? next(o) : PA_OPERATION_CANCELLED;
}
void pa_operation_unref(pa_operation *o) {
static void (*next)(pa_operation *);
if (!o)
return;
if (!next)
next = (void (*)(pa_operation *))libpulse("pa_operation_unref");
if (next)
next(o);
}
void pa_operation_cancel(pa_operation *o) {
static void (*next)(pa_operation *);
if (!o)
return;
if (!next)
next = (void (*)(pa_operation *))libpulse("pa_operation_cancel");
if (next)
next(o);
}
#else
typedef int pulseguard_arm_build_has_nothing_to_do;
#endif
+178
View File
@@ -2,13 +2,18 @@
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/futex.h>
#include <linux/magic.h>
#include <pthread.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/vfs.h>
#include <unistd.h>
#ifndef SYS_openat2
@@ -17,6 +22,17 @@
#define BL_RESOLVE_BENEATH 0x08
#define BL_RESOLVE_IN_ROOT 0x10
// The kernel's MAXSYMLINKS.
#define BL_MAX_SYMLINKS 40
#define BL_PROC_ROOT_INO 1
#ifdef SYS_newfstatat
#define BL_SYS_FSTATAT SYS_newfstatat
typedef struct stat bl_stat;
#else
#define BL_SYS_FSTATAT SYS_fstatat64
typedef struct stat64 bl_stat;
#endif
struct bl_open_how {
uint64_t flags;
@@ -25,8 +41,22 @@ struct bl_open_how {
};
static long (*real_syscall)(long, ...);
static void *(*real_dlopen)(const char *, int);
static int openat2_missing;
void *dlopen(const char *filename, int flags) {
if (!real_dlopen) {
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
}
const char *basename = filename ? strrchr(filename, '/') : NULL;
basename = basename ? basename + 1 : filename;
// Steam's deep binding bypasses the robust-list shim under PRoot.
if (basename && strcmp(basename, "vrclient.so") == 0) {
flags &= ~RTLD_DEEPBIND;
}
return real_dlopen(filename, flags);
}
int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
static struct robust_list_head *thread_robust_head(void) {
@@ -61,6 +91,151 @@ static struct robust_list_head *thread_robust_head(void) {
return head;
}
// Magic links are procfs links below a process's directory; procfs's root holds only plain ones (self, thread-self, mounts).
static int is_magic_link(int dirfd, char *link, size_t parent_len) {
int fd = (int)real_syscall(SYS_openat, (long)dirfd, (long)link, (long)(O_PATH | O_NOFOLLOW | O_CLOEXEC), 0L);
if (fd < 0) {
return 0;
}
struct statfs fs;
int procfs = real_syscall(SYS_fstatfs, (long)fd, (long)&fs) == 0 && fs.f_type == PROC_SUPER_MAGIC;
real_syscall(SYS_close, (long)fd);
if (!procfs) {
return 0;
}
char saved = link[parent_len];
link[parent_len] = 0;
bl_stat parent;
long result = real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)(parent_len ? link : "."), (long)&parent, 0L);
link[parent_len] = saved;
return result != 0 || parent.st_ino != BL_PROC_ROOT_INO;
}
// RESOLVE_IN_ROOT walked one component at a time: absolute symlinks restart at dirfd and ".." stops there.
static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
char resolved[PATH_MAX];
char pending[PATH_MAX];
size_t resolved_len = 0;
int symlinks = 0;
int have_root = 0;
int root_on_procfs = 0;
dev_t root_dev = 0;
// O_NOFOLLOW and O_CREAT | O_EXCL leave a final symlink alone, unless a trailing slash follows it.
int nofollow = (flags & O_NOFOLLOW) || (flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
const char *rest = path;
for (;;) {
while (*rest == '/') {
rest++;
}
if (!*rest) {
break;
}
const char *name = rest;
const char *end = name;
while (*end && *end != '/') {
end++;
}
size_t len = (size_t)(end - name);
rest = end;
while (*rest == '/') {
rest++;
}
int last = !*rest;
int trailing_slash = last && rest != end;
if (len == 1 && name[0] == '.') {
continue;
}
if (len == 2 && name[0] == '.' && name[1] == '.') {
while (resolved_len > 0 && resolved[resolved_len - 1] != '/') {
resolved_len--;
}
if (resolved_len > 0) {
resolved_len--;
}
continue;
}
size_t separator = resolved_len > 0;
size_t candidate_len = resolved_len + separator + len;
if (candidate_len + 1 >= PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
if (separator) {
resolved[resolved_len] = '/';
}
memcpy(resolved + resolved_len + separator, name, len);
resolved[candidate_len] = 0;
bl_stat st;
int follow = !last || trailing_slash || !nofollow;
long stat_result = follow ? real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)resolved, (long)&st, (long)AT_SYMLINK_NOFOLLOW) : -1;
if (stat_result == 0 && S_ISLNK(st.st_mode)) {
if (++symlinks > BL_MAX_SYMLINKS) {
errno = ELOOP;
return -1;
}
if (!have_root) {
bl_stat root;
struct statfs root_fs;
if (real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)".", (long)&root, 0L) != 0) {
return -1;
}
root_dev = root.st_dev;
root_on_procfs = real_syscall(SYS_fstatfs, (long)dirfd, (long)&root_fs) == 0 && root_fs.f_type == PROC_SUPER_MAGIC;
have_root = 1;
}
if ((st.st_dev != root_dev || root_on_procfs) && is_magic_link(dirfd, resolved, resolved_len)) {
// RESOLVE_IN_ROOT refuses magic links.
errno = EXDEV;
return -1;
}
size_t rest_len = strlen(end);
if (rest_len + 1 >= PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
char *tail = pending + PATH_MAX - rest_len - 1;
memmove(tail, end, rest_len + 1);
long target_len = real_syscall(SYS_readlinkat, (long)dirfd, (long)resolved, (long)pending, (long)(PATH_MAX - rest_len));
if (target_len <= 0) {
if (target_len == 0) {
errno = ENOENT;
}
return -1;
}
if ((size_t)target_len + rest_len >= PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
memmove(pending + target_len, tail, rest_len + 1);
if (pending[0] == '/') {
resolved_len = 0;
}
rest = pending;
continue;
}
if (last) {
resolved_len = candidate_len;
if (trailing_slash) {
resolved[resolved_len++] = '/';
}
break;
}
if (stat_result != 0) {
return -1;
}
if (!S_ISDIR(st.st_mode)) {
errno = ENOTDIR;
return -1;
}
resolved_len = candidate_len;
}
if (resolved_len == 0) {
resolved[resolved_len++] = '.';
}
resolved[resolved_len] = 0;
return real_syscall(SYS_openat, (long)dirfd, (long)resolved, (long)flags, mode);
}
static long openat2_via_openat(const long *args) {
const char *path = (const char *)args[1];
const struct bl_open_how *how = (const struct bl_open_how *)args[2];
@@ -68,6 +243,9 @@ static long openat2_via_openat(const long *args) {
errno = EINVAL;
return -1;
}
if ((how->resolve & BL_RESOLVE_IN_ROOT) && (int)args[0] != AT_FDCWD) {
return openat_in_root((int)args[0], path, (int)how->flags, (long)how->mode);
}
if (how->resolve & BL_RESOLVE_IN_ROOT) {
while (*path == '/') {
path++;
+2 -1
View File
@@ -145,7 +145,8 @@ static int steam_client(void) {
static int cached = -1;
if (cached < 0)
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL;
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
strstr(program_invocation_name, "steamrt64") != NULL);
return cached;
}
+14 -5
View File
@@ -4,8 +4,10 @@
#define _GNU_SOURCE
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
@@ -31,9 +33,16 @@ static int is_status_path(const char *path) {
return strcmp(rest, "/status") == 0;
}
static int is_web_helper(void) {
return strcmp(program_invocation_short_name, "steamwebhelper") == 0 ||
strcmp(program_invocation_short_name, "vrwebhelper") == 0;
static int is_web_helper(const void *caller) {
if (strcmp(program_invocation_short_name, "steamwebhelper") != 0 &&
strcmp(program_invocation_short_name, "vrwebhelper") != 0)
return 0;
const char *hide = getenv("BL_WEBHELPER_HIDE_TRACER");
Dl_info info;
if (hide && hide[0] == '1' && caller && dladdr(caller, &info) && info.dli_fname
&& strstr(info.dli_fname, "libtier0_s.so"))
return 0;
return 1;
}
static int write_all(int fd, const char *data, size_t len) {
@@ -47,13 +56,13 @@ static int write_all(int fd, const char *data, size_t len) {
return 0;
}
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags) {
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) {
char text[STATUS_MAX];
size_t len = 0;
int saved = errno;
int out = -1;
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper()) return -1;
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper(caller)) return -1;
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (in < 0) goto done;
for (;;) {
+73
View File
@@ -0,0 +1,73 @@
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#ifndef WEBHELPER_DEFAULT
#define WEBHELPER_DEFAULT "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
#endif
static int is_webhelper_browser(const char *path, char *const argv[]) {
if (!path || !argv) return 0;
const char *base = strrchr(path, '/');
base = base ? base + 1 : path;
if (strcmp(base, "steamwebhelper")) return 0;
for (int i = 1; argv[i]; i++)
if (!strncmp(argv[i], "--type=", 7)) return 0;
return 1;
}
static char *join_features(const char *have, const char *add) {
size_t a = have ? strlen(have) : 0, b = strlen(add);
char *out = malloc(a + b + 2);
if (!out) return NULL;
out[0] = 0;
if (a) strcat(strcat(out, have), ",");
return strcat(out, add);
}
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]) {
if (!is_webhelper_browser(path, argv)) return argv;
const char *spec = getenv("BL_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;
int argc = 0;
while (argv[argc]) argc++;
char *tokens = strdup(spec);
if (!tokens) return argv;
int extra = 0;
for (char *c = tokens; *c; c++)
if (*c == ' ') extra++;
char **out = calloc(argc + extra + 4, sizeof *out);
if (!out) return argv;
const char *enable = NULL, *disable = NULL;
int n = 0;
for (int i = 0; i < argc; i++) {
if (i && !strncmp(argv[i], "--enable-features=", 18)) enable = argv[i] + 18;
else if (i && !strncmp(argv[i], "--disable-features=", 19)) disable = argv[i] + 19;
else out[n++] = argv[i];
}
char *add_enable = NULL, *add_disable = NULL, *save = NULL;
for (char *t = strtok_r(tokens, " ", &save); t; t = strtok_r(NULL, " ", &save)) {
if (t[0] == '+' && t[1]) {
char *joined = join_features(add_enable, t + 1);
free(add_enable);
add_enable = joined;
} else if (t[0] == '-' && t[1] && t[1] != '-') {
char *joined = join_features(add_disable, t + 1);
free(add_disable);
add_disable = joined;
} else if (!strncmp(t, "--", 2)) {
out[n++] = t;
}
}
char *merged;
if (add_enable && (merged = join_features(enable, add_enable))) enable = merged;
if (add_disable && (merged = join_features(disable, add_disable))) disable = merged;
char *flag;
if (enable && (flag = malloc(strlen(enable) + 19))) out[n++] = strcat(strcpy(flag, "--enable-features="), enable);
if (disable && (flag = malloc(strlen(disable) + 20))) out[n++] = strcat(strcpy(flag, "--disable-features="), disable);
out[n] = NULL;
return out;
}
+348
View File
@@ -0,0 +1,348 @@
"""Prepare the audited Windows runtime from a pinned APK and rebuilt replacements.
The donor was built from a CI merge, not just the PR head. Only unchanged
components are reused. Session helpers come from this checkout, libblsession
must be rebuilt for all three architectures, Gamescope comes from the current
checksum-pinned release, and the VR components are rebuilt in Docker (or reused
from a verified build manifest). Store engines are omitted (build with skipRust).
"""
import argparse
import hashlib
import io
import json
from pathlib import Path, PurePosixPath
import shutil
import struct
import subprocess
import sys
import tarfile
import tempfile
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/release'))
import runtime_inputs as runtime
from check_session_assets import source_assets
sys.path.insert(0, str(ROOT / 'tools/vr'))
import build_windows as vr_build
DONOR_SHA256 = 'b7efef6442f384446bdd1750cec21f0eda61b370bc21d9f55187448e5c256760'
DONOR_PR_SOURCE = 'bdf876d47cc9bb6fa810d014370da5bbb3c28039'
DONOR_MAIN_SOURCE = '46fac69438ed428f2ca43ea935cd47790264f380'
DONOR_TREE = 'ddbca4d572b809fb969be0cf80ef83d6ef6580ce'
DONOR_REVISION = 'cf24c5f2c771633ea426046006c2b977c7bd7d32'
DONOR_CERT_SHA256 = 'b241ea7d77822d39b89d3227e06f3ecf62adec6cbfd38ad06196787991b5d3f0'
DONOR_URL = 'https://github.com/Droid-Deck/DroidDeck-CI/releases/download/pr-732/DroidDeck-PR.732-bdf876d.apk'
AUDITED_SOURCE = '1dc66bf9be64a404c80400049c0803614814461b'
LOCAL_BUILD_PLUMBING = {'app/build.gradle', 'tools/release/runtime_inputs.py'}
# These Android-only inputs are compiled by Gradle, never taken from the donor.
# Keep this list explicit so unrelated native or Linux runtime edits still fail.
LOCAL_ANDROID_SOURCES = {'app/src/main/cpp/CMakeLists.txt',
'app/src/main/cpp/viture/sdk_bridge.cpp',
'app/src/main/cpp/viture/display_modes.h',
'app/src/main/cpp/viture/stereo_frame_gate.h',
'app/src/main/cpp/viture/uvc_bridge.cpp',
'app/src/main/cpp/waylandcomp/src/cardboard.c',
'app/src/main/cpp/waylandcomp/src/cardboard.h',
'app/src/main/cpp/waylandcomp/src/cardboard.frag',
'app/src/main/cpp/waylandcomp/src/cardboard_frag.h',
'app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c',
'app/src/main/cpp/waylandcomp/src/spatialpose.c',
'app/src/main/cpp/waylandcomp/CMakeLists.txt'}
# These audited helper updates are copied from this checkout by runtime.record().
# Permit them only while source_assets() still guarantees that staging path.
LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr'}
VR_PREFIX = 'assets/linuxfs/usr/local/lib/droiddeck-vr/'
CHECK_PATHS = list(dict.fromkeys(runtime.SOURCE_PATHS + [
'app/src/main/cpp', 'app/src/main/jniLibs', 'app/src/main/rust/stores', 'tools/vr']))
REBUILT = {'libblsession.so': 183, 'x86_64/libblsession.so': 62, 'i386/libblsession.so': 3}
REBUILT_SHA256 = {
'libblsession.so': '1093ce33ca6d0a17a2eec7b3a3cc53969b01ffc459aef16b320cd3857825b738',
'x86_64/libblsession.so': 'd0a558fee1ac4d5b898170a96b03e15610d9835e7097425027b8c31728da870a',
'i386/libblsession.so': '785d8d9bf1fa20d083a7fed65d064c7580684d7065530d95a648e2d32901d2a2',
}
JNI = ('libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so')
PREPARED = ('pulseaudio.tzst',
'graphics_driver/adrenotools-turnip25.1.0-quest1.tzst',
'graphics_driver/adrenotools-turnip26.3.0-a6xx.tzst',
'graphics_driver/adrenotools-turnip26.3.0-quest2.tzst')
def git(*args):
return subprocess.check_output(['git', '-C', str(ROOT), *args])
def changed(base, target=None):
args = ['diff', '--no-ext-diff', '--ignore-cr-at-eol', '--name-only', '-z', base]
if target:
args.append(target)
return set(filter(None, git(*args, '--', *CHECK_PATHS).decode().split('\0')))
def check_sources():
# A branch label alone is insufficient: CI merged this main commit into it.
if git('merge-tree', '--write-tree', DONOR_PR_SOURCE, DONOR_MAIN_SOURCE).decode().splitlines()[0] != DONOR_TREE:
raise ValueError('The donor CI merge does not match the audited source tree')
helper_sources = {path.relative_to(ROOT).as_posix() for path in source_assets()}
reviewed = LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | (LOCAL_SESSION_HELPERS & helper_sources)
unexpected = {p for p in changed(AUDITED_SOURCE, 'HEAD') - reviewed if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Sources changed since the component audit:\n' + '\n'.join(sorted(unexpected)))
local = changed('HEAD')
untracked = set(filter(None, git('ls-files', '--others', '--exclude-standard', '-z',
'--', *CHECK_PATHS).decode().split('\0')))
unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES)
if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Unreviewed runtime/native/Rust changes:\n' + '\n'.join(sorted(unexpected)))
classifications = {}
for path in sorted(changed(DONOR_TREE, 'HEAD') | local | untracked):
if vr_build.is_source(path):
action = 'VR component rebuilt from current source and verified; never imported from donor'
elif path in LOCAL_ANDROID_SOURCES:
action = 'Android native source compiled by Gradle; not imported from donor'
elif path.startswith('app/src/main/rust/stores/'):
action = 'store engines omitted; Gradle must use skipRust=true'
elif path in helper_sources:
action = 'restaged from current source with LF line endings'
elif path in {'tools/linuxfs/preload/net.c', 'tools/linuxfs/preload/webhelper.c'}:
action = 'all three libblsession libraries rebuilt from current source'
elif path == 'tools/gamescope/release.env':
action = 'current checksum-pinned Gamescope archive replaces donor'
elif path in {'tools/build_local.sh', 'tools/directaudio/fetch.sh'}:
action = 'audited download/build cache plumbing; component inputs unchanged'
elif path == 'app/src/main/cpp/waylandcomp/src/compositor.c':
action = 'Android native library rebuilt by Gradle; not imported'
elif path in LOCAL_BUILD_PLUMBING:
action = 'local Windows build plumbing; changes recorded below'
else:
raise ValueError('Unclassified donor source difference: ' + path)
classifications[path] = action
return classifications
def validate_relative(name):
path = PurePosixPath(name)
if path.is_absolute() or not path.parts or any(part in {'.', '..'} or ':' in part for part in path.parts):
raise ValueError('Unsafe archive member: ' + name)
if '\\' in name:
raise ValueError('Backslash in archive member: ' + name)
return path
def checked_output(relative):
validate_relative(relative)
target = (ROOT / relative).resolve()
if not target.is_relative_to(ROOT.resolve()):
raise ValueError('Output escapes the checkout: ' + relative)
if git('ls-files', '--', relative).strip():
raise ValueError('Refusing to overwrite tracked file: ' + relative)
return target
def read_gamescope(path):
pins = dict(line.split('=', 1) for line in (ROOT / 'tools/gamescope/release.env').read_text().splitlines()
if line and not line.startswith('#'))
if runtime.digest(path) != pins['GAMESCOPE_SHA256']:
raise ValueError('Gamescope archive checksum does not match tools/gamescope/release.env')
data = subprocess.run(['zstd', '-dc', str(path)], capture_output=True, check=True).stdout
files = {}
with tarfile.open(fileobj=io.BytesIO(data)) as archive:
for member in archive:
name = member.name.removeprefix('./')
validate_relative(name)
if member.isdir():
continue
if not member.isfile():
raise ValueError('Gamescope archive contains a non-regular member: ' + name)
if name in files:
raise ValueError('Duplicate Gamescope archive member: ' + name)
files[name] = archive.extractfile(member).read()
if set(files) != {'usr/local/bin/gamescope'}:
raise ValueError('Unexpected Gamescope archive payload: ' + ', '.join(files))
return files, pins
def validate_rebuilt(path, machine):
data = path.read_bytes()
if len(data) < 20 or data[:4] != b'\x7fELF' or data[5] != 1 or struct.unpack('<H', data[18:20])[0] != machine:
raise ValueError('Replacement has the wrong ELF architecture: ' + str(path))
return data
def validate_tracked_assets(package, llvm_strip):
checked = {}
for prefix, apk_prefix in [('app/src/main/jniLibs/', 'lib/'),
('app/src/main/assets/desktop-removal/', 'assets/desktop-removal/')]:
tracked = filter(None, git('ls-files', '-z', '--', prefix).decode().split('\0'))
for name in tracked:
archive_name = apk_prefix + name.removeprefix(prefix)
content = (ROOT / name).read_bytes()
donor_content = package.read(archive_name)
verification = 'identical bytes'
if content != donor_content:
if prefix != 'app/src/main/jniLibs/':
raise ValueError('Tracked bytes differ from the donor: ' + name +
' (text inputs must be checked out with LF)')
# AGP strips prebuilt JNI libraries during packaging. Verify that
# deterministic transformation on a temporary copy, never the source.
with tempfile.TemporaryDirectory(prefix='droiddeck-strip-check-') as temp:
stripped = Path(temp) / 'library.so'
subprocess.run([str(llvm_strip), '--strip-unneeded', '-o', str(stripped),
str(ROOT / name)], check=True, capture_output=True)
if stripped.read_bytes() != donor_content:
raise ValueError('Stripped tracked binary differs from donor: ' + name)
verification = 'identical after NDK llvm-strip --strip-unneeded'
checked[name] = {'source_sha256': hashlib.sha256(content).hexdigest(),
'packaged_sha256': hashlib.sha256(donor_content).hexdigest(),
'verification': verification}
return checked
def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_include=None, vr_image=vr_build.IMAGE):
classifications = check_sources()
if runtime.digest(apk) != DONOR_SHA256:
raise ValueError('Donor APK checksum mismatch')
gamescope_files, pins = read_gamescope(gamescope)
replacements = {name: validate_rebuilt(rebuilt_dir / name, machine) for name, machine in REBUILT.items()}
for name, data in replacements.items():
if hashlib.sha256(data).hexdigest() != REBUILT_SHA256[name]:
raise ValueError('Replacement does not match the audited local rebuild: ' + name)
if vk_include is None:
if llvm_strip is None:
raise ValueError('Set --vk-include or --llvm-strip to locate the NDK Vulkan headers')
vk_include = llvm_strip.parent.parent / 'sysroot/usr/include'
if rebuilt_vr is None:
vr_files, vr_manifest = vr_build.build(ROOT / 'build/windows-setup/vr', vk_include, root=ROOT, image=vr_image)
else:
vr_files, vr_manifest = vr_build.validate(rebuilt_vr, vk_include, root=ROOT)
helpers = source_assets()
helper_assets = set(helpers.values())
plan = {}
origins = {}
with ZipFile(apk) as package:
names = package.namelist()
if len(set(names)) != len(names):
raise ValueError('Donor APK has duplicate ZIP entries')
tracked = validate_tracked_assets(package, llvm_strip)
excluded = {'assets/linuxfs/' + name for name in REBUILT}
excluded.update('assets/linuxfs/' + name for name in gamescope_files)
excluded.update(helper_assets)
for name in names:
if name.endswith('/') or name in excluded or name.startswith(VR_PREFIX):
continue
if name.startswith(('assets/linuxfs/', 'assets/directaudio/', 'assets/droiddeck-esync/')):
target = 'app/src/main/' + name
checked_output(target)
plan[target] = package.read(name)
origins[target] = 'verified donor APK'
for name in JNI:
target = 'app/src/main/jniLibs/arm64-v8a/' + name
checked_output(target)
plan[target] = package.read('lib/arm64-v8a/' + name)
origins[target] = 'verified donor APK'
for name in PREPARED:
target = 'app/build/prepared-assets/' + name
checked_output(target)
plan[target] = package.read('assets/' + name)
origins[target] = 'verified donor APK'
for name, data in replacements.items():
target = 'app/src/main/assets/linuxfs/' + name
checked_output(target)
plan[target] = data
origins[target] = 'locally rebuilt libblsession'
for name, data in gamescope_files.items():
target = 'app/src/main/assets/linuxfs/' + name
checked_output(target)
plan[target] = data
origins[target] = 'checksum-pinned Gamescope release'
for name, data in vr_files.items():
target = 'app/src/main/' + VR_PREFIX + name
checked_output(target)
plan[target] = data
origins[target] = 'VR rebuilt from current source; source and output checksums verified'
# Do not silently retain unrelated files from a prior preparation.
expected = set(plan) | {'app/src/main/' + name for name in helper_assets}
for tree in ('linuxfs', 'directaudio', 'droiddeck-esync'):
base = ROOT / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
if path.relative_to(ROOT).as_posix() not in expected:
raise ValueError('Unexpected existing generated asset: ' + str(path))
for source in helpers:
data = source.read_bytes()
normalized = data.replace(b'\r\n', b'\n')
if data != normalized:
source.write_bytes(normalized)
for target, data in plan.items():
path = checked_output(target)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
runtime.record()
runtime.verify()
provenance = {
'version': 1,
'donor': {'url': DONOR_URL, 'sha256': DONOR_SHA256, 'signer_sha256': DONOR_CERT_SHA256,
'pr_source': DONOR_PR_SOURCE, 'main_source': DONOR_MAIN_SOURCE,
'source_tree': DONOR_TREE, 'embedded_revision': DONOR_REVISION},
'source_commit': git('rev-parse', 'HEAD').decode().strip(),
'classified_differences': classifications,
'build_plumbing': {name: {'sha256': runtime.digest(ROOT / name),
'diff': git('diff', 'HEAD', '--', name).decode()}
for name in sorted(LOCAL_BUILD_PLUMBING)},
'android_sources_built_by_gradle': {name: runtime.digest(ROOT / name)
for name in sorted(LOCAL_ANDROID_SOURCES)
if (ROOT / name).is_file()},
'stores': 'omitted; use -PskipRust=true',
'gamescope': {'repo': pins['GAMESCOPE_REPO'], 'tag': pins['GAMESCOPE_TAG'],
'archive_sha256': pins['GAMESCOPE_SHA256']},
'tracked_files_verified': tracked,
'vr_build': vr_manifest,
'outputs': {name: {'origin': origins[name], 'sha256': hashlib.sha256(data).hexdigest()}
for name, data in sorted(plan.items())},
'preload_sources': {path.relative_to(ROOT).as_posix(): runtime.digest(path)
for path in sorted((ROOT / 'tools/linuxfs/preload').glob('*.c'))},
'preload_build_scripts': {path.relative_to(ROOT).as_posix(): {
'sha256': runtime.digest(path), 'script': path.read_text()}
for path in sorted((ROOT / 'build/windows-setup').glob('build-preloads-*.sh'))},
'runtime_manifest_sha256': runtime.digest(ROOT / runtime.MANIFEST),
}
output = ROOT / 'app/build/windows-runtime-provenance.json'
output.write_text(json.dumps(provenance, indent=2, sort_keys=True) + '\n', encoding='utf-8')
print('Runtime inputs verified; donor components, rebuilt preloads, rebuilt VR and pinned Gamescope recorded.')
print('Store engines omitted: build with -PskipRust=true.')
print(output)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apk', type=Path, default=ROOT / 'build/windows-setup/DroidDeck-PR.732-bdf876d.apk')
parser.add_argument('--rebuilt-linuxfs', type=Path, default=ROOT / 'build/windows-setup/rebuilt-linuxfs')
parser.add_argument('--gamescope', type=Path, default=ROOT / 'build/windows-setup/gamescope.tzst')
parser.add_argument('--llvm-strip', type=Path, default=Path.home() /
'AppData/Local/Android/Sdk/ndk/27.3.13750724/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-strip.exe')
parser.add_argument('--rebuilt-vr', type=Path, help='Reuse a VR build with vr-build.json; default rebuilds in Docker')
parser.add_argument('--vk-include', type=Path, help='NDK Vulkan headers; defaults to the sysroot beside --llvm-strip')
parser.add_argument('--vr-image', default=vr_build.IMAGE, help='Docker compiler image for a fresh VR build')
parser.add_argument('--check-sources', action='store_true', help='Audit source differences without extracting files')
args = parser.parse_args()
zstd = ROOT / 'build/windows-setup/tools/zstd/zstd.exe'
if not shutil.which('zstd') and zstd.is_file():
import os
os.environ['PATH'] = str(zstd.parent) + os.pathsep + os.environ.get('PATH', '')
try:
if args.check_sources:
print(json.dumps(check_sources(), indent=2, sort_keys=True))
else:
prepare(args.apk.resolve(), args.rebuilt_linuxfs.resolve(), args.gamescope.resolve(), args.llvm_strip.resolve(),
args.rebuilt_vr.resolve() if args.rebuilt_vr else None,
args.vk_include.resolve() if args.vk_include else None, args.vr_image)
except (ValueError, OSError, subprocess.CalledProcessError, KeyError) as error:
parser.exit(1, str(error) + '\n')
if __name__ == '__main__':
main()
+17
View File
@@ -88,6 +88,12 @@ Added by DroidDeck:
`mnt_id` from the pin's fdinfo. A later close/reuse of the tracee fd cannot redirect that read;
a concurrent reuse for the same inode through a different bind mount is indistinguishable at
the exit stop. It does not synthesize `STATX_MNT_ID_UNIQUE`.
- `0016-robust-list-from-seccomp.patch` - Android's app policy refuses `set_robust_list` and
`get_robust_list`. proot still answers the first with `ENOSYS` but keeps the head each thread
offered (cleared on `execve`, none in a new task), and answers the second for the calling thread
with it. SteamVR's `vrclient.so` asks for the head through libc's `syscall()`, which
`libblsession.so`'s robust.c never sees: `libopenvr_api.so` opens it `RTLD_DEEPBIND`. Steam
aborted on "futex robust_list not initialized by pthreads" as soon as SteamVR was registered.
Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-performance.md`):
@@ -100,3 +106,14 @@ Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-per
first tracee starts at `-w`'s, so relative lookups inside the tracee resolve where proot would.
SM8850 (adb shell): `stat` 25.3 -> 0.6 us, `open+close` 25.3 -> 0.9 us, ENOENT 22.9 -> 1.6 us,
8 threads `stat`ing 89k -> 3.6M/s; equivalence suite (`bench/equiv.py`) byte-identical to proot.
Old kernel fixes:
- `0015-lost-fork-events.patch` - works around a problem reported on Xiaomi's msm 4.14 kernel:
the kernel sometimes reports a new process or thread but gives its ID as zero. Without that ID,
PRoot cannot finish setting it up, which can leave the session stuck. The patch searches `/proc`
for the child. If exactly one matches, PRoot uses its existing setup code. If several threads
match, it waits for the creating thread's `clone` call to return and uses the child ID returned
by the kernel instead. The original clone flags are preserved. When the kernel supplies a valid
ID in the notification, normal setup is unchanged. No timers or background polling are added.
Completely missing notifications and ambiguous matches for separate processes are not recovered.
+21
View File
@@ -298,6 +298,27 @@ def deep_section():
t("unlink missing", lambda: os.unlink(DEEP + "/new"))
t("unlink", lambda: os.unlink(DEEP + "/renamed"))
t("realpath", lambda: realpath(DEEP + "/sub/../sub/link"))
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
t("bind socket", lambda: srv.bind(DEEP + "/s.sock"))
t("listen", lambda: srv.listen(1))
cli = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
t("connect socket", lambda: cli.connect(DEEP + "/s.sock"))
t("stat socket", lambda: mode_of(os.stat(DEEP + "/s.sock")))
t("sockname", srv.getsockname)
t("peername", cli.getpeername)
t("accepted sockname", lambda: srv.accept()[0].getsockname())
twin = DEEP[:-len("some")] + "more"
os.makedirs(twin)
other = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
t("bind same name elsewhere", lambda: other.bind(twin + "/s.sock"))
t("sockname, first", srv.getsockname)
t("sockname, same name elsewhere", other.getsockname)
other.close()
os.unlink(twin + "/s.sock")
os.rmdir(twin)
cli.close()
srv.close()
t("unlink socket", lambda: os.unlink(DEEP + "/s.sock"))
t("listing", lambda: sorted(os.listdir(DEEP)))
+130 -12
View File
@@ -109,7 +109,8 @@ static long tracer;
static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t bind_lock;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); }
static pthread_mutex_t long_lock;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); }
static int traced_by_match(const char *key) {
static char buf[32768];
@@ -140,6 +141,26 @@ static int traced_by_match(const char *key) {
return found;
}
static int fex_runs_32bit(void) {
if (strcmp(program_invocation_short_name, "FEX") != 0 && strcmp(program_invocation_short_name, "FEXInterpreter") != 0)
return 0;
char args[PATH_MAX + 64];
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 1;
long n = syscall(SYS_read, fd, args, sizeof args - 1);
syscall(SYS_close, fd);
if (n <= 0) return 1;
args[n] = 0;
const char *prog = args + strlen(args) + 1;
if (prog >= args + n || !*prog) return 1;
unsigned char ident[5];
fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 1;
n = syscall(SYS_read, fd, ident, sizeof ident);
syscall(SYS_close, fd);
return !(n == 5 && memcmp(ident, "\x7f" "ELF", 4) == 0 && ident[4] == 2);
}
static int in_tracer(struct bind *bd) {
char h[PATH_MAX];
if (snprintf(h, sizeof h, "/proc/%ld%s", tracer, bd->host + 10) >= (int)sizeof h) return 0;
@@ -156,6 +177,7 @@ static void fp_init(void) {
const char *r = getenv("PROOT_FP_ROOT"), *b = getenv("PROOT_FP_BINDS"), *t = getenv("PROOT_FP_TTL_MS");
const char *key = getenv("PROOT_FP_KEY");
if (!r || !*r || !key || !*key || getenv("PROOT_FP_OFF")) return;
if (fex_runs_32bit()) return;
void *p = mmap((void *)FP_STUB_ADDR, FP_STUB_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
if (p != (void *)FP_STUB_ADDR) {
@@ -1187,8 +1209,67 @@ int inotify_add_watch(int fd, const char *path, uint32_t mask) {
}
static long socket_address(const struct sockaddr *addr, socklen_t len, int follow, struct sockaddr_un *out, socklen_t *out_len) {
/* The kernel reports a socket named through /proc/self/fd/N/<name> under that name: map it back, per socket. */
enum { LONG_SELF, LONG_PEER };
static struct { unsigned long ino; int kind; char name[sizeof ((struct sockaddr_un *)0)->sun_path]; char guest[sizeof ((struct sockaddr_un *)0)->sun_path]; } long_names[64];
static unsigned long_next;
static pthread_mutex_t long_lock = PTHREAD_MUTEX_INITIALIZER;
static const char *fd_name(const char *path) {
if (strncmp(path, "/proc/self/fd/", 14) != 0) return NULL;
const char *p = path + 14;
if (*p < '0' || *p > '9') return NULL;
while (*p >= '0' && *p <= '9') p++;
return *p == '/' && p[1] ? p + 1 : NULL;
}
static unsigned long socket_ino(int fd) {
struct stat st;
return sc(SYS_newfstatat, fd, (long)"", (long)&st, AT_EMPTY_PATH, 0) == 0 ? (unsigned long)st.st_ino : 0;
}
static void remember_long(int fd, int kind, const char *name, const char *guest) {
unsigned long ino = socket_ino(fd);
if (!ino || !name || strlen(name) >= sizeof long_names[0].name || strlen(guest) >= sizeof long_names[0].guest) return;
unsigned count = sizeof long_names / sizeof long_names[0], i = count;
pthread_mutex_lock(&long_lock);
for (unsigned n = 0; n < count && i == count; n++)
if (long_names[n].ino == ino && long_names[n].kind == kind) i = n;
if (i == count) i = long_next++ % count;
long_names[i].ino = ino;
long_names[i].kind = kind;
snprintf(long_names[i].name, sizeof long_names[i].name, "%s", name);
snprintf(long_names[i].guest, sizeof long_names[i].guest, "%s", guest);
pthread_mutex_unlock(&long_lock);
}
static int long_entry(int fd, int kind, const char *name, char *guest, size_t size) {
unsigned long ino = socket_ino(fd);
int found = -1;
if (!ino || !name) return -1;
pthread_mutex_lock(&long_lock);
for (unsigned n = 0; n < sizeof long_names / sizeof long_names[0] && found < 0; n++)
if (long_names[n].ino == ino && long_names[n].kind == kind && strcmp(long_names[n].name, name) == 0
&& strlen(long_names[n].guest) < size) {
memcpy(guest, long_names[n].guest, strlen(long_names[n].guest) + 1);
found = 0;
}
pthread_mutex_unlock(&long_lock);
return found;
}
static void remember_long_address(int fd, int kind, const struct sockaddr *addr, socklen_t len, const struct sockaddr_un *used) {
const struct sockaddr_un *un = (const struct sockaddr_un *)addr;
char guest[sizeof un->sun_path + 1];
size_t glen = strnlen(un->sun_path, len - offsetof(struct sockaddr_un, sun_path));
memcpy(guest, un->sun_path, glen);
guest[glen] = 0;
remember_long(fd, kind, fd_name(used->sun_path), guest);
}
static long socket_address(const struct sockaddr *addr, socklen_t len, int follow, struct sockaddr_un *out, socklen_t *out_len, long *dir) {
const struct sockaddr_un *un = (const struct sockaddr_un *)addr;
*dir = -1;
size_t room = sizeof un->sun_path;
if (!addr || len <= offsetof(struct sockaddr_un, sun_path) || addr->sa_family != AF_UNIX || un->sun_path[0] == 0)
return 0;
@@ -1204,10 +1285,20 @@ static long socket_address(const struct sockaddr *addr, socklen_t len, int follo
if (rs == 1 && follow) return -ENOENT;
if (r.magic) return FP_SLOW;
size_t hlen = strlen(r.host);
if (hlen >= room) return FP_SLOW;
memset(out, 0, sizeof *out);
out->sun_family = AF_UNIX;
memcpy(out->sun_path, r.host, hlen + 1);
if (hlen >= room) {
/* proot would bind it to a temporary name the fast path cannot see: name it through its directory. */
char *slash = strrchr(r.host, '/');
if (!slash || slash == r.host) return FP_SLOW;
*slash = 0;
*dir = sc(SYS_openat, AT_FDCWD, (long)r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0);
if (*dir < 0) return FP_SLOW;
hlen = snprintf(out->sun_path, room, "/proc/self/fd/%ld/%s", *dir, slash + 1);
if (hlen >= room) { sc(SYS_close, *dir, 0, 0, 0, 0); *dir = -1; return FP_SLOW; }
} else {
memcpy(out->sun_path, r.host, hlen + 1);
}
*out_len = offsetof(struct sockaddr_un, sun_path) + hlen + 1;
return 1;
}
@@ -1221,10 +1312,15 @@ int connect(int fd, const struct sockaddr *addr, socklen_t len) {
REAL(connect, int (*)(int, const struct sockaddr *, socklen_t));
struct sockaddr_un un;
socklen_t un_len;
long rs = fp_ready() ? socket_address(addr, len, 1, &un, &un_len) : FP_SLOW;
long dir = -1;
long rs = fp_ready() ? socket_address(addr, len, 1, &un, &un_len, &dir) : FP_SLOW;
if (rs == 0 && !(addr && addr->sa_family == AF_UNIX) && !nonblocking(fd)) rs = FP_SLOW;
if (rs == 0) rs = sc(SYS_connect, fd, (long)addr, len, 0, 0);
else if (rs == 1) rs = sc(SYS_connect, fd, (long)&un, un_len, 0, 0);
if (dir >= 0) {
sc(SYS_close, dir, 0, 0, 0, 0);
if (rs == 0 || rs == -EINPROGRESS) remember_long_address(fd, LONG_PEER, addr, len, &un);
}
ANSWER(rs, AT_FDCWD, "(connect)", real_connect(fd, addr, len));
}
@@ -1232,13 +1328,18 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
REAL(bind, int (*)(int, const struct sockaddr *, socklen_t));
struct sockaddr_un un;
socklen_t un_len;
long rs = fp_ready() ? socket_address(addr, len, 0, &un, &un_len) : FP_SLOW;
long dir = -1;
long rs = fp_ready() ? socket_address(addr, len, 0, &un, &un_len, &dir) : FP_SLOW;
if (rs == 0) rs = sc(SYS_bind, fd, (long)addr, len, 0, 0);
else if (rs == 1) rs = sc(SYS_bind, fd, (long)&un, un_len, 0, 0);
if (dir >= 0) {
sc(SYS_close, dir, 0, 0, 0, 0);
if (rs == 0) remember_long_address(fd, LONG_SELF, addr, len, &un);
}
ANSWER(rs, AT_FDCWD, "(bind)", real_bind(fd, addr, len));
}
static void report_address(const struct sockaddr_storage *got, socklen_t got_len, struct sockaddr *addr, socklen_t *len) {
static void report_address(int fd, int kind, const struct sockaddr_storage *got, socklen_t got_len, struct sockaddr *addr, socklen_t *len) {
struct sockaddr_storage shown = *got;
socklen_t shown_len = got_len;
const struct sockaddr_un *un = (const struct sockaddr_un *)got;
@@ -1248,7 +1349,7 @@ static void report_address(const struct sockaddr_storage *got, socklen_t got_len
memcpy(h, un->sun_path, hl);
h[hl] = 0;
struct sockaddr_un *out = (struct sockaddr_un *)&shown;
if (to_guest(h, g, sizeof g) == 0 && strlen(g) < sizeof out->sun_path) {
if ((long_entry(fd, kind, fd_name(h), g, sizeof g) == 0 || to_guest(h, g, sizeof g) == 0) && strlen(g) < sizeof out->sun_path) {
memset(out->sun_path, 0, sizeof out->sun_path);
strcpy(out->sun_path, g);
shown_len = offsetof(struct sockaddr_un, sun_path) + strlen(g) + 1;
@@ -1259,6 +1360,22 @@ static void report_address(const struct sockaddr_storage *got, socklen_t got_len
}
static void inherit_long_name(int listener, int accepted) {
unsigned long ino = socket_ino(listener);
char name[sizeof long_names[0].name], guest[sizeof long_names[0].guest];
int found = -1;
if (!ino) return;
pthread_mutex_lock(&long_lock);
for (unsigned n = 0; n < sizeof long_names / sizeof long_names[0] && found < 0; n++)
if (long_names[n].ino == ino && long_names[n].kind == LONG_SELF) {
snprintf(name, sizeof name, "%s", long_names[n].name);
snprintf(guest, sizeof guest, "%s", long_names[n].guest);
found = 0;
}
pthread_mutex_unlock(&long_lock);
if (found == 0) remember_long(accepted, LONG_SELF, name, guest);
}
static int pending(int fd) {
struct pollfd p = { .fd = fd, .events = POLLIN };
struct timespec now = { 0, 0 };
@@ -1269,11 +1386,12 @@ static int accept_common(int fd, struct sockaddr *addr, socklen_t *len, int flag
REAL(accept4, int (*)(int, struct sockaddr *, socklen_t *, int));
if (!fp_ready() || (addr && !len) || (!nonblocking(fd) && !pending(fd))) { missed(__func__, AT_FDCWD, "(accept)"); return real_accept4(fd, addr, len, flags); }
hits++;
if (!addr) return ret(sc(SYS_accept4, fd, 0, 0, flags, 0));
struct sockaddr_storage got;
socklen_t got_len = sizeof got;
long r = sc(SYS_accept4, fd, (long)&got, (long)&got_len, flags, 0);
if (r >= 0) report_address(&got, got_len, addr, len);
long r = sc(SYS_accept4, fd, addr ? (long)&got : 0, addr ? (long)&got_len : 0, flags, 0);
if (r >= 0) inherit_long_name(fd, (int)r);
if (!addr) return ret(r);
if (r >= 0) report_address((int)r, LONG_PEER, &got, got_len, addr, len);
return ret(r);
}
int accept4(int fd, struct sockaddr *addr, socklen_t *len, int flags) { return accept_common(fd, addr, len, flags); }
@@ -1285,7 +1403,7 @@ static int name_common(long nr, int fd, struct sockaddr *addr, socklen_t *len, i
struct sockaddr_storage got;
socklen_t got_len = sizeof got;
long r = sc(nr, fd, (long)&got, (long)&got_len, 0, 0);
if (r == 0) report_address(&got, got_len, addr, len);
if (r == 0) report_address(fd, nr == SYS_getsockname ? LONG_SELF : LONG_PEER, &got, got_len, addr, len);
return ret(r);
}
int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
@@ -0,0 +1,315 @@
Subject: [PATCH] recover zero child IDs, resolving ambiguous threads at clone exit
Use a unique procfs match for delivered creation events with a zero child
PID. When concurrent thread clones are ambiguous, keep the creator's real
flags and obtain its exact child TID from the clone syscall return value.
Validate that TID against the traced thread group before existing child setup.
Do not defer vfork, guess parents, or select by PID order. Missing creation
events and ambiguous process (non-thread) clones remain unsupported.
No timers or polling are added by this recovery patch.
diff --git a/src/tracee/tracee.c b/src/tracee/tracee.c
--- a/src/tracee/tracee.c
+++ b/src/tracee/tracee.c
@@ -32,6 +32,10 @@
#include <sys/ptrace.h> /* ptrace(2), PTRACE_*, */
#include <errno.h> /* E*, */
#include <inttypes.h> /* PRI*, */
+#include <unistd.h> /* getpid(2), */
+#include <stdio.h> /* fopen(3), fgets(3), snprintf(3), */
+#include <dirent.h> /* opendir(3), readdir(3), closedir(3), */
+#include <limits.h> /* INT_MAX, */
#include "tracee/tracee.h"
#include "tracee/reg.h"
@@ -402,16 +406,128 @@
}
}
+/* Read host process IDs, not PRoot's guest /proc view. /proc/<tid>/status
+ * works for non-leader threads too, even though /proc lists only leaders. */
+static int read_task_ids(pid_t pid, long *tgid, long *ppid, long *tracer)
+{
+ char path[64], line[256];
+ FILE *file;
+ int status;
+
+ *tgid = *ppid = *tracer = -1;
+ snprintf(path, sizeof(path), "/proc/%d/status", (int) pid);
+ file = fopen(path, "re");
+ if (file == NULL)
+ return -errno;
+
+ while (fgets(line, sizeof(line), file) != NULL) {
+ if (strncmp(line, "Tgid:", 5) == 0)
+ *tgid = strtol(line + 5, NULL, 10);
+ else if (strncmp(line, "PPid:", 5) == 0)
+ *ppid = strtol(line + 5, NULL, 10);
+ else if (strncmp(line, "TracerPid:", 10) == 0)
+ *tracer = strtol(line + 10, NULL, 10);
+ }
+ status = ferror(file) || *tgid <= 0 || *ppid < 0 || *tracer < 0
+ ? -EIO : 0;
+ fclose(file);
+ return status;
+}
+
+/* Recover only a delivered creation event whose GETEVENTMSG succeeded but
+ * returned zero. The creator is still stopped at that event, and its real
+ * clone flags have already been read. Require exactly one uninitialized,
+ * PRoot-traced candidate of the right kind and relationship. Never infer
+ * clone flags from PPid, substitute a process for a thread, or choose by PID
+ * order. Include tracees whose initial SIGSTOP was handled before this event.
+ * Missing events and ambiguous candidates need separate recovery logic. */
+static int find_event_child(Tracee *parent, word_t clone_flags, unsigned long *result)
+{
+ char path[64];
+ long parent_tgid, parent_ppid, tracer;
+ const long self = (long) getpid();
+ const bool thread = (clone_flags & CLONE_THREAD) != 0;
+ struct dirent *entry;
+ DIR *dir;
+ unsigned long found = 0;
+ int status;
+
+ status = read_task_ids(parent->pid, &parent_tgid, &parent_ppid, &tracer);
+ if (status < 0)
+ return status;
+ if (tracer != self)
+ return -ESRCH;
+
+ if (thread)
+ snprintf(path, sizeof(path), "/proc/%ld/task", parent_tgid);
+ else
+ snprintf(path, sizeof(path), "/proc");
+ dir = opendir(path);
+ if (dir == NULL)
+ return -errno;
+
+ status = 0;
+ for (;;) {
+ long pid, tgid, ppid;
+ char *end;
+ Tracee *known;
+
+ errno = 0;
+ entry = readdir(dir);
+ if (entry == NULL) {
+ if (errno != 0)
+ status = -errno;
+ break;
+ }
+ if (entry->d_name[0] < '0' || entry->d_name[0] > '9')
+ continue;
+ errno = 0;
+ pid = strtol(entry->d_name, &end, 10);
+ if (errno != 0 || *end != '\0' || pid <= 0 || pid > INT_MAX ||
+ pid == parent->pid)
+ continue;
+ known = get_tracee(NULL, (pid_t) pid, false);
+ if (known != NULL && (known->terminated || known->exe != NULL ||
+ known->parent != NULL))
+ continue;
+ if (read_task_ids((pid_t) pid, &tgid, &ppid, &tracer) < 0 ||
+ tracer != self)
+ continue;
+ if (thread) {
+ if (tgid != parent_tgid)
+ continue;
+ } else {
+ long expected_ppid = (clone_flags & CLONE_PARENT) != 0
+ ? parent_ppid : parent_tgid;
+ if (tgid != pid || ppid != expected_ppid)
+ continue;
+ }
+ if (found != 0) {
+ status = -EAGAIN;
+ break;
+ }
+ found = (unsigned long) pid;
+ }
+ closedir(dir);
+ if (status < 0)
+ return status;
+ if (found == 0)
+ return -ESRCH;
+ *result = found;
+ return 0;
+}
+
/**
* Make new @parent's child inherit from it. Depending on
* @clone_flags, some information are copied or shared. This function
* returns -errno if an error occured, otherwise 0.
*/
+static int new_child_setup(Tracee *parent, unsigned long pid, word_t clone_flags);
+
int new_child(Tracee *parent, word_t clone_flags)
{
- int ptrace_options;
+ bool flags_known;
unsigned long pid;
- Tracee *child;
int status;
/* If the tracee calls clone(2) with the CLONE_VFORK flag,
@@ -425,24 +541,62 @@
* order to get the right flags.
*/
status = fetch_regs(parent);
+ flags_known = (status >= 0);
if (status >= 0 && get_sysnum(parent, CURRENT) == PR_clone)
clone_flags = peek_reg(parent, CURRENT, SYSARG_1);
else if (status >= 0 && get_sysnum(parent, CURRENT) == PR_clone3) {
word_t args = peek_reg(parent, CURRENT, SYSARG_1);
word_t flags = peek_uint64(parent, args);
+ flags_known = false;
if (errno == 0) {
word_t exit_signal = peek_uint64(parent, args + 4 * sizeof(uint64_t));
- if (errno == 0)
+ if (errno == 0) {
clone_flags = (flags & ~(word_t) 0xFF) | (exit_signal & 0xFF);
+ flags_known = true;
+ }
}
}
/* Get the pid of the parent's new child. */
status = ptrace(PTRACE_GETEVENTMSG, parent->pid, NULL, &pid);
- if (status < 0 || pid == 0) {
+ if (status < 0) {
note(parent, WARNING, SYSTEM, "ptrace(GETEVENTMSG)");
return status;
}
+ if (pid == 0) {
+ static bool warned;
+
+ status = flags_known ? find_event_child(parent, clone_flags, &pid) : -EIO;
+ /* A thread creator can reach clone's exit while its child is held.
+ * vfork cannot: its creator waits for the child, so do not defer it. */
+ if (status == -EAGAIN && (clone_flags & CLONE_THREAD) != 0 &&
+ (clone_flags & CLONE_VFORK) == 0) {
+ parent->pending_clone_flags = clone_flags;
+ parent->restart_how = PTRACE_SYSCALL;
+ return 0;
+ }
+ if (status < 0) {
+ note(parent, WARNING, USER,
+ "zero fork-event pid for task %d: cannot safely identify child (%s); leaving it uninitialized",
+ (int) parent->pid, strerror(-status));
+ return status;
+ }
+ if (!warned) {
+ warned = true;
+ note(parent, WARNING, USER,
+ "kernel returned a zero fork-event pid; using procfs child discovery");
+ }
+ VERBOSE(parent, 1, "recovered child %lu for task %d from procfs",
+ pid, (int) parent->pid);
+ }
+
+ return new_child_setup(parent, pid, clone_flags);
+}
+
+static int new_child_setup(Tracee *parent, unsigned long pid, word_t clone_flags)
+{
+ int ptrace_options;
+ Tracee *child;
child = get_tracee(parent, (pid_t) pid, true);
if (child == NULL) {
@@ -628,6 +782,52 @@
return 0;
}
+/* A clone event occurs before the creating thread returns from clone. For an
+ * ambiguous thread lookup, obtain the exact TID at that syscall's exit instead
+ * of guessing from the order of /proc entries. Called before normal syscall
+ * exit handling so the registers and inherited tracee state are still intact. */
+void finish_pending_child(Tracee *parent)
+{
+ word_t flags = parent->pending_clone_flags;
+ word_t pid;
+ long ptgid, ppid, tracer, ctgid;
+ Tracee *known;
+ int status;
+
+ parent->pending_clone_flags = 0;
+ status = fetch_regs(parent);
+ if (status < 0)
+ goto failed;
+ pid = peek_reg(parent, CURRENT, SYSARG_RESULT);
+ if (pid == 0 || pid > INT_MAX || pid == (word_t) parent->pid) {
+ status = -ESRCH;
+ goto failed;
+ }
+ /* Validate the host TID before setup. This also rejects an unmappable
+ * PID from a different PID namespace instead of adopting an unrelated task. */
+ status = read_task_ids(parent->pid, &ptgid, &ppid, &tracer);
+ if (status < 0)
+ goto failed;
+ status = read_task_ids((pid_t) pid, &ctgid, &ppid, &tracer);
+ if (status < 0)
+ goto failed;
+ known = get_tracee(NULL, (pid_t) pid, false);
+ if (ctgid != ptgid || tracer != (long) getpid() ||
+ (known != NULL && (known->terminated || known->exe != NULL || known->parent != NULL))) {
+ status = -ESRCH;
+ goto failed;
+ }
+ status = new_child_setup(parent, (unsigned long) pid, flags);
+ if (status < 0)
+ goto failed;
+ VERBOSE(parent, 1, "recovered thread %lu for task %d from clone return",
+ (unsigned long) pid, (int) parent->pid);
+ return;
+failed:
+ note(parent, WARNING, USER, "cannot recover thread at clone exit for task %d (error %d)",
+ (int) parent->pid, status);
+}
+
/**
* Helper for swap_config().
*/
diff --git a/src/tracee/event.c b/src/tracee/event.c
--- a/src/tracee/event.c
+++ b/src/tracee/event.c
@@ -398,6 +398,7 @@
* before the exit stage, eg. PTRACE_EVENT_EXEC for the exit
* stage of execve(2). */
sysexit_necessary = tracee->sysexit_pending
+ || tracee->pending_clone_flags != 0
|| tracee->chain.syscalls != NULL
|| tracee->restore_original_regs_after_seccomp_event;
/* Don't overwrite restart_how if it is explicitly set
@@ -474,6 +475,9 @@
/* Fall through. */
case SIGTRAP | 0x80:
signal = 0;
+
+ if (tracee->pending_clone_flags != 0)
+ finish_pending_child(tracee);
/* This tracee got signaled then freed during the
sysenter stage but the kernel reports the sysexit
diff --git a/src/tracee/tracee.h b/src/tracee/tracee.h
--- a/src/tracee/tracee.h
+++ b/src/tracee/tracee.h
@@ -172,6 +172,9 @@
SIGSTOP_ALLOWED, /* Allow SIGSTOP (once the parent is known). */
SIGSTOP_PENDING, /* Block SIGSTOP until the parent is unknown. */
} sigstop;
+
+ /* Nonzero only while resolving an ambiguous thread clone at its exit. */
+ word_t pending_clone_flags;
/* True if next SIGSYS caused by seccomp should be silently dropped
* without affecting state of any registers. */
@@ -310,6 +313,7 @@
bool only_with_pevent, word_t wait_options);
extern bool has_ptracees(const Tracee *ptracer, pid_t pid, word_t wait_options);
extern int new_child(Tracee *parent, word_t clone_flags);
+extern void finish_pending_child(Tracee *parent);
extern Tracee *new_dummy_tracee(TALLOC_CTX *context);
extern void terminate_tracee(Tracee *tracee);
extern void free_terminated_tracees();
@@ -0,0 +1,61 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: DroidDeck <droiddeck@users.noreply.github.com>
Date: Tue, 13 Oct 2026 00:00:00 +0000
Subject: [PATCH] seccomp: answer get_robust_list with the head set_robust_list
was refused for
diff --git a/src/execve/exit.c b/src/execve/exit.c
index f32d3ec..b5475b3 100644
--- a/src/execve/exit.c
+++ b/src/execve/exit.c
@@ -473,6 +473,8 @@ void translate_execve_exit(Tracee *tracee)
talloc_set_name_const(tracee->exe, "$exe");
}
+ tracee->robust_list = 0;
+
/* New processes have no heap. */
if (talloc_reference_count(tracee->heap) >= 1) {
talloc_unlink(tracee, tracee->heap);
diff --git a/src/tracee/seccomp.c b/src/tracee/seccomp.c
index 77d5b27..0af232b 100644
--- a/src/tracee/seccomp.c
+++ b/src/tracee/seccomp.c
@@ -559,6 +559,24 @@ static int handle_seccomp_event_common(Tracee *tracee)
}
case PR_set_robust_list:
+ tracee->robust_list = peek_reg(tracee, CURRENT, SYSARG_1);
+ set_result_after_seccomp(tracee, -ENOSYS);
+ break;
+
+ case PR_get_robust_list:
+ {
+ pid_t pid = (pid_t) peek_reg(tracee, CURRENT, SYSARG_1);
+ if (tracee->robust_list == 0 || (pid != 0 && pid != tracee->pid)) {
+ set_result_after_seccomp(tracee, -ENOSYS);
+ break;
+ }
+ poke_word(tracee, peek_reg(tracee, CURRENT, SYSARG_2), tracee->robust_list);
+ if (errno == 0)
+ poke_word(tracee, peek_reg(tracee, CURRENT, SYSARG_3), 3 * sizeof_word(tracee));
+ set_result_after_seccomp(tracee, errno != 0 ? -EFAULT : 0);
+ break;
+ }
+
default:
/* Set errno to -ENOSYS */
set_result_after_seccomp(tracee, -ENOSYS);
diff --git a/src/tracee/tracee.h b/src/tracee/tracee.h
index 1fca85f..496ca75 100644
--- a/src/tracee/tracee.h
+++ b/src/tracee/tracee.h
@@ -248,6 +248,8 @@ typedef struct tracee {
* has to be ignored as it's same syscall entry */
bool seccomp_already_handled_enter;
+ word_t robust_list;
+
/**********************************************************************
* Shared or private resources, depending on the CLONE_FS/VM flags. *
**********************************************************************/
+74
View File
@@ -0,0 +1,74 @@
/* Exercise the production vkp_render entrypoint without Android/Vulkan hardware.
* The Python runner extracts that function verbatim into the included file. */
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
struct vkp_draw { int unused; };
static int quest, framegen, cardboard, pass_result, base_result, pass_shown;
static int first_frames, pass_calls, base_calls, fallback_calls;
static int vkp_quest_layer_presentation(void) { return quest; }
static int vkp_framegen_active(void) { return framegen; }
static int vkp_cardboard_active(void) { return cardboard; }
static void vkp_apply_window_request(void) {}
static void sc_layer_hide_overlay(void) {}
static void sc_layer_hide(void) {}
static void droiddeck_log(const char *tag, const char *message, ...) {}
static void vkp_signal_first_frame(void) { first_frames++; }
static int vkp_base_black(int w, int h) { base_calls++; return base_result; }
static int sc_layer_present_pass(const struct vkp_draw *draws, int n, int w, int h) {
pass_calls++;
/* Production sc_layer_present_pass signals only after a content submission.
* Its no-op results (off-screen geometry or pool exhaustion) also return 0. */
if (pass_result == 0 && pass_shown) vkp_signal_first_frame();
return pass_result;
}
static int render_impl(int w, int h, const struct vkp_draw *draws, int n,
const void *hdr, int *how) { fallback_calls++; return 17; }
#include "vkp_render_under_test.inc"
static void reset(void) {
quest = 1;
framegen = cardboard = pass_result = base_result = pass_shown = 0;
first_frames = pass_calls = base_calls = fallback_calls = 0;
}
int main(void) {
const struct vkp_draw draw = {0};
reset();
for (int i = 0; i < 3; i++) assert(vkp_render(1280, 720, NULL, 0) == 0);
assert(base_calls == 3 && pass_calls == 0 && first_frames == 0);
/* An accepted layer operation is not necessarily a displayed client frame. */
reset();
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(pass_calls == 1 && base_calls == 1 && first_frames == 0);
/* Content is the sole owner of the notification, with no second backdrop event. */
reset(); pass_shown = 1;
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(first_frames == 1);
assert(vkp_render(1280, 720, NULL, 0) == 0);
assert(first_frames == 1);
reset(); pass_result = -1;
assert(vkp_render(1280, 720, &draw, 1) == -1);
assert(first_frames == 0 && base_calls == 0);
reset(); base_result = -1;
assert(vkp_render(1280, 720, NULL, 0) == -1);
assert(first_frames == 0);
/* Existing routes remain responsible for their own notifications. */
for (int mode = 0; mode < 3; mode++) {
reset();
if (mode == 0) quest = 0;
if (mode == 1) framegen = 1;
if (mode == 2) cardboard = 1;
assert(vkp_render(1280, 720, &draw, 1) == 17);
assert(fallback_calls == 1 && pass_calls == 0 && base_calls == 0);
assert(first_frames == 0);
}
puts("PASS: Quest first-frame notification waits for client content");
return 0;
}
+103
View File
@@ -0,0 +1,103 @@
/* Exercise the production backdrop with mock Android buffers/transactions. */
#include "../../app/src/main/cpp/waylandcomp/src/sc_layer.c"
#include "../../app/src/main/cpp/waylandcomp/src/quest_device.h"
#include <assert.h>
struct AHardwareBuffer { unsigned char pixels[20 * 16 * 4]; };
static struct AHardwareBuffer buffer;
static int fail_alloc, fail_lock, fail_unlock, fail_tx;
static int allocs, locks, unlocks, buffers, applies, creates, releases, retirements;
static int visible, zorder, opacity;
static ARect destination;
static ANativeWindow *window = (ANativeWindow *)1;
ANativeWindow *vkp_window(void) { return window; }
void droiddeck_log(const char *kind, const char *fmt, ...) { (void)kind; (void)fmt; }
int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *d, AHardwareBuffer **b) {
assert(d->width == 16 && d->height == 16);
assert(d->usage & AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY);
allocs++;
if (fail_alloc) return -1;
memset(&buffer, 0xa5, sizeof(buffer)); *b = &buffer; return 0;
}
void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) {
assert(b == &buffer); *d = (AHardwareBuffer_Desc){.width=16,.height=16,.stride=20};
}
int AHardwareBuffer_lock(AHardwareBuffer *b, uint64_t usage, int32_t fd, const ARect *r, void **p) {
(void)usage; (void)fd; (void)r; assert(b == &buffer); locks++;
if (fail_lock) return -1;
*p = buffer.pixels; return 0;
}
int AHardwareBuffer_unlock(AHardwareBuffer *b, int32_t *f) {
assert(b == &buffer && f == NULL); unlocks++; return fail_unlock ? -1 : 0;
}
void AHardwareBuffer_release(AHardwareBuffer *b) { assert(b == &buffer); releases++; }
static ASurfaceControl *create(ANativeWindow *w, const char *n) {
assert(w == window && strcmp(n, "droiddeck_wayland_black") == 0); creates++;
return (ASurfaceControl *)(uintptr_t)(100 + creates);
}
static ASurfaceTransaction *tx_create(void) { return fail_tx ? NULL : (ASurfaceTransaction *)2; }
static void tx_delete(ASurfaceTransaction *t) { assert(t == (ASurfaceTransaction *)2); }
static void tx_apply(ASurfaceTransaction *t) { (void)t; applies++; }
static void set_buffer(ASurfaceTransaction *t, ASurfaceControl *s, AHardwareBuffer *b, int fd) {
(void)t; (void)s; assert(b == &buffer && fd == -1);
/* No garbage, including padded row bytes, reaches the display. */
for (unsigned i=0; i<sizeof(buffer.pixels); i++) assert(buffer.pixels[i] == 0);
assert(unlocks > 0); buffers++;
}
static void visibility(ASurfaceTransaction *t, ASurfaceControl *s, int8_t v) { (void)t; (void)s; visible=v; }
static void z(ASurfaceTransaction *t, ASurfaceControl *s, int32_t v) { (void)t; (void)s; zorder=v; }
static void transparency(ASurfaceTransaction *t, ASurfaceControl *s, int8_t v) { (void)t; (void)s; opacity=v; }
static void geometry(ASurfaceTransaction *t, ASurfaceControl *s, const ARect *src, const ARect *dst, int32_t rotation) {
(void)t; (void)s; assert(src->right==16 && src->bottom==16 && rotation==0); destination=*dst;
}
static void reparent(ASurfaceTransaction *t, ASurfaceControl *s, ASurfaceControl *parent) {
(void)t; (void)s; assert(parent==NULL); retirements++;
}
static void release(ASurfaceControl *s) { assert(s); }
static void reset(void) {
base_hide(1); g_blank=NULL;
fail_alloc=fail_lock=fail_unlock=fail_tx=0;
allocs=locks=unlocks=buffers=applies=creates=releases=retirements=0;
window=(ANativeWindow *)1;
}
int main(void) {
assert(quest_device_matches("Quest 2", "", ""));
assert(quest_device_matches("quest 3", "", ""));
assert(quest_device_matches("Quest 3S", "", ""));
assert(quest_device_matches("unknown", "hollywood", "Oculus"));
assert(quest_device_matches("unknown", "eureka", "Meta"));
assert(quest_device_matches("unknown", "panther", "Oculus"));
assert(!quest_device_matches("Pixel", "panther", "Google"));
assert(!quest_device_matches("Quest Pro", "seacliff", "Meta"));
assert(!quest_device_matches("", "", ""));
api.state=1; api.createFromWindow=create; api.txCreate=tx_create; api.txDelete=tx_delete;
api.txApply=tx_apply; api.setBuffer=set_buffer; api.setVisibility=visibility;
api.setZOrder=z; api.setBufferTransparency=transparency; api.setGeometry=geometry;
api.reparent=reparent; api.release=release;
reset();
assert(sc_layer_base_black(1920,1080)==0);
assert(visible==ASC_VISIBILITY_SHOW && zorder==0 && opacity==ASC_TRANSPARENCY_OPAQUE);
assert(destination.right==1920 && destination.bottom==1080);
assert(allocs==1 && locks==1 && buffers==1 && creates==1);
assert(sc_layer_base_black(1920,1080)==0 && applies==1); /* retained, not redrawn */
assert(sc_layer_base_black(1440,1080)==0 && destination.right==1440 && allocs==1);
sc_layer_hide_base(); assert(!visible && !g_base_shown);
assert(sc_layer_base_black(1440,1080)==0 && visible && allocs==1);
base_hide(1); assert(!g_base_sc && !g_base_shown && retirements==1);
window=(ANativeWindow *)3;
assert(sc_layer_base_black(1280,720)==0 && creates==2 && allocs==1 && locks==1);
reset(); fail_alloc=1;
assert(sc_layer_base_black(1920,1080)==-1 && buffers==0 && locks==0);
reset(); fail_lock=1;
assert(sc_layer_base_black(1920,1080)==-1 && buffers==0 && releases==1 && g_blank==NULL);
reset(); fail_unlock=1;
assert(sc_layer_base_black(1920,1080)==-1 && buffers==0 && releases==1 && g_blank==NULL);
reset(); fail_tx=1;
assert(sc_layer_base_black(1920,1080)==-1 && buffers==0 && !g_base_shown);
fail_tx=0; assert(sc_layer_base_black(1920,1080)==0 && creates==1 && locks==1);
reset(); window=NULL;
assert(sc_layer_base_black(1920,1080)==-1 && allocs==0);
window=(ANativeWindow *)1;
assert(sc_layer_base_black(0,1080)==-1 && allocs==0);
puts("PASS: Quest backdrop initialization, padding, reuse, resize, retire and failure recovery");
}
+5 -4
View File
@@ -8,13 +8,14 @@ from zipfile import ZipFile
SYSTEM = set('libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so '
'libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so '
'libGLESv2.so libGLESv3.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so '
'libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so'.split())
EXPORTS = ['Java_com_droiddeck_launcher_stores_StoresNative_nativeVersion',
'Java_com_droiddeck_launcher_stores_gog_GogNative_nativeStart',
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStart',
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeAssemble',
'Java_com_droiddeck_launcher_stores_amazon_AmazonNative_nativeStart']
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeCall',
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeInstall',
'Java_com_droiddeck_launcher_stores_amazon_AmazonNative_nativeCall',
'Java_com_droiddeck_launcher_stores_amazon_AmazonNative_nativeInstall']
def check(apk, readelf, stores=True):
+10 -1
View File
@@ -1,10 +1,19 @@
"""Reject an APK with missing or stale session helpers, including cached local bundles."""
from pathlib import Path
import re
import sys
from zipfile import ZipFile
OVERLAY = Path(__file__).resolve().parents[1] / 'linuxfs/overlay'
SESSION_FILES = OVERLAY.parents[2] / 'app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt'
def check_extraction(overlay, source):
deployed = set(re.findall(r'"(usr/local/bin/droiddeck-[^"]+)"\s+to\s+"\1"', source))
return ['not extracted at session start: ' + path.relative_to(overlay).as_posix()
for path in sorted((overlay / 'usr/local/bin').glob('droiddeck-*'))
if path.relative_to(overlay).as_posix() not in deployed]
def source_assets(overlay=OVERLAY):
@@ -23,7 +32,7 @@ def source_assets(overlay=OVERLAY):
def check(apk, overlay=OVERLAY):
errors = []
errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else []
with ZipFile(apk) as package:
for source, asset in source_assets(overlay).items():
try:
+13 -5
View File
@@ -18,6 +18,8 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/mangoapp', 'tools/msitools', 'tools/comet', 'tools/build_local.sh',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
@@ -37,7 +39,7 @@ def sources(root):
for name in SOURCE_PATHS:
path = root / name
files.extend(path.rglob('*') if path.is_dir() else [path])
return {str(path.relative_to(root)): digest(path) for path in sorted(set(files))
return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files))
if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'}
@@ -47,7 +49,7 @@ def outputs(root):
base = root / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
result['assets/' + tree + '/' + str(path.relative_to(base))] = str(path.relative_to(root))
result['assets/' + tree + '/' + path.relative_to(base).as_posix()] = path.relative_to(root).as_posix()
for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']:
result['lib/arm64-v8a/' + library] = 'app/src/main/jniLibs/arm64-v8a/' + library
result['assets/pulseaudio.tzst'] = 'app/build/prepared-assets/pulseaudio.tzst'
@@ -69,14 +71,20 @@ def required():
for arch in ['x86_64', 'i386']:
paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libblsession.so']]
paths += ['assets/linuxfs/x86_64/' + lib for lib in
['libfaultreport.so', 'libthunkaudit.so', 'libvulkan-thunk.so']]
['libfaultreport.so', 'libvulkan-thunk.so', 'libwebkitinput.so']]
paths += ['assets/linuxfs/i386/libfaultreport.so']
paths += ['assets/linuxfs/usr/local/lib/droiddeck-msitools/' + name for name in
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-vr/' + name for name in
['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/driver.vrdrivermanifest',
['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/bin/linuxarm64/xr-display-mode',
'droiddeck/driver.vrdrivermanifest',
'droiddeck/resources/settings/default.vrsettings', 'layer/libVkLayer_droiddeck_vr.so',
'layer/VK_LAYER_DROIDDECK_vr.json', 'layer/VK_LAYER_DROIDDECK_vr_implicit.json']]
'layer/VK_LAYER_DROIDDECK_vr.json', 'layer/VK_LAYER_DROIDDECK_vr_implicit.json',
'layer/libdroiddeck_vr_scheduling.so']]
for side in ['left', 'right']:
paths += [f'assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/resources/rendermodels/droiddeck_hand_{side}/{name}'
for name in [f'droiddeck_hand_{side}.json', 'hand.mtl', 'hand.png', 'hand_open.obj', 'hand_fist.obj',
'thumb_index_open.obj', 'thumb_index_pinch.obj']]
paths += ['assets/linuxfs/usr/local/lib/mangoapp/' + name for name in
['mangoapp', 'libfmt.so.10', 'libspdlog.so.1.13', 'libglfw.so.3', 'libtraceevent.so.1', 'libtracefs.so.1']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-comet/' + name for name in
+1
View File
@@ -28,6 +28,7 @@ else
python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
"$P.vr_recovery=$pkg.vr_recovery" \
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
fi
got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p")
+24
View File
@@ -0,0 +1,24 @@
param([string]$Serial)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
Push-Location $repoRoot
try {
$javaConfig = if (Test-Path -LiteralPath '.gradle/config.properties' -PathType Leaf) {
Get-Content -LiteralPath '.gradle/config.properties' | Where-Object { $_ -match '^java.home=' } | Select-Object -First 1
}
if ($javaConfig) { $env:JAVA_HOME = $javaConfig.Substring('java.home='.Length).Replace('\\', '\').Replace('\:', ':') }
& .\gradlew.bat :app:assembleDebug --console=plain
if ($LASTEXITCODE -ne 0) { throw 'Android build failed.' }
$adbArgs = @()
if ($Serial) { $adbArgs = @('-s', $Serial) }
& adb @adbArgs install -r 'app/build/outputs/apk/debug/app-debug.apk'
if ($LASTEXITCODE -ne 0) { throw 'APK installation failed; existing app data was not removed.' }
$suffixLine = if (Test-Path -LiteralPath 'local.properties' -PathType Leaf) {
Get-Content -LiteralPath 'local.properties' | Where-Object { $_ -match '^droiddeck.debugApplicationIdSuffix=' } | Select-Object -First 1
}
$suffix = if ($suffixLine) { $suffixLine.Substring('droiddeck.debugApplicationIdSuffix='.Length) } else { '' }
& adb @adbArgs shell am start -W -n "com.droiddeck.launcher$suffix/com.droiddeck.launcher.MainActivity"
if ($LASTEXITCODE -ne 0) { throw 'App launch failed.' }
} finally {
Pop-Location
}
+134
View File
@@ -0,0 +1,134 @@
import argparse
import json
import os
import subprocess
import time
from pathlib import Path
from adb_device import resolve_serial
def validate_samples(samples, require_controllers=False):
if len(samples) < 2:
return 'No advancing telemetry; check runtime initialization and headset wake/proximity'
if samples[-1]['rendered'] - samples[0]['rendered'] < 72:
return 'Fewer than 72 additional stereo frames were submitted'
if not any(sample['sessionState'] == 5 and sample['headFlags'] & 15 == 15 for sample in samples):
return 'No focused session with tracked 6DoF position and orientation'
if samples[-1]['sessionState'] != 5 or samples[-1]['headFlags'] & 15 != 15:
return 'Session did not remain focused with tracked 6DoF through the final sample'
if require_controllers and not any(all(sample['controllersActive']) for sample in samples):
return 'Both controllers did not become active'
if samples[-1].get('uploadedFrames', 0) - samples[0].get('uploadedFrames', 0) < 72:
return 'No advancing owned SteamVR images; XR submissions alone are insufficient'
if samples[-1].get('sourceFrameId', 0) <= samples[0].get('sourceFrameId', 0):
return 'SteamVR source frame IDs did not advance'
if samples[-1].get('steamvrState') != 4:
return 'SteamVR did not report RUNNING'
expected = 'frames'
if samples[-1].get('source') != expected:
return 'Wrong projection source'
return None
def summarize_samples(samples):
result = {'sampleCount': len(samples), 'focusedTrackedFraction': None, 'observedSeconds': None, 'ratesHz': {}}
if not samples:
return result
result['focusedTrackedFraction'] = sum(sample.get('sessionState') == 5 and sample.get('headFlags', 0) & 15 == 15
for sample in samples) / len(samples)
if len(samples) < 2 or '_hostMonotonicSeconds' not in samples[0] or '_hostMonotonicSeconds' not in samples[-1]:
return result
duration = samples[-1]['_hostMonotonicSeconds'] - samples[0]['_hostMonotonicSeconds']
if duration <= 0:
return result
result['observedSeconds'] = duration
for counter in ('rendered', 'guestFrames', 'receivedFrames', 'rejectedFrames', 'uploadedFrames'):
if counter in samples[0] and counter in samples[-1]:
delta = samples[-1][counter] - samples[0][counter]
result['ratesHz'][counter] = delta / duration if delta >= 0 else None
period = samples[-1].get('periodNs', 0)
result['runtimeRefreshHz'] = 1000000000 / period if period > 0 else None
return result
def collect_device_metrics(adb, package):
result = {}
for name, command in [('battery', ('shell', 'dumpsys', 'battery')),
('thermal', ('shell', 'dumpsys', 'thermalservice')),
('memory', ('shell', 'dumpsys', 'meminfo', package))]:
try:
result[name] = {'available': True, 'text': adb(*command)}
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
result[name] = {'available': False, 'error': type(error).__name__}
return result
def main():
parser = argparse.ArgumentParser(description='Validate immersive DroidDeck XR on a connected Quest')
parser.add_argument('--adb', default=os.environ.get('ADB', 'adb'))
parser.add_argument('--serial')
parser.add_argument('--seconds', type=int, default=20)
parser.add_argument('--output', type=Path, default=Path('build/questxr-validation'))
parser.add_argument('--require-controllers', action='store_true')
parser.add_argument('--keep-awake', action='store_true')
parser.add_argument('--metrics', action='store_true', help='Record public battery, thermal and package memory dumps before/after testing')
args = parser.parse_args()
if args.seconds < 5 or args.seconds > 600:
parser.error('--seconds must be between 5 and 600')
serial = resolve_serial(args.adb, args.serial)
args.output.mkdir(parents=True, exist_ok=True)
def adb(*command):
return subprocess.run([args.adb, '-s', serial, *command], check=True,
capture_output=True, text=True, timeout=15).stdout
package = 'com.droiddeck.launcher'
health_path = f'/sdcard/Android/data/{package}/files/xr-health.json'
adb('shell', 'rm', '-f', health_path)
adb('shell', 'input', 'keyevent', 'KEYCODE_WAKEUP')
launch = ['shell', 'am', 'start', '-n', f'{package}/.QuestXrActivity']
samples = []
failure = None
metrics = {'before': collect_device_metrics(adb, package)} if args.metrics else None
try:
adb('shell', 'am', 'broadcast', '-a', 'com.oculus.vrpowermanager.prox_close')
adb(*launch)
deadline = time.monotonic() + args.seconds
while time.monotonic() < deadline:
time.sleep(1)
adb('shell', 'am', 'broadcast', '-a', 'com.oculus.vrpowermanager.prox_close')
try:
sample = json.loads(adb('shell', 'cat', health_path))
sample['_hostMonotonicSeconds'] = time.monotonic()
samples.append(sample)
if sample.get('error'):
failure = sample['error']
break
except (subprocess.CalledProcessError, json.JSONDecodeError):
pass
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
failure = f'ADB operation failed: {type(error).__name__}'
finally:
if not args.keep_awake:
try:
adb('shell', 'am', 'broadcast', '-a', 'com.oculus.vrpowermanager.prox_far')
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
failure = failure or 'Could not restore headset proximity after testing'
try:
log = adb('logcat', '-d', '-s', 'DroidDeckXR:I', 'OpenXR-Loader:W', 'AndroidRuntime:E')
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
log = str(error)
(args.output / 'logcat.txt').write_text(log, encoding='utf-8')
if metrics is not None:
metrics['after'] = collect_device_metrics(adb, package)
failure = failure or validate_samples(samples, args.require_controllers)
report = {'ok': failure is None, 'error': failure, 'samples': samples, 'summary': summarize_samples(samples), 'deviceMetrics': metrics}
(args.output / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps({'ok': report['ok'], 'error': failure, 'samples': len(samples),
'last': samples[-1] if samples else None}, indent=2))
return 0 if report['ok'] else 1
if __name__ == '__main__':
raise SystemExit(main())
+88
View File
@@ -0,0 +1,88 @@
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define WL_POINTER_BUTTON_STATE_RELEASED 0
#define WL_POINTER_FRAME_SINCE_VERSION 5
struct wl_resource { int version, releases, frames; uint32_t held; };
struct seat_pointer { struct wl_resource *ptr, *focus; };
static struct seat_pointer g_ptrs[3];
static int g_nptrs = 3;
static void *g_grab, *g_display;
static unsigned motion_calls, flushes;
static uint32_t now_ms(void) { return 42; }
static uint32_t wl_display_next_serial(void *d) { (void)d; return 1; }
static int wl_resource_get_version(struct wl_resource *r) { return r->version; }
static void wl_pointer_send_frame(struct wl_resource *r) { r->frames++; }
static void wl_display_flush_clients(void *d) { (void)d; flushes++; }
static void wl_pointer_send_button(struct wl_resource *r, uint32_t serial,
uint32_t t, uint32_t button, uint32_t state) {
(void)serial; (void)t;
assert(state == WL_POINTER_BUTTON_STATE_RELEASED);
r->held &= ~(1u << (button - 0x110));
r->releases++;
}
/* The old dispatcher calls this even for releases, emitting stale coordinates.
* Recording this boundary detects that unwanted motion/focus routing path. */
static void pointer_input(double x, double y, int relative, uint32_t button, int pressed) {
assert(x == 0 && y == 0 && relative == 1 && button >= 0x110 && button <= 0x112);
assert(pressed == 1);
motion_calls++;
}
#include "pointer_button.inc"
#define BTN_LEFT 0x110
#define MAX_TOUCH_POINTS 2
struct touch_point { int pointer_fallback; };
static struct touch_point g_touch_points[MAX_TOUCH_POINTS];
struct seat_touch { struct wl_resource *touch, *focus; };
static struct seat_touch g_touches[1];
static int g_ntouches = 1, cancels;
static void wl_touch_send_cancel(struct wl_resource *r) { (void)r; cancels++; }
#include "touch_cancel_all.inc"
int main(int argc, char **argv) {
assert(argc == 2);
struct wl_resource surface = {0};
struct wl_resource a = {.version = 5, .held = 7};
struct wl_resource b = {.version = 4, .held = 7};
struct wl_resource other = {.version = 5, .held = 7};
g_ptrs[0] = (struct seat_pointer){&a, &surface};
g_ptrs[1] = (struct seat_pointer){&b, &surface};
g_ptrs[2] = (struct seat_pointer){&other, NULL};
g_grab = &surface;
if (!strcmp(argv[1], "fallback") || !strcmp(argv[1], "native")) {
int fallback = !strcmp(argv[1], "fallback");
g_touches[0] = (struct seat_touch){&a, &surface};
g_touch_points[0].pointer_fallback = fallback;
touch_cancel_all();
assert(!motion_calls && cancels == 1 && !g_touches[0].focus);
assert(!g_touch_points[0].pointer_fallback);
assert(a.releases == fallback && a.held == (fallback ? 6u : 7u));
for (uint32_t button = 0x110; button <= 0x112; button++) pointer_button(button, 0);
assert(!motion_calls && !a.held && !b.held && !g_grab);
} else if (!strcmp(argv[1], "press")) {
pointer_button(0x110, 1);
assert(motion_calls == 1 && !a.releases && g_grab == &surface);
} else if (!strcmp(argv[1], "unfocused")) {
g_ptrs[0].focus = g_ptrs[1].focus = NULL;
pointer_button(0x110, 0);
assert(!motion_calls && !a.releases && !b.releases && !other.releases);
assert(!g_grab);
} else if (!strcmp(argv[1], "cleanup")) {
for (uint32_t button = 0x110; button <= 0x112; button++) pointer_button(button, 0);
assert(!motion_calls && !a.held && !b.held && other.held == 7);
assert(a.releases == 3 && b.releases == 3 && !other.releases);
assert(!g_grab && flushes == 3);
} else {
assert(!strcmp(argv[1], "focused"));
a.held = b.held = 1;
pointer_button(0x110, 0);
assert(!motion_calls && !a.held && !b.held);
assert(a.releases == 1 && b.releases == 1 && !other.releases);
assert(a.frames == 1 && !b.frames && !other.frames);
assert(g_ptrs[0].focus == &surface && g_ptrs[1].focus == &surface);
assert(!g_grab && flushes == 1);
}
puts("PASS");
}
+83
View File
@@ -0,0 +1,83 @@
const assert = require('assert');
const vm = require('vm');
const source = require('fs').readFileSync(process.argv[2], 'utf8');
const calls = [], requests = [], errors = [], timers = new Set();
let changed;
const apps = { RunGame(...args) { calls.push({receiver: this, args}); return 'native'; } };
const openvr = {
RegisterForVRModeChange(callback) { changed = callback; callback(false); return {unregister() {}}; },
StartVR(...args) { return args; },
};
const overview = new Map([
['611670', {vr_only: true}],
['620980', {vr_supported: true}],
['730', {vr_only: false, vr_supported: false}],
['18446744069414584320', {BSupportsVR() { return true; }}],
]);
const context = {
SteamClient: {Apps: apps, OpenVR: openvr},
appStore: {GetAppOverviewByGameID: id => overview.get(id)},
droiddeckLaunchSteamVr: id => requests.push(id),
setTimeout(callback, ms) { assert.strictEqual(ms, 600000); timers.add(callback); return callback; },
clearTimeout: timer => timers.delete(timer),
console: {error: message => errors.push(message)},
};
context.window = context;
vm.createContext(context);
assert.strictEqual(vm.runInContext(source, context), 'installed');
assert.strictEqual(vm.runInContext(source, context), 'present');
assert.strictEqual(apps.RunGame(730, '', -1, 100), 'native');
assert.deepStrictEqual(requests, []);
assert.strictEqual(calls[0].receiver, apps);
const receiver = {};
apps.RunGame.call(receiver, '611670', 'custom args', 2, 100);
apps.RunGame('611670', 'duplicate', -1, 100);
assert.strictEqual(apps.RunGame(620980, '', -1, 100), 'native');
assert.deepStrictEqual(requests, ['611670']);
assert.strictEqual(calls.length, 2);
assert.deepStrictEqual(calls[1].args, [620980, '', -1, 100]);
changed(false);
assert.strictEqual(calls.length, 2);
changed(true);
assert.strictEqual(calls.length, 3);
assert.strictEqual(calls[2].receiver, receiver);
assert.deepStrictEqual(calls[2].args, ['611670', 'custom args', 2, 100]);
assert.strictEqual(timers.size, 0);
changed(true);
assert.strictEqual(calls.length, 3);
changed(false);
assert.strictEqual(apps.RunGame('18446744069414584320', '', -1, 100), 'native');
assert.deepStrictEqual(calls[3].args, ['18446744069414584320', '', -1, 100]);
assert.deepStrictEqual(requests, ['611670']);
assert.strictEqual(timers.size, 0);
changed(true);
apps.RunGame('250820', '', -1, 100);
openvr.StartVR(true);
assert.deepStrictEqual(requests.slice(-2), ['250820', '250820']);
assert.strictEqual(calls.length, 4);
changed(false);
apps.RunGame('611670', '', -1, 100);
for (const timeout of [...timers]) { timers.delete(timeout); timeout(); }
assert.strictEqual(context.__droiddeckSteamVr.pending.size, 0);
assert.strictEqual(errors.length, 1);
changed(true);
assert.strictEqual(calls.length, 4);
apps.RunGame('611670', '', -1, 100);
assert.strictEqual(calls.length, 5);
assert.strictEqual(context.__droiddeckSteamVr.lastError, null);
changed(false);
context.droiddeckLaunchSteamVr = () => { throw new Error('bridge disconnected'); };
assert.throws(() => apps.RunGame('611670', '', -1, 100), /bridge disconnected/);
assert.strictEqual(context.__droiddeckSteamVr.pending.size, 0);
assert.strictEqual(timers.size, 0);
delete context.droiddeckLaunchSteamVr;
assert.strictEqual(apps.RunGame('611670', '', -1, 100), 'native');
assert.strictEqual(apps.RunGame('250820', '', -1, 100), 'native');
assert.deepStrictEqual(openvr.StartVR(true), [true]);
assert.strictEqual(calls.length, 7);
+1 -1
View File
@@ -60,7 +60,7 @@ class BinfmtPreloadTest(unittest.TestCase):
cls.library = cls.tmp / "libbinfmt.so"
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DBINFMT_TEST",
'-DBINFMT_HANDLER="%s"' % cls.handler, "-o", str(cls.library),
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c")] + ["-ldl"],
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "webhelper.c")] + ["-ldl"],
check=True)
source = cls.tmp / "program.c"
source.write_text(PROGRAM)
+35
View File
@@ -0,0 +1,35 @@
import importlib.util
import io
from pathlib import Path
import unittest
import zipfile
spec = importlib.util.spec_from_file_location('build_hand_lite', Path(__file__).parents[1] / 'build_hand_lite.py')
builder = importlib.util.module_from_spec(spec)
spec.loader.exec_module(builder)
class HandLiteBundleTest(unittest.TestCase):
def test_embedded_labels_are_reproducible_without_changing_model_bytes(self):
model = b'\x08\x00\x00\x00TFL3model tensors and weights'
outputs = []
for year, order in [(2020, ['labels.txt', 'handedness.txt']),
(2026, ['handedness.txt', 'labels.txt'])]:
source = io.BytesIO(model)
with zipfile.ZipFile(source, 'a') as archive:
for name in order:
entry = zipfile.ZipInfo(name, (year, 10, 16, 12, 30, 0))
archive.writestr(entry, name.encode())
output = builder.canonicalize_associated_files(source.getvalue())
self.assertEqual(model, output[:len(model)])
self.assertEqual(output, builder.canonicalize_associated_files(output))
with zipfile.ZipFile(io.BytesIO(output)) as archive:
for name in order:
self.assertEqual(name.encode(), archive.read(name))
outputs.append(output)
self.assertEqual(*outputs)
if __name__ == '__main__':
unittest.main()
+1 -1
View File
@@ -16,7 +16,7 @@ class CdpGuardTest(unittest.TestCase):
def setUpClass(cls):
cls.build = tempfile.TemporaryDirectory()
cls.library = Path(cls.build.name) / "net.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), "-x", "c", "-", "-ldl",
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"), "-x", "c", "-", "-ldl",
"-o", str(cls.library)],
input=b"int bl_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
+59
View File
@@ -516,6 +516,65 @@ class ProtonRunTest(Temp):
self.assertEqual(env["SteamAppId"], "413150")
self.assertTrue((self.root / "steamapps/compatdata/413150").is_dir())
def run_main(self, argv):
calls, dirs = [], []
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
mock.patch.object(RUN["os"], "execve", lambda *a: calls.append(a)), \
mock.patch.object(RUN["os"], "chdir", dirs.append), mock.patch.dict(RUN, {"say": lambda message: None}):
code = RUN["main"](argv)
return code, calls, dirs
def test_without_steam_a_steam_game_starts_its_default_windows_launch(self):
info = {"common": {"type": "Game", "oslist": "windows,linux"}, "config": {"launch": {
"0": {"executable": "Bin\\Game.exe", "arguments": "-dx11 \"-name=Two Words\"", "workingdir": "bin",
"type": "default", "config": {"oslist": "windows"}},
"1": {"executable": "game.sh", "type": "default", "config": {"oslist": "linux"}},
"2": {"executable": "Beta.exe", "type": "default", "config": {"oslist": "windows", "betakey": "beta"}},
"3": {"executable": "Tools\\Editor.exe", "type": "option1"},
}}}
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
program = self.game("413150", "Some Game", "bin/game.exe")
self.game("413150", "Some Game", "Tools/Editor.exe")
code, calls, dirs = self.run_main(["--app", "413150", "--options", "-windowed"])
self.assertIsNone(code)
entry, argv, env = calls[0]
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-dx11", "-name=Two Words", "-windowed"])
self.assertEqual((env["SteamAppId"], env["STEAM_COMPAT_DATA_PATH"]),
("413150", str(self.root / "steamapps/compatdata/413150")))
self.assertEqual(dirs, [str(program.parent)])
def test_without_steam_a_game_steam_cannot_start_is_refused(self):
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
self.assertEqual(self.run_main(["--app", "413150"])[0], 2)
self.assertEqual(self.run_main(["--app", "3384071994"])[0], 2)
self.assertEqual(self.run_main(["--app", "0"])[0], 2)
self.assertEqual(self.run_main(["--app", "game"])[0], 2)
linux = {"common": {"type": "Game"}, "config": {"launch": {"0": {"executable": "run.sh", "config": {"oslist": "linux"}}}}}
self.write("Steam/appcache/appinfo.vdf", appinfo({70: linux}))
self.game("70", "Linux Game", "run.sh")
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self):
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
start = self.tmp / "Games/Epic/Game/Binaries"
start.mkdir()
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--options",
"PROTON_LOG=1 %command% -epicportal", "--", str(bat)])
self.assertIsNone(code)
entry, argv, env = calls[0]
self.assertEqual(argv[1:], ["waitforexitandrun", str(bat), "-epicportal"])
self.assertEqual((env["STEAM_COMPAT_DATA_PATH"], env["SteamAppId"], env["SteamGameId"], env["PROTON_LOG"]),
(str(self.root / "steamapps/compatdata/2733369024"), "0", str(2733369024 << 32 | 0x02000000), "1"))
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
self.assertEqual(dirs, [str(start)])
def test_launch_options_split_like_steam_does(self):
split = RUN["split_options"]
self.assertEqual(split(""), ({}, []))
self.assertEqual(split("-windowed -w 1280"), ({}, ["-windowed", "-w", "1280"]))
self.assertEqual(split("A=1 B=\"x y\" gamemoderun %command% -dx12"), ({"A": "1", "B": "x y"}, ["-dx12"]))
self.assertEqual(split("\"unterminated -x"), ({}, ["\"unterminated", "-x"]))
if __name__ == "__main__":
unittest.main()
+113
View File
@@ -255,6 +255,89 @@ class AgentTest(unittest.TestCase):
answer = self.ask({"kind": "steam-selection"})
self.assertEqual("INVALID_SELECTION", answer["error"]["code"])
def test_shortcut_cgameid_waits_for_exact_steam_overview_mapping(self):
game_id = str((3551182975 << 32) | 0x02000000)
self.assertEqual(3551182975, agent.steam_shortcut_app_id(game_id))
self.assertIsNone(agent.steam_shortcut_app_id("413150"))
self.assertIsNone(agent.steam_shortcut_app_id(str((3551182975 << 32) | 0x03000000)))
clock = [0.0]
with patch.object(agent, "cdp_eval", side_effect=[{"value": None}, {"value": "3551182975"}]) as evaluate, \
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
result = agent.wait_for_steam_shortcut_overview(self.dir, game_id, timeout=1)
self.assertEqual({"supported": True, "ready": True, "appId": 3551182975}, result)
expression = evaluate.call_args_list[0].args[1]
self.assertIn("GetAppOverviewByGameID", expression)
self.assertIn(json.dumps(game_id), expression)
self.assertNotIn("RequestAppDetails", expression)
self.assertFalse(evaluate.call_args_list[0].kwargs["await_promise"])
def test_wrong_overview_app_id_keeps_shortcut_url_held_until_timeout(self):
game_id = str((3537741571 << 32) | 0x02000000)
clock = [0.0]
with patch.object(agent, "cdp_eval", return_value={"value": "646570"}) as evaluate, \
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
with self.assertRaises(agent.AgentError) as raised:
agent.wait_for_steam_shortcut_overview(self.dir, game_id, timeout=0.5)
self.assertEqual("STEAM_OVERVIEW_TIMEOUT", raised.exception.code)
self.assertGreater(evaluate.call_count, 0)
self.assertTrue(all("RequestAppDetails" not in call.args[1] for call in evaluate.call_args_list))
def test_normal_steam_ids_and_unknown_cgameids_skip_overview_wait(self):
for game_id in ("413150", str((123456789 << 32) | 0x03000000), "18446744073709551616"):
with self.subTest(game_id=game_id), patch.object(agent, "cdp_eval") as evaluate:
result = agent.wait_for_steam_shortcut_overview(self.dir, game_id)
self.assertFalse(result["supported"])
evaluate.assert_not_called()
def test_shortcut_state_tells_a_lost_shortcut_from_a_loading_library(self):
game_id = str((3333273269 << 32) | 0x02000000)
self.assertEqual("not-shortcut", agent.steam_shortcut_state(self.dir, "413150"))
for values, wanted, calls in ((["loading", "ready"], "ready", 2), (["loading", "missing"], "missing", 3),
([None], "loading", 3)):
clock = [0.0]
replies = [{"value": v} for v in values] + [{"value": values[-1]}] * 10
with self.subTest(values=values), patch.object(agent, "cdp_eval", side_effect=replies) as evaluate, \
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
self.assertEqual(wanted, agent.steam_shortcut_state(self.dir, game_id, timeout=1))
self.assertEqual(calls, evaluate.call_count)
self.assertIn("GetAppOverviewByGameID(%s)" % json.dumps(game_id), evaluate.call_args_list[0].args[1])
def test_shortcut_state_waits_out_an_unreachable_client_but_not_other_errors(self):
game_id = str((3333273269 << 32) | 0x02000000)
clock = [0.0]
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")), \
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
self.assertEqual("loading", agent.steam_shortcut_state(self.dir, game_id, timeout=1))
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("CDP_EXCEPTION", "boom")):
with self.assertRaises(agent.AgentError):
agent.steam_shortcut_state(self.dir, game_id, timeout=1)
def test_shortcut_state_command_exits_with_the_state(self):
game_id = str((3333273269 << 32) | 0x02000000)
launch = self.dir.parent
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}):
for state, code in (("ready", 0), ("missing", 4), ("not-shortcut", 3), ("loading", 1)):
with self.subTest(state=state), patch.object(agent, "steam_shortcut_state", return_value=state) as ask:
self.assertEqual(code, agent.main(["--steam-shortcut-state", game_id, "2"]))
self.assertEqual((launch / "agent", game_id, "2"), ask.call_args.args)
with patch.object(agent, "steam_shortcut_state", side_effect=agent.AgentError("CDP_EXCEPTION", "boom")):
self.assertEqual(1, agent.main(["--steam-shortcut-state", game_id]))
self.assertEqual(2, agent.main(["--steam-shortcut-state"]))
def test_asleep_command_reports_steams_own_sleep_state(self):
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
for value, code in (("yes", 0), ("no", 5), ("unknown", 1), (None, 1)):
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
self.assertEqual(code, agent.main(["--steam-asleep"]))
self.assertIn("m_bSuspending", ask.call_args.args[1])
self.assertFalse(ask.call_args.kwargs["await_promise"])
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
self.assertEqual(1, agent.main(["--steam-asleep"]))
def test_cdp_exception(self):
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
@@ -299,5 +382,35 @@ class AgentTest(unittest.TestCase):
self.assertIn(child.pid, agent.game_pids(424242))
class VrFocusTest(unittest.TestCase):
def test_scene_dashboard_and_external_focus_changes(self):
focus = agent.VrSceneFocus()
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
self.assertIsNone(focus.order([42, 9, 7], [7, 42], 42))
self.assertEqual(focus.order([42, 9, 7], [7, 42], None), [9, 7])
self.assertIsNone(focus.order([9, 7], [7], 42))
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
# Do not overwrite a different focus order installed after our last write.
self.assertIsNone(focus.order([123, 7], [7, 42], None))
def test_scene_requires_live_server_and_game_environment(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
state = root / 'scene.json'
for pid in (100, 200):
(root / str(pid)).mkdir()
(root / '100/comm').write_text('vrserver\n')
(root / '200/environ').write_bytes(b'SteamAppId=42\0Other=value\0')
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=False)))
self.assertEqual(agent.vr_scene_app(state, root), 42)
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=True)))
self.assertIsNone(agent.vr_scene_app(state, root))
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=False)))
(root / '100/comm').write_text('other\n')
self.assertIsNone(agent.vr_scene_app(state, root))
(root / '100/comm').unlink()
self.assertIsNone(agent.vr_scene_app(state, root))
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+259 -29
View File
@@ -92,6 +92,38 @@ class FexTestCase(unittest.TestCase):
self.write(self.steam / "steamapps/appmanifest_1628350.acf", '"AppState" { "installdir" "SteamLinuxRuntime_sniper" }')
return platform
def graphics(self, sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41", libstdcxx=b"GLIBCXX_3.4.28 GLIBCXX_3.4.33"):
files = Path(sniper) / "files"
x86 = files / "lib/x86_64-linux-gnu"
self.write(x86 / "libc-2.31.so", b"GLIBC_2.2.5 GLIBC_2.31")
os.unlink(x86 / "libc.so.6")
os.symlink("libc-2.31.so", x86 / "libc.so.6")
self.write(x86 / "ld-2.31.so", b"old ld")
os.symlink("ld-2.31.so", x86 / "ld-linux-x86-64.so.2")
self.write(x86 / "libstdc++.so.6", b"GLIBCXX_3.4.28")
self.write(x86 / "libSegFault.so", b"old")
self.write(x86 / "libSDL2-2.0.so.0", b"sdl")
self.write(x86 / "libfoo.so.1.2", b"foo")
os.symlink("libfoo.so.1.2", x86 / "libfoo.so.1")
self.write(x86 / "gconv/OLD.so", b"old gconv")
self.write(files / "lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.31")
self.write(files / "lib/i386-linux-gnu/ld-2.31.so", b"old ld32")
os.symlink("i386-linux-gnu/ld-2.31.so", files / "lib/ld-linux.so.2")
os.unlink(files / "lib64/ld-linux-x86-64.so.2")
os.symlink("../lib/x86_64-linux-gnu/ld-2.31.so", files / "lib64/ld-linux-x86-64.so.2")
platform = self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390"
provided = platform / "files/lib/x86_64-linux-gnu"
self.write(provided / "libc.so.6", libc)
self.write(provided / "libstdc++.so.6", libstdcxx)
self.write(provided / "ld-linux-x86-64.so.2", b"new ld")
self.write(provided / "gconv/NEW.so", b"new gconv")
self.write(platform / "files/lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.41")
self.write(platform / "files/lib/i386-linux-gnu/ld-linux.so.2", b"new ld32")
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
out.write("#mtree\n. type=dir\n")
self.write(self.steam / "steamapps/appmanifest_4183110.acf", '"AppState" { "installdir" "SteamLinuxRuntime_4" }')
return platform
def quiet(self, function, *args):
with contextlib.redirect_stderr(io.StringIO()) as err:
return function(*args), err.getvalue()
@@ -198,12 +230,11 @@ class PrepareTest(FexTestCase):
for arch in ("x86_64", "i386"):
for name in ("libblsession.so", "libfakeinput.so"):
self.write(self.tmp / "preloads" / arch / name, arch.encode() + name.encode())
self.write(self.tmp / "preloads/x86_64/libthunkaudit.so", b"audit")
self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", b"pin")
self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libblsession.so\n/usr/local/lib/libfakeinput.so\n")
FEX["install_preloads"](str(root))
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/libthunkaudit.so").read_bytes(), b"audit")
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/libvulkan-thunk.so").read_bytes(), b"pin")
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so.1").read_bytes(), b"pin")
self.assertEqual(os.readlink(root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so"), "libvulkan.so.1")
self.assertEqual((root / "etc/ld.so.preload").read_text(),
"/usr/$LIB/droiddeck/libblsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n")
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfakeinput.so").read_bytes(), b"i386libfakeinput.so")
@@ -252,7 +283,71 @@ class PrepareTest(FexTestCase):
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertEqual((status["ready"], status["runtime"], status["thunks"]), (True, str(platform), True))
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
self.assertEqual(self.quiet(FEX["prepare"])[1], "")
self.assertNotIn("prepared", self.quiet(FEX["prepare"])[1])
def test_a_newer_runtime_supplies_the_c_and_cxx_libraries(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
fex, said = self.quiet(FEX["prepare"])
root = self.home / ".local/share/droiddeck-fex/rootfs"
self.assertIn("built the x86 runtime from sniper_platform_", said)
self.assertEqual(fex["rootfs"], str(root))
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(config["Config"]["RootFS"], str(root))
x86 = root / "lib/x86_64-linux-gnu"
self.assertEqual((x86 / "libc.so.6").read_bytes(), b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41")
self.assertEqual((x86 / "libstdc++.so.6").read_bytes(), b"GLIBCXX_3.4.28 GLIBCXX_3.4.33")
self.assertEqual((x86 / "ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual((x86 / "gconv/NEW.so").read_bytes(), b"new gconv")
self.assertEqual((root / "lib/i386-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.41")
self.assertEqual((x86 / "libSDL2-2.0.so.0").read_bytes(), b"sdl")
self.assertEqual(os.readlink(x86 / "libfoo.so.1"), "libfoo.so.1.2")
self.assertEqual((x86 / "libfoo.so.1").read_bytes(), b"foo")
for stale in ("libc-2.31.so", "ld-2.31.so", "libSegFault.so"):
self.assertFalse(os.path.lexists(x86 / stale), stale)
self.assertEqual(os.readlink(root / "lib/ld-linux.so.2"), "i386-linux-gnu/ld-linux.so.2")
self.assertEqual((root / "lib/ld-linux.so.2").read_bytes(), b"new ld32")
self.assertEqual(os.readlink(root / "lib64/ld-linux-x86-64.so.2"), "../lib/x86_64-linux-gnu/ld-linux-x86-64.so.2")
self.assertEqual((root / "lib64/ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual(os.readlink(root / "usr"), ".")
self.assertEqual((root / "usr/bin/[").read_bytes(), b"blob")
self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.2.5 GLIBC_2.31")
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertEqual(status["graphics"], str(provider))
self.assertNotIn("built", self.quiet(FEX["prepare"])[1])
os.utime(provider / "usr-mtree.txt.gz", ns=(1, 1))
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"])
def test_a_runtime_that_is_not_newer_is_left_out(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31", libstdcxx=b"GLIBCXX_3.4.28")
fex, said = self.quiet(FEX["prepare"])
self.assertEqual(fex["rootfs"], str(sniper / "files"))
self.assertIn("has no newer C and C++ libraries than sniper_platform_", said)
self.assertFalse((self.home / ".local/share/droiddeck-fex/rootfs").exists())
def test_x86_steamworks_finds_the_x86_client(self):
for directory, machine in (("linux64", 62), ("linux32", 3), ("linuxarm64", 183)):
self.write(self.steam / directory / "steamclient.so", elf(machine))
sdk = self.home / ".steam"
sdk.mkdir(parents=True)
os.symlink(self.steam / "linuxarm64", sdk / "sdk64")
os.symlink(self.steam / "linuxarm64", sdk / "sdkarm64")
FEX["link_steam_sdk"]()
self.assertEqual(os.readlink(sdk / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(sdk / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(os.readlink(sdk / "sdkarm64"), str(self.steam / "linuxarm64"))
os.unlink(sdk / "sdk32")
os.symlink(self.tmp / "elsewhere", sdk / "sdk32")
self.write(self.tmp / "elsewhere/steamclient.so", elf(3))
FEX["link_steam_sdk"]()
self.assertEqual(os.readlink(sdk / "sdk32"), str(self.tmp / "elsewhere"))
self.assertEqual(sorted(os.listdir(sdk)), ["sdk32", "sdk64", "sdkarm64"])
def test_status_refreshes_what_the_app_reads_once_steam_installed_fex(self):
with mock.patch.dict(G, {"steam_running": lambda: False}):
@@ -317,6 +412,35 @@ class ExtractTest(FexTestCase):
self.assertTrue((self.home / ".config/droiddeck/fex-wanted").is_file())
self.assertFalse(json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())["ready"])
def test_uruntime_that_only_drops_extended_attributes_still_unpacks(self):
tool = self.uruntime(
"mkdir -p AppDir && touch AppDir/AppRun\n"
"echo 'Failed to exec memfd: EACCES: Permission denied. Trying tmpfile in /tmp...' >&2\n"
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
"echo 'Further error messages of this type are suppressed!' >&2\n"
"exit 2\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("could not keep the image's extended attributes", said)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_an_attribute_only_failure_without_apprun_is_not_taken_as_unpacked(self):
tool = self.uruntime(
"mkdir -p AppDir\n"
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
"exit 2\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False, "prepare": lambda: None}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertIn("uruntime could not extract it (status 2)", said)
self.assertNotIn("could not keep the image's extended attributes", said)
self.assertFalse(os.path.lexists("squashfs-root/AppRun"))
def test_other_uruntime_errors_are_not_taken_as_unpacked(self):
self.assertFalse(FEX["only_xattrs_failed"]("write_xattr: could not write xattr\nwrite_file: failed to create file x\n"))
self.assertFalse(FEX["only_xattrs_failed"](""))
self.assertTrue(FEX["only_xattrs_failed"]("proot error: execveat() failed\nwrite_xattr: could not write xattr\n"))
def test_an_arm64_image_does_not_ask_for_fex(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime("mkdir -p squashfs-root\n")
@@ -335,13 +459,40 @@ class ExtractTest(FexTestCase):
self.assertIn("no AppImage runtime for ARM64, no FEX yet and no unsquashfs", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def test_unsquashfs_fallback_disables_unwritable_xattrs(self):
tool = self.uruntime("exit 1\n")
commands = []
def call(argv, **kwargs):
commands.append(argv)
if argv[0] == tool:
return 1
(self.work / "squashfs-root").mkdir()
(self.work / "squashfs-root/AppRun").touch()
return 0
with mock.patch.dict(G, {
"URUNTIME": tool,
"prepare": lambda: None,
"fex_install": lambda: None,
"steam_running": lambda: False,
"want_fex": lambda: None,
}), mock.patch("shutil.which", return_value="/usr/bin/unsquashfs"), \
mock.patch("subprocess.call", side_effect=call):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual(commands[-1][0], "/usr/bin/unsquashfs")
self.assertIn("-no-xattrs", commands[-1])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
class LaunchTest(FexTestCase):
def test_the_guest_environment(self):
arm = self.write(self.tmp / "arm.so", elf(183))
x86 = self.write(self.tmp / "x86.so", elf(62))
env = {"LD_PRELOAD": "%s:%s %s" % (arm, x86, self.tmp / "gone.so"),
"LD_LIBRARY_PATH": "/steam/steamrtarm64:/usr/lib/aarch64-linux-gnu:/game/lib",
"LD_LIBRARY_PATH": "/steam/steamrtarm64:/usr/lib/aarch64-linux-gnu:/game/lib:/steam/linuxarm64",
"FEX_ROOTFS": "/usr/share/guestos/fex-mesa", "FEX_TSOENABLED": "1"}
guest = FEX["guest_environment"]({"portable": True}, env)
self.assertEqual((guest["LD_PRELOAD"], guest["LD_LIBRARY_PATH"], guest["FEX_PORTABLE"]), (str(x86), "/game/lib", "1"))
@@ -349,8 +500,10 @@ class LaunchTest(FexTestCase):
self.assertEqual(guest["FEX_TSOENABLED"], "1")
self.assertTrue(guest["FEX_APP_CONFIG_LOCATION"].endswith("/config/"))
self.assertEqual((guest["FEX_SILENTLOG"], guest["FEX_OUTPUTLOG"]), ("0", "stderr"))
guest = FEX["guest_environment"]({"portable": False}, {"LD_PRELOAD": str(arm), "FEX_PORTABLE": "1", "FEX_OUTPUTLOG": "/tmp/fex.log"})
self.assertEqual(guest["FEX_OUTPUTLOG"], "/tmp/fex.log")
self.assertEqual(guest["GC_DISABLE_INCREMENTAL"], "1")
guest = FEX["guest_environment"]({"portable": False}, {"LD_PRELOAD": str(arm), "FEX_PORTABLE": "1", "FEX_OUTPUTLOG": "/tmp/fex.log",
"GC_DISABLE_INCREMENTAL": "0"})
self.assertEqual((guest["FEX_OUTPUTLOG"], guest["GC_DISABLE_INCREMENTAL"]), ("/tmp/fex.log", "0"))
self.assertNotIn("LD_PRELOAD", guest)
self.assertNotIn("FEX_PORTABLE", guest)
@@ -414,9 +567,8 @@ class LaunchTest(FexTestCase):
self.runtime()
self.write(tool / "usr/share/fex-emu/GuestThunks/libvulkan-guest.so",
elf(62) + b"\0libstdc++.so.6\0GLIBCXX_3.4\0GLIBCXX_3.4.29\0libc.so.6\0GLIBC_2.2.5\0GLIBC_2.34\0")
self.write(self.tmp / "preloads/x86_64/libthunkaudit.so", elf(62))
pin = self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", elf(62))
audit = "/usr/lib/x86_64-linux-gnu/droiddeck/libthunkaudit.so"
pin = self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", elf(62) + b"\0libc.so.6\0GLIBC_2.2.5\0")
pinned = "/usr/lib/x86_64-linux-gnu/droiddeck/vulkan"
def app(name, glibc=b"GLIBC_2.34\0GLIBC_2.44", glibcxx=b"GLIBCXX_3.4.29\0GLIBCXX_3.4.36", bundled=True):
run = self.write(self.tmp / name / "AppRun", elf(62), 0o755)
@@ -431,25 +583,32 @@ class LaunchTest(FexTestCase):
_, said = self.quiet(FEX["launch"], [str(program)], dict(env or {}), "on", decide)
return emulated.call_args[0][2], said
def search(env):
return env.get("LD_LIBRARY_PATH", "").split(":")[0]
env, said = started(app("new"))
self.assertEqual(env["LD_AUDIT"], audit)
self.assertIn("thunks on, its own Vulkan loader too", said)
env, _ = started(app("kept"), {"LD_AUDIT": "/opt/audit.so"})
self.assertEqual(env["LD_AUDIT"], audit + ":/opt/audit.so")
env, _ = started(self.write(self.tmp / "elsewhere/run.sh", "#!/bin/sh\n", 0o755), decide=str(self.tmp / "new"))
self.assertEqual(env["LD_AUDIT"], audit)
env, said = started(app("old-cxx", glibcxx=b"GLIBCXX_3.4.28"))
self.assertEqual(search(env), pinned)
self.assertNotIn("LD_AUDIT", env)
self.assertNotIn("LD_BIND_NOW", env)
self.assertIn("thunks on, its own Vulkan loader too", said)
env, _ = started(app("kept"), {"LD_LIBRARY_PATH": "/game/lib"})
self.assertEqual(env["LD_LIBRARY_PATH"], pinned + ":/game/lib")
env, _ = started(self.write(self.tmp / "elsewhere/run.sh", "#!/bin/sh\n", 0o755), decide=str(self.tmp / "new"))
self.assertEqual(search(env), pinned)
env, said = started(app("old-cxx", glibcxx=b"GLIBCXX_3.4.28"))
self.assertNotEqual(search(env), pinned)
self.assertIn("thunks on)", said)
self.assertNotIn("LD_AUDIT", started(app("old-libc", glibc=b"GLIBC_2.31"))[0])
self.assertNotIn("LD_AUDIT", started(app("runtime-only", bundled=False))[0])
self.assertNotEqual(search(started(app("old-libc", glibc=b"GLIBC_2.31"))[0]), pinned)
self.assertNotEqual(search(started(app("runtime-only", bundled=False))[0]), pinned)
i386 = self.write(self.tmp / "new/game.i386", elf(3), 0o755)
self.assertNotIn("LD_AUDIT", started(i386)[0])
self.assertNotEqual(search(started(i386)[0]), pinned)
self.write(pin, elf(62) + b"\0libc.so.6\0GLIBC_2.45\0")
self.assertNotEqual(search(started(app("new"))[0]), pinned)
pin.unlink()
self.assertNotIn("LD_AUDIT", started(app("no-pin"))[0])
self.assertNotEqual(search(started(app("no-pin"))[0]), pinned)
self.write(pin, elf(62))
(tool / "usr/share/fex-emu/GuestThunks/libvulkan-guest.so").unlink()
self.assertNotIn("LD_AUDIT", started(app("no-thunk"))[0])
self.assertNotEqual(search(started(app("no-thunk"))[0]), pinned)
def test_steam_verbs(self):
with mock.patch.dict(G, {"launch": mock.Mock(return_value=0)}):
@@ -499,19 +658,70 @@ class AppInfoTest(unittest.TestCase):
table = struct.pack("<I", len(strings)) + b"".join(s.encode() + b"\0" for s in strings)
return struct.pack("<IIq", magic, 1, table_at) + body + table
def test_linux_only_titles_are_sent_to_fex(self):
def test_linux_only_titles_are_sent_to_fex_and_dual_platform_is_deferred(self):
for magic in (0x07564427, 0x07564428, 0x07564429):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "appcache").mkdir()
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: ("windows", "", "Game"), 20: ("linux", "64", "Game"), 30: ("windows,linux,macos", "", "game"),
40: ("linux", "arm64", "game"), 50: ("linux", "", "Demo"), 70: ("linux", "", "Tool"), 80: ("linux", "", "config"),
40: ("linux", "arm64", "game"), 41: ("windows,linux", "aarch64", "game"),
50: ("linux", "", "Demo"), 70: ("linux", "", "Tool"), 80: ("linux", "", "config"),
90: ("linux", "", ""),
}, magic))
self.COMPAT["APPINFO_CACHE"].clear()
targets = self.COMPAT["native_targets"](str(steam), ["10", "20", "30", "40", "50", "70", "80", "90", "1628350", "60"])
self.assertEqual(targets, {"20": "droiddeck-fex", "50": "droiddeck-fex"}, hex(magic))
targets = self.COMPAT["native_targets"](str(steam), ["10", "20", "30", "40", "41", "50", "70", "80", "90", "1628350", "60"])
self.assertEqual(targets, {
"20": "droiddeck-fex", "30": self.COMPAT["NATIVE_CHOICE"],
"40": None, "41": None, "50": "droiddeck-fex",
}, hex(magic))
@staticmethod
def manifest(steam, app, flags="4"):
(steam / "steamapps").mkdir(exist_ok=True)
(steam / ("steamapps/appmanifest_%s.acf" % app)).write_text('"AppState" { "appid" "%s" "StateFlags" "%s" }' % (app, flags))
def test_dual_platform_titles_keep_the_proton_default_unless_the_user_picks_fex(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp) / "Steam"
(steam / "appcache").mkdir(parents=True)
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: ("windows,linux", "", "game"), 20: ("windows,linux", "", "game"), 30: ("windows,linux", "", "game"),
40: ("linux", "", "game"),
}))
self.COMPAT["APPINFO_CACHE"].clear()
for app in ("3127680", "1628350", "4183110"):
self.manifest(steam, app)
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
state = Path(tmp) / "state"
state.mkdir()
(state / "state.json").write_text(json.dumps({"auto": {"20": fex}}))
catalog = [{"name": tool, "display": "Proton Experimental ARM64", "dir": "Proton Experimental (ARM64)", "valve": True}]
config = steam / "config/config.vdf"
config.parent.mkdir()
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { '
'"0" { "name" "%s" "config" "" "priority" "75" } '
'"20" { "name" "%s" "config" "" "priority" "250" } '
'"30" { "name" "%s" "config" "" "priority" "250" } } } } } }' % (tool, fex, fex))
self.COMPAT["register_default"](str(config), ["10", "20", "30", "40"], catalog=catalog, directory=str(state))
self.assertEqual(self.COMPAT["read_config_mapping"](str(config)),
{"0": tool, "10": tool, "20": tool, "30": fex, "40": fex})
def test_tools_are_fetched_until_fully_installed_and_up_to_date(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "steamapps").mkdir()
downloads = self.COMPAT["tool_downloads"]
self.assertEqual(downloads(str(steam)), [
("4427310", "install"), ("3127680", "install"), ("1628350", "install"), ("4183110", "install")])
self.manifest(steam, "4427310", flags="6")
self.manifest(steam, "3127680", flags="1026")
self.manifest(steam, "1628350", flags="4")
(steam / "steamapps/appmanifest_4183110.acf").write_text('"AppState" { "appid" "4183110" }')
self.assertEqual(downloads(str(steam)), [("4427310", "update"), ("3127680", "update"), ("4183110", "update")])
for app in ("4427310", "3127680", "4183110"):
self.manifest(steam, app)
self.assertEqual(downloads(str(steam)), [])
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
def deck(oslist, runtime, kind="game"):
@@ -545,14 +755,34 @@ class AppInfoTest(unittest.TestCase):
self.assertEqual(changes, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
self.assertEqual(auto, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
def test_the_mapping_sends_native_titles_to_fex_and_keeps_picks(self):
def test_automatic_native_mapping_uses_fex_and_keeps_explicit_tools(self):
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "20": "fex", "21": "steamlinuxruntime_sniper", "22": "GE-Proton11-7"},
["20", "21", "22", "23", "24"], [tool, "GE-Proton11-7"], tool, {},
{"20": fex, "21": fex, "22": fex, "23": fex})
self.assertEqual(changes, {"20": fex, "21": fex, "23": fex, "24": tool})
self.assertEqual(auto, {"20": fex, "21": fex, "23": fex, "24": tool})
self.assertEqual(changes, {"23": fex, "24": tool})
self.assertEqual(auto, {"23": fex, "24": tool})
def test_explicit_linux_runtime_and_fex_selections_survive_default_maintenance(self):
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "20": "steamlinuxruntime_arm64", "21": fex},
["20", "21"], [tool], tool, {}, {"20": None, "21": fex}, ["20", "21"])
self.assertEqual(changes, {})
self.assertEqual(auto, {})
def test_native_arm64_default_stays_unmapped_and_old_auto_proton_is_cleared(self):
tool = self.COMPAT["TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "20": tool}, ["20"], [tool], tool, {"20": tool}, {"20": None}, ["20"])
self.assertEqual(changes, {"20": None})
self.assertEqual(auto, {})
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool}, ["20"], [tool], tool, {}, {"20": None}, ["20"])
self.assertEqual(changes, {})
self.assertEqual(auto, {})
def test_the_tool_files(self):
with tempfile.TemporaryDirectory() as tmp:
+141
View File
@@ -12,6 +12,7 @@ import sys
import tempfile
import textwrap
import unittest
import unittest.mock
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
@@ -56,6 +57,8 @@ FAKE_ADB = textwrap.dedent('''\
print(config.get("dumpsys_display", ""))
elif args[:3] == ["shell", "dumpsys", "power"]:
print(" mWakefulness=Awake")
elif args[:3] == ["shell", "dumpsys", "SurfaceFlinger"] and "-dump" in args:
print(config.get("timestats", ""))
elif args[:2] == ["exec-out", "screencap"]:
sys.stdout.buffer.write(b"\\x89PNG fake")
with open(config["log"], "a") as log:
@@ -78,6 +81,32 @@ DUMPSYS_DISPLAY = textwrap.dedent('''\
''')
def timestats_record(name, frames, histogram, hz):
bins = " ".join(f"{ms}ms={histogram.get(ms, 0)}" for ms in (8, 16, 17, 25, 33, 50))
return (f"displayRefreshRate = {hz} fps\nrenderRate = {hz} fps\nuid = 10479\nlayerName = {name}\n"
f"packageName = \ntotalFrames = {frames}\ndroppedFrames = 0\n"
f"present2present histogram is as below:\n{bins}\nlatch2present histogram is as below:\n8ms={frames}\n")
# A capture where the panel went from 60 to 120 Hz: the game layer is split in two records. The
# activity's own window and an unrelated app draw too, and must not count.
TIMESTATS_SPLIT = "SurfaceFlinger TimeStats:\ntotalFrames = 2000\n" + "".join([
timestats_record("droiddeck_wayland_game#6110", 900, {16: 700, 33: 199}, 60),
timestats_record("droiddeck_wayland_game#6110", 900, {16: 850, 25: 49}, 120),
timestats_record("com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity#6097", 8, {16: 7}, 60),
timestats_record("f291fb6 SurfaceView[com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity]#6101",
30, {33: 29}, 60),
timestats_record("StatusBar#106", 1, {}, 60),
])
# A build that presents the game on the session's SurfaceView instead of a layer of its own.
TIMESTATS_SURFACEVIEW = "SurfaceFlinger TimeStats:\n" + "".join([
timestats_record("a1b2c3 SurfaceView[com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity]#77",
1800, {16: 1796, 33: 3}, 120),
timestats_record("a1b2c3 SurfaceView[com.other.app/com.other.app.Main]#12", 500, {8: 499}, 120),
])
def state(phase="READY", focused=None, focusable=()):
focus = None if focused is None else {"focusedApp": focused, "focusableApps": list(focusable),
"baselayerAppIds": [], "seq": 1, "t": 0}
@@ -122,6 +151,25 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual("INVALID_REQUEST", caught.exception.code)
self.assertFalse(self.calls())
def test_a_variant_package_is_reached_through_its_own_provider_and_activity(self):
with unittest.mock.patch.dict(os.environ, {"DROIDDECK_PACKAGE": "com.antutu.benchmark.full"}):
variant = load("droiddeckctl")
self.assertEqual("content://com.antutu.benchmark.full.agent", variant.AUTHORITY)
with self.assertRaises(variant.ControlError): # the fake adb does not answer `am start`
variant.start_agent_activity(str(self.adb), "fake-1", {"mode": "steam"})
started = [e["args"] for e in self.calls() if e["args"][:3] == ["shell", "am", "start"]]
self.assertIn("com.antutu.benchmark.full/com.droiddeck.launcher.agent.AgentStartActivity", started[0])
def test_a_malformed_package_is_refused_before_adb(self):
with unittest.mock.patch.dict(os.environ, {"DROIDDECK_PACKAGE": "com.example;reboot"}):
variant = load("droiddeckctl")
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code = variant.main(["--adb", str(self.adb), "--serial", "fake-1", "state"])
self.assertEqual(2, code)
self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"])
self.assertFalse(self.calls())
def test_state_passes_through_with_the_serial(self):
self.configure({"state": state()})
code, out = self.run_ctl("state")
@@ -233,6 +281,99 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual(2, code)
self.assertEqual("NO_SUCH_DISPLAY", out["error"]["code"])
def test_pacing_sums_split_records_of_the_game_layer_only(self):
summary = ctl.pacing_summary(TIMESTATS_SPLIT, "com.droiddeck.launcher")
self.assertEqual(["droiddeck_wayland_game"], summary["layers"])
self.assertEqual(1800, summary["frames"])
self.assertEqual([60, 120], summary["refreshRates"])
self.assertEqual({"16": 1550, "25": 49, "33": 199}, summary["presentToPresentMs"])
self.assertEqual(16, summary["cadenceMs"])
self.assertEqual(248, summary["offCadence"])
self.assertEqual(13.8, summary["offCadencePercent"])
def test_pacing_falls_back_to_the_sessions_surfaceview(self):
summary = ctl.pacing_summary(TIMESTATS_SURFACEVIEW, "com.droiddeck.launcher")
self.assertEqual(1, len(summary["layers"]))
self.assertIn("SurfaceView[com.droiddeck.launcher/", summary["layers"][0])
self.assertEqual(1800, summary["frames"])
self.assertEqual(3, summary["offCadence"])
def test_pacing_captures_then_turns_timestats_off(self):
self.configure({}, timestats=TIMESTATS_SURFACEVIEW)
with unittest.mock.patch.object(ctl.time, "sleep"):
code, out = self.run_ctl("pacing", "--seconds", "1")
self.assertEqual(0, code)
self.assertEqual("pacing", out["command"])
self.assertIn("fpsOnScreen", out)
sf = [c["args"][3:] for c in self.calls() if c["args"][:3] == ["shell", "dumpsys", "SurfaceFlinger"]]
self.assertEqual([["--timestats", "-clear", "-enable"], ["--timestats", "-dump"], ["--timestats", "-disable"]], sf)
def test_pacing_without_a_session_on_screen_exits_4(self):
self.configure({}, timestats="SurfaceFlinger TimeStats:\n" + timestats_record("StatusBar#1", 3, {16: 2}, 60))
with unittest.mock.patch.object(ctl.time, "sleep"):
code, out = self.run_ctl("pacing", "--seconds", "1")
self.assertEqual(4, code)
self.assertEqual("NO_FRAMES", out["error"]["code"])
def test_pacing_counts_both_buckets_of_one_cadence_and_only_the_chosen_layers_rates(self):
text = "SurfaceFlinger TimeStats:\n" + "".join([
timestats_record("droiddeck_wayland_game#7", 910, {16: 450, 17: 450, 33: 10}, 60),
timestats_record("StatusBar#106", 4, {8: 3}, 90),
])
summary = ctl.pacing_summary(text, "com.droiddeck.launcher")
self.assertEqual(10, summary["offCadence"])
self.assertEqual([60], summary["refreshRates"])
def test_pacing_skips_a_game_layer_with_no_frames_for_the_surfaceview(self):
text = "SurfaceFlinger TimeStats:\n" + "".join([
timestats_record("droiddeck_wayland_game#7", 0, {}, 120),
timestats_record("a1 SurfaceView[com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity]#8", 600, {16: 598, 33: 1}, 120),
])
summary = ctl.pacing_summary(text, "com.droiddeck.launcher")
self.assertEqual(600, summary["frames"])
self.assertIn("SurfaceView[com.droiddeck.launcher/", summary["layers"][0])
def test_pacing_with_a_layer_that_drew_no_frames_exits_4(self):
self.configure({}, timestats="SurfaceFlinger TimeStats:\n" + timestats_record("droiddeck_wayland_game#7", 0, {}, 120))
with unittest.mock.patch.object(ctl.time, "sleep"):
code, out = self.run_ctl("pacing", "--seconds", "1")
self.assertEqual(4, code)
self.assertEqual("NO_FRAMES", out["error"]["code"])
def test_pacing_turns_timestats_off_when_the_dump_fails(self):
calls = []
def adb(_adb, _serial, *args, timeout=30):
calls.append(args[3:])
if "-dump" in args:
raise ctl.ControlError("timed out", "ADB_FAILED")
return ctl.subprocess.CompletedProcess(args, 0, b"", b"")
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
with self.assertRaises(ctl.ControlError) as caught:
ctl.pacing("adb", "fake-1", 1)
self.assertEqual("PACING_FAILED", caught.exception.code)
self.assertEqual(("--timestats", "-disable"), calls[-1])
def test_pacing_fails_when_timestats_cannot_be_turned_off(self):
def adb(_adb, _serial, *args, timeout=30):
return ctl.subprocess.CompletedProcess(args, 1 if "-disable" in args else 0, b"", b"")
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
with self.assertRaises(ctl.ControlError) as caught:
ctl.pacing("adb", "fake-1", 1)
self.assertEqual("PACING_FAILED", caught.exception.code)
self.assertIn("timestats off", str(caught.exception))
def test_pacing_maps_an_adb_failure_while_enabling_to_pacing_failed(self):
def adb(*_args, **_kwargs):
raise ctl.ControlError("adb vanished", "ADB_FAILED")
with unittest.mock.patch.object(ctl, "run_adb", adb):
with self.assertRaises(ctl.ControlError) as caught:
ctl.pacing("adb", "fake-1", 1)
self.assertEqual("PACING_FAILED", caught.exception.code)
def test_input_requests(self):
self.configure({"input": {"ok": True, "command": "input"}})
self.run_ctl("input", "tap", "0.5", "0.25", "--space", "fraction")
+119
View File
@@ -0,0 +1,119 @@
import importlib.machinery
import importlib.util
import json
import gzip
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import zlib
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
loader = importlib.machinery.SourceFileLoader('ctl_xr', str(TOOLS / 'droiddeckctl'))
spec = importlib.util.spec_from_loader(loader.name, loader)
ctl = importlib.util.module_from_spec(spec)
loader.exec_module(ctl)
class XrCaptureTest(unittest.TestCase):
def test_png_keeps_rgb_rows_and_dimensions(self):
pixels = bytes([255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255])
png = ctl.xr_ppm_to_png(b'P6\n2 2\n255\n' + pixels)
self.assertEqual(png[:8], b'\x89PNG\r\n\x1a\n')
self.assertEqual(struct.unpack('>II', png[16:24]), (2, 2))
position = png.index(b'IDAT')
size = struct.unpack('>I', png[position - 4:position])[0]
self.assertEqual(zlib.decompress(png[position + 4:position + 4 + size]),
b'\0' + pixels[:6] + b'\0' + pixels[6:])
def test_incomplete_or_invalid_images_are_rejected(self):
for data in (b'P6\n2 2\n255\nabc', b'P6\n0 1\n255\n', b'P6\n999999 1\n255\n', b'junk'):
with self.subTest(data=data), self.assertRaises(ctl.ControlError):
ctl.xr_ppm_to_png(data)
def test_linear_source_and_display_eye_have_distinct_png_transfer_tags(self):
image = b'P6\n1 1\n255\n\x37\x37\x37'
self.assertIn(b'gAMA' + struct.pack('>I', 100000), ctl.xr_ppm_to_png(image, linear=True))
self.assertIn(b'sRGB\0', ctl.xr_ppm_to_png(image))
def capture(self, root, failed=False, replaced=False, no_response=False, source=False, truncated=False):
calls = []
token = None
reads = 0
def adb(_adb, _serial, *args, **kwargs):
nonlocal token, reads
calls.append(args)
stdout = b''
if args[0] == 'push':
token = Path(args[1]).read_text()
if args[:2] == ('shell', 'cat'):
reads += 1
stdout = json.dumps({'id': ('old' if reads == 1 or no_response or (replaced and reads > 2) else token),
'ok': not failed, 'validLayer': not failed, 'sourceImage': source}).encode()
if args[0] == 'exec-out':
stdout = gzip.compress(b'P6\n1 1\n255\n\x12\x34\x56')
if truncated:
stdout = stdout[:-5]
return subprocess.CompletedProcess(args, 0, stdout, b'')
with patch.object(ctl, 'run_adb', side_effect=adb), patch.object(ctl.time, 'sleep'):
result = ctl.xr_capture('adb', 'quest', root, 0.01 if no_response else 2)
return result, calls
def test_stale_response_is_ignored_and_matching_pair_is_published(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory) / 'capture'
result, calls = self.capture(root)
self.assertTrue(result['ok'])
self.assertEqual((root / 'left.png').read_bytes(), (root / 'right.png').read_bytes())
self.assertEqual(len([c for c in calls if c[:2] == ('shell', 'cat')]), 3)
self.assertTrue((root / 'capture.json').is_file())
def test_invalid_layer_replaced_capture_and_timeout_publish_no_images(self):
for flags in ({'failed': True}, {'replaced': True}, {'no_response': True}, {'truncated': True}):
with self.subTest(flags=flags), tempfile.TemporaryDirectory() as directory:
root = Path(directory) / 'capture'
with self.assertRaises(ctl.ControlError):
self.capture(root, **flags)
self.assertFalse(root.exists())
def test_source_capture_is_pulled_when_supported_by_the_headset(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory) / 'capture'
result, calls = self.capture(root, source=True)
self.assertEqual(result['source'], str((root / 'source.png').resolve()))
self.assertEqual(len([c for c in calls if c[0] == 'exec-out']), 3)
def test_output_creation_and_write_failures_are_file_errors(self):
for operation in ('mkdir', 'write_bytes'):
with self.subTest(operation=operation), tempfile.TemporaryDirectory() as directory:
with patch.object(Path, operation, side_effect=PermissionError('output denied')):
with self.assertRaises(ctl.ControlError) as caught:
self.capture(Path(directory) / 'capture')
self.assertEqual(caught.exception.code, 'FILE_IO')
self.assertEqual(ctl.exit_code(caught.exception), 6)
def test_stalled_metadata_read_uses_capture_deadline_and_reports_timeout(self):
calls = []
def adb(_adb, _serial, *args, **kwargs):
calls.append((args, kwargs))
if args[:2] == ('shell', 'cat'):
self.assertGreater(kwargs['timeout'], 0)
self.assertLessEqual(kwargs['timeout'], 0.1)
try:
raise subprocess.TimeoutExpired('adb', kwargs['timeout'])
except subprocess.TimeoutExpired as cause:
raise ctl.ControlError('metadata stalled', 'ADB_FAILED') from cause
return subprocess.CompletedProcess(args, 0, b'', b'')
with tempfile.TemporaryDirectory() as directory, patch.object(ctl, 'run_adb', side_effect=adb):
with self.assertRaises(ctl.ControlError) as caught:
ctl.xr_capture('adb', 'quest', Path(directory) / 'capture', 0.1)
self.assertEqual(caught.exception.code, 'TIMEOUT')
self.assertTrue(any(args[:3] == ('shell', 'rm', '-f') for args, _ in calls))
if __name__ == '__main__':
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
import os
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
RING_MAGIC = 0x46494252
DESCRIPTION_MAGIC = 0x46495544
HEADER = 64
EVENT = 24
CAPACITY = 4096
DESCRIPTION = 1824
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
perror("open");
return 1;
}
while (read(fd, events, sizeof(events)) > 0)
;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 1;
ssize_t got = read(fd, events, sizeof(events));
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
events[i].code, events[i].value);
return got > 0 ? 0 : 1;
}
"""
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/joystick.h>
#include <stdio.h>
#include <sys/ioctl.h>
int main(void)
{
char name[128] = "";
struct input_id id = {0};
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0)
return 1;
int joydev = ioctl(fd, JSIOCGNAME(sizeof(name)), name);
printf("JSIOCGNAME %d %s\n", joydev, joydev < 0 && errno == EINVAL ? "EINVAL" : name);
if (ioctl(fd, EVIOCGID, &id) < 0 || ioctl(fd, EVIOCGNAME(sizeof(name)), name) < 0)
return 1;
printf("%04x:%04x %s\n", id.vendor, id.product, name);
return 0;
}
"""
def can_build(bits):
with tempfile.TemporaryDirectory() as tmp:
probe = Path(tmp) / "probe.cpp"
probe.write_text("#include <string>\nint main() { return std::string().size(); }\n")
return subprocess.run(["g++", bits, "-static-libstdc++", "-o", str(Path(tmp) / "probe"), str(probe)],
capture_output=True).returncode == 0
@unittest.skipUnless(sys.platform == "linux" and os.uname().machine == "x86_64" and shutil.which("g++")
and shutil.which("gcc"), "needs gcc and g++ on an x86-64 Linux host")
class FakeinputRingTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
def ring(self):
hooks = self.tmp / "hooks"
hooks.mkdir()
(hooks / "event16").touch()
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 5, 0, 0)
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
path = hooks / ".uinput-event16"
path.write_bytes(bytes(ring))
return hooks, path
def build(self, bits, program, name):
if not can_build(bits):
self.skipTest("no %s C++ toolchain" % bits)
library = self.tmp / ("libfakeinput%s.so" % bits)
subprocess.run(["g++", bits, "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17",
"-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(library),
str(SOURCE), "-ldl"], check=True, capture_output=True)
binary = self.tmp / (name + bits)
(self.tmp / (name + ".c")).write_text(program)
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
return library, binary
def read_through(self, bits):
library, reader = self.build(bits, READER, "reader")
hooks, path = self.ring()
env = dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks))
process = subprocess.Popen([str(reader)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
self.addCleanup(process.kill)
self.assertEqual(process.stdout.readline(), "ready\n")
with open(path, "r+b") as ring:
for i, (kind, code, value) in enumerate(((1, 304, 1), (3, 1, -32768), (0, 0, 0))):
ring.seek(HEADER + (5 + i) * EVENT)
ring.write(struct.pack("<qqHHi", 1700000000 + i, 250000, kind, code, value))
ring.seek(16)
ring.write(struct.pack("<Q", 8))
output, _ = process.communicate("g", timeout=10)
self.assertEqual(process.returncode, 0)
return output
def test_a_32_bit_guest_reads_the_64_bit_ring(self):
self.assertEqual(self.read_through("-m32"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_a_64_bit_guest_reads_the_same_ring(self):
self.assertEqual(self.read_through("-m64"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_an_event_node_rejects_joydev_requests_so_sdl_reads_its_id(self):
library, probe = self.build("-m64", PROBE, "probe")
hooks, _ = self.ring()
run = subprocess.run([str(probe)], capture_output=True, text=True, timeout=10,
env=dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks)))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "JSIOCGNAME -1 EINVAL\n28de:11ff Microsoft X-Box 360 pad 0\n")
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
import hashlib
import os
from pathlib import Path
import subprocess
import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("fex_install() {")
END = SOURCE.index("\n}\n", START) + 3
FEX_INSTALL = SOURCE[START:END]
HARNESS = textwrap.dedent("""\
set -eu
# The archive comes from PKG; the installed tree loads when INSTALLED_LOADS=1, any staged tree always does.
curl() { local out=; while [ $# -gt 0 ]; do [ "$1" = -o ] && out=$2; shift; done; cp "$PKG" "$out"; }
fex_loads() { case $1 in "$ROOT"/) [ "${INSTALLED_LOADS:-1}" = 1 ] ;; *) true ;; esac; }
""")
class FexInstallTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
base = Path(self.temp.name)
self.root = base / "root"
old = self.root / "usr/local"
(old / "bin").mkdir(parents=True)
(old / "bin/FEX").write_text("old FEX\n")
(old / "share/fex-emu").mkdir(parents=True)
(old / "share/fex-emu/.droiddeck-tag").write_text("fex-2610-r5\n")
new = base / "pkg/usr/local"
(new / "bin").mkdir(parents=True)
(new / "bin/FEX").write_text("new FEX\n")
(new / "lib").mkdir()
(new / "lib/libxxhash.so.0").write_text("lib\n")
self.pkg = base / "fex.tzst"
subprocess.run(f"tar -C '{base / 'pkg'}' -c . | zstd -q -o '{self.pkg}'", shell=True, check=True)
self.sha = hashlib.sha256(self.pkg.read_bytes()).hexdigest()
def install(self, installed_loads, sha=None):
body = FEX_INSTALL.replace("local tag=$1 sha=$2 urls=$3 dst=/ ", "local tag=$1 sha=$2 urls=$3 dst=$ROOT/ ")
self.assertNotEqual(body, FEX_INSTALL)
script = HARNESS + body + 'if fex_install fex-2610-r6 "$SHA" u; then echo OK; else echo FAILED; fi\n'
env = dict(os.environ, ROOT=str(self.root), PKG=str(self.pkg), SHA=sha or self.sha,
INSTALLED_LOADS="1" if installed_loads else "0")
out = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=30)
self.assertEqual(0, out.returncode, out.stderr)
return out.stdout.strip().splitlines()[-1], out.stderr
def tag(self):
return (self.root / "usr/local/share/fex-emu/.droiddeck-tag").read_text().strip()
def test_a_build_that_loads_once_installed_replaces_the_old_one(self):
result, _ = self.install(installed_loads=True)
self.assertEqual("OK", result)
self.assertEqual("new FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertTrue((self.root / "usr/local/lib/libxxhash.so.0").is_file())
self.assertEqual("fex-2610-r6", self.tag())
def test_an_installed_copy_that_does_not_load_puts_the_old_files_back(self):
result, err = self.install(installed_loads=False)
self.assertEqual("FAILED", result)
self.assertIn("putting the previous files back", err)
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertFalse((self.root / "usr/local/lib/libxxhash.so.0").exists())
self.assertEqual("fex-2610-r5", self.tag())
def test_a_tag_that_cannot_be_written_puts_the_old_files_back(self):
share = self.root / "usr/local/share/fex-emu"
(share / ".droiddeck-tag").unlink()
share.rmdir()
share.write_text("not a folder\n")
result, err = self.install(installed_loads=True)
self.assertEqual("FAILED", result)
self.assertIn("putting the previous files back", err)
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertFalse((self.root / "usr/local/lib/libxxhash.so.0").exists())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
self.assertIn("no source gave the archive", err)
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertEqual("fex-2610-r5", self.tag())
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
import os
from pathlib import Path
import subprocess
import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("x64_fex() {")
END = SOURCE.index("\n}\n", START) + 3
X64_FEX = SOURCE[START:END]
HARNESS = textwrap.dedent("""\
set -eu
FEX_TAG=fex-2610-r5 FEX_SHA256=builtin FEX_URL=builtin-url
step() { echo "STEP $*"; }
# Installed FEX loads when LOADS=1; a build installs when its tag is in INSTALLABLE.
fex_loads() { [ "${LOADS:-0}" = 1 ]; }
fex_install() {
echo "INSTALL $1 $2 $3"
case " ${INSTALLABLE:-} " in *" $1 "*) echo "$1" > "$ROOT/tag"; : > "$ROOT/FEX"; chmod +x "$ROOT/FEX"; return 0 ;; esac
return 1
}
""")
class FexSelectTest(unittest.TestCase):
def run_select(self, installed=None, loads=False, catalog=None, installable=()):
with tempfile.TemporaryDirectory() as root:
if installed:
Path(root, "tag").write_text(installed + "\n")
fex = Path(root, "FEX")
fex.write_text("")
fex.chmod(0o755)
body = (X64_FEX.replace("/usr/local/share/fex-emu/.droiddeck-tag", "$ROOT/tag")
.replace("/usr/local/bin/FEX", "$ROOT/FEX"))
script = HARNESS + body + 'if x64_fex; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n'
env = dict(os.environ, ROOT=root, LOADS="1" if loads else "0", INSTALLABLE=" ".join(installable))
env.pop("BL_FEX_TAG", None)
if catalog:
env.update(BL_FEX_TAG=catalog, BL_FEX_SHA256="catsha", BL_FEX_URLS="a b")
out = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10)
self.assertEqual(0, out.returncode, out.stderr)
lines = out.stdout.splitlines()
return [l for l in lines if l.startswith("INSTALL")], lines[-1]
def test_the_catalog_build_already_installed_is_used(self):
installs, now = self.run_select(installed="fex-2610-r6", loads=True, catalog="fex-2610-r6")
self.assertEqual([], installs)
self.assertEqual("NOW fex-2610-r6|catalog", now)
def test_a_newer_catalog_build_is_installed(self):
installs, now = self.run_select(installed="fex-2610-r5", loads=True, catalog="fex-2610-r6", installable=["fex-2610-r6"])
self.assertEqual(["INSTALL fex-2610-r6 catsha a b"], installs)
self.assertEqual("NOW fex-2610-r6|catalog", now)
def test_a_catalog_build_that_does_not_install_keeps_the_working_one(self):
installs, now = self.run_select(installed="fex-2610-r5", loads=True, catalog="fex-2610-r6")
self.assertEqual(["INSTALL fex-2610-r6 catsha a b"], installs)
self.assertEqual("NOW fex-2610-r5|kept; fex-2610-r6 did not install", now)
def test_without_a_catalog_the_built_in_build_replaces_an_older_one(self):
installs, now = self.run_select(installed="fex-2610-r4", loads=True, installable=["fex-2610-r5"])
self.assertEqual(["INSTALL fex-2610-r5 builtin builtin-url"], installs)
self.assertEqual("NOW fex-2610-r5|built-in", now)
def test_an_installed_build_that_does_not_load_is_replaced(self):
installs, now = self.run_select(installed="fex-2610-r6", loads=False, catalog="fex-2610-r6", installable=["fex-2610-r6"])
self.assertEqual(["INSTALL fex-2610-r6 catsha a b"], installs)
self.assertEqual("NOW fex-2610-r6|catalog", now)
def test_a_first_install_falls_back_to_the_built_in_build(self):
installs, now = self.run_select(catalog="fex-2610-r6", installable=["fex-2610-r5"])
self.assertEqual(["INSTALL fex-2610-r6 catsha a b", "INSTALL fex-2610-r5 builtin builtin-url"], installs)
self.assertEqual("NOW fex-2610-r5|built-in", now)
def test_nothing_usable_fails(self):
installs, now = self.run_select(catalog="fex-2610-r6")
self.assertEqual(2, len(installs))
self.assertEqual("FAILED", now)
if __name__ == "__main__":
unittest.main()
+298 -25
View File
@@ -26,7 +26,44 @@ def config_text(entries):
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class ReadConfigMappingTest(unittest.TestCase):
def test_missing_parent_or_unbalanced_vdf_is_not_treated_as_absent_choices(self):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.vdf"
config.write_text('"InstallConfigStore" { "Software" { "Other" {} } }')
self.assertIsNone(COMPAT["read_config_mapping"](str(config)))
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" {} }')
self.assertIsNone(COMPAT["read_config_mapping"](str(config)))
def test_valid_steam_parent_without_compat_mapping_has_no_per_app_choices(self):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.vdf"
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" {} } } }')
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {})
class GameEnvironmentTest(unittest.TestCase):
def test_directaudio_capture_follows_the_session_microphone_setting(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
probe = home / "probe"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('BANNER_AUDIO_DIRECT_MIC', 'unset'))\n")
probe.chmod(0o755)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
for enabled, override, expected in (("1", None, "1"), ("0", "1", "0"), ("1", "0", "0")):
with self.subTest(enabled=enabled, override=override):
profile = {} if override is None else {
"BANNER_AUDIO_DIRECT_MIC": override, "BL_MIC_ENABLED": override,
}
config.write_text(json.dumps({"version": 1, "games": {"42": profile}}))
env = dict(os.environ, HOME=tmp, BL_MIC_ENABLED=enabled,
BANNER_AUDIO_DIRECT_MIC="1", STEAM_COMPAT_DATA_PATH="/compatdata/42")
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"),
str(probe), "waitforexitandrun"],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip(), expected)
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -53,6 +90,12 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["REMOVE"], "inherited")
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
chosen = MODULE["apply_config"](env, MODULE["sync_config"](config, "42"), "42")
self.assertEqual(chosen, {"BL_SYNC": "0", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "OTHER": "kept"})
def test_component_profiles_override_general_and_restore_it_for_the_next_game(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -136,6 +179,25 @@ class GameEnvironmentTest(unittest.TestCase):
(other / "Other.exe").touch()
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
city.mkdir(parents=True)
for name in ("BatmanAC.exe", "BmLauncher.exe"):
(city / name).touch()
for exe in ("BatmanAC.exe", "BmLauncher.exe"):
env, extra, notes = MODULE["engine_fixes"](str(city / exe), [])
self.assertEqual((env, extra), ({"FEX_X87REDUCEDPRECISION": "0"}, []))
config = {"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"}}
self.assertEqual(MODULE["apply_config"]({}, config, "200260", env)["FEX_X87REDUCEDPRECISION"], "0")
config["games"] = {"200260": {"FEX_X87REDUCEDPRECISION": "1"}}
self.assertEqual(MODULE["apply_config"]({}, config, "200260", env)["FEX_X87REDUCEDPRECISION"], "1")
asylum = Path(tmp) / "Batman Arkham Asylum GOTY/Binaries"
asylum.mkdir(parents=True)
for name in ("ShippingPC-BmGame.exe", "BmLauncher.exe"):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_a_new_fix_only_needs_registering(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "Game.exe").touch()
@@ -415,6 +477,218 @@ class ProtonDefaultTest(unittest.TestCase):
self.assertEqual(changes, {"0": "GE-Proton11-7", "10": "GE-Proton11-7", "11": "GE-Proton11-7", "14": "GE-Proton11-7"})
self.assertEqual(auto, {"10": "GE-Proton11-7", "11": "GE-Proton11-7", "14": "GE-Proton11-7"})
def test_windows_only_titles_still_follow_the_default(self):
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL}, ["42"], self.NAMES, self.TOOL, {})
self.assertEqual(changes, {"42": self.TOOL})
self.assertEqual(auto, {"42": self.TOOL})
def test_native_arm64_default_clears_only_our_auto_mapping(self):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.vdf"
config.write_text(config_text([("0", self.TOOL), ("42", self.TOOL)]))
(Path(tmp) / "state.json").write_text(json.dumps({
"default": self.TOOL,
"auto": {"42": self.TOOL},
}))
globals_ = COMPAT["register_default"].__globals__
original_native_targets = globals_["native_targets"]
globals_["native_targets"] = lambda _root, _apps: {"42": None}
try:
COMPAT["register_default"](
str(config), ["42"], catalog=self.CATALOG, directory=tmp)
first = config.read_bytes()
self.assertEqual(mapping_of(first.decode()), {"0": self.TOOL})
self.assertEqual(COMPAT["tokenize"](first.decode()),
COMPAT["tokenize"](config_text([("0", self.TOOL)])))
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
COMPAT["register_default"](
str(config), ["42"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(config.read_bytes(), first)
finally:
globals_["native_targets"] = original_native_targets
def test_saved_native_choice_survives_valve_pick_without_appinfo(self):
app = "452280"
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
steam = root / "Steam"
config = steam / "config/config.vdf"
config.parent.mkdir(parents=True)
(steam / "steamapps").mkdir()
(steam / "steamapps" / ("appmanifest_%s.acf" % app)).write_text("")
config.write_text(config_text([("0", self.TOOL)]))
(root / "state.json").write_text(json.dumps({
"default": self.TOOL,
"auto": {},
"native_choices": [app],
}))
globals_ = COMPAT["register_default"].__globals__
original_native_targets = globals_["native_targets"]
globals_["native_targets"] = lambda _root, _apps: {}
try:
COMPAT["register_default"](
str(config), [], catalog=self.CATALOG, directory=tmp, picks=[app])
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL})
state = json.loads((root / "state.json").read_text())
self.assertEqual(state["auto"], {})
self.assertEqual(state["native_choices"], [app])
finally:
globals_["native_targets"] = original_native_targets
def test_shortcuts_scanner_keeps_native_choice_for_unrelated_app_list(self):
app, added_shortcut = "452280", "3537741571"
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
steam = root / "Steam"
config = steam / "config/config.vdf"
config.parent.mkdir(parents=True)
(steam / "steamapps").mkdir()
(steam / "steamapps" / ("appmanifest_%s.acf" % app)).write_text("")
config.write_text(config_text([("0", self.TOOL)]))
(root / "state.json").write_text(json.dumps({
"default": self.TOOL,
"auto": {},
"native_choices": [app],
}))
globals_ = COMPAT["register_default"].__globals__
original_native_targets = globals_["native_targets"]
globals_["native_targets"] = lambda _root, wanted: {
app: COMPAT["NATIVE_CHOICE"]
} if app in wanted else {}
try:
COMPAT["register_default"](
str(config), [app], catalog=self.CATALOG, directory=tmp)
self.assertEqual(json.loads((root / "state.json").read_text())["native_choices"], [app])
COMPAT["register_default"](
str(config), [added_shortcut], catalog=self.CATALOG, directory=tmp)
state = json.loads((root / "state.json").read_text())
self.assertEqual(state["native_choices"], [app])
self.assertEqual(state["auto"], {added_shortcut: self.TOOL})
self.assertEqual(mapping_of(config.read_text()), {
"0": self.TOOL,
added_shortcut: self.TOOL,
})
finally:
globals_["native_targets"] = original_native_targets
def test_factorio_preserves_an_observed_native_choice_despite_ambiguous_metadata(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp) / "Steam"
config = steam / "config/config.vdf"
config.parent.mkdir(parents=True)
config.write_text(config_text([("0", self.TOOL)]))
state = {"default": self.TOOL, "auto": {}}
(Path(tmp) / "state.json").write_text(json.dumps(state))
globals_ = COMPAT["native_targets"].__globals__
original_platforms = globals_["appinfo_platforms"]
globals_["appinfo_platforms"] = lambda _path, wanted: {
"427520": ({"linux", "macos", "windows"}, "", "game")
} if "427520" in wanted else {}
try:
native = COMPAT["native_targets"](str(steam), ["427520"])
self.assertIs(native["427520"], COMPAT["NATIVE_CHOICE"])
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL}, ["427520"], self.NAMES, self.TOOL, {}, native)
self.assertEqual(changes, {"427520": self.TOOL})
self.assertEqual(auto, {"427520": self.TOOL})
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": self.TOOL})
state["auto"] = {"427520": self.TOOL}
(Path(tmp) / "state.json").write_text(json.dumps(state))
config.write_text(config_text([("0", self.TOOL)]))
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
first = config.read_bytes()
self.assertEqual(mapping_of(first.decode()), {"0": self.TOOL})
self.assertEqual(COMPAT["tokenize"](first.decode()),
COMPAT["tokenize"](config_text([("0", self.TOOL)])))
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native_choices"], ["427520"])
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(config.read_bytes(), first)
config.write_text(config_text([("0", self.TOOL), ("427520", "")]))
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
native_choice = config.read_bytes()
self.assertEqual(mapping_of(native_choice.decode()), {"0": self.TOOL, "427520": ""})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native_choices"], ["427520"])
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(config.read_bytes(), native_choice)
for choice in (COMPAT["FEX_TOOL"], COMPAT["TOOL_11"], "GE-Proton11-7"):
config.write_text(config_text([("0", self.TOOL), ("427520", choice)]))
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": choice})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native_choices"], [])
state = json.loads((Path(tmp) / "state.json").read_text())
state["native_choices"] = ["427520"]
state["auto"] = {}
(Path(tmp) / "state.json").write_text(json.dumps(state))
config.write_text(config_text([("0", self.TOOL), ("427520", "proton_experimental")]))
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": self.TOOL})
saved = json.loads((Path(tmp) / "state.json").read_text())
self.assertEqual(saved["native_choices"], [])
self.assertEqual(saved["auto"], {"427520": self.TOOL})
finally:
globals_["appinfo_platforms"] = original_platforms
def test_native_arm64_preserves_a_proton_mapping_without_managed_state(self):
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL, "42": self.TOOL}, ["42"], self.NAMES, self.TOOL,
{"42": self.TOOL}, {"42": None}, managed=())
self.assertEqual(changes, {})
self.assertEqual(auto, {})
def test_native_arm64_keeps_a_chosen_valve_proton_through_its_wrapper(self):
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL, "42": "proton_experimental"}, ["42"], self.NAMES,
self.TOOL, {}, {"42": None})
self.assertEqual(changes, {"42": self.TOOL})
self.assertEqual(auto, {})
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL, "42": self.TOOL}, ["42"], self.NAMES,
self.TOOL, {}, {"42": None})
self.assertEqual(changes, {})
self.assertEqual(auto, {})
def test_native_arm64_keeps_explicit_runtime_fex_and_proton_profiles(self):
fex = COMPAT["FEX_TOOL"]
current = {
"0": self.TOOL,
"42": COMPAT["TOOL_11"],
"43": "GE-Proton11-7",
"44": "steamlinuxruntime_arm64",
"45": fex,
"46": "",
}
changes, auto = COMPAT["plan_mapping"](
current, ["42", "43", "44", "45", "46"], self.NAMES, self.TOOL, {},
{app: None for app in ("42", "43", "44", "45", "46")},
overrides={"46": "GE-Proton11-7"},
)
self.assertEqual(changes, {"46": "GE-Proton11-7"})
self.assertEqual(auto, {})
def test_titles_following_the_default_move_with_it_and_picks_stay(self):
current = {"0": self.TOOL, "10": self.TOOL, "11": "GE-Proton11-7", "12": self.TOOL}
auto = {"10": self.TOOL, "11": self.TOOL, "12": self.TOOL}
@@ -575,12 +849,12 @@ class DirectAudioPrefixTest(unittest.TestCase):
(self.windows / folder).mkdir(parents=True)
self.reg = self.compat / "pfx/user.reg"
def run_setup(self):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
def run_setup(self, verb="waitforexitandrun"):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat))
env.pop("WINEDLLPATH", None)
env.pop("WINE_AUDIO_DRIVER", None)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool)], env=env, capture_output=True, text=True, check=True)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb], env=env, capture_output=True, text=True, check=True)
def audio_values(self):
found, current = [], None
@@ -595,6 +869,27 @@ class DirectAudioPrefixTest(unittest.TestCase):
path = self.windows / folder / "winedirectaudio.drv"
return os.readlink(path) if path.is_symlink() else None
def test_non_launch_verbs_preserve_audio_configuration(self):
for verb in ("getcompatpath", "getnativepath", "destroyprefix"):
with self.subTest(verb=verb):
self.reg.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Wine\\\\Drivers] 1\n"Audio"="pulse"\n')
before = self.reg.read_bytes()
result = self.run_setup(verb)
self.assertEqual(self.reg.read_bytes(), before)
self.assertIsNone(self.link("system32"))
self.assertIsNone(self.link("syswow64"))
self.assertIn("WINEDLLPATH=\n", result.stdout)
self.assertIn("WINE_AUDIO_DRIVER=\n", result.stdout)
def test_other_windows_launch_verbs_still_set_up_audio(self):
self.reg.write_text("WINE REGISTRY Version 2\n")
for verb in ("run", "runinprefix"):
with self.subTest(verb=verb):
result = self.run_setup(verb)
self.assertIn("DirectAudio ready", result.stderr)
self.assertIn("WINE_AUDIO_DRIVER=directaudio,pulse\n", result.stdout)
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
def test_the_driver_is_placed_and_selected_the_way_wine_reads_it(self):
self.reg.write_text("WINE REGISTRY Version 2\n;; All keys relative to \\\\User\\\\S-1-5-21-0-0-0-1000\n\n#arch=win64\n")
result = self.run_setup()
@@ -679,28 +974,6 @@ if __name__ == "__main__":
unittest.main()
class StartWithoutSteamTest(unittest.TestCase):
def test_start_without_steam_uses_umu_or_runinprefix_and_only_when_asked(self):
with tempfile.TemporaryDirectory() as tmp:
ge = Path(tmp) / "ge/proton"
ge.parent.mkdir()
ge.write_text('if "UMU_ID" in os.environ:\n argv = [wine, "c:\\\\windows\\\\system32\\\\umu.exe"]\n')
valve = Path(tmp) / "valve/proton"
valve.parent.mkdir()
valve.write_text('argv = [wine, "c:\\\\windows\\\\system32\\\\steam.exe"]\n')
start = MODULE["start_without_steam"]
game = [str(ge), "waitforexitandrun", "/games/Game.exe", "-windowed"]
self.assertEqual(start(game, {}, "3384071994"), (game, {}))
on = {"DROIDDECK_NO_STEAM": "1"}
self.assertEqual(start(game, on, "3384071994"), (game, dict(on, UMU_ID="0")))
self.assertEqual(start(game, on, "570940")[1]["UMU_ID"], "570940")
self.assertEqual(start(game, dict(on, UMU_ID="umu-1"), "570940")[1]["UMU_ID"], "umu-1")
plain = [str(valve)] + game[1:]
self.assertEqual(start(plain, on, "570940"), ([str(valve), "runinprefix", "/games/Game.exe", "-windowed"], on))
for other in ([str(ge), "run", "/x.exe"], [str(ge), "waitforexitandrun"], [str(valve), "getcompatpath", "/x"]):
self.assertEqual(start(other, on, "570940"), (other, on))
class ForceSsbsTest(unittest.TestCase):
def test_libssbs_is_preloaded_only_when_asked_and_only_into_arm64_proton(self):
with tempfile.TemporaryDirectory() as tmp:
+71
View File
@@ -0,0 +1,71 @@
import collections
from pathlib import Path
import re
import unicodedata
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[2]
RES = ROOT / "app/src/main/res"
FORMAT = re.compile(r"%(?:\d+\$)?[-#+ 0,(]*\d*(?:\.\d+)?[a-zA-Z%]")
def strings(path):
return {
element.attrib["name"]: "".join(element.itertext())
for element in ET.parse(path).getroot()
if element.tag == "string" and element.get("translatable") != "false"
}
class GlassesLocalizationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.english = strings(RES / "values/strings.xml")
cls.required = {
key: value for key, value in cls.english.items()
if key.startswith(("glasses_", "spatial_", "tracking_recovery_", "setup_glasses_", "phone_camera_tracking_"))
or key in ("setup_tab_glasses", "hand_camera_prompt_title", "hand_camera_prompt_body", "hand_camera_setting_hint")
}
language_source = (ROOT / "app/src/main/java/com/droiddeck/launcher/core/AppLanguage.kt").read_text(encoding="utf-8")
tags = re.findall(r'"([a-zA-Z0-9-]+)"', re.search(r"val supported:.*?listOf\((.*?)\)", language_source, re.S).group(1))
special = {"id": "in", "es-419": "b+es+419", "pt-BR": "pt"}
cls.locales = {}
for tag in tags:
if tag == "en":
continue
qualifier = special.get(tag, tag.replace("-", "-r"))
cls.locales[tag] = strings(RES / f"values-{qualifier}/strings.xml")
def test_every_supported_language_has_nonempty_glasses_and_calibration_text(self):
for locale, translated in self.locales.items():
for key in self.required:
with self.subTest(locale=locale, key=key):
self.assertTrue(translated.get(key, "").strip(), "Missing translation would fall back to English")
def test_translations_preserve_format_arguments_and_explicit_line_breaks(self):
for locale, translated in self.locales.items():
for key, source in self.required.items():
with self.subTest(locale=locale, key=key):
target = translated.get(key, "")
self.assertEqual(collections.Counter(FORMAT.findall(source)), collections.Counter(FORMAT.findall(target)))
self.assertEqual(source.count(r"\n"), target.count(r"\n"))
def test_printed_board_and_distance_guidance_preserve_measurements(self):
keys = ("spatial_print_hint", "spatial_print_scale", "spatial_print_check", "spatial_distance_12in",
"spatial_distance_30cm", "spatial_distance_20in", "spatial_distance_50cm",
"spatial_distance_hint", "spatial_distance_corners")
def numbers(value):
value = "".join(str(unicodedata.decimal(char)) if char.isdecimal() else char for char in value)
return collections.Counter(number.replace(",", ".") for number in re.findall(r"\d+(?:[.,]\d+)?", value))
for locale, translated in self.locales.items():
for key in keys:
with self.subTest(locale=locale, key=key):
self.assertEqual(numbers(self.english[key]), numbers(translated.get(key, "")))
if __name__ == "__main__":
unittest.main()
+77 -1
View File
@@ -22,6 +22,9 @@ IFACE = NAME + ".Manager"
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class SleepHandshakeTest(unittest.TestCase):
ARGS = []
AGENT_EXIT = None
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.dir = Path(self.directory.name)
@@ -35,7 +38,16 @@ class SleepHandshakeTest(unittest.TestCase):
lambda bus, sender, path, interface, name, body: self.signals.append(body.unpack()[0]))
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir),
DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT)], env=env,
script = SCRIPT
if self.AGENT_EXIT is not None:
bin_dir = self.dir / "bin"
bin_dir.mkdir()
script = bin_dir / SCRIPT.name
script.write_text(SCRIPT.read_text())
agent = bin_dir / "droiddeck-agent"
agent.write_text("#!/bin/sh\necho \"$@\" >> \"%s\"\nexit %d\n" % (self.dir / "agent-calls", self.AGENT_EXIT))
agent.chmod(0o755)
self.process = subprocess.Popen(["/usr/bin/python3", str(script), *self.ARGS], env=env,
stdout=subprocess.DEVNULL)
self.wait_for(lambda: (self.dir / "steam-sleep-ready").exists())
@@ -218,5 +230,69 @@ class SleepHandshakeTest(unittest.TestCase):
self.call(IFACE, "PowerOff", GLib.Variant("(b)", (True,)))
class FakeAgentCase(unittest.TestCase):
ARGS = []
setUp = SleepHandshakeTest.setUp
tearDown = SleepHandshakeTest.tearDown
wait_for = SleepHandshakeTest.wait_for
call = SleepHandshakeTest.call
suspend = SleepHandshakeTest.suspend
state = SleepHandshakeTest.state
request_wake = SleepHandshakeTest.request_wake
def asked(self):
path = self.dir / "agent-calls"
return path.read_text().split() if path.exists() else []
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class AwakeSteamTest(FakeAgentCase):
AGENT_EXIT = 5
def test_resuming_an_awake_steam_sends_no_sleep_wake_pair(self):
self.request_wake()
self.wait_for(lambda: self.asked())
deadline = time.monotonic() + 1.5
while time.monotonic() < deadline:
self.wait_for(lambda: True)
time.sleep(0.05)
self.assertEqual([], self.signals)
self.assertEqual(["--steam-asleep"], self.asked())
def test_a_pending_sleep_still_wakes_without_asking_steam(self):
token = self.suspend()
self.state(token, "paused")
self.request_wake()
self.wait_for(lambda: self.signals == [True, False])
self.assertEqual([], self.asked())
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class AsleepSteamTest(FakeAgentCase):
AGENT_EXIT = 0
def test_resuming_a_sleeping_steam_replays_the_pair(self):
self.request_wake()
self.wait_for(lambda: self.signals == [True, False])
self.assertEqual(["--steam-asleep"], self.asked())
class WithNetworkManagerTest(SleepHandshakeTest):
ARGS = ["--with-netmanager"]
def owner(self, name):
return self.bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
"GetConnectionUnixProcessID", GLib.Variant("(s)", (name,)), None,
Gio.DBusCallFlags.NONE, 2000, None).unpack()[0]
def test_one_process_owns_login1_and_networkmanager(self):
self.wait_for(lambda: self.bus.call_sync(
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner",
GLib.Variant("(s)", ("org.freedesktop.NetworkManager",)), None,
Gio.DBusCallFlags.NONE, 2000, None).unpack()[0])
self.assertEqual(self.owner("org.freedesktop.NetworkManager"), self.process.pid)
self.assertEqual(self.owner(NAME), self.process.pid)
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -0,0 +1,23 @@
#include "../../app/src/main/cpp/viture/mjpeg_payload.h"
#include <cassert>
#include <cstdio>
#include <cstring>
int main() {
const uint8_t jpeg[] = {0xff,0xd8,0xff,0xc0,0,4,1,2,0xff,0xd9};
uint8_t frame[32]{};
std::memcpy(frame,jpeg,sizeof(jpeg));
for (std::size_t padding=0; padding<=7; ++padding)
assert(mjpeg_payload_size(frame,sizeof(jpeg)+padding) == sizeof(jpeg));
assert(mjpeg_payload_size(frame,sizeof(jpeg)+8) == 0);
for (std::size_t size=0; size<sizeof(jpeg); ++size)
assert(mjpeg_payload_size(frame,size) == 0);
frame[sizeof(jpeg)] = 0x42;
assert(mjpeg_payload_size(frame,sizeof(jpeg)+1) == 0);
frame[sizeof(jpeg)] = 0;
frame[0] = 0;
assert(mjpeg_payload_size(frame,sizeof(jpeg)) == 0);
assert(mjpeg_payload_size(nullptr,10) == 0);
assert(mjpeg_payload_size(jpeg,4*1024*1024+1) == 0);
std::puts("PASS: JPEG boundaries, 0-7 padding bytes, truncation, garbage, and bounds");
}
+192
View File
@@ -0,0 +1,192 @@
import errno
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
# Opens each "<dirfd>\t<flags>\t<path>" case with openat2(RESOLVE_IN_ROOT) as FEX does: first through the kernel's own
# openat2 on argv[1] when it has one, then, with openat2 failing ENOSYS as under proot, through the preload on argv[2].
PROGRAM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef SYS_openat2
#define SYS_openat2 437
#endif
struct how { uint64_t flags, mode, resolve; };
static char cases[256][512];
static int count;
static void run(long (*call)(long, ...), const char *tree) {
int root = open(tree, O_PATH | O_DIRECTORY | O_CLOEXEC), outer = open("/", O_PATH | O_DIRECTORY | O_CLOEXEC);
for (int i = 0; i < count; i++) {
char *flags = strchr(cases[i], '\t') + 1, *path = strchr(flags, '\t') + 1;
struct how h = {strtoull(flags, NULL, 0), 0, 0x10};
if (h.flags & O_CREAT) h.mode = 0644;
long fd = call(SYS_openat2, (long)(cases[i][0] == 'o' ? outer : root), (long)path, (long)&h, (long)sizeof(h));
struct stat st;
if (fd < 0) {
printf("ERR %d\n", errno);
} else {
fstat((int)fd, &st);
printf("OK %llu %llu\n", (unsigned long long)st.st_dev, (unsigned long long)st.st_ino);
close((int)fd);
}
}
}
int main(int argc, char **argv) {
if (argc < 3) return 2;
while (count < 256 && fgets(cases[count], sizeof(cases[count]), stdin)) {
cases[count][strcspn(cases[count], "\n")] = 0;
count++;
}
long (*kernel)(long, ...) = (long (*)(long, ...))dlsym(dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD), "syscall");
struct how probe = {O_RDONLY, 0, 0x10};
long fd = kernel(SYS_openat2, (long)AT_FDCWD, (long)".", (long)&probe, (long)sizeof(probe));
if (fd >= 0) {
close((int)fd);
printf("kernel\n");
run(kernel, argv[1]);
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_openat2, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
perror("seccomp");
return 3;
}
}
printf("preload\n");
run(syscall, argv[2]);
return 0;
}
"""
O_PATH = getattr(os, "O_PATH", 0o10000000)
# (dirfd: r = the tree, o = "/"), flags, path, expected: a path in the tree, an errno name, or "proc" for a file outside it.
CASES = [
("r", os.O_RDONLY, "etc/alternatives/hn", "etc/hostname"),
("r", os.O_RDONLY, "/lib64/x86_64-linux-gnu/libfoo.so.1", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
("r", os.O_RDONLY, "lib/x86_64-linux-gnu/libfoo.so.1", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
("r", os.O_RDONLY, "etc/escape", "etc/hostname"),
("r", os.O_RDONLY, "dirlink/../etc/hostname", "etc/hostname"),
("r", os.O_RDONLY, "rootlink/rootlink//etc/./hostname", "etc/hostname"),
("r", os.O_RDONLY, "../../etc/hostname", "etc/hostname"),
("r", os.O_RDONLY | os.O_DIRECTORY, "/", "."),
("r", os.O_RDONLY | os.O_DIRECTORY, "usr/../..", "."),
("r", os.O_RDONLY, "chain/l2", "chain/end"),
("r", os.O_RDONLY, "chain/l1", "ELOOP"),
("r", os.O_RDONLY, "loop/a/x", "ELOOP"),
("r", os.O_RDONLY | os.O_NOFOLLOW, "etc/alternatives/hn", "ELOOP"),
("r", O_PATH | os.O_NOFOLLOW, "etc/alternatives/hn", "etc/alternatives/hn"),
("r", os.O_RDONLY | os.O_NOFOLLOW, "lib/x86_64-linux-gnu/libfoo.so.1.2", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
("r", os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY, "dirlink/", "usr"),
("r", os.O_RDONLY, "file/", "ENOTDIR"),
("r", os.O_RDONLY, "file/../etc/hostname", "ENOTDIR"),
("r", os.O_RDONLY, "nonexist/../etc/hostname", "ENOENT"),
("r", os.O_RDWR | os.O_CREAT | os.O_EXCL, "dangling", "EEXIST"),
("r", os.O_RDWR | os.O_CREAT, "dangling", "usr/newfile"),
("r", os.O_RDWR | os.O_CREAT, "missing/newfile", "ENOENT"),
("r", os.O_RDWR | os.O_CREAT, "newdir/", "EISDIR"),
("o", os.O_RDONLY | os.O_NONBLOCK, "proc/self/fd/0", "EXDEV"),
("o", os.O_RDONLY, "proc/self/exe", "EXDEV"),
("o", os.O_RDONLY, "proc/self/cwd/x", "EXDEV"),
("o", os.O_RDONLY, "proc/self/status", "proc"),
]
def make_tree(root):
for folder in ("usr/lib/x86_64-linux-gnu", "etc/alternatives", "loop", "chain"):
(root / folder).mkdir(parents=True)
(root / "usr/lib/x86_64-linux-gnu/libfoo.so.1.2").write_text("x86")
(root / "etc/hostname").write_text("inside")
(root / "file").write_text("f")
(root / "chain/end").write_text("end")
links = {"usr/lib/x86_64-linux-gnu/libfoo.so.1": "libfoo.so.1.2", "lib": "usr/lib", "lib64": "/usr/lib",
"etc/alternatives/hn": "/etc/hostname", "etc/escape": "../../../../../../etc/hostname", "loop/a": "b",
"loop/b": "a", "dirlink": "/usr", "rootlink": "/", "dangling": "/usr/newfile"}
links.update({"chain/l%d" % i: ("l%d" % (i + 1) if i < 41 else "end") for i in range(1, 42)})
for link, target in links.items():
os.symlink(target, root / link)
def labels(lines, root):
inodes = {(os.lstat(root).st_dev, os.lstat(root).st_ino): "."}
for folder, dirs, files in os.walk(root):
for name in dirs + files:
st = os.lstat(os.path.join(folder, name))
inodes[(st.st_dev, st.st_ino)] = os.path.relpath(os.path.join(folder, name), root)
out = []
for line in lines:
kind, *values = line.split()
if kind == "OK":
out.append(inodes.get((int(values[0]), int(values[1])), "proc"))
else:
out.append(errno.errorcode[int(values[0])])
return out
@unittest.skipUnless(shutil.which("cc") and os.path.isdir("/proc/self"), "needs cc and procfs")
class Openat2PreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
cls.lib = cls.tmp / "libopenat2.so"
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), "-ldl"], check=True)
source = cls.tmp / "openat2.c"
source.write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
cls.trees = (cls.tmp / "kernel", cls.tmp / "preload")
for tree in cls.trees:
make_tree(tree)
cases = "".join("%s\t%d\t%s\n" % case[:3] for case in CASES)
result = subprocess.run([str(cls.tmp / "openat2"), *map(str, cls.trees)], input=cases, capture_output=True, text=True,
env=dict(os.environ, LD_PRELOAD=str(cls.lib)), timeout=60)
if result.returncode != 0:
raise AssertionError(result.stdout + result.stderr)
lines = result.stdout.splitlines()
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0]) if lines[0] == "kernel" else None
cls.preload = labels(lines[-len(CASES):], cls.trees[1])
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_preload_resolves_in_the_root_without_openat2(self):
for case, got in zip(CASES, self.preload):
self.assertEqual(got, case[3], case)
self.assertTrue((self.trees[1] / "usr/newfile").exists())
def test_the_kernel_agrees(self):
if self.kernel is None:
self.skipTest("this kernel or sandbox has no openat2")
for case, got in zip(CASES, self.kernel):
self.assertEqual(got, case[3], case)
if __name__ == "__main__":
unittest.main()
+170
View File
@@ -0,0 +1,170 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / 'app/src/main/cpp/waylandcomp/src/compositor.c'
def extract_function(source, name):
match = re.search(r'^(?:static )?(?:void|int|uint32_t) ' + re.escape(name) + r'\([^;]*?\) \{',
source, re.MULTILINE)
if match is None:
raise AssertionError(f'Missing compositor function: {name}')
cursor, depth = match.end(), 1
while depth:
depth += (source[cursor] == '{') - (source[cursor] == '}')
cursor += 1
return source[match.start():cursor]
PREAMBLE = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
struct wl_resource { int version, modes, done, hz, w, h; struct wl_resource *next; };
struct surface { int xdg_toplevel, toplevel_committed; struct surface *next; };
struct input_msg { int type, p1, p2, p3, p4; };
static struct wl_resource second = { .version = 1 };
static struct wl_resource first = { .version = 4, .next = &second };
static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 };
static int g_input_pipe[2] = {-1, -1};
static atomic_int g_output_refresh_mhz = 60000;
static atomic_int g_output_refresh_pending;
static int g_output_announced_refresh_mhz = 60000;
static int g_output_w = 1920, g_output_h = 1080;
static int flushes, resizes, pointers, ticks;
static int scale_changes, scale_mode, scale_alignment, renders;
static void *g_display;
#define WL_OUTPUT_MODE_CURRENT 1
#define WL_OUTPUT_MODE_PREFERRED 2
#define wl_resource_for_each(r, list) for ((r) = &first; (r); (r) = (r)->next)
#define wl_list_for_each(s, list, link) for ((s) = &surface; (s); (s) = (s)->next)
static int wl_resource_get_version(struct wl_resource *r) { return r->version; }
static void wl_output_send_mode(struct wl_resource *r, int flags, int w, int h, int hz) {
assert(flags == 3); r->modes++; r->hz = hz; r->w = w; r->h = h;
}
static void wl_output_send_done(struct wl_resource *r) { r->done++; }
static void wl_display_flush_clients(void *display) { (void)display; flushes++; }
static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
#define droiddeck_log(...) ((void)0)
#define deliver_key(m) ((void)0)
#define pointer_event(...) ((void)0)
#define pointer_button(...) ((void)0)
#define scroll_event(...) ((void)0)
#define axis_event(...) ((void)0)
#define pointer_delta(...) ((void)0)
#define deliver_touch(m) ((void)0)
#define deliver_pointer(m) (pointers++)
static void on_vsync(int64_t ns) { assert(ns > 0); ticks++; }
static void vk_present_set_scale_mode(int mode, int alignment) {
scale_changes++; scale_mode = mode; scale_alignment = alignment;
}
static void schedule_render(void) { renders++; }
'''
CHECKS = r'''
static int queued(void) { int n; assert(ioctl(g_input_pipe[0], FIONREAD, &n) == 0); return n; }
static void drain(void) { on_input_readable(g_input_pipe[0], 0, NULL); }
static void expect(int modes, int hz, int resize_count) {
assert(first.modes == modes && second.modes == modes);
assert(first.hz == hz && second.hz == hz);
assert(first.w == 1920 && second.w == 1920 && first.h == 1080 && second.h == 1080);
assert(first.done == modes && second.done == 0);
assert(resizes == resize_count);
assert(pointers == 0);
}
int main(void) {
droiddeck_wayland_set_output_refresh_rate(120000);
assert(atomic_load(&g_output_refresh_mhz) == 120000);
assert(!atomic_load(&g_output_refresh_pending));
assert(first.modes == 0 && second.modes == 0);
assert(pipe2(g_input_pipe, O_CLOEXEC | O_NONBLOCK) == 0);
g_output_announced_refresh_mhz = atomic_load(&g_output_refresh_mhz);
droiddeck_wayland_set_scale_mode(1, 4);
assert(queued() == sizeof(struct input_msg));
drain();
assert(scale_changes == 1 && scale_mode == 1 && scale_alignment == 4 && renders == 1);
assert(first.modes == 0 && second.modes == 0);
droiddeck_wayland_set_output_refresh_rate(120000);
assert(queued() == 0);
droiddeck_wayland_set_output_refresh_rate(60000);
assert(first.modes == 0 && queued() == sizeof(struct input_msg));
drain(); expect(1, 60000, 0); assert(flushes == 1);
droiddeck_wayland_set_output_refresh_rate(60000);
assert(queued() == 0); drain(); expect(1, 60000, 0);
droiddeck_wayland_set_output_refresh_rate(90000);
droiddeck_wayland_set_output_refresh_rate(120000);
drain(); expect(2, 120000, 0);
droiddeck_wayland_set_output_refresh_rate(90000);
droiddeck_wayland_set_output_refresh_rate(120000);
drain(); expect(2, 120000, 0);
droiddeck_wayland_set_output_refresh_rate(60000);
droiddeck_wayland_output_resized();
drain(); expect(3, 60000, 1); assert(flushes == 3);
struct input_msg wake = {10, 0, 0, 0, 0};
int n = 0;
while (write(g_input_pipe[1], &wake, sizeof(wake)) == sizeof(wake)) n++;
assert(n > 0 && errno == EAGAIN);
droiddeck_wayland_set_output_refresh_rate(120000);
drain(); expect(4, 120000, 1);
droiddeck_wayland_set_output_refresh_rate(0);
drain(); expect(5, 60000, 1);
droiddeck_wayland_set_output_refresh_rate(-1);
assert(queued() == 0);
struct input_msg vsync = {5, 0, 16000000, 0, 0};
assert(write(g_input_pipe[1], &vsync, sizeof(vsync)) == sizeof(vsync));
drain(); expect(5, 60000, 1); assert(ticks == 1);
assert(nominal_refresh_ns() == 16666666);
assert(flushes == 5);
assert(scale_changes == 1 && scale_mode == 1 && scale_alignment == 4 && renders == 1);
droiddeck_wayland_set_scale_mode(1, 3);
droiddeck_wayland_set_output_refresh_rate(90000);
drain(); expect(6, 90000, 1);
assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2);
close(g_input_pipe[0]); close(g_input_pipe[1]);
puts("PASS");
}
'''
@unittest.skipUnless(sys.platform.startswith('linux'), 'needs Linux nonblocking pipes')
class OutputRefreshTest(unittest.TestCase):
def test_refresh_notifications_preserve_client_pacing_without_resizing(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
self.skipTest('A host C compiler is required')
source = SOURCE.read_text()
functions = ('nominal_refresh_ns', 'output_send_mode', 'output_notify_mode',
'output_resized', 'on_input_readable', 'droiddeck_wayland_output_resized',
'droiddeck_wayland_set_scale_mode',
'droiddeck_wayland_set_output_refresh_rate')
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
with tempfile.TemporaryDirectory(prefix='droiddeck-output-refresh-') as folder:
path = Path(folder)
(path / 'refresh.c').write_text(harness)
binary = path / 'refresh-test'
build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror',
'-Wno-unused-parameter', '-O2', str(path / 'refresh.c'),
'-o', str(binary)], capture_output=True, text=True)
self.assertEqual(0, build.returncode, build.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('PASS', result.stdout.strip())
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,74 @@
"""Test the renderer's actual map and inverse map without a Vulkan device."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
REPO = Path(__file__).resolve().parents[2]
class GameTopMappingTest(unittest.TestCase):
def test_letterbox_alignment_and_touch_inverse(self):
cc = shutil.which(os.environ.get('CC', 'cc'))
if not cc:
self.skipTest('A host C compiler is required')
source = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.c').read_text()
header = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.h').read_text()
enums = header[header.index('enum vkp_scale_mode'):header.index('void vk_present_set_scale_mode')]
state = source[source.index('static volatile int g_mode'):source.index('static int64_t g_swap_retry_at_ns')]
def function(signature):
start = source.index(signature)
return source[start:source.index('\n}\n', start) + 3]
funcs = '\n'.join(function(name) for name in ['static const char *mode_name(',
'static const char *align_name(', 'static void update_map(', 'int vkp_output_to_scene(', 'int vkp_game_picture_rect('])
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
code = '#include <assert.h>\n#include <math.h>\n#include <stdio.h>\n#include <string.h>\n#include <pthread.h>\n'
code += '#define droiddeck_log(...) ((void)0)\nstatic struct { unsigned width, height; } g_extent;\n'
code += enums + state + funcs
code += r'''
static void near(double a, double b) { assert(fabs(a - b) < 0.01); }
static void check(int sw, int sh, int ow, int oh, int alignment) {
g_extent.width = ow; g_extent.height = oh;
g_mode = VKP_MODE_FIT; g_align = alignment;
update_map(sw, sh);
float rect[4];
assert(vkp_game_picture_rect(rect));
double top = alignment == VKP_ALIGN_PICTURE_TOP ? 0 : oh - sh * g_map.ky;
near(rect[0], g_map.off_x); near(rect[1], top);
near(rect[2], g_map.off_x + sw * g_map.kx);
near(rect[3], top + sh * g_map.ky);
near(g_map.off_y, top);
double sx, sy;
assert(vkp_output_to_scene(g_map.off_x + sw * g_map.kx / 2,
top + sh * g_map.ky / 2, &sx, &sy));
near(sx, sw / 2.0); near(sy, sh / 2.0);
near(g_map.kx, g_map.ky);
assert(sh * g_map.ky <= oh + 0.01);
g_align = VKP_ALIGN_CENTER; update_map(sw, sh);
assert(!vkp_game_picture_rect(rect));
near(g_map.off_y, (int)((oh - sh * g_map.ky) * 0.5));
}
int main(void) {
for (int alignment = VKP_ALIGN_PICTURE_TOP; alignment <= VKP_ALIGN_PICTURE_BOTTOM; alignment++) {
check(1240, 1100, 2480, 2200, alignment);
check(1280, 720, 2480, 2200, alignment);
check(1024, 768, 2480, 2200, alignment);
check(1920, 1080, 2400, 1080, alignment);
check(1240, 1100, 2480, 1394, alignment);
}
g_align = VKP_ALIGN_TOP; update_map(1280, 720);
assert(g_map.rh == 697 && g_map.ry == 0);
puts("PASS");
}
'''
(tmp / 'map.c').write_text(code)
subprocess.run([cc, '-std=c11', str(tmp / 'map.c'), '-lm', '-o', str(tmp / 'map')], check=True, capture_output=True, text=True)
result = subprocess.run([str(tmp / 'map')], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == '__main__':
unittest.main()
+57
View File
@@ -0,0 +1,57 @@
"""Exercise the compositor's real button dispatcher with a recording Wayland sink."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
REPO = Path(__file__).resolve().parents[2]
class PointerReleaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
raise unittest.SkipTest('A host C compiler is required')
source = (REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c').read_text()
start = source.index('static void pointer_button(uint32_t button, int pressed) {')
end = source.index('\n}\n', start) + 3
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-pointer-release-')
cls.addClassCleanup(cls.temp.cleanup)
folder = Path(cls.temp.name)
(folder / 'pointer_button.inc').write_text(source[start:end])
start = source.index('static void touch_cancel_all(void) {')
end = source.index('\n}\n', start) + 3
(folder / 'touch_cancel_all.inc').write_text(source[start:end])
cls.binary = folder / 'pointer-test'
subprocess.run([compiler, '-std=c11', '-Wall', '-I', str(folder),
str(REPO / 'tools/tests/pointer_release_harness.c'),
'-o', str(cls.binary)], check=True, capture_output=True, text=True)
def check_case(self, case):
result = subprocess.run([str(self.binary), case], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_cleanup_releases_all_buttons_without_motion(self):
self.check_case('cleanup')
def test_release_without_focus_does_not_select_a_window(self):
self.check_case('unfocused')
def test_release_reaches_each_focused_pointer_and_clears_grab(self):
self.check_case('focused')
def test_touch_fallback_cancel_releases_without_motion(self):
self.check_case('fallback')
def test_native_touch_cancel_then_cleanup_releases_stale_buttons(self):
self.check_case('native')
def test_press_keeps_existing_routing(self):
self.check_case('press')
if __name__ == '__main__':
unittest.main()
Loaded 100 of 793 files, more files were not shown because too many files have changed in this diff. Show more