Merge origin/main into game debug logging

This commit is contained in:
xXJsonDeruloXx committed 2026-10-22 10:24:09 -04:00
commit f67ff86470
495 files changed
+35293 -2510

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ for bad in libstdc++.so.6 libgcc_s.so.1; do
done
syms() { "${READELF:-readelf}" -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; }
FAKE=$(syms "$D/libfakeinput.so")
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
for sym in open openat ioctl read readv close poll ppoll select stat fstat access scandir; do
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
done
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
@@ -23,6 +23,7 @@ import json
import math
import re
import os
import select
import selectors
import signal
import socket
@@ -532,6 +533,151 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
ws.close()
KEYBOARD_BINDING = "droiddeckSteamKeyboard"
KEYBOARD_CHECK_SECONDS = 30
KEYBOARD_JS = r"""
(() => {
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
self.check = () => {
let showing = false;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
if (!value) continue;
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
self.watched.add(value);
value.Subscribe(() => setTimeout(() => self.check()));
}
if (value.m_currentValue === true) showing = true;
}
if (showing !== self.last) {
self.last = showing;
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(showing));
}
return showing;
};
self.timer = self.timer || setInterval(() => self.check(), 500);
return self.check();
})()
""".replace("__BINDING__", KEYBOARD_BINDING)
class KeyboardWatcher(threading.Thread):
def __init__(self, agent_dir):
super().__init__(daemon=True, name="keyboard")
self.agent_dir = agent_dir
self.path = agent_dir / "keyboard.json"
self.showing = None
self.seq = 0
self.next_id = 0
self.attached = False
def report(self, showing):
if showing == self.showing:
return
self.showing = showing
self.seq += 1
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
def run(self):
failures, last = 0, None
while True:
try:
self.watch()
except Exception as e:
if self.attached:
log("Steam keyboard: lost the client (%s); reattaching" % e)
failures = 0
elif str(e) != last:
log("Steam keyboard: waiting for the client (%s)" % e)
self.attached = False
last = str(e)
self.report(False)
failures += 1
time.sleep(min(2 * failures, 10))
def watch(self):
targets = [t for t in cdp_targets(self.agent_dir)
if t.get("title") == "SharedJSContext" and t.get("webSocketDebuggerUrl")]
if not targets:
raise AgentError("NO_TARGET", "No SharedJSContext yet")
ws = WebSocket(targets[0]["webSocketDebuggerUrl"], 5)
try:
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
self.report(self.install(ws))
self.attached = True
while True:
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
self.report(self.install(ws))
continue
self.event(json.loads(ws.recv()))
finally:
ws.close()
def install(self, ws):
result = self.call(ws, "Runtime.evaluate", {"expression": KEYBOARD_JS, "returnByValue": True})
if result.get("exceptionDetails"):
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
return result.get("result", {}).get("value") is True
def call(self, ws, method, params):
self.next_id += 1
ws.send(json.dumps({"id": self.next_id, "method": method, "params": params}))
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
message = json.loads(ws.recv())
if message.get("id") == self.next_id:
if "error" in message:
raise AgentError("CDP_ERROR", json.dumps(message["error"]))
return message.get("result", {})
self.event(message)
raise AgentError("TIMEOUT", "No answer to %s from DevTools" % method)
def event(self, message):
params = message.get("params") or {}
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
self.report(params.get("payload") == "true")
def steam_idle_inhibit(agent_dir, inhibit):
expression = """(async want => {
const toggle = () => new Promise(done => {
let handle = null;
let timer = null;
const finish = value => {
clearTimeout(timer);
handle?.unregister?.();
done(value);
};
timer = setTimeout(() => finish(null), 2500);
handle = SteamClient.Console.RegisterForSpewOutput(entry => {
const found = /Suspend inhibit: ([01])/.exec(entry?.spew || "");
if (found) finish(found[1] === "1");
});
SteamClient.Console.ExecCommand("toggle_idle_suspend_inhibit 1");
});
let state = await toggle();
if (state === !want) state = await toggle();
return state === want;
})(%s)""" % ("true" if inhibit else "false")
return cdp_eval(agent_dir, expression, timeout=12).get("value") is True
def steam_idle_suspend_seconds(agent_dir, vpower=Path("/run/vpower/ac_status")):
expression = """(() => {
const settings = globalThis.settingsStore?.clientSettings;
return settings ? [settings.system_idle_suspend_ac_sec, settings.system_idle_suspend_battery_sec] : null;
})()"""
seconds = cdp_eval(agent_dir, expression, await_promise=False, timeout=5).get("value")
if not isinstance(seconds, list) or len(seconds) != 2:
return None
try:
on_ac = vpower.read_text().strip() != "Disconnected"
except OSError:
on_ac = True
value = seconds[0 if on_ac else 1]
return max(0, int(value)) if isinstance(value, (int, float)) else None
def steam_selection(agent_dir, timeout=5):
result = cdp_eval(
agent_dir,
@@ -878,6 +1024,8 @@ def serve(agent_dir, focus=True, poll=0.1):
can_focus = focus and bool(os.environ.get("DISPLAY"))
if can_focus:
FocusWatcher(agent_dir / "focus.json").start()
if focus:
KeyboardWatcher(agent_dir).start()
write_json(agent_dir / "hello.json", {"pid": os.getpid(), "version": VERSION, "started": int(time.time() * 1000),
"displays": displays(), "focus": can_focus})
log("serving %s (focus %s)" % (agent_dir, "on" if can_focus else "off"))
@@ -912,6 +1060,24 @@ def main(argv):
return 3
print("droiddeck-agent: Steam overview is ready for shortcut app %d" % prepared["appId"])
return 0
if argv and argv[0] == "--steam-supports-vr":
if len(argv) != 2 or not argv[1].isascii() or not argv[1].isdecimal():
print("usage: droiddeck-agent --steam-supports-vr <appid>", file=sys.stderr)
return 2
# Optional-VR games (Thumper, VRChat) carry vr_supported without vr_only.
expression = ("(o => o ? (o.vr_supported === true || o.vr_only === true) : null)"
"(window.appStore?.GetAppOverviewByGameID?.(%s))" % json.dumps(argv[1]))
value = None
deadline = time.monotonic() + 12 # Steam's UI is busiest while a game starts.
while value is None and time.monotonic() < deadline:
try:
value = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=8).get("value")
except (AgentError, OSError, ValueError):
pass
if value is None:
time.sleep(0.5)
print({True: "yes", False: "no"}.get(value, "unknown"))
return {True: 0, False: 5}.get(value, 1)
if argv and argv[0] == "--steam-asleep":
expression = """(() => {
const store = globalThis.SuspendResumeStore;
@@ -923,6 +1089,26 @@ def main(argv):
state = "unknown"
print(state)
return {"yes": 0, "no": 5}.get(state, 1)
if argv and argv[0] == "--steam-idle-inhibit":
if len(argv) != 2 or argv[1] not in ("on", "off"):
print("usage: droiddeck-agent --steam-idle-inhibit on|off", file=sys.stderr)
return 2
try:
done = steam_idle_inhibit(Path(base) / "agent", argv[1] == "on")
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: could not reach the client's idle sleep: %s" % error, file=sys.stderr)
return 1
return 0 if done else 1
if argv and argv[0] == "--steam-idle-suspend-seconds":
try:
seconds = steam_idle_suspend_seconds(Path(base) / "agent")
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: could not read the client's idle sleep: %s" % error, file=sys.stderr)
return 1
if seconds is None:
return 1
print(seconds)
return 0
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)
@@ -17,7 +17,7 @@ if [ -s /etc/ld.so.preload ]; then
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
fi
flags=()
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
if [ -n "$(find -H "$APPDIR" -maxdepth 4 \( -name chrome-sandbox -o -name chrome_100_percent.pak -o -name v8_context_snapshot.bin \) -print -quit 2>/dev/null)" ]; then
flags+=(--no-sandbox)
if [ -n "${DISPLAY:-}" ]; then
export XDG_SESSION_TYPE=x11
@@ -7,7 +7,21 @@ import socket
import struct
import sys
SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap")
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
def socket_name():
name = os.environ.get("DROIDDECK_BWRAP_SOCKET", "")
if not name:
try:
with open(SOCKET_FILE, encoding="utf-8") as f:
name = f.read().strip()
except OSError:
pass
return "\0" + (name or "com.droiddeck.launcher.bwrap")
SOCKET = socket_name()
VERSION = "bubblewrap 0.11.0 (droiddeck)"
NO_ARG = {
@@ -1232,6 +1232,7 @@ class Session:
seed_settings()
install_shims()
install_preload(files)
fex_module()["install_fonts"](files)
clear_playing()
sync_installations()
forget_sign_in()
@@ -30,9 +30,11 @@ FEX_APPID = "3127680"
SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"}
RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper"),
SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")}
MARKER = ".droiddeck-fex"
LAYOUT = 1
ROOTFS_LAYOUT = 1
ROOTFS_LAYOUT = 2
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
PROVIDED = frozenset((
@@ -40,6 +42,7 @@ PROVIDED = frozenset((
"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",
"libssl.so.3", "libcrypto.so.3",
))
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"))
@@ -48,6 +51,7 @@ FAULT_REPORT = "libfaultreport.so"
VULKAN_PIN = "libvulkan-thunk.so"
VULKAN_PIN_DIR = "lib/x86_64-linux-gnu/droiddeck/vulkan"
VULKAN_THUNK = "libvulkan-guest.so"
ASOUND_CONF = "pcm.!default {\n type pulse\n}\nctl.!default {\n type pulse\n}\n"
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]")
BUNDLE_DEPTH = 3
@@ -59,6 +63,8 @@ SCAN_LIMIT = 4000
MODES = ("auto", "on", "off")
STEAM_VERBS = ("run", "waitforexitandrun")
ESCAPE = re.compile(rb"\\([0-7]{3})")
DEVICE_FONTS = "/usr/local/share/fonts/android"
FONT_RULES = "/etc/fonts/conf.d/66-droiddeck-device-fonts.conf"
def say(message):
@@ -174,15 +180,15 @@ def platform_version(path):
return tuple(int(part) for part in re.findall(r"\d+", os.path.basename(path)))
def runtime_platform(appid=SNIPER_APPID, prefix="sniper_platform_"):
runtime = app_dir(appid)
def runtime_platform(app=SNIPER_APPID):
runtime = app_dir(app)
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(prefix)]
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith(RUNTIMES[app][0])]
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)
@@ -245,7 +251,7 @@ def materialize(platform):
def graphics_platform():
return runtime_platform(SLR4_APPID, "steamrt4_platform_")
return runtime_platform(SLR4_APPID)
def provides_newer(base, provider):
@@ -338,6 +344,7 @@ def install_preloads(root):
if len(shipped.get(FAULT_REPORT, ())) == len(GUEST_LIBDIRS):
wanted.append(FAULT_REPORT)
write_if_changed(os.path.join(root, "etc", "ld.so.preload"), "".join("/usr/$LIB/droiddeck/%s\n" % name for name in wanted))
write_if_changed(os.path.join(root, "etc", "asound.conf"), ASOUND_CONF)
def write_config(fex, root):
@@ -350,6 +357,16 @@ def write_config(fex, root):
write_if_changed(os.path.join(CONFIG_DIR, "Config.json"), json.dumps(config, indent=2) + "\n")
def install_fonts(root):
target = os.path.join(root, FONT_RULES.lstrip("/"))
rules = read_text(FONT_RULES) or ""
if not os.path.isdir(DEVICE_FONTS) or "<fontconfig>" not in rules:
with contextlib.suppress(FileNotFoundError):
os.unlink(target)
return
write_if_changed(target, rules.replace("<fontconfig>", "<fontconfig>\n<dir>%s</dir>" % DEVICE_FONTS, 1))
def link_steam_sdk():
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
link = os.path.join(HOME, ".steam", sdk)
@@ -366,6 +383,24 @@ def link_steam_sdk():
break
def link_guest_sdk(root):
# Proton's lsteamclient only looks in $HOME/.steam/sdk64; on ARM Steam that is the arm64 client, so
# the x86 runtime gets its own link, which FEX resolves before the host path.
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
want = "x86_64" if sdk == "sdk64" else "i386"
directory = next((os.path.join(STEAM_ROOT, candidate) for candidate in candidates
if elf_arch(os.path.join(STEAM_ROOT, candidate, "steamclient.so")) == want), None)
if not directory:
continue
link = os.path.join(root, HOME.lstrip("/"), ".steam", sdk)
if os.path.islink(link) and os.readlink(link) == directory:
continue
os.makedirs(os.path.dirname(link), exist_ok=True)
if os.path.lexists(link):
os.unlink(link)
os.symlink(directory, link)
def steam_running():
for pid in os.listdir("/proc"):
if not pid.isdigit():
@@ -380,13 +415,15 @@ def steam_running():
return False
def request_install():
def request_install(app=SNIPER_APPID):
os.makedirs(os.path.dirname(WANTED), exist_ok=True)
write_if_changed(WANTED, "1\n")
if not steam_running():
return []
try:
compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility"))
if app != SNIPER_APPID and app_dir(app) is None:
return compat["request_app"](STEAM_ROOT, app)
return compat["request_fex"](STEAM_ROOT, set())
except Exception as error:
say("could not ask the client to install FEX (%s)" % error)
@@ -406,10 +443,10 @@ def describe(fex, platform, graphics=None):
}
def prepare():
def prepare(app=SNIPER_APPID):
with locked():
fex = fex_install()
platform = runtime_platform()
platform = runtime_platform(app)
status = describe(fex, platform)
if not status["ready"]:
missing = []
@@ -422,8 +459,8 @@ def prepare():
elif not fex["server"]:
missing.append("FEXServer beside %s" % fex["bin"])
if not platform:
missing.append("Steam Linux Runtime 3.0 (sniper, Steam app %s)" % SNIPER_APPID)
requested = request_install()
missing.append("%s, Steam app %s)" % (RUNTIMES[app][1], app))
requested = request_install(app)
say("x86 Linux programs need %s; %s" % (" and ".join(missing),
"the Steam client was asked to install it" if requested else "open Steam once and it is installed for you"))
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
@@ -432,20 +469,25 @@ 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")
install_fonts(root)
provider = None
if app == SNIPER_APPID:
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")
with contextlib.suppress(OSError):
link_guest_sdk(root)
write_config(fex, root)
fex["rootfs"] = root
try:
@@ -530,6 +572,8 @@ def guest_environment(fex, env):
result["STEAM_COMPAT_DATA_PATH"] = short
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
# The session's tunables are for the host libc; an x86 ld.so copying them under FEX fails in sbrk.
result.pop("GLIBC_TUNABLES", None)
# 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"]:
@@ -594,6 +638,12 @@ def vulkan_thunk_loads(fex, folder):
return True
def required_runtime(program):
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
def resolve(program, env):
if "/" in program:
return os.path.abspath(program)
@@ -605,7 +655,7 @@ def launch(command, env, mode, decide=None):
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
if not use:
return os.execvpe(command[0], command, env)
fex = prepare()
fex = prepare(required_runtime(program))
if fex is None:
return 126
guest = guest_environment(fex, env)
@@ -624,6 +674,7 @@ def launch(command, env, mode, decide=None):
def game_environment(env):
try:
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
env = game_env["game_gpu"](env)
app = game_env["game_id"](env) or env.get("SteamAppId") or env.get("SteamGameId")
if not app:
return env
@@ -1,4 +1,5 @@
#!/usr/bin/python3
import hashlib
import json
import os
import re
@@ -7,6 +8,7 @@ import subprocess
import sys
from pathlib import Path
GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
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 +100,12 @@ def godot_sentry(game):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def deep_rock_gdk_raytracing(game):
if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")):
return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)"
@fix
def arkham_city_x87(game):
"""Batman: Arkham City (BatmanAC.exe, also started through BmLauncher.exe beside it) leans on x87
@@ -119,6 +127,35 @@ def skip_red_launcher(command):
return command
def offline_without_anticheat(command, env):
"""Start the configured game executable when the player opts into launching without EAC."""
if (env.get("DROIDDECK_ANTICHEAT_OFFLINE") != "1" or len(command) <= 2
or command[1] != "waitforexitandrun"
or not re.fullmatch(r"start_protected_game(?:_?x64|_?64)?\.exe",
os.path.basename(command[2]), re.IGNORECASE)):
return command
folder = os.path.dirname(command[2])
try:
with open(os.path.join(folder, "EasyAntiCheat", "settings.json"), encoding="utf-8-sig") as source:
executable = json.load(source).get("executable")
except (OSError, ValueError, AttributeError):
return command
if not isinstance(executable, str) or not executable:
return command
relative = os.path.normpath(executable.replace("\\", "/"))
game = os.path.join(folder, relative)
if os.path.isabs(relative) or relative.startswith("..") or not os.path.isfile(game):
return command
# Resolve symlinks before accepting an executable inside the game directory.
root = os.path.realpath(folder)
if os.path.commonpath((root, os.path.realpath(game))) != root:
return command
if os.path.normcase(os.path.abspath(game)) == os.path.normcase(os.path.abspath(command[2])):
return command
print("droiddeck-game-env: started without Easy Anti-Cheat (offline only)", file=sys.stderr)
return command[:2] + [game] + command[3:]
def engine_fixes(exe, args):
"""Environment and extra arguments a game needs because of what it is built with."""
game = Game(exe, args)
@@ -147,6 +184,18 @@ def win_components(compat, app_id):
return ""
def game_gpu(env):
if GAME_TU_DEBUG not in env:
return env
result = env.copy()
value = result.pop(GAME_TU_DEBUG)
if value:
result["TU_DEBUG"] = value
else:
result.pop("TU_DEBUG", None)
return result
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -313,27 +362,135 @@ def mark_install_scripts(command, env):
starts - on first launch the shared ones may still be downloading, and on ARM64 Proton the VC++
ones stop with an error."""
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
return
return []
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:
return
return []
try:
subprocess.run([SEED_REDISTS, root], env=dict(env, DROIDDECK_SEED_SCRIPTS="\n".join(scripts)),
stdout=sys.stderr, timeout=60, check=False)
except (OSError, subprocess.SubprocessError) as error:
print("droiddeck-game-env: install scripts not marked (%s)" % error, file=sys.stderr)
return scripts
INSTALL_STAMP = ".droiddeck-install-scripts"
VDF_TOKEN = re.compile(r'"((?:[^"\\]|\\.)*)"|([{}])')
def read_vdf(text):
tokens = iter(VDF_TOKEN.findall(text))
def block():
items = []
for word, brace in tokens:
if brace == "}":
return items
if brace:
raise ValueError("a block without a name")
value, opens = next(tokens, ("", "}"))
if opens == "}":
raise ValueError("a name without a value")
items.append((re.sub(r"\\(.)", r"\1", word), block() if opens else re.sub(r"\\(.)", r"\1", value)))
return items
return block()
def run_keys(items, appid=""):
appid = next((value for name, value in items if name.lower() == "appid" and isinstance(value, str)), appid)
found = set()
for name, value in items:
if not isinstance(value, list):
continue
if any(isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in value):
key = next((v for n, v in value if n.lower() == "hasrunkey" and isinstance(v, str)),
"HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\" + appid)
found.add((key.lower(), name.lower()))
found |= run_keys(value, appid)
return found
def registry_values(path):
found, section = set(), None
with open(path, encoding="utf-8", errors="replace") as reg:
for line in reg:
if line.startswith("["):
section = line[1:line.find("]")].replace("\\\\", "\\").lower() if "]" in line else None
elif section and line.startswith('"') and '"=' in line:
found.add((section, line[1:line.index('"=')].replace("\\\\", "\\").lower()))
return found
def has_run(key, value, values):
path = key[len("hkey_local_machine\\"):] if key.startswith("hkey_local_machine\\") else None
if path is None:
return False
views = [path]
if path.startswith("software\\"):
views.append("software\\wow6432node\\" + path[len("software\\"):])
return any((view, value) in values for view in views)
def scripts_digest(scripts):
digest = hashlib.sha256()
for path in sorted(scripts):
digest.update(os.path.basename(path).encode() + b"\0")
digest.update(Path(path).read_bytes())
return digest.hexdigest()
def install_scripts_done(scripts, env):
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
try:
if (prefix / INSTALL_STAMP).read_text().strip() != scripts_digest(scripts):
return False
keys = set()
for path in scripts:
keys |= run_keys(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
values = registry_values(prefix / "system.reg")
except (OSError, ValueError):
return False
return bool(keys) and all(has_run(key, value, values) for key, value in keys)
def record_install_scripts(digest, env):
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
try:
if prefix.is_dir():
staged = prefix / (INSTALL_STAMP + ".tmp")
staged.write_text(digest + "\n")
staged.replace(prefix / INSTALL_STAMP)
except OSError as error:
print("droiddeck-game-env: install scripts not recorded (%s)" % error, file=sys.stderr)
def start(launch, launch_env, digest):
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
record_install_scripts(digest, launch_env)
return code
return os.execvpe(launch[0], launch, launch_env)
def main():
command = sys.argv[1:]
if not command:
return 2
env = os.environ.copy()
env = game_gpu(os.environ.copy())
mic_enabled = env.get("BL_MIC_ENABLED")
debug_dir = env.get("BL_DEBUG_DIR", "")
mark_install_scripts(command, env)
scripts = mark_install_scripts(command, env)
if scripts and install_scripts_done(scripts, env):
print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr)
return 0
try:
digest = scripts_digest(scripts) if scripts else None
except OSError:
digest = None
app_id = game_id(env)
if app_id:
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
@@ -367,19 +524,33 @@ def main():
env = apply_game_debug_logs(env, config, debug_dir)
if env is not before_debug:
print("droiddeck-game-env: game debug logs enabled for this launch", file=sys.stderr)
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env = force_ssbs(command, env)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
print("droiddeck-game-env: Xbox support unavailable (%s); stock launch" % error, file=sys.stderr)
xbox = {"launch": lambda command, env: None}
try:
xbox_result = xbox["launch"](command, env)
except (OSError, ValueError, KeyError, RuntimeError) as error:
print("droiddeck-game-env: Xbox launch could not start (%s)" % error, file=sys.stderr)
return 1
if xbox_result is not None:
return xbox_result
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
os.execvpe(launch[0], launch, launch_env)
return start(launch, launch_env, digest)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
os.execvpe(launch[0], launch, launch_env)
return start(launch, launch_env, digest)
if __name__ == "__main__":
@@ -28,6 +28,8 @@ UPOWER_ROOT = "/org/freedesktop/UPower"
NATIVE_PREPARE_MS = 1500
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
ASLEEP_WAIT = 6
INHIBIT_WAIT = 12
RELEASE_RETRIES = 8
INTROSPECTION = """
<node>
<interface name="org.freedesktop.login1.Manager">
@@ -58,8 +60,14 @@ class LoginManager:
self.native_request = self.directory / "steam-native-sleep"
self.native_ready = self.directory / "steam-native-ready"
self.pending = None
self.pending_idle = False
self.waiting = set()
self.timeout = None
self.preparation = None
self.inhibited = False
self.inhibit_lock = threading.Lock()
self.release = None
self.generation = 0
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
self.registration = bus.register_object(ROOT, info, self.method, self.property, None)
upower_info = Gio.DBusNodeInfo.new_for_xml(UPOWER_INTROSPECTION).interfaces[0]
@@ -89,6 +97,7 @@ class LoginManager:
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
return
self.pending = uuid.uuid4().hex
self.pending_idle = False
self.notify(True)
reply.return_value(None)
self.bus.flush(None, self.publish_after_flush, self.pending)
@@ -101,7 +110,7 @@ class LoginManager:
self.resume()
return
if self.pending == token:
self.publish(self.request)
self.hold(token, self.publish, self.request)
def publish(self, request):
self.check_state()
@@ -119,15 +128,21 @@ class LoginManager:
def prepare_native(self):
try:
token = self.native_request.read_text().strip()
words = self.native_request.read_text().split()
self.native_request.unlink(missing_ok=True)
except OSError:
return
if not re.fullmatch(r"[a-f0-9]{32}", token) or self.pending is not None:
token = words[0] if words else ""
if not re.fullmatch(r"[a-f0-9]{32}", token) or words[1:] not in ([], ["idle"]) or self.pending is not None:
return
if self.read_state() == token + ":awake":
return
self.pending = token
self.pending_idle = words[1:] == ["idle"]
self.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
self.hold(token, self.prepared, token, "hold")
if self.pending_idle:
return
self.notify(True)
self.bus.flush(None, self.prepare_after_flush, token)
@@ -144,10 +159,73 @@ class LoginManager:
def finish_preparation(self, token):
self.preparation = None
if self.pending == token:
self.prepared(token, "prepare")
return False
def prepared(self, token, step):
if self.pending != token:
return False
self.waiting.discard(step)
if not self.waiting:
self.publish(self.native_ready)
return False
def hold(self, token, then, *args):
self.cancel_release()
def work():
self.set_inhibit(True)
GLib.idle_add(self.after_hold, token, then, args)
threading.Thread(target=work, daemon=True).start()
def after_hold(self, token, then, args):
if self.pending == token:
then(*args)
elif self.pending is None:
self.release_later()
return False
def set_inhibit(self, inhibit, generation=None):
with self.inhibit_lock:
if (generation is not None and generation != self.generation) or self.inhibited == inhibit:
return
if steam_idle_inhibit(inhibit):
self.inhibited = inhibit
print("== login1: Steam idle sleep " + ("held" if inhibit else "released"), flush=True)
else:
self.inhibited = None
def cancel_release(self):
self.generation += 1
if self.release is not None:
GLib.source_remove(self.release)
self.release = None
def release_later(self):
self.cancel_release()
if self.inhibited is False:
return
generation = self.generation
threading.Thread(target=lambda: GLib.idle_add(self.schedule_release, generation, steam_idle_suspend_seconds()),
daemon=True).start()
def schedule_release(self, generation, seconds, attempt=0):
if generation == self.generation and self.pending is None:
self.release = GLib.timeout_add_seconds(seconds or 0, self.release_now, generation, attempt)
return False
def release_now(self, generation, attempt):
self.release = None
def work():
self.set_inhibit(False, generation)
if self.inhibited is not False and attempt < RELEASE_RETRIES:
GLib.idle_add(self.schedule_release, generation, 1 << attempt, attempt + 1)
threading.Thread(target=work, daemon=True).start()
return False
def changed(self, monitor, file, other, event):
if file.get_basename() == self.native_request.name or (other and other.get_basename() == self.native_request.name):
self.prepare_native()
@@ -178,8 +256,10 @@ class LoginManager:
def woken(self):
if self.pending is not None:
idle = self.pending_idle
self.resume(force=True)
return
if not idle:
return
threading.Thread(target=lambda: GLib.idle_add(self.replay_unless_awake, steam_asleep()), daemon=True).start()
def replay_unless_awake(self, asleep):
@@ -195,14 +275,18 @@ class LoginManager:
self.notify(True)
self.bus.flush(None, self.finish_recovery, None)
return
idle = self.pending_idle
self.pending = None
self.pending_idle = False
if self.preparation is not None:
GLib.source_remove(self.preparation)
self.preparation = None
if self.timeout is not None:
GLib.source_remove(self.timeout)
self.timeout = None
self.notify(False)
if not idle:
self.notify(False)
self.release_later()
def finish_recovery(self, connection, result, _data):
try:
@@ -213,13 +297,26 @@ class LoginManager:
self.notify(False)
def steam_asleep():
def agent(*args, timeout=ASLEEP_WAIT):
try:
code = subprocess.run([str(AGENT), "--steam-asleep"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=ASLEEP_WAIT).returncode
done = subprocess.run([str(AGENT), *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, timeout=timeout)
except (OSError, subprocess.SubprocessError):
return None
return {0: True, 5: False}.get(code)
return None, ""
return done.returncode, done.stdout
def steam_asleep():
return {0: True, 5: False}.get(agent("--steam-asleep")[0])
def steam_idle_inhibit(inhibit):
return agent("--steam-idle-inhibit", "on" if inhibit else "off", timeout=INHIBIT_WAIT)[0] == 0
def steam_idle_suspend_seconds():
code, output = agent("--steam-idle-suspend-seconds")
return int(output) if code == 0 and output.strip().isdigit() else None
def load_netmanager():
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Audio stays on the session's PulseAudio, so WirePlumber runs its upstream video-only profile.
set -u
bundle=/usr/local/lib/droiddeck-pipewire.tzst
dir=/usr/local/lib/droiddeck-pipewire
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-pipewire
client_env() {
echo "export PIPEWIRE_CONFIG_DIR=$dir/share/pipewire PIPEWIRE_MODULE_DIR=$dir/lib/pipewire-0.3 SPA_PLUGIN_DIR=$dir/lib/spa-0.2"
}
unpack() {
[ -f "$bundle" ] || { echo "droiddeck-pipewire: $bundle is missing" >&2; return 1; }
sum=$(cksum < "$bundle")
[ "$(cat "$dir/.bundle" 2>/dev/null)" = "$sum" ] && return 0
rm -rf "$dir.new" && mkdir -p "$dir.new" &&
zstd -dc "$bundle" | tar -xf - -C "$dir.new" &&
printf '%s\n' "$sum" > "$dir.new/.bundle" &&
rm -rf "$dir" && mv "$dir.new" "$dir" ||
{ rm -rf "$dir.new"; echo "droiddeck-pipewire: could not unpack $bundle" >&2; return 1; }
}
stop() {
for pid in $(cat "$state/pids" 2>/dev/null); do kill "$pid" 2>/dev/null; done
rm -f "$state/pids"
}
case "${1:-}" in
env)
client_env
;;
start)
unpack || exit 1
stop
mkdir -p "$state"
eval "$(client_env)"
export LD_LIBRARY_PATH=$dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export WIREPLUMBER_MODULE_DIR=$dir/lib/wireplumber-0.5 WIREPLUMBER_CONFIG_DIR=$dir/share/wireplumber \
WIREPLUMBER_DATA_DIR=$dir/share/wireplumber
socket=${XDG_RUNTIME_DIR:-/tmp}/pipewire-0
rm -f "$socket" "$socket.lock" "$socket-manager" "$socket-manager.lock"
"$dir/bin/pipewire" < /dev/null &
echo $! > "$state/pids"
i=0
while [ ! -S "$socket" ]; do
i=$((i + 1))
[ "$i" -le 50 ] || { echo "droiddeck-pipewire: pipewire did not open $socket" >&2; stop; exit 1; }
sleep 0.1
done
"$dir/bin/wireplumber" --profile video-only < /dev/null &
echo $! >> "$state/pids"
echo "droiddeck-pipewire: pipewire and wireplumber (video-only) up at $socket"
;;
stop)
stop
;;
*)
echo "usage: droiddeck-pipewire env|start|stop" >&2
exit 2
;;
esac
@@ -96,14 +96,14 @@ done <<<"$pairs"
want+=("vcrt"$'\t'"$VCRT_MAJOR.$VCRT_MINOR.$VCRT_BUILD")
printf -v now '%(%s)T' -1
block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" -v hive="$hive" '
{
path = $1
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
if (path == $1)
next
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
if (substr(path, 1, 10) != "Software\\\\")
if (hive != "HKEY_LOCAL_MACHINE" || substr(path, 1, 10) != "Software\\\\")
next
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", "Software\\\\Wow6432Node\\\\" substr(path, 11), now, $2
}
@@ -115,16 +115,17 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
unseed() {
local reg=$1 out
shift
out=$(mktemp "${reg%/*}/.system.reg.XXXXXX") || return 1
if printf '%s\n' "$@" | awk -F'\t' '
[ -w "$reg" ] || return 1
out=$(mktemp "${reg%/*}/.${reg##*/}.XXXXXX") || return 1
if printf '%s\n' "$@" | awk -F'\t' -v hive="$hive" '
NR == FNR {
path = $1
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
if (path == $1)
next
path = tolower(path)
drop["[" path "]" SUBSEP tolower($2)] = 1
if (substr(path, 1, 10) == "software\\\\")
if (hive == "HKEY_LOCAL_MACHINE" && substr(path, 1, 10) == "software\\\\")
drop["[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)] = 1
next
}
@@ -145,11 +146,11 @@ unseed() {
# 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' '
present() { awk -F'\t' -v hive="$hive" '
NR == FNR {
path = $1
if (path != "vcrt") {
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
if (path == $1)
next
}
@@ -163,7 +164,7 @@ present() { awk -F'\t' '
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" runtime "]" SUBSEP "installed"
}
} else {
both = substr(path, 1, 10) == "Software\\\\"
both = hive == "HKEY_LOCAL_MACHINE" && substr(path, 1, 10) == "Software\\\\"
path = tolower(path)
key[n, ++need[n]] = "[" path "]" SUBSEP tolower($2)
if (both)
@@ -188,6 +189,7 @@ present() { awk -F'\t' '
}
' - "$1"; }
regs=()
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 \
@@ -195,46 +197,84 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
"$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" ] || continue
seeded=${reg%/*}/.droiddeck-redists
legacy=${reg%/*}/.bannerlator-redists
[ -f "$reg" ] && regs+=("$reg")
done
declare -A regid=()
if [ ${#regs[@]} -gt 0 ]; then
users=()
for reg in "${regs[@]}"; do users+=("${reg%/*}/user.reg"); done
while IFS=$'\t' read -r id name; do
regid[$name]=$id
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" "${users[@]}" 2>/dev/null)
fi
for system in "${regs[@]}"; do
user=${system%/*}/user.reg
seeded=${system%/*}/.droiddeck-redists
checked=${system%/*}/.droiddeck-redists-checked
id="${regid[$system]:-}|${regid[$user]:-missing}"
prev=
[ -f "$checked" ] && read -r prev <"$checked"
legacy=${system%/*}/.bannerlator-redists
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
mv -f "$legacy" "$seeded"
fi
declare -A had=()
if [ -f "$seeded" ]; then
while IFS= read -r line; do [[ $line == *$'\t'* ]] && had[$line]=1; done <"$seeded"
fi
stale=() kept=()
for line in "${!had[@]}"; do
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
done
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
had=()
for line in "${kept[@]}"; do had[$line]=1; done
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"
for reg in "$system" "$user"; do
hive=HKEY_LOCAL_MACHINE
[ "$reg" == "$user" ] && hive=HKEY_CURRENT_USER
declare -A had=()
other=()
if [ -f "$seeded" ]; then
while IFS= read -r line; do
[[ $line == *$'\t'* ]] || continue
if [[ $line == "$hive\\"* ]] || { [ "$reg" == "$system" ] && [[ $line == vcrt$'\t'* ]]; }; then
had[$line]=1
else
other+=("$line")
fi
done <"$seeded"
fi
unset held
fi
missing=()
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
[ ${#missing[@]} -eq 0 ] && continue
dated=$(mktemp) || continue
touch -r "$reg" "$dated"
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
printf '%s\n' "${!had[@]}" "${missing[@]}" >"$seeded"
echo "== seeded redist markers into $reg"
fi
touch -r "$dated" "$reg"
rm -f "$dated"
stale=() kept=()
for line in "${!had[@]}"; do
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
done
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
id=
had=()
for line in "${kept[@]}"; do had[$line]=1; done
printf '%s\n' "${other[@]}" "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
declare -A held=()
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <([ -f "$reg" ] && 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' "${other[@]}" "${!had[@]}" >"$seeded"
fi
unset held
fi
missing=()
for line in "${want[@]}"; do
[[ $line == "$hive\\"* ]] || { [ "$reg" == "$system" ] && [[ $line == vcrt$'\t'* ]]; } || continue
[ -n "${had[$line]:-}" ] || missing+=("$line")
done
if [ ${#missing[@]} -eq 0 ]; then
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
continue
fi
[ -f "$reg" ] && [ -w "$reg" ] || continue
rm -f "$checked"
dated=$(mktemp) || continue
touch -r "$reg" "$dated"
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
printf '%s\n' "${other[@]}" "${!had[@]}" "${missing[@]}" >"$seeded"
id=
echo "== seeded redist markers into $reg"
fi
touch -r "$dated" "$reg"
rm -f "$dated"
done
done
@@ -4,6 +4,11 @@ export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S) $*"; }
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
[ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE"
exit "$1"
}
if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
mkdir -p "$(dirname "$BL_LOG")" 2>/dev/null
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
@@ -129,6 +134,8 @@ export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-steamvr/active"
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
/usr/local/bin/droiddeck-desktop-bookmarks || true
fi
@@ -245,8 +252,15 @@ if [ -z "${BL_INSIDE:-}" ]; then
fi
export BL_INSIDE=1
if [ "$mode" = steam ]; then
if /usr/local/bin/droiddeck-pipewire start; then
eval "$(/usr/local/bin/droiddeck-pipewire env)"
else
echo "== pipewire: not running; Remote Play and game recording have no picture"
fi
run_gamescope "${args[@]}" -- "$0" "$mode" "$@"
exit $?
_bl_status=$?
/usr/local/bin/droiddeck-pipewire stop
exit $_bl_status
fi
exec gamescope "${args[@]}" -- "$0" "$mode" "$@"
fi
@@ -302,6 +316,9 @@ case $mode in
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
fi
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11
fi
run_program() {
local rc=0 child sig forwarded=0
{ trap - INT QUIT; exec "$@"; } <&0 &
@@ -330,6 +347,10 @@ case $mode in
*.appimage)
export APPIMAGE_EXTRACT_AND_RUN=1
chmod +x "$target" 2>/dev/null
if [ ${#fex[@]} -eq 0 ] && [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$target
run_program /usr/local/lib/droiddeck/uruntime "$@"
fi
run_program "${fex[@]}" "$target" "$@"
;;
*.sh)
@@ -345,6 +366,12 @@ case $mode in
esac
;;
steam)
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11
fi
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
steam_x64=0
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
steam_cef_gpu=1
@@ -353,10 +380,10 @@ case $mode in
# 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 || steam_setup_failed $?
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 $?
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || steam_setup_failed $?
step "x86-64 Steam client ready"
steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
steam_client=(droiddeck-steam-x64 --exec)
@@ -366,7 +393,7 @@ case $mode in
fi
else
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
droiddeck-steam-install || exit $?
droiddeck-steam-install || steam_setup_failed $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
if [ -f "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then
@@ -595,6 +622,7 @@ case $mode in
steam_hold_launch() {
local game=$1 shortcut= waited=0 status=0
_bl_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
_bl_starting() { pgrep -f "reaper SteamLaunch AppId=$(((game >> 32) & 0xffffffff))( |$)" >/dev/null 2>&1; }
_bl_hand_off() {
printf '%s\n' "$game" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
}
@@ -609,16 +637,22 @@ case $mode in
_bl_hand_off
[ -n "$shortcut" ] || return 0
# Steam can drop a shortcut launch it gets before the shortcut's overview exists (large libraries).
# Hand it over again only if the game never took focus, so a launch that worked is not started twice.
# A launch can be running before it creates its first window.
while [ "$(_bl_focused)" = 769 ] && [ "$waited" -lt 20 ]; do
sleep 1
waited=$((waited + 1))
done
[ "$(_bl_focused)" = 769 ] || return 0
if _bl_starting; then
echo "== steam: the requested game is already starting; not launching again"
return 0
fi
echo "== steam: the game is not in front after about 20 s; waiting for the shortcut overview"
/usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$game" 45 || status=$?
if [ "$status" -eq 3 ]; then
echo "== steam: not a shortcut CGameID; not launching again"
elif _bl_starting; then
echo "== steam: the requested game started while waiting; not launching again"
elif [ "$(_bl_focused)" = 769 ]; then
echo "== steam: launching the requested game again $game (overview status $status)"
_bl_hand_off
@@ -105,7 +105,7 @@ INSTALL_JS = r"""
const body = [];
uint(1, appid, body);
const r = await send("CompatManager.GetCompatTools#1", body);
if (!r.ok) throw new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")");
if (!r.ok) throw Object.assign(new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")"), { eresult: r.eresult });
return { selected: text(r.body, 3), fallback: text(r.body, 4), tools: (r.body[1] || []).map((t) => text(parse(t), 1)) };
};
self.set = async (appid, name) => {
@@ -119,7 +119,13 @@ INSTALL_JS = r"""
};
self.many = async (apps) => {
const out = {};
for (const app of apps) out[app] = (await self.get(Number(app))).selected;
for (const app of apps) {
try {
out[app] = (await self.get(Number(app))).selected;
} catch (e) {
if (e.eresult !== 128) throw e;
}
}
return out;
};
window.__droiddeckCompat = self;
@@ -555,11 +561,24 @@ class Helper:
# "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 ())
picked = COMPAT["picked_apps"](state)
runnable = {t["name"].lower() for t in live}
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 {})
refused = set(apps) - set(current)
refused_native = native_choices & refused
if refused:
apps = [app for app in apps if app not in refused]
installed = [app for app in installed if app not in refused]
picks = [app for app in picks if app not in refused]
prior_auto = {app: tool for app, tool in prior_auto.items() if app not in refused}
if isinstance(state.get("auto"), dict):
state["auto"] = prior_auto
native_choices -= refused
overrides = {app: tool for app, tool in overrides.items() if app not in refused}
current["0"] = top["selected"]
native = COMPAT["native_targets"](self.steam_root, apps)
raw_mapping = COMPAT["read_config_mapping"](
@@ -568,7 +587,7 @@ class Helper:
for app in native_choices:
current[app] = ""
for app in set(native) - native_choices:
if not current.get(app):
if not current.get(app) and app not in picked:
current.pop(app, None)
else:
for app in set(native) | native_choices:
@@ -576,7 +595,8 @@ class Helper:
# 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:
elif app in prior_auto or app in native_choices or app in picked and (
not current.get(app) or COMPAT["unrunnable"](current[app], runnable)):
current[app] = ""
elif not current.get(app):
current.pop(app, None)
@@ -590,8 +610,8 @@ class Helper:
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)
native_choices=sorted(refused_native | {app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]}),
picked=COMPAT["picked_after"](current, changes), tools=catalog, live=True)
state.pop("native", None)
if waiting:
state["pending"] = wanted
@@ -291,7 +291,7 @@ def libraries(steam_root):
except OSError:
text = ""
paths = [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', text)]
return list(dict.fromkeys([Path(steam_root), Path(LIBRARY)] + [Path(path) for path in paths]))
return list(dict.fromkeys([Path(steam_root)] + [Path(path) for path in paths]))
def ours(manifest, appid):
@@ -311,6 +311,16 @@ def unpark(steamapps):
os.replace(manifest, live)
def seeded(steamapps, game, appid):
target = steamapps / "common" / f"DroidDeck-{appid}"
manifest = steamapps / f"appmanifest_{appid}.acf"
try:
return (target.is_symlink() and target.is_dir() and manifest.is_file() and ours(manifest, appid)
and os.readlink(target) in (game.get("folder", ""), legacy_path(game.get("folder", ""))))
except OSError:
return False
def park(steamapps):
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
@@ -428,6 +438,9 @@ def route(steam_root, acct, games):
continue
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
routes[str(game["appid"])] = appid
continue
shortcuts.append(game)
try:
park(steamapps)
@@ -8,7 +8,7 @@ ROOTFS_SHA256=2854b06d3ff1b8f6e526135bfb6dd5b7b30ab3ab73e79ae933a3d9fed959a178
CDN=https://client-update.fastly.steamstatic.com
# Must match the -clientbeta droiddeck-session starts this client with (steam_channel).
X64_CHANNEL=steamdeck_publicbeta
MANIFEST=steam_client_${X64_CHANNEL}_ubuntu12
MANIFEST=steam_client_${X64_CHANNEL}_steamrt64
REAL_HOME=${HOME:-/root}
X64_HOME=${BL_X64_HOME:-$REAL_HOME/.droiddeck-x64}
@@ -37,17 +37,17 @@ x64_client_parts() {
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
END { for (b in file) if (b ~ /_all$/ || b ~ /_steamrt64$/) print b, file[b], sha[b] }
' "$1" | sort
}
x64_sync_client() {
local chan cur version work total i block file sum old
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
old=$STEAM_X64/package/steam_client_${chan}_ubuntu12.manifest
old=$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest
cur=$(awk -F'"' '$2 == "version" { print $4; exit }' "$old" 2>/dev/null || true)
work=$(mktemp -d)
if ! curl -fsSL "$CDN/steam_client_${chan}_ubuntu12" -o "$work/manifest"; then
if ! curl -fsSL "$CDN/steam_client_${chan}_steamrt64" -o "$work/manifest"; then
rm -rf "$work"; return 0
fi
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
@@ -471,7 +471,7 @@ if [ ! -x "$STEAM_X64/steamrt64/steam" ] || [ ! -f "$STEAM_X64/package/droiddeck
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
END { for (b in file) if (b ~ /_all$/ || b ~ /_steamrt64$/) print b, file[b], sha[b] }
' "$work/manifest" | sort > "$work/parts"
[ -s "$work/parts" ] || { step "no client components in $MANIFEST"; exit 1; }
mkdir -p "$STEAM_X64/package"
@@ -910,7 +910,7 @@ x64_exec() {
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ]; then
local chan x86_build arm_build
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_ubuntu12.manifest" 2>/dev/null || true)
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true)
arm_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$ARM_STEAM/package/steam_client_${chan}_linuxarm64.manifest" 2>/dev/null || true)
if [ -n "$x86_build" ] && [ "$x86_build" = "$arm_build" ]; then
export BL_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-arm-webhelper
@@ -937,7 +937,7 @@ x64_exec() {
touch "$STEAM_X64/logs/bootstrap_log.txt"
( tail -n0 -F --pid=$$ "$STEAM_X64/logs/bootstrap_log.txt" 2>/dev/null |
grep --line-buffered -oE 'Downloading update \([0-9,]+ of [0-9,]+ KB\)' | sed -u 's/,//g' >&2 ) &
echo "== x86-64 client: ubuntu12 $(x64_manifest_version ubuntu12), steamrt64 $(x64_manifest_version steamrt64) (the client may update itself)" >&2
echo "== x86-64 client: steamrt64 $(x64_manifest_version steamrt64) (the client may update itself)" >&2
x64_webhelper_gpu && { x64_gpu_watch >&2 & }
exec "${BL_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@"
}
@@ -952,6 +952,76 @@ arm, x64, arm_reg, x64_reg = sys.argv[1:5]
FILES = ("config/loginusers.vdf", "local.vdf")
def read(path):
try:
return open(path, encoding="utf-8", errors="surrogateescape").read()
except OSError:
return None
def write(path, text):
open(path, "w", encoding="utf-8", errors="surrogateescape").write(text)
def block(text, name):
m = re.search(r'"%s"\s*\{' % name, text)
if not m:
return None
depth, k = 1, m.end()
while depth and k < len(text):
depth += text[k] == "{"
depth -= text[k] == "}"
k += 1
return m, k
def accounts(root):
text = read(os.path.join(root, "config/config.vdf")) or ""
found = block(text, "Accounts")
if not found:
return {}
return dict(re.findall(r'"([^"]+)"\s*\{\s*"SteamID"\s*"(\d+)"', text[found[0].end():found[1]]))
def add_accounts(root, wanted):
path = os.path.join(root, "config/config.vdf")
text = read(path)
if text is None:
return
have = accounts(root)
missing = {name: sid for name, sid in wanted.items() if name not in have}
if not missing:
return
entries = "".join('\n\t\t\t\t\t"%s"\n\t\t\t\t\t{\n\t\t\t\t\t\t"SteamID"\t\t"%s"\n\t\t\t\t\t}' % item for item in missing.items())
found = block(text, "Accounts")
if found:
text = text[:found[0].end()] + entries + text[found[0].end():]
else:
steam = re.search(r'"Valve"\s*\{\s*"Steam"\s*\{', text)
if not steam:
return
text = text[:steam.end()] + '\n\t\t\t\t"Accounts"\n\t\t\t\t{' + entries + '\n\t\t\t\t}' + text[steam.end():]
write(path, text)
def set_keys(src_reg, dst_reg, force):
st, dt = read(src_reg), read(dst_reg)
if st is None or dt is None:
return
for key in ("AutoLoginUser", "RememberPassword"):
v = re.search(r'"%s"\s*"([^"]*)"' % key, st)
if not v:
continue
if re.search(r'"%s"\s*"' % key, dt):
if force:
dt = re.sub(r'("%s"\s*")[^"]*(")' % key, lambda m: m.group(1) + v.group(1) + m.group(2), dt, count=1)
continue
hkcu = re.search(r'"HKCU"\s*\{\s*"Software"\s*\{\s*"Valve"\s*\{\s*"Steam"\s*\{\n', dt)
if hkcu:
dt = dt[:hkcu.end()] + '\t\t\t\t\t"%s"\t\t"%s"\n' % (key, v.group(1)) + dt[hkcu.end():]
write(dst_reg, dt)
def stamp(root):
if not all(os.path.isfile(os.path.join(root, f)) for f in FILES):
return None
@@ -963,31 +1033,26 @@ def stamp(root):
a, x = stamp(arm), stamp(x64)
if a is None and x is None:
sys.exit(0)
if a is not None and x is not None and abs(a - x) < 1:
sys.exit(0)
if x is None or (a is not None and a > x):
src, dst, sreg, dreg, who = arm, x64, arm_reg, x64_reg, "arm64"
else:
src, dst, sreg, dreg, who = x64, arm, x64_reg, arm_reg, "x86-64"
for f in FILES:
os.makedirs(os.path.dirname(os.path.join(dst, f)), exist_ok=True)
# copy2 keeps the time stamp, so both match until one client signs in again.
shutil.copy2(os.path.join(src, f), os.path.join(dst, f))
if os.path.isfile(sreg):
st = open(sreg, encoding="utf-8", errors="surrogateescape").read()
if not os.path.isfile(dreg):
os.makedirs(os.path.dirname(dreg), exist_ok=True)
shutil.copy2(sreg, dreg)
if a is not None or x is not None:
if x is None or (a is not None and a > x):
src, dst, sreg, dreg, who = arm, x64, arm_reg, x64_reg, "arm64"
else:
dt = open(dreg, encoding="utf-8", errors="surrogateescape").read()
for key in ("AutoLoginUser", "RememberPassword"):
v = re.search(r'"%s"\s*"([^"]*)"' % key, st)
if v and re.search(r'"%s"\s*"' % key, dt):
dt = re.sub(r'("%s"\s*")[^"]*(")' % key, lambda m: m.group(1) + v.group(1) + m.group(2), dt, count=1)
open(dreg, "w", encoding="utf-8", errors="surrogateescape").write(dt)
print("droiddeck-steam-x64: sign-in shared from the %s client (the newer one)" % who)
src, dst, sreg, dreg, who = x64, arm, x64_reg, arm_reg, "x86-64"
copy = a is None or x is None or abs(a - x) >= 1
if copy:
for f in FILES:
os.makedirs(os.path.dirname(os.path.join(dst, f)), exist_ok=True)
# copy2 keeps the time stamp, so both match until one client signs in again.
shutil.copy2(os.path.join(src, f), os.path.join(dst, f))
if os.path.isfile(sreg) and not os.path.isfile(dreg):
os.makedirs(os.path.dirname(dreg), exist_ok=True)
shutil.copy2(sreg, dreg)
set_keys(sreg, dreg, copy)
set_keys(dreg, sreg, False)
add_accounts(dst, accounts(src))
add_accounts(src, accounts(dst))
if copy:
print("droiddeck-steam-x64: sign-in shared from the %s client (the newer one)" % who)
PY
}
@@ -41,6 +41,22 @@ configure_graphics() {
esac
}
# Any OpenXR probe (Steam runs one through Proton at every client start) starts vrserver
# while a runtime is registered, so SteamVR is registered only during a DroidDeck VR session.
unregister() {
if grep -qF "\"$steamvr\"" "$HOME/.config/openvr/openvrpaths.vrpath" 2>/dev/null; then
rm -f "$HOME/.config/openvr/openvrpaths.vrpath"
fi
case "$(readlink "$HOME/.config/openxr/1/active_runtime.json" 2>/dev/null)" in
"$steamvr"/*) rm -f "$HOME/.config/openxr/1/active_runtime.json" ;;
esac
}
idle() {
[ ! -f "$state/active" ] && ! running && ! pgrep -x vrstartup >/dev/null 2>&1 &&
( flock -n 9 ) 9>"$state/start.lock"
}
stop() {
rm -f "$state/active"
for n in vrcompositor vrserver vrmonitor vrdashboard vrstartup vrwebhelper; do
@@ -56,6 +72,7 @@ stop() {
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
sleep 0.1
done
unregister
quest_settings restore
}
@@ -74,6 +91,7 @@ status)
i=0; installed && i=1
r=0; running && r=1
if [ "$r" = 0 ] && [ -n "$(find "$state/active" -mmin +2 2>/dev/null)" ]; then rm -f "$state/active"; fi
if idle; then unregister; fi
n=0; [ -f "$state/installing" ] && n=1
d=0; [ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] && [ -f "$layer/libVkLayer_droiddeck_vr.so" ] && d=1
echo "installed=$i running=$r installing=$n driver=$d"
@@ -100,6 +118,9 @@ install)
stop)
stop || exit 1
;;
unregister)
if idle; then unregister; fi
;;
start)
exec 9>"$state/start.lock"
flock -n 9 || { echo "SteamVR start already in progress"; exit 0; }
@@ -234,7 +255,7 @@ JSON
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
;;
*)
echo "usage: droiddeck-steamvr status|install|start|stop|launch" >&2
echo "usage: droiddeck-steamvr status|install|start|stop|launch|unregister" >&2
exit 2
;;
esac
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Exit 0 when this game run should open as a SteamVR panel: SteamVR is running and Steam
# lists no VR support for the app, optional or required. Under SteamVR, Steam stacks a flat game's window behind
# its own, so without the panel the game plays unseen.
[ "${1:-}" = waitforexitandrun ] || exit 1
[ -z "${DROIDDECK_STEAMVR_PANEL:-}" ] || exit 1
# Non-Steam shortcuts run with SteamAppId=0 and their CGameID in SteamGameId.
app=${SteamAppId:-}
[ "$app" = 0 ] && app=${SteamGameId:-}
case $app in '' | 0 | *[!0-9]*) exit 1 ;; esac
pgrep -x vrserver >/dev/null 2>&1 || exit 1
/usr/local/bin/droiddeck-agent --steam-supports-vr "$app" >/dev/null 2>&1
[ $? -eq 5 ]
@@ -6,6 +6,8 @@ pgrep -x vrserver >/dev/null 2>&1 || {
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
exit 1
}
# droiddeck-steamvr-flat skips a run that a launch option already wrapped.
export DROIDDECK_STEAMVR_PANEL=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}"
@@ -28,8 +28,11 @@ build wrote is removed - with it the game exited while loading.
droiddeck-store-launch <the arguments Steam gave the compat tool>
"""
import base64
import binascii
import json
import os
import re
import sys
import time
import subprocess
@@ -268,6 +271,23 @@ def provision_prefix(compat_data, wait=SERVER_WAIT):
return state + (" server-running" if busy else "")
def create_prefix(compat_data, proton, timeout=120):
if not compat_data or not proton or not Path(proton).is_file():
return "no-proton"
reg = Path(compat_data) / "pfx/user.reg"
if reg.is_file():
return "present"
try:
Path(compat_data).mkdir(parents=True, exist_ok=True)
subprocess.run([proton, "run", "cmd.exe", "/d", "/c", "exit"], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
except subprocess.TimeoutExpired:
return "timeout"
except OSError:
return "failed"
return "created" if reg.is_file() else "failed"
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
STORE_GAME = 10
@@ -364,6 +384,123 @@ def prepare_gog(sidecar, compat_data, launch_dir):
return state == "ready"
GOG_SCRIPTS = "goggame-*.script"
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
WINE_USER = "C:\\users\\steamuser"
def gog_paths(folder, product):
app = windows_path(str(folder))
support = app + "\\support\\" + product
return {"app": app, "productid": product, "support": support, "supportdir": support,
"localappdata": WINE_USER + "\\AppData\\Local", "userdocs": WINE_USER + "\\Documents"}
def gog_expand(text, paths):
return re.sub(r"\{([A-Za-z]+)\}", lambda m: paths[m.group(1).lower()], text)
def gog_number(data):
if isinstance(data, bool):
raise ValueError
if isinstance(data, int):
return data
text = str(data).strip()
try:
return int(text, 0)
except ValueError:
return int(text, 10)
def gog_value(kind, data):
kind = str(kind).lower()
if kind == "string":
text = str(data)
if any(c in text for c in "\r\n\0"):
return None
return '"%s"' % reg_escape(text)
if kind == "dword":
return "dword:%08x" % (gog_number(data) & 0xFFFFFFFF)
if kind == "binary":
return "hex:" + ",".join("%02x" % b for b in base64.b64decode(str(data), validate=True))
return None
def gog_entry(arguments, paths):
if not isinstance(arguments, dict):
return None
try:
root = GOG_ROOTS.get(str(arguments.get("root") or "").upper())
subkey = gog_expand(str(arguments.get("subkey") or ""), paths).strip("\\")
if root is None or not subkey or any(c in subkey for c in "\r\n\0"):
return None
section = "[%s\\%s]" % (root, subkey)
if not arguments.get("valueType"):
return section
data = arguments.get("valueData")
value = gog_value(arguments["valueType"], gog_expand(data, paths) if isinstance(data, str) else data)
name = gog_expand(str(arguments.get("valueName") or ""), paths)
if value is None or any(c in name for c in "\r\n\0"):
return None
return section + "\r\n" + ('"%s"' % reg_escape(name) if name else "@") + "=" + value
except (KeyError, ValueError, TypeError, binascii.Error):
return None
def gog_registry(folder):
entries, skipped = [], 0
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
try:
actions = json.loads(script.read_text(encoding="utf-8-sig")).get("actions")
except (OSError, ValueError, AttributeError):
continue
paths = gog_paths(folder, product)
for action in actions if isinstance(actions, list) else []:
install = action.get("install") if isinstance(action, dict) else None
if not isinstance(install, dict) or install.get("action") != "setRegistry":
continue
entry = gog_entry(install.get("arguments"), paths)
if entry is None:
skipped += 1
else:
entries.append(entry)
return entries, skipped
def apply_gog_registry(folder, compat_data, proton, timeout=90):
entries, skipped = gog_registry(folder)
note = " skipped=%d" % skipped if skipped else ""
if not entries:
return "none" + note
if not compat_data or not proton or not Path(proton).is_file():
return "no-proton" + note
text = "Windows Registry Editor Version 5.00\r\n\r\n" + "".join(entry + "\r\n\r\n" for entry in entries)
stamp = hashlib.sha256(text.encode("utf-8")).hexdigest()
pfx = Path(compat_data) / "pfx"
marker = pfx / GOG_REGISTRY_MARK
try:
if marker.is_file() and marker.read_text() == stamp and (pfx / "system.reg").is_file():
return "ready" + note
Path(compat_data).mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
source = Path(tmp) / "registry.reg"
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
if run.returncode or not (pfx / "system.reg").is_file():
return "import-failed" + note
marker.write_text(stamp)
return "written=%d%s" % (len(entries), note)
except subprocess.TimeoutExpired:
return "timeout" + note
except OSError:
return "import-failed" + note
def main(argv):
if argv and argv[0] == "--exited":
rest, code = argv[1:], 0
@@ -382,8 +519,13 @@ def main(argv):
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
if launch_dir and cloud_on(sidecar):
made = create_prefix(compat_data, os.environ.get("BL_STORE_PROTON", ""))
if made != "present":
log("cloud %s %s prefix=%s" % (store, game, made))
if store == "gog":
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
if store == "epic":
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/python3
"""Licensed Xbox launches through Xodus and the game's selected ARM64 Proton."""
import hmac
import json
import os
from pathlib import Path
import runpy
import secrets
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
BIN = Path(__file__).resolve().parent
RUNTIME = Path('/usr/local/lib/droiddeck-xbox')
DLLS = ('xgameruntime.dll', 'winhttp.dll', 'windows.web.dll', 'twinapi.appcore.dll', 'libnghttp2.dll')
def bridge(upstream):
key = secrets.token_hex(32).encode('ascii')
server = socket.socket()
server.bind(('127.0.0.1', 0))
server.listen(16)
clients = set()
lock = threading.Lock()
stopped = threading.Event()
def forward(source, target):
try:
while not stopped.is_set():
data = source.recv(65536)
if not data:
break
target.sendall(data)
except OSError:
pass
finally:
try:
target.shutdown(socket.SHUT_WR)
except OSError:
pass
def connect(client):
remote = None
try:
client.settimeout(10)
supplied = b''
while len(supplied) < len(key):
part = client.recv(len(key) - len(supplied))
if not part:
return
supplied += part
if not hmac.compare_digest(supplied, key):
return
remote = socket.socket(socket.AF_UNIX)
remote.connect(upstream)
client.settimeout(None)
with lock:
clients.add(remote)
writer = threading.Thread(target=forward, args=(client, remote), daemon=True)
writer.start()
forward(remote, client)
writer.join(2)
except OSError:
pass
finally:
for sock in (client, remote):
if sock is not None:
with lock:
clients.discard(sock)
sock.close()
def accept():
while not stopped.is_set():
try:
client, _ = server.accept()
except OSError:
break
with lock:
if len(clients) >= 64:
client.close()
continue
clients.add(client)
threading.Thread(target=connect, args=(client,), daemon=True).start()
threading.Thread(target=accept, daemon=True).start()
def close():
stopped.set()
server.close()
with lock:
for client in clients:
try:
client.shutdown(socket.SHUT_RDWR)
except OSError:
pass
client.close()
clients.clear()
return server.getsockname()[1], key.decode('ascii'), close
def wine(argv, source_env=None):
source_env = os.environ if source_env is None else source_env
with open(source_env['DROIDDECK_XBOX_COMMAND_FILE'], encoding='utf-8') as file:
command = json.load(file)
if len(command) < 3 or command[1] != 'waitforexitandrun' or len(argv) != 1:
raise ValueError('Invalid Xbox Proton invocation')
env = dict(source_env)
env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
env.pop('DROIDDECK_XBOX_COMMAND_FILE', None)
prefix = Path(source_env['STEAM_COMPAT_DATA_PATH']) / 'pfx'
prefix.parent.mkdir(parents=True, exist_ok=True)
if not (prefix / 'system.reg').is_file():
result = subprocess.run([command[0], 'run', 'cmd', '/c', 'exit', '0'], stdout=sys.stderr, env=env)
if result.returncode:
return result.returncode
system = prefix / 'drive_c/windows/system32'
system.mkdir(parents=True, exist_ok=True)
for name in DLLS:
target = system / name
if target.is_symlink():
target.unlink()
shutil.copyfile(RUNTIME / 'windows' / name, target)
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
return subprocess.call([*command[:2], argv[0], *command[3:]], env=env)
def renew_lease(ask, channel, product, lease, stopped):
while not stopped.wait(15):
response = ask(channel, {'op': 'xbox-renew', 'id': product, 'lease': lease}, timeout=10)
if response is not None and response.get('ok') is False:
return
def launch(command, env):
if len(command) < 3 or command[1] != 'waitforexitandrun' or env.get('DROIDDECK_XBOX_ACTIVE') == '1':
return None
try:
store = runpy.run_path(str(BIN / 'droiddeck-store-launch'))
except Exception as error:
print('droiddeck-xbox: store detection unavailable (%s); stock launch' % error, file=sys.stderr)
return None
found = store['find_store_game'](command[2:])
if found is None or found[1].get('store') != 'xbox':
return None
folder, sidecar = found
for name in DLLS:
if not (RUNTIME / 'windows' / name).is_file():
raise RuntimeError('Xbox Windows runtime is missing; update the Linux runtime')
launch_dir = env.get('BL_LAUNCH_DIR')
if not launch_dir:
raise RuntimeError('No Xbox account channel; start the game from DroidDeck')
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190)
if not reply or not reply.get('ok'):
raise RuntimeError('Xbox account service is unavailable; sign in again and retry')
stopped = threading.Event()
close = lambda: None
try:
port, key, close = bridge(reply['socket'])
threading.Thread(target=renew_lease, args=(store['ask'], Path(launch_dir) / 'stores',
sidecar['id'], reply['lease'], stopped), daemon=True).start()
with tempfile.TemporaryDirectory(prefix='droiddeck-xbox-') as temporary:
context = Path(temporary) / 'command.json'
context.write_text(json.dumps(command), encoding='utf-8')
context.chmod(0o600)
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
owned_env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
if reply.get('playfab'):
owned_env['XODUS_XSTS_PLAYFAB'] = reply['playfab']
content = folder / '.xbox-content'
roots = []
if content.is_dir():
for entry in content.iterdir():
try:
marker = json.loads((entry / '.droiddeck-content.json').read_text())
if marker.get('parent') == sidecar['id'] and marker.get('productId') == entry.name and not entry.is_symlink():
roots.append('Z:' + str(entry).replace('/', '\\'))
except (OSError, ValueError, TypeError):
pass
if roots:
owned_env['XODUS_CONTENT_ROOTS'] = ';'.join(roots)
return wine([reply['exe']], owned_env)
finally:
stopped.set()
close()
store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-released', 'lease': reply['lease']})
if __name__ == '__main__':
try:
sys.exit(wine(sys.argv[1:]))
except (OSError, ValueError, KeyError, RuntimeError):
print('droiddeck-xbox: Xbox launch failed; check your account, runtime and package.', file=sys.stderr)
sys.exit(1)
@@ -74,6 +74,9 @@ bl_store_launch() {
}
bl_run() {
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "${verb:-}"; then
set -- /usr/local/bin/droiddeck-steamvr-game "$@"
fi
if [ -n "${BL_STORE_EXIT:-}" ]; then
"$@"
rc=$?
@@ -243,6 +246,13 @@ bl_vacdiag() {
"""
BL_DIRECTAUDIO_SETUP = """
bl_is_steam_installscript_target() {
local target=${1:-}
local steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
local helper="$steam_root/legacycompat/iscriptevaluator.exe"
[ -f "$helper" ] && [[ -n "$target" && "$target" -ef "$helper" ]]
}
bl_directaudio() {
case "${verb:-}" in
run|waitforexitandrun|runinprefix) ;;
@@ -251,6 +261,17 @@ bl_directaudio() {
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
if bl_is_steam_installscript_target "${2:-}"; then
echo "droiddeck-proton: DirectAudio skipped for Steam's install-script evaluator" >&2
return 0
fi
streamer=$(cat "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-remote-play" 2>/dev/null)
if [ -n "$streamer" ] && kill -0 "$streamer" 2>/dev/null; then
WINE_AUDIO_DRIVER=pulse
export WINE_AUDIO_DRIVER
echo "droiddeck-proton: a Remote Play client is connected - game audio goes through PulseAudio so the stream carries it" >&2
return 0
fi
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
major=${version#wine-}
major=${major%%.*}
@@ -338,7 +359,7 @@ for name in %s; do
done
if [ -n "$depot" ]; then
bl_components "$depot"
bl_directaudio "$depot"
bl_directaudio "$depot" "$@"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
@@ -393,7 +414,7 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
esac
fi
bl_components "$here"
bl_directaudio "$here"
bl_directaudio "$here" "$@"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
@@ -445,7 +466,12 @@ verb=$1; shift
case $verb in
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
esac
exec /usr/local/bin/droiddeck-fex steam "$verb" "$@"
""" + BL_GAME_CPUS_SETUP + """
bl_game_cpus
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
fi
exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
"""
@@ -901,24 +927,33 @@ def fex_wanted_marker():
return os.path.join(os.environ.get("HOME", "/root"), ".config", "droiddeck", "fex-wanted")
def request_fex(steam_root, asked):
def request_app(steam_root, app):
import subprocess
client = os.path.join(steam_root, "steamrtarm64", "steam")
if not os.access(client, os.X_OK):
return []
try:
process = subprocess.Popen([client, "steam://install/%s" % app], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
except OSError:
return []
try:
process.wait(timeout=REQUEST_HANDOFF_SECONDS)
except subprocess.TimeoutExpired:
pass
return [app]
def request_fex(steam_root, asked):
client = os.path.join(steam_root, "steamrtarm64", "steam")
missing = fex_missing(steam_root)
if not os.access(client, os.X_OK) or any(app in asked for app in missing):
return []
for app in missing:
asked.add(app)
try:
process = subprocess.Popen([client, "steam://install/%s" % app], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
except OSError:
continue
try:
process.wait(timeout=REQUEST_HANDOFF_SECONDS)
except subprocess.TimeoutExpired:
pass
return [app]
requested = request_app(steam_root, app)
if requested:
return requested
return []
@@ -1022,6 +1057,16 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
return changes, kept
def picked_apps(state):
picked = state.get("picked", ())
return {app for app in picked if isinstance(app, str)} if isinstance(picked, list) else set()
def picked_after(current, changes):
return sorted(({app for app, tool in current.items() if tool} - set(changes) |
{app for app, tool in changes.items() if tool}) - {"0"}, key=app_order)
def followers(state, current):
if "auto" in state:
return state["auto"]
@@ -1267,6 +1312,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
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()}
for app in picked_apps(state) & set(native):
current.setdefault(app, "")
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices)
@@ -1277,6 +1324,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
write_changed(config_path, text)
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["picked"] = picked_after(current, changes)
state.pop("native", None)
state["tools"] = catalog
state.setdefault("default", default)
+6
View File
@@ -617,9 +617,13 @@ int shm_unlink(const char *name) {
return r;
}
int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
void *(*real)(void *, size_t, int, int, int, off_t), void **out) __attribute__((weak, visibility("hidden")));
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
void *p;
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, fs_real_mmap, &p)) return p;
p = fs_real_mmap(addr, len, prot, flags, fd, off);
if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap(addr, len, prot & ~PROT_EXEC, flags, fd, off);
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
@@ -629,6 +633,8 @@ void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off64_t off) {
void *p;
if (!fs_real_mmap64) fs_real_mmap64 = (void *(*)(void *, size_t, int, int, int, off64_t))dlsym(RTLD_NEXT, "mmap64");
if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, (void *(*)(void *, size_t, int, int, int, off_t))fs_real_mmap64, &p))
return p;
p = fs_real_mmap64(addr, len, prot, flags, fd, off);
if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap64(addr, len, prot & ~PROT_EXEC, flags, fd, off);
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
+54 -11
View File
@@ -406,6 +406,7 @@ 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_venc_ioctl(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")));
@@ -419,6 +420,7 @@ int ioctl(int fd, unsigned long request, ...) {
int rc;
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
if (bl_venc_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;
@@ -504,19 +506,55 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
}
}
static const char *denied_table(const char *path) {
static const char *const tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp" };
#define CARRIER_TABLE 5
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" };
static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])];
#define CARRIER_SLOTS 8
static struct { char path[64]; long long at; } carrier_denied[CARRIER_SLOTS];
static int denied_recently(int table, const char *path) {
if (table != CARRIER_TABLE) return fresh(&net_denied_at[table]);
int hit = 0;
pthread_mutex_lock(&link_lock);
for (int i = 0; i < CARRIER_SLOTS && !hit; i++) {
hit = strcmp(carrier_denied[i].path, path) == 0 && fresh(&carrier_denied[i].at);
}
pthread_mutex_unlock(&link_lock);
return hit;
}
static void remember_denial(int table, const char *path) {
if (table != CARRIER_TABLE) {
__atomic_store_n(&net_denied_at[table], now_ns(), __ATOMIC_RELAXED);
return;
}
if (strlen(path) >= sizeof(carrier_denied[0].path)) return;
pthread_mutex_lock(&link_lock);
int slot = 0;
for (int i = 0; i < CARRIER_SLOTS; i++) {
if (strcmp(carrier_denied[i].path, path) == 0) { slot = i; break; }
if (carrier_denied[i].at < carrier_denied[slot].at) slot = i;
}
snprintf(carrier_denied[slot].path, sizeof(carrier_denied[slot].path), "%s", path);
carrier_denied[slot].at = now_ns();
pthread_mutex_unlock(&link_lock);
}
static int denied_table(const char *path) {
if (strncmp(path, "/proc/net/", 10) == 0) {
for (size_t i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
if (strcmp(path + 10, tables[i]) == 0) return tables[i];
for (int i = 0; i < CARRIER_TABLE; i++) {
if (strcmp(path + 10, net_tables[i]) == 0) return i;
}
return NULL;
return -1;
}
size_t len = strlen(path);
if (strncmp(path, "/sys/class/net/", 15) == 0 && len > 8 && strcmp(path + len - 8, "/carrier") == 0) {
return "carrier";
return CARRIER_TABLE;
}
return NULL;
return -1;
}
static FILE *synthesize(const char *table) {
@@ -548,11 +586,16 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
if (copy == NULL) close(status);
return copy;
}
FILE *f = real(path, mode);
if (f || path == NULL || mode == NULL || mode[0] != 'r') return f;
int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1;
FILE *f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f;
f = real(path, mode);
if (f || table < 0) return f;
int saved = errno;
const char *table = denied_table(path);
if (table && (f = synthesize(table)) != NULL) return f;
if ((f = synthesize(net_tables[table])) != NULL) {
if (saved == EACCES) remember_denial(table, path);
return f;
}
errno = saved;
return NULL;
}
+2
View File
@@ -1253,9 +1253,11 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
}
void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
void bl_venc_closed(int fd) __attribute__((visibility("hidden")));
int close(int fd) {
if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd);
bl_venc_closed(fd);
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd);
return ns_close_fd(fd);
+3
View File
@@ -14,6 +14,7 @@
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
@@ -53,6 +54,7 @@ int open(const char *path, int flags, ...) {
}
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
if (real_open == NULL) {
errno = ENOSYS;
@@ -78,6 +80,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
}
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
if (real_openat == NULL) {
errno = ENOSYS;
+71 -7
View File
@@ -3,6 +3,7 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <link.h>
#include <linux/futex.h>
#include <linux/magic.h>
#include <pthread.h>
@@ -28,9 +29,11 @@
#ifdef SYS_newfstatat
#define BL_SYS_FSTATAT SYS_newfstatat
#define BL_FSTATAT_NAME "fstatat"
typedef struct stat bl_stat;
#else
#define BL_SYS_FSTATAT SYS_fstatat64
#define BL_FSTATAT_NAME "fstatat64"
typedef struct stat64 bl_stat;
#endif
@@ -43,6 +46,51 @@ struct bl_open_how {
static long (*real_syscall)(long, ...);
static void *(*real_dlopen)(const char *, int);
static int openat2_missing;
static int (*next_fstatat)(int, const char *, bl_stat *, int);
static int (*next_openat)(int, const char *, int, ...);
static ssize_t (*next_readlinkat)(int, const char *, char *, size_t);
static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) {
(void)size;
const char *slash = strrchr(info->dlpi_name, '/');
if (!slash || strcmp(slash + 1, "libblfastpath.so") != 0 || strlen(info->dlpi_name) >= PATH_MAX) {
return 0;
}
strcpy(name, info->dlpi_name);
return 1;
}
__attribute__((constructor)) static void find_fastpath_calls(void) {
char name[PATH_MAX] = "";
dl_iterate_phdr(find_fastpath, name);
void *fastpath = *name ? dlopen(name, RTLD_NOLOAD | RTLD_LAZY) : NULL;
if (fastpath) {
next_fstatat = (int (*)(int, const char *, bl_stat *, int))dlsym(fastpath, BL_FSTATAT_NAME);
next_openat = (int (*)(int, const char *, int, ...))dlsym(fastpath, "openat");
next_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(fastpath, "readlinkat");
}
}
static long path_stat(int dirfd, const char *path, bl_stat *st, int flags) {
if (!next_fstatat) {
return real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)path, (long)st, (long)flags);
}
return next_fstatat(dirfd, path, st, flags);
}
static long path_open(int dirfd, const char *path, int flags, long mode) {
if (!next_openat) {
return real_syscall(SYS_openat, (long)dirfd, (long)path, (long)flags, mode);
}
return next_openat(dirfd, path, flags, (mode_t)mode);
}
static long path_readlink(int dirfd, const char *path, char *buf, size_t size) {
if (!next_readlinkat) {
return real_syscall(SYS_readlinkat, (long)dirfd, (long)path, (long)buf, (long)size);
}
return next_readlinkat(dirfd, path, buf, size);
}
void *dlopen(const char *filename, int flags) {
if (!real_dlopen) {
@@ -93,7 +141,7 @@ static struct robust_list_head *thread_robust_head(void) {
// 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);
int fd = (int)path_open(dirfd, link, O_PATH | O_NOFOLLOW | O_CLOEXEC, 0L);
if (fd < 0) {
return 0;
}
@@ -106,7 +154,7 @@ static int is_magic_link(int dirfd, char *link, size_t parent_len) {
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);
long result = path_stat(dirfd, (parent_len ? link : "."), &parent, 0);
link[parent_len] = saved;
return result != 0 || parent.st_ino != BL_PROC_ROOT_INO;
}
@@ -167,7 +215,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
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;
long stat_result = follow ? path_stat(dirfd, resolved, &st, AT_SYMLINK_NOFOLLOW) : -1;
if (stat_result == 0 && S_ISLNK(st.st_mode)) {
if (++symlinks > BL_MAX_SYMLINKS) {
errno = ELOOP;
@@ -176,7 +224,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
if (!have_root) {
bl_stat root;
struct statfs root_fs;
if (real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)".", (long)&root, 0L) != 0) {
if (path_stat(dirfd, ".", &root, 0) != 0) {
return -1;
}
root_dev = root.st_dev;
@@ -195,7 +243,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
}
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));
long target_len = path_readlink(dirfd, resolved, pending, PATH_MAX - rest_len);
if (target_len <= 0) {
if (target_len == 0) {
errno = ENOENT;
@@ -208,6 +256,19 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
}
memmove(pending + target_len, tail, rest_len + 1);
if (pending[0] == '/') {
char saved = pending[target_len];
pending[target_len] = 0;
const char *inside = pending;
while (*inside == '/') {
inside++;
}
bl_stat probe;
int host = *inside && path_stat(dirfd, inside, &probe, AT_SYMLINK_NOFOLLOW) != 0 &&
errno == ENOENT && path_stat(AT_FDCWD, pending, &probe, 0) == 0;
pending[target_len] = saved;
if (host) {
return path_open(AT_FDCWD, pending, flags, mode);
}
resolved_len = 0;
}
rest = pending;
@@ -233,7 +294,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
resolved[resolved_len++] = '.';
}
resolved[resolved_len] = 0;
return real_syscall(SYS_openat, (long)dirfd, (long)resolved, (long)flags, mode);
return path_open(dirfd, resolved, flags, mode);
}
static long openat2_via_openat(const long *args) {
@@ -257,7 +318,7 @@ static long openat2_via_openat(const long *args) {
errno = EXDEV;
return -1;
}
return real_syscall(SYS_openat, args[0], (long)path, (long)(int)how->flags, (long)how->mode);
return path_open((int)args[0], path, (int)how->flags, (long)how->mode);
}
static int execveat_is_execve(const long *args) {
@@ -303,6 +364,9 @@ long syscall(long number, ...) {
}
return openat2_via_openat(args);
}
if (number == SYS_openat) {
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
}
if (number == SYS_execveat && execveat_is_execve(args)) {
return real_syscall(SYS_execve, args[1], args[2], args[3]);
}
+89
View File
@@ -0,0 +1,89 @@
/* Steam's Linux Remote Play host has no touch injection: client touches arrive as an XTest mouse (absolute
* motion plus button 1). While a stream holds the encoder, those become touches into gamescope's own touch
* input, as a finger on the device screen would. */
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "../../../app/src/main/cpp/venc/venc_proto.h"
int bl_venc_streaming(void) __attribute__((visibility("hidden")));
int bl_venc_connect(void) __attribute__((visibility("hidden")));
static pthread_mutex_t rt_lock = PTHREAD_MUTEX_INITIALIZER;
static int rt_fd = -1, rt_down, rt_x, rt_y, rt_screen;
static int rt_enabled(void) {
static int enabled = -1;
if (enabled < 0) {
const char *v = getenv("BL_REMOTE_TOUCH");
enabled = v == NULL || strcmp(v, "0") != 0;
}
return enabled && bl_venc_streaming();
}
static uint32_t rt_fraction(int value, int extent) {
if (extent <= 1 || value <= 0) return 0;
if (value >= extent - 1) return 65535;
return (uint32_t)((int64_t)value * 65535 / (extent - 1));
}
static void rt_send(void *dpy, uint32_t action) {
static int (*width)(void *, int), (*height)(void *, int);
if (!width) width = (int (*)(void *, int))dlsym(RTLD_DEFAULT, "XDisplayWidth");
if (!height) height = (int (*)(void *, int))dlsym(RTLD_DEFAULT, "XDisplayHeight");
if (!width || !height) return;
struct venc_touch m = {
.type = VENC_TOUCH, .action = action,
.x = rt_fraction(rt_x, width(dpy, rt_screen)), .y = rt_fraction(rt_y, height(dpy, rt_screen)),
};
for (int attempt = 0; attempt < 2; attempt++) {
if (rt_fd < 0) rt_fd = bl_venc_connect();
if (rt_fd < 0) return;
if (send(rt_fd, &m, sizeof m, MSG_NOSIGNAL) == (ssize_t)sizeof m) return;
close(rt_fd);
rt_fd = -1;
}
}
int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay) {
static int (*real)(void *, int, int, int, unsigned long);
if (!real) real = (int (*)(void *, int, int, int, unsigned long))dlsym(RTLD_NEXT, "XTestFakeMotionEvent");
if (rt_enabled()) {
pthread_mutex_lock(&rt_lock);
rt_x = x;
rt_y = y;
rt_screen = screen < 0 ? 0 : screen;
int down = rt_down;
if (down) rt_send(dpy, VENC_TOUCH_MOVE);
pthread_mutex_unlock(&rt_lock);
if (down) return 1;
}
return real ? real(dpy, screen, x, y, delay) : 0;
}
int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay) {
static int (*real)(void *, unsigned int, int, unsigned long);
if (!real) real = (int (*)(void *, unsigned int, int, unsigned long))dlsym(RTLD_NEXT, "XTestFakeButtonEvent");
if (button == 1) {
pthread_mutex_lock(&rt_lock);
int handled = 0;
if (press && rt_enabled()) {
rt_down = 1;
rt_send(dpy, VENC_TOUCH_DOWN);
handled = 1;
} else if (!press && rt_down) {
rt_down = 0;
rt_send(dpy, VENC_TOUCH_UP);
handled = 1;
}
pthread_mutex_unlock(&rt_lock);
if (handled) return 1;
}
return real ? real(dpy, button, press, delay) : 0;
}
+81 -10
View File
@@ -403,6 +403,9 @@ struct msg_queue {
struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS];
};
struct msg_map { int id; int refs; struct msg_queue *q; };
static struct msg_map g_msgs[MAX_OBJECTS];
static struct msg_queue *msg_map(int id) {
int fd = open_by_id("msg", id);
if (fd < 0) return NULL;
@@ -415,6 +418,47 @@ static struct msg_queue *msg_map(int id) {
return NULL;
}
static int msg_removed(struct msg_queue *q) { return __atomic_load_n(&q->magic, __ATOMIC_ACQUIRE) != MSG_MAGIC; }
static struct msg_map *msg_get(int id) {
struct msg_map *found = NULL, *spare = NULL, *idle = NULL;
pthread_mutex_lock(&g_lock);
for (int i = 0; i < MAX_OBJECTS; i++) {
struct msg_map *e = &g_msgs[i];
if (e->q && !e->refs && msg_removed(e->q)) {
munmap(e->q, sizeof(*e->q));
e->q = NULL;
}
if (!e->q) {
if (!spare) spare = e;
} else if (e->id == id && !msg_removed(e->q)) {
found = e;
} else if (!e->refs && !idle) {
idle = e;
}
}
if (!found && !spare && idle) {
munmap(idle->q, sizeof(*idle->q));
idle->q = NULL;
spare = idle;
}
if (!found && spare && (spare->q = msg_map(id))) {
spare->id = id;
found = spare;
} else if (!found && !spare) {
errno = ENOSPC;
}
if (found) found->refs++;
pthread_mutex_unlock(&g_lock);
return found;
}
static void msg_put(struct msg_map *m) {
pthread_mutex_lock(&g_lock);
m->refs--;
pthread_mutex_unlock(&g_lock);
}
static void msg_lock(struct msg_queue *q) {
for (int32_t owner = 0; !atomic_compare_exchange_strong(&q->lock, &owner, getpid()); owner = 0) {
if (kill(owner, 0) != 0 && errno == ESRCH) atomic_compare_exchange_strong(&q->lock, &owner, 0);
@@ -446,12 +490,19 @@ int msgget(key_t key, int msgflg) {
}
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
struct msg_queue *q = msg_map(msqid);
if (!q) return -1;
if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { munmap(q, sizeof(*q)); errno = EINVAL; return -1; }
struct msg_map *m = msg_get(msqid);
if (!m) return -1;
struct msg_queue *q = m->q;
if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { msg_put(m); errno = EINVAL; return -1; }
for (;;) {
msg_lock(q);
int32_t seen = atomic_load(&q->changed);
if (msg_removed(q)) {
msg_unlock(q, 0);
msg_put(m);
errno = EIDRM;
return -1;
}
for (int i = 0; i < MSG_SLOTS; i++) {
if (q->slot[i].seq) continue;
q->slot[i].mtype = *(const long *)msgp;
@@ -459,12 +510,12 @@ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
memcpy(q->slot[i].data, (const long *)msgp + 1, msgsz);
q->slot[i].seq = ++q->next_seq;
msg_unlock(q, 1);
munmap(q, sizeof(*q));
msg_put(m);
return 0;
}
msg_unlock(q, 0);
if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
munmap(q, sizeof(*q));
msg_put(m);
if (msgflg & IPC_NOWAIT) errno = EAGAIN;
return -1;
}
@@ -473,11 +524,18 @@ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
if (msgtyp < 0) { errno = EINVAL; return -1; }
struct msg_queue *q = msg_map(msqid);
if (!q) return -1;
struct msg_map *m = msg_get(msqid);
if (!m) return -1;
struct msg_queue *q = m->q;
for (;;) {
msg_lock(q);
int32_t seen = atomic_load(&q->changed);
if (msg_removed(q)) {
msg_unlock(q, 0);
msg_put(m);
errno = EIDRM;
return -1;
}
int best = -1;
for (int i = 0; i < MSG_SLOTS; i++)
if (q->slot[i].seq && (!msgtyp || q->slot[i].mtype == msgtyp) && (best < 0 || q->slot[i].seq < q->slot[best].seq))
@@ -488,12 +546,12 @@ ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
memcpy((long *)msgp + 1, q->slot[best].data, n);
q->slot[best].seq = 0;
msg_unlock(q, 1);
munmap(q, sizeof(*q));
msg_put(m);
return (ssize_t)n;
}
msg_unlock(q, 0);
if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
munmap(q, sizeof(*q));
msg_put(m);
if (msgflg & IPC_NOWAIT) errno = ENOMSG;
return -1;
}
@@ -502,15 +560,28 @@ ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
int msgctl(int msqid, int cmd, struct msqid_ds *buf) {
if (cmd != IPC_RMID) { errno = EINVAL; return -1; }
struct msg_queue *q = msg_map(msqid);
if (!q) return -1;
pthread_mutex_lock(&g_lock);
int rc = unlink_by_id("msg", msqid);
pthread_mutex_unlock(&g_lock);
int saved = errno;
if (rc == 0) {
__atomic_store_n(&q->magic, 0, __ATOMIC_SEQ_CST);
atomic_fetch_add(&q->changed, 1);
futex(&q->changed, FUTEX_WAKE, INT_MAX, NULL);
}
munmap(q, sizeof(*q));
errno = saved;
return rc;
}
static void sysv_lock_before_fork(void) { pthread_mutex_lock(&g_lock); }
static void sysv_unlock_after_fork(void) { pthread_mutex_unlock(&g_lock); }
static void sysv_reset_after_fork(void) { pthread_mutex_init(&g_lock, NULL); }
static void sysv_reset_after_fork(void) {
pthread_mutex_init(&g_lock, NULL);
for (int i = 0; i < MAX_OBJECTS; i++) g_msgs[i].refs = 0;
}
__attribute__((constructor)) static void install_sysv_fork_handlers(void) {
pthread_atfork(sysv_lock_before_fork, sysv_unlock_after_fork, sysv_reset_after_fork);
+28 -10
View File
@@ -22,15 +22,17 @@ static const char *skip_digits(const char *s) {
return end == s ? NULL : end;
}
static int is_status_path(const char *path) {
static long status_pid(const char *path) {
const char *rest;
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return 0;
long pid = 0;
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return -1;
path += 6;
if (strncmp(path, "self/", 5) == 0) rest = path + 4;
else if (strncmp(path, "thread-self/", 12) == 0) rest = path + 11;
else if ((rest = skip_digits(path)) == NULL) return 0;
if (strncmp(rest, "/task/", 6) == 0 && (rest = skip_digits(rest + 6)) == NULL) return 0;
return strcmp(rest, "/status") == 0;
else if ((rest = skip_digits(path)) == NULL) return -1;
else pid = strtol(path, NULL, 10);
if (strncmp(rest, "/task/", 6) == 0 && (rest = skip_digits(rest + 6)) == NULL) return -1;
return strcmp(rest, "/status") == 0 ? pid : -1;
}
static int is_web_helper(const void *caller) {
@@ -56,13 +58,26 @@ static int write_all(int fd, const char *data, size_t len) {
return 0;
}
static int read_only_copy(const char *data, size_t len, int flags) {
char path[] = "/tmp/.droiddeck-status-XXXXXX";
int rw = mkostemp(path, O_CLOEXEC);
if (rw < 0) return -1;
int ro = -1;
if (write_all(rw, data, len) == 0)
ro = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | (flags & O_CLOEXEC));
unlink(path);
close(rw);
return ro;
}
__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(caller)) return -1;
long pid;
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || 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 (;;) {
@@ -78,13 +93,16 @@ __attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *p
if (field == NULL) goto done;
char *value = field + strlen(TRACER_FIELD);
char *line_end = strchr(value, '\n');
if (line_end == NULL) goto done;
if (line_end == NULL || line_end == value) goto done;
memmove(value + 1, line_end, len - (size_t)(line_end - text) + 1);
*value = '0';
len = (size_t)(value + 1 - text) + strlen(value + 1);
if (pid != 0 && pid != getpid() && (out = read_only_copy(text, len, flags)) >= 0) goto done;
out = memfd_create("status", (flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
if (out < 0) goto done;
if (write_all(out, text, (size_t)(value - text)) != 0 || write_all(out, "0", 1) != 0
|| write_all(out, line_end, len - (size_t)(line_end - text)) != 0
|| lseek(out, 0, SEEK_SET) != 0) {
if (write_all(out, text, len) != 0 || lseek(out, 0, SEEK_SET) != 0) {
close(out);
out = -1;
}
+633
View File
@@ -0,0 +1,633 @@
/* /dev/video-enc0 for Steam's Remote Play V4L2 encoder stage, backed by the app's MediaCodec encoder. */
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include "../../../app/src/main/cpp/venc/venc_proto.h"
#ifndef V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR
#define V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR (V4L2_CID_MPEG_BASE + 644)
#endif
#define VENC_DEVICE "/dev/video-enc0"
#define VENC_INSTANCES 4
#define VENC_OFFSET_STEP 0x1000000L
#define VENC_CAPTURE_OFFSET (VENC_OFFSET_STEP * 64)
struct vq_buf {
int memfd;
uint32_t size;
};
struct vq_item {
uint32_t index, bytes, flags, sequence;
struct timeval timestamp;
};
struct vq {
struct vq_buf bufs[VENC_MAX_BUFFERS];
uint32_t count;
struct vq_item queued[VENC_MAX_BUFFERS], done[VENC_MAX_BUFFERS];
uint32_t nqueued, ndone;
int streaming;
};
struct venc {
int used, fd;
pid_t owner;
uint32_t width, height, stride, crop_w, crop_h, raw_size;
uint32_t coded_fourcc, coded_size;
uint32_t fps_num, fps_den;
uint32_t bitrate, peak, vbr, gop;
int32_t h264_profile, h264_level, hevc_profile;
int force_key, configured, sent_bitrate;
uint32_t sequence;
struct vq raw, coded;
};
static pthread_mutex_t vn_lock = PTHREAD_MUTEX_INITIALIZER;
static struct venc vn_all[VENC_INSTANCES];
static int vn_open_count;
static void vn_marker(int streaming) {
const char *dir = getenv("XDG_RUNTIME_DIR");
char path[512];
if (dir == NULL || snprintf(path, sizeof path, "%s/droiddeck-remote-play", dir) >= (int)sizeof path) return;
if (!streaming) {
unlink(path);
return;
}
FILE *f = fopen(path, "w");
if (f == NULL) return;
fprintf(f, "%d\n", (int)getpid());
fclose(f);
}
static void vn_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void vn_log(const char *fmt, ...) {
va_list ap;
char line[256];
va_start(ap, fmt);
int n = vsnprintf(line, sizeof line - 1, fmt, ap);
va_end(ap);
if (n < 0) return;
if (n > (int)sizeof line - 2) n = sizeof line - 2;
line[n++] = '\n';
if (write(2, "droiddeck-venc: ", 16) < 0 || write(2, line, n) < 0) return;
}
static struct venc *vn_find(int fd) {
if (fd < 0 || __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return NULL;
for (int i = 0; i < VENC_INSTANCES; i++) if (vn_all[i].used && vn_all[i].fd == fd) return &vn_all[i];
return NULL;
}
static int is_raw(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT || type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; }
static int is_coded(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_CAPTURE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; }
static int is_mplane(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; }
static struct vq *vn_queue(struct venc *v, uint32_t type) { return is_raw(type) ? &v->raw : is_coded(type) ? &v->coded : NULL; }
static void vn_sizes(struct venc *v) {
if (v->stride < v->width) v->stride = v->width;
v->raw_size = v->stride * v->height * 3 / 2;
uint32_t coded = v->width * v->height * 3 / 2;
if (coded < 512 * 1024) coded = 512 * 1024;
if (v->coded_size < coded) v->coded_size = coded;
}
static void vn_free_queue(struct vq *q) {
for (uint32_t i = 0; i < q->count; i++) if (q->bufs[i].memfd >= 0) close(q->bufs[i].memfd);
memset(q, 0, sizeof *q);
}
__attribute__((visibility("hidden"))) int bl_venc_streaming(void) {
return __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) > 0;
}
__attribute__((visibility("hidden"))) int bl_venc_connect(void);
int bl_venc_connect(void) {
const char *path = getenv("BL_VENC_SOCKET");
if (path == NULL || *path == '\0') return -1;
struct sockaddr_un addr = { .sun_family = AF_UNIX };
if (strlen(path) >= sizeof addr.sun_path) return -1;
strcpy(addr.sun_path, path);
int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (fd < 0) return -1;
if (connect(fd, (struct sockaddr *)&addr, sizeof addr) != 0) {
close(fd);
return -1;
}
struct timeval tv = { .tv_sec = 2 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
return fd;
}
__attribute__((visibility("hidden"))) int bl_venc_open(const char *path, int flags) {
(void)flags;
if (path == NULL || strcmp(path, VENC_DEVICE) != 0) return -2;
int fd = bl_venc_connect();
if (fd < 0) return -2;
pthread_mutex_lock(&vn_lock);
struct venc *v = NULL;
for (int i = 0; i < VENC_INSTANCES && v == NULL; i++) if (!vn_all[i].used) v = &vn_all[i];
if (v == NULL) {
pthread_mutex_unlock(&vn_lock);
close(fd);
errno = EBUSY;
return -1;
}
memset(v, 0, sizeof *v);
v->used = 1;
v->fd = fd;
v->owner = getpid();
v->width = v->crop_w = 1280;
v->height = v->crop_h = 720;
v->coded_fourcc = V4L2_PIX_FMT_H264;
v->fps_num = 1;
v->fps_den = 60;
v->bitrate = 20000000;
v->gop = 0xffff;
vn_sizes(v);
if (__atomic_add_fetch(&vn_open_count, 1, __ATOMIC_RELEASE) == 1) vn_marker(1);
pthread_mutex_unlock(&vn_lock);
vn_log("opened %s as fd %d (MediaCodec through the app)", path, fd);
return fd;
}
static int vn_send(struct venc *v, const void *msg, size_t len, const int *fds, int nfds) {
struct iovec iov = { .iov_base = (void *)msg, .iov_len = len };
char control[CMSG_SPACE(sizeof(int) * VENC_MAX_BUFFERS * 2)];
struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1 };
if (nfds > 0) {
memset(control, 0, sizeof control);
m.msg_control = control;
m.msg_controllen = CMSG_SPACE(sizeof(int) * nfds);
struct cmsghdr *c = CMSG_FIRSTHDR(&m);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_RIGHTS;
c->cmsg_len = CMSG_LEN(sizeof(int) * nfds);
memcpy(CMSG_DATA(c), fds, sizeof(int) * nfds);
}
return sendmsg(v->fd, &m, MSG_NOSIGNAL) == (ssize_t)len ? 0 : -1;
}
static int vn_configure(struct venc *v) {
struct venc_config c = {
.type = VENC_CONFIG,
.codec = v->coded_fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->crop_w, .height = v->crop_h, .stride = v->stride, .rows = v->height,
.fps_num = v->fps_num, .fps_den = v->fps_den,
.bitrate = v->bitrate, .peak_bitrate = v->peak, .vbr = v->vbr, .gop = v->gop,
.profile = v->coded_fourcc == V4L2_PIX_FMT_HEVC ? v->hevc_profile : v->h264_profile,
.level = v->h264_level,
.inputs = v->raw.count, .outputs = v->coded.count,
.input_size = v->raw_size, .output_size = v->coded_size,
};
int fds[VENC_MAX_BUFFERS * 2], n = 0;
for (uint32_t i = 0; i < v->raw.count; i++) fds[n++] = v->raw.bufs[i].memfd;
for (uint32_t i = 0; i < v->coded.count; i++) fds[n++] = v->coded.bufs[i].memfd;
if (vn_send(v, &c, sizeof c, fds, n) != 0) return -1;
struct venc_done d;
if (recv(v->fd, &d, sizeof d, 0) != (ssize_t)sizeof d || d.type != VENC_DONE || d.status != 0) {
vn_log("the app's encoder refused %ux%u %s", c.width, c.height, c.codec == VENC_HEVC ? "HEVC" : "H.264");
return -1;
}
vn_log("encoding %ux%u at %u/%u fps, %u kbit/s %s, %s", c.width, c.height, c.fps_den, c.fps_num,
c.bitrate / 1000, c.vbr ? "VBR" : "CBR", c.codec == VENC_HEVC ? "HEVC" : "H.264");
v->configured = 1;
v->sent_bitrate = (int)v->bitrate;
return 0;
}
static void vn_pump(struct venc *v) {
while (v->raw.streaming && v->coded.streaming && v->raw.nqueued > 0 && v->coded.nqueued > 0) {
struct vq_item in = v->raw.queued[0], out = v->coded.queued[0];
memmove(v->raw.queued, v->raw.queued + 1, --v->raw.nqueued * sizeof in);
memmove(v->coded.queued, v->coded.queued + 1, --v->coded.nqueued * sizeof out);
int ok = v->configured || vn_configure(v) == 0;
if (ok && v->sent_bitrate != (int)v->bitrate) {
struct venc_bitrate b = { .type = VENC_BITRATE, .bitrate = v->bitrate };
if (vn_send(v, &b, sizeof b, NULL, 0) == 0) v->sent_bitrate = (int)v->bitrate;
}
struct venc_frame f = {
.type = VENC_FRAME, .input = in.index, .output = out.index, .bytes = in.bytes,
.keyframe = (uint32_t)v->force_key,
.pts_us = (int64_t)in.timestamp.tv_sec * 1000000 + in.timestamp.tv_usec,
};
struct venc_done d = { 0 };
ok = ok && vn_send(v, &f, sizeof f, NULL, 0) == 0 &&
recv(v->fd, &d, sizeof d, 0) == (ssize_t)sizeof d && d.type == VENC_DONE && d.status == 0;
if (!ok) vn_log("frame %u was not encoded (%s)", v->sequence, strerror(errno));
v->force_key = 0;
in.flags = V4L2_BUF_FLAG_DONE;
out.bytes = ok ? d.bytes : 0;
out.flags = V4L2_BUF_FLAG_DONE | (ok ? (d.keyframe ? V4L2_BUF_FLAG_KEYFRAME : V4L2_BUF_FLAG_PFRAME) : V4L2_BUF_FLAG_ERROR);
out.timestamp = in.timestamp;
in.sequence = out.sequence = v->sequence++;
v->raw.done[v->raw.ndone++] = in;
v->coded.done[v->coded.ndone++] = out;
}
}
static void vn_fill_format(struct venc *v, struct v4l2_format *f) {
if (is_mplane(f->type)) {
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
memset(p, 0, sizeof *p);
p->width = v->width;
p->height = v->height;
p->field = V4L2_FIELD_NONE;
p->num_planes = 1;
p->colorspace = V4L2_COLORSPACE_REC709;
if (is_raw(f->type)) {
p->pixelformat = V4L2_PIX_FMT_NV12;
p->plane_fmt[0].bytesperline = v->stride;
p->plane_fmt[0].sizeimage = v->raw_size;
} else {
p->pixelformat = v->coded_fourcc;
p->plane_fmt[0].sizeimage = v->coded_size;
}
} else {
struct v4l2_pix_format *p = &f->fmt.pix;
memset(p, 0, sizeof *p);
p->width = v->width;
p->height = v->height;
p->field = V4L2_FIELD_NONE;
p->colorspace = V4L2_COLORSPACE_REC709;
p->pixelformat = is_raw(f->type) ? V4L2_PIX_FMT_NV12 : v->coded_fourcc;
p->bytesperline = is_raw(f->type) ? v->stride : 0;
p->sizeimage = is_raw(f->type) ? v->raw_size : v->coded_size;
}
}
static int vn_set_format(struct venc *v, struct v4l2_format *f, int apply) {
uint32_t w, h, fourcc, stride, size;
if (is_mplane(f->type)) {
w = f->fmt.pix_mp.width; h = f->fmt.pix_mp.height; fourcc = f->fmt.pix_mp.pixelformat;
stride = f->fmt.pix_mp.plane_fmt[0].bytesperline; size = f->fmt.pix_mp.plane_fmt[0].sizeimage;
} else if (is_raw(f->type) || is_coded(f->type)) {
w = f->fmt.pix.width; h = f->fmt.pix.height; fourcc = f->fmt.pix.pixelformat;
stride = f->fmt.pix.bytesperline; size = f->fmt.pix.sizeimage;
} else {
return -EINVAL;
}
struct venc t = *v;
if (w >= 64 && h >= 64 && w <= 4096 && h <= 4096) {
t.width = (w + 1) & ~1u;
t.height = (h + 1) & ~1u;
t.crop_w = t.width;
t.crop_h = t.height;
}
if (is_raw(f->type)) {
t.stride = stride;
} else {
t.coded_fourcc = fourcc == V4L2_PIX_FMT_HEVC ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264;
t.coded_size = size;
}
vn_sizes(&t);
if (apply) {
if (t.width != v->width || t.height != v->height || t.coded_fourcc != v->coded_fourcc) v->configured = 0;
*v = t;
}
vn_fill_format(&t, f);
return 0;
}
static int vn_reqbufs(struct venc *v, struct v4l2_requestbuffers *r) {
struct vq *q = vn_queue(v, r->type);
if (q == NULL) return -EINVAL;
if (r->memory != V4L2_MEMORY_MMAP) return -EINVAL;
vn_free_queue(q);
v->configured = 0;
uint32_t n = r->count > VENC_MAX_BUFFERS ? VENC_MAX_BUFFERS : r->count;
uint32_t size = is_raw(r->type) ? v->raw_size : v->coded_size;
for (uint32_t i = 0; i < n; i++) {
int fd = memfd_create("droiddeck-venc", MFD_CLOEXEC);
if (fd < 0 || ftruncate(fd, size) != 0) {
if (fd >= 0) close(fd);
vn_free_queue(q);
return -ENOMEM;
}
q->bufs[i].memfd = fd;
q->bufs[i].size = size;
q->count = i + 1;
}
r->count = n;
#ifdef V4L2_BUF_CAP_SUPPORTS_MMAP
r->capabilities = V4L2_BUF_CAP_SUPPORTS_MMAP;
#endif
return 0;
}
static long vn_offset(struct v4l2_buffer *b) {
return (is_raw(b->type) ? 0 : VENC_CAPTURE_OFFSET) + (long)(b->index + 1) * VENC_OFFSET_STEP;
}
static void vn_describe(struct venc *v, struct v4l2_buffer *b, const struct vq_item *item) {
struct vq *q = vn_queue(v, b->type);
uint32_t size = q->bufs[b->index].size;
b->memory = V4L2_MEMORY_MMAP;
b->field = V4L2_FIELD_NONE;
b->flags = V4L2_BUF_FLAG_MAPPED | (item ? item->flags : 0);
if (item) {
b->timestamp = item->timestamp;
b->sequence = item->sequence;
}
if (is_mplane(b->type)) {
if (b->m.planes == NULL || b->length < 1) return;
b->length = 1;
b->m.planes[0].length = size;
b->m.planes[0].m.mem_offset = (uint32_t)vn_offset(b);
b->m.planes[0].data_offset = 0;
if (item) b->m.planes[0].bytesused = item->bytes;
} else {
b->length = size;
b->m.offset = (uint32_t)vn_offset(b);
if (item) b->bytesused = item->bytes;
}
}
static int vn_qbuf(struct venc *v, struct v4l2_buffer *b) {
struct vq *q = vn_queue(v, b->type);
if (q == NULL || b->index >= q->count || q->nqueued >= VENC_MAX_BUFFERS) return -EINVAL;
struct vq_item item = { .index = b->index, .timestamp = b->timestamp };
if (is_raw(b->type))
item.bytes = is_mplane(b->type) ? (b->m.planes && b->length ? b->m.planes[0].bytesused : 0) : b->bytesused;
if (item.bytes == 0 || item.bytes > q->bufs[b->index].size) item.bytes = q->bufs[b->index].size;
q->queued[q->nqueued++] = item;
vn_describe(v, b, NULL);
b->flags |= V4L2_BUF_FLAG_QUEUED;
vn_pump(v);
return 0;
}
static int vn_dqbuf(struct venc *v, struct v4l2_buffer *b) {
struct vq *q = vn_queue(v, b->type);
if (q == NULL) return -EINVAL;
if (q->ndone == 0) return -EAGAIN;
struct vq_item item = q->done[0];
memmove(q->done, q->done + 1, --q->ndone * sizeof item);
b->index = item.index;
vn_describe(v, b, &item);
return 0;
}
static void vn_set_control(struct venc *v, uint32_t id, int32_t value) {
switch (id) {
case V4L2_CID_MPEG_VIDEO_BITRATE: if (value > 0) v->bitrate = (uint32_t)value; break;
case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: if (value > 0) v->peak = (uint32_t)value; break;
case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: v->vbr = value == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_GOP_SIZE: v->gop = (uint32_t)value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_H264_PROFILE: v->h264_profile = value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_H264_LEVEL: v->h264_level = value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_HEVC_PROFILE: v->hevc_profile = value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME: v->force_key = 1; break;
default: break;
}
}
static int vn_get_control(struct venc *v, uint32_t id, int32_t *value) {
switch (id) {
case V4L2_CID_MPEG_VIDEO_BITRATE: *value = (int32_t)v->bitrate; return 0;
case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: *value = (int32_t)v->peak; return 0;
case V4L2_CID_MPEG_VIDEO_GOP_SIZE: *value = (int32_t)v->gop; return 0;
default: *value = 0; return 0;
}
}
static int vn_ioctl(struct venc *v, unsigned long req, void *arg) {
switch (req) {
case VIDIOC_QUERYCAP: {
struct v4l2_capability *c = arg;
memset(c, 0, sizeof *c);
strcpy((char *)c->driver, "droiddeck_venc");
strcpy((char *)c->card, "Android MediaCodec");
strcpy((char *)c->bus_info, "platform:droiddeck-venc");
c->version = 0x00060000;
c->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
c->capabilities = c->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
case VIDIOC_ENUM_FMT: {
struct v4l2_fmtdesc *d = arg;
static const uint32_t coded[] = { V4L2_PIX_FMT_H264, V4L2_PIX_FMT_HEVC };
if (is_raw(d->type) && d->index == 0) {
d->pixelformat = V4L2_PIX_FMT_NV12;
strcpy((char *)d->description, "Y/CbCr 4:2:0");
d->flags = 0;
} else if (is_coded(d->type) && d->index < 2) {
d->pixelformat = coded[d->index];
strcpy((char *)d->description, d->index ? "HEVC" : "H.264");
d->flags = V4L2_FMT_FLAG_COMPRESSED;
} else {
return -EINVAL;
}
return 0;
}
case VIDIOC_ENUM_FRAMESIZES: {
struct v4l2_frmsizeenum *s = arg;
if (s->index != 0) return -EINVAL;
s->type = V4L2_FRMSIZE_TYPE_STEPWISE;
s->stepwise = (struct v4l2_frmsize_stepwise){ 64, 4096, 2, 64, 4096, 2 };
return 0;
}
case VIDIOC_G_FMT: vn_fill_format(v, arg); return 0;
case VIDIOC_S_FMT: return vn_set_format(v, arg, 1);
case VIDIOC_TRY_FMT: return vn_set_format(v, arg, 0);
case VIDIOC_REQBUFS: return vn_reqbufs(v, arg);
case VIDIOC_QUERYBUF: {
struct v4l2_buffer *b = arg;
struct vq *q = vn_queue(v, b->type);
if (q == NULL || b->index >= q->count) return -EINVAL;
vn_describe(v, b, NULL);
return 0;
}
case VIDIOC_QBUF: return vn_qbuf(v, arg);
case VIDIOC_DQBUF: return vn_dqbuf(v, arg);
case VIDIOC_STREAMON:
case VIDIOC_STREAMOFF: {
struct vq *q = vn_queue(v, *(uint32_t *)arg);
if (q == NULL) return -EINVAL;
q->streaming = req == VIDIOC_STREAMON;
if (!q->streaming) q->nqueued = q->ndone = 0;
vn_pump(v);
return 0;
}
case VIDIOC_S_PARM:
case VIDIOC_G_PARM: {
struct v4l2_streamparm *p = arg;
if (!is_raw(p->type)) return req == VIDIOC_G_PARM ? 0 : -EINVAL;
struct v4l2_fract *t = &p->parm.output.timeperframe;
if (req == VIDIOC_S_PARM && t->numerator > 0 && t->denominator > 0) {
v->fps_num = t->numerator;
v->fps_den = t->denominator;
v->configured = 0;
}
p->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
t->numerator = v->fps_num;
t->denominator = v->fps_den;
return 0;
}
case VIDIOC_S_CTRL: {
struct v4l2_control *c = arg;
vn_set_control(v, c->id, c->value);
return 0;
}
case VIDIOC_G_CTRL: {
struct v4l2_control *c = arg;
return vn_get_control(v, c->id, &c->value);
}
case VIDIOC_S_EXT_CTRLS:
case VIDIOC_TRY_EXT_CTRLS:
case VIDIOC_G_EXT_CTRLS: {
struct v4l2_ext_controls *e = arg;
for (uint32_t i = 0; i < e->count && e->controls; i++) {
if (req == VIDIOC_S_EXT_CTRLS) vn_set_control(v, e->controls[i].id, e->controls[i].value);
else if (req == VIDIOC_G_EXT_CTRLS) {
int32_t value;
vn_get_control(v, e->controls[i].id, &value);
e->controls[i].value = value;
}
}
return 0;
}
case VIDIOC_QUERYCTRL: {
struct v4l2_queryctrl *q = arg;
if (q->id & V4L2_CTRL_FLAG_NEXT_CTRL) return -EINVAL;
q->type = V4L2_CTRL_TYPE_INTEGER;
q->minimum = 0;
q->maximum = 0x7fffffff;
q->step = 1;
q->flags = 0;
return 0;
}
case VIDIOC_S_SELECTION:
case VIDIOC_G_SELECTION: {
struct v4l2_selection *s = arg;
if (req == VIDIOC_S_SELECTION && s->r.width >= 64 && s->r.height >= 64 &&
s->r.width <= v->width && s->r.height <= v->height) {
v->crop_w = s->r.width & ~1u;
v->crop_h = s->r.height & ~1u;
v->configured = 0;
}
s->r = (struct v4l2_rect){ 0, 0, v->crop_w, v->crop_h };
return 0;
}
case VIDIOC_SUBSCRIBE_EVENT:
case VIDIOC_UNSUBSCRIBE_EVENT:
case VIDIOC_ENCODER_CMD:
case VIDIOC_TRY_ENCODER_CMD:
return 0;
case VIDIOC_DQEVENT:
return -ENOENT;
default: {
static unsigned long logged[32];
int seen = 0;
for (int i = 0; i < 32 && logged[i]; i++) seen |= logged[i] == req;
for (int i = 0; i < 32 && !seen; i++) if (!logged[i]) { logged[i] = req; break; }
if (!seen) vn_log("unhandled ioctl 0x%lx", req);
return -ENOTTY;
}
}
}
__attribute__((visibility("hidden"))) int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc) {
struct venc *v = vn_find(fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vn_lock);
int r = arg ? vn_ioctl(v, req, arg) : -EFAULT;
pthread_mutex_unlock(&vn_lock);
if (r < 0) {
errno = -r;
*rc = -1;
} else {
*rc = 0;
}
return 1;
}
__attribute__((visibility("hidden"))) int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
void *(*real)(void *, size_t, int, int, int, off_t), void **out) {
struct venc *v = vn_find(fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vn_lock);
struct vq *q = off >= VENC_CAPTURE_OFFSET ? &v->coded : &v->raw;
long index = (off - (off >= VENC_CAPTURE_OFFSET ? VENC_CAPTURE_OFFSET : 0)) / VENC_OFFSET_STEP - 1;
int memfd = index >= 0 && index < (long)q->count ? q->bufs[index].memfd : -1;
pthread_mutex_unlock(&vn_lock);
if (memfd < 0) {
errno = EINVAL;
*out = MAP_FAILED;
} else {
*out = real(addr, len, prot, (flags & ~MAP_PRIVATE) | MAP_SHARED, memfd, 0);
}
return 1;
}
__attribute__((visibility("hidden"))) void bl_venc_closed(int fd) {
struct venc *v = vn_find(fd);
if (v == NULL) return;
pthread_mutex_lock(&vn_lock);
vn_free_queue(&v->raw);
vn_free_queue(&v->coded);
v->used = 0;
/* A forked child closing its inherited copy must not end the stream for the parent. */
if (__atomic_sub_fetch(&vn_open_count, 1, __ATOMIC_RELEASE) == 0 && v->owner == getpid()) vn_marker(0);
pthread_mutex_unlock(&vn_lock);
}
static short vn_ready(struct venc *v) {
pthread_mutex_lock(&vn_lock);
short r = (v->coded.ndone ? POLLIN | POLLRDNORM : 0) | (v->raw.ndone ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vn_lock);
return r;
}
static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int)) {
int ours = 0, ready = 0;
int saved[64];
if (n > 64) return real(fds, n, timeout_ms);
for (nfds_t i = 0; i < n; i++) {
saved[i] = fds[i].fd;
struct venc *v = vn_find(fds[i].fd);
if (v == NULL) continue;
ours++;
fds[i].revents = vn_ready(v) & (fds[i].events | POLLERR);
if (fds[i].revents) ready++;
fds[i].fd = -1;
}
if (ours == 0) return real(fds, n, timeout_ms);
if (ready || timeout_ms < 0 || timeout_ms > 100) timeout_ms = ready ? 0 : 100;
short keep[64];
for (nfds_t i = 0; i < n; i++) keep[i] = fds[i].fd < 0 && saved[i] >= 0 ? fds[i].revents : 0;
int r = n - ours > 0 ? real(fds, n, timeout_ms) : (timeout_ms && !ready ? real(NULL, 0, timeout_ms) : 0);
if (r < 0) r = 0;
for (nfds_t i = 0; i < n; i++) {
if (fds[i].fd < 0 && saved[i] >= 0) fds[i].revents = keep[i];
fds[i].fd = saved[i];
}
return r + ready;
}
int poll(struct pollfd *fds, nfds_t n, int timeout_ms) {
static int (*real)(struct pollfd *, nfds_t, int);
if (!real) real = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll");
if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms);
return vn_poll(fds, n, timeout_ms, real);
}
+55
View File
@@ -0,0 +1,55 @@
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/uio.h>
#include <unistd.h>
typedef ssize_t (*vm_writev_fn)(pid_t, const struct iovec *, unsigned long, const struct iovec *, unsigned long,
unsigned long);
static int in_wineserver(void) {
static int known = -1;
if (known < 0) {
char exe[512];
ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1);
exe[n > 0 ? n : 0] = 0;
const char *name = strrchr(exe, '/');
known = !strcmp(name ? name + 1 : exe, "wineserver");
}
return known;
}
ssize_t process_vm_writev(pid_t pid, const struct iovec *local, unsigned long liovcnt, const struct iovec *remote,
unsigned long riovcnt, unsigned long flags) {
static vm_writev_fn real;
if (!real) real = (vm_writev_fn)dlsym(RTLD_NEXT, "process_vm_writev");
if (!real) {
errno = ENOSYS;
return -1;
}
ssize_t result = real(pid, local, liovcnt, remote, riovcnt, flags);
if (result >= 0 || errno != EFAULT || liovcnt != 1 || riovcnt != 1 || flags || !in_wineserver()) return result;
struct iovec ends[2];
struct iovec into = {ends, sizeof ends};
struct iovec from[2] = {{(void *)local, sizeof *local}, {(void *)remote, sizeof *remote}};
if (process_vm_readv(getpid(), &into, 1, from, 2, 0) != (ssize_t)sizeof ends || ends[0].iov_len != ends[1].iov_len) {
errno = EFAULT;
return -1;
}
char path[32];
snprintf(path, sizeof path, "/proc/%d/mem", (int)pid);
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) {
errno = EFAULT;
return -1;
}
ssize_t written = pwrite(fd, ends[0].iov_base, ends[0].iov_len, (off_t)(uintptr_t)ends[1].iov_base);
close(fd);
if (written < 0) errno = EFAULT;
return written;
}