Merge main (c298da6f) into feat/bionic-runtime

One conflict: .github/workflows/build.yml. This branch had a step that
fetched Robolectric's Android jars from a DroidDeck-CI release because
Maven Central answered the runners with HTTP 429; main now caches those
jars (#3127, #3134), so build.yml is main's again and this pull request
no longer changes it.

ProtonMenu, ProtonExtras, SessionService, SessionOverlay and
droiddeck-game-env merged cleanly; test_game_environment.py and
test_proton_extra.py pass (207 tests).
This commit is contained in:
The412Banner committed 2026-11-24 21:38:54 +00:00
commit cc5de0ba63
308 files changed
+14468 -3934

No files matched your search

+3
View File
@@ -115,6 +115,9 @@ fi
if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND
export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
# On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn
# frames; its software renderer draws correctly.
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0
if [ -z "${KWIN_RENDER_NODES:-}" ]; then
for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do
if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi
+2 -49
View File
@@ -1,7 +1,6 @@
#!/usr/bin/python3
import os
import re
import shutil
HOME = os.environ.get("HOME", "/root")
SYSTEM_DIR = "/usr/share/applications"
@@ -10,8 +9,6 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
USER_DIR = os.path.join(HOME, ".local/share/applications")
MARK = "X-DroidDeck-GPU=1"
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
def enabled():
@@ -27,33 +24,6 @@ def main_group(text):
return lines[:start + 1], lines[start + 1:end], lines[end:]
def split_program(exec_line):
if exec_line.startswith('"'):
end = exec_line.find('"', 1)
if end < 0:
return None, None
return exec_line[:end + 1], exec_line[end + 1:]
program, _, rest = exec_line.partition(" ")
return program, (" " + rest) if rest else ""
def chromium(exec_line):
program, _ = split_program(exec_line)
if not program:
return False
program = program.strip('"')
path = program if os.path.isabs(program) else shutil.which(program)
if not path:
return False
here = os.path.dirname(os.path.realpath(path))
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
def chromium_exec(exec_line):
program, rest = split_program(exec_line)
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
def gpu_exec(exec_line):
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
@@ -75,24 +45,8 @@ def wrap(text, gpu_on=True):
if not exec_line or exec_line.startswith("droiddeck-gpu "):
return None
cats = set(filter(None, keys.get("Categories", "").split(";")))
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
browser = chromium(exec_line)
if not gpu and not browser:
if not (gpu_on and cats & {"Game", "Emulator"}):
return None
if browser:
exec_line = chromium_exec(exec_line)
if not gpu:
def fix(lines):
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
for l in lines]
out_group = fix(group)
while out_group and not out_group[-1].strip():
out_group.pop()
out_group.append(MARK)
out_rest = fix(rest)
if out_rest and out_rest[0].strip():
out_rest.insert(0, "")
return "\n".join(head + out_group + out_rest) + "\n"
out_group = []
actions = keys.get("Actions", "")
for l in group:
@@ -111,8 +65,7 @@ def wrap(text, gpu_on=True):
wrapped_rest = []
for l in rest:
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
action = l[5:].strip()
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
l = "Exec=" + gpu_exec(l[5:].strip())
wrapped_rest.append(l)
if wrapped_rest and wrapped_rest[0].strip():
wrapped_rest.insert(0, "")
@@ -1206,6 +1206,15 @@ def handle(agent_dir, req):
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
def reply(agent_dir, req):
try:
return dict(handle(agent_dir, req), ok=True)
except AgentError as e:
return {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
def answer(agent_dir, path):
rid = path.stem
try:
@@ -1225,12 +1234,7 @@ def answer(agent_dir, path):
except OSError:
pass
if req is not None:
try:
result = dict(handle(agent_dir, req), ok=True)
except AgentError as e:
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
result = reply(agent_dir, req)
write_json(agent_dir / "resp" / (rid + ".json"), result)
@@ -1257,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1):
def main(argv):
if argv and argv[0] == "--cdp-inspector":
if len(argv) != 4:
print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr)
return 2
print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2],
"expression": argv[3], "commandLineApi": True})))
return 0
base = os.environ.get("DD_LAUNCH_DIR")
if not base:
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
@@ -9,6 +9,40 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;;
esac
fi
if [ -n "${DDNATV_ROOT:-}" ]; then
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
fi
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
fi
if [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$image
exec /usr/local/lib/droiddeck/uruntime "$@"
@@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
export QT_QPA_PLATFORM=xcb
fi
arch=$(cat "$dir/arch" 2>/dev/null)
if [ "$arch" = arm64 ]; then
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
while IFS= read -r lib; do
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
done
fi
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("$APPDIR/AppRun")
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $fex:$(cat "$dir/arch" 2>/dev/null) in
case $fex:$arch in
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
auto:arm64) ;;
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
@@ -79,8 +79,7 @@ AGENT_START = 90
AGENT_HELPER = "agent.js"
AGENT_RUNTIME = "agent-runtime"
AGENT_LOG = "agent.log"
AGENT_LOG_LIMIT = 4 << 20
HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"]
HEADLESS = "/usr/local/bin/droiddeck-headless"
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
COUNTRY = re.compile(r"[A-Z]{3}")
@@ -1416,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
windows = install_path(root, folder)
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
os.makedirs(CACHE, exist_ok=True)
for suffix in (".json", ".game", ".form", ".error"):
try:
os.unlink(base + suffix)
except OSError:
pass
runtime = os.path.join(CACHE, AGENT_RUNTIME)
os.makedirs(runtime, mode=0o700, exist_ok=True)
env = agent_env()
for name in ("DISPLAY", "WAYLAND_DISPLAY"):
env.pop(name, None)
env["XDG_RUNTIME_DIR"] = runtime
cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--",
os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
output = os.path.join(CACHE, AGENT_LOG)
try:
if os.path.getsize(output) > AGENT_LOG_LIMIT:
os.replace(output, output + ".1")
except OSError:
pass
before = {pid for pid, _ in wine_processes(pfx)}
with open(output, "ab") as log:
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
seen = None
mark = None
moved = time.monotonic()
@@ -5,39 +5,17 @@ self=${BASH_SOURCE[0]}
proc=${DD_PROC:-/proc}
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless}
wait_s=${DD_CURSEFORGE_WAIT:-60}
cmd=${1:-}
dir=${2:-}
flag=--inspect-publish-uid=stderr
case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display <imported AppImage directory>" >&2; exit 2 ;; esac
if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then
case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac
if [ ! -d "$dir/app" ]; then
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
exit 2
fi
x_display() {
if [ -n "${DISPLAY:-}" ]; then
printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}"
return 0
fi
local p name a prev display auth
for p in "$proc"/[0-9]*; do
name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1)
case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac
display= auth= prev=
while IFS= read -r a; do
case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac
[ "$prev" = -auth ] && auth=$a
prev=$a
done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline")
if [ -n "$display" ]; then
printf '%s\n%s\n' "$display" "$auth"
return 0
fi
done
return 1
}
running() {
local p
for p in "$proc"/[0-9]*; do
@@ -79,7 +57,7 @@ inspector() {
}
start() {
local shown display auth url pid
local url pid child=
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
if ! ours >/dev/null; then
if tracked >/dev/null || running; then
@@ -87,18 +65,18 @@ start() {
echo busy
return 3
fi
shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; }
display=$(sed -n 1p <<<"$shown")
auth=$(sed -n 2p <<<"$shown")
env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \
setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >"$state/log" 2>&1 9>&- &
mv -f "$state/log" "$state/log.1" 2>/dev/null
env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \
"$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- &
pid=$!
child=$pid
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
fi
exec 9>&-
for _ in $(seq 1 $((wait_s * 2))); do
if url=$(inspector); then
echo "$url"
hold "$child"
return 0
fi
ours >/dev/null || break
@@ -108,6 +86,18 @@ start() {
return 5
}
hold() {
local pid
if [ -n "$1" ]; then
wait "$1"
return 0
fi
pid=$(ours) || return 0
while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do
sleep 1
done
}
stop() {
local pid p
lock || return 1
@@ -118,6 +108,7 @@ stop() {
sleep 0.5
done
kill -KILL -- "-$pid" 2>/dev/null
kill -KILL "$pid" 2>/dev/null
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
done
@@ -127,22 +118,10 @@ stop() {
}
case $cmd in
display)
x_display || exit 4
;;
start)
start
exit $?
;;
hold)
start >/dev/null || exit $?
trap 'stop; exit 0' TERM INT HUP
while ours >/dev/null; do
sleep 1 &
wait $!
done
exit 0
;;
stop)
stop
exit 0
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
"libssl.so.3", "libcrypto.so.3",
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
))
PROVIDED_NEEDS = {
"libwayland-client.so.0": ("libffi.so.8",),
@@ -670,6 +670,8 @@ def guest_environment(fex, env):
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
result.pop("GLIBC_TUNABLES", None)
if "aarch64" in result.get("GCONV_PATH", ""):
result["GCONV_PATH"] = ""
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
@@ -849,8 +851,12 @@ def extract(image):
clear_extracted()
x86 = elf_arch(image) in X86.values()
if os.access(URUNTIME, os.X_OK):
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=image))
with open(image, "rb") as source:
native = bool(os.environ.get("DDNATV_ROOT"))
target = "/proc/self/fd/%d" % source.fileno() if native else image
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=target),
pass_fds=(source.fileno(),) if native else ())
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
@@ -880,7 +886,17 @@ def extract(image):
want_fex()
return 0
say("unsquashfs could not extract it (status %d)" % status)
elif fex is None:
seven = shutil.which("7z")
if seven:
clear_extracted()
status = subprocess.call([seven, "x", "-tSquashFS", "-y", "-osquashfs-root", image], stdout=subprocess.DEVNULL)
if status == 0 and extracted():
if x86:
want_fex()
return 0
say("7-Zip could not extract it (status %d)" % status)
clear_extracted()
elif fex is None and not unsquashfs:
say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs")
return 1
@@ -164,6 +164,12 @@ def ff7_rebirth_feature_level(game):
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)"
@fix
def hades2_feature_level(game):
if game.stem == "hades2":
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Hades II: D3D12 feature level 12_2 (on Adreno 6xx/7xx it finds no D3D12 adapter at the detected level)"
@fix
def kcd2_feature_level(game):
if game.app_id == "1771300":
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
set -u
runtime=${1:-}
shift
log=
if [ "${1:-}" = --log ]; then
log=${2:-}
shift 2
fi
if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then
echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2
exit 2
fi
shift
umask 077
mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1
if [ -n "$log" ]; then
size=$(stat -c %s "$log" 2>/dev/null || echo 0)
[ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1"
exec >>"$log" 2>&1
fi
unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY
export XDG_RUNTIME_DIR=$runtime
exec gamescope --backend headless -w 640 -h 480 -- "$@"
@@ -65,12 +65,15 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
cache_only=
applied=
[ "${1:-}" = --cache ] && cache_only=1
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
@@ -130,6 +133,156 @@ fetch() {
done
}
# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries:
# the shell here cannot open /dev/fd for process substitution from a background job.
fetch_one() {
local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait
while :; do
if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then
echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0
rm -f "$dest"
finished=0 bad=$((bad + 1))
[ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; }
fi
before=$(size_of "$dest")
http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$?
if [ "$rc" = 0 ]; then finished=1; continue; fi
case "$rc:${http:-}" in
22:416 | 33:*) rm -f "$dest" ;;
22:4??)
echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2
return 1
;;
esac
if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi
if [ "$failures" -gt "${#delays[@]}" ]; then
echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2
return 1
fi
wait=${delays[$((failures > 0 ? failures - 1 : 0))]}
step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s"
sleep "$wait"
done
}
parallel=${DD_STEAM_PARALLEL:-4}
case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac
flock_command=${DD_STEAM_FLOCK:-flock}
command -v "$flock_command" > /dev/null 2>&1 || parallel=1
# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into
# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the
# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover.
unzip_alone() {
local rc
( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$?
return $rc
}
# Takes the next unclaimed line number from a counter under a flock, and prints 0 when none is left. mkdir was tried for this
# and handed the same line to two workers now and then in the app's guest shell, so only the kernel's lock is trusted here.
claim_next() {
local n
while :; do
# A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none.
n=$( { "$flock_command" 8 || exit 1
n=$(cat "$state/next") || exit 1
case $n in ''|*[!0-9]*) exit 1 ;; esac
echo $((n + 1)) > "$state/next" || exit 1
echo "$n"; } 8> "$state/claim.lock" ) || return 1
[ "$n" -le "$count" ] || { echo 0; return; }
if [ ! -e "$state/$n.done" ]; then
: > "$state/claim.$n"
echo "$n"
return
fi
done
}
# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third
# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a
# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves
# (claim_next) and only plain background jobs and wait on a pid are used, so nothing depends on job control.
run_parallel() {
local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size
local -a blocks=() files=() sums=() sizes=() pids=()
state=$work/parallel
rm -rf "$state"
mkdir -p "$state"
echo 1 > "$state/next"
while read -r block file sum size; do
index=$((index + 1))
blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size
if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then
: > "$state/$index.done"
fi
done < "$list"
local count=$index total_bytes=0
for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done
local slot
for slot in $(seq 1 "$parallel"); do
(
trap ': > "$state/exit.$slot"' EXIT
while [ ! -e "$state/failed" ]; do
# run_parallel is called in an || list, which switches set -e off in here: a failed claim has to be checked by hand.
index=$(claim_next) || { : > "$state/failed"; exit 1; }
[ "$index" -gt 0 ] || exit 0
file=${files[index]}
fetched=""
for host in "${cdn_order[@]}"; do
if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then
fetched=$host
break
fi
done
if [ -z "$fetched" ]; then
echo "droiddeck-steam-install: $file failed on every CDN" >&2
: > "$state/failed"
exit 1
fi
if [ -n "$unpack" ]; then
unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; }
: > "$dir/$file.unpacked"
rm -f "$dir/$file"
fi
: > "$state/$index.done"
done
) &
pids+=($!)
done
local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90}
while :; do
alive=0
for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done
got=0 n=0 current=""
for index in $(seq 1 "$count"); do
if [ -e "$state/$index.done" ]; then
got=$((got + sizes[index])) n=$((n + 1))
elif [ -e "$state/claim.$index" ]; then
current=$index
[ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}")))
fi
done
mark=$((got / 1000000))
if [ -n "$current" ] && [ "$mark" != "$shown" ]; then
shown=$mark
step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB"
fi
[ "$n" -lt "$count" ] || alive=0
if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi
# A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while
# and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging.
[ $((SECONDS - since)) -lt "$stall" ] || alive=0
[ "$alive" = 1 ] || break
sleep 1
done
local failed=""
for slot in "${pids[@]}"; do wait "$slot" || failed=1; done
[ ! -e "$state/failed" ] || failed=1
rm -rf "$state"
[ -z "$failed" ]
}
fetch_manifest() {
cdn=""
for candidate in $cdn_list; do
@@ -167,6 +320,66 @@ if ! fetch_manifest; then
fallback=1
fetch_manifest || exit 1
fi
if [ -n "$cache_only" ]; then
cache=$steam_root/package
cached=$cache/droiddeck-cached
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
$2 == "size" { size[block] = $4 }
$2 == "zipvz" { vz[block] = $4 }
$2 == "sha2vz" { vzsha[block] = $4 }
END {
for (b in file) {
f = file[b]; h = sha[b]; n = size[b] + 0
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
print b, f, h, n
}
}
' "$work/manifest" | sort > "$work/cache"
mkdir -p "$cache"
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
done_bytes=0
i=0
if [ "$parallel" -gt 1 ]; then
run_parallel "$work/cache" "$cache" || exit 1
else
while read -r block file sum size; do
i=$((i + 1))
progress "$cache/$file" "$block"
fetched=""
for host in "${cdn_order[@]}"; do
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
fetched=$host
break
fi
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
done_bytes=$((done_bytes + size))
done < "$work/cache"
fi
applier=
trap 'kill "$applier" 2>/dev/null || :; wait "$applier" 2>/dev/null || :; rm -f "$cache/$manifest.installed" "$cached"; exit 143' TERM INT HUP
echo "$version" > "$cached"
preapply=${DD_STEAM_PREAPPLY:-/usr/local/bin/droiddeck-steam-preapply}
if [ -x "$preapply" ] && command -v python3 >/dev/null 2>&1; then
python3 "$preapply" "$cache" "$steam_root" "$work/manifest" "$manifest" &
applier=$!
if wait "$applier"; then
cp -f "$work/manifest" "$cache/$manifest.manifest"
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
while read -r _ file _; do rm -f "$cache/$file"; done < "$work/cache"
[ -f "$stamp" ] || applied=1
else
rm -f "$cache/$manifest.installed" "$cached"
fi
fi
trap - TERM INT HUP
[ -n "$applied" ] || exit 0
fi
if [ -n "$sync" ]; then
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
@@ -175,6 +388,7 @@ if [ -n "$sync" ]; then
fi
echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client"
fi
if [ -z "$applied" ]; then
total=$(grep -c . "$work/parts" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/parts")
@@ -186,6 +400,9 @@ for left in "$parts"/*; do
grep -qF " $name " "$work/parts" || rm -rf "$left"
done
done_bytes=0
if [ "$parallel" -gt 1 ]; then
run_parallel "$work/parts" "$parts" unpack || exit 1
else
while read -r block file sum size; do
i=$((${i:-0} + 1))
if [ -f "$parts/$file.unpacked" ]; then
@@ -206,6 +423,8 @@ while read -r block file sum size; do
rm -f "$parts/$file"
done_bytes=$((done_bytes + size))
done < "$work/parts"
fi
fi
find "$steam_root" -depth -name '*\\*' | while read -r odd; do
fixed=${odd//\\//}
mkdir -p "$(dirname "$fixed")"
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Extract Steam's cached update packages and record them the way Steam's own updater does."""
import hashlib, lzma, os, re, stat, struct, sys, time, zipfile, io, zlib, calendar
OSVER = "-184"
MTIME_OFFSET = 28800
def blocks(manifest):
out, cur, depth = {}, None, 0
for line in manifest.splitlines():
m = re.match(r'^(\t+)"([^"]+)"\s*(?:"([^"]*)")?\s*$', line)
if m and m.group(3) is None and len(m.group(1)) == 1:
cur = m.group(2)
out[cur] = {}
elif m and m.group(3) is not None and len(m.group(1)) == 2 and cur:
out[cur][m.group(2)] = m.group(3)
return out
def unvz(d):
if d[:3] != b"VZa" or d[-2:] != b"zv":
raise ValueError("not a VZip")
props = d[7]
dict_size = struct.unpack("<I", d[8:12])[0]
crc, size = struct.unpack("<II", d[-10:-2])
f = [{"id": lzma.FILTER_LZMA1, "dict_size": dict_size,
"lc": props % 9, "lp": (props // 9) % 5, "pb": props // 45}]
out = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=f).decompress(d[12:-10], max_length=size)
if len(out) != size or zlib.crc32(out) & 0xFFFFFFFF != crc:
raise ValueError("bad VZip")
return out
def inside(root, path):
return os.path.commonpath([root, path]) == root
def main(package_dir, steam_root, manifest_path, name):
steam_root = os.path.realpath(steam_root)
manifest = open(manifest_path, encoding="utf-8", errors="replace").read()
rows = {}
for block, attrs in blocks(manifest).items():
for key in ("zipvz", "file"):
f = attrs.get(key)
if f and os.path.isfile(os.path.join(package_dir, f)):
break
else:
raise SystemExit(f"missing package for {block}")
data = open(os.path.join(package_dir, f), "rb").read()
zdata = unvz(data) if key == "zipvz" else data
del data
with zipfile.ZipFile(io.BytesIO(zdata)) as z:
for info in z.infolist():
rel = info.filename.replace("\\", "/")
if rel.startswith("/") or ".." in rel.split("/"):
raise SystemExit(f"unsafe path in {block}: {rel}")
dest = os.path.join(steam_root, rel)
if not inside(steam_root, os.path.realpath(os.path.dirname(dest.rstrip("/")))):
raise SystemExit(f"path leaves the Steam root in {block}: {rel}")
mode = (info.external_attr >> 16) & 0xFFFF
mtime = calendar.timegm(info.date_time + (0, 0, 0)) + MTIME_OFFSET
if rel.endswith("/"):
os.makedirs(dest, exist_ok=True)
rows[rel] = (-1, mtime, 0)
continue
os.makedirs(os.path.dirname(dest), exist_ok=True)
if stat.S_ISLNK(mode):
if os.path.lexists(dest):
os.unlink(dest)
os.symlink(z.read(info).decode(), dest)
rows[rel] = (-2, mtime, info.CRC)
continue
with open(dest + ".dd-tmp", "wb") as out:
out.write(z.read(info))
os.chmod(dest + ".dd-tmp", (mode & 0o777) | 0o644 if mode else 0o644)
os.replace(dest + ".dd-tmp", dest)
rows[rel] = (info.file_size, mtime, info.CRC)
del zdata
body = "".join(f"{p},{s};{m};{c}\n" for p, (s, m, c) in sorted(rows.items(), key=lambda kv: kv[0].upper()))
body += f"OSVER={OSVER}\nVERSION=3\n"
sha = hashlib.sha1(body.encode()).hexdigest().upper()
pkg = os.path.join(steam_root, "package")
os.makedirs(pkg, exist_ok=True)
tmp = os.path.join(pkg, name + ".installed.dd-tmp")
with open(tmp, "w", encoding="utf-8") as f:
f.write(body + f"SHA1={sha}\n")
os.replace(tmp, os.path.join(pkg, name + ".installed"))
if __name__ == "__main__":
main(*sys.argv[1:5])
@@ -125,6 +125,14 @@ RECORD = ".droiddeck-shortcuts.json"
AWAY_LIMIT = 256
FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions")
FOLLOWED = ("StartDir", "LaunchOptions")
# Guest mountpoints whose contents live on storage the user can unplug. The app creates
# the mountpoint before binding it, so it outlives a removed card; libraries, store
# volumes and added game folders get one mountpoint each under these families.
REMOVABLE_ROOTS = ("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")
REMOVABLE_FAMILIES = ("/mnt/droiddeck-lib", "/mnt/droiddeck-stores", "/root/Games")
# Guest trees the app always has, whatever storage is in the device. A target that is
# missing from one of these is gone even when its whole folder was removed.
INTERNAL_ROOTS = ("/root/Games/Stores", "/root/.local/share/Steam")
def unquoted(value):
@@ -146,6 +154,46 @@ def read_record(path):
}
def under(path, root):
return path == root or path.startswith(root + "/")
def internal_target(target):
path = os.path.normpath(target)
return any(under(path, root) for root in INTERNAL_ROOTS)
def removable_mount(target):
"""The guest mountpoint holding target, when it is storage the user can unplug."""
path = os.path.normpath(target)
for root in REMOVABLE_ROOTS:
if under(path, root):
return root
for family in REMOVABLE_FAMILIES:
prefix = family + "/"
if path.startswith(prefix):
return prefix + path[len(prefix):].split("/", 1)[0]
return None
def storage_mounted(target):
"""Whether the storage holding target is there this session.
The app creates a guest mountpoint before binding storage to it, so a mountpoint that
lists nothing is one a removed card or volume left behind. A target under it may work
again when that storage returns, so its absence is not proof the file is gone.
"""
if internal_target(target):
return True
mount = removable_mount(target)
if mount is None:
return True
try:
return bool(os.listdir(mount))
except OSError:
return False
def merge(fresh, current, state, seen):
state = state if isinstance(state, dict) else {}
rev = state.get("rev") if isinstance(state.get("rev"), int) else 0
@@ -158,7 +206,16 @@ def merge(fresh, current, state, seen):
entry = dict(current)
entry["appid"] = fresh["appid"]
exe = unquoted(fresh["Exe"])
if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev):
target = unquoted(current.get("Exe"))
# A target Steam still points at after the file is gone starts nothing, so it is not
# an edit to keep: the app's own exe replaces it (#694: a hand-typed Target outlived
# the game update that removed the file, and every launch died before the game ran).
# Only when its storage is mounted and it is missing from a tree the app always has or
# from a folder that is still there. An absent folder under a mountpoint can equally be
# unplugged storage, and that target may work again next session.
gone = (bool(target) and not os.path.isfile(target) and storage_mounted(target) and
(internal_target(target) or os.path.isdir(os.path.dirname(target))))
if exe != target and (gone or exe != unquoted(base.get("Exe")) or seen == rev):
entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"]
for field in ("AppName", "icon"):
if current.get(field) == base.get(field):
@@ -10,6 +10,7 @@ import tempfile
DISPLAY = "External: gamescope|||Windowed"
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
@@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text):
return seed_value(text, SCREENSAVER_IN_GAME, '0')
def seed_bouncing_logo(text):
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
def atomic_write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
@@ -179,6 +184,11 @@ def initialize_screensaver(steam_root):
'== steam: no screensaver over a running game')
def initialize_screensaver_choice(steam_root):
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
'== steam: bouncing logo screensaver')
if __name__ == '__main__':
status = 0
try:
@@ -186,7 +196,7 @@ if __name__ == '__main__':
except (OSError, ValueError, RecursionError) as error:
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
status = 1
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
try:
step(sys.argv[1])
except (OSError, ValueError, RecursionError) as error:
+38 -21
View File
@@ -21,6 +21,29 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) {
if (!file || !*file) return 0;
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
const char *paths = getenv("PATH");
if (!paths) paths = "/bin:/usr/bin";
char candidate[PATH_MAX];
int found = 0;
for (const char *p = paths;; ) {
const char *end = strchrnul(p, ':');
int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file)
: snprintf(candidate, sizeof candidate, "%s", file);
struct stat st;
if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) {
int runs = access(candidate, X_OK) == 0;
if (runs || !found) memcpy(out, candidate, (size_t)n + 1);
found = 1;
if (runs) return 1;
}
if (!*end) return found;
p = end + 1;
}
}
#if defined(__aarch64__) || defined(BINFMT_TEST)
static int flag(const char *name) {
@@ -32,17 +55,26 @@ static int handing_off(void) {
return flag("DD_DESKTOP") || flag("DD_BINFMT");
}
static int appimage(int fd, const unsigned char *head, ssize_t n) {
Elf64_Ehdr eh;
if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0;
memcpy(&eh, head, sizeof eh);
char magic[6];
off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum;
return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6));
}
static int foreign(const char *path, int error) {
if (!path || !strcmp(path, BINFMT_HANDLER)) return 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
struct stat st;
unsigned char head[20];
unsigned char head[sizeof(Elf64_Ehdr)];
ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1;
int kind = 0;
if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) {
unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8;
kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0;
kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0;
} else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') {
kind = 2;
} else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) {
@@ -58,21 +90,6 @@ static int wanted(const char *path, int error) {
return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error);
}
static int lookup(const char *file, char *out, size_t size) {
if (!file || !*file) return 0;
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
const char *paths = getenv("PATH");
if (!paths) paths = "/bin:/usr/bin";
for (const char *p = paths;; ) {
const char *end = strchrnul(p, ':');
int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file);
struct stat st;
if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1;
if (!*end) return 0;
p = end + 1;
}
}
static int count(char *const argv[]) {
int n = 0;
while (argv && argv[n]) n++;
@@ -117,12 +134,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char
__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) {
char path[PATH_MAX];
if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
}
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) {
char path[PATH_MAX];
if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
errno = error;
return -1;
}
@@ -144,7 +161,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char
int execvpe(const char *file, char *const argv[], char *const envp[]) {
char resolved[PATH_MAX];
const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file;
const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file;
char *const *adjusted = dd_webhelper_argv(path, argv, envp);
static int (*real)(const char *, char *const[], char *const[]);
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe");
@@ -156,7 +173,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) {
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr,
char *const argv[], char *const envp[]) {
char path[PATH_MAX];
int found = lookup(file, path, sizeof path);
int found = dd_program_lookup(file, path, sizeof path);
char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp);
static spawn_fn real, spawn;
if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp");
+2 -14
View File
@@ -25,7 +25,6 @@
#define CP_FDS 65536
static const int64_t *cp_shift;
static int cp_state;
static size_t cp_cond_byte;
static unsigned char cp_cond_mask;
static unsigned char cp_fds[CP_FDS / 8];
@@ -94,25 +93,14 @@ static void cp_init(void) {
}
static int64_t cp_offset(void) {
const int64_t *shift;
int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE);
if (state == 0) {
int expected = 0;
if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
cp_init();
__atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE);
}
return 0;
}
if (state != 2) return 0;
shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
if (!shift) return 0;
int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED);
return value > 0 ? value : 0;
}
__attribute__((constructor)) static void cp_start(void) {
cp_offset();
cp_init();
}
static int cp_mono(clockid_t clock) {
+3 -1
View File
@@ -277,6 +277,7 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size);
__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
spawn_fn real);
@@ -377,7 +378,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
}
int execvp(const char *file, char *const argv_in[]) {
char *const *argv = dd_webhelper_argv(file, argv_in, environ);
char resolved[PATH_MAX];
char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
maybe_answer_lsof(file, argv);
+192 -5
View File
@@ -29,6 +29,8 @@
#define VDEC_BITSTREAM_SIZE (4u << 20)
#define VDEC_PADDING 64
#define VDEC_DUMB 64
#define VDEC_CAP_MIN_WIDTH 4096u
#define VDEC_CAP_MIN_HEIGHT 2304u
struct vd_dma_heap_alloc {
uint64_t len;
@@ -135,6 +137,8 @@ struct vdec {
uint32_t n_cap_done;
int out_on, cap_on;
int sock, hw, hw_failed;
int resizing;
uint32_t stream_w, stream_h;
int64_t pts;
void *ctx, *packet, *frame;
uint8_t *packet_data;
@@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) {
if (sock < 0) return -1;
struct vdec_config c = {
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
.width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width,
.height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height,
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
};
struct vdec_result r;
@@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
t.fourcc = p->pixelformat;
t.width = p->width;
t.height = p->height;
t.stream_w = p->width;
t.stream_h = p->height;
} else {
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH;
if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT;
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
t.cap_width = (w + 15) & ~15u;
t.cap_height = (h + 15) & ~15u;
@@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
if (apply) {
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
*v = t;
if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0;
}
vd_fill_format(&t, f);
return 0;
@@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
struct vd_bits {
const uint8_t *data;
size_t size, pos;
};
static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) {
uint32_t value = 0;
while (count--) {
size_t byte = b->pos >> 3;
value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u);
b->pos++;
}
return value;
}
static uint32_t vd_get_ue(struct vd_bits *b) {
unsigned zeros = 0;
while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++;
if (zeros >= 32) return 0;
return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0);
}
static int32_t vd_get_se(struct vd_bits *b) {
uint32_t k = vd_get_ue(b);
return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2);
}
static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) {
int32_t last = 8, next = 8;
for (unsigned i = 0; i < size; i++) {
if (next != 0) {
int32_t delta = vd_get_se(b);
if (delta < -128 || delta > 127) return -1;
next = (last + delta + 256) % 256;
}
last = next == 0 ? last : next;
}
return 0;
}
/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */
static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
uint32_t profile = vd_get_bits(&b, 8);
vd_get_bits(&b, 16);
vd_get_ue(&b);
uint32_t chroma = 1;
if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 ||
profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) {
chroma = vd_get_ue(&b);
if (chroma == 3) vd_get_bits(&b, 1);
vd_get_ue(&b);
vd_get_ue(&b);
vd_get_bits(&b, 1);
if (vd_get_bits(&b, 1)) {
for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++)
if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1;
}
}
vd_get_ue(&b);
uint32_t poc = vd_get_ue(&b);
if (poc == 0) {
vd_get_ue(&b);
} else if (poc == 1) {
vd_get_bits(&b, 1);
vd_get_se(&b);
vd_get_se(&b);
uint32_t cycle = vd_get_ue(&b);
for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b);
}
vd_get_ue(&b);
vd_get_bits(&b, 1);
uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1;
if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1;
uint32_t frame_mbs_only = vd_get_bits(&b, 1);
if (b.pos > b.size * 8) return -1;
*width = mbs_wide * 16;
*height = map_units_high * 16 * (2 - frame_mbs_only);
return 0;
}
/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */
static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 4 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue;
size_t start = i + 4, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h264(data + start, end - start, width, height);
}
return -1;
}
/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */
static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
vd_get_bits(&b, 4);
uint32_t sub_layers = vd_get_bits(&b, 3);
vd_get_bits(&b, 1);
for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8);
vd_get_bits(&b, 8);
uint32_t profile_present = 0, level_present = 0;
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
profile_present |= vd_get_bits(&b, 1) << i;
level_present |= vd_get_bits(&b, 1) << i;
}
if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2);
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8);
if (level_present >> i & 1) vd_get_bits(&b, 8);
}
vd_get_ue(&b);
if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1);
uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b);
if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1;
*width = (w + 15) & ~15u;
*height = (h + 15) & ~15u;
return 0;
}
static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 5 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue;
size_t start = i + 5, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h265(data + start, end - start, width, height);
}
return -1;
}
/*
* A stream can change its picture size without telling the client: the host switches games or the window
* becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which
* the client polls; the capture buffers it already allocated stay at the old size until it reconfigures.
*/
static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) {
uint32_t width, height;
int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height)
: vd_stream_size_h264(data, size, &width, &height);
if (found != 0) return 0;
uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height;
if (width == known_w && height == known_h) return 0;
vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h);
if (width <= v->cap_width && height <= v->cap_height) {
/* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */
v->stream_w = width;
v->stream_h = height;
if (v->hw) vd_close_decoder(v);
return 1;
}
v->width = v->stream_w = width;
v->height = v->stream_h = height;
v->resizing = 1;
v->n_cap_done = 0;
return 1;
}
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
uint32_t bytes = b->m.planes[0].bytesused;
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes);
if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp);
v->out_done[v->n_out_done++] = b->index;
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
@@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
if (v->n_cap_done == 0) return -EAGAIN;
struct vd_done d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct vd_done d;
for (;;) {
if (v->n_cap_done == 0) return -EAGAIN;
d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct stat st;
struct vd_capture *c = &v->cap[d.index];
if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break;
}
b->index = d.index;
b->memory = V4L2_MEMORY_DMABUF;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
+67 -24
View File
@@ -26,40 +26,83 @@ static char *join_features(const char *have, const char *add) {
return strcat(out, add);
}
static int electron_node_mode(char *const envp[]) {
static const char variable[] = "ELECTRON_RUN_AS_NODE=";
static const char *env_value(char *const envp[], const char *variable) {
size_t n = strlen(variable);
for (int i = 0; envp && envp[i]; i++)
if (!strncmp(envp[i], variable, sizeof variable - 1))
return envp[i][sizeof variable - 1] != 0;
return 0;
if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1;
return NULL;
}
static char *const *chromium_argv(const char *path, char *const argv[]) {
const char *slash = path ? strrchr(path, '/') : NULL;
if (!slash || !argv || !argv[0]) return argv;
int argc = 0;
for (; argv[argc]; argc++)
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
size_t dir = (size_t)(slash - path) + 1;
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
if (!sandbox) return argv;
memcpy(sandbox, path, dir);
strcpy(sandbox + dir, "chrome-sandbox");
int chromium = access(sandbox, F_OK) == 0;
free(sandbox);
if (!chromium) return argv;
char **out = calloc((size_t)argc + 2, sizeof *out);
static int electron_node_mode(char *const envp[]) {
const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE");
return mode && *mode;
}
static int beside_chrome_sandbox(const char *path) {
char *real = realpath(path, NULL);
if (!real) return 0;
int found = 0;
for (int up = 0; up < 2 && !found; up++) {
char *slash = strrchr(real, '/');
if (!slash) break;
*slash = 0;
size_t dir = strlen(real);
char *sandbox = malloc(dir + sizeof "/chrome-sandbox");
if (!sandbox) break;
memcpy(sandbox, real, dir);
strcpy(sandbox + dir, "/chrome-sandbox");
found = access(sandbox, F_OK) == 0;
free(sandbox);
}
free(real);
return found;
}
static char *folder_of(const char *path) {
char *real = realpath(path, NULL);
char *slash = real ? strrchr(real, '/') : NULL;
if (slash) *slash = 0;
return real;
}
static int started_by_its_own_app(const char *path) {
char self[4096];
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n <= 0) return 0;
self[n] = 0;
char *mine = folder_of(self), *theirs = folder_of(path);
int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self);
free(mine);
free(theirs);
return same;
}
static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) {
if (!path || !argv || !argv[0]) return argv;
int argc = 0, sandbox = 1, ozone = 0;
for (; argv[argc]; argc++) {
if (!argc) continue;
if (!strncmp(argv[argc], "--type=", 7)) return argv;
if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0;
if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1;
}
const char *display = env_value(envp, "DISPLAY");
int x11 = !ozone && display && *display;
if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv;
char **out = calloc((size_t)argc + 3, sizeof *out);
if (!out) return argv;
out[0] = argv[0];
out[1] = (char *)"--no-sandbox";
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
int n = 0;
out[n++] = argv[0];
if (sandbox) out[n++] = (char *)"--no-sandbox";
if (x11) out[n++] = (char *)"--ozone-platform=x11";
for (int i = 1; i < argc; i++) out[n++] = argv[i];
return out;
}
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) {
if (electron_node_mode(envp)) return argv;
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp);
const char *spec = getenv("DD_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;