mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-23 06:46:02 +00:00
chore: merge main to catch up with 0.5.0
This commit is contained in:
commit
6d105c1649
1480 files changed
+186541
-49002
No files matched your search
@@ -26,7 +26,7 @@ for arch in x86_64 i386; do
|
||||
fi
|
||||
done
|
||||
done
|
||||
for target in x86_64/faultreport i386/faultreport x86_64/thunkaudit; do
|
||||
for target in x86_64/faultreport i386/faultreport; do
|
||||
arch=${target%/*} name=${target#*/}
|
||||
case $arch in
|
||||
x86_64) bits=-m64 ;;
|
||||
@@ -41,13 +41,24 @@ for target in x86_64/faultreport i386/faultreport x86_64/thunkaudit; do
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
lib=$out/x86_64/libwebkitinput.so
|
||||
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
|
||||
-o "$lib" tools/linuxfs/fex/webkitinput.c
|
||||
strip --strip-unneeded "$lib"
|
||||
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
|
||||
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
|
||||
exit 1
|
||||
fi
|
||||
stub=$(mktemp -d)
|
||||
gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
|
||||
gcc -m64 -shared -nostdlib -Wl,-z,nodelete -Wl,--no-as-needed \
|
||||
-o "$out/x86_64/libvulkan-thunk.so" -x c /dev/null -x none "$stub/libvulkan.so.1"
|
||||
lib=$out/x86_64/libvulkan-thunk.so
|
||||
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
|
||||
-o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl
|
||||
rm -rf "$stub"
|
||||
if ! objdump -p "$out/x86_64/libvulkan-thunk.so" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|
||||
|| ! objdump -p "$out/x86_64/libvulkan-thunk.so" | grep -q 'FLAGS_1 *0x0*8$'; then
|
||||
echo "$out/x86_64/libvulkan-thunk.so must be nodelete and need only the Vulkan thunk" >&2
|
||||
strip --strip-unneeded "$lib"
|
||||
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
|
||||
if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|
||||
|| ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
|
||||
echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared native ABI checks for CI and local builds.
|
||||
set -euo pipefail
|
||||
D=${1:?asset directory}
|
||||
NEED=$("${READELF:-readelf}" -d "$D/libfakeinput.so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p')
|
||||
@@ -13,9 +12,6 @@ FAKE=$(syms "$D/libfakeinput.so")
|
||||
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
|
||||
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
|
||||
done
|
||||
# The static C++ runtime stays private: every session process preloads this library,
|
||||
# and an exported personality routine takes over other programs' unwinding (shadPS4
|
||||
# aborted in pthread_exit).
|
||||
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
|
||||
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
|
||||
fi
|
||||
@@ -23,7 +19,6 @@ SESSION=$(syms "$D/libblsession.so")
|
||||
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle; do
|
||||
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
||||
done
|
||||
# Zink's GEM_CLOSE is caught at ioctl(); an exported drmIoctl made NMS replay old frames.
|
||||
if grep -qx drmIoctl <<<"$SESSION"; then
|
||||
echo "::error::libblsession.so exports drmIoctl"; exit 1
|
||||
fi
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
/* Android text -> Gamescope's Xwayland selection. Gamescope's Wayland backend does not
|
||||
* relay the outer compositor's clipboard. libX11 is loaded from the guest at runtime;
|
||||
* the small stable Xlib ABI below keeps this helper independent of cross X11 headers.
|
||||
* The private host file is atomically replaced, never put in session logs. */
|
||||
#define _GNU_SOURCE
|
||||
#include <sys/inotify.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -45,12 +41,9 @@ API(int, XConnectionNumber, (Display *));
|
||||
API(int, XCloseDisplay, (Display *));
|
||||
API(void *, XSetErrorHandler, (int (*)(Display *, void *)));
|
||||
|
||||
/* Stay below X11's normal maximum property request. Never paste a truncated command. */
|
||||
#define MAX_TEXT (64 * 1024)
|
||||
static int ignore_x_error(Display *d, void *event) { (void)d; (void)event; return 0; }
|
||||
|
||||
/* The host renames complete files into place. The inode distinguishes copying the same
|
||||
* text again after a guest program has taken ownership of the clipboard. */
|
||||
static int refresh(Display *d, Window w, Atom clipboard, const char *path,
|
||||
char **text, size_t *len, ino_t *inode) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
@@ -98,7 +91,7 @@ int main(int argc, char **argv) {
|
||||
LOAD(XSetErrorHandler);
|
||||
Display *d = XOpenDisplay(NULL);
|
||||
if (!d) { fprintf(stderr, "== clipboard: cannot open Xwayland\n"); return 1; }
|
||||
XSetErrorHandler(ignore_x_error); /* A paste requester can close its window at any time. */
|
||||
XSetErrorHandler(ignore_x_error);
|
||||
Window w = XCreateSimpleWindow(d, XDefaultRootWindow(d), 0, 0, 1, 1, 0, 0, 0);
|
||||
Atom clipboard = XInternAtom(d, "CLIPBOARD", 0);
|
||||
Atom targets = XInternAtom(d, "TARGETS", 0), utf8 = XInternAtom(d, "UTF8_STRING", 0);
|
||||
@@ -117,7 +110,7 @@ int main(int argc, char **argv) {
|
||||
for (;;) {
|
||||
while (XPending(d)) {
|
||||
Event e; XNextEvent(d, &e);
|
||||
if (e.type != 30) continue; /* SelectionRequest */
|
||||
if (e.type != 30) continue;
|
||||
SelectionRequest *r = &e.request;
|
||||
Atom property = r->property ? r->property : r->target;
|
||||
Event reply = {0};
|
||||
@@ -126,14 +119,13 @@ int main(int argc, char **argv) {
|
||||
size_t ascii; for (ascii = 0; ascii < len && (unsigned char)text[ascii] < 128; ascii++) {}
|
||||
if (r->target == targets) {
|
||||
Atom supported[] = {targets, utf8, plain, text_atom, string};
|
||||
XChangeProperty(d, r->requestor, property, 4 /* XA_ATOM */, 32, 0,
|
||||
XChangeProperty(d, r->requestor, property, 4 , 32, 0,
|
||||
(const unsigned char *)supported, ascii == len ? 5 : 4);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == utf8 || r->target == plain || r->target == text_atom) {
|
||||
XChangeProperty(d, r->requestor, property, utf8, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == string) {
|
||||
/* STRING is Latin-1. Offer it only for ASCII rather than corrupt UTF-8. */
|
||||
if (ascii == len) {
|
||||
XChangeProperty(d, r->requestor, property, string, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
# The Debian 11 image the x86 preloads are compiled in (glibc 2.31, what Steam's Linux runtime
|
||||
# has). Published once by .github/workflows/ci-debian-image.yml to a release on this repo; the
|
||||
# build downloads it from there instead of pulling from a public registry mirror, whose
|
||||
# anonymous rate limit the shared runners keep hitting. Debian 11 is frozen upstream, so a
|
||||
# refresh is only ever a new -rN release with the three lines below updated.
|
||||
DEBIAN_IMAGE_TAG=ci-debian-bullseye-r1
|
||||
DEBIAN_IMAGE_ASSET=debian-bullseye.tar.zst
|
||||
DEBIAN_IMAGE_SHA256=5ac13c6b0f2e3ab3e8acc8cadcd39ee453a51a72870645d592635e24bcb85459
|
||||
@@ -1,91 +1,48 @@
|
||||
#!/bin/bash
|
||||
# The desktop session: KDE Plasma, set up as SteamOS's desktop mode - KWin nested as a client of the
|
||||
# app's compositor, Plasma's shell on it, and Xwayland for the X11 programs (the Steam client, most
|
||||
# emulators). Run by droiddeck-session in place of gamescope for mode "lxqt" (the mode's name from
|
||||
# the LXQt desktop this replaced; it is what the app and its preferences use).
|
||||
# Staged by the app over the desktop package's copy on every launch, so a fix here reaches an
|
||||
# installed desktop without re-downloading the package.
|
||||
set -u
|
||||
export XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=KDE XDG_SESSION_DESKTOP=KDE DESKTOP_SESSION=plasma
|
||||
export KDE_FULL_SESSION=true KDE_SESSION_VERSION=6 KDE_APPLICATIONS_AS_SCOPE=0
|
||||
# Qt tries Wayland and falls back to X11 (Xwayland): an AppImage that bundles only Qt's xcb
|
||||
# plugin - melonDS - exits at once on a plain "wayland" ("Could not find the Qt platform plugin").
|
||||
export QT_QPA_PLATFORM="wayland;xcb" GDK_BACKEND=wayland,x11 SDL_VIDEODRIVER=wayland,x11
|
||||
unset QT_QPA_PLATFORMTHEME
|
||||
# KDE's programs log through Qt, which writes to the journal when stderr is not a terminal; there is
|
||||
# no journal here, so their messages go to the desktop log with everything else.
|
||||
export QT_FORCE_STDERR_LOGGING=1
|
||||
# SteamOS's /etc/profile.d/kde.sh.
|
||||
export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1
|
||||
# Konsole's profile starts the login shell, which it finds here.
|
||||
export SHELL=/bin/bash
|
||||
# Firefox's child processes sandbox themselves with seccomp and namespaces, neither of which
|
||||
# behaves under proot: the content process ends up unable to read the font files its parent can,
|
||||
# reports "no fonts" and dies - the tab crash, with the chrome around it still drawing text.
|
||||
# The prefs for this are only advisory and a profile can override them; the environment is not.
|
||||
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
|
||||
# Firefox seals the size of the shared memory it hands a tab; on Android 16 (Galaxy S25/S26,
|
||||
# RedMagic) adding the seal fails, Firefox only warns, and the tab refuses the unsealed memory
|
||||
# ("Shared memory PlatformHandle is not safe to map") and dies on signal 11 - every page. Firefox's
|
||||
# own switch skips the seals. (#280; the line went missing in the fontconfig move of #252.)
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
# KWin composites in software (QPainter): its GPU path allocates through gbm on a DRM render node,
|
||||
# and the KGSL stand-in is not one. Its windows get shm buffers only, so GL programs on it draw with
|
||||
# Mesa's software rasterizer, Plasma's own Qt Quick draws with Qt's software renderer (plasmashell
|
||||
# crashes on llvmpipe here), and a Vulkan program cannot draw at all: games and emulators from the
|
||||
# menu run through droiddeck-gpu (their own gamescope on the app's compositor), and Steam goes back
|
||||
# to the app as a Steam session - SteamOS's "Return to Gaming Mode". The session's own GL choice
|
||||
# (zink on Turnip, for the Steam client) is put back by droiddeck-gpu.
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
# mpv refuses that software GL and then fails its X11 fallback (an assertion): allowed it, it plays.
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
export DROIDDECK_NESTED_SCALE=1
|
||||
export DROIDDECK_GLTHREAD=${mesa_glthread:-}
|
||||
unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 mesa_glthread
|
||||
# The desktop's own log, beside the session's, so KWin and the programs on it can be read apart
|
||||
# from the session that started them. The session log keeps the milestones either way.
|
||||
if [ -n "${BL_DEBUG_DIR:-}" ]; then
|
||||
mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true
|
||||
exec >>"$BL_DEBUG_DIR/desktop.log" 2>&1
|
||||
echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-1280}x${BL_HEIGHT:-720}"
|
||||
fi
|
||||
# The runtime directory outlives a session. KDE's daemons are single-instance programs that leave a
|
||||
# lock and a socket there; finding last session's, they decide they are already running and exit
|
||||
# without a word. Only the app's own compositor socket (wayland-0) is kept.
|
||||
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null
|
||||
chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null
|
||||
# KWin will not start Xwayland when its socket directory is not sticky, as a shared /tmp would be,
|
||||
# and Plasma's session manager cannot listen at all without the ICE directory, which only root may
|
||||
# create for it.
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null
|
||||
# Fontconfig defaults and Android language fallbacks are set up by droiddeck-session before this
|
||||
# script or any desktop program starts.
|
||||
# The menu's "Steam" / "Steam Big Picture" entries and one entry per installed game: all of them
|
||||
# hand off to the app (droiddeck-steam-launch), since the client cannot draw on this desktop.
|
||||
export BL_DESKTOP=1
|
||||
ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
|
||||
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
|
||||
python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /'
|
||||
# Player 1 on the controller in every emulator that has no profile of its own yet - now, and again
|
||||
# every half minute: an emulator started for the first time writes its own config, which is then
|
||||
# given the controller for its next start without waiting for the next desktop.
|
||||
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Steam x86-64 (FEX, experimental)
|
||||
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
|
||||
Exec=qterminal -e /usr/local/bin/droiddeck-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
|
||||
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
|
||||
# Games and emulators from the menu run through droiddeck-gpu; BL_DESKTOP_GPU=on/off overrides,
|
||||
# and each entry keeps "Run in a desktop window" either way.
|
||||
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
|
||||
# The windowed action still opens melonDS at the size/placement the LXQt desktop used.
|
||||
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
|
||||
# Windows programs, Linux programs, AppImages and scripts open with droiddeck-open (Steam's Proton,
|
||||
# FEX for x86); an exec the kernel refuses is handed to it as well (libblsession's binfmt.c). An
|
||||
# AppImage run directly cannot mount itself under proot, so it unpacks itself to run.
|
||||
python3 /usr/local/bin/droiddeck-open --install 2>&1 | sed 's/^/[open] /'
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
# A click runs an executable script or program without KIO asking first; Dolphin's settings can still ask.
|
||||
[ -e /etc/xdg/kiorc ] || printf '[Executable scripts]\nbehaviourOnLaunch=execute\n' >/etc/xdg/kiorc 2>/dev/null
|
||||
# SteamOS's desktop icons: Return to Gaming Mode and Steam, put there once - what the user moves
|
||||
# or deletes stays that way.
|
||||
desktop_dir=$(xdg-user-dir DESKTOP 2>/dev/null); [ -n "$desktop_dir" ] && [ "$desktop_dir" != "$HOME" ] || desktop_dir=$HOME/Desktop
|
||||
if [ ! -e "$HOME/.config/droiddeck-desktop-icons" ]; then
|
||||
mkdir -p "$desktop_dir" "$HOME/.config"
|
||||
@@ -94,23 +51,16 @@ if [ ! -e "$HOME/.config/droiddeck-desktop-icons" ]; then
|
||||
chmod +x "$desktop_dir"/*.desktop 2>/dev/null
|
||||
touch "$HOME/.config/droiddeck-desktop-icons"
|
||||
fi
|
||||
# A Return icon still there is kept current with the package's entry (what it runs has changed).
|
||||
[ -f "$desktop_dir/Return.desktop" ] && cp -f /usr/share/applications/droiddeck-return-gaming.desktop "$desktop_dir/Return.desktop" 2>/dev/null
|
||||
# Plasma's caches of the menu, the icons and the MIME types, which a package install never ran.
|
||||
update-mime-database /usr/share/mime >/dev/null 2>&1 &
|
||||
[ -f /usr/share/icons/hicolor/icon-theme.cache ] || gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null &
|
||||
[ -f /usr/share/glib-2.0/schemas/gschemas.compiled ] || glib-compile-schemas /usr/share/glib-2.0/schemas 2>/dev/null
|
||||
# In debug runs Firefox (started from the panel or the menu, so it inherits this) writes its
|
||||
# own network log: name lookups, connects, HTTP transactions, the link/offline decisions.
|
||||
if [ -f "$HOME/.droiddeck-desktop-debug" ]; then
|
||||
mkdir -p "$HOME/.cache/droiddeck"
|
||||
export MOZ_LOG="nsHttp:3,nsSocketTransport:3,nsHostResolver:4,NetworkLinkService:5,NetworkConnectivityService:5,nsIOService:5"
|
||||
export MOZ_LOG_FILE="$HOME/.cache/droiddeck/firefox-net.log"
|
||||
export QT_LOGGING_RULES="kwin_*.debug=true"
|
||||
fi
|
||||
# Remote runs, for driving the desktop from a debugger: with ~/.droiddeck-remote-run present (only
|
||||
# the app or root can create it), each script dropped into ~/.cache/droiddeck/run/ is run once,
|
||||
# inside the session with its environment, its output tagged into the desktop log.
|
||||
if [ -f "$HOME/.droiddeck-remote-run" ]; then
|
||||
mkdir -p "$HOME/.cache/droiddeck/run"
|
||||
(
|
||||
@@ -123,18 +73,10 @@ if [ -f "$HOME/.droiddeck-remote-run" ]; then
|
||||
done
|
||||
) &
|
||||
fi
|
||||
# Plasma as its own login starts it: startplasma-wayland sets up the session's environment and runs
|
||||
# plasma_session, which starts KWin (through kwin_wayland_wrapper, ours first on PATH) as a client of
|
||||
# the app's compositor with its own Xwayland, then Plasma's daemons, shell and autostart entries on
|
||||
# it. The session bus is ours: Plasma, the file manager and the portal all expect one.
|
||||
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
|
||||
dbus-run-session -- startplasma-wayland
|
||||
rc=$?
|
||||
echo "== droiddeck-desktop: Plasma ended ($rc)"
|
||||
# Plasma logged out - Log Out, or Return to Gaming Mode, which logs out the same way, so open windows
|
||||
# are asked to close (and to save) first. As on SteamOS, leaving the desktop goes to Gaming Mode: the
|
||||
# app is asked for a Steam session, and it ends this one to start it. A desktop the app stops never
|
||||
# gets here; a Plasma that failed does not count as a logout.
|
||||
if [ "$rc" -eq 0 ]; then
|
||||
/usr/local/bin/droiddeck-steam-launch bigpicture
|
||||
sleep 30
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
#!/usr/bin/python3
|
||||
# The desktop's games and emulators, started on the GPU. Every menu entry whose categories say
|
||||
# Game or Emulator gets a copy of its own in ~/.local/share/applications (which wins over
|
||||
# /usr/share/applications) whose Exec runs it through droiddeck-gpu: full screen on the app's
|
||||
# compositor, where Vulkan and OpenGL work. The entry keeps the old way as a second action, "Run in
|
||||
# a desktop window". Run at every desktop start; copies whose original is gone, or all of them when
|
||||
# the switch is off, are removed.
|
||||
#
|
||||
# BL_DESKTOP_GPU=on (default: the desktop composites in software) | off
|
||||
import os
|
||||
import re
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
SYSTEM_DIR = "/usr/share/applications"
|
||||
# The user's own AppImages (the front end's Add AppImage).
|
||||
LOCAL_DIR = "/usr/local/share/applications"
|
||||
# Flathub's games, as Flatpak exports them; the copies here win over these as they do over the system's.
|
||||
FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/applications")
|
||||
USER_DIR = os.path.join(HOME, ".local/share/applications")
|
||||
MARK = "X-DroidDeck-GPU=1"
|
||||
# The client and its games already hand themselves to the app (droiddeck-steam-launch).
|
||||
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
|
||||
|
||||
|
||||
@@ -76,7 +65,6 @@ def wrap(text):
|
||||
out_group.append("Actions=" + ("droiddeck-window;" + actions if actions else "droiddeck-window;"))
|
||||
out_group.append(MARK)
|
||||
window = ["", "[Desktop Action droiddeck-window]", "Name=Run in a desktop window", "Exec=" + exec_line]
|
||||
# The entry's own actions (new window, a different mode...) run on the GPU as well.
|
||||
wrapped_rest = []
|
||||
for l in rest:
|
||||
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
|
||||
@@ -105,7 +93,6 @@ def main():
|
||||
if not name.endswith(".desktop") or SKIP.match(name):
|
||||
continue
|
||||
target = os.path.join(USER_DIR, name)
|
||||
# A copy the user made or edited themselves is theirs.
|
||||
if os.path.exists(target) and not ours(target):
|
||||
continue
|
||||
try:
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
#!/bin/bash
|
||||
# Runs a program from the desktop on the GPU: in a gamescope of its own that draws straight into
|
||||
# the app's compositor (wayland-0), not inside the desktop's KWin. KWin composites in software, and
|
||||
# gives its windows no DMA-BUFs - a Vulkan program there fails at its swapchain
|
||||
# (VK_ERROR_SURFACE_LOST, RPCS3's error). Here it gets the same path as a program started from the
|
||||
# app's rail: full screen over the desktop until it exits, then the desktop is back.
|
||||
# droiddeck-gpu <program> [args...]
|
||||
set -u
|
||||
[ $# -gt 0 ] || { echo "usage: droiddeck-gpu <program> [args...]" >&2; exit 64; }
|
||||
if [ -n "${BL_DEBUG_DIR:-}" ]; then
|
||||
@@ -20,16 +14,11 @@ elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
|
||||
fi
|
||||
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
|
||||
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
|
||||
# gamescope is a client of the app's compositor, beside the desktop's KWin; the program inside it reaches it
|
||||
# through gamescope's own Xwayland, as in a Steam session.
|
||||
export WAYLAND_DISPLAY=wayland-0
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
# GL on the GPU again (zink on Turnip, as the session sets it): the desktop itself draws GL in software.
|
||||
# Qt Quick back on its GPU renderer and KWin's software compositing not passed on, too.
|
||||
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
|
||||
export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
|
||||
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
|
||||
# AppImages cannot mount under proot; the menu entries already say so, a hand-typed one may not.
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
|
||||
rc=$?
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
// Firefox defaults for the DroidDeck desktop, staged by the app into
|
||||
// /usr/lib/firefox/defaults/pref/. A user's own prefs.js still wins.
|
||||
|
||||
// Firefox judges "online" by dumping the routing table over netlink, which Android denies to
|
||||
// apps; seeing no default route it switches itself to Work Offline and every page fails while
|
||||
// the network is fine. Let it just try.
|
||||
pref("network.manage-offline-status", false);
|
||||
pref("browser.offline", false);
|
||||
// No user namespaces on Android kernels and a ptrace'd process tree: the process sandboxes
|
||||
// have nothing to set up and only add failure modes.
|
||||
pref("security.sandbox.content.level", 0);
|
||||
pref("media.cubeb.sandbox", false);
|
||||
pref("security.sandbox.socket.process.level", 0);
|
||||
// Handheld-sized chrome, and nothing phoning home on first run.
|
||||
pref("browser.shell.checkDefaultBrowser", false);
|
||||
pref("datareporting.policy.dataSubmissionEnabled", false);
|
||||
pref("browser.aboutwelcome.enabled", false);
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
#!/bin/bash
|
||||
# KWin for the desktop. Plasma's session (plasma_session) starts KWin through kwin_wayland_wrapper as
|
||||
# found on PATH; this one, first on it, has KWin draw into the app's compositor (wayland-0) and serve
|
||||
# its own clients on wayland-1 - by default it takes wayland-0 and finds the app's lock on it - with
|
||||
# its nested output at the app's surface size (left alone, a 1024x768 window the desktop is scaled
|
||||
# from), and without the lock screen, which the app's own suspend stands in for. Anything else (a KWin
|
||||
# started outside DroidDeck's desktop) gets the real wrapper as it is.
|
||||
if [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
set -- --wayland-display wayland-0 --socket wayland-1 --width "${BL_WIDTH:-1280}" --height "${BL_HEIGHT:-720}" --no-lockscreen "$@"
|
||||
fi
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
#if !defined(__x86_64__)
|
||||
#error thunkaudit is built for x86_64 guests only
|
||||
#endif
|
||||
|
||||
#define LA_SER_ORIG 0x01
|
||||
|
||||
static const char vulkan_thunk[] = "/usr/lib/x86_64-linux-gnu/libvulkan.so.1";
|
||||
static const char vulkan_pin[] = "/usr/lib/x86_64-linux-gnu/droiddeck/libvulkan-thunk.so";
|
||||
|
||||
static int same(const char *a, const char *b)
|
||||
{
|
||||
while (*a && *a == *b) {
|
||||
a++;
|
||||
b++;
|
||||
}
|
||||
return *a == *b;
|
||||
}
|
||||
|
||||
static const char *base_name(const char *path)
|
||||
{
|
||||
const char *name = path;
|
||||
for (; *path; path++)
|
||||
if (*path == '/')
|
||||
name = path + 1;
|
||||
return name;
|
||||
}
|
||||
|
||||
__attribute__((visibility("default"))) unsigned int la_version(unsigned int version)
|
||||
{
|
||||
return version;
|
||||
}
|
||||
|
||||
__attribute__((visibility("default"))) char *la_objsearch(const char *name, unsigned long *cookie, unsigned int flag)
|
||||
{
|
||||
const char *file = base_name(name);
|
||||
(void)cookie;
|
||||
if (flag == LA_SER_ORIG && !same(name, vulkan_thunk) && (same(file, "libvulkan.so.1") || same(file, "libvulkan.so")))
|
||||
return (char *)vulkan_pin;
|
||||
return (char *)name;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
#include <dlfcn.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef VULKAN_THUNK
|
||||
#define VULKAN_THUNK "/usr/lib/x86_64-linux-gnu/libvulkan.so.1"
|
||||
#endif
|
||||
|
||||
#define VK_INCOMPLETE 5
|
||||
#define VK_ERROR_INITIALIZATION_FAILED (-3)
|
||||
#define EXTENSIONS 128
|
||||
|
||||
typedef int VkResult;
|
||||
typedef void (*Function)(void);
|
||||
typedef struct {
|
||||
char extensionName[256];
|
||||
unsigned int specVersion;
|
||||
} VkExtensionProperties;
|
||||
typedef VkResult (*Enumerate)(const char *, unsigned int *, VkExtensionProperties *);
|
||||
typedef Function (*ProcAddr)(void *, const char *);
|
||||
|
||||
/* The driver cannot enumerate devices for an instance with VK_KHR_display, and gamescope's WSI layer aborts on that. */
|
||||
static const char *const hidden_extensions[] = {
|
||||
"VK_KHR_display",
|
||||
"VK_KHR_get_display_properties2",
|
||||
"VK_EXT_direct_mode_display",
|
||||
"VK_EXT_acquire_xlib_display",
|
||||
"VK_EXT_acquire_drm_display",
|
||||
"VK_EXT_display_surface_counter",
|
||||
};
|
||||
|
||||
static void *thunk(const char *name)
|
||||
{
|
||||
void *library = dlopen(VULKAN_THUNK, RTLD_NOW | RTLD_NOLOAD);
|
||||
void *found = library ? dlsym(library, name) : NULL;
|
||||
if (library)
|
||||
dlclose(library);
|
||||
return found;
|
||||
}
|
||||
|
||||
static int hidden(const char *name)
|
||||
{
|
||||
for (size_t i = 0; i < sizeof(hidden_extensions) / sizeof(hidden_extensions[0]); i++)
|
||||
if (!strcmp(name, hidden_extensions[i]))
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
__attribute__((visibility("default"))) VkResult vkEnumerateInstanceExtensionProperties(const char *layer, unsigned int *count,
|
||||
VkExtensionProperties *properties)
|
||||
{
|
||||
static Enumerate real;
|
||||
VkExtensionProperties all[EXTENSIONS];
|
||||
unsigned int total = EXTENSIONS, kept = 0, room = properties ? *count : 0;
|
||||
VkResult result;
|
||||
if (!real)
|
||||
real = (Enumerate)thunk("vkEnumerateInstanceExtensionProperties");
|
||||
if (!real)
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
result = real(layer, &total, all);
|
||||
if (result < 0)
|
||||
return result;
|
||||
for (unsigned int i = 0; i < total; i++) {
|
||||
if (hidden(all[i].extensionName))
|
||||
continue;
|
||||
if (properties && kept < room)
|
||||
memcpy(&properties[kept], &all[i], sizeof(all[i]));
|
||||
kept++;
|
||||
}
|
||||
if (!properties) {
|
||||
*count = kept;
|
||||
return result;
|
||||
}
|
||||
*count = kept < room ? kept : room;
|
||||
return kept > room ? VK_INCOMPLETE : result;
|
||||
}
|
||||
|
||||
__attribute__((visibility("default"))) Function vkGetInstanceProcAddr(void *instance, const char *name)
|
||||
{
|
||||
static ProcAddr real;
|
||||
if (!strcmp(name, "vkGetInstanceProcAddr"))
|
||||
return (Function)vkGetInstanceProcAddr;
|
||||
if (!strcmp(name, "vkEnumerateInstanceExtensionProperties"))
|
||||
return (Function)vkEnumerateInstanceExtensionProperties;
|
||||
if (!real)
|
||||
real = (ProcAddr)thunk("vkGetInstanceProcAddr");
|
||||
return real ? real(instance, name) : NULL;
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
#if !defined(__x86_64__)
|
||||
#error webkitinput is built for x86_64 guests only
|
||||
#endif
|
||||
|
||||
typedef struct _WebKitSettings WebKitSettings;
|
||||
typedef struct _WebKitUserContentManager WebKitUserContentManager;
|
||||
typedef struct _WebKitUserScript WebKitUserScript;
|
||||
|
||||
extern void g_object_set(void *object, const char *first_property, ...) __attribute__((weak));
|
||||
extern void *g_object_get_data(void *object, const char *key) __attribute__((weak));
|
||||
extern void g_object_set_data(void *object, const char *key, void *data) __attribute__((weak));
|
||||
extern void *dlsym(void *handle, const char *symbol) __attribute__((weak));
|
||||
extern unsigned gtk_key_snooper_install(int (*snooper)(void *, void *, void *), void *data) __attribute__((weak));
|
||||
extern void *gtk_widget_get_toplevel(void *widget) __attribute__((weak));
|
||||
extern void gtk_container_forall(void *container, void (*callback)(void *, void *), void *data) __attribute__((weak));
|
||||
extern unsigned long gtk_container_get_type(void) __attribute__((weak));
|
||||
extern unsigned long webkit_web_view_get_type(void) __attribute__((weak));
|
||||
extern int g_type_check_instance_is_a(void *instance, unsigned long type) __attribute__((weak));
|
||||
extern const char *webkit_web_view_get_uri(void *view) __attribute__((weak));
|
||||
extern void webkit_web_view_run_javascript(void *view, const char *script, void *cancellable, void *callback,
|
||||
void *data) __attribute__((weak));
|
||||
extern WebKitUserScript *webkit_user_script_new(const char *source, int frames, int time,
|
||||
const char *const *allow, const char *const *block) __attribute__((weak));
|
||||
extern void webkit_user_script_unref(WebKitUserScript *script) __attribute__((weak));
|
||||
|
||||
static const char NAV_SCRIPT[] =
|
||||
"(()=>{let open=-1e9,arrowAt=-1e9,ringed=null,ringOutline='',ringOffset='',settleTimer=0,settling=false,redirecting=false;"
|
||||
"const shown=()=>[...document.querySelectorAll('[role=dialog],[role=alertdialog],[aria-modal=true],[role=menu]')]"
|
||||
".some(e=>e.getClientRects().length);"
|
||||
"const hidden=e=>{const r=e.getBoundingClientRect();if(!r.width||!r.height)return true;"
|
||||
"for(let n=e;n&&n.nodeType===1;n=n.parentElement){const s=getComputedStyle(n);"
|
||||
"if(s.visibility==='hidden'||+s.opacity<0.1)return true;}return false;};"
|
||||
"const windowButton=e=>/^(Minimize|Maximize|Restore|Close) window$/.test(e.getAttribute('aria-label')||'');"
|
||||
"const editing=e=>!!e&&e.nodeType===1&&(e.isContentEditable||"
|
||||
"e.matches('input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]),textarea,select'));"
|
||||
"const mainNav=()=>[...document.querySelectorAll('nav')].filter(n=>n.querySelectorAll('a[href]').length>1&&!hidden(n))"
|
||||
".sort((a,b)=>a.getBoundingClientRect().y-b.getBoundingClientRect().y)[0];"
|
||||
"const first=nav=>{const below=nav?nav.getBoundingClientRect().bottom:0,all=[];"
|
||||
"for(const e of document.querySelectorAll('a[href],button,input,[role=button],[tabindex]')){"
|
||||
"if(e.tabIndex<0||(nav&&nav.contains(e)))continue;const r=e.getBoundingClientRect();"
|
||||
"if(r.top<below||r.bottom>innerHeight||windowButton(e)||hidden(e))continue;all.push({e,r});}"
|
||||
"const big=all.filter(c=>c.r.width*c.r.height>=12000),list=big.length?big:all;"
|
||||
"const key=c=>Math.round(c.r.top/8)*1e5+c.r.left;"
|
||||
"list.sort((a,b)=>key(a)-key(b));return list.length?list[0].e:null;};"
|
||||
"const big=e=>{const r=e.getBoundingClientRect();return r.width*r.height>=12000;};"
|
||||
"const toward=(from,key,nav,small)=>{const r=from.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;let best=null,score=1e9;"
|
||||
"for(const c of document.querySelectorAll('a[href],button,[role=button],[tabindex]')){if(c===from||c.tabIndex<0||(nav&&nav.contains(c))||from.contains(c)||c.contains(from))continue;"
|
||||
"const q=c.getBoundingClientRect();if(!small&&q.width*q.height<12000)continue;const qx=q.left+q.width/2,qy=q.top+q.height/2;let along,across;"
|
||||
"if(key==='ArrowDown'){along=q.top-r.bottom;across=qx-cx;}else if(key==='ArrowUp'){along=r.top-q.bottom;across=qx-cx;}"
|
||||
"else if(key==='ArrowRight'){along=q.left-r.right;across=qy-cy;}else{along=r.left-q.right;across=qy-cy;}"
|
||||
"if(along<-4)continue;const d=Math.max(along,0)+2*Math.abs(across);if(d<score&&!windowButton(c)&&!hidden(c)){score=d;best=c;}}return best;};"
|
||||
"const settle=()=>{const a=document.activeElement;if(editing(a)||shown())return;const nav=mainNav(),list=[];"
|
||||
"for(const c of document.querySelectorAll('a[href],button,[role=button],[tabindex]')){if(c.tabIndex<0||(nav&&nav.contains(c)))continue;"
|
||||
"const r=c.getBoundingClientRect();if(r.width*r.height>=12000&&r.top>=0&&r.left>=0&&r.bottom<=innerHeight&&r.right<=innerWidth)list.push({c,r});}"
|
||||
"const key=x=>Math.round(x.r.top/8)*1e5+x.r.left;list.sort((x,y)=>key(x)-key(y));"
|
||||
"for(const {c,r} of list){const hit=document.elementFromPoint(r.left+r.width/2,r.top+8);"
|
||||
"if(hit&&(hit===c||c.contains(hit))&&!hidden(c)){arrowAt=performance.now();c.focus({preventScroll:true});return;}}};"
|
||||
"const arm=()=>{clearTimeout(settleTimer);settleTimer=setTimeout(()=>{settling=false;settle();},200);};"
|
||||
"addEventListener('scroll',()=>{if(settling)arm();},true);"
|
||||
"const unring=()=>{if(ringed){ringed.style.outline=ringOutline;ringed.style.outlineOffset=ringOffset;ringed=null;}};"
|
||||
"addEventListener('keydown',e=>{const k=e.key||'';if(k.startsWith('Arrow')){arrowAt=e.timeStamp;const a=document.activeElement;"
|
||||
"if(!editing(a)&&!shown()){const nav=mainNav();"
|
||||
"if(!a||a===document.body||hidden(a)||(k==='ArrowDown'&&nav&&nav.contains(a))){const f=first(nav);"
|
||||
"if(f){e.preventDefault();e.stopImmediatePropagation();f.focus();f.scrollIntoView({block:'nearest'});}}"
|
||||
"else if(big(a)&&!e.ctrlKey&&!e.altKey){let t=toward(a,k,nav);"
|
||||
"if(!t&&(k==='ArrowUp'||k==='ArrowDown'))t=toward(a,k,nav,true);"
|
||||
"if(t){e.preventDefault();e.stopImmediatePropagation();t.focus({preventScroll:true});t.scrollIntoView({block:'nearest',inline:'nearest'});}}}}"
|
||||
"if(k==='Escape')open=shown()?e.timeStamp:-1e9;"
|
||||
"if(e.code==='F13'){e.preventDefault();e.stopImmediatePropagation();settling=true;arm();}},true);"
|
||||
"addEventListener('keydown',e=>{if(e.key!=='BrowserBack')return;e.preventDefault();e.stopImmediatePropagation();"
|
||||
"const a=document.activeElement;if(editing(a)){a.blur();return;}"
|
||||
"if(e.timeStamp-open>500)history.back();},true);"
|
||||
"window.droiddeckTab=step=>{"
|
||||
"const nav=mainNav();if(!nav)return;"
|
||||
"const tabs=[...nav.querySelectorAll('a[href]')].filter(a=>!hidden(a)),part=p=>p.split('/')[1]||'';"
|
||||
"const at=tabs.findIndex(a=>part(new URL(a.href).pathname)===part(location.pathname));"
|
||||
"const to=tabs[Math.min(tabs.length-1,Math.max(0,at+step))];"
|
||||
"if(at>=0&&to!==tabs[at]){to.click();to.blur();}};"
|
||||
"const redirect=n=>{redirecting=true;try{n.focus();}finally{redirecting=false;}};"
|
||||
"addEventListener('focusout',unring,true);"
|
||||
"addEventListener('focusin',e=>{const t=e.target;if(!(t instanceof Element)||e.timeStamp-arrowAt>1000)return;"
|
||||
"const back=e.relatedTarget instanceof Element&&e.relatedTarget.focus?e.relatedTarget:null;"
|
||||
"if(!redirecting&&windowButton(t)){if(back)redirect(back);return;}"
|
||||
"if(!redirecting&&hidden(t)){let a=t.parentElement;"
|
||||
"while(a&&!(a.matches('a[href],button,[role=button],[tabindex]')&&!hidden(a)))a=a.parentElement;"
|
||||
"if(a)redirect(a);else if(back)redirect(back);return;}"
|
||||
"unring();ringed=(t.matches('input,textarea')&&t.closest('label'))||t;"
|
||||
"ringOutline=ringed.style.outline;ringOffset=ringed.style.outlineOffset;"
|
||||
"ringed.style.outline='3px solid #fff';ringed.style.outlineOffset='2px';},true);})();";
|
||||
|
||||
typedef struct {
|
||||
int type;
|
||||
void *window;
|
||||
signed char send_event;
|
||||
unsigned time;
|
||||
unsigned state;
|
||||
unsigned keyval;
|
||||
} KeyEvent;
|
||||
|
||||
static void *launcher_view;
|
||||
|
||||
static void find_launcher_view(void *widget, void *data)
|
||||
{
|
||||
(void)data;
|
||||
if (launcher_view)
|
||||
return;
|
||||
if (g_type_check_instance_is_a(widget, webkit_web_view_get_type())) {
|
||||
const char *uri = webkit_web_view_get_uri(widget);
|
||||
const char *prefix = "tauri:";
|
||||
while (uri && *prefix && *uri == *prefix) {
|
||||
uri++;
|
||||
prefix++;
|
||||
}
|
||||
if (uri && !*prefix)
|
||||
launcher_view = widget;
|
||||
} else if (g_type_check_instance_is_a(widget, gtk_container_get_type())) {
|
||||
gtk_container_forall(widget, find_launcher_view, 0);
|
||||
}
|
||||
}
|
||||
|
||||
static int switch_tab(void *grab, void *event_data, void *data)
|
||||
{
|
||||
KeyEvent *event = event_data;
|
||||
(void)data;
|
||||
if (!grab || event->type != 8 || !(event->state & 4) || (event->keyval != 0xff55 && event->keyval != 0xff56))
|
||||
return 0;
|
||||
launcher_view = 0;
|
||||
find_launcher_view(gtk_widget_get_toplevel(grab), 0);
|
||||
if (!launcher_view)
|
||||
return 0;
|
||||
webkit_web_view_run_javascript(launcher_view, event->keyval == 0xff56 ? "window.droiddeckTab&&droiddeckTab(1)"
|
||||
: "window.droiddeckTab&&droiddeckTab(-1)",
|
||||
0, 0, 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void watch_tab_keys(void)
|
||||
{
|
||||
static int watching;
|
||||
if (watching || !gtk_key_snooper_install || !gtk_widget_get_toplevel || !gtk_container_forall ||
|
||||
!gtk_container_get_type || !webkit_web_view_get_type || !g_type_check_instance_is_a ||
|
||||
!webkit_web_view_get_uri || !webkit_web_view_run_javascript)
|
||||
return;
|
||||
watching = 1;
|
||||
gtk_key_snooper_install(switch_tab, 0);
|
||||
}
|
||||
|
||||
static void set(WebKitSettings *settings, const char *setter, const char *property, int value)
|
||||
{
|
||||
static int setting;
|
||||
if (setting) {
|
||||
void (*next)(WebKitSettings *, int) = dlsym ? (void (*)(WebKitSettings *, int))dlsym((void *)-1l, setter) : 0;
|
||||
if (next)
|
||||
next(settings, value);
|
||||
return;
|
||||
}
|
||||
if (!g_object_set)
|
||||
return;
|
||||
setting = 1;
|
||||
g_object_set(settings, property, value, "enable-smooth-scrolling", 0, "enable-spatial-navigation", 1, (const char *)0);
|
||||
setting = 0;
|
||||
}
|
||||
|
||||
#define SETTER(name, property) \
|
||||
__attribute__((visibility("default"))) void webkit_settings_set_##name(WebKitSettings *settings, int value) \
|
||||
{ \
|
||||
set(settings, "webkit_settings_set_" #name, property, value); \
|
||||
}
|
||||
|
||||
SETTER(enable_javascript, "enable-javascript")
|
||||
SETTER(enable_developer_extras, "enable-developer-extras")
|
||||
SETTER(enable_webgl, "enable-webgl")
|
||||
SETTER(enable_webaudio, "enable-webaudio")
|
||||
SETTER(enable_page_cache, "enable-page-cache")
|
||||
SETTER(javascript_can_access_clipboard, "javascript-can-access-clipboard")
|
||||
SETTER(javascript_can_open_windows_automatically, "javascript-can-open-windows-automatically")
|
||||
SETTER(enable_back_forward_navigation_gestures, "enable-back-forward-navigation-gestures")
|
||||
|
||||
__attribute__((visibility("default"))) void webkit_user_content_manager_add_script(WebKitUserContentManager *manager,
|
||||
WebKitUserScript *script)
|
||||
{
|
||||
static void (*next)(WebKitUserContentManager *, WebKitUserScript *);
|
||||
if (!next && dlsym)
|
||||
next = (void (*)(WebKitUserContentManager *, WebKitUserScript *))dlsym((void *)-1l, "webkit_user_content_manager_add_script");
|
||||
if (!next)
|
||||
return;
|
||||
watch_tab_keys();
|
||||
if (g_object_get_data && g_object_set_data && webkit_user_script_new && webkit_user_script_unref &&
|
||||
!g_object_get_data(manager, "droiddeck-nav")) {
|
||||
g_object_set_data(manager, "droiddeck-nav", (void *)1);
|
||||
WebKitUserScript *nav = webkit_user_script_new(NAV_SCRIPT, 1, 0, 0, 0);
|
||||
if (nav) {
|
||||
next(manager, nav);
|
||||
webkit_user_script_unref(nav);
|
||||
}
|
||||
}
|
||||
next(manager, script);
|
||||
}
|
||||
@@ -1,3 +1,2 @@
|
||||
#!/bin/sh
|
||||
# No Deck BIOS here. The client calls this in Deck mode; a clean exit is "nothing to do".
|
||||
exit 0
|
||||
@@ -1,3 +1,2 @@
|
||||
#!/bin/sh
|
||||
# No Deck BIOS here. The client calls this in Deck mode; a clean exit is "nothing to do".
|
||||
exit 0
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/bin/sh
|
||||
# No Deck dock here. The client runs this with --check at start (systemdockmanager.txt) and reads
|
||||
# the exit code: 0 with nothing printed is taken as "an update is available" and puts a Dock
|
||||
# Firmware Update row with an Apply button in Settings > System. 7, SteamOS's "nothing to do",
|
||||
# is read as up to date (state 2 in that log, against state 4 for exit 0; both seen on device).
|
||||
case "${1:-}" in
|
||||
--check) exit 7 ;;
|
||||
esac
|
||||
|
||||
@@ -1,6 +1,2 @@
|
||||
#!/bin/sh
|
||||
# steamos-priv-write <path> <value>: how the client in Deck mode sets brightness, TDP and fan
|
||||
# controls through sysfs. None of those paths is writable from an app on Android, and the app
|
||||
# already sets the panel's mode and the game-tier power policy from the Android side. Accept
|
||||
# and do nothing, so the client never logs a failed helper.
|
||||
exit 0
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/bin/sh
|
||||
# The SteamOS update-branch selector the client calls in Deck mode. The session forces the client
|
||||
# branch on the command line and keeps package/beta in step with it, so a selection here would
|
||||
# only start the restart loop the session script describes. List and report the stable branch;
|
||||
# accept and ignore a choice.
|
||||
case "${1:-}" in
|
||||
-l) printf 'rel\n' ;;
|
||||
-c) printf 'rel\n' ;;
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
#!/bin/sh
|
||||
# The session carries the device's time zone in TZ already; the client's own setter is a no-op.
|
||||
exit 0
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/bin/sh
|
||||
# What the Steam client calls in Deck mode (from /usr/bin/steamos-polkit-helpers/, seen in its
|
||||
# console log on device; a copy sits in /usr/bin as well) to look for a SteamOS update. There is no SteamOS
|
||||
# here: the answer is "no update", which is exit 7 in SteamOS's convention, and the client moves
|
||||
# on. --supports-duplicate-detection is a capability probe and answers yes. Staged from the apk.
|
||||
case "${1:-}" in
|
||||
--supports-duplicate-detection) exit 0 ;;
|
||||
esac
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/bin/sh
|
||||
# The SteamOS update-branch selector the client calls in Deck mode. The session forces the client
|
||||
# branch on the command line and keeps package/beta in step with it, so a selection here would
|
||||
# only start the restart loop the session script describes. List and report the stable branch;
|
||||
# accept and ignore a choice.
|
||||
case "${1:-}" in
|
||||
-l) printf 'rel\n' ;;
|
||||
-c) printf 'rel\n' ;;
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
#!/bin/sh
|
||||
# The SteamOS session switch. Big Picture's power menu runs it for "Switch to Desktop" (a Plasma
|
||||
# session: "plasma", "plasma-wayland-persistent", ...) and waits for Game Mode to end; with nothing
|
||||
# here it sat on "Switching to Desktop..." for ever. Here the desktop is DroidDeck's own: the app is
|
||||
# asked for a desktop session with Steam's desktop client open in it (the request file
|
||||
# droiddeck-steam-launch uses; the app ends this session and starts that one). Anything else -
|
||||
# "gamescope", the session Game Mode already is - has nothing to do.
|
||||
echo "steamos-session-select: $*" >&2
|
||||
case "${1:-}" in
|
||||
""|gamescope) exit 0 ;;
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
#!/bin/sh
|
||||
# What the Steam client calls in Deck mode to look for a SteamOS update. There is no SteamOS
|
||||
# here: the answer is "no update", which is exit 7 in SteamOS's convention, and the client moves
|
||||
# on. --supports-duplicate-detection is a capability probe and answers yes. Staged from the apk.
|
||||
case "${1:-}" in
|
||||
--supports-duplicate-detection) exit 0 ;;
|
||||
esac
|
||||
|
||||
@@ -21,6 +21,7 @@ Requests: ping, exec, focus, cdp, quit. Each answer is {"ok": true, ...} or
|
||||
import base64
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import os
|
||||
import selectors
|
||||
import signal
|
||||
@@ -68,7 +69,6 @@ class AgentError(Exception):
|
||||
self.code = code
|
||||
|
||||
|
||||
# --- X11: just enough of the protocol for root properties, the window tree and events ---------
|
||||
|
||||
class X:
|
||||
"""One connection to an Xwayland server. The rootfs has xprop but no python X library."""
|
||||
@@ -178,6 +178,11 @@ class X:
|
||||
return list(struct.unpack("<%dI" % n, data))
|
||||
return data
|
||||
|
||||
def cardinals(self, window, name, values):
|
||||
self.s.sendall(struct.pack("<BBHIIIB3xI", 18, 0, 6 + len(values), window,
|
||||
self.atom(name), self.atom("CARDINAL"), 32, len(values))
|
||||
+ struct.pack("<%dI" % len(values), *values))
|
||||
|
||||
|
||||
def windows(x):
|
||||
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
|
||||
@@ -250,6 +255,67 @@ def focus_snapshot():
|
||||
return snap
|
||||
|
||||
|
||||
STEAM_APP_CLASS = re.compile(r"steam_app_(\d+)$")
|
||||
|
||||
|
||||
def tag_game_windows(snap):
|
||||
if os.environ.get("BL_STEAM_CLIENT_ARCH") != "x86_64":
|
||||
return False
|
||||
tagged = False
|
||||
for display, wins in snap.get("displays", {}).items():
|
||||
if display == os.environ.get("DISPLAY"):
|
||||
continue
|
||||
for win in wins:
|
||||
match = STEAM_APP_CLASS.match(win.get("class") or "")
|
||||
if not match or win.get("appId") or win.get("map") != "viewable" or win.get("overrideRedirect"):
|
||||
continue
|
||||
try:
|
||||
done = subprocess.run(["xprop", "-display", display, "-id", str(win["window"]), "-f", "STEAM_GAME", "32c",
|
||||
"-set", "STEAM_GAME", match.group(1)],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5).returncode == 0
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
done = False
|
||||
log("game window %s on %s tagged STEAM_GAME=%s: %s" % (win["window"], display, match.group(1), "ok" if done else "failed"))
|
||||
tagged = tagged or done
|
||||
return tagged
|
||||
|
||||
|
||||
def vr_scene_app(path=Path('/run/droiddeck/droiddeck-steamvr/scene-focus.json'), proc=Path('/proc')):
|
||||
"""Only a live SteamVR scene with its dashboard hidden may claim game focus."""
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
server, scene = int(state['serverPid']), int(state['scenePid'])
|
||||
if server <= 0 or scene <= 0 or state['dashboard'] is not False:
|
||||
return None
|
||||
if (proc / str(server) / 'comm').read_text().strip() != 'vrserver':
|
||||
return None
|
||||
for entry in (proc / str(scene) / 'environ').read_bytes().split(b'\0'):
|
||||
if entry.startswith(b'SteamAppId='):
|
||||
app = int(entry.split(b'=', 1)[1])
|
||||
return app if 0 < app < 2**32 else None
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
class VrSceneFocus:
|
||||
def __init__(self):
|
||||
self.original = None
|
||||
self.written = None
|
||||
|
||||
def order(self, current, focusable, app):
|
||||
if app is None or app not in focusable:
|
||||
restore = self.original if self.written == current else None
|
||||
self.original = self.written = None
|
||||
return restore
|
||||
if current and current[0] == app:
|
||||
return None
|
||||
if self.original is None:
|
||||
self.original = list(current)
|
||||
self.written = [app] + [item for item in current if item != app]
|
||||
return self.written
|
||||
|
||||
|
||||
class FocusWatcher(threading.Thread):
|
||||
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
|
||||
the windows do (a window can change without any root property moving)."""
|
||||
@@ -260,19 +326,35 @@ class FocusWatcher(threading.Thread):
|
||||
self.changed = threading.Event()
|
||||
self.last = None
|
||||
self.seq = 0
|
||||
self.vr_focus = VrSceneFocus()
|
||||
|
||||
def run(self):
|
||||
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
|
||||
last_app, last_snapshot = None, 0
|
||||
while True:
|
||||
self.changed.wait(timeout=5)
|
||||
notified = self.changed.wait(timeout=0.5)
|
||||
self.changed.clear()
|
||||
time.sleep(0.2) # let a burst of property changes settle
|
||||
app = vr_scene_app()
|
||||
if not notified and app == last_app and time.monotonic() - last_snapshot < 5:
|
||||
continue
|
||||
last_app, last_snapshot = app, time.monotonic()
|
||||
time.sleep(0.2)
|
||||
try:
|
||||
snap = focus_snapshot()
|
||||
order = self.vr_focus.order(snap.get('baselayerAppIds', []), snap.get('focusableApps', []), app)
|
||||
if order is not None:
|
||||
x = X(os.environ['DISPLAY'])
|
||||
try:
|
||||
x.cardinals(x.root, 'GAMESCOPECTRL_BASELAYER_APPID', order)
|
||||
finally:
|
||||
x.close()
|
||||
except (OSError, AgentError) as e:
|
||||
log("focus snapshot failed: %s" % e)
|
||||
time.sleep(2)
|
||||
continue
|
||||
if tag_game_windows(snap):
|
||||
self.changed.set()
|
||||
continue
|
||||
body = {k: v for k, v in snap.items() if k != "t"}
|
||||
if body == self.last:
|
||||
continue
|
||||
@@ -286,9 +368,7 @@ class FocusWatcher(threading.Thread):
|
||||
try:
|
||||
x = X(os.environ["DISPLAY"])
|
||||
wanted = {x.atom(name) for name in FOCUS_PROPS}
|
||||
x.select(x.root, 0x400000) # PropertyChangeMask
|
||||
# Waits for events as long as there are none: the connect timeout left in place
|
||||
# here dropped and remade the connection, and took a snapshot, every few seconds.
|
||||
x.select(x.root, 0x400000)
|
||||
x.s.settimeout(None)
|
||||
self.changed.set()
|
||||
while True:
|
||||
@@ -300,7 +380,6 @@ class FocusWatcher(threading.Thread):
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
# --- Steam client DevTools (CDP) -----------------------------------------------------------------
|
||||
|
||||
class WebSocket:
|
||||
"""A minimal RFC 6455 client: text frames out, text frames in. Enough for CDP."""
|
||||
@@ -384,7 +463,7 @@ class WebSocket:
|
||||
op = b0 & 0x0F
|
||||
if op == 8:
|
||||
raise OSError("DevTools closed the WebSocket")
|
||||
if op == 9: # ping
|
||||
if op == 9:
|
||||
continue
|
||||
if op in (0, 1, 2):
|
||||
message += data
|
||||
@@ -453,7 +532,108 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
|
||||
ws.close()
|
||||
|
||||
|
||||
# --- Game processes ------------------------------------------------------------------------------
|
||||
def steam_selection(agent_dir, timeout=5):
|
||||
result = cdp_eval(
|
||||
agent_dir,
|
||||
"""(() => {
|
||||
let node = document.activeElement;
|
||||
while (node) {
|
||||
for (const name of ["data-id", "data-appid"]) {
|
||||
const value = node.getAttribute?.(name);
|
||||
if (/^[1-9][0-9]{0,9}$/.test(value || "")) {
|
||||
const appId = Number(value);
|
||||
if (Number.isSafeInteger(appId) && appId <= 4294967295) return value;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
})()""",
|
||||
target="Steam Big Picture Mode",
|
||||
timeout=timeout,
|
||||
)
|
||||
value = result.get("value")
|
||||
if value is None:
|
||||
return {"appId": None}
|
||||
if not isinstance(value, str) or not value.isdigit() or not 0 < int(value) <= 4294967295:
|
||||
raise AgentError("INVALID_SELECTION", "Steam returned an invalid selected app id")
|
||||
return {"appId": int(value)}
|
||||
|
||||
|
||||
def steam_shortcut_app_id(game_id):
|
||||
"""Return the 32-bit app id in Steam's shortcut CGameID form, or None for other ids.
|
||||
|
||||
DroidDeck's shortcut IDs are `(appid << 32) | 0x02000000`. The URL still needs that full
|
||||
CGameID for RunGame; the app-details API separately needs the unsigned 32-bit app id.
|
||||
"""
|
||||
if not isinstance(game_id, str) or not game_id.isascii() or not game_id.isdigit():
|
||||
return None
|
||||
try:
|
||||
game_id_value = int(game_id)
|
||||
except ValueError:
|
||||
return None
|
||||
if str(game_id_value) != game_id or not 0 < game_id_value <= 0xFFFFFFFFFFFFFFFF:
|
||||
return None
|
||||
if game_id_value <= 0xFFFFFFFF or game_id_value & 0xFFFFFFFF != 0x02000000:
|
||||
return None
|
||||
app_id = game_id_value >> 32
|
||||
return app_id if 0 < app_id <= 0xFFFFFFFF else None
|
||||
|
||||
|
||||
def wait_for_steam_shortcut_overview(agent_dir, game_id, timeout=45):
|
||||
"""Wait until Steam can map a shortcut CGameID to its 32-bit app overview."""
|
||||
app_id = steam_shortcut_app_id(game_id)
|
||||
if app_id is None:
|
||||
return {"supported": False, "ready": False}
|
||||
|
||||
timeout = request_timeout({"timeout": timeout}, 45)
|
||||
deadline = time.monotonic() + timeout
|
||||
expression = """(() => {
|
||||
const store = globalThis.appStore;
|
||||
if (typeof store?.GetAppOverviewByGameID !== 'function') return null;
|
||||
const overview = store.GetAppOverviewByGameID(%s);
|
||||
return overview == null ? null : String(overview.appid);
|
||||
})()""" % json.dumps(game_id)
|
||||
while True:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
try:
|
||||
result = cdp_eval(agent_dir, expression, await_promise=False,
|
||||
timeout=min(5, max(0.25, remaining)))
|
||||
if result.get("value") == str(app_id):
|
||||
return {"supported": True, "ready": True, "appId": app_id}
|
||||
except AgentError as error:
|
||||
if error.code not in ("NO_DEVTOOLS", "DEVTOOLS_UNREACHABLE", "NO_TARGET", "TIMEOUT"):
|
||||
raise
|
||||
time.sleep(min(0.25, max(0, deadline - time.monotonic())))
|
||||
raise AgentError("STEAM_OVERVIEW_TIMEOUT", "Steam did not load shortcut app overview %d" % app_id)
|
||||
|
||||
|
||||
def steam_shortcut_state(agent_dir, game_id, timeout=6):
|
||||
if steam_shortcut_app_id(game_id) is None:
|
||||
return "not-shortcut"
|
||||
timeout = request_timeout({"timeout": timeout}, 6)
|
||||
deadline = time.monotonic() + timeout
|
||||
expression = """(() => {
|
||||
const store = globalThis.appStore;
|
||||
if (typeof store?.GetAppOverviewByGameID !== 'function' || !store.m_bIsInitialized) return 'loading';
|
||||
if (store.GetAppOverviewByGameID(%s) != null) return 'ready';
|
||||
return store.allApps.some(app => app.app_type == 1073741824) ? 'missing' : 'loading';
|
||||
})()""" % json.dumps(game_id)
|
||||
state = "loading"
|
||||
while True:
|
||||
try:
|
||||
state = cdp_eval(agent_dir, expression, await_promise=False,
|
||||
timeout=min(5, max(0.25, deadline - time.monotonic()))).get("value") or "loading"
|
||||
except AgentError as error:
|
||||
if error.code not in ("NO_DEVTOOLS", "DEVTOOLS_UNREACHABLE", "NO_TARGET", "TIMEOUT"):
|
||||
raise
|
||||
state = "loading"
|
||||
if state == "ready" or time.monotonic() >= deadline:
|
||||
return state
|
||||
time.sleep(min(0.5, max(0, deadline - time.monotonic())))
|
||||
|
||||
|
||||
def game_pids(app_id):
|
||||
"""Our processes started for this Steam app (Steam sets SteamAppId / SteamGameId in their
|
||||
@@ -510,7 +690,38 @@ def quit_game(agent_dir, app_id, timeout):
|
||||
return {"appId": int(app_id), "steps": steps, "remaining": game_pids(app_id)}
|
||||
|
||||
|
||||
# --- Requests ------------------------------------------------------------------------------------
|
||||
|
||||
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
|
||||
VR_ACTIONS = ("status", "install", "start", "stop")
|
||||
|
||||
|
||||
def steamvr(req):
|
||||
"""Cardboard mode's SteamVR: a fixed helper with four actions, unlike exec (no command line from
|
||||
the request). install downloads 571 MB, so it runs detached and status reports it."""
|
||||
action = req.get("action", "status")
|
||||
if action not in VR_ACTIONS:
|
||||
raise AgentError("INVALID_REQUEST", "vr action must be one of " + ", ".join(VR_ACTIONS))
|
||||
helper = os.environ.get("DROIDDECK_VR_HELPER", VR_HELPER)
|
||||
if not os.path.isfile(helper):
|
||||
raise AgentError("UNAVAILABLE", "this runtime has no " + helper)
|
||||
if action == "install":
|
||||
state = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "droiddeck-steamvr"
|
||||
state.mkdir(parents=True, exist_ok=True)
|
||||
with open(state / "install.log", "ab") as log_file:
|
||||
subprocess.Popen(["sh", helper, "install"], stdin=subprocess.DEVNULL, stdout=log_file,
|
||||
stderr=subprocess.STDOUT, start_new_session=True)
|
||||
return {"action": action, "started": True}
|
||||
done = subprocess.run(["sh", helper, action], stdin=subprocess.DEVNULL, capture_output=True,
|
||||
timeout=request_timeout(req, 30))
|
||||
out = done.stdout.decode("utf-8", "replace").strip()
|
||||
result = {"action": action, "exitCode": done.returncode, "output": out[-2000:]}
|
||||
if action == "status":
|
||||
for part in out.split():
|
||||
key, _, value = part.partition("=")
|
||||
if key in ("installed", "running", "installing", "driver"):
|
||||
result[key] = value == "1"
|
||||
return result
|
||||
|
||||
|
||||
def run_exec(req):
|
||||
argv = req.get("argv")
|
||||
@@ -624,8 +835,12 @@ def handle(agent_dir, req):
|
||||
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
|
||||
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
|
||||
request_timeout(req, 15))
|
||||
if kind == "steam-selection":
|
||||
return steam_selection(agent_dir, request_timeout(req, 5))
|
||||
if kind == "quit":
|
||||
return quit_game(agent_dir, req.get("appId"), request_timeout(req, 15))
|
||||
if kind == "vr":
|
||||
return steamvr(req)
|
||||
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
|
||||
|
||||
|
||||
@@ -652,7 +867,7 @@ def answer(agent_dir, path):
|
||||
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: # an answer of some kind always goes back
|
||||
except Exception as e:
|
||||
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
|
||||
write_json(agent_dir / "resp" / (rid + ".json"), result)
|
||||
|
||||
@@ -682,6 +897,43 @@ def main(argv):
|
||||
if not base:
|
||||
print("BL_LAUNCH_DIR is not set", file=sys.stderr)
|
||||
return 2
|
||||
if argv and argv[0] == "--wait-steam-shortcut-overview":
|
||||
if len(argv) not in (2, 3):
|
||||
print("usage: droiddeck-agent --wait-steam-shortcut-overview <cgameid> [timeout-seconds]", file=sys.stderr)
|
||||
return 2
|
||||
timeout = argv[2] if len(argv) == 3 else 45
|
||||
try:
|
||||
prepared = wait_for_steam_shortcut_overview(Path(base) / "agent", argv[1], timeout)
|
||||
except (AgentError, OSError, ValueError) as error:
|
||||
print("droiddeck-agent: shortcut overview was not ready: %s" % error, file=sys.stderr)
|
||||
return 1
|
||||
if not prepared["supported"]:
|
||||
print("droiddeck-agent: id is not a DroidDeck shortcut CGameID")
|
||||
return 3
|
||||
print("droiddeck-agent: Steam overview is ready for shortcut app %d" % prepared["appId"])
|
||||
return 0
|
||||
if argv and argv[0] == "--steam-asleep":
|
||||
expression = """(() => {
|
||||
const store = globalThis.SuspendResumeStore;
|
||||
return store ? (store.m_bSuspending ? 'yes' : 'no') : 'unknown';
|
||||
})()"""
|
||||
try:
|
||||
state = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=3).get("value") or "unknown"
|
||||
except (AgentError, OSError, ValueError):
|
||||
state = "unknown"
|
||||
print(state)
|
||||
return {"yes": 0, "no": 5}.get(state, 1)
|
||||
if argv and argv[0] == "--steam-shortcut-state":
|
||||
if len(argv) not in (2, 3):
|
||||
print("usage: droiddeck-agent --steam-shortcut-state <cgameid> [timeout-seconds]", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
state = steam_shortcut_state(Path(base) / "agent", argv[1], argv[2] if len(argv) == 3 else 6)
|
||||
except (AgentError, OSError, ValueError) as error:
|
||||
print("droiddeck-agent: could not ask the client about the shortcut: %s" % error, file=sys.stderr)
|
||||
return 1
|
||||
print(state)
|
||||
return {"ready": 0, "missing": 4, "not-shortcut": 3}.get(state, 1)
|
||||
serve(Path(base) / "agent", focus="--no-focus" not in argv)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -1,33 +1,17 @@
|
||||
#!/bin/bash
|
||||
# An AppImage imported from the front end (AppImageManager), extracted once at import into
|
||||
# /opt/appimages/user/<id>/app
|
||||
# and started from there: proot has no FUSE to mount the image, and extracting it at every
|
||||
# start (APPIMAGE_EXTRACT_AND_RUN) would cost the whole image in /tmp each time.
|
||||
# droiddeck-appimage-run /opt/appimages/user/<id> [args...]
|
||||
set -u
|
||||
dir=${1:?usage: droiddeck-appimage-run <imported AppImage directory> [args...]}
|
||||
shift
|
||||
export APPDIR=$dir/app
|
||||
# APPIMAGE is left unset on purpose: with it an app believes it runs from an image file and offers
|
||||
# to add itself to the menu (DuckStation) or update the file in place - DroidDeck already does the
|
||||
# one, and there is no image file for the other.
|
||||
unset APPIMAGE
|
||||
export ARGV0=$(cat "$dir/name" 2>/dev/null || basename "$dir")
|
||||
if [ ! -x "$APPDIR/AppRun" ]; then
|
||||
echo "droiddeck-appimage-run: $APPDIR/AppRun is missing; import the AppImage again" >&2
|
||||
exit 127
|
||||
fi
|
||||
# Browsers sandbox their own children with namespaces and a setuid helper, neither of which proot
|
||||
# can give them (the Flatpak sandboxes get the same; see BwrapSpawner): Firefox and its forks (Zen,
|
||||
# LibreWolf) by these switches, Electron and Chromium builds by --no-sandbox. Chromium on Wayland
|
||||
# also asks the render node for a DRM version KGSL cannot give, so with an X server up it stays on
|
||||
# X11, which it picks from the session type.
|
||||
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
|
||||
# Android 16 refuses Firefox the size seal on a tab's shared memory; see droiddeck-desktop.
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
# sharun images start the app through their own ld.so, patched not to read /etc/ld.so.preload, and
|
||||
# drop LD_PRELOAD unless allowed: without this the app never gets the session's pads.
|
||||
if [ -s /etc/ld.so.preload ]; then
|
||||
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
@@ -74,8 +58,6 @@ fi
|
||||
echo "== appimage $ARGV0 ($APPDIR) ${flags[*]} FEX $fex Qt $qt${QT_QPA_PLATFORM:+ ($QT_QPA_PLATFORM)}"
|
||||
cd "$APPDIR" || exit 1
|
||||
started=$(mktemp "${TMPDIR:-/tmp}/droiddeck-appimage.XXXXXX")
|
||||
# Apps expect a session bus; Electron's main process traps (SIGTRAP) on an address it cannot
|
||||
# parse. A run mode has none, so one is started for the app, as for Flatpak apps.
|
||||
case ${DBUS_SESSION_BUS_ADDRESS:-} in
|
||||
unix:*) "${run[@]}" "${flags[@]}" "$@" ;;
|
||||
*) unset DBUS_SESSION_BUS_ADDRESS
|
||||
@@ -100,10 +82,6 @@ if [ "$rc" -ne 0 ] && [ -n "$started" ]; then
|
||||
done
|
||||
fi
|
||||
rm -f "$started"
|
||||
# The program a session was started for may hand over to another process and exit: Electron apps
|
||||
# relaunch themselves (Obsidian on its first start), launchers fork their real program. The
|
||||
# session ends with this script, and takes the rest with it - so it waits while anything running
|
||||
# from the image is still up.
|
||||
image_running() {
|
||||
local p exe arg cwd
|
||||
for p in /proc/[0-9]*; do
|
||||
|
||||
@@ -1,17 +1,4 @@
|
||||
#!/usr/bin/python3
|
||||
# bubblewrap for Flatpak (FLATPAK_BWRAP), in a runtime that cannot have it.
|
||||
#
|
||||
# bwrap builds each sandbox from mount namespaces, which Android gives no app. proot gives the same
|
||||
# picture - Flatpak's runtime as /usr, the app as /app, host paths bound where Flatpak asks - but a
|
||||
# proot nested inside the session's proot runs every system call through two tracers, some thirty
|
||||
# times slower on a program's start. So a sandbox is described to the app instead, over a socket
|
||||
# only this app's uid may use, and the app starts it as a proot of its own beside the session's
|
||||
# (BwrapSpawner). This process stands in for the sandbox until it ends: its output, its pid for
|
||||
# --info-fd, and its exit status come back here.
|
||||
#
|
||||
# Sandboxes that remap nothing - Flatpak's install triggers (`--ro-bind / /` and the directory they
|
||||
# update) and the D-Bus proxy (every top-level directory bound onto itself) - need no proot at all
|
||||
# and run here directly, with the file descriptors Flatpak handed them.
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
@@ -20,10 +7,9 @@ import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
SOCKET = "\0com.droiddeck.launcher.bwrap"
|
||||
SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap")
|
||||
VERSION = "bubblewrap 0.11.0 (droiddeck)"
|
||||
|
||||
# Options and how many arguments each takes; bwrap(1).
|
||||
NO_ARG = {
|
||||
"--unshare-user", "--unshare-user-try", "--unshare-ipc", "--unshare-pid", "--unshare-net",
|
||||
"--unshare-uts", "--unshare-cgroup", "--unshare-cgroup-try", "--unshare-all", "--share-net",
|
||||
@@ -68,7 +54,6 @@ def expand(argv):
|
||||
a = argv[i]
|
||||
if a == "--args" and i + 1 < len(argv):
|
||||
data = read_fd(int(argv[i + 1]))
|
||||
# Each argument ends in a NUL; an empty one (--setenv LD_LIBRARY_PATH "") is kept.
|
||||
parts = data.split(b"\0")
|
||||
if parts and parts[-1] == b"":
|
||||
parts.pop()
|
||||
@@ -155,7 +140,6 @@ def parse(argv):
|
||||
elif a == "--dev":
|
||||
s.ops.append({"t": "dev", "dest": args[0]})
|
||||
elif a in ("--seccomp", "--add-seccomp-fd"):
|
||||
# proot is the sandbox; there is no filter to install under it.
|
||||
os.close(int(args[0]))
|
||||
elif a == "--block-fd":
|
||||
read_fd(int(args[0]))
|
||||
@@ -165,8 +149,6 @@ def parse(argv):
|
||||
s.info_fds.append(int(args[0]))
|
||||
elif a == "--json-status-fd":
|
||||
s.json_fds.append(int(args[0]))
|
||||
# Everything else - namespaces, capabilities, labels, locks, --remount-ro, --chmod - has
|
||||
# nothing to act on under proot.
|
||||
if not s.command:
|
||||
sys.stderr.write("bwrap: No command specified\n")
|
||||
sys.exit(1)
|
||||
@@ -196,7 +178,6 @@ def remaps_nothing(s):
|
||||
if not os.path.islink(op["dest"]) or os.readlink(op["dest"]) != op["target"]:
|
||||
return False
|
||||
elif t == "file":
|
||||
# The D-Bus proxy's /.flatpak-info names the app to the bus; nothing here reads it.
|
||||
if op["dest"] != "/.flatpak-info":
|
||||
return False
|
||||
elif t == "dir":
|
||||
@@ -258,7 +239,6 @@ def run_by_app(s):
|
||||
for op in s.ops:
|
||||
op = dict(op)
|
||||
if op["t"] == "bind":
|
||||
# The app resolves no guest symlinks; hand it the path they lead to.
|
||||
op["src"] = real(op["src"])
|
||||
if op["t"] == "file":
|
||||
op["data"] = base64.b64encode(op["data"]).decode()
|
||||
@@ -274,7 +254,6 @@ def run_by_app(s):
|
||||
sys.stderr.write("bwrap: DroidDeck is not answering (%s); open DroidDeck and try again\n" % e)
|
||||
sys.exit(1)
|
||||
send(sock, b"R", json.dumps(request).encode())
|
||||
# This process is the sandbox as far as Flatpak is concerned: ended, it takes the sandbox down.
|
||||
for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
|
||||
signal.signal(sig, lambda *_: os._exit(128 + 15))
|
||||
status = 1
|
||||
|
||||
@@ -29,7 +29,7 @@ def steam_libraries(home, data):
|
||||
try:
|
||||
selected = {Path(e["path"]): str(e["label"]) for e in json.loads(Path(listing).read_text())}
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass # Fall back to the client's registered libraries if the app's list is unreadable.
|
||||
pass
|
||||
vdf = steam / "steamapps/libraryfolders.vdf"
|
||||
if vdf.is_file():
|
||||
parser = runpy.run_path(str(Path(__file__).with_name("droiddeck-steam-ui-scale")))
|
||||
@@ -76,7 +76,6 @@ def update_places(path, libraries):
|
||||
else:
|
||||
if not libraries:
|
||||
return
|
||||
# Leave KDE's file version unset so it still adds its normal Home/Downloads/etc. places.
|
||||
root = ET.Element("xbel", {"version": "1.0"})
|
||||
before = ET.tostring(root)
|
||||
seen = set()
|
||||
@@ -112,7 +111,6 @@ def update_places(path, libraries):
|
||||
|
||||
|
||||
def bookmarks_file(home, config):
|
||||
# libfm-qt reads GTK3 bookmarks first, falling back to the legacy file when empty.
|
||||
current = config / "gtk-3.0/bookmarks"
|
||||
legacy = home / ".gtk-bookmarks"
|
||||
if current.is_file() and current.read_text(errors="surrogateescape").strip():
|
||||
@@ -153,7 +151,6 @@ def main():
|
||||
home = Path.home()
|
||||
config = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")
|
||||
label = os.environ.get("BL_LIBRARY_LABEL")
|
||||
# An unbound mount-point directory may remain from a previous session.
|
||||
available = bool(label) and (LIBRARY / "steamapps").is_dir()
|
||||
update_bookmark(bookmarks_file(home, config), label if available else None)
|
||||
data = Path(os.environ.get("XDG_DATA_HOME") or home / ".local/share")
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
#!/bin/bash
|
||||
# Plasma starts this after its nested Xwayland display is available. The session launcher still
|
||||
# sees the outer compositor before startplasma, so starting its X11 helper there cannot work.
|
||||
[ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0
|
||||
# The native helper dies with its parent. Keep this shell until it exits: Plasma's autostart
|
||||
# launcher may itself exit immediately after starting us.
|
||||
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
|
||||
child=$!
|
||||
trap 'kill "$child" 2>/dev/null' EXIT
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
#!/usr/bin/python3
|
||||
# The client's installed games, on the desktop. The client writes a menu entry per game itself
|
||||
# (`steam steam://rungameid/<id>`, with the game's icon), which the desktop's `steam` shim hands to
|
||||
# the app - so an entry of ours exists only for a game the client wrote none for. Plus two links in
|
||||
# the home folder to the game files. Run at every desktop start; stale entries go.
|
||||
#
|
||||
# droiddeck-desktop-games [steam root]
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam")
|
||||
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd", "SD Games"))
|
||||
# The client's own tools and runtimes live in steamapps beside the games; they are not titles. A
|
||||
# depot with a toolmanifest.vdf is one too (a runtime or a Proton), listed here or not.
|
||||
X64 = os.environ.get("BL_STEAM_CLIENT_ARCH") == "x86_64"
|
||||
CLIENT_HOME = (os.environ.get("BL_X64_HOME") or os.path.join(HOME, ".droiddeck-x64")) if X64 else HOME
|
||||
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(CLIENT_HOME, ".local/share/Steam")
|
||||
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd/x86-64" if X64 else "/mnt/droiddeck-sd", "SD Games"))
|
||||
NOT_GAMES = {228980, 1070560, 1391110, 1493710, 1628350, 3127680, 4183110, 4185400, 4427310, 4628740}
|
||||
APPS_DIR = os.path.join(HOME, ".local/share/applications")
|
||||
PREFIX = "droiddeck-game-"
|
||||
@@ -41,7 +35,6 @@ def games(library):
|
||||
continue
|
||||
name = NAME.search(text)
|
||||
state = STATE.search(text)
|
||||
# StateFlags 4 = fully installed; anything else is downloading, updating or broken.
|
||||
if not name or not state or (int(state.group(1)) & 4) == 0:
|
||||
continue
|
||||
installdir = INSTALLDIR.search(text)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/bin/bash
|
||||
# Port the old desktop's melonDS window rule once; later window rules belong to the user.
|
||||
set -euo pipefail
|
||||
config=${XDG_CONFIG_HOME:-$HOME/.config}
|
||||
marker=$config/droiddeck-window-rules-v1
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
[ -n "${LD_PRELOAD:-}" ] && export DROIDDECK_STEAM_PRELOAD="$LD_PRELOAD"
|
||||
unset LD_PRELOAD LD_LIBRARY_PATH
|
||||
exec /usr/bin/python3 -I /usr/local/bin/droiddeck-epic run
|
||||
@@ -1,7 +1,4 @@
|
||||
#!/usr/bin/python3
|
||||
# droiddeck-esync: picks and stages the esync pack for each Proton build.
|
||||
# Credit: esync and ntsync were designed by Elizabeth Figura for Wine and Proton, and fsync by Elizabeth Figura
|
||||
# and Paul Gofman; droiddeck-esync, droiddeck-ntsync and droiddeck-fsync build on that work.
|
||||
import contextlib
|
||||
import fcntl
|
||||
import hashlib
|
||||
|
||||
@@ -28,15 +28,25 @@ URUNTIME = "/usr/local/lib/droiddeck/uruntime"
|
||||
HOST_PRELOAD = "/etc/ld.so.preload"
|
||||
FEX_APPID = "3127680"
|
||||
SNIPER_APPID = "1628350"
|
||||
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper"}
|
||||
SLR4_APPID = "4183110"
|
||||
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"}
|
||||
MARKER = ".droiddeck-fex"
|
||||
LAYOUT = 1
|
||||
ROOTFS_LAYOUT = 1
|
||||
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
|
||||
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
|
||||
PROVIDED = frozenset((
|
||||
"ld-linux-x86-64.so.2", "ld-linux.so.2", "libc.so.6", "libm.so.6", "libmvec.so.1", "libpthread.so.0", "libdl.so.2",
|
||||
"librt.so.1", "libutil.so.1", "libresolv.so.2", "libanl.so.1", "libBrokenLocale.so.1", "libnsl.so.1",
|
||||
"libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1",
|
||||
"libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1",
|
||||
))
|
||||
GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$")
|
||||
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
|
||||
PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so")
|
||||
FAULT_REPORT = "libfaultreport.so"
|
||||
THUNK_AUDIT = "libthunkaudit.so"
|
||||
THUNK_AUDIT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + THUNK_AUDIT
|
||||
VULKAN_PIN = "libvulkan-thunk.so"
|
||||
VULKAN_PIN_DIR = "lib/x86_64-linux-gnu/droiddeck/vulkan"
|
||||
VULKAN_THUNK = "libvulkan-guest.so"
|
||||
RUNTIME_LIBRARIES = (("libc.so.6", b"GLIBC_"), ("libstdc++.so.6", b"GLIBCXX_"))
|
||||
VERSION_NAME = re.compile(rb"GLIBC(?:XX)?_[0-9][0-9.]*[0-9]")
|
||||
@@ -164,15 +174,15 @@ def platform_version(path):
|
||||
return tuple(int(part) for part in re.findall(r"\d+", os.path.basename(path)))
|
||||
|
||||
|
||||
def runtime_platform():
|
||||
runtime = app_dir(SNIPER_APPID)
|
||||
def runtime_platform(appid=SNIPER_APPID, prefix="sniper_platform_"):
|
||||
runtime = app_dir(appid)
|
||||
if not runtime:
|
||||
return None
|
||||
try:
|
||||
entries = os.listdir(runtime)
|
||||
except OSError:
|
||||
return None
|
||||
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith("sniper_platform_")]
|
||||
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith(prefix)]
|
||||
platforms = [path for path in platforms if os.path.isdir(os.path.join(path, "files"))
|
||||
and os.path.isfile(os.path.join(path, "usr-mtree.txt.gz"))]
|
||||
return max(platforms, key=platform_version, default=None)
|
||||
@@ -234,6 +244,75 @@ def materialize(platform):
|
||||
return True
|
||||
|
||||
|
||||
def graphics_platform():
|
||||
return runtime_platform(SLR4_APPID, "steamrt4_platform_")
|
||||
|
||||
|
||||
def provides_newer(base, provider):
|
||||
for name, prefix in RUNTIME_LIBRARIES:
|
||||
ours = {v for v in version_names(os.path.join(base, "files/lib/x86_64-linux-gnu", name)) if v.startswith(prefix)}
|
||||
theirs = {v for v in version_names(os.path.join(provider, "files/lib/x86_64-linux-gnu", name)) if v.startswith(prefix)}
|
||||
if not ours or not theirs or not ours < theirs:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def mirror(source, provider, name, target):
|
||||
if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)):
|
||||
os.symlink(os.path.realpath(os.path.join(provider, name)), os.path.join(target, name))
|
||||
return
|
||||
path = os.path.join(source, name)
|
||||
link = os.readlink(path) if os.path.islink(path) else None
|
||||
if link and GLIBC_BUILD.match(os.path.basename(link)):
|
||||
if name not in INTERPRETERS:
|
||||
return
|
||||
link = os.path.join(os.path.dirname(link), name)
|
||||
if provider and GLIBC_BUILD.match(name):
|
||||
return
|
||||
if link and not link.startswith("/"):
|
||||
os.symlink(link, os.path.join(target, name))
|
||||
else:
|
||||
os.symlink(os.path.realpath(path), os.path.join(target, name))
|
||||
|
||||
|
||||
def build_rootfs(base, provider):
|
||||
"""The runtime with glibc and libstdc++ taken from a newer one, which FEX's GL and Vulkan thunks are built against."""
|
||||
base_files, provider_files = os.path.join(base, "files"), os.path.join(provider, "files")
|
||||
rootfs = os.path.join(STATE, "rootfs")
|
||||
stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "",
|
||||
os.path.realpath(provider), read_text(os.path.join(provider_files, MARKER)) or "")
|
||||
if read_text(os.path.join(rootfs, MARKER)) == stamp:
|
||||
return False
|
||||
for entry in os.listdir(STATE):
|
||||
if entry.startswith("rootfs."):
|
||||
shutil.rmtree(os.path.join(STATE, entry), ignore_errors=True)
|
||||
tmp = "%s.%d.tmp" % (rootfs, os.getpid())
|
||||
os.makedirs(tmp)
|
||||
for entry in os.listdir(base_files):
|
||||
if entry not in ("lib", "lib64", "usr", MARKER):
|
||||
os.symlink(os.path.realpath(os.path.join(base_files, entry)), os.path.join(tmp, entry))
|
||||
os.symlink(".", os.path.join(tmp, "usr"))
|
||||
for top in ("lib", "lib64"):
|
||||
source = os.path.join(base_files, top)
|
||||
os.makedirs(os.path.join(tmp, top))
|
||||
for entry in os.listdir(source) if os.path.isdir(source) else ():
|
||||
path = os.path.join(source, entry)
|
||||
if entry in ARCH_DIRS and os.path.isdir(path) and not os.path.islink(path):
|
||||
provided = os.path.join(provider_files, top, entry)
|
||||
os.makedirs(os.path.join(tmp, top, entry))
|
||||
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}:
|
||||
mirror(path, provided, name, os.path.join(tmp, top, entry))
|
||||
else:
|
||||
mirror(source, None, entry, os.path.join(tmp, top))
|
||||
write_if_changed(os.path.join(tmp, MARKER), stamp)
|
||||
old = "%s.%d.old" % (rootfs, os.getpid())
|
||||
if os.path.lexists(rootfs):
|
||||
os.rename(rootfs, old)
|
||||
os.rename(tmp, rootfs)
|
||||
shutil.rmtree(old, ignore_errors=True)
|
||||
return True
|
||||
|
||||
|
||||
def host_preloads():
|
||||
listed = read_text(HOST_PRELOAD) or ""
|
||||
return [name for name in PRELOAD_NAMES if name in listed]
|
||||
@@ -247,14 +326,15 @@ def install_preloads(root):
|
||||
if os.path.isfile(source):
|
||||
copy_if_changed(source, os.path.join(root, libdir, "droiddeck", name))
|
||||
shipped.setdefault(name, set()).add(arch)
|
||||
for name in (THUNK_AUDIT, VULKAN_PIN):
|
||||
source = os.path.join(PRELOADS, "x86_64", name)
|
||||
if os.path.isfile(source):
|
||||
copy_if_changed(source, os.path.join(root, "lib/x86_64-linux-gnu/droiddeck", name))
|
||||
pin = os.path.join(PRELOADS, "x86_64", VULKAN_PIN)
|
||||
if os.path.isfile(pin):
|
||||
copy_if_changed(pin, os.path.join(root, VULKAN_PIN_DIR, "libvulkan.so.1"))
|
||||
alias = os.path.join(root, VULKAN_PIN_DIR, "libvulkan.so")
|
||||
if not os.path.islink(alias) or os.readlink(alias) != "libvulkan.so.1":
|
||||
if os.path.lexists(alias):
|
||||
os.unlink(alias)
|
||||
os.symlink("libvulkan.so.1", alias)
|
||||
wanted = [name for name in host_preloads() if name in shipped]
|
||||
# The fault report is preloaded from the runtime's own list, which only x86 loaders read: through
|
||||
# LD_PRELOAD it reached FEX's own loader too, and every FEX after it, which could not open it and
|
||||
# said so at each start. Listed only with both builds, or i386 programs would say so instead.
|
||||
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))
|
||||
@@ -273,14 +353,16 @@ def write_config(fex, root):
|
||||
def link_steam_sdk():
|
||||
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
|
||||
link = os.path.join(HOME, ".steam", sdk)
|
||||
if os.path.lexists(link):
|
||||
continue
|
||||
want = "x86_64" if sdk == "sdk64" else "i386"
|
||||
if elf_arch(os.path.join(link, "steamclient.so")) == want:
|
||||
continue
|
||||
for candidate in candidates:
|
||||
directory = os.path.join(STEAM_ROOT, candidate)
|
||||
if elf_arch(os.path.join(directory, "steamclient.so")) == want:
|
||||
os.makedirs(os.path.dirname(link), exist_ok=True)
|
||||
os.symlink(directory, link)
|
||||
tmp = "%s.%d.tmp" % (link, os.getpid())
|
||||
os.symlink(directory, tmp)
|
||||
os.replace(tmp, link)
|
||||
break
|
||||
|
||||
|
||||
@@ -311,7 +393,7 @@ def request_install():
|
||||
return []
|
||||
|
||||
|
||||
def describe(fex, platform):
|
||||
def describe(fex, platform, graphics=None):
|
||||
return {
|
||||
"fex": fex["bin"] if fex else None,
|
||||
"server": fex["server"] if fex else None,
|
||||
@@ -320,6 +402,7 @@ def describe(fex, platform):
|
||||
"steamclient64": os.path.realpath(os.path.join(HOME, ".steam", "sdk64", "steamclient.so"))
|
||||
if elf_arch(os.path.join(HOME, ".steam", "sdk64", "steamclient.so")) == "x86_64" else None,
|
||||
"ready": bool(fex and fex["server"] and platform),
|
||||
"graphics": graphics,
|
||||
}
|
||||
|
||||
|
||||
@@ -349,13 +432,27 @@ def prepare():
|
||||
if materialize(platform):
|
||||
say("prepared %s as the x86 runtime" % os.path.basename(platform))
|
||||
install_preloads(root)
|
||||
provider = graphics_platform()
|
||||
if provider and materialize(provider):
|
||||
say("prepared %s for the x86 runtime's C and C++ libraries" % os.path.basename(provider))
|
||||
if not provider:
|
||||
say("Steam Linux Runtime 4.0 (Steam app %s) is not installed yet; x86 games may not find their graphics drivers"
|
||||
% SLR4_APPID)
|
||||
elif not provides_newer(platform, provider):
|
||||
say("%s has no newer C and C++ libraries than %s" % (os.path.basename(provider), os.path.basename(platform)))
|
||||
provider = None
|
||||
else:
|
||||
if build_rootfs(platform, provider):
|
||||
say("built the x86 runtime from %s with the C and C++ libraries of %s"
|
||||
% (os.path.basename(platform), os.path.basename(provider)))
|
||||
root = os.path.join(STATE, "rootfs")
|
||||
write_config(fex, root)
|
||||
fex["rootfs"] = root
|
||||
try:
|
||||
link_steam_sdk()
|
||||
except OSError:
|
||||
pass
|
||||
status = describe(fex, platform)
|
||||
status = describe(fex, platform, provider)
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(WANTED)
|
||||
@@ -411,8 +508,6 @@ def split_paths(value):
|
||||
|
||||
|
||||
def data_dir(env):
|
||||
# FEXServer's socket lives here. Under ~/.local its host path passes sun_path's 108 bytes, and
|
||||
# proot then binds it to a temporary name only the server sees: no client ever reaches it.
|
||||
runtime = env.get("XDG_RUNTIME_DIR")
|
||||
if runtime and os.path.isdir(runtime) and os.access(runtime, os.W_OK):
|
||||
return os.path.join(runtime, "fex")
|
||||
@@ -427,8 +522,16 @@ def guest_environment(fex, env):
|
||||
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
|
||||
result["FEX_APP_DATA_LOCATION"] = data + "/"
|
||||
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
|
||||
# Valve's FEX-Emu binds its server socket under $STEAM_COMPAT_DATA_PATH/fex-emu whatever FEX_APP_DATA_LOCATION or
|
||||
# FEX_SERVERSOCKETPATH say, and sun_path is 108 bytes: compatdata under the app's data folder is too long.
|
||||
if result.get("STEAM_COMPAT_DATA_PATH"):
|
||||
short = data if data != DATA_DIR else "/tmp/fex"
|
||||
os.makedirs(short, exist_ok=True)
|
||||
result["STEAM_COMPAT_DATA_PATH"] = short
|
||||
result.setdefault("FEX_SILENTLOG", "0")
|
||||
result.setdefault("FEX_OUTPUTLOG", "stderr")
|
||||
# Mono's incremental Boehm collector corrupts its heap under FEX, so Unity games crash at their first collections.
|
||||
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
|
||||
if fex["portable"]:
|
||||
result["FEX_PORTABLE"] = "1"
|
||||
else:
|
||||
@@ -444,7 +547,7 @@ def guest_environment(fex, env):
|
||||
result["FEX_THUNKCONFIG"] = os.path.join(CONFIG_DIR, "ThunksConfig.json")
|
||||
preload = [part for part in split_paths(result.get("LD_PRELOAD")) if os.path.exists(part) and not is_arm(part)]
|
||||
library_path = [part for part in (result.get("LD_LIBRARY_PATH") or "").split(":")
|
||||
if part and "steamrtarm64" not in part and "aarch64" not in part]
|
||||
if part and "arm64" not in part and "aarch64" not in part]
|
||||
for name, parts in (("LD_PRELOAD", preload), ("LD_LIBRARY_PATH", library_path)):
|
||||
if parts:
|
||||
result[name] = ":".join(parts)
|
||||
@@ -482,6 +585,7 @@ def vulkan_thunk_loads(fex, folder):
|
||||
needed = version_names(os.path.join(fex["guest_thunks"], VULKAN_THUNK))
|
||||
if not needed:
|
||||
return False
|
||||
needed |= version_names(os.path.join(PRELOADS, "x86_64", VULKAN_PIN))
|
||||
found = bundled_libraries(folder)
|
||||
for name, prefix in RUNTIME_LIBRARIES:
|
||||
library = found.get(name) or os.path.join(fex["rootfs"], "lib/x86_64-linux-gnu", name)
|
||||
@@ -508,9 +612,10 @@ def launch(command, env, mode, decide=None):
|
||||
x86_64 = elf_arch(program) != "i386"
|
||||
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
|
||||
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
|
||||
if thunks == "on" and x86_64 and all(os.path.isfile(os.path.join(PRELOADS, "x86_64", name)) for name in (THUNK_AUDIT, VULKAN_PIN)) \
|
||||
if thunks == "on" and x86_64 and os.path.isfile(os.path.join(PRELOADS, "x86_64", VULKAN_PIN)) \
|
||||
and vulkan_thunk_loads(fex, folder):
|
||||
guest["LD_AUDIT"] = ":".join([THUNK_AUDIT_GUEST] + split_paths(guest.get("LD_AUDIT")))
|
||||
# Any LD_AUDIT module makes Mono's garbage collector crash under FEX, so the Vulkan thunk is pinned by search path.
|
||||
guest["LD_LIBRARY_PATH"] = ":".join(["/usr/" + VULKAN_PIN_DIR] + split_paths(guest.get("LD_LIBRARY_PATH")))
|
||||
thunks = "on, its own Vulkan loader too"
|
||||
say("running %s with %s (runtime %s, thunks %s)" % (program, fex["bin"], guest.get("FEX_ROOTFS", "none"), thunks))
|
||||
return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest)
|
||||
@@ -562,19 +667,38 @@ def extracted():
|
||||
|
||||
def want_fex():
|
||||
with locked():
|
||||
status = describe(fex_install(), runtime_platform())
|
||||
status = describe(fex_install(), runtime_platform(), graphics_platform())
|
||||
if not status["ready"]:
|
||||
request_install()
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
|
||||
|
||||
XATTR_ONLY_NOISE = re.compile(r"^(proot (error|warning)|Failed to exec memfd|Further error messages of this type are suppressed)")
|
||||
|
||||
|
||||
def only_xattrs_failed(errors):
|
||||
seen = False
|
||||
for line in errors.splitlines():
|
||||
if "write_xattr" in line:
|
||||
seen = True
|
||||
elif re.search(r"fail|could not|cannot|error", line, re.I) and not XATTR_ONLY_NOISE.match(line):
|
||||
return False
|
||||
return seen
|
||||
|
||||
|
||||
def extract(image):
|
||||
image = os.path.abspath(image)
|
||||
clear_extracted()
|
||||
x86 = elf_arch(image) in X86.values()
|
||||
if os.access(URUNTIME, os.X_OK):
|
||||
status = subprocess.call([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL,
|
||||
env=dict(os.environ, TARGET_APPIMAGE=image))
|
||||
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||
env=dict(os.environ, TARGET_APPIMAGE=image))
|
||||
errors = run.stderr.decode("utf-8", "replace")
|
||||
sys.stderr.write(errors)
|
||||
status = run.returncode
|
||||
if status == 2 and only_xattrs_failed(errors) and extracted() and os.path.lexists("squashfs-root/AppRun"):
|
||||
say("uruntime could not keep the image's extended attributes; the files are unpacked")
|
||||
status = 0
|
||||
if status == 0 and extracted():
|
||||
if x86:
|
||||
want_fex()
|
||||
@@ -591,7 +715,7 @@ def extract(image):
|
||||
unsquashfs = shutil.which("unsquashfs")
|
||||
if unsquashfs:
|
||||
clear_extracted()
|
||||
status = subprocess.call([unsquashfs, "-q", "-n", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
|
||||
status = subprocess.call([unsquashfs, "-q", "-n", "-no-xattrs", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
|
||||
stdout=subprocess.DEVNULL)
|
||||
if status == 0:
|
||||
if x86:
|
||||
@@ -659,7 +783,7 @@ def main(argv):
|
||||
return 0 if prepare() else 1
|
||||
if action == "status":
|
||||
with locked():
|
||||
status = describe(fex_install(), runtime_platform())
|
||||
status = describe(fex_install(), runtime_platform(), graphics_platform())
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
print(json.dumps(status, indent=2))
|
||||
return 0 if status["ready"] else 1
|
||||
|
||||
@@ -1,27 +1,14 @@
|
||||
#!/usr/bin/python3
|
||||
# The app's store talks to Flatpak through this: one JSON object per line on stdout, so progress
|
||||
# reaches the front end as numbers rather than a terminal's redrawn bar. Per-user installation,
|
||||
# Flathub as the remote, this device's architecture.
|
||||
#
|
||||
# droiddeck-flatpak install <app-id> the app and whatever runtimes it needs
|
||||
# droiddeck-flatpak install-bundle <file> a .flatpak file, its runtimes from Flathub
|
||||
# droiddeck-flatpak uninstall <app-id> the app, then runtimes nothing uses any more
|
||||
# droiddeck-flatpak update [<app-id>] one app, or everything with an update
|
||||
# droiddeck-flatpak updates what has one (a "updates" line)
|
||||
#
|
||||
# Lines: {"e":"op","i":1,"n":3,"kind":"install","ref":"..."} as each step starts,
|
||||
# {"e":"progress","i":1,"n":3,"percent":45,"status":"..."} while it runs,
|
||||
# {"e":"error","message":"..."} and {"e":"done"} at the end (with "id" for a bundle). Exit status 0 on success.
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
|
||||
|
||||
import gi # noqa: E402
|
||||
import gi
|
||||
|
||||
gi.require_version("Flatpak", "1.0")
|
||||
from gi.repository import Flatpak, Gio, GLib # noqa: E402
|
||||
from gi.repository import Flatpak, Gio, GLib
|
||||
|
||||
REMOTE = "flathub"
|
||||
|
||||
@@ -82,12 +69,6 @@ def transaction(inst):
|
||||
progress.connect("changed", changed)
|
||||
|
||||
def on_operation_error(tr, op, err, details):
|
||||
# A runtime extension that fails to install (a missing translation, an unneeded GL
|
||||
# driver) is not worth losing the app over; anything else ends the transaction.
|
||||
# FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL is 1, but PyGObject does not always hand the
|
||||
# flags over ("g_value_get_flags: assertion ... failed" and a 0). An extension installed
|
||||
# alongside an app - its translations, debug data, a GL or codecs runtime - is what Flatpak
|
||||
# marks non-fatal, as the flatpak CLI does: its failure costs that extension, not the app.
|
||||
try:
|
||||
non_fatal = bool(int(details) & 1)
|
||||
except (TypeError, ValueError):
|
||||
@@ -108,7 +89,6 @@ def transaction(inst):
|
||||
t.connect("ready", on_ready)
|
||||
t.connect("new-operation", on_new_operation)
|
||||
t.connect("operation-error", on_operation_error)
|
||||
# A dependency found on more than one remote comes from the first (Flathub, the only one).
|
||||
t.connect("choose-remote-for-ref", lambda tr, ref, runtime_ref, remotes: 0)
|
||||
t.connect("end-of-lifed-with-rebase", lambda *a: False)
|
||||
t.connect("add-new-remote", lambda *a: False)
|
||||
@@ -135,7 +115,6 @@ def install(app_id):
|
||||
if app_ref(inst, app_id) is not None:
|
||||
emit(e="done", note="already installed")
|
||||
return 0
|
||||
# Flathub publishes apps on "stable"; libflatpak's default branch is "master".
|
||||
branch, last = None, None
|
||||
for candidate in ("stable", "master"):
|
||||
try:
|
||||
@@ -149,8 +128,6 @@ def install(app_id):
|
||||
t, state = transaction(inst)
|
||||
t.add_install(REMOTE, "app/%s/%s/%s" % (app_id, arch, branch), None)
|
||||
rc = run(t, state, report_done=False)
|
||||
# A failure the transaction did not report (an error handler that raised, say) must not read
|
||||
# as an install: the app is there, or it is not.
|
||||
if rc == 0 and app_ref(installation(), app_id) is None:
|
||||
emit(e="error", message="%s did not install; see flatpak-install.log" % app_id)
|
||||
return 1
|
||||
@@ -192,7 +169,6 @@ def uninstall(app_id):
|
||||
t.add_uninstall(ref.format_ref())
|
||||
rc = run(t, state)
|
||||
if rc == 0:
|
||||
# Runtimes only this app used; Flatpak's own `uninstall --unused`.
|
||||
try:
|
||||
unused = inst.list_unused_refs(None, None)
|
||||
except GLib.Error:
|
||||
@@ -205,6 +181,27 @@ def uninstall(app_id):
|
||||
return rc
|
||||
|
||||
|
||||
def prune():
|
||||
inst = installation()
|
||||
try:
|
||||
unused = inst.list_unused_refs(None, None)
|
||||
except GLib.Error as err:
|
||||
emit(e="error", message=err.message)
|
||||
return 1
|
||||
if unused:
|
||||
t, state = transaction(inst)
|
||||
for r in unused:
|
||||
t.add_uninstall(r.format_ref())
|
||||
if run(t, state, report_done=False):
|
||||
return 1
|
||||
try:
|
||||
inst.prune_local_repo(None)
|
||||
except GLib.Error as err:
|
||||
emit(e="warning", message=err.message)
|
||||
emit(e="done", removed=len(unused))
|
||||
return 0
|
||||
|
||||
|
||||
def updatable(inst):
|
||||
try:
|
||||
return inst.list_installed_refs_for_update(None)
|
||||
@@ -240,7 +237,7 @@ def updates():
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
|
||||
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates|prune [app-id|file]\n")
|
||||
return 2
|
||||
cmd, args = sys.argv[1], sys.argv[2:]
|
||||
if cmd in ("install", "install-bundle", "update"):
|
||||
@@ -255,7 +252,9 @@ def main():
|
||||
return update(args[0] if args else None)
|
||||
if cmd == "updates":
|
||||
return updates()
|
||||
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
|
||||
if cmd == "prune":
|
||||
return prune()
|
||||
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates|prune [app-id|file]\n")
|
||||
return 2
|
||||
|
||||
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
#!/bin/bash
|
||||
# A Flatpak app from the front end, full screen under gamescope like an emulator:
|
||||
# droiddeck-flatpak-run <app-id> [args...]
|
||||
set -u
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
case ":${XDG_DATA_DIRS:-}:" in
|
||||
*"/flatpak/exports/share:"*) ;;
|
||||
*) export XDG_DATA_DIRS=$HOME/.local/share/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share} ;;
|
||||
esac
|
||||
# Under gamescope - a program's session (BL_INSIDE), or droiddeck-gpu from the desktop
|
||||
# (GAMESCOPE_WAYLAND_DISPLAY) - windows have to reach gamescope's X server. Flatpak would hand an
|
||||
# app wayland-0 (it finds it in the runtime directory even with WAYLAND_DISPLAY unset) and the
|
||||
# window would open behind gamescope. gamescope's own Wayland socket is no way out: Chromium on
|
||||
# Wayland asks the render node it names for its DRM version, which KGSL cannot answer, and exits.
|
||||
# The session is X11 as far as an app can tell; Electron picks its platform from that.
|
||||
# Its own flatpak options (--branch, --command, from a menu entry) come first, then the app id.
|
||||
socket=()
|
||||
if [ -n "${BL_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
|
||||
unset WAYLAND_DISPLAY
|
||||
@@ -21,7 +12,6 @@ if [ -n "${BL_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
|
||||
socket=(--nosocket=wayland --socket=x11)
|
||||
fi
|
||||
echo "== flatpak run ${socket[*]} $*"
|
||||
# Apps expect a session bus (settings, portals, single-instance checks); a run mode has none.
|
||||
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
|
||||
exec dbus-run-session -- flatpak run "${socket[@]}" "$@"
|
||||
fi
|
||||
|
||||
@@ -1,26 +1,10 @@
|
||||
#!/bin/bash
|
||||
# Puts Flatpak into the runtime, with Flathub as a per-user remote. Run by the app under proot's
|
||||
# fake root (pacman and pacman-key refuse any other uid), outside a session.
|
||||
#
|
||||
# The runtime's pacman database lists only the base image: the desktop and emulator packages were
|
||||
# unpacked over it without registering. Asked for flatpak the usual way, pacman "reinstalls" about
|
||||
# a hundred of those - Mesa among them, over the runtime's own Turnip build with its KGSL backend -
|
||||
# and then runs every hook in the image, mkinitcpio included. So pacman only fetches and checks the
|
||||
# few packages Flatpak needs on top of this image, verifying each against the Arch Linux ARM
|
||||
# keyring, and they are unpacked here without hooks or scripts, like the desktop package itself.
|
||||
#
|
||||
# droiddeck-flatpak-setup install or repair; prints "== STEP ..." milestones
|
||||
set -u
|
||||
export LANG=C.UTF-8
|
||||
step() { echo "== STEP $*"; }
|
||||
fail() { echo "== FAIL $*"; exit 1; }
|
||||
|
||||
# Flatpak, the libraries it and appstream add to this image, and the D-Bus proxy flatpak run puts
|
||||
# between an app and the session bus. bubblewrap is not among them: Android gives an app no user
|
||||
# namespaces, and droiddeck-bwrap stands in for it (FLATPAK_BWRAP).
|
||||
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
|
||||
# Libraries Flatpak and the store's helper also need, which the Desktop package brings but a
|
||||
# runtime without it may lack: each is fetched only when its file is not already there.
|
||||
while read -r pkg probe; do
|
||||
[ -n "$pkg" ] || continue
|
||||
compgen -G "$probe" >/dev/null || PACKAGES="$PACKAGES $pkg"
|
||||
@@ -41,10 +25,15 @@ WORK=/var/cache/droiddeck-flatpak
|
||||
CONF=$WORK/pacman.conf
|
||||
mkdir -p "$WORK/pkg" "$WORK/db" || fail "cannot create $WORK"
|
||||
|
||||
# The image's pacman.conf names a download user this rootfs does not have (only root exists) and a
|
||||
# sandbox proot cannot set up. Its one mirror is plain HTTP; these serve the same repos over TLS.
|
||||
{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org \
|
||||
https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do
|
||||
OVERSEAS="https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org"
|
||||
MAINLAND=""
|
||||
for m in https://mirrors.tuna.tsinghua.edu.cn/archlinuxarm https://mirrors.ustc.edu.cn/archlinuxarm \
|
||||
https://mirrors.bfsu.edu.cn/archlinuxarm https://mirrors.sjtug.sjtu.edu.cn/archlinuxarm; do
|
||||
if curl -fsS -r 0-0 --connect-timeout 4 --max-time 8 -o /dev/null "$m/aarch64/core/core.db" 2>/dev/null; then
|
||||
MAINLAND="$MAINLAND $m"
|
||||
fi
|
||||
done
|
||||
{ for m in $MAINLAND $OVERSEAS; do
|
||||
echo "Server = $m/\$arch/\$repo"; done
|
||||
grep '^Server' /etc/pacman.d/mirrorlist 2>/dev/null; } > "$WORK/mirrorlist"
|
||||
sed -e 's/^DownloadUser/#DownloadUser/' \
|
||||
@@ -58,8 +47,6 @@ if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubrin
|
||||
pacman-key --populate archlinuxarm >/dev/null 2>&1 || fail "pacman-key --populate failed"
|
||||
fi
|
||||
|
||||
# A database of our own, so the image's stays exactly as it was built: -Sy on it would leave the
|
||||
# rest of the image a partial upgrade behind the repos.
|
||||
step "Reading the package lists"
|
||||
pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \
|
||||
|| pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1 | tail -3 \
|
||||
@@ -67,8 +54,6 @@ pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \
|
||||
[ -f "$WORK/db/sync/extra.db" ] || fail "could not reach the Arch Linux ARM mirrors"
|
||||
|
||||
step "Downloading Flatpak"
|
||||
# -w only downloads; pacman still checks each package's signature against the keyring. -dd: the
|
||||
# dependencies are already in the image (and checked below by what the binaries actually link).
|
||||
out=$(pacman --config "$CONF" --dbpath "$WORK/db" --cachedir "$WORK/pkg" --noconfirm -Sw -dd $PACKAGES 2>&1)
|
||||
rc=$?
|
||||
echo "$out" | grep -vE '^\s*$' | tail -4
|
||||
@@ -84,10 +69,8 @@ for name in $PACKAGES; do
|
||||
echo "$name $ver" >> "$WORK/installed.new"
|
||||
done
|
||||
mv -f "$WORK/installed.new" "$WORK/installed"
|
||||
# Only the newest file of each package is worth keeping for a repair.
|
||||
find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null
|
||||
|
||||
# What the binaries link is the real dependency list: anything this image lacks shows here.
|
||||
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
|
||||
ldd "$f" 2>&1 | grep -E 'not found|version .* not found'
|
||||
done | sort -u)
|
||||
@@ -98,9 +81,6 @@ python3 -c 'import gi; gi.require_version("Flatpak", "1.0"); from gi.repository
|
||||
|
||||
step "Adding Flathub"
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
# Flathub's descriptor - its URL and the key its commits are signed with - is carried here rather
|
||||
# than fetched: adding the remote then needs no network, and a descriptor that did not arrive
|
||||
# whole cannot be what failed. Flathub's own copy: https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
cat > "$WORK/flathub.flatpakrepo" <<'REPO'
|
||||
[Flatpak Repo]
|
||||
Title=Flathub
|
||||
@@ -115,7 +95,6 @@ if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; t
|
||||
out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1)
|
||||
rc=$?
|
||||
echo "$out"
|
||||
# What Flatpak said goes up with the failure, so the app can show it rather than a guess.
|
||||
[ $rc -eq 0 ] || fail "could not add the Flathub remote: $(echo "$out" | grep -v '^[[:space:]]*$' | tail -1)"
|
||||
fi
|
||||
echo "== DONE $(flatpak --version)"
|
||||
@@ -1,24 +1,12 @@
|
||||
#!/bin/bash
|
||||
# DroidDeck's fontconfig setup for the Linux runtime. The rootfs ships DejaVu alone and no rules
|
||||
# for a default family: applications then find fonts but no default, and Firefox logs "no fonts"
|
||||
# and draws pages without text. DejaVu also has no CJK, Thai or Arabic glyphs, so those draw as
|
||||
# tofu boxes. The app binds Android's fonts for the session, which adds language-specific fallbacks
|
||||
# separately. This script links fontconfig's default rules and writes generic DejaVu aliases to an
|
||||
# owned conf.d file. Fontconfig reads local.conf afterward, so user overrides keep precedence and
|
||||
# are never replaced.
|
||||
# The first argument is the root to set up, "/" in a session; the tests point it at a temp tree.
|
||||
set -u
|
||||
root=${1:-/}
|
||||
root=${root%/}
|
||||
# "/" strips to empty above; put it back so the paths below read as absolute and the test for a
|
||||
# real session ("/") still holds.
|
||||
[ -n "$root" ] || root=/
|
||||
conf_dir=$root/etc/fonts
|
||||
defaults_dir=$root/usr/share/fontconfig/conf.default
|
||||
mkdir -p "$conf_dir/conf.d" 2>/dev/null
|
||||
|
||||
# The default rules (sans-serif -> DejaVu Sans and the rest) live as links in /etc/fonts/conf.d,
|
||||
# and the rootfs has none. Linked by name, so a file we ship is never overwritten.
|
||||
if [ -d "$defaults_dir" ]; then
|
||||
for f in "$defaults_dir"/*.conf; do
|
||||
[ -e "$f" ] || continue
|
||||
|
||||
@@ -7,7 +7,7 @@ import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SYNC_KEYS = ("BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
|
||||
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
|
||||
|
||||
@@ -25,8 +25,6 @@ def game_id(env):
|
||||
return str(number % 2**32)
|
||||
|
||||
|
||||
# A .NET (CoreCLR) runtime under FEX crashes in the runtime itself unless memory ordering is fully
|
||||
# emulated and multiblock is off: the Stability preset.
|
||||
DOTNET_FEX = {
|
||||
"FEX_TSOENABLED": "1",
|
||||
"FEX_VECTORTSOENABLED": "1",
|
||||
@@ -69,8 +67,6 @@ class Game:
|
||||
return any(a == name or a.startswith(name + "=") for a in self.args)
|
||||
|
||||
|
||||
# Each fix looks at a Game and returns (environment, extra arguments, note) for the games it
|
||||
# applies to, or None. Adding one is writing a function and decorating it.
|
||||
FIXES = []
|
||||
|
||||
|
||||
@@ -91,21 +87,25 @@ def dotnet_memory_ordering(game):
|
||||
|
||||
@fix
|
||||
def godot_vulkan(game):
|
||||
# Godot 4 on Direct3D 12 through VKD3D-Proton fails to create its swap chain and runs behind a
|
||||
# black window; its own Vulkan renderer draws.
|
||||
if is_godot(game) and not game.has_arg("--rendering-driver"):
|
||||
return {}, ["--rendering-driver", "vulkan"], "Godot: Vulkan renderer"
|
||||
|
||||
|
||||
@fix
|
||||
def godot_sentry(game):
|
||||
# The Sentry GDExtension's native crash handler takes the .NET runtime down under FEX. Godot
|
||||
# loads it on demand and carries on without it.
|
||||
sentry = sorted(n[:-4] for n in game.files if n.startswith("libsentry.windows.") and n.endswith(".dll"))
|
||||
if is_godot(game) and sentry:
|
||||
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
|
||||
|
||||
|
||||
@fix
|
||||
def arkham_city_x87(game):
|
||||
"""Batman: Arkham City (BatmanAC.exe, also started through BmLauncher.exe beside it) leans on x87
|
||||
and stops with Unreal's "Fatal error!" right after start when FEX reduces its precision."""
|
||||
if "batmanac.exe" in game.files:
|
||||
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
|
||||
|
||||
|
||||
def skip_red_launcher(command):
|
||||
"""Cyberpunk 2077's prelauncher opens REDlauncher, a Qt WebEngine window that hands over to the
|
||||
game half a minute later and then stays up beside it, well over a core busy for as long as the
|
||||
@@ -166,9 +166,10 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
result[name] = value
|
||||
else:
|
||||
raise ValueError("invalid environment value")
|
||||
# The app's texture filtering (Display page), as DXVK options appended after the profiles so
|
||||
# a DXVK_CONFIG entry of the user's keeps its own.
|
||||
dxvk = config.get("dxvkConfig")
|
||||
game_dxvk = config.get("dxvkConfigGames", {})
|
||||
if not isinstance(game_dxvk, dict):
|
||||
raise ValueError("invalid game dxvk configuration")
|
||||
dxvk = game_dxvk.get(app_id, config.get("dxvkConfig"))
|
||||
if dxvk is not None:
|
||||
if not isinstance(dxvk, str) or "\0" in dxvk or len(dxvk) > 8192:
|
||||
raise ValueError("invalid dxvk configuration")
|
||||
@@ -260,7 +261,7 @@ def mark_install_scripts(command, env):
|
||||
ones stop with an error."""
|
||||
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
|
||||
return
|
||||
root = env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
|
||||
root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
|
||||
scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)]
|
||||
scripts = [path for path in scripts if os.path.isfile(path)]
|
||||
if not scripts:
|
||||
@@ -277,6 +278,7 @@ def main():
|
||||
if not command:
|
||||
return 2
|
||||
env = os.environ.copy()
|
||||
mic_enabled = env.get("BL_MIC_ENABLED")
|
||||
mark_install_scripts(command, env)
|
||||
app_id = game_id(env)
|
||||
if app_id:
|
||||
@@ -305,6 +307,8 @@ def main():
|
||||
env = apply_config(env, {"version": 1}, app_id, fixes)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
if mic_enabled == "0":
|
||||
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
|
||||
env = force_ssbs(command, env)
|
||||
sync = load_sync()
|
||||
launch, launch_env = select_sync(command, env, sync)
|
||||
|
||||
@@ -8,8 +8,6 @@ import sys
|
||||
|
||||
|
||||
def advertise_compositing():
|
||||
# This is gamescope's private X server: it composites alpha buffers already, but GTK also
|
||||
# requires the compositing-manager selection and frame-extents hint before enabling CSD.
|
||||
x = c.CDLL('libX11.so.6')
|
||||
display_type, window_type = c.c_void_p, c.c_ulong
|
||||
x.XOpenDisplay.argtypes = [c.c_char_p]
|
||||
@@ -41,7 +39,6 @@ def advertise_compositing():
|
||||
x.XChangeProperty(display, root, atom('_NET_SUPPORTED'), atom('ATOM'), 32, 2, c.byref(extents), 1)
|
||||
x.XSync.argtypes = [display_type, c.c_int]
|
||||
x.XSync(display, False)
|
||||
# Keep the selection's connection alive until the program exits.
|
||||
return x, display
|
||||
|
||||
|
||||
|
||||
@@ -22,14 +22,10 @@ import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# Image paths (lower case, backslashes), matched at the end: the helpers held back, and the
|
||||
# programs whose window having focus means the user is looking at the launcher.
|
||||
HELPERS = ("\\rockstar games\\social club\\socialclubhelper.exe",)
|
||||
FRONTS = HELPERS + ("\\rockstar games\\launcher\\launcher.exe",)
|
||||
NICE = 19
|
||||
POLL = 2.0
|
||||
# How often a held launcher is looked over again: for a helper the unheld Launcher.exe started
|
||||
# since, and for threads the program has moved back.
|
||||
RESCAN = 10.0
|
||||
STEAM_CLIENT = 769
|
||||
|
||||
@@ -72,8 +68,6 @@ class Cores:
|
||||
try:
|
||||
os.sched_setaffinity(tid, cpus)
|
||||
except OSError:
|
||||
# A mask outside the app's cpuset now (Android shrinks it in the background) is
|
||||
# EINVAL; the session's own is always allowed.
|
||||
os.sched_setaffinity(tid, self.own())
|
||||
os.setpriority(os.PRIO_PROCESS, tid, nice)
|
||||
|
||||
@@ -83,7 +77,7 @@ class Holder:
|
||||
self.proc = proc
|
||||
self.cpufreq = cpufreq
|
||||
self.cores = cores or Cores()
|
||||
self.held = {} # pid -> {tid: (cpus, nice) before the hold}
|
||||
self.held = {}
|
||||
self.core = None
|
||||
|
||||
def slow_core(self):
|
||||
@@ -117,10 +111,8 @@ class Holder:
|
||||
if now != hold:
|
||||
self.cores.set(tid, *hold)
|
||||
except OSError:
|
||||
continue # the thread ended
|
||||
continue
|
||||
if tid not in before:
|
||||
# A thread that already has the hold inherited it from a held parent: it gets
|
||||
# what its process had, or the helpers' first.
|
||||
before[tid] = now if now != hold else before.get(pid) or self.first() or now
|
||||
for pid in [pid for pid in self.held if not (self.proc / str(pid)).exists()]:
|
||||
del self.held[pid]
|
||||
@@ -191,8 +183,6 @@ class Governor:
|
||||
self.holder.release()
|
||||
self.report("released: the launcher has focus")
|
||||
return
|
||||
# Nothing to look for until a game has had focus: launchers only run for one, and a launcher
|
||||
# left running after its game stays held through the Steam client's own focus.
|
||||
if self.app in (None, 0, STEAM_CLIENT) and not self.holder.held:
|
||||
return
|
||||
now = self.clock()
|
||||
|
||||
@@ -5,16 +5,20 @@ Android owns device power. Suspend here pauses the guest through SessionService;
|
||||
the app's Resume action thaws it and completes PrepareForSleep(false). Steam
|
||||
must see this service before startup or it can stay black after its idle timer.
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib # noqa: E402
|
||||
from gi.repository import Gio, GLib
|
||||
|
||||
NAME = "org.freedesktop.login1"
|
||||
ROOT = "/org/freedesktop/login1"
|
||||
@@ -22,6 +26,8 @@ INTERFACE = NAME + ".Manager"
|
||||
UPOWER = "org.freedesktop.UPower"
|
||||
UPOWER_ROOT = "/org/freedesktop/UPower"
|
||||
NATIVE_PREPARE_MS = 1500
|
||||
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
|
||||
ASLEEP_WAIT = 6
|
||||
INTROSPECTION = """
|
||||
<node>
|
||||
<interface name="org.freedesktop.login1.Manager">
|
||||
@@ -56,8 +62,6 @@ class LoginManager:
|
||||
self.preparation = None
|
||||
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
|
||||
self.registration = bus.register_object(ROOT, info, self.method, self.property, None)
|
||||
# Steam can issue its suspend command through the legacy UPower service even
|
||||
# while listening to login1's sleep/resume notifications. Use one handshake.
|
||||
upower_info = Gio.DBusNodeInfo.new_for_xml(UPOWER_INTROSPECTION).interfaces[0]
|
||||
self.upower_registration = bus.register_object(UPOWER_ROOT, upower_info, self.method, None, None)
|
||||
self.monitor = Gio.File.new_for_path(str(self.directory)).monitor_directory(Gio.FileMonitorFlags.NONE, None)
|
||||
@@ -80,14 +84,13 @@ class LoginManager:
|
||||
if name == "CanSuspend":
|
||||
reply.return_value(GLib.Variant("(s)", ("yes",)))
|
||||
elif name in ("Suspend", "SuspendWithFlags"):
|
||||
print("== login1: %s.%s asked by %s" % (interface.rsplit(".", 1)[-1], name, sender), flush=True)
|
||||
if self.pending:
|
||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||
return
|
||||
self.pending = uuid.uuid4().hex
|
||||
self.notify(True)
|
||||
reply.return_value(None)
|
||||
# Flush the signal and method reply without blocking this D-Bus callback. Once both are
|
||||
# on the wire, publishing the request lets the host safely freeze this service.
|
||||
self.bus.flush(None, self.publish_after_flush, self.pending)
|
||||
|
||||
def publish_after_flush(self, connection, result, token):
|
||||
@@ -122,7 +125,6 @@ class LoginManager:
|
||||
return
|
||||
if not re.fullmatch(r"[a-f0-9]{32}", token) or self.pending is not None:
|
||||
return
|
||||
# Android may have returned before this helper read its request.
|
||||
if self.read_state() == token + ":awake":
|
||||
return
|
||||
self.pending = token
|
||||
@@ -138,8 +140,6 @@ class LoginManager:
|
||||
return
|
||||
self.check_state()
|
||||
if self.pending == token:
|
||||
# Keep Steam runnable while it handles the system sleep notification.
|
||||
# This is a bounded grace period, not a claim that every game has saved.
|
||||
self.preparation = GLib.timeout_add(NATIVE_PREPARE_MS, self.finish_preparation, token)
|
||||
|
||||
def finish_preparation(self, token):
|
||||
@@ -154,7 +154,7 @@ class LoginManager:
|
||||
if file.get_basename() == self.wake.name or (other and other.get_basename() == self.wake.name):
|
||||
if self.wake.exists():
|
||||
self.wake.unlink(missing_ok=True)
|
||||
self.resume(force=True)
|
||||
self.woken()
|
||||
if file.get_basename() == self.state.name or (other and other.get_basename() == self.state.name):
|
||||
self.check_state()
|
||||
|
||||
@@ -171,17 +171,27 @@ class LoginManager:
|
||||
def check_ack(self):
|
||||
self.timeout = None
|
||||
if self.pending and self.read_state() != self.pending + ":paused":
|
||||
# A missing host or a failed freeze must not strand Steam in black.
|
||||
self.request.unlink(missing_ok=True)
|
||||
self.native_ready.unlink(missing_ok=True)
|
||||
self.resume()
|
||||
return False
|
||||
|
||||
def woken(self):
|
||||
if self.pending is not None:
|
||||
self.resume(force=True)
|
||||
return
|
||||
threading.Thread(target=lambda: GLib.idle_add(self.replay_unless_awake, steam_asleep()), daemon=True).start()
|
||||
|
||||
def replay_unless_awake(self, asleep):
|
||||
if asleep is False and self.pending is None:
|
||||
print("== login1: Steam is awake; no sleep/wake replay", flush=True)
|
||||
return False
|
||||
self.resume(force=True)
|
||||
return False
|
||||
|
||||
def resume(self, force=False):
|
||||
if self.pending is None:
|
||||
if force:
|
||||
# A missed suspend command leaves Steam without the first half of
|
||||
# the handshake. Replay both notifications, without pausing again.
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.finish_recovery, None)
|
||||
return
|
||||
@@ -203,6 +213,24 @@ class LoginManager:
|
||||
self.notify(False)
|
||||
|
||||
|
||||
def steam_asleep():
|
||||
try:
|
||||
code = subprocess.run([str(AGENT), "--steam-asleep"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=ASLEEP_WAIT).returncode
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
return {0: True, 5: False}.get(code)
|
||||
|
||||
|
||||
def load_netmanager():
|
||||
path = Path(__file__).resolve().with_name("droiddeck-netmanager")
|
||||
loader = importlib.machinery.SourceFileLoader("droiddeck_netmanager", str(path))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def main():
|
||||
directory = os.environ.get("BL_LAUNCH_DIR")
|
||||
if not directory or not Path(directory).is_dir():
|
||||
@@ -228,6 +256,8 @@ def main():
|
||||
|
||||
owners = [Gio.bus_own_name(Gio.BusType.SYSTEM, name, Gio.BusNameOwnerFlags.NONE, connected, acquired, lost)
|
||||
for name in (NAME, UPOWER)]
|
||||
if "--with-netmanager" in sys.argv[1:]:
|
||||
owners.append(load_netmanager().own(loop))
|
||||
try:
|
||||
loop.run()
|
||||
finally:
|
||||
|
||||
@@ -43,7 +43,6 @@ CABEXTRACT = os.environ.get("DROIDDECK_CABEXTRACT", str(TOOLS / "cabextract"))
|
||||
SEVENZIP = os.environ.get("DROIDDECK_7Z", str(TOOLS / "7z"))
|
||||
MSI_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
||||
BURN_MAGIC = 0x00F14300
|
||||
# A bundle's manifest names ARM64 packages too; a game's prefix wants the x86 and x64 ones.
|
||||
SKIP_PLATFORMS = ("arm64", "arm")
|
||||
|
||||
|
||||
@@ -53,9 +52,6 @@ def tool_env():
|
||||
env["LD_LIBRARY_PATH"] = ":".join(p for p in (str(TOOLS), env.get("LD_LIBRARY_PATH", "")) if p)
|
||||
return env
|
||||
|
||||
# The folders Windows Installer knows by name, as a 64-bit Windows 10 prefix lays them out (Proton's
|
||||
# user is steamuser). None is a folder whose files a game never needs: installer temp files and
|
||||
# shortcuts.
|
||||
SKIP = None
|
||||
KNOWN_FOLDERS = {
|
||||
"TARGETDIR": "C:\\", "ROOTDRIVE": "C:\\", "WindowsVolume": "C:\\",
|
||||
@@ -78,25 +74,17 @@ for _name in ("TempFolder", "DesktopFolder", "ProgramMenuFolder", "StartMenuFold
|
||||
"TemplateFolder", "MyPicturesFolder", "AdminToolsFolder"):
|
||||
KNOWN_FOLDERS[_name] = SKIP
|
||||
|
||||
# What Wine's msi reports on a 64-bit Windows 10 prefix, for the packages' conditions.
|
||||
SYSTEM_PROPERTIES = {
|
||||
"VersionNT": "603", "VersionNT64": "603", "WindowsBuild": "9600", "ServicePackLevel": "0",
|
||||
"Msix64": "6", "ALLUSERS": "1", "Privileged": "1", "AdminUser": "1", "MsiNTProductType": "1",
|
||||
"UILevel": "2", "INSTALLLEVEL": "1", "ProgramFilesFolder": None, "VersionMsi": "5.00",
|
||||
}
|
||||
|
||||
# Win64 component (msidbComponentAttributes64bit); file attributes.
|
||||
COMPONENT_64BIT = 0x100
|
||||
FILE_NONCOMPRESSED = 0x2000
|
||||
# Custom action types that only set a property or a folder: done here, the rest are named in notes.
|
||||
SET_PROPERTY, SET_DIRECTORY, ERROR_ACTION = 51, 35, 19
|
||||
# Microsoft's "SFP CA" merge module (MDAC, MSXML): on Windows 2000 and later it parks system DLLs in a
|
||||
# cache folder and its own code copies them into the system folder past Windows File Protection.
|
||||
# Skipping the folder change puts them where that copy would. Its actions, and the side-by-side
|
||||
# merge module's (done here from MsiAssembly), are then left out of the notes.
|
||||
SFP_CACHE_ACTION = "CDirSystemSFPCacheDir"
|
||||
HANDLED_ACTIONS = ("Wdsfpca_", "SxsInstallCA", "SxsUninstallCA")
|
||||
# Tables whose work needs the package's own code or is not done here yet.
|
||||
UNSUPPORTED_TABLES = ("SelfReg", "Class", "ProgId", "TypeLib", "Extension", "Verb", "MIME", "AppId",
|
||||
"IniFile", "ServiceInstall", "MoveFile", "IsolatedComponent", "PublishComponent",
|
||||
"ODBCDriver", "ODBCDataSource")
|
||||
@@ -123,7 +111,6 @@ class Span:
|
||||
progress(text, self.lo + (self.hi - self.lo) * max(0.0, min(1.0, fraction)))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reading the package
|
||||
|
||||
IDT_ESCAPES = str.maketrans({"\x19": "\n", "\x11": "\r", "\x15": "\t", "\x1b": ";"})
|
||||
|
||||
@@ -182,7 +169,6 @@ def to_int(value, default=0):
|
||||
return default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- conditions
|
||||
|
||||
TOKEN = re.compile(r'\s*(?:(?P<str>"[^"]*")|(?P<num>-?\d+)(?![\w.])|(?P<op>~?(?:<>|<=|>=|><|<<|>>|=|<|>))'
|
||||
r'|(?P<paren>[()])|(?P<word>[%$?&!]?[A-Za-z_][\w.]*))')
|
||||
@@ -330,7 +316,6 @@ class Conditions:
|
||||
return value not in ("", None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the install
|
||||
|
||||
def win_to_rel(path):
|
||||
"""C:\\windows\\x\\ -> drive_c/windows/x; None for a path off drive C or a folder left out."""
|
||||
@@ -375,7 +360,7 @@ class Installer:
|
||||
self.span = span or Span()
|
||||
self.notes = []
|
||||
self.registry = []
|
||||
self.files = {} # File key -> rel path it was installed to
|
||||
self.files = {}
|
||||
self.counts = {"files": 0, "assemblies": 0, "registry": 0}
|
||||
template = self.pkg.summary.get("template", "")
|
||||
self.platform = template.split(";")[0].strip().lower()
|
||||
@@ -385,7 +370,6 @@ class Installer:
|
||||
for name, path in KNOWN_FOLDERS.items():
|
||||
self.props[name] = path if path is not None else "\0skip"
|
||||
for row in self.pkg.table("Property"):
|
||||
# The package's own defaults, but never over the folders and the system it runs on.
|
||||
if row["Property"] not in self.props or row["Property"] in ("INSTALLLEVEL", "ALLUSERS", "UILevel"):
|
||||
self.props[row["Property"]] = row["Value"]
|
||||
self.props["ALLUSERS"] = "1"
|
||||
@@ -397,7 +381,6 @@ class Installer:
|
||||
self._resolving = set()
|
||||
self._set_by_action = set()
|
||||
|
||||
# -- states, folders, formatted text
|
||||
|
||||
def feature_state(self, name):
|
||||
return 3 if name in self.included_features else -1
|
||||
@@ -411,13 +394,11 @@ class Installer:
|
||||
return None
|
||||
value = self.props.get(key)
|
||||
row = self.directories.get(key)
|
||||
# A folder Windows knows by name, one a custom action set, or a property naming a path.
|
||||
if key in KNOWN_FOLDERS or key in self._set_by_action or row is None:
|
||||
return None if value in (None, "", "\0skip") else win_to_rel(value)
|
||||
parent_key = row.get("Directory_Parent", "")
|
||||
default = long_name(row.get("DefaultDir", "").split(":")[0])
|
||||
if not parent_key or parent_key == key:
|
||||
# A root: TARGETDIR (SourceDir) is drive C.
|
||||
return "drive_c"
|
||||
self._resolving.add(key)
|
||||
try:
|
||||
@@ -466,7 +447,6 @@ class Installer:
|
||||
text = re.sub(r"\[([^\[\]]*)\]", one, text)
|
||||
return text
|
||||
|
||||
# -- what gets installed
|
||||
|
||||
def run_set_actions(self):
|
||||
"""The property/folder-setting custom actions, in sequence order; the rest go to the notes."""
|
||||
@@ -581,8 +561,6 @@ class Installer:
|
||||
self.pkg.stream(cabinet[1:], cab)
|
||||
own = True
|
||||
else:
|
||||
# An external cabinet: a file beside the package, as an installer wrapper lays it out
|
||||
# (vc_red.cab beside vc_red.msi, netfx_Full.mzz beside netfx_Full_x64.msi).
|
||||
cab = sibling(Path(self.pkg.path), cabinet)
|
||||
if cab is None:
|
||||
self.notes.append("external cabinet %s is not part of the package; its files are missing" % cabinet)
|
||||
@@ -601,15 +579,17 @@ class Installer:
|
||||
|
||||
def put(self, source, rel):
|
||||
target = self.out / rel
|
||||
if target.exists() and Path(source).samefile(target):
|
||||
return False
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
return True
|
||||
|
||||
def install_files(self, unpacked):
|
||||
assemblies = self.assemblies()
|
||||
files = self.pkg.table("File")
|
||||
missing = 0
|
||||
destinations = {}
|
||||
# Where each file goes: its component's folder, or the assembly store for a global assembly.
|
||||
for row in files:
|
||||
comp = row["Component_"]
|
||||
if comp not in self.included_components:
|
||||
@@ -664,16 +644,12 @@ class Installer:
|
||||
folder = self.directory(row["DestFolder"]) if row.get("DestFolder") else self.files[row["File_"]].rsplit("/", 1)[0]
|
||||
name = long_name(row.get("DestName", "")) or self.files[row["File_"]].rsplit("/", 1)[1]
|
||||
source = self.out / self.files[row["File_"]]
|
||||
if folder and source.is_file() and "/" not in name:
|
||||
self.put(source, folder + "/" + name)
|
||||
if folder and source.is_file() and "/" not in name and self.put(source, folder + "/" + name):
|
||||
self.counts["files"] += 1
|
||||
if missing:
|
||||
self.notes.append("%d file(s) were not in the package's cabinets" % missing)
|
||||
|
||||
def value(self, hive, key, name, kind, data, wow64):
|
||||
# A 32-bit component writes through the 32-bit view, as Wine's msi does: HKLM\Software is
|
||||
# Software\Wow6432Node, and the prefix's link keys there (Classes, TypeLib, Fonts...) lead
|
||||
# to the keys both views share - droiddeck-wincomponents follows them when it writes.
|
||||
lower = key.lower()
|
||||
if hive == "HKLM" and wow64 and lower.startswith("software\\") and not lower.startswith("software\\wow6432node\\"):
|
||||
key = "Software\\Wow6432Node\\" + key[len("software\\"):]
|
||||
@@ -782,7 +758,6 @@ class Installer:
|
||||
self.check()
|
||||
if not self.counts["files"] and not self.registry:
|
||||
raise MsiError("the package installs nothing here")
|
||||
# A component made of several packages (32- and 64-bit) gets them all in one registry.json.
|
||||
values = []
|
||||
try:
|
||||
with open(self.out / "registry.json", encoding="utf-8") as source:
|
||||
@@ -796,7 +771,6 @@ class Installer:
|
||||
"counts": self.counts, "notes": self.notes}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- installer wrappers
|
||||
|
||||
def sibling(path, name):
|
||||
"""A file next to [path] called [name], whatever its case; None when there is none."""
|
||||
@@ -974,8 +948,6 @@ def install_wrapper(path, out):
|
||||
try:
|
||||
result = Installer(str(package), out, span=Span(lo, hi)).install()
|
||||
except MsiError as error:
|
||||
# A package with nothing for this prefix (a patch for another Windows) is skipped,
|
||||
# unless it is the only one; anything else is the whole installer's failure.
|
||||
if "installs nothing" in str(error) and len(packages) > 1:
|
||||
total["notes"].append("%s: %s" % (package.name, error))
|
||||
continue
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/usr/bin/python3
|
||||
# Based on WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0.
|
||||
# Steam speaks NetworkManager; Android owns the radios, routes and connection. Export the
|
||||
# app's live snapshot through that API, including nearby Wi-Fi access points. Requests to
|
||||
# scan are handed to Android; Android settings still handle joining networks.
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
@@ -16,7 +12,7 @@ from xml.sax.saxutils import escape
|
||||
import gi
|
||||
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib # noqa: E402
|
||||
from gi.repository import Gio, GLib
|
||||
|
||||
NAME = "org.freedesktop.NetworkManager"
|
||||
ROOT = "/org/freedesktop/NetworkManager"
|
||||
@@ -60,7 +56,6 @@ def v(signature, value):
|
||||
|
||||
|
||||
def read_snapshot():
|
||||
# Atomic replacement by the app means we never see a partially written handover.
|
||||
try:
|
||||
state = json.loads(SNAPSHOT.read_text())
|
||||
if not isinstance(state, dict) or not isinstance(state.get("connected"), bool):
|
||||
@@ -71,7 +66,6 @@ def read_snapshot():
|
||||
|
||||
|
||||
def legacy_snapshot():
|
||||
# Older APKs do not publish transport metadata. Never guess Wi-Fi from an interface name.
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.connect(("192.0.2.1", 9))
|
||||
@@ -101,10 +95,10 @@ def connection_name(state):
|
||||
|
||||
def connectivity(state):
|
||||
if not state["connected"]:
|
||||
return 1 # NONE
|
||||
return 1
|
||||
if state.get("validated"):
|
||||
return 4 # FULL
|
||||
return 2 if state.get("captivePortal") else 3 # PORTAL / LIMITED
|
||||
return 4
|
||||
return 2 if state.get("captivePortal") else 3
|
||||
|
||||
|
||||
def metered(state):
|
||||
@@ -155,7 +149,6 @@ def active_ap(state):
|
||||
|
||||
|
||||
def ap_security(capabilities):
|
||||
# NetworkManager's cipher/key-management flags, from Android's beacon capabilities.
|
||||
wpa = rsn = 0
|
||||
for group in re.findall(r"\[([^]]+)\]", capabilities.upper()):
|
||||
flags = 0
|
||||
@@ -280,7 +273,6 @@ def objects(state):
|
||||
if present:
|
||||
found[path] = {NAME + f".IP{version}Config": ip_config(state, version)}
|
||||
if up and not wifi and state.get("wifiEnabled"):
|
||||
# Android can keep its Wi-Fi radio available while cellular/VPN is the default route.
|
||||
wireless = objects(dict(state, connected=False, transport="none",
|
||||
interface=state.get("wifiInterface", "wlan0"), metered=None))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
@@ -304,13 +296,11 @@ def settings(state):
|
||||
"ssid": v("ay", list((state.get("ssid") or "Wi-Fi").encode("utf-8"))), "mode": v("s", "infrastructure"),
|
||||
}
|
||||
elif state.get("transport") == "cellular":
|
||||
result["gsm"] = {} # Android owns the SIM/APN; no credentials are exported.
|
||||
result["gsm"] = {}
|
||||
return result
|
||||
|
||||
|
||||
def interface_info(interface, values):
|
||||
# Register properties on the actual objects as well as returning ObjectManager snapshots.
|
||||
# Steam/libnm also use Properties.Get/GetAll and introspect the wireless methods.
|
||||
props = "".join(f'<property name="{escape(key)}" type="{value.get_type_string()}" access="read"/>'
|
||||
for key, value in values.items())
|
||||
node = Gio.DBusNodeInfo.new_for_xml(f'<node><interface name="{interface}">{METHODS.get(interface, "")}{props}</interface></node>')
|
||||
@@ -372,7 +362,7 @@ class NetworkManager:
|
||||
def check(self):
|
||||
state = read_snapshot()
|
||||
if state is None:
|
||||
return True # A transient read failure must not replace a known link with Ethernet.
|
||||
return True
|
||||
if state == self.state:
|
||||
return True
|
||||
before, after = self.objects, objects(state)
|
||||
@@ -418,8 +408,7 @@ class NetworkManager:
|
||||
self.bus.emit_signal(None, path, OBJECT_MANAGER, signal, body)
|
||||
|
||||
|
||||
def main():
|
||||
loop = GLib.MainLoop()
|
||||
def own(loop):
|
||||
state = {}
|
||||
|
||||
def acquired(bus, name):
|
||||
@@ -429,7 +418,12 @@ def main():
|
||||
print("== netmanager: the system bus is gone", file=sys.stderr)
|
||||
loop.quit()
|
||||
|
||||
Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lost)
|
||||
return Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lost)
|
||||
|
||||
|
||||
def main():
|
||||
loop = GLib.MainLoop()
|
||||
own(loop)
|
||||
loop.run()
|
||||
|
||||
|
||||
|
||||
@@ -33,9 +33,7 @@ APPIMAGE_RUN = os.path.join(BIN, "droiddeck-appimage-run")
|
||||
SCRIPT_RUN = os.path.join(BIN, "droiddeck-script-run")
|
||||
STEAM_LAUNCH = os.path.join(BIN, "droiddeck-steam-launch")
|
||||
CACHE = os.path.join(HOME, ".cache", "droiddeck")
|
||||
# Where the app adds each kind, and what an added one holds.
|
||||
IMPORTS = {"appimage": ("/opt/appimages/user", "app"), "folder": ("/opt/droiddeck-apps", "entry")}
|
||||
# Android's own folders on shared storage: never copied in whole.
|
||||
SHARED_FOLDERS = ("alarms", "android", "audiobooks", "dcim", "documents", "download", "movies", "music",
|
||||
"notifications", "pictures", "podcasts", "recordings", "ringtones")
|
||||
SCAN_LIMIT = 4000
|
||||
|
||||
@@ -36,7 +36,6 @@ def where(url):
|
||||
|
||||
def main(argv):
|
||||
url = argv[0] if argv else ""
|
||||
# The Steam client's own form (steam://openurl/<address>), in case a launcher passes it on.
|
||||
if url.startswith("steam://openurl/"):
|
||||
url = url[len("steam://openurl/"):]
|
||||
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
#!/usr/bin/python3
|
||||
# Player 1 on the session's controller, for every emulator that would otherwise start on the
|
||||
# keyboard. The session's pad is an Xbox 360 controller (libfakeinput's identity outside Steam) that
|
||||
# SDL maps by itself; what an emulator lacks is a profile that points Player 1 at it. One is
|
||||
# written only where the emulator has none yet - a profile the user made is never touched.
|
||||
# Run at every desktop start and before every program from the rail.
|
||||
import os
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
@@ -21,10 +16,6 @@ def seed(path, text, what, done="Player 1 on the controller"):
|
||||
return True
|
||||
|
||||
|
||||
# RPCS3: its global input configuration (rpcs3::utils::get_input_config_dir() + "Default.yml").
|
||||
# Without one it adds the keyboard pad handler (pad_config.cpp, cfg_input::load). SDL handler
|
||||
# names from rpcs3/Input/sdl_pad_handler.cpp (button_list, init_config); the device is
|
||||
# "<SDL gamepad name> <n>" (sdl_pad_handler::enumerate_devices).
|
||||
RPCS3_PLAYER1 = """Player 1 Input:
|
||||
Handler: SDL
|
||||
Device: Xbox 360 Controller 1
|
||||
@@ -71,13 +62,8 @@ def rpcs3():
|
||||
rpcs3_shader_mode()
|
||||
|
||||
|
||||
# RPCS3's default shader mode (Async Recompiler with Shader Interpreter) builds 6650 interpreter
|
||||
# pipelines at the start of every boot, minutes on an Adreno. The async recompiler compiles only
|
||||
# what a game draws, in the background, once. A new install starts with it (a config.yml that
|
||||
# holds only this is merged over RPCS3's defaults); an existing one still on the default is moved
|
||||
# once, and a marker keeps any later choice the user makes in RPCS3's own settings.
|
||||
RPCS3_INTERPRETER = "Async Recompiler with Shader Interpreter"
|
||||
RPCS3_RECOMPILER = "Async Recompiler (multi-threaded)" # the GUI says "Async Shader Recompiler"; this is the value (system_config_types.cpp)
|
||||
RPCS3_RECOMPILER = "Async Recompiler (multi-threaded)"
|
||||
|
||||
|
||||
def rpcs3_shader_mode():
|
||||
@@ -101,7 +87,6 @@ def rpcs3_shader_mode():
|
||||
open(marker, "w").close()
|
||||
|
||||
|
||||
# ---- ini helpers (DuckStation and PCSX2 share one ini dialect, keys may repeat) -------------
|
||||
|
||||
def ini_section(lines, name):
|
||||
"""(start, end) line indices of [name]'s body, or None."""
|
||||
@@ -132,7 +117,6 @@ def patch_ini_section(path, section, body, what, needle="SDL-", require=None, do
|
||||
return
|
||||
new = body.strip("\n").splitlines()
|
||||
if span:
|
||||
# The controller type the emulator already wrote stays; only bindings are added.
|
||||
have = {l.split("=", 1)[0].strip() for l in lines[span[0]:span[1]] if "=" in l}
|
||||
new = [l for l in new if not (l.split("=", 1)[0].strip() == "Type" and "Type" in have)]
|
||||
end = span[1]
|
||||
@@ -147,8 +131,6 @@ def patch_ini_section(path, section, body, what, needle="SDL-", require=None, do
|
||||
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
|
||||
|
||||
|
||||
# DuckStation: SDL-<n>/<name>, axes signed (src/util/sdl_input_source.cpp); Pad1 keys from
|
||||
# src/core/analog_controller.cpp. Its defaults bind the keyboard only (settings.cpp).
|
||||
DUCKSTATION_PAD1 = """Type = AnalogController
|
||||
Up = SDL-0/DPadUp
|
||||
Down = SDL-0/DPadDown
|
||||
@@ -244,17 +226,12 @@ def bios_folder(base):
|
||||
d = os.path.join(base, "bios")
|
||||
if os.path.isdir(ROMS):
|
||||
try:
|
||||
os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS
|
||||
os.makedirs(d, exist_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return d
|
||||
|
||||
|
||||
# DuckStation (PS1) - set up like ARMSX2: users bring their own BIOS and games, in the ROMs folder.
|
||||
# Front-end runs use -batch -bigpicture -fullscreen, so the guide button is the pause menu
|
||||
# (Hotkeys OpenPauseMenu, src/core/hotkeys.cpp), not the analog toggle. Keys from
|
||||
# src/core/settings.cpp: [BIOS] SearchDirectory, [GPU] Renderer ("Vulkan"), [Main]
|
||||
# SetupWizardIncomplete (src/duckstation-qt/qthost.cpp).
|
||||
DUCKSTATION_PAD1_GUIDE_FREE = "\n".join(l for l in DUCKSTATION_PAD1.splitlines() if not l.startswith("Analog ")) + "\n"
|
||||
|
||||
|
||||
@@ -266,8 +243,6 @@ def duckstation():
|
||||
if not os.path.isfile(ini) and os.path.isfile(legacy):
|
||||
ini = legacy
|
||||
if not os.path.isfile(ini):
|
||||
# A new player: everything DuckStation's first-time setup asks is answered here (it finds
|
||||
# the BIOS in its folder by itself), so a game from the front end boots straight away.
|
||||
bios = bios_folder(ps1)
|
||||
seed(ini, "[Main]\nSetupWizardIncomplete = false\nInhibitScreensaver = false\n\n"
|
||||
f"[BIOS]\nSearchDirectory = {bios}\n\n"
|
||||
@@ -282,17 +257,12 @@ def duckstation():
|
||||
done="the guide button opens the pause menu")
|
||||
patch_ini_section(ini, "GameList", f"RecursivePaths = {ps1}\n", "DuckStation", needle=ROMS,
|
||||
done="games listed from the ROMs folder")
|
||||
# One set up by an earlier build still has its first-time setup pending, in the way of a game.
|
||||
if ini_get(ini, "Main", "SetupWizardIncomplete") == "true":
|
||||
ini_set(ini, "Main", "SetupWizardIncomplete", "false")
|
||||
print("droiddeck-pad-defaults: DuckStation: first-time setup already done here")
|
||||
# Keeping the screen awake goes through org.freedesktop.ScreenSaver, which nothing in the session
|
||||
# provides (Android decides when the screen sleeps): DuckStation only warns it failed, every game.
|
||||
if (ini_get(ini, "Main", "InhibitScreensaver") or "true") == "true":
|
||||
ini_set(ini, "Main", "InhibitScreensaver", "false")
|
||||
print("droiddeck-pad-defaults: DuckStation: no screensaver inhibit (no such service here)")
|
||||
# Once, for a DuckStation set up before this: its own empty BIOS folder moves to the ROMs folder,
|
||||
# and Automatic becomes Vulkan. A later choice in DuckStation's settings is kept.
|
||||
marker = os.path.join(os.path.dirname(ini), ".droiddeck-setup")
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
@@ -307,8 +277,6 @@ def duckstation():
|
||||
open(marker, "w").close()
|
||||
|
||||
|
||||
# PCSX2: FaceSouth/... names (pcsx2/Input/SDLInputSource.cpp), keys from SIO/Pad/PadDualshock2.cpp.
|
||||
# An ini without [UI] SettingsVersion is thrown away and rebuilt, so only a complete one is patched.
|
||||
PCSX2_PAD1 = """Type = DualShock2
|
||||
Up = SDL-0/DPadUp
|
||||
Right = SDL-0/DPadRight
|
||||
@@ -346,8 +314,6 @@ def pcsx2():
|
||||
|
||||
|
||||
|
||||
# Dolphin: SDL/<id>/<SDL gamepad name>; control names from InputCommon/.../SDL/SDLGamepad.h (Left Y+
|
||||
# is up). A section that exists is taken whole - keys it lacks are unbound - so both are complete.
|
||||
DOLPHIN_GC = """[GCPad1]
|
||||
Device = SDL/0/Xbox 360 Controller
|
||||
Buttons/A = `Button S`
|
||||
@@ -406,11 +372,6 @@ Nunchuk/Stick/Right = `Left X+`
|
||||
"""
|
||||
|
||||
|
||||
# ARMSX2 - the PS2 emulator (PCSX2 with ARM64 recompilers; upstream PCSX2 interprets on ARM64). Its
|
||||
# files are PCSX2's under $XDG_CONFIG_HOME/ARMSX2 (pcsx2/Pcsx2Config.cpp). The user supplies the BIOS
|
||||
# and the games; they live in the ROMs folder (/root/ROMs). The guide button opens the pause menu
|
||||
# (Hotkeys OpenPauseMenu) - the way out of a game started from the front end, which runs ARMSX2
|
||||
# without its window (-batch -bigpicture) - so it is not also the analog toggle here.
|
||||
ARMSX2_PAD1 = "\n".join(l for l in PCSX2_PAD1.splitlines() if not l.startswith("Analog ")) + "\n"
|
||||
ROMS = "/root/ROMs"
|
||||
|
||||
@@ -432,7 +393,7 @@ def ps2_bios_folder():
|
||||
d = os.path.join(base, "bios")
|
||||
if os.path.isdir(ROMS):
|
||||
try:
|
||||
os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS
|
||||
os.makedirs(d, exist_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return d
|
||||
@@ -443,8 +404,6 @@ def armsx2():
|
||||
ini = os.path.join(root, "inis/PCSX2.ini")
|
||||
old = os.path.join(CONFIG, "PCSX2")
|
||||
if not os.path.isfile(ini) and os.path.isfile(os.path.join(old, "inis/PCSX2.ini")):
|
||||
# Someone who played on PCSX2 here: the same settings, BIOS choice and memory cards (the
|
||||
# saves), copied once. PCSX2's own folder is left as it was.
|
||||
import shutil
|
||||
for sub in ("inis", "memcards", "bios", "gamesettings", "cheats", "patches", "covers",
|
||||
"inputprofiles", "textures"):
|
||||
@@ -453,22 +412,16 @@ def armsx2():
|
||||
shutil.copytree(src, os.path.join(root, sub), dirs_exist_ok=True)
|
||||
print(f"droiddeck-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})")
|
||||
elif not os.path.isfile(ini):
|
||||
# A new player: everything ARMSX2's first-time setup asks is answered here - the BIOS
|
||||
# folder in the ROMs folder, the ps2 folder as its game list, the controller on Player 1 -
|
||||
# and the BIOS file itself is picked below once one is there.
|
||||
bios, games = ps2_bios_folder(), ps2_folder()
|
||||
seed(ini, "[UI]\nSettingsVersion = 1\nSetupWizardIncomplete = false\n\n"
|
||||
f"[Folders]\nBios = {bios}\n\n"
|
||||
f"[GameList]\nRecursivePaths = {games}\n\n"
|
||||
# Vulkan outright rather than Auto's pick: the renderer every other path here uses.
|
||||
"[EmuCore/GS]\nRenderer = 14\n\n"
|
||||
"[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n"
|
||||
"[Pad1]\n" + ARMSX2_PAD1, "ARMSX2", "first-time setup, BIOS from " + bios)
|
||||
armsx2_bios(ini)
|
||||
return
|
||||
patch_ini_section(ini, "Pad1", ARMSX2_PAD1, "ARMSX2", require="SettingsVersion")
|
||||
# The guide button is the pause menu here; PCSX2's profile (ours, copied over) had it as the
|
||||
# analog toggle as well.
|
||||
with open(ini, encoding="utf-8", errors="replace") as f:
|
||||
lines = f.read().splitlines()
|
||||
kept = [l for l in lines if l.replace(" ", "") != "Analog=SDL-0/Guide"]
|
||||
@@ -497,7 +450,6 @@ def armsx2_bios(ini):
|
||||
if current and os.path.isfile(os.path.join(folder, current)):
|
||||
return
|
||||
try:
|
||||
# A PS2 BIOS dump is 4 MiB (a few are 8); the .nvm/.mec files beside it are not dumps.
|
||||
dumps = sorted(f for f in os.listdir(folder)
|
||||
if os.path.isfile(os.path.join(folder, f)) and 4 << 20 <= os.path.getsize(os.path.join(folder, f)) <= 8 << 20)
|
||||
except OSError:
|
||||
@@ -510,12 +462,6 @@ def armsx2_bios(ini):
|
||||
print(f"droiddeck-pad-defaults: ARMSX2: BIOS {pick}")
|
||||
|
||||
|
||||
# Dolphin (PC) has no controller menu, so the guide button is its Toggle Fullscreen hotkey: out of full
|
||||
# screen is Dolphin's own window with its Config / Graphics / Stop buttons. Hotkeys.ini is all-or-
|
||||
# nothing - a file with one line drops every other default - so a new one carries Dolphin's defaults,
|
||||
# generated from HotkeyManager.cpp's LoadDefaults (Linux branch, RetroAchievements on) plus the guide;
|
||||
# an existing one only gets the guide added to its Toggle Fullscreen. The Wii remote's Home, which
|
||||
# was on the guide button, is on the right shoulder button instead.
|
||||
DOLPHIN_GUIDE = "`SDL/0/Xbox 360 Controller:Guide`"
|
||||
DOLPHIN_HOTKEYS = """[Hotkeys]
|
||||
Device = XInput2/0/Virtual core pointer
|
||||
@@ -632,11 +578,6 @@ def dolphin():
|
||||
ini_set(hotkeys, "Hotkeys", "General/Toggle Fullscreen",
|
||||
(current + " | " if current else "") + DOLPHIN_GUIDE)
|
||||
print("droiddeck-pad-defaults: Dolphin: the guide button shows Dolphin's window (Toggle Fullscreen)")
|
||||
# Games from the ROMs folder's gamecube and wii folders, subfolders included; Vulkan; no
|
||||
# NKit warning (it will not let a game start until a box is ticked - games run either way,
|
||||
# the warning is about loading times, netplay and save states); no statistics question.
|
||||
# Names from Dolphin's MainSettings.cpp / UISettings.cpp. Only what is not set yet is added,
|
||||
# except the game folders, which are added to whatever the user has.
|
||||
ini = os.path.join(d, "Dolphin.ini")
|
||||
gc = system_folder(("gamecube", "gc", "ngc"), "gamecube")
|
||||
wii = system_folder(("wii",), "wii")
|
||||
@@ -655,9 +596,6 @@ def dolphin():
|
||||
count = 0
|
||||
paths = [ini_get(ini, "General", "ISOPath%d" % i) for i in range(count)]
|
||||
changed = []
|
||||
# The whole ROMs folder as a game folder (what Dolphin's "set a games directory" was pointed at
|
||||
# before) would, searched with its subfolders, have Dolphin open every PS2 and PS3 image too;
|
||||
# the system folders below cover it.
|
||||
if any((p or "").rstrip("/") == ROMS for p in paths):
|
||||
paths = [p for p in paths if p and p.rstrip("/") != ROMS]
|
||||
for i, p in enumerate(paths):
|
||||
@@ -680,7 +618,6 @@ def dolphin():
|
||||
changed.append("subfolders")
|
||||
if changed:
|
||||
print("droiddeck-pad-defaults: Dolphin: games from " + ", ".join(changed))
|
||||
# Once, for a Dolphin set up before this: Vulkan unless it was chosen already, and the NKit box.
|
||||
marker = os.path.join(d, ".droiddeck-setup")
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
@@ -694,10 +631,6 @@ def dolphin():
|
||||
print("droiddeck-pad-defaults: Dolphin: Vulkan, no NKit warning")
|
||||
|
||||
|
||||
# Cemu: an SDLController profile for the GamePad. The uuid is "<index>_<SDL GUID>" and SDL's GUID
|
||||
# carries a CRC of the device name; this is the one SDL reports for the session's pad
|
||||
# ("Xbox 360 Controller (0)", 045e:028e - read from RPCS3's SDL log on the device). Mapping ids
|
||||
# from VPADController.h, values from Controller.h, Cemu's own SDL default layout plus Home.
|
||||
CEMU_MAP = [(1, 1), (2, 0), (3, 3), (4, 2), (5, 9), (6, 10), (7, 42), (8, 43), (9, 6), (10, 4),
|
||||
(11, 11), (12, 12), (13, 13), (14, 14), (15, 7), (16, 8), (17, 45), (18, 39), (19, 44),
|
||||
(20, 38), (21, 47), (22, 41), (23, 46), (24, 40), (27, 5)]
|
||||
@@ -717,11 +650,6 @@ CEMU_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
"""
|
||||
|
||||
|
||||
# Cemu's settings, so its Getting Started dialog (shown while settings.xml is missing, and whose
|
||||
# folder picker cannot reach ROMs) never blocks a launch: the Wii U games folder, Vulkan
|
||||
# (Graphic api 1), and audio through Cubeb (the only backend on Linux; api 3) on the default
|
||||
# device for both the TV and the GamePad speaker - some titles play everything through the
|
||||
# GamePad - at full volume (Cemu's own default is 20 %). Keys from config/CemuConfig.cpp.
|
||||
CEMU_SETTINGS = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<content>
|
||||
<mlc_path></mlc_path>
|
||||
@@ -749,11 +677,6 @@ def cemu():
|
||||
done=f"games in {games}, Vulkan, Cubeb audio on the default device")
|
||||
|
||||
|
||||
# melonDS 1.x: raw SDL joystick indices. The session's pad has the kernel's Xbox 360 layout
|
||||
# (buttons A B X Y LB RB Back Start Guide LS RS = 0..10, hat 0 for the d-pad); the d-pad values
|
||||
# also take the left stick (EmuInstanceInput.cpp; encoding InputConfig/MapButton.h). The guide
|
||||
# button toggles full screen (HK_FullscreenToggle), as it does in Dolphin: the front end starts
|
||||
# melonDS full screen (-f), and leaving it shows the window's menus for settings.
|
||||
MELONDS_GUIDE = 8
|
||||
MELONDS_JOY = f"""[Instance0.Joystick]
|
||||
A = 1
|
||||
@@ -771,28 +694,15 @@ Right = 65794
|
||||
HK_FullscreenToggle = {MELONDS_GUIDE}
|
||||
"""
|
||||
|
||||
# The screen a handheld's wide panel suits best: the top screen as big as the panel's height allows
|
||||
# with the bottom screen alone beside it, centred (ScreenLayout.h: Horizontal = 2, EmphTop = 1;
|
||||
# melonDS's Hybrid shows the big screen a second time, small, above the bottom one; nobody needs
|
||||
# it twice). Sharp pixels: no filtering, and no integer steps that leave the panel half used. Keys as
|
||||
# melonDS writes them (Window.cpp windowCfg).
|
||||
MELONDS_WINDOW = """[Instance0.Window0]
|
||||
ScreenLayout = 2
|
||||
ScreenSizing = 1
|
||||
IntegerScaling = false
|
||||
ScreenFilter = false
|
||||
"""
|
||||
# melonDS's own defaults for those, which an existing install is moved off once. Hybrid (3) was
|
||||
# this preset's first layout, and moves on too.
|
||||
MELONDS_WINDOW_DEFAULTS = {"ScreenLayout": ("0", "3"), "ScreenSizing": ("0",), "ScreenFilter": ("true",)}
|
||||
|
||||
|
||||
# The window melonDS returns to when the guide button leaves full screen: 1x wide (the width of
|
||||
# two DS screens side by side, Screen.cpp screenGetMinSize) and 16:9, so gamescope stretches it to
|
||||
# fill the panel and the menu bar and cursor come out large enough to use. A bigger window keeps
|
||||
# its menus at their real size, tiny on a handheld. Qt's saveGeometry() v3 blob: magic, version,
|
||||
# frame and normal rects (x, y, right, bottom), screen, maximized, full screen, screen width, and
|
||||
# the normal rect again (QWidget::restoreGeometry).
|
||||
def melonds_geometry():
|
||||
import base64, struct
|
||||
w, h = 512, 288
|
||||
@@ -845,11 +755,6 @@ def toml_str(path):
|
||||
return '"' + path.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
# The user's own BIOS, firmware and DSi NAND, found in the ROMs folder's nds/bios (or firmware)
|
||||
# folder by what each file is: the DS BIOSes by size and checksum (the GBA BIOS is also 16 KB),
|
||||
# firmware and NAND by size, the DSi boot ROMs (both 64 KB) by the 7 or 9 in their names. A path
|
||||
# is only filled where melonDS has none, and external files are only switched on when a whole set
|
||||
# was found - without them melonDS runs DS games on its built-in free BIOS.
|
||||
DS_BIOS7_MD5 = "df692a80a5b1bc90728bc3dfc76cd948"
|
||||
DS_BIOS9_MD5 = "a392174eb3e572fed6447e956bde4b25"
|
||||
|
||||
@@ -924,7 +829,6 @@ def melonds():
|
||||
lines = text.splitlines()
|
||||
done = []
|
||||
if not any(isinstance(v, int) and v != -1 and k != "HK_FullscreenToggle" for k, v in joy.items()):
|
||||
# Replace melonDS's own all-unbound table with ours (a TOML table can be defined only once).
|
||||
out, skipping = [], False
|
||||
for line in lines:
|
||||
t = line.strip()
|
||||
@@ -937,8 +841,6 @@ def melonds():
|
||||
elif joy.get("HK_FullscreenToggle", -1) == -1 and MELONDS_GUIDE not in joy.values():
|
||||
toml_set(lines, "Instance0.Joystick", "HK_FullscreenToggle", str(MELONDS_GUIDE))
|
||||
done.append("guide button toggles full screen")
|
||||
# Once, for a melonDS set up before this: the big top screen, where it is still on its own
|
||||
# defaults. The marker keeps whatever the user picks in melonDS's View menu afterwards.
|
||||
if not os.path.exists(marker):
|
||||
for l in MELONDS_WINDOW.splitlines()[1:]:
|
||||
k, v = (x.strip() for x in l.split("=", 1))
|
||||
@@ -957,9 +859,6 @@ def melonds():
|
||||
print(f"droiddeck-pad-defaults: melonDS: {'; '.join(done)} ({path})")
|
||||
|
||||
|
||||
# PPSSPP (SDL): its pad defaults leave the shoulders, the right stick and the triggers unbound on
|
||||
# SDL builds (SDLJoystick.cpp codes vs KeyMapDefaults.cpp); a [ControlMapping] that exists replaces
|
||||
# every default, so this one is complete, keyboard included (device 1 keyboard, 10 pad).
|
||||
PPSSPP_CONTROLS = """[ControlMapping]
|
||||
Up = 1-19,10-19
|
||||
Down = 1-20,10-20
|
||||
@@ -989,8 +888,6 @@ def ppsspp():
|
||||
seed(os.path.join(CONFIG, "ppsspp/PSP/SYSTEM/controls.ini"), PPSSPP_CONTROLS, "PPSSPP")
|
||||
|
||||
|
||||
# RetroArch: the udev joypad driver finds nothing here (no udev database in the runtime); sdl2
|
||||
# does, and matches this profile by vendor/product (task_autodetect.c).
|
||||
RETROARCH_PROFILE = """input_driver = "sdl2"
|
||||
input_device = "Xbox 360 Controller"
|
||||
input_vendor_id = "1118"
|
||||
@@ -1044,11 +941,6 @@ def retroarch():
|
||||
print(f"droiddeck-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})")
|
||||
|
||||
|
||||
# yuzu and its forks: Player 1 in [Controls] of <name>/qt-config.ini, which each writes at its first
|
||||
# start with the keyboard bound. Bindings are input_common ParamPackages, laid out by position as the
|
||||
# frontend's own auto-map does (sdl_driver.cpp GetDefaultButtonBinding); the guid is SDL's with the
|
||||
# name CRC cleared (GetGUID). A key is only read while its \default is false. Done once per emulator,
|
||||
# and only while Player 1 is still on the keyboard.
|
||||
SWITCH_PAD = "engine:sdl,port:0,guid:030000005e0400008e02000010010000,"
|
||||
SWITCH_PLAYER1 = {
|
||||
"button_a": "button:1", "button_b": "button:0", "button_x": "button:3", "button_y": "button:2",
|
||||
|
||||
@@ -1,23 +1,4 @@
|
||||
#!/usr/bin/python3
|
||||
# Installs a third-party Proton build into the client's compatibilitytools.d, so it appears in the
|
||||
# Compatibility dropdown beside our own Proton ARM64 and can be picked per game.
|
||||
#
|
||||
# droiddeck-proton-extra <steam root> ge [--tag GE-Proton11-7]
|
||||
# droiddeck-proton-extra <steam root> cachyos [--tag cachyos-11.0-20260703-slr]
|
||||
# droiddeck-proton-extra <steam root> <url of an aarch64 tarball>
|
||||
# droiddeck-proton-extra <steam root> /path/to/an/aarch64/tarball
|
||||
# droiddeck-proton-extra <steam root> --list what is installed now
|
||||
#
|
||||
# Both projects publish native ARM64 builds - GloriousEggroll as "*-aarch64.tar.gz", CachyOS as
|
||||
# "*-arm64.tar.xz" - and both are ordinary Proton trees: a python entry point beside a files/
|
||||
# directory holding Wine, DXVK and VKD3D. That is the same shape as the depot the Steam client
|
||||
# downloads, so the runtime can run them the same way.
|
||||
#
|
||||
# What it cannot use is their toolmanifest. Like Valve's ARM64 depot they declare
|
||||
# require_tool_appid, which makes Steam stack pressure-vessel underneath - and pressure-vessel
|
||||
# needs unprivileged user namespaces, which an Android app does not get. Patching that out is
|
||||
# steam-compatibility's job (adopt_extras); this script only puts the tree in place and then
|
||||
# calls it, so an install is usable without restarting the client.
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -29,16 +10,12 @@ import urllib.error
|
||||
import urllib.request
|
||||
|
||||
RELEASES = "https://api.github.com/repos/%s/releases"
|
||||
# Each source: the GitHub repo, and how its ARM64 asset is named. Ordered newest-release-first by
|
||||
# the API, so "latest usable" is the first release that actually carries an ARM64 asset - the
|
||||
# projects do not build one for every tag.
|
||||
SOURCES = {
|
||||
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
|
||||
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
}
|
||||
USER_AGENT = "droiddeck-proton-extra"
|
||||
# Room for the tarball and the tree it unpacks to. GE-Proton's aarch64 build is ~650 MB packed and
|
||||
# unpacks to about three times that; refusing early beats a half-written tool directory.
|
||||
NEED_BYTES = 4 * 1024 * 1024 * 1024
|
||||
|
||||
|
||||
@@ -54,10 +31,10 @@ def fetch_json(url):
|
||||
|
||||
|
||||
def pick_asset(source):
|
||||
"""(release tag, asset url, sha512 url or None) for the newest release with an ARM64 build."""
|
||||
"""(release tag, asset url, sha512 url or None) for the newest full release with an ARM64 build."""
|
||||
repo, pattern = SOURCES[source]
|
||||
for release in fetch_json(RELEASES % repo + "?per_page=15"):
|
||||
if release.get("draft"):
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
continue
|
||||
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
|
||||
for name in sorted(assets):
|
||||
@@ -119,8 +96,6 @@ def extract(tarball, into):
|
||||
rc = subprocess.call(["tar", "-xf", tarball, "-C", into])
|
||||
if rc != 0:
|
||||
raise SystemExit("droiddeck-proton-extra: tar failed (%d)" % rc)
|
||||
# A Proton tarball holds one top-level directory. Take whichever entry has the entry point so a
|
||||
# stray ._ file or a nested layout does not decide it.
|
||||
entries = [e for e in sorted(os.listdir(into)) if not e.startswith(".")]
|
||||
for entry in entries:
|
||||
path = os.path.join(into, entry)
|
||||
@@ -144,7 +119,7 @@ def installed(tools):
|
||||
def main():
|
||||
argv = sys.argv[1:]
|
||||
if not argv:
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|<url>")
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|droiddeck|<url>")
|
||||
steam_root = argv.pop(0)
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
os.makedirs(tools, exist_ok=True)
|
||||
@@ -160,9 +135,6 @@ def main():
|
||||
argv.pop(0)
|
||||
tag = argv.pop(0) if argv else None
|
||||
|
||||
# A tarball already on the device is used as it is: a session that has to pull 650 MB down
|
||||
# first shows nothing on screen for ten minutes, so the download can be done ahead of time and
|
||||
# handed over by path.
|
||||
local = None
|
||||
if what in SOURCES:
|
||||
tag, url, sums = release_asset(what, tag) if tag else pick_asset(what)
|
||||
@@ -176,7 +148,7 @@ def main():
|
||||
log("using %s" % what)
|
||||
else:
|
||||
raise SystemExit(
|
||||
"droiddeck-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
|
||||
"droiddeck-proton-extra: expected ge, cachyos, droiddeck, a URL or a tarball path, got %r" % what)
|
||||
|
||||
free = shutil.disk_usage(tools).free
|
||||
if free < NEED_BYTES:
|
||||
@@ -198,8 +170,6 @@ def main():
|
||||
tree = extract(tarball, unpacked)
|
||||
name = os.path.basename(tree)
|
||||
final = os.path.join(tools, name)
|
||||
# Replaced rather than merged: a half-written tree from an interrupted run would otherwise
|
||||
# leave stale files behind that Proton would load.
|
||||
if os.path.exists(final):
|
||||
shutil.rmtree(final, ignore_errors=True)
|
||||
os.rename(tree, final)
|
||||
@@ -209,8 +179,6 @@ def main():
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
log("installed %s" % name)
|
||||
|
||||
# Patches out require_tool_appid and wraps the entry point, which is what makes it launchable
|
||||
# here. Doing it now means the client picks the tool up on its next restart with no extra step.
|
||||
subprocess.call(["steam-compatibility", steam_root])
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"""Runs a Windows program with the Proton the Steam client has chosen for it.
|
||||
|
||||
droiddeck-proton-run [--window] PROGRAM [ARGS...]
|
||||
droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]]
|
||||
|
||||
The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it
|
||||
sits in one's drive_c, or to a non-Steam shortcut that names it; any other program gets a prefix of
|
||||
@@ -10,11 +11,15 @@ config.vdf picks the tool, else the client's default for all other titles ("0").
|
||||
started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and
|
||||
the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio.
|
||||
--window keeps the program in the desktop's own window, drawn with WineD3D.
|
||||
--app starts one game without the Steam client (its Start without Steam): a Steam game's default
|
||||
Windows launch option from appinfo.vdf when no program is given, else the program in that
|
||||
shortcut's own prefix, started in --dir with the shortcut's launch options (--options).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import shlex
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
@@ -249,6 +254,81 @@ def locate(program, root):
|
||||
os.path.dirname(program), root, "own")
|
||||
|
||||
|
||||
def split_words(text):
|
||||
try:
|
||||
return shlex.split(text or "")
|
||||
except ValueError:
|
||||
return (text or "").split()
|
||||
|
||||
|
||||
def split_options(text):
|
||||
"""A shortcut's launch options: NAME=value words before %command% go to the environment, the words
|
||||
after it - or all of them, without %command% - are the program's arguments."""
|
||||
words = split_words(text)
|
||||
if "%command%" not in words:
|
||||
return {}, words
|
||||
at = words.index("%command%")
|
||||
env = {}
|
||||
for word in words[:at]:
|
||||
name, equals, value = word.partition("=")
|
||||
if equals and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
|
||||
env[name] = value
|
||||
return env, words[at + 1:]
|
||||
|
||||
|
||||
def find_file(base, relative):
|
||||
"""base/relative, matching each part without regard to case as Windows does."""
|
||||
path = base
|
||||
for part in [p for p in relative.replace("\\", "/").split("/") if p and p != "."]:
|
||||
exact = os.path.join(path, part)
|
||||
if part == ".." or os.path.exists(exact):
|
||||
path = exact
|
||||
continue
|
||||
try:
|
||||
match = next((name for name in sorted(os.listdir(path)) if name.lower() == part.lower()), None)
|
||||
except OSError:
|
||||
return None
|
||||
if match is None:
|
||||
return None
|
||||
path = os.path.join(path, match)
|
||||
return os.path.normpath(path)
|
||||
|
||||
|
||||
def steam_install(appid, root):
|
||||
for library in libraries(root):
|
||||
found = re.search(r'"installdir"\s+"([^"]+)"',
|
||||
read_text(os.path.join(library, "steamapps", "appmanifest_%s.acf" % appid)) or "")
|
||||
if found:
|
||||
return library, os.path.join(library, "steamapps", "common", found.group(1))
|
||||
return None, None
|
||||
|
||||
|
||||
def steam_launch(appid, root):
|
||||
"""(target, program, arguments) for a Steam game's default Windows launch option, or None."""
|
||||
library, install = steam_install(appid, root)
|
||||
if not install or not os.path.isdir(install):
|
||||
return None
|
||||
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf")).get(str(appid), {})
|
||||
options = [option for option in entry.get("launch_options", ())
|
||||
if not option["betakey"] and (not option["oslist"] or "windows" in option["oslist"])]
|
||||
options.sort(key=lambda option: (option["type"] not in ("", "default", "none"),
|
||||
int(option["key"]) if option["key"].isdigit() else 0))
|
||||
for option in options:
|
||||
program = find_file(install, option["executable"])
|
||||
if not program or not os.path.isfile(program):
|
||||
continue
|
||||
start = find_file(install, option["workingdir"]) if option["workingdir"] else None
|
||||
target = Target(appid, os.path.join(library, "steamapps", "compatdata", str(appid)), install, library, "steam",
|
||||
start if start and os.path.isdir(start) else os.path.dirname(program))
|
||||
return target, program, split_words(option["arguments"])
|
||||
return None
|
||||
|
||||
|
||||
def shortcut_target(appid, program, start, root):
|
||||
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root,
|
||||
"shortcut", start if start and os.path.isdir(start) else None)
|
||||
|
||||
|
||||
def steam_launches(target, program, root):
|
||||
"""Whether a launch option of the Steam game starts [program]: then Steam should start it."""
|
||||
if target.kind != "steam":
|
||||
@@ -292,24 +372,52 @@ def arguments(program, args):
|
||||
|
||||
def main(argv):
|
||||
window = False
|
||||
app, start, options = None, None, ""
|
||||
while argv and argv[0].startswith("--"):
|
||||
option = argv.pop(0)
|
||||
if option == "--window":
|
||||
window = True
|
||||
elif option in ("--app", "--dir", "--options") and argv:
|
||||
value = argv.pop(0)
|
||||
if option == "--app":
|
||||
app = value
|
||||
elif option == "--dir":
|
||||
start = value
|
||||
else:
|
||||
options = value
|
||||
elif option == "--":
|
||||
break
|
||||
else:
|
||||
say("unknown option %s" % option)
|
||||
return 2
|
||||
if not argv:
|
||||
if app is not None and not (app.isdigit() and 0 < int(app) < 2 ** 32):
|
||||
say("%s is not an app id" % app)
|
||||
return 2
|
||||
if not argv and app is None:
|
||||
say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]")
|
||||
return 2
|
||||
program = os.path.abspath(argv[0])
|
||||
if not os.path.isfile(program):
|
||||
say("%s does not exist" % program)
|
||||
return 2
|
||||
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
|
||||
target = locate(program, root)
|
||||
extra, args = split_options(options)
|
||||
if not argv:
|
||||
if int(app) >= STEAM_APP_LIMIT:
|
||||
say("shortcut %s needs its program" % app)
|
||||
return 2
|
||||
found = steam_launch(app, root)
|
||||
if found is None:
|
||||
say("Steam game %s is not installed, or has no Windows launch option" % app)
|
||||
return 2
|
||||
target, program, own = found
|
||||
args = own + args
|
||||
else:
|
||||
program = os.path.abspath(argv[0])
|
||||
if not os.path.isfile(program):
|
||||
say("%s does not exist" % program)
|
||||
return 2
|
||||
args = args + argv[1:]
|
||||
if app is not None and int(app) >= STEAM_APP_LIMIT:
|
||||
target = shortcut_target(app, program, start, root)
|
||||
else:
|
||||
target = locate(program, root)
|
||||
available = tools(root)
|
||||
name, why = choose_tool(target.appid, mapping(root), available)
|
||||
if name is None:
|
||||
@@ -318,13 +426,15 @@ def main(argv):
|
||||
folder, command = available[name]
|
||||
os.makedirs(target.compatdata, exist_ok=True)
|
||||
env = environment(os.environ, target, folder, root, window)
|
||||
say("%s with %s (%s), %s prefix %s" % (program, name, why, target.kind, target.compatdata))
|
||||
env.update(extra)
|
||||
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
|
||||
", without the Steam client" if app is not None else ""))
|
||||
try:
|
||||
os.chdir(target.start)
|
||||
except OSError:
|
||||
os.chdir(os.path.dirname(program))
|
||||
entry = os.path.join(folder, command)
|
||||
os.execve(entry, [entry, VERB] + arguments(program, argv[1:]), env)
|
||||
os.execve(entry, [entry, VERB] + arguments(program, args), env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
#!/bin/bash
|
||||
# A script added on the Desktop page (UserApps), run from its own folder:
|
||||
# droiddeck-script-run /opt/droiddeck-apps/<id> [args...]
|
||||
set -u
|
||||
dir=${1:?usage: droiddeck-script-run <added app directory> [args...]}
|
||||
shift
|
||||
entry=$(cat "$dir/entry" 2>/dev/null) || { echo "droiddeck-script-run: $dir has no entry" >&2; exit 127; }
|
||||
cd -P "$dir/files" 2>/dev/null || { echo "droiddeck-script-run: $dir/files is missing; add the script again" >&2; exit 127; }
|
||||
folder=$PWD
|
||||
# Shared storage is noexec, so the script is handed to its interpreter rather than executed.
|
||||
first=
|
||||
IFS= read -r first < "$entry"
|
||||
first=${first%$'\r'}
|
||||
interp=(/bin/bash)
|
||||
# A program as the entry (the desktop's copy of a game's folder) runs itself.
|
||||
case $first in '#!'*) read -r -a interp <<< "${first#'#!'}" ;; $'\x7f'ELF*) interp=() ;; esac
|
||||
fex=$(cat "$dir/fex" 2>/dev/null)
|
||||
case $fex in on|off) ;; *) fex=auto ;; esac
|
||||
@@ -31,7 +27,6 @@ case ${DBUS_SESSION_BUS_ADDRESS:-} in
|
||||
fi ;;
|
||||
esac
|
||||
rc=$?
|
||||
# A launcher script often starts the game and returns; the session lasts while it runs.
|
||||
running() {
|
||||
local p exe arg cwd
|
||||
for p in /proc/[0-9]*; do
|
||||
|
||||
@@ -1,43 +1,16 @@
|
||||
#!/bin/bash
|
||||
# Marks Steam's shared redistributables as already run in every Proton prefix, and in the
|
||||
# template Proton makes new prefixes from.
|
||||
#
|
||||
# A game whose depot lists _CommonRedist makes the client run the real installer inside the
|
||||
# prefix on first launch. Those are x86 bundles, so they run under FEX, and the 2019 one leaves
|
||||
# a task behind every time: its main thread exits while a helper stays blocked reading a pipe it
|
||||
# also holds the write end of, so the process never reaps and the client keeps waiting on it.
|
||||
#
|
||||
# The client skips a "Run Process" block whose HasRunKey is already set, which is the same escape
|
||||
# WineUtils.seedVcRedistRegistryIfDllsPresent() takes for the app's own containers. The names and
|
||||
# versions come out of the install scripts rather than a list kept here, because Valve revises
|
||||
# them; a prefix already carrying the same set is left alone.
|
||||
#
|
||||
# Games also carry install scripts of their own (<game>/_CommonRedist/vcredist/2022/installscript.vdf
|
||||
# and the like), often with another version in the value name; those are read too. And the VC++
|
||||
# 2015-2022 runtime is recorded as installed the way Microsoft's installers look for it: on ARM64
|
||||
# Proton the x64 bundle otherwise stops with "Microsoft Visual C++ 2015-2022 Redistributable (arm64)
|
||||
# is required", while Proton's own msvcp140/vcruntime140 already serve the game.
|
||||
#
|
||||
# A Vulkan runtime installer is the one left to run. Proton has no stand-in for it: for a game whose
|
||||
# Steam compat config says nativevulkanloader (Red Dead Redemption 2) it loads vulkan-1.dll native
|
||||
# only, and Khronos' loader is in the prefix only once that installer has run - without it the game
|
||||
# exits with STATUS_DLL_NOT_FOUND before it opens a window. The installer finishes in a second.
|
||||
set -u
|
||||
steam_root=${1:?steam root}
|
||||
LIBRARIES=${DROIDDECK_LIBRARIES-/mnt/droiddeck /mnt/droiddeck-sd}
|
||||
|
||||
redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
|
||||
|
||||
# Every process an install script would run, as the registry key and value the client writes once
|
||||
# it has run it. Names sit one level inside "Run Process", the key they share a level further in.
|
||||
# "read_scripts vulkan" lists only the Vulkan runtime installers, which the plain call leaves out.
|
||||
read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
|
||||
# A block whose HasRunKey is set is one process; its name is the key the block opened under, at
|
||||
# whatever depth - an install script nests it under "Run Process", the client'"'"'s evaluator script
|
||||
# for a game wraps the same blocks once more.
|
||||
FNR == 1 { depth = 0; pending = "" }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; pending = ""; next }
|
||||
FNR == 1 { depth = 0; pending = ""; appid = "" }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; proc[depth] = 0; pending = ""; next }
|
||||
/^[[:space:]]*\}/ {
|
||||
if (depth > 0 && key[depth] == "" && proc[depth] && appid != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
|
||||
printf "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\%s\t%s\n", appid, name[depth]
|
||||
if (depth > 0 && key[depth] != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
|
||||
printf "%s\t%s\n", key[depth], name[depth]
|
||||
if (depth > 0) depth--
|
||||
@@ -45,8 +18,10 @@ read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
|
||||
}
|
||||
{
|
||||
n = split($0, part, "\"")
|
||||
if (n >= 5 && tolower(part[2]) == "appid" && part[4] ~ /^[0-9]+$/) { appid = part[4]; next }
|
||||
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key[depth] = part[4]; next }
|
||||
if (n >= 5 && tolower(part[2]) ~ /^process [0-9]+$/) {
|
||||
proc[depth] = 1
|
||||
program = tolower(part[4])
|
||||
sub(/.*[\\\/]/, "", program)
|
||||
if (program ~ /vulkan/) vulkan[depth] = 1
|
||||
@@ -56,8 +31,6 @@ read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
|
||||
}
|
||||
'; }
|
||||
pairs=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | read_scripts)
|
||||
# The client downloads the scripts with the first game that wants them, which is too late for that
|
||||
# game; until then the set they held when this was written stands in. (WinNative's list.)
|
||||
[ -n "$pairs" ] || pairs=$(sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' <<'KNOWN'
|
||||
DirectX\\Jun2010 dxsetup
|
||||
.NET\\4.8 4.8
|
||||
@@ -78,8 +51,6 @@ vcredist\\2022 x64 14.51.36247.0
|
||||
KNOWN
|
||||
)
|
||||
|
||||
# The games' own scripts. Finding them walks every game folder, so the list is kept until a game is
|
||||
# installed, updated or removed (its appmanifest changes) - this runs every quarter minute.
|
||||
cache="$steam_root/.droiddeck-game-scripts"
|
||||
libraries="$steam_root"
|
||||
for library in $LIBRARIES; do libraries="$libraries
|
||||
@@ -96,21 +67,14 @@ if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then
|
||||
done <<<"$libraries" | sort -u
|
||||
} >"$cache.tmp" && mv -f "$cache.tmp" "$cache"
|
||||
fi
|
||||
# DROIDDECK_SEED_SCRIPTS: more scripts, one path a line - droiddeck-game-env passes the client's
|
||||
# evaluator script for the game about to run its installers, read before the client looks.
|
||||
game_scripts() { { tail -n +2 "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; }
|
||||
game_pairs=$(game_scripts | read_scripts)
|
||||
[ -n "$(printf '%s' "$game_pairs" | tr -d '[:space:]')" ] && pairs=$(printf '%s\n%s\n' "$pairs" "$game_pairs" | sort -u | sed '/^$/d')
|
||||
# A Vulkan runtime installer marked as run by an earlier seeding still has its marker: those come out
|
||||
# again below, so the client runs the installer on the game's next launch.
|
||||
declare -A vulkan=()
|
||||
while IFS= read -r line; do
|
||||
[[ $line == *$'\t'* ]] && vulkan[$line]=1
|
||||
done < <(game_scripts | read_scripts vulkan)
|
||||
|
||||
# The VC++ 2015-2022 runtime as its installers check for it, for each architecture and both registry
|
||||
# views. The version is the newest the scripts above know, so any 2015-2022 bundle finds itself
|
||||
# already installed and exits without asking for anything.
|
||||
VCRT_MAJOR=14 VCRT_MINOR=51 VCRT_BUILD=36247
|
||||
vcrt() {
|
||||
local view arch
|
||||
@@ -124,9 +88,6 @@ vcrt() {
|
||||
done
|
||||
}
|
||||
|
||||
# Each prefix's marker lists the names it was given, so it is handed only what it lacks. One stamp
|
||||
# for the whole set flipped between the session's set and the evaluator's (which adds the game's
|
||||
# own names) on every launch, and every prefix was appended to again, inside the launch.
|
||||
want=()
|
||||
declare -A wanted=()
|
||||
while IFS= read -r line; do
|
||||
@@ -142,9 +103,6 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
|
||||
if (path == $1)
|
||||
next
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
|
||||
# The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node;
|
||||
# both spellings are seeded because the reader picks by its own word size.
|
||||
# Joined rather than sub()stituted: gawk and mawk read backslashes in a replacement differently.
|
||||
if (substr(path, 1, 10) != "Software\\\\")
|
||||
next
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", "Software\\\\Wow6432Node\\\\" substr(path, 11), now, $2
|
||||
@@ -154,7 +112,6 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
|
||||
for line; do [[ $line == vcrt$'\t'* ]] && vcrt "$now"; done
|
||||
}
|
||||
|
||||
# Takes the given markers out of a registry file again, in both views, keeping its date.
|
||||
unseed() {
|
||||
local reg=$1 out
|
||||
shift
|
||||
@@ -186,9 +143,51 @@ unseed() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Proton builds a new prefix from its template, and the client runs the install scripts in that
|
||||
# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a
|
||||
# changed one as a new template and upgrades every prefix made from the old.
|
||||
# The ledger lines whose values the registry still holds, in both views where we wrote both. A Proton
|
||||
# update replaces its default_pfx system.reg but not our ledger beside it, and new prefixes copy both.
|
||||
present() { awk -F'\t' '
|
||||
NR == FNR {
|
||||
path = $1
|
||||
if (path != "vcrt") {
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
}
|
||||
n++
|
||||
line[n] = $0
|
||||
need[n] = 0
|
||||
if (path == "vcrt") {
|
||||
for (a = split("x86 x64 arm64", arch, " "); a > 0; a--) {
|
||||
runtime = "microsoft\\\\visualstudio\\\\14.0\\\\vc\\\\runtimes\\\\" arch[a]
|
||||
key[n, ++need[n]] = "[software\\\\" runtime "]" SUBSEP "installed"
|
||||
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" runtime "]" SUBSEP "installed"
|
||||
}
|
||||
} else {
|
||||
both = substr(path, 1, 10) == "Software\\\\"
|
||||
path = tolower(path)
|
||||
key[n, ++need[n]] = "[" path "]" SUBSEP tolower($2)
|
||||
if (both)
|
||||
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)
|
||||
}
|
||||
for (j = 1; j <= need[n]; j++) wanted[key[n, j]] = 1
|
||||
next
|
||||
}
|
||||
/^\[/ { section = tolower(substr($0, 1, index($0, "]"))) }
|
||||
/^"/ {
|
||||
value = substr($0, 2)
|
||||
value = tolower(substr(value, 1, index(value, "\"=") - 1))
|
||||
if ((section SUBSEP value) in wanted)
|
||||
seen[section SUBSEP value] = 1
|
||||
}
|
||||
END {
|
||||
for (i = 1; i <= n; i++) {
|
||||
ok = 1
|
||||
for (j = 1; j <= need[i]; j++) if (!(key[i, j] in seen)) ok = 0
|
||||
if (ok) print line[i]
|
||||
}
|
||||
}
|
||||
' - "$1"; }
|
||||
|
||||
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
@@ -216,6 +215,17 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
printf '%s\n' "${kept[@]}" >"$seeded"
|
||||
echo "== took Vulkan runtime markers out of $reg"
|
||||
fi
|
||||
if [ ${#had[@]} -gt 0 ]; then
|
||||
declare -A held=()
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
|
||||
if [ ${#held[@]} -lt ${#had[@]} ]; then
|
||||
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
|
||||
had=()
|
||||
for line in "${!held[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${!had[@]}" >"$seeded"
|
||||
fi
|
||||
unset held
|
||||
fi
|
||||
missing=()
|
||||
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
|
||||
[ ${#missing[@]} -eq 0 ] && continue
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -126,10 +126,29 @@ INSTALL_JS = r"""
|
||||
return "installed";
|
||||
})()
|
||||
""".replace("__BINDING__", BINDING)
|
||||
# Big Picture's "Switch to Desktop" asks the client's SteamOS manager, which the client has only when it
|
||||
# runs as SteamOS (-steamos3, Deck mode); otherwise the request fails and the screen stays on "Switching
|
||||
# to Desktop..." for good. The request is caught on its way to the client and answered as SteamOS's
|
||||
# own path does, with steamos-session-select.
|
||||
TOOLS_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckTools) return "present";
|
||||
const installs = SteamClient.Installs, downloads = SteamClient.Downloads;
|
||||
if (typeof installs?.OpenInstallWizard !== "function" || typeof installs?.RegisterForShowInstallWizard !== "function" ||
|
||||
typeof installs?.ContinueInstall !== "function" || typeof downloads?.QueueAppUpdate !== "function")
|
||||
throw new Error("the client's install calls are not ready");
|
||||
const self = { asked: new Map() };
|
||||
installs.RegisterForShowInstallWizard((state) => {
|
||||
const app = Number(state?.currentAppID);
|
||||
if (state?.eInstallState === 7 && Date.now() - (self.asked.get(app) || 0) < 120000) {
|
||||
self.asked.delete(app);
|
||||
installs.ContinueInstall();
|
||||
}
|
||||
});
|
||||
self.install = (app) => { self.asked.set(app, Date.now()); installs.OpenInstallWizard([app], "0"); return true; };
|
||||
self.update = (app) => { downloads.QueueAppUpdate(app, "0"); return true; };
|
||||
window.__droiddeckTools = self;
|
||||
return "installed";
|
||||
})()
|
||||
"""
|
||||
TOOL_CHECK_SECONDS = 60
|
||||
TOOL_RETRY_SECONDS = 300
|
||||
SWITCH_BINDING = "droiddeckSwitchToDesktop"
|
||||
SWITCH_JS = r"""
|
||||
(() => {
|
||||
@@ -157,6 +176,82 @@ SWITCH_JS = r"""
|
||||
})()
|
||||
""".replace("__BINDING__", SWITCH_BINDING)
|
||||
SESSION_SELECT = "/usr/bin/steamos-session-select"
|
||||
VR_BINDING = "droiddeckLaunchSteamVr"
|
||||
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
|
||||
VR_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckSteamVr) return "present";
|
||||
const apps = SteamClient.Apps;
|
||||
if (!apps || typeof apps.RunGame !== "function") throw new Error("Steam RunGame is not ready");
|
||||
const run = apps.RunGame;
|
||||
const self = { running: false, pending: new Map(), lastError: null };
|
||||
const flush = () => {
|
||||
if (!self.running) return;
|
||||
const queued = Array.from(self.pending.values());
|
||||
self.pending.clear();
|
||||
for (const item of queued) {
|
||||
clearTimeout(item.timer);
|
||||
run.call(item.receiver, item.id, ...item.args);
|
||||
}
|
||||
};
|
||||
if (typeof SteamClient.OpenVR?.RegisterForVRModeChange === "function") {
|
||||
self.subscription = SteamClient.OpenVR.RegisterForVRModeChange(running => {
|
||||
self.running = !!running;
|
||||
flush();
|
||||
});
|
||||
}
|
||||
const wrapped = function (id, ...args) {
|
||||
const gameid = String(id);
|
||||
if (typeof window.__BINDING__ !== "function") return run.call(this, id, ...args);
|
||||
if (gameid === "250820") {
|
||||
window.__BINDING__(gameid);
|
||||
return;
|
||||
}
|
||||
const overview = window.appStore?.GetAppOverviewByGameID?.(gameid);
|
||||
const vr = overview?.vr_only === true;
|
||||
if (vr && self.subscription && /^[1-9][0-9]{0,19}$/.test(gameid)) {
|
||||
if (self.pending.has(gameid)) return;
|
||||
self.lastError = null;
|
||||
const item = { receiver: this, id, args, timer: null };
|
||||
item.timer = setTimeout(() => {
|
||||
self.pending.delete(gameid);
|
||||
self.lastError = "SteamVR did not become ready. Start SteamVR from DroidDeck and try the game again.";
|
||||
console.error("DroidDeck: " + self.lastError);
|
||||
}, 600000);
|
||||
self.pending.set(gameid, item);
|
||||
try { window.__BINDING__(gameid); }
|
||||
catch (e) { clearTimeout(item.timer); self.pending.delete(gameid); throw e; }
|
||||
flush();
|
||||
return;
|
||||
}
|
||||
return run.call(this, id, ...args);
|
||||
};
|
||||
apps.RunGame = wrapped;
|
||||
if (apps.RunGame !== wrapped) throw new Error("Steam RunGame could not be redirected");
|
||||
if (typeof SteamClient.OpenVR?.StartVR === "function") {
|
||||
const start = SteamClient.OpenVR.StartVR;
|
||||
SteamClient.OpenVR.StartVR = function (...args) {
|
||||
if (typeof window.__BINDING__ === "function") return window.__BINDING__("250820");
|
||||
return start.apply(this, args);
|
||||
};
|
||||
}
|
||||
window.__droiddeckSteamVr = self;
|
||||
return "installed";
|
||||
})()
|
||||
""".replace("__BINDING__", VR_BINDING)
|
||||
|
||||
|
||||
def launch_steamvr():
|
||||
"""Keep downloads/startup off the Steam UI bridge's event loop."""
|
||||
say("SteamVR library launch: using the DroidDeck ARM64 helper")
|
||||
state = os.path.join(os.environ.get("XDG_RUNTIME_DIR", "/tmp"), "droiddeck-steamvr")
|
||||
try:
|
||||
os.makedirs(state, exist_ok=True)
|
||||
with open(os.path.join(state, "library-launch.log"), "a") as log:
|
||||
return subprocess.Popen([VR_HELPER, "launch"], stdin=subprocess.DEVNULL,
|
||||
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
except OSError as e:
|
||||
say("SteamVR library launch failed: %s" % e)
|
||||
|
||||
|
||||
class Closed(Exception):
|
||||
@@ -325,6 +420,9 @@ class Page:
|
||||
raise RuntimeError((details.get("exception") or {}).get("description") or details.get("text") or "script failed")
|
||||
return result.get("result", {}).get("value")
|
||||
|
||||
def tools(self, call):
|
||||
return self.evaluate("%s;\nwindow.__droiddeckTools.%s" % (TOOLS_JS, call))
|
||||
|
||||
def compat(self, call):
|
||||
return self.evaluate("%s;\nwindow.__droiddeckCompat.%s" % (INSTALL_JS, call))
|
||||
|
||||
@@ -409,6 +507,9 @@ class Helper:
|
||||
self.known = set()
|
||||
self.installed = None
|
||||
self.fex_asked = set()
|
||||
self.tools_asked = {}
|
||||
self.tools_checked = None
|
||||
self.vr_launch = None
|
||||
|
||||
def attach(self):
|
||||
path = shared_context(self.port)
|
||||
@@ -419,6 +520,8 @@ class Helper:
|
||||
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
|
||||
raise LookupError("SteamClient is not ready")
|
||||
page.call("Runtime.addBinding", {"name": BINDING})
|
||||
page.call("Runtime.addBinding", {"name": VR_BINDING})
|
||||
page.evaluate(VR_JS)
|
||||
if not self.steamos:
|
||||
page.call("Runtime.addBinding", {"name": SWITCH_BINDING})
|
||||
page.evaluate(SWITCH_JS)
|
||||
@@ -446,24 +549,77 @@ class Helper:
|
||||
installed = COMPAT["installed_apps"](self.steam_root)
|
||||
self.installed = installed
|
||||
picks = COMPAT["valve_picks"](self.steam_root)
|
||||
apps = sorted(set(installed) | set(picks) | set(state.get("auto", {})), key=COMPAT["app_order"])
|
||||
prior_auto = state.get("auto", {})
|
||||
if not isinstance(prior_auto, dict):
|
||||
prior_auto = {}
|
||||
# "native" from earlier builds also lists dual-platform games nobody chose to run natively.
|
||||
prior_native = state.get("native_choices", ())
|
||||
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
|
||||
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"])
|
||||
overrides = COMPAT["requested_games"](
|
||||
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
|
||||
apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"])
|
||||
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
|
||||
current["0"] = top["selected"]
|
||||
native = COMPAT["native_targets"](self.steam_root, installed)
|
||||
changes, auto = COMPAT["plan_mapping"](current, installed, [t["name"] for t in live], default, COMPAT["followers"](state, current), native, picks)
|
||||
native = COMPAT["native_targets"](self.steam_root, apps)
|
||||
raw_mapping = COMPAT["read_config_mapping"](
|
||||
os.path.join(self.steam_root, "config", "config.vdf"))
|
||||
if raw_mapping is None:
|
||||
for app in native_choices:
|
||||
current[app] = ""
|
||||
for app in set(native) - native_choices:
|
||||
if not current.get(app):
|
||||
current.pop(app, None)
|
||||
else:
|
||||
for app in set(native) | native_choices:
|
||||
if app in raw_mapping:
|
||||
# The client shows an explicit native choice as the tool it inherits, and writes config.vdf late.
|
||||
if raw_mapping[app] == "" or current.get(app) not in self.known:
|
||||
current[app] = raw_mapping[app]
|
||||
elif app in prior_auto or app in native_choices:
|
||||
current[app] = ""
|
||||
elif not current.get(app):
|
||||
current.pop(app, None)
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, installed, [t["name"] for t in live], default,
|
||||
COMPAT["followers"](state, current), native, picks, overrides,
|
||||
prior_auto.keys(), native_choices)
|
||||
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
|
||||
page.compat("set(%d, %s)" % (int(app), json.dumps(tool)))
|
||||
say("%s -> %s" % ("default" if app == "0" else "app %s" % app, tool))
|
||||
state.update(auto=auto, tools=catalog, live=True)
|
||||
page.compat("set(%d, %s)" % (int(app), json.dumps(tool if tool is not None else "")))
|
||||
say("%s -> %s" % ("default" if app == "0" else "app %s" % app,
|
||||
tool if tool is not None else "Steam native default"))
|
||||
state.update(
|
||||
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
|
||||
native_choices=sorted(app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]),
|
||||
tools=catalog, live=True)
|
||||
state.pop("native", None)
|
||||
if waiting:
|
||||
state["pending"] = wanted
|
||||
say("%s is new to the running client; it applies when Steam next starts" % wanted)
|
||||
else:
|
||||
state.pop("pending", None)
|
||||
COMPAT["write_json"](state_file, state)
|
||||
if native or os.path.exists(COMPAT["fex_wanted_marker"]()):
|
||||
for app in COMPAT["request_fex"](self.steam_root, self.fex_asked):
|
||||
say("asked the client to install %s for x86 Linux titles and programs" % app)
|
||||
|
||||
def ensure_tools(self):
|
||||
"""Proton, FEX and the runtimes FEX needs are fetched as soon as the client is up, never left pending."""
|
||||
now = time.monotonic()
|
||||
if self.tools_checked is not None and now - self.tools_checked < TOOL_CHECK_SECONDS:
|
||||
return
|
||||
self.tools_checked = now
|
||||
if COMPAT["game_running"]():
|
||||
return
|
||||
for app, action in COMPAT["tool_downloads"](self.steam_root):
|
||||
if now - self.tools_asked.get(app, -TOOL_RETRY_SECONDS) < TOOL_RETRY_SECONDS:
|
||||
continue
|
||||
self.tools_asked[app] = now
|
||||
try:
|
||||
self.page.tools("%s(%d)" % (action, int(app)))
|
||||
say("asked the client to %s %s" % (action, app))
|
||||
except Exception as e:
|
||||
say("the client could not %s %s (%s)" % (action, app, e))
|
||||
if action == "install":
|
||||
for asked in COMPAT["request_fex"](self.steam_root, self.fex_asked):
|
||||
say("asked the client to install %s through steam://install" % asked)
|
||||
|
||||
def request_waiting(self):
|
||||
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
|
||||
@@ -475,6 +631,14 @@ class Helper:
|
||||
events = self.page.drain()
|
||||
if any(called(e, SWITCH_BINDING) for e in events):
|
||||
switch_to_desktop()
|
||||
vr_games = {e.get("params", {}).get("payload") for e in events if called(e, VR_BINDING) and
|
||||
isinstance(e.get("params", {}).get("payload"), str)}
|
||||
vr_games = {game for game in vr_games if isinstance(game, str) and game.isascii() and
|
||||
game.isdecimal() and not game.startswith("0") and len(game) <= 20 and
|
||||
int(game) <= 0xffffffffffffffff}
|
||||
if vr_games and (self.vr_launch is None or self.vr_launch.poll() is not None):
|
||||
say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games)))
|
||||
self.vr_launch = launch_steamvr()
|
||||
return events
|
||||
|
||||
def serve(self, watcher):
|
||||
@@ -482,6 +646,7 @@ class Helper:
|
||||
f.write("%d\n" % os.getpid())
|
||||
say("attached to the client on port %d" % self.port)
|
||||
self.reconcile()
|
||||
self.ensure_tools()
|
||||
while True:
|
||||
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
|
||||
ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0]
|
||||
@@ -489,13 +654,14 @@ class Helper:
|
||||
if self.page.ws in ready:
|
||||
due = any(called(e, BINDING) for e in self.drain())
|
||||
if (watcher in ready or watcher.fileno() < 0) and watcher.changed():
|
||||
due = self.installed != COMPAT["installed_apps"](self.steam_root) or self.request_waiting()
|
||||
due = True
|
||||
if due:
|
||||
time.sleep(0.3)
|
||||
if watcher.fileno() >= 0 and select.select([watcher], [], [], 0)[0]:
|
||||
watcher.changed()
|
||||
self.drain()
|
||||
self.reconcile()
|
||||
self.ensure_tools()
|
||||
|
||||
|
||||
def detach():
|
||||
@@ -519,8 +685,8 @@ def main():
|
||||
say("no devtools port for this session; the client's mapping is kept through config.vdf")
|
||||
return 0
|
||||
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json")] + [os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
# The client has its own SteamOS manager when started as SteamOS (droiddeck-session's Deck mode).
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
|
||||
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
steamos = os.environ.get("BL_STEAMDECK") == "1" and os.environ.get("BL_STEAM_UI") != "desktop"
|
||||
helper = Helper(steam_root, port, steamos)
|
||||
failures = 0
|
||||
|
||||
@@ -16,7 +16,6 @@ def select_desktop(evaluate, timeout=90):
|
||||
if result.get('value') is True:
|
||||
return True
|
||||
except Exception:
|
||||
# CEF and SharedJSContext are not ready during the client's initial startup/update.
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -62,6 +63,12 @@ def source_stamp(game):
|
||||
return None
|
||||
|
||||
|
||||
def store_game(game):
|
||||
"""Games a store client installed belong to that store: the Steam copy of the same title is
|
||||
another license with its own files, and an import would let Steam update over the store's."""
|
||||
return bool(game.get("store"))
|
||||
|
||||
|
||||
def manifest_ids(steamapps, name):
|
||||
matches = []
|
||||
for manifest in Path(steamapps).glob("appmanifest_*.acf"):
|
||||
@@ -113,8 +120,7 @@ def method(obj, slot, result, *args):
|
||||
|
||||
|
||||
def probe(steam_root, ids):
|
||||
# Slots belong to Valve's SteamClient020, SteamUser021 and STEAMAPPS_INTERFACE_VERSION008.
|
||||
library = C.CDLL(str(Path(steam_root) / "steamrtarm64/steamclient.so"))
|
||||
library = C.CDLL(os.environ.get("BL_STEAMCLIENT") or str(Path(steam_root) / "steamrtarm64/steamclient.so"))
|
||||
library.CreateInterface.argtypes = [C.c_char_p, C.c_void_p]
|
||||
library.CreateInterface.restype = C.c_void_p
|
||||
client = library.CreateInterface(b"SteamClient020", None)
|
||||
@@ -168,7 +174,8 @@ def request_restart(steam_root):
|
||||
"""The client reads manifests and shortcuts only at start, so an import needs one restart;
|
||||
the session's loop runs the importer between the exit and the next start."""
|
||||
Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch()
|
||||
subprocess.run([str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"],
|
||||
command = shlex.split(os.environ.get("BL_STEAM_SHUTDOWN", "")) or [str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"]
|
||||
subprocess.run(command,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
|
||||
|
||||
|
||||
@@ -179,18 +186,12 @@ def unimported(steam_root, snapshot, candidates):
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
games = read_json(listing, [])
|
||||
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")]
|
||||
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
|
||||
return
|
||||
candidates, sources = {}, {}
|
||||
next_lookup = 0
|
||||
last_status = None
|
||||
# The probe is a fresh python that loads steamclient.so, seconds of CPU under proot. Ownership
|
||||
# only moves with a purchase or a new match, so it runs when the matches or their sources
|
||||
# change, after a failed probe, and otherwise every five minutes - not on every 30 s beat.
|
||||
# A failed probe is retried on a doubling delay up to those five minutes rather than on every
|
||||
# beat (a client that is not logged on fails it for as long as it stays that way), and none
|
||||
# starts while a game is running: the answer can wait, the game's cores cannot.
|
||||
probed, next_probe, failures = None, 0, 0
|
||||
pending, requested = [], []
|
||||
while True:
|
||||
@@ -214,9 +215,10 @@ def watch(steam_root, listing):
|
||||
elif candidates and (key != probed or now >= next_probe):
|
||||
probed, next_probe = key, now + 300
|
||||
try:
|
||||
probe_env = dict(os.environ, HOME=os.environ["BL_STEAM_IPC_HOME"]) if os.environ.get("BL_STEAM_IPC_HOME") else None
|
||||
result = subprocess.run([sys.executable, __file__, "probe", steam_root,
|
||||
*map(str, sorted(set(candidates.values())))],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
capture_output=True, text=True, timeout=15, env=probe_env)
|
||||
if result.returncode != 0:
|
||||
status = "ownership probe failed: " + (result.stderr.strip()[-300:] or str(result.returncode))
|
||||
failures += 1
|
||||
@@ -370,6 +372,22 @@ def seed_install(steam_root, game, appid):
|
||||
return True
|
||||
|
||||
|
||||
def release(steam_root, game):
|
||||
"""Undoes an import made before store games were skipped. Only our symlink and manifest go;
|
||||
the store's folder stays where it is."""
|
||||
steamapps = Path(steam_root) / "steamapps"
|
||||
sources = {game.get("folder", ""), legacy_path(game.get("folder", ""))}
|
||||
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
|
||||
appid = target.name.removeprefix("DroidDeck-")
|
||||
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources):
|
||||
continue
|
||||
for manifest in (steamapps / f"appmanifest_{appid}.acf", steamapps / PARKED / f"appmanifest_{appid}.acf"):
|
||||
if manifest.is_file() and ours(manifest, appid):
|
||||
manifest.unlink()
|
||||
target.unlink()
|
||||
print(f"droiddeck-steam-games: {game.get('name', appid)} came from {game['store']}; it is a shortcut again, not Steam app {appid}")
|
||||
|
||||
|
||||
def route(steam_root, acct, games):
|
||||
snapshot = read_json(Path(acct) / "config" / STATE, {})
|
||||
if not isinstance(snapshot, dict):
|
||||
@@ -386,6 +404,16 @@ def route(steam_root, acct, games):
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: set-aside installs not restored ({error})")
|
||||
for game in games:
|
||||
if store_game(game):
|
||||
try:
|
||||
release(steam_root, game)
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: store import not undone ({error})")
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
if game.get("native"):
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
folder = game.get("folder", "")
|
||||
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
|
||||
stamp = source_stamp(game)
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
#!/bin/bash
|
||||
# Fetches the native arm64 Steam client from Valve's client-update CDN into ~/.local/share/Steam.
|
||||
# The client is not redistributable, so the runtime ships this script instead of the client.
|
||||
set -eu
|
||||
cdn=https://client-update.fastly.steamstatic.com
|
||||
# The Deck's beta branch, which droiddeck-session forces on the command line too. A client already
|
||||
# on disk from another branch is left for the client to move (droiddeck-session's package/beta).
|
||||
cdn_list="https://client-update.steamstatic.com https://client-update.akamai.steamstatic.com https://client-update.fastly.steamstatic.com"
|
||||
steam_channel=steamdeck_publicbeta
|
||||
manifest=steam_client_${steam_channel}_linuxarm64
|
||||
steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
|
||||
@@ -45,7 +41,12 @@ if [ -n "$repair" ]; then
|
||||
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
|
||||
done
|
||||
fi
|
||||
[ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
sync=
|
||||
if [ "${1:-}" = --sync ]; then
|
||||
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
|
||||
manifest=steam_client_${sync}_linuxarm64
|
||||
fi
|
||||
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
@@ -112,8 +113,28 @@ fetch() {
|
||||
done
|
||||
}
|
||||
|
||||
curl -fsSL "${limits[@]}" --retry 5 --retry-connrefused --retry-delay 5 "$cdn/$manifest" -o "$work/manifest"
|
||||
cdn=""
|
||||
for candidate in $cdn_list; do
|
||||
if curl -fsSL --connect-timeout 10 --max-time 30 --retry 2 --retry-connrefused --retry-delay 3 \
|
||||
"$candidate/$manifest" -o "$work/manifest"; then
|
||||
cdn=$candidate
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$cdn" ] || { echo "droiddeck-steam-install: no Steam client CDN answered for $manifest" >&2; exit 1; }
|
||||
cdn_order=("$cdn")
|
||||
for candidate in $cdn_list; do
|
||||
[ "$candidate" = "$cdn" ] || cdn_order+=("$candidate")
|
||||
done
|
||||
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
|
||||
if [ -n "$sync" ]; then
|
||||
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
|
||||
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
|
||||
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client"
|
||||
fi
|
||||
# Every component block: its name, then the plain zip's file name, sha256 and size.
|
||||
awk -F'"' '
|
||||
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
|
||||
@@ -143,7 +164,14 @@ while read -r block file sum size; do
|
||||
continue
|
||||
fi
|
||||
progress "$parts/$file" "$block"
|
||||
fetch "$cdn/$file" "$parts/$file" "$size" "$sum" "$block" || exit 1
|
||||
fetched=""
|
||||
for host in "${cdn_order[@]}"; do
|
||||
if fetch "$host/$file" "$parts/$file" "$size" "$sum" "$block"; then
|
||||
fetched=$host
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
|
||||
unzip -qo "$parts/$file" -d "$steam_root"
|
||||
: > "$parts/$file.unpacked"
|
||||
rm -f "$parts/$file"
|
||||
@@ -159,20 +187,20 @@ find "$steam_root" -depth -name '*\\*' | while read -r odd; do
|
||||
mv -f "$odd" "$fixed"
|
||||
fi
|
||||
done
|
||||
echo "$steam_channel" > "$steam_root/package/beta"
|
||||
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
|
||||
if [ -n "$sync" ]; then
|
||||
cp -f "$work/manifest" "$steam_root/package/$manifest.manifest"
|
||||
else
|
||||
echo "$steam_channel" > "$steam_root/package/beta"
|
||||
fi
|
||||
ln -sfn "$steam_root/steamrtarm64" "$steam_root/steamrtarm32"
|
||||
chmod +x "$steam_root/steamrtarm64/steam" 2>/dev/null || true
|
||||
# What Valve's steam.sh sets up before it runs the client (it has no arm64 branch itself).
|
||||
mkdir -p "$HOME/.steam"
|
||||
ln -sfn "$steam_root" "$HOME/.steam/root"
|
||||
ln -sfn "$steam_root" "$HOME/.steam/steam"
|
||||
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/bin64"
|
||||
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdk64"
|
||||
# The arm64 client runs every game through $HOME/.steam/sdkarm64/steam-launch-wrapper. Valve's
|
||||
# steam.sh has no arm64 branch to create it, and without it a launch dies in /bin/sh before Proton
|
||||
# is ever invoked - "No such file or directory", no Proton log, and the only other clue is an
|
||||
# unrelated-looking installscript assertion. Same target as sdk64; the client picks the name by
|
||||
# architecture.
|
||||
# sdk64 is where x86_64 Steamworks looks for steamclient.so; arm64 builds look in sdkarm64.
|
||||
ln -sfn "$steam_root/linux64" "$HOME/.steam/sdk64"
|
||||
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdkarm64"
|
||||
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/binarm64"
|
||||
ln -sfn "$steam_root/linux32" "$HOME/.steam/sdk32"
|
||||
|
||||
@@ -122,7 +122,6 @@ def set_value(tokens, opening, key, value):
|
||||
def with_language(text, language):
|
||||
tokens = tokenize(text)
|
||||
if child(tokens, 0, len(tokens), "Registry") is None:
|
||||
# Not a registry the client wrote (or none at all): start one it will read.
|
||||
tokens = []
|
||||
for path in KEYS:
|
||||
set_value(tokens, ensure_block(tokens, path), "language", language)
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
#!/bin/bash
|
||||
# Starts the Steam client from inside a session (the desktop's menu entries and the per-game
|
||||
# launchers droiddeck-desktop-games writes):
|
||||
# droiddeck-steam-launch desktop [appid|steam-url] Steam's desktop UI, optionally a game
|
||||
# droiddeck-steam-launch bigpicture [appid|steam-url] Big Picture
|
||||
#
|
||||
# The desktop (KDE Plasma) composites in software and has no dma-buf, so the client's own Vulkan
|
||||
# window - and any game it starts - would die at its first frame there. The request goes to the app
|
||||
# instead, which ends the desktop and starts a Steam session under gamescope in its place, as
|
||||
# SteamOS's desktop hands Steam back to Gaming Mode.
|
||||
set -u
|
||||
ui=${1:-desktop}
|
||||
target=${2:-}
|
||||
@@ -20,12 +11,38 @@ case $target in
|
||||
*) url=steam://rungameid/$target ;;
|
||||
esac
|
||||
|
||||
# Ask the app for a Steam session.
|
||||
if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
if [ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ]; then
|
||||
client_home=${BL_X64_HOME:-${HOME:-/root}/.droiddeck-x64}
|
||||
client=(/usr/local/bin/droiddeck-steam-x64 --exec)
|
||||
else
|
||||
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
|
||||
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
|
||||
client_home=$HOME
|
||||
client=("$steam_root/steamrtarm64/steam")
|
||||
fi
|
||||
mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck"
|
||||
exec 9>"${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck/steam-desktop.lock"
|
||||
if ! flock -n 9; then
|
||||
for ((attempt = 0; attempt < 180; attempt++)); do
|
||||
pid=$(cat "$client_home/.steam/steam.pid" 2>/dev/null || true)
|
||||
if [ -p "$client_home/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
|
||||
exec "${client[@]}" -nobigpicture -no-cef-sandbox \
|
||||
-cef-ozone-platform=x11 -cef-disable-gpu "${url:-steam://open/library}"
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
|
||||
exit 69
|
||||
fi
|
||||
export BL_INSIDE=1 BL_STEAM_UI=desktop
|
||||
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
|
||||
fi
|
||||
|
||||
dir=${BL_LAUNCH_DIR:-}
|
||||
if [ -z "$dir" ] || [ ! -d "$dir" ]; then
|
||||
echo "droiddeck-steam-launch: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2
|
||||
exit 69
|
||||
fi
|
||||
# Written whole, then renamed: the app reads it on close, never half-written.
|
||||
printf 'ui=%s\nurl=%s\n' "$ui" "$url" > "$dir/steam-launch.tmp" && mv -f "$dir/steam-launch.tmp" "$dir/steam-launch"
|
||||
echo "droiddeck-steam-launch: asked the app for Steam ($ui${url:+, $url})"
|
||||
@@ -1,23 +1,10 @@
|
||||
#!/usr/bin/python3
|
||||
# Registers the card the app installs to (bound at /mnt/droiddeck-sd) as a library folder of the
|
||||
# native Steam client, so they show as installed there instead of being downloaded a second time.
|
||||
#
|
||||
# droiddeck-steam-library <steam root>
|
||||
#
|
||||
# Ported from WinNative's gamescope runtime (GPL-3.0).
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
# The client's own library is internal storage (its steamapps/common is bound to the app's root);
|
||||
# the card is the one extra library folder.
|
||||
# The app binds the storage the user chose (Steam cog -> Game storage) at this path and names it
|
||||
# in BL_LIBRARY_LABEL; nothing bound = internal only, and the entry is removed so the client does
|
||||
# not keep offering a place that is not there.
|
||||
LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),)
|
||||
# The client calls its own library "Local Drive (/)", which says nothing about where that is.
|
||||
# It is the phone's internal storage, so say so.
|
||||
MAIN_LABEL = "Internal Storage"
|
||||
|
||||
|
||||
@@ -153,10 +140,6 @@ def relabel(steam_root, target, label):
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out))
|
||||
print("droiddeck-steam-library: labelled %s %r" % (target, label))
|
||||
# A library also carries its own libraryfolder.vdf, and the client takes the label from there
|
||||
# back into the list above - so editing the list alone is undone on the next start. The
|
||||
# client's own library has no such file, which is why that one kept the new name and the card
|
||||
# went back to the name it was first registered with.
|
||||
marker = os.path.join(target, "libraryfolder.vdf")
|
||||
if not os.path.isfile(marker):
|
||||
return
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
#!/bin/bash
|
||||
# `steam` on the desktop. The client writes a menu entry per installed game that runs
|
||||
# `steam steam://rungameid/<id>`, and its own launchers say `steam`. On the desktop that goes
|
||||
# through droiddeck-steam-launch - which runs the client on the desktop itself when it draws with
|
||||
# the GPU, hands the URL to a client already running there, and asks the app for a Steam session
|
||||
# on a software desktop. Anywhere else it is the client itself.
|
||||
set -u
|
||||
if [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
url=
|
||||
@@ -16,4 +11,5 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
done
|
||||
exec /usr/local/bin/droiddeck-steam-launch "$ui" ${url:+"$url"}
|
||||
fi
|
||||
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && exec /usr/local/bin/droiddeck-steam-x64 --exec "$@"
|
||||
exec "${HOME:-/root}/.local/share/Steam/steamrtarm64/steam" "$@"
|
||||
@@ -29,7 +29,6 @@ def account_dir(steam_root):
|
||||
pass
|
||||
userdata = os.path.join(steam_root, "userdata")
|
||||
if recent is not None:
|
||||
# loginusers holds the 64-bit id; userdata folders use the 32-bit account id.
|
||||
acct = recent - 76561197960265728
|
||||
return os.path.join(userdata, str(acct))
|
||||
try:
|
||||
@@ -39,7 +38,6 @@ def account_dir(steam_root):
|
||||
return os.path.join(userdata, dirs[0]) if len(dirs) == 1 else None
|
||||
|
||||
|
||||
# ---- binary VDF: 0x00 map, 0x01 string, 0x02 int32, 0x08 end ----
|
||||
|
||||
def parse(data):
|
||||
pos = [0]
|
||||
@@ -123,8 +121,6 @@ def shortcut(game, launch_options=None):
|
||||
RECORD = ".droiddeck-shortcuts.json"
|
||||
AWAY_LIMIT = 256
|
||||
FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions")
|
||||
# What the app may change after the shortcut exists. Each follows the app only while Steam still
|
||||
# has what the app last asked for; a value the user set in Steam's Properties stays.
|
||||
FOLLOWED = ("StartDir", "LaunchOptions")
|
||||
|
||||
|
||||
@@ -164,9 +160,6 @@ def merge(fresh, current, state, seen):
|
||||
for field in ("AppName", "icon"):
|
||||
if current.get(field) == base.get(field):
|
||||
entry[field] = fresh[field]
|
||||
# Start in and launch options the app sets: only once there is a record of what it asked for
|
||||
# before (a first run keeps whatever the shortcut already had), and an older record that did
|
||||
# not keep launch options means the app asked for none.
|
||||
if isinstance(state.get("app"), dict):
|
||||
for field in FOLLOWED:
|
||||
was = base.get(field, "" if field == "LaunchOptions" else current.get(field))
|
||||
@@ -187,12 +180,14 @@ def merge(fresh, current, state, seen):
|
||||
def reconcile(existing, wanted, seen, record):
|
||||
games, away = record["games"], dict(record["away"])
|
||||
kept, ours, placed = [], [], {}
|
||||
claimed = {(unquoted(fresh["Exe"]), fresh["AppName"]) for fresh in wanted.values()}
|
||||
for value in existing.values():
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
tags = value.get("tags")
|
||||
if not isinstance(tags, dict) or TAG not in tags.values():
|
||||
kept.append(value)
|
||||
if (unquoted(value.get("Exe")), value.get("AppName")) not in claimed:
|
||||
kept.append(value)
|
||||
continue
|
||||
appid = value.get("appid")
|
||||
if not isinstance(appid, int) or appid in placed:
|
||||
@@ -240,8 +235,6 @@ def save_record(path, record):
|
||||
|
||||
|
||||
ART_MANIFEST = ".droiddeck-art.json"
|
||||
# listing key -> the client's grid file suffix: <appid>p = portrait capsule, <appid> = header,
|
||||
# <appid>_hero, <appid>_logo.
|
||||
ART_SLOTS = (("p", "p"), ("header", ""), ("hero", "_hero"), ("logo", "_logo"))
|
||||
|
||||
|
||||
@@ -273,7 +266,7 @@ def install_art(acct, games):
|
||||
dst = os.path.join(grid, name)
|
||||
size = os.path.getsize(src)
|
||||
if os.path.exists(dst) and name not in manifest:
|
||||
continue # the user's own choice inside the client; never ours to touch
|
||||
continue
|
||||
wanted[name] = size
|
||||
if os.path.exists(dst) and manifest.get(name) == size:
|
||||
continue
|
||||
@@ -344,19 +337,29 @@ def main():
|
||||
save_record(record_path, record)
|
||||
print("droiddeck-steam-shortcuts: %d added game(s) written, %d of the client's own kept" % (len(ours), len(kept)))
|
||||
install_art(acct, [g for g in games if g.get("exe") and g.get("name")])
|
||||
# Each added game runs under the ARM64 Proton: the compat registrar's own mapping writer.
|
||||
try:
|
||||
# No .py suffix on the registrar, so the loader has to be named.
|
||||
compat_path = "/usr/local/bin/steam-compatibility"
|
||||
spec = importlib.util.spec_from_file_location("compat", compat_path, loader=importlib.machinery.SourceFileLoader("compat", compat_path))
|
||||
compat = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(compat)
|
||||
cfg = os.path.join(steam_root, "config", "config.vdf")
|
||||
if os.path.isfile(cfg) and (ours or routes):
|
||||
compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe")] + [str(appid) for appid in set(routes.values())],
|
||||
protect=compat.adopt_extras(os.path.join(steam_root, "compatibilitytools.d")))
|
||||
print("droiddeck-steam-shortcuts: mapped them to %s" % compat.TOOL)
|
||||
except Exception as e: # noqa: BLE001 - the games still show; the client falls back to the default tool
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
x64_tool = os.environ.get("BL_COMPAT_TOOL")
|
||||
own = {}
|
||||
if x64_tool:
|
||||
protect = {compat.first_key(os.path.join(tools, e, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or e: e
|
||||
for e in (os.listdir(tools) if os.path.isdir(tools) else [])}
|
||||
# Its own state: the arm64 client's state.json lists which of that client's titles follow its default.
|
||||
own = {"default": x64_tool,
|
||||
"directory": os.path.join(os.path.dirname(os.path.abspath(steam_root)), "droiddeck-compat"),
|
||||
"linux_tool": "droiddeck-direct"}
|
||||
else:
|
||||
protect = compat.adopt_extras(tools)
|
||||
used = compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe") and not g.get("native")] + [str(appid) for appid in set(routes.values())],
|
||||
protect=protect, **own)
|
||||
print("droiddeck-steam-shortcuts: mapped them to %s" % used)
|
||||
except Exception as e:
|
||||
print("droiddeck-steam-shortcuts: compat mapping skipped (%s)" % e)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ import tempfile
|
||||
|
||||
DISPLAY = "External: gamescope|||Windowed"
|
||||
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
|
||||
# screensaver_while_ingame: kept in config.vdf like the Gamescope settings, under this path.
|
||||
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
|
||||
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
|
||||
|
||||
@@ -79,8 +78,6 @@ def parse(text):
|
||||
|
||||
|
||||
def initial_scale(width, height):
|
||||
# The Thor setting chosen on device at 1280x720 was 140% of its automatic scale.
|
||||
# Adjust with canvas area so choosing a different session resolution keeps the UI usable.
|
||||
if not 320 <= width <= 16384 or not 320 <= height <= 16384:
|
||||
raise ValueError("invalid session size")
|
||||
return 1.3281567096710205 * math.sqrt(width * height / (1280 * 720))
|
||||
@@ -97,8 +94,6 @@ def seed_text(text, scale):
|
||||
if display is not None and not isinstance(display, Block):
|
||||
raise ValueError("invalid display settings")
|
||||
if display is not None:
|
||||
# Current describes the active display and is written even with automatic scaling.
|
||||
# Named display entries are the user's saved choices, including a return to Auto.
|
||||
if any(name.lower() != 'current' and isinstance(value, Block)
|
||||
and value.get('ScaleFactor') is not None for name, value in display.pairs):
|
||||
return text, False
|
||||
@@ -111,7 +106,6 @@ def seed_text(text, scale):
|
||||
else:
|
||||
entry = '"UI"\n{\n"display"\n{\n' + entry + '}\n}\n'
|
||||
at, indent = root.end, 1
|
||||
# Insert only the new block; leave every existing byte, comment and credential untouched.
|
||||
insertion = '\n' + '\n'.join('\t' * indent + line for line in entry.splitlines()) + '\n'
|
||||
return text[:at] + insertion + text[at:], True
|
||||
|
||||
@@ -138,7 +132,6 @@ def seed_value(text, path, value):
|
||||
for level, section in reversed(list(enumerate(sections))):
|
||||
lines = [(level, f'"{section}"'), (level, '{')] + lines + [(level, '}')]
|
||||
insertion = ''.join('\t' * (depth + level) + line + '\n' for level, line in lines)
|
||||
# Before the line the block closes on, when it has one of its own; else beside the brace.
|
||||
at = text.rfind('\n', 0, block.end) + 1
|
||||
if text[at:block.end].strip():
|
||||
at, insertion = block.end, '\n' + insertion
|
||||
|
||||
+1080
File diff suppressed because it is too large.
Load diff
+240
@@ -0,0 +1,240 @@
|
||||
#!/bin/sh
|
||||
set -u
|
||||
|
||||
steamvr=${STEAMVR:-/opt/steamvr}
|
||||
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
|
||||
driver=$vrdir/droiddeck
|
||||
layer=$vrdir/layer
|
||||
logs=$HOME/.local/share/Steam/logs
|
||||
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steamvr
|
||||
umask 077
|
||||
mkdir -p "$state"
|
||||
chmod 700 "$state"
|
||||
|
||||
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
|
||||
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
|
||||
|
||||
running() { pgrep -x vrserver >/dev/null 2>&1; }
|
||||
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
|
||||
quest_settings() {
|
||||
backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json
|
||||
[ "$1" != restore ] || [ -f "$backup" ] || return 0
|
||||
python3 "${DROIDDECK_VR_SETTINGS_HELPER:-/usr/local/bin/droiddeck-steamvr-settings}" "$1" \
|
||||
"$HOME/.local/share/Steam/config/steamvr.vrsettings" "$backup"
|
||||
}
|
||||
|
||||
configure_graphics() {
|
||||
case "$(cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)" in
|
||||
Adreno840*)
|
||||
# The session's forced sysmem mode loses the Vulkan device in SteamVR.
|
||||
export TU_DEBUG="$(
|
||||
IFS=', '
|
||||
set -f
|
||||
separator=
|
||||
for flag in ${TU_DEBUG:-}; do
|
||||
case "$flag" in ''|sysmem) continue ;; esac
|
||||
printf '%s%s' "$separator" "$flag"
|
||||
separator=,
|
||||
done
|
||||
)"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
stop() {
|
||||
rm -f "$state/active"
|
||||
for n in vrcompositor vrserver vrmonitor vrdashboard vrstartup vrwebhelper; do
|
||||
for p in $(pgrep -x "$n"); do kill "$p" 2>/dev/null; done
|
||||
done
|
||||
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
|
||||
attempts=0
|
||||
while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do
|
||||
attempts=$((attempts + 1))
|
||||
if [ "$attempts" = 10 ]; then
|
||||
for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done
|
||||
fi
|
||||
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
quest_settings restore
|
||||
}
|
||||
|
||||
case "${1:-status}" in
|
||||
launch)
|
||||
# Library/URL entry point: use the same installer and start path as the app.
|
||||
exec 8>"$state/launch.lock"
|
||||
flock -n 8 || exit 0
|
||||
if ! installed; then
|
||||
"$0" install || exit $?
|
||||
while [ -f "$state/installing" ]; do sleep 1; done
|
||||
fi
|
||||
"$0" start
|
||||
;;
|
||||
status)
|
||||
i=0; installed && i=1
|
||||
r=0; running && r=1
|
||||
if [ "$r" = 0 ] && [ -n "$(find "$state/active" -mmin +2 2>/dev/null)" ]; then rm -f "$state/active"; 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"
|
||||
;;
|
||||
install)
|
||||
exec 7>"$state/install.lock"
|
||||
flock -n 7 || { echo "already installing"; exit 0; }
|
||||
installed && { echo "SteamVR is already in $steamvr"; exit 0; }
|
||||
: > "$state/installing"
|
||||
trap 'rm -f "$state/installing"' EXIT
|
||||
cache=$HOME/.cache/droiddeck-vr
|
||||
mkdir -p "$cache"
|
||||
pkg=$cache/steamvr.pkg.tar.zst
|
||||
echo "downloading SteamVR (571 MB) from Valve's package server"
|
||||
curl -fsSL --retry 5 -C - -o "$pkg" "$PKG_URL" || { echo "download failed"; exit 1; }
|
||||
echo "$PKG_SHA256 $pkg" | sha256sum -c - >/dev/null 2>&1 || { echo "checksum mismatch: removing the download"; rm -f "$pkg"; exit 1; }
|
||||
tmp=$cache/extract
|
||||
rm -rf "$tmp" && mkdir -p "$tmp"
|
||||
zstd -dc "$pkg" | tar -x -C "$tmp" opt/steamvr || { echo "extract failed"; rm -rf "$tmp"; exit 1; }
|
||||
mkdir -p "$(dirname "$steamvr")"
|
||||
rm -rf "$steamvr" && mv "$tmp/opt/steamvr" "$steamvr" && rm -rf "$tmp" "$pkg"
|
||||
echo "SteamVR installed in $steamvr"
|
||||
;;
|
||||
stop)
|
||||
stop || exit 1
|
||||
;;
|
||||
start)
|
||||
exec 9>"$state/start.lock"
|
||||
flock -n 9 || { echo "SteamVR start already in progress"; exit 0; }
|
||||
installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; }
|
||||
[ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; }
|
||||
if [ -f "$state/active" ] && { running || pgrep -x vrstartup >/dev/null 2>&1; }; then
|
||||
echo "DroidDeck SteamVR is already running"
|
||||
exit 0
|
||||
fi
|
||||
stop || exit 1
|
||||
sleep 1
|
||||
mkdir -p "$HOME/.config/openvr" "$HOME/.config/openxr/1" "$logs" "$HOME/.local/share/Steam/config"
|
||||
if [ -S "/run/droiddeck/droiddeck-xr-frames" ] && [ -z "${DROIDDECK_VR_PRESENT:-}" ]; then
|
||||
export DROIDDECK_VR_PRESENT=questwsi
|
||||
fi
|
||||
python3 - "$HOME/.local/share/Steam/config/steamvr.vrsettings" <<'PY'
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
path = Path(sys.argv[1])
|
||||
try:
|
||||
settings = json.loads(path.read_text()) if path.exists() else {}
|
||||
section = settings.setdefault("steamvr", {})
|
||||
defaults = {} if os.environ.get("DROIDDECK_VR_PRESENT", "").startswith("quest") else {"supersampleManualOverride": True, "supersampleScale": 1.0}
|
||||
changed = any(key not in section for key in defaults)
|
||||
for key, value in defaults.items():
|
||||
section.setdefault(key, value)
|
||||
driver = settings.get("driver_droiddeck")
|
||||
if isinstance(driver, dict) and driver.get("blocked_by_safe_mode") is True:
|
||||
driver["blocked_by_safe_mode"] = False
|
||||
changed = True
|
||||
print("SteamVR had blocked the DroidDeck driver after a crash; unblocked it")
|
||||
if changed:
|
||||
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as output:
|
||||
temporary = Path(output.name)
|
||||
try:
|
||||
json.dump(settings, output, indent=3)
|
||||
output.write("\n")
|
||||
except BaseException:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
except (OSError, ValueError, AttributeError, TypeError) as error:
|
||||
print("Could not set SteamVR resolution defaults: " + str(error), file=sys.stderr)
|
||||
try:
|
||||
(path.parent / "vrserver_crash_timestamp.txt").unlink()
|
||||
print("Removed SteamVR's crash marker so it starts without safe mode")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as error:
|
||||
print("Could not remove SteamVR's crash marker: " + str(error), file=sys.stderr)
|
||||
PY
|
||||
cat > "$HOME/.config/openvr/openvrpaths.vrpath" <<JSON
|
||||
{
|
||||
"config": ["$HOME/.local/share/Steam/config"],
|
||||
"external_drivers": ["$driver"],
|
||||
"jsonid": "vrpathreg",
|
||||
"log": ["$logs"],
|
||||
"runtime": ["$steamvr"],
|
||||
"version": 1
|
||||
}
|
||||
JSON
|
||||
ln -sf "$steamvr/steamxr_linuxarm64.json" "$HOME/.config/openxr/1/active_runtime.json"
|
||||
chaperone=$HOME/.local/share/Steam/config/chaperone_info.vrchap
|
||||
[ -s "$chaperone" ] || cat > "$chaperone" <<'JSON'
|
||||
{
|
||||
"jsonid" : "chaperone_info",
|
||||
"universes" : [
|
||||
{
|
||||
"collision_bounds" : [
|
||||
[ [ -1.0, 0.0, -1.0 ], [ -1.0, 2.43, -1.0 ], [ -1.0, 2.43, 1.0 ], [ -1.0, 0.0, 1.0 ] ],
|
||||
[ [ -1.0, 0.0, 1.0 ], [ -1.0, 2.43, 1.0 ], [ 1.0, 2.43, 1.0 ], [ 1.0, 0.0, 1.0 ] ],
|
||||
[ [ 1.0, 0.0, 1.0 ], [ 1.0, 2.43, 1.0 ], [ 1.0, 2.43, -1.0 ], [ 1.0, 0.0, -1.0 ] ],
|
||||
[ [ 1.0, 0.0, -1.0 ], [ 1.0, 2.43, -1.0 ], [ -1.0, 2.43, -1.0 ], [ -1.0, 0.0, -1.0 ] ]
|
||||
],
|
||||
"play_area" : [ 2.0, 2.0 ],
|
||||
"seated" : { "translation" : [ 0.0, -1.6, 0.0 ], "yaw" : 0.0 },
|
||||
"standing" : { "translation" : [ 0.0, 0.0, 0.0 ], "yaw" : 0.0 },
|
||||
"universeID" : "2"
|
||||
}
|
||||
],
|
||||
"version" : 5
|
||||
}
|
||||
JSON
|
||||
|
||||
export VK_LAYER_PATH="$layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
|
||||
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
|
||||
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
|
||||
configure_graphics
|
||||
export LD_PRELOAD="$layer/libdroiddeck_vr_scheduling.so${LD_PRELOAD:+:$LD_PRELOAD}"
|
||||
if [ "${DROIDDECK_VR_PRESENT:-}" = questwsi ]; then
|
||||
quest_settings apply || exit 1
|
||||
startup_handed_off=0
|
||||
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
|
||||
# The pinned Frame package's CVP constructor exits on Quest's unsupported SoC.
|
||||
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
|
||||
if [ -f "$cvp" ]; then
|
||||
disabled=$cvp.droiddeck-disabled
|
||||
if [ -e "$disabled" ]; then disabled=$(mktemp "$disabled.XXXXXX") || exit 1; fi
|
||||
mv "$cvp" "$disabled" || exit 1
|
||||
echo "Disabled Frame-only CVP backend for Quest; SteamVR uses its normal compositor"
|
||||
fi
|
||||
fi
|
||||
if [ "${DROIDDECK_VR_PRESENT:-}" = questframes ]; then
|
||||
export DROIDDECK_VR_PRODUCER_LEASE=${DROIDDECK_VR_PRODUCER_LEASE:-1}
|
||||
fi
|
||||
if [ -z "${DROIDDECK_VR_DISPLAY_MODE:-}" ] && [ -x "$driver/bin/linuxarm64/xr-display-mode" ]; then
|
||||
mode=$("$driver/bin/linuxarm64/xr-display-mode") || mode=
|
||||
if [ -n "$mode" ]; then export DROIDDECK_VR_DISPLAY_MODE="$mode"; fi
|
||||
fi
|
||||
|
||||
shims=$state/shims
|
||||
mkdir -p "$shims"
|
||||
if ! command -v xset >/dev/null 2>&1; then
|
||||
printf '#!/bin/sh\n# xset stand-in for vrwebhelper.sh: "q" only checks the display answers.\nexec xprop -root -display "${DISPLAY:-:0}" _NET_SUPPORTED >/dev/null 2>&1\n' > "$shims/xset"
|
||||
chmod +x "$shims/xset"
|
||||
export PATH="$shims:$PATH"
|
||||
fi
|
||||
|
||||
: > "$state/active"
|
||||
cd "$steamvr/bin/linuxarm64" || exit 1
|
||||
startup_log=$logs/droiddeck-vrstartup.log
|
||||
ln -sf "$startup_log" "$state/vrstartup.log"
|
||||
setsid ./vrstartup 8>&- 9>&- > "$startup_log" 2>&1 < /dev/null &
|
||||
startup_handed_off=1
|
||||
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
|
||||
;;
|
||||
*)
|
||||
echo "usage: droiddeck-steamvr status|install|start|stop|launch" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
[ "$#" -gt 0 ] || { echo 'usage: droiddeck-steamvr-game COMMAND [ARG...]' >&2; exit 2; }
|
||||
pgrep -x vrserver >/dev/null 2>&1 || {
|
||||
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
|
||||
exit 1
|
||||
}
|
||||
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
|
||||
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
|
||||
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
|
||||
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
|
||||
# Quest's guest GPU images use Vulkan sharing rather than DMA-BUF modifiers.
|
||||
if [ -S "/run/droiddeck/droiddeck-xr-frames" ]; then
|
||||
export gamescope_vr_use_modifiers=${gamescope_vr_use_modifiers:-false}
|
||||
fi
|
||||
export gamescope_vr_nudge_to_visible=${gamescope_vr_nudge_to_visible:-true}
|
||||
exec gamescope --backend openvr \
|
||||
--vr-overlay-key "gamescope.droiddeck.game.$$" \
|
||||
--vr-overlay-default-name 'DroidDeck game' \
|
||||
--vr-overlay-show-immediately --vr-overlay-physical-width 2.4 -- "$@"
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/python3
|
||||
"""Preserve SteamVR preferences across Quest's required compositor overrides."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}
|
||||
|
||||
|
||||
def read(path):
|
||||
try:
|
||||
with path.open() as source:
|
||||
settings = json.load(source)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
if not isinstance(settings, dict) or not isinstance(settings.get('steamvr', {}), dict):
|
||||
raise ValueError('Invalid SteamVR settings object')
|
||||
return settings
|
||||
|
||||
|
||||
def write(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
temporary = path.with_name(path.name + '.tmp')
|
||||
with os.fdopen(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), 'w') as destination:
|
||||
json.dump(value, destination, indent=3)
|
||||
destination.write('\n')
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def saved_preferences(path):
|
||||
try:
|
||||
backup = read(path)
|
||||
if not isinstance(backup.get('section'), bool) or not isinstance(backup.get('values'), dict):
|
||||
raise ValueError('invalid backup object')
|
||||
for key in OVERRIDES:
|
||||
entry = backup['values'].get(key)
|
||||
if not isinstance(entry, list) or len(entry) != 2 or not isinstance(entry[0], bool):
|
||||
raise ValueError('invalid saved preference: ' + key)
|
||||
return backup
|
||||
except ValueError as error:
|
||||
raise ValueError(f'Invalid preference backup {path}; repair the saved section/values and retry restore. '
|
||||
'The backup and current preferences have been preserved.') from error
|
||||
|
||||
|
||||
def update(operation, settings_path, backup_path):
|
||||
settings = read(settings_path)
|
||||
if operation == 'apply':
|
||||
if backup_path.exists():
|
||||
saved_preferences(backup_path)
|
||||
else:
|
||||
section = settings.get('steamvr', {})
|
||||
write(backup_path, {'section': 'steamvr' in settings,
|
||||
'values': {key: [key in section, section.get(key)] for key in OVERRIDES}})
|
||||
settings.setdefault('steamvr', {}).update(OVERRIDES)
|
||||
write(settings_path, settings)
|
||||
elif operation == 'restore':
|
||||
if not backup_path.exists():
|
||||
return
|
||||
backup = saved_preferences(backup_path)
|
||||
section = settings.setdefault('steamvr', {})
|
||||
for key in OVERRIDES:
|
||||
present, value = backup['values'][key]
|
||||
if present:
|
||||
section[key] = value
|
||||
else:
|
||||
section.pop(key, None)
|
||||
if not section and not backup['section']:
|
||||
settings.pop('steamvr')
|
||||
write(settings_path, settings)
|
||||
backup_path.unlink()
|
||||
else:
|
||||
raise ValueError('Expected apply or restore')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
update(sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]))
|
||||
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
|
||||
sys.exit('Could not update SteamVR settings: ' + str(error))
|
||||
@@ -6,8 +6,10 @@ whoever started it: the Games tab, a pinned shortcut, or the Steam client's own
|
||||
looks for the store launcher DroidDeck wrote (.droiddeck-launch.bat) among the arguments; beside it
|
||||
.droiddeck-store.json says which store and game it is.
|
||||
|
||||
For an Epic game the game needs a fresh exchange code to sign in, which only the app can mint. The
|
||||
request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both
|
||||
For an Epic game, once the Epic Games Launcher is installed (droiddeck-epic), the game is started
|
||||
through it: the hidden launcher signs the game in and hands its arguments back in
|
||||
.droiddeck-epic-args. Without the launcher, or when it cannot, the game needs a fresh exchange code
|
||||
to sign in, which only the app can mint. The request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both
|
||||
sides):
|
||||
|
||||
req/<id>.json {"op": "epic-code", "store": "epic", "id": "<app name>"} (tmp + rename)
|
||||
@@ -30,11 +32,19 @@ import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
import tempfile
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
LAUNCHER = ".droiddeck-launch.bat"
|
||||
SIDECAR = ".droiddeck-store.json"
|
||||
EPIC_CODE = ".droiddeck-epic-code"
|
||||
EPIC_ARGS = ".droiddeck-epic-args"
|
||||
EPIC_CLIENT = "/usr/local/bin/droiddeck-epic"
|
||||
EPIC_CLIENT_CURRENT = ".local/share/droiddeck-epic/current.json"
|
||||
EPIC_HANDLED = "DROIDDECK_EPIC_HANDLED"
|
||||
CLIENT_TIMEOUT = 150.0
|
||||
TIMEOUT = 5.0
|
||||
STALE_SECONDS = 300
|
||||
SERVER_WAIT = 8.0
|
||||
@@ -95,6 +105,30 @@ def drop_stale(folder, now=None):
|
||||
return False
|
||||
|
||||
|
||||
def client_wanted():
|
||||
home = os.environ.get("HOME") or "/root"
|
||||
return os.access(EPIC_CLIENT, os.X_OK) and os.path.isfile(os.path.join(home, EPIC_CLIENT_CURRENT))
|
||||
|
||||
|
||||
def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
|
||||
extra = sidecar.get("extra") if isinstance(sidecar.get("extra"), dict) else {}
|
||||
namespace, item = str(extra.get("namespace") or ""), str(extra.get("catalogItemId") or "")
|
||||
if not namespace or not item:
|
||||
return "no-catalog-ids"
|
||||
command = [EPIC_CLIENT, "launch", "--app", str(sidecar.get("id")), "--namespace", namespace, "--item", item,
|
||||
"--folder", str(folder), "--owner", str(os.getppid()), "--timeout", str(int(timeout))]
|
||||
try:
|
||||
run = subprocess.run(command, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, timeout=timeout + 30)
|
||||
answer = json.loads(run.stdout.decode("utf-8", "replace").strip().splitlines()[-1])
|
||||
except (OSError, ValueError, IndexError, subprocess.TimeoutExpired) as error:
|
||||
return "error-" + type(error).__name__
|
||||
if not isinstance(answer, dict):
|
||||
return "no-answer"
|
||||
if answer.get("ok") and (folder / EPIC_ARGS).is_file():
|
||||
return "ok"
|
||||
return str(answer.get("reason") or "failed")
|
||||
|
||||
|
||||
def ask(channel, request, timeout=TIMEOUT):
|
||||
"""Writes [request] under channel/req and waits for channel/resp; the answer, or None on timeout."""
|
||||
req_dir, resp_dir = channel / "req", channel / "resp"
|
||||
@@ -113,7 +147,6 @@ def ask(channel, request, timeout=TIMEOUT):
|
||||
return value
|
||||
except (OSError, ValueError):
|
||||
time.sleep(0.05)
|
||||
# Not answered: the request is withdrawn so a late app does not mint a code nobody reads.
|
||||
try:
|
||||
(req_dir / (rid + ".json")).unlink()
|
||||
except OSError:
|
||||
@@ -226,10 +259,7 @@ def provision_prefix(compat_data, wait=SERVER_WAIT):
|
||||
reg = pfx / "user.reg"
|
||||
if not reg.is_file():
|
||||
return "prefix-not-created"
|
||||
# A wineserver still up for this prefix would write its own copy of user.reg over these lines.
|
||||
busy = not wait_for_server(pfx, wait)
|
||||
# winebrowser starts the first entry it can; an absolute path does not depend on the PATH Wine
|
||||
# hands it.
|
||||
set_value(reg, BROWSER_KEY, "Browsers", BROWSER + ",xdg-open")
|
||||
removed = remove_value(reg, EOS_KEY, "OverlayPath")
|
||||
state = "browser-set" if has_value(reg, BROWSER_KEY, "Browsers", BROWSER + ",xdg-open") else "browser-not-written"
|
||||
@@ -240,8 +270,6 @@ def provision_prefix(compat_data, wait=SERVER_WAIT):
|
||||
|
||||
CLOUD_TIMEOUT = 15.0
|
||||
CLOUD_STORES = ("gog", "epic")
|
||||
# Exit status that tells droiddeck-proton this was a store game with cloud saves: it then waits for
|
||||
# Proton instead of exec'ing it, and runs `droiddeck-store-launch --exited` after.
|
||||
STORE_GAME = 10
|
||||
|
||||
|
||||
@@ -250,10 +278,16 @@ def cloud_on(sidecar):
|
||||
return str(sidecar.get("store")) in CLOUD_STORES and sidecar.get("cloud", True) is not False
|
||||
|
||||
|
||||
def exited(argv):
|
||||
def exited(argv, code=0):
|
||||
"""After the game: ask the app to upload what changed, without waiting for it."""
|
||||
found = find_store_game(argv)
|
||||
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \
|
||||
and os.access(EPIC_CLIENT, os.X_OK):
|
||||
try:
|
||||
subprocess.run([EPIC_CLIENT, "exited", "--code", str(code)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, timeout=10)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
if found is None or not launch_dir or not cloud_on(found[1]):
|
||||
return 0
|
||||
store, game = str(found[1].get("store")), str(found[1].get("id"))
|
||||
@@ -262,9 +296,84 @@ def exited(argv):
|
||||
return 0
|
||||
|
||||
|
||||
COMET_DIR = Path("/usr/local/lib/droiddeck-comet")
|
||||
|
||||
|
||||
def provision_galaxy(compat_data, proton, timeout=90):
|
||||
"""Proton creates the prefix and registers Galaxy before the first game runs."""
|
||||
if not compat_data or not proton or not Path(proton).is_file():
|
||||
return "no-proton"
|
||||
data = Path(compat_data)
|
||||
data.mkdir(parents=True, exist_ok=True)
|
||||
marker = data / "pfx/.droiddeck-comet-service"
|
||||
try:
|
||||
version = (COMET_DIR / "version").read_text().strip()
|
||||
tools = [COMET_DIR / "GalaxyCommunication.exe", COMET_DIR / "update-permissions.exe"]
|
||||
if not all(p.is_file() for p in tools):
|
||||
return "not-installed"
|
||||
stamp = version + " " + " ".join(hashlib.sha256(p.read_bytes()).hexdigest() for p in tools)
|
||||
if marker.is_file() and marker.read_text() == stamp and (data / "pfx/system.reg").is_file():
|
||||
return "ready"
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-galaxy-") as tmp:
|
||||
folder = Path(tmp)
|
||||
result = folder / "result"
|
||||
bat = folder / "install.bat"
|
||||
src = windows_path(str(COMET_DIR))
|
||||
answer = windows_path(str(result))
|
||||
target = r"C:\ProgramData\GOG.com\Galaxy\redists"
|
||||
lines = ["@echo off", "setlocal", 'set "DD_DIR=%s"' % target,
|
||||
"sc query GalaxyCommunication >nul 2>&1",
|
||||
'if not errorlevel 1 if not exist "%DD_DIR%\\droiddeck-comet" goto existing',
|
||||
'if not exist "%DD_DIR%" mkdir "%DD_DIR%"',
|
||||
'copy /y "%s\\GalaxyCommunication.exe" "%s\\GalaxyCommunication.exe" >nul' % (src, target),
|
||||
'if errorlevel 1 exit /b 1',
|
||||
'sc query GalaxyCommunication >nul 2>&1',
|
||||
'if errorlevel 1 sc create GalaxyCommunication binpath= "%s\\GalaxyCommunication.exe"' % target,
|
||||
'if errorlevel 1 exit /b 1',
|
||||
'"%s\\update-permissions.exe"' % src,
|
||||
'if errorlevel 1 exit /b 1',
|
||||
'sc query GalaxyCommunication >nul 2>&1',
|
||||
'if errorlevel 1 exit /b 1',
|
||||
'echo managed>"%s\\droiddeck-comet"' % target,
|
||||
':existing', 'echo ready>"%s"' % answer, 'exit /b 0']
|
||||
bat.write_bytes(("\r\n".join(lines) + "\r\n").encode())
|
||||
env = os.environ.copy()
|
||||
env["BL_COMET_BOOTSTRAP"] = "1"
|
||||
run = subprocess.run([proton, "run", "cmd.exe", "/d", "/c", windows_path(str(bat))],
|
||||
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
if run.returncode or not result.is_file() or result.read_text().strip() != "ready":
|
||||
return "service-unavailable"
|
||||
marker.write_text(stamp)
|
||||
return "ready"
|
||||
except subprocess.TimeoutExpired:
|
||||
return "timeout"
|
||||
except (OSError, ValueError):
|
||||
return "service-unavailable"
|
||||
|
||||
|
||||
def prepare_gog(sidecar, compat_data, launch_dir):
|
||||
if not launch_dir:
|
||||
log("gog achievements unavailable: no-channel")
|
||||
return False
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "gog-achievements", "store": "gog", "id": str(sidecar.get("id"))}, timeout=25.0)
|
||||
if not isinstance(answer, dict) or not answer.get("ready"):
|
||||
log("gog achievements: " + (str(answer.get("reason", "unavailable")) if isinstance(answer, dict) else "timeout"))
|
||||
return False
|
||||
state = provision_galaxy(compat_data, os.environ.get("BL_STORE_PROTON", ""))
|
||||
log("gog achievements prefix: " + state)
|
||||
return state == "ready"
|
||||
|
||||
|
||||
def main(argv):
|
||||
if argv and argv[0] == "--exited":
|
||||
return exited(argv[1:])
|
||||
rest, code = argv[1:], 0
|
||||
if rest[:1] == ["--code"] and len(rest) > 1:
|
||||
try:
|
||||
code = int(rest[1])
|
||||
except ValueError:
|
||||
pass
|
||||
rest = rest[2:]
|
||||
return exited(rest, code)
|
||||
found = find_store_game(argv)
|
||||
if found is None:
|
||||
return 0
|
||||
@@ -273,11 +382,30 @@ 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 store == "gog":
|
||||
prepare_gog(sidecar, compat_data, launch_dir)
|
||||
if store == "epic":
|
||||
drop_stale(folder)
|
||||
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
|
||||
if not handled:
|
||||
drop_stale(folder)
|
||||
try:
|
||||
(folder / EPIC_ARGS).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
choice = options(sidecar)
|
||||
if not (choice["eos"] and not choice["offline"]):
|
||||
# Sign-in off, or offline: no code, and none left over from before.
|
||||
client = None
|
||||
if handled:
|
||||
client = "ok"
|
||||
elif choice["eos"] and not choice["offline"] and client_wanted():
|
||||
client = through_client(folder, sidecar)
|
||||
log("epic launch id=%s client=%s" % (game, client))
|
||||
if client == "ok":
|
||||
try:
|
||||
(folder / EPIC_CODE).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
log("epic launch id=%s through=client" % game)
|
||||
elif not (choice["eos"] and not choice["offline"]):
|
||||
try:
|
||||
(folder / EPIC_CODE).unlink()
|
||||
except OSError:
|
||||
@@ -298,7 +426,6 @@ def main(argv):
|
||||
log("cloud %s %s down result=skipped reason=off" % (store, game))
|
||||
return 0
|
||||
if launch_dir:
|
||||
# The cloud copy where it is newer, before the game reads its saves; bounded, then on regardless.
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
|
||||
if answer is None:
|
||||
log("cloud %s %s down result=timeout" % (store, game))
|
||||
@@ -312,6 +439,6 @@ def main(argv):
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
except Exception as e: # never in the way of the launch
|
||||
except Exception as e:
|
||||
log("skipped: %s" % type(e).__name__)
|
||||
sys.exit(0)
|
||||
@@ -32,20 +32,13 @@ from pathlib import Path
|
||||
|
||||
STORE = Path("/opt/droiddeck/wincomponents")
|
||||
SELECTION = Path.home() / ".config/droiddeck/wincomponents.json"
|
||||
# Components the app is still downloading for a game Steam installed during this session:
|
||||
# {"games": {"<appid>": ["vcredist2019_dll", ...]}}. A launch waits a little for them.
|
||||
PENDING = Path.home() / ".config/droiddeck/wincomponents-pending.json"
|
||||
PENDING_WAIT = 10.0
|
||||
# What this prefix holds from us, so a component the user turns off is taken out again.
|
||||
STATE = ".droiddeck-wincomponents.json"
|
||||
# A file ours replaced that was not Proton's (a real installer's, the user's own), put back when the
|
||||
# component is turned off. Proton's builtins need no copy: it restores those itself.
|
||||
BACKUP = ".droiddeck-wincomponents-backup"
|
||||
BUILTIN_MARKS = (b"Wine builtin DLL", b"Wine placeholder DLL")
|
||||
ARCH_DIRS = ("system32", "syswow64")
|
||||
ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
||||
# The registry file of each hive in a prefix, and the kinds of value registry.json holds: "key"
|
||||
# makes a key, "append"/"prepend" add to a list such as PATH unless it is already there.
|
||||
HIVES = {"HKLM": "system.reg", "HKCU": "user.reg"}
|
||||
VALUE_TYPES = {"key", "sz", "expand_sz", "multi_sz", "dword", "binary", "append", "prepend"}
|
||||
|
||||
@@ -80,7 +73,6 @@ def component(store, cid):
|
||||
for arch in ARCH_DIRS:
|
||||
folder = root / arch
|
||||
if folder.is_dir():
|
||||
# A few go one level down (gmdls: system32/drivers/gm.dls).
|
||||
for entry in sorted(folder.rglob("*")):
|
||||
if entry.is_file() and not entry.is_symlink():
|
||||
rel = entry.relative_to(folder).as_posix().lower()
|
||||
@@ -195,12 +187,10 @@ def place(src, target, backup=None):
|
||||
final = found or target
|
||||
temp = final.with_name(".%s.droiddeck" % final.name)
|
||||
shutil.copy2(src, temp)
|
||||
# Over a Proton builtin this swaps its symlink for our file.
|
||||
os.replace(temp, final)
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the prefix's registry files
|
||||
|
||||
def reg_escape(text, extra=""):
|
||||
"""A string as Wine's registry files write it."""
|
||||
@@ -556,7 +546,6 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
"""Brings the prefix in line with the game's picks. Returns (overrides, notes)."""
|
||||
compat = Path(compat_path)
|
||||
pfx = compat / "pfx"
|
||||
# A game Steam installed during this session may have components still on their way.
|
||||
waited = wait(app_id, pending, store) if wait else None
|
||||
ids = wanted(app_id, selection)
|
||||
state = load_state(compat)
|
||||
@@ -576,7 +565,6 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
overrides += names
|
||||
values += [(cid, value) for value in registry]
|
||||
for rel, src in files:
|
||||
# A file this prefix already has from us is ours to replace; anything else is kept.
|
||||
if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
|
||||
copied += 1
|
||||
keep[rel] = cid
|
||||
@@ -594,8 +582,6 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
path.unlink()
|
||||
removed += 1
|
||||
if removed:
|
||||
# Proton refreshes its builtins only when its config changes; forgetting the config puts
|
||||
# its own DLLs back where ours were on the next launch - this one.
|
||||
try:
|
||||
(compat / "config_info").unlink()
|
||||
except FileNotFoundError:
|
||||
@@ -627,7 +613,6 @@ def overrides_value(names):
|
||||
|
||||
|
||||
def main():
|
||||
# droiddeck-wincomponents <compatdata dir> <appid>: what a launch would do, for a shell.
|
||||
if len(sys.argv) != 3:
|
||||
print("usage: droiddeck-wincomponents <compatdata dir> <appid>", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
# Runs natively: droiddeck-steam-x64's x86 wrappers start it through an arm64 binary, which FEX hands to the CPU.
|
||||
tool=$1; shift
|
||||
x64_home=$HOME
|
||||
|
||||
# The game overlay tags the game's windows with the Steam app ID; without it gamescope never shows them.
|
||||
overlay=0
|
||||
case ${LD_PRELOAD:-} in *gameoverlayrenderer.so*) overlay=1 ;; esac
|
||||
|
||||
for v in $(compgen -e); do
|
||||
case $v in FEX_*) unset "$v" ;; esac
|
||||
done
|
||||
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME_STEAMRT STEAM_STEAMRT_RECURSION_GUARD \
|
||||
LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER BL_WEBHELPER_HIDE_TRACER PROOT_FP_OFF
|
||||
|
||||
game_display=${DISPLAY:-}
|
||||
if [ -f "$x64_home/arm-session.env" ]; then
|
||||
. "$x64_home/arm-session.env"
|
||||
else
|
||||
export HOME=/root
|
||||
fi
|
||||
[ -z "$game_display" ] || export DISPLAY=$game_display
|
||||
# Proton takes its Steam client parts from the client's install folder; the x86-64 client's are x86.
|
||||
export BL_X64_STEAM_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-}
|
||||
export STEAM_COMPAT_CLIENT_INSTALL_PATH=$HOME/.local/share/Steam
|
||||
arm_overlay=$STEAM_COMPAT_CLIENT_INSTALL_PATH/steamrtarm64/gameoverlayrenderer.so
|
||||
if [ "$overlay" = 1 ] && [ -f "$arm_overlay" ]; then
|
||||
export LD_PRELOAD=$arm_overlay${LD_PRELOAD:+:$LD_PRELOAD}
|
||||
fi
|
||||
|
||||
dir=$HOME/.local/share/Steam/compatibilitytools.d/$tool
|
||||
manifest=$dir/toolmanifest.vdf
|
||||
[ -f "$manifest" ] || { echo "droiddeck-x64-arm-proton: no tool $dir" >&2; exit 127; }
|
||||
if ! grep -q droiddeck-proton-wrap "$manifest" 2>/dev/null; then
|
||||
python3 - "${dir%/*}" <<'PY' >&2 || true
|
||||
import importlib.machinery, importlib.util, sys
|
||||
path = "/usr/local/bin/steam-compatibility"
|
||||
spec = importlib.util.spec_from_file_location("compat", path, loader=importlib.machinery.SourceFileLoader("compat", path))
|
||||
compat = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(compat)
|
||||
compat.adopt_extras(sys.argv[1])
|
||||
PY
|
||||
fi
|
||||
cmd=$(sed -n 's/^[[:space:]]*"commandline"[[:space:]]*"\([^"]*\)".*/\1/p' "$manifest" | head -n 1)
|
||||
entry=${cmd%% *}
|
||||
exec "$dir/${entry#/}" "$@"
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
# The arm64 client's web helper for the x86-64 client, run natively: FEX hands this arm64 program to the CPU.
|
||||
x64_home=$HOME
|
||||
arm=/root/.local/share/Steam/steamrtarm64
|
||||
|
||||
for v in $(compgen -e); do
|
||||
case $v in FEX_*) unset "$v" ;; esac
|
||||
done
|
||||
unset LD_PRELOAD LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE BL_WEBHELPER_HIDE_TRACER BL_X64_ARM_WEBHELPER
|
||||
if [ -f "$x64_home/arm-session.env" ]; then
|
||||
eval "$(grep -E '^declare -x (VK_ICD_FILENAMES|VK_DRIVER_FILES|GALLIUM_DRIVER|MESA_LOADER_DRIVER_OVERRIDE|LIBGL_KOPPER_DRI2|TU_DEBUG|ZINK_DEBUG|ZINK_DESCRIPTORS|MESA_NO_ERROR|MESA_DISK_CACHE_DATABASE)=' "$x64_home/arm-session.env")"
|
||||
fi
|
||||
export LD_LIBRARY_PATH=$arm:$arm/panorama LIBGL_KOPPER_DISABLE=true
|
||||
|
||||
args=()
|
||||
for a in "$@"; do
|
||||
case $a in --disable-gpu|--disable-gpu-compositing) ;; *) args+=("$a") ;; esac
|
||||
done
|
||||
cd "$arm" || exit 1
|
||||
exec "$arm/steamwebhelper" "${args[@]}" --ignore-gpu-blocklist
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# Steam's compositor draws each browser window from its X pixmap: frames must reach X, not gamescope's WSI layer.
|
||||
# gamescope sets vk_xwayland_wait_ready=false for its children; kopper swapchains flashed black even with the wait.
|
||||
unset BL_X64_ARM_WEBHELPER
|
||||
# The shim already added the GPU flags (preload/webhelper.c) to these arguments.
|
||||
export BL_WEBHELPER_ARGS=stock DISABLE_GAMESCOPE_WSI=1 vk_xwayland_wait_ready=true LIBGL_KOPPER_DISABLE=true
|
||||
if [ -x ./steamwebhelper ]; then
|
||||
exec ./steamwebhelper "$@"
|
||||
fi
|
||||
exec "$HOME/.local/share/Steam/steamrt64/steamwebhelper" "$@"
|
||||
@@ -1,20 +1,4 @@
|
||||
#!/usr/bin/python3
|
||||
# Makes the ARM64 Proton the client already downloaded usable here, and sets it as the default tool
|
||||
# for Windows titles (CompatToolMapping "0" in config.vdf) when the user has not chosen one. Run
|
||||
# before the client starts; it rewrites config.vdf on exit.
|
||||
#
|
||||
# steam-compatibility <steam root>
|
||||
#
|
||||
# Valve ships a native aarch64 Proton (arm64ec Wine with FEX as the x86 layer) as an ordinary depot,
|
||||
# which is exactly what this runtime wants. Its toolmanifest declares require_tool_appid 4185400 -
|
||||
# Steam Linux Runtime 4 for arm64 - so Steam stacks pressure-vessel underneath it, and
|
||||
# pressure-vessel needs unprivileged user namespaces, which an Android app does not get. Steam then
|
||||
# drops the launch on the floor: no window, no log, straight back to the library.
|
||||
#
|
||||
# So the depot is re-registered here as a compatibility tool of our own: every entry symlinked so
|
||||
# nothing is copied and Steam still updates the real depot, but with a toolmanifest that leaves out
|
||||
# require_tool_appid. Proton takes its base directory from dirname(sys.argv[0]) without resolving
|
||||
# it, so it reads files/ through those symlinks and runs directly on this rootfs.
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -26,22 +10,10 @@ TOOL = "droiddeck-proton-arm64"
|
||||
TOOL_11 = "droiddeck-proton-11-arm64"
|
||||
LEGACY_TOOL = "bannerlator-proton-arm64"
|
||||
LABEL_FILE = "/etc/steam-compatibility-label"
|
||||
# The ARM64 Proton depot the client downloads for itself, as a compatibility-tool appid.
|
||||
# The session asks the client to install it on the command line the first time (steam://install),
|
||||
# so a new client has it before a Windows title is first launched. It is deliberately NOT named as
|
||||
# this tool's dependency: a dependency is composed with its own dependencies, and this depot
|
||||
# requires 4185400, the arm64 Steam Linux Runtime, whose container needs user namespaces Android
|
||||
# does not give - the launch would be wrapped in it and die before this tool ever ran.
|
||||
PROTON_ARM64_APPID = "4427310"
|
||||
LAUNCHER = "droiddeck-proton"
|
||||
LEGACY_LAUNCHER = "bannerlator-proton"
|
||||
# The extra Steam library the app mounts the installed games into (see droiddeck-steam-library).
|
||||
# installed_apps() scans it too; it lives only in the sibling script, so define it here as well.
|
||||
LIBRARY = "/mnt/droiddeck" # the card library is LIBRARY + "-sd"; internal storage is steam_root itself
|
||||
# The client lists its own "Proton Experimental (ARM64)" and "Proton 11.0 (ARM64)" in the same
|
||||
# Compatibility dropdown, and those are the two that cannot start a game here. Ours has to be
|
||||
# unmistakable at a glance, or a user picks a neighbour and gets a launch that fails silently.
|
||||
# Newest first: whichever the client has downloaded is used.
|
||||
LIBRARY = "/mnt/droiddeck"
|
||||
SOURCES = ("Proton Experimental (ARM64)", "Proton 11.0 (ARM64)")
|
||||
OWN_TOOLS = ((TOOL, SOURCES), (TOOL_11, ("Proton 11.0 (ARM64)",)))
|
||||
FEX_TOOL = "droiddeck-fex"
|
||||
@@ -49,17 +21,15 @@ FEX_LAUNCHER = "droiddeck-fex-tool"
|
||||
FEX_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", FEX_LAUNCHER)
|
||||
FEX_APPID = "3127680"
|
||||
SNIPER_APPID = "1628350"
|
||||
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID)
|
||||
SLR4_APPID = "4183110"
|
||||
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
|
||||
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
|
||||
FULLY_INSTALLED = 4
|
||||
UPDATE_REQUIRED = 2
|
||||
REQUEST_HANDOFF_SECONDS = 30
|
||||
PLAYABLE_TYPES = frozenset(("game", "demo", "application", "beta"))
|
||||
COMPAT_DIR = os.path.join(os.environ.get("HOME", "/root"), ".local", "share", "droiddeck-compat")
|
||||
# Written by us; everything else in the depot is symlinked through.
|
||||
OWN_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", LAUNCHER)
|
||||
# The client assigns a Proton to a Windows title by itself, as a per-app CompatToolMapping entry at
|
||||
# priority 250 - which outranks the "0" default, so setting that default alone changes nothing. Every
|
||||
# Proton it can pick is one this runtime cannot start: the ARM64 ones want pressure-vessel (see
|
||||
# above) and the x86_64 ones want pressure-vessel and FEX on top. Ours is the only one that runs
|
||||
# here, so every Proton mapping is repointed at it. Tools that are not Proton are left alone.
|
||||
COMPAT_TOOL_VDF = """"compatibilitytools"
|
||||
{
|
||||
"compat_tools"
|
||||
@@ -84,52 +54,30 @@ TOOL_MANIFEST_VDF = """"manifest"
|
||||
""" % LAUNCHER
|
||||
|
||||
|
||||
# Steam runs its own graphics probe through EVERY registered tool at once, ~40 s after logging in,
|
||||
# all with STEAM_COMPAT_DATA_PATH=.../compatdata/0, and those concurrent Protons can write their
|
||||
# builtin DLLs through each other's prefix links into each other's trees (seen: GE's FEX DLLs became
|
||||
# Proton Experimental's). Moving those runs to a prefix per tool was tried and crashed the Steam
|
||||
# client right after the probe started (segfault, rc 139, first ever in 25 sessions), so the client
|
||||
# relies on compatdata/0 itself. The launch-time check below is the protection instead.
|
||||
|
||||
# The Components page's choices, enforced in the one place every game launch passes: the app keeps
|
||||
# desired.tsv (tool dir, Proton build, component, file, sha256, source copy) and an unpacked copy of
|
||||
# each package in use. A file that no longer matches - whatever changed it - is put back before
|
||||
# Proton starts. Only for the Proton build the choice was made for: after a Steam update the build
|
||||
# differs and the Proton's own new files are left alone until the user chooses again.
|
||||
# A store game (GOG, Epic, Amazon) is started through the launcher .bat DroidDeck wrote beside it.
|
||||
# An Epic game needs a fresh sign-in code, which only the app can mint: droiddeck-store-launch asks
|
||||
# for it and the app writes it into the game's folder, so a launch from the client's own Play
|
||||
# button signs in just as one from the app does. A real launch only; never in the way of it.
|
||||
BL_STORE_SETUP = """
|
||||
bl_store_launch() {
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
# A web address the game opens (Wine's winebrowser runs xdg-open) goes to Android's browser:
|
||||
# droiddeck-open-url as xdg-open, first on the game's PATH, with the session channel left in a
|
||||
# file in case Wine does not pass BL_LAUNCH_DIR on. (The prefix also names it as Wine's browser.)
|
||||
if [ -x /usr/local/bin/droiddeck-open-url ]; then
|
||||
mkdir -p /tmp/droiddeck-browser
|
||||
ln -sfn /usr/local/bin/droiddeck-open-url /tmp/droiddeck-browser/xdg-open
|
||||
[ -n "${BL_LAUNCH_DIR:-}" ] && printf '%s\n' "$BL_LAUNCH_DIR" > /tmp/droiddeck-browser/launch-dir
|
||||
[ -n "${BL_LAUNCH_DIR:-}" ] && printf '%s
|
||||
' "$BL_LAUNCH_DIR" > /tmp/droiddeck-browser/launch-dir
|
||||
PATH="/tmp/droiddeck-browser:$PATH"; export PATH
|
||||
fi
|
||||
# BL_DEBUG_BROWSER=1 (droiddeck-env): Wine traces how the game opens a web address.
|
||||
if [ "${BL_DEBUG_BROWSER:-}" = 1 ]; then
|
||||
WINEDEBUG="${WINEDEBUG:+$WINEDEBUG,}+shell,+winebrowser"; export WINEDEBUG
|
||||
fi
|
||||
[ -x /usr/local/bin/droiddeck-store-launch ] || return 0
|
||||
/usr/local/bin/droiddeck-store-launch "$@"
|
||||
# 10: a store game with cloud saves - the launch waits for Proton and uploads after (bl_run).
|
||||
[ $? -eq 10 ] && BL_STORE_EXIT=1
|
||||
return 0
|
||||
}
|
||||
|
||||
# Runs Proton: exec'd as always, except for a store game with cloud saves, where the wrapper stays
|
||||
# to tell the app the game has exited so it can upload what changed.
|
||||
bl_run() {
|
||||
if [ -n "${BL_STORE_EXIT:-}" ]; then
|
||||
"$@"
|
||||
rc=$?
|
||||
/usr/local/bin/droiddeck-store-launch --exited "${BL_STORE_ARGS[@]}" || true
|
||||
/usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}" || true
|
||||
exit $rc
|
||||
fi
|
||||
exec "$@"
|
||||
@@ -141,29 +89,57 @@ bl_components() {
|
||||
base=$1
|
||||
cm_dir="${HOME:-/root}/.local/share/droiddeck-components"
|
||||
cm_list="$cm_dir/desired.tsv"
|
||||
# A real game launch only: the verb the client starts a game with and the game's own prefix. Every
|
||||
# other run - above all the client's own probes right after login, which all share compatdata/0 -
|
||||
# is left exactly as it was: with this check running through them, the client segfaulted (rc 139)
|
||||
# within seconds of starting its probes, four sessions out of four. The prefix decides rather than
|
||||
# the app id because a non-Steam shortcut launches with app id 0 but still gets a prefix of its own.
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
case "${STEAM_COMPAT_DATA_PATH:-}" in ''|*/compatdata/0|*/compatdata/0/|*/compatdata/0-*) return 0 ;; esac
|
||||
[ -f "$cm_list" ] || return 0
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH%/}
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH}
|
||||
while [[ "$cm_app" == */ ]]; do cm_app=${cm_app%/}; done
|
||||
cm_app=${cm_app##*/}
|
||||
if [[ "$cm_app" =~ ^(-?)([0-9]+)$ ]]; then
|
||||
cm_sign=${BASH_REMATCH[1]}
|
||||
cm_digits=${BASH_REMATCH[2]}
|
||||
while [[ ${#cm_digits} -gt 1 && "$cm_digits" == 0* ]]; do cm_digits=${cm_digits#0}; done
|
||||
if [[ ${#cm_digits} -le 10 ]]; then
|
||||
cm_app=$((10#$cm_digits))
|
||||
[ "$cm_sign" = "-" ] && cm_app=$((-cm_app))
|
||||
if (( cm_app >= -2147483648 && cm_app <= 4294967295 && cm_app != 0 )); then
|
||||
(( cm_app < 0 )) && cm_app=$((cm_app + 4294967296))
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
if [ -z "$cm_app" ]; then
|
||||
echo "droiddeck-proton: components: invalid game prefix, left as it is" >&2
|
||||
return 0
|
||||
fi
|
||||
cm_tool=${base##*/}
|
||||
cm_build=$(awk 'NR == 1 { print $2 }' "$base/version" 2>/dev/null)
|
||||
cm_fixed=0
|
||||
cm_checked=0
|
||||
# One sha256sum for every file: each program started here pays a dozen traced library lookups
|
||||
# under the game's search path before it does anything.
|
||||
cm_selected=$(awk -F '\\t' -v app="$cm_app" -v tool="$cm_tool" -v build="$cm_build" '
|
||||
$2 == tool && $3 == build {
|
||||
rows[++count] = $0
|
||||
scopes[count] = $1
|
||||
comps[count] = $4
|
||||
if ($1 == app) specific[$4] = 1
|
||||
}
|
||||
END {
|
||||
for (i = 1; i <= count; i++)
|
||||
if (scopes[i] == app || (scopes[i] == "*" && !specific[comps[i]])) print rows[i]
|
||||
}
|
||||
' "$cm_list")
|
||||
local cm_rows=() cm_files=() row h p
|
||||
local -A cm_sums=()
|
||||
while IFS=$'\\t' read -r t want comp rel sum src; do
|
||||
[ "$t" = "$cm_tool" ] && [ "$want" = "$cm_build" ] || continue
|
||||
while IFS=$'\\t' read -r scope t want comp rel sum src; do
|
||||
[ -n "$scope" ] || continue
|
||||
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
|
||||
[ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done < "$cm_list"
|
||||
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done <<< "$cm_selected"
|
||||
if [ ${#cm_files[@]} -gt 0 ]; then
|
||||
while read -r h p; do cm_sums["$p"]=$h; done < <(sha256sum -- "${cm_files[@]}" 2>/dev/null)
|
||||
fi
|
||||
@@ -171,6 +147,10 @@ bl_components() {
|
||||
IFS=$'\\t' read -r comp rel sum src <<< "$row"
|
||||
cm_checked=$((cm_checked + 1))
|
||||
f="$base/$rel"
|
||||
if [ "$src" = "-" ]; then
|
||||
if [ -e "$f" ]; then rm -f "$f" && cm_fixed=$((cm_fixed + 1)); fi
|
||||
continue
|
||||
fi
|
||||
if [ -f "$f" ] && [ "${cm_sums[$f]:-}" = "$sum" ]; then continue; fi
|
||||
if [ ! -f "$src" ]; then
|
||||
echo "droiddeck-proton: components: $comp source missing ($src), left as it is" >&2
|
||||
@@ -189,36 +169,17 @@ bl_components() {
|
||||
}
|
||||
"""
|
||||
|
||||
# Resolves the depot at launch time, so the tool can be registered before the depot exists and
|
||||
# survives the client updating or replacing it. Proton takes its base directory from
|
||||
# dirname(sys.argv[0]) without resolving it, so it is run from the depot itself.
|
||||
# Cores for a game the client launches, kept separate from the client's own. One mask suits the
|
||||
# client's menus and another suits a game, and they are wanted at the same time - so the game's is
|
||||
# applied here, in the launch path every game goes through, rather than to the session as a whole.
|
||||
BL_GAME_CPUS_SETUP = """
|
||||
bl_game_cpus() {
|
||||
[ -n "${BL_GAME_CPUS:-}" ] || return 0
|
||||
command -v taskset >/dev/null 2>&1 || return 0
|
||||
# exec'd through taskset rather than set afterwards: a mask applied to a pid races the process
|
||||
# into spawning its own threads, and this way every thread inherits it from the first instruction.
|
||||
BL_TASKSET="taskset -c $BL_GAME_CPUS"
|
||||
echo "droiddeck-proton: game cores $BL_GAME_CPUS" >&2
|
||||
}
|
||||
"""
|
||||
|
||||
# Quake III engine games (id Tech 3) set their own resolution and switch the display to it. Under
|
||||
# gamescope with the ARM64 Proton that switch is refused ("calling CDS: failed, bad mode") and the
|
||||
# game never gets OpenGL; left at its own size in a window, it draws small in a corner. So these
|
||||
# titles are told to stay windowed at the session's own size - unless the user's launch options
|
||||
# already say something about the video mode, which are left as they are.
|
||||
# The session puts the client's own libraries (steamrtarm64, its panorama/) ahead of everything for
|
||||
# the client, and a game inherits that: Wine then resolved gnutls, SDL, FFmpeg and the rest against
|
||||
# the client's private copies instead of the rootfs it was built for. Inside Steam's runtime
|
||||
# container that path never reaches Proton either. (WinNative's winnative-proton-launch.)
|
||||
BL_LIBPATH_SETUP = """
|
||||
bl_libpath() {
|
||||
# A Proton built to prefer PipeWire (CachyOS's among the adopted ones) hung its audio thread
|
||||
# here, where only PulseAudio answers. (WinNative, winnative-proton-launch.)
|
||||
export PROTON_USE_PIPEWIRE=${PROTON_USE_PIPEWIRE:-0}
|
||||
[ -n "${LD_LIBRARY_PATH:-}" ] || return 0
|
||||
local kept= dir old_ifs=$IFS
|
||||
@@ -238,7 +199,6 @@ BL_IDTECH3_SETUP = """
|
||||
bl_idtech3() {
|
||||
BL_EXTRA_ARGS=()
|
||||
case "${SteamAppId:-${STEAM_COMPAT_APP_ID:-}}" in
|
||||
# Quake III Arena, Quake III: Team Arena, Return to Castle Wolfenstein, Jedi Academy.
|
||||
2200|2350|9010|6020) ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
@@ -254,8 +214,40 @@ bl_idtech3() {
|
||||
}
|
||||
"""
|
||||
|
||||
# Source games report VAC-secure or insecure only in their console, written to console.log only with -condebug.
|
||||
# The app keeps the switch and the records in /root: the x86-64 client runs games with its own HOME.
|
||||
BL_VACDIAG_SETUP = """
|
||||
bl_vacdiag() {
|
||||
[ -f /root/.droiddeck-vac-diagnostics ] || return 0
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
local exe= a dir added=no app=${SteamAppId:-${STEAM_COMPAT_APP_ID:-0}}
|
||||
for a in "$@"; do case $a in *.exe|*.EXE) exe=$a ;; esac; done
|
||||
[ -n "$exe" ] || return 0
|
||||
dir=$(dirname "$exe")
|
||||
# Source: <mod>/gameinfo.txt beside the exe. Source 2: game/bin/win64/<exe> with game/<mod>/gameinfo.gi.
|
||||
if ls "$dir"/*/gameinfo.txt >/dev/null 2>&1 || ls "$dir"/../../*/gameinfo.gi >/dev/null 2>&1; then
|
||||
case " $* " in
|
||||
*" -condebug "*) echo "droiddeck-proton: vac-diag: app $app already has -condebug" >&2 ;;
|
||||
*) BL_EXTRA_ARGS+=(-condebug); added=yes
|
||||
echo "droiddeck-proton: vac-diag: app $app is a Source title; launched with -condebug" >&2 ;;
|
||||
esac
|
||||
else
|
||||
added=not-source
|
||||
echo "droiddeck-proton: vac-diag: app $app is not a Source title; it keeps no console log to read" >&2
|
||||
fi
|
||||
case " $* " in
|
||||
*" -insecure "*) echo "droiddeck-proton: vac-diag: app $app has -insecure in its launch options - it can never be VAC-secure this way" >&2 ;;
|
||||
esac
|
||||
printf '%s\tapp %s\tcondebug %s\t%s\n' "$(date +%s)" "$app" "$added" "${exe##*/}" >> /root/.droiddeck-vac-launches
|
||||
}
|
||||
"""
|
||||
|
||||
BL_DIRECTAUDIO_SETUP = """
|
||||
bl_directaudio() {
|
||||
case "${verb:-}" in
|
||||
run|waitforexitandrun|runinprefix) ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
base=$1
|
||||
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
|
||||
[ -d "$BL_DIRECTAUDIO" ] || return 0
|
||||
@@ -266,10 +258,6 @@ bl_directaudio() {
|
||||
echo "droiddeck-proton: DirectAudio left off - it is built for Wine 11 and this Proton is '${version:-unknown}'. Pairing them would be silent rather than broken, so it is not worth guessing." >&2
|
||||
return 0
|
||||
fi
|
||||
# Two builds of the driver ship, one per Wine audio interface, and both Wines call themselves
|
||||
# 11.0: the private mmdevapi table is not versioned, and the wrong set plays silence, not an
|
||||
# error. Proton's own winepulse.so tells them apart - it imports PsCreateSystemThread only on
|
||||
# the system-thread table (Proton-CachyOS), never on the classic one (Valve, GE-Proton).
|
||||
winepulse="$base/files/lib/wine/aarch64-unix/winepulse.so"
|
||||
if [ ! -f "$winepulse" ]; then
|
||||
echo "droiddeck-proton: DirectAudio left off - no winepulse.so to read this Proton's audio interface from" >&2
|
||||
@@ -281,20 +269,10 @@ bl_directaudio() {
|
||||
echo "droiddeck-proton: DirectAudio left off - no driver set for the $set interface is staged" >&2
|
||||
return 0
|
||||
fi
|
||||
# Wine appends the per-architecture subdirectory to each entry, so the directory holding
|
||||
# aarch64-unix/ and aarch64-windows/ is what goes here.
|
||||
WINEDLLPATH="$da/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
|
||||
export WINEDLLPATH
|
||||
# Proton-CachyOS's launcher sets WINE_AUDIO_DRIVER=pulse,alsa (setdefault, so an existing value
|
||||
# wins), and its mmdevapi reads that variable BEFORE the registry - so the selection below was
|
||||
# being overridden to pulse on every CachyOS game. Valve's and GE's mmdevapi do not read the
|
||||
# variable at all and take the registry, which is why both are done. A value the user set for
|
||||
# the game still wins: the per-game environment is applied after this.
|
||||
WINE_AUDIO_DRIVER="directaudio,pulse"
|
||||
export WINE_AUDIO_DRIVER
|
||||
# mmdevapi only tries the drivers named in the registry; its built-in list is pulse, alsa, oss and
|
||||
# coreaudio and knows nothing about this one. The key is appended to the prefix's user.reg rather
|
||||
# than written with `wine reg`, which would start a wineserver here just to set one value.
|
||||
pfx="${STEAM_COMPAT_DATA_PATH:-}/pfx"
|
||||
reg="$pfx/user.reg"
|
||||
if [ -f "$reg" ]; then
|
||||
@@ -311,46 +289,21 @@ bl_directaudio() {
|
||||
elif ! BL_KEY="$key" awk 'index($0, "[") == 1 { inside = index($0, ENVIRON["BL_KEY"] " ") == 1 } inside && index($0, "\\"Audio\\"=") == 1 { last = $0 } END { exit last != "\\"Audio\\"=\\"directaudio,pulse\\"" }' "$reg" 2>/dev/null; then
|
||||
printf '\\n%s %s\\n"Audio"="directaudio,pulse"\\n' "$key" "$(date +%s)" >> "$reg"
|
||||
echo "droiddeck-proton: DirectAudio selected in the prefix" >&2
|
||||
# Steam runs this tool several times per launch (getcompatpath, run, waitforexitandrun); a
|
||||
# wineserver from an earlier verb that still holds the registry saves its own copy on exit
|
||||
# and drops this line. Said out loud so a game that stays on pulse once is explained; it
|
||||
# takes on the next launch. (Writing through the live server with a bare `wine reg add` was
|
||||
# tried and withdrawn: a second Wine invocation inside Steam's launch sequence is not safe.)
|
||||
srv="${BL_WINE_SERVER_BASE:-/tmp/.wine-$(id -u)}/server-$(printf '%x-%x' $(stat -c '%d %i' "$pfx" 2>/dev/null || echo 0 0))/socket"
|
||||
if [ -S "$srv" ]; then
|
||||
echo "droiddeck-proton: a wineserver is already running for this prefix; DirectAudio may only engage on the next launch" >&2
|
||||
fi
|
||||
fi
|
||||
else
|
||||
# A prefix that does not exist yet is created by Proton moments from now, after this runs, so
|
||||
# the value lands on the NEXT launch of that game. Said out loud so a first launch on Proton's
|
||||
# own audio does not look like a fault. (Having Proton create the prefix from here first was
|
||||
# tried and withdrawn: a second Proton run inside Steam's launch sequence got the launch
|
||||
# aborted - Steam games bounced back to their page with a half-made prefix.)
|
||||
echo "droiddeck-proton: no prefix yet - DirectAudio takes effect the next time this game starts" >&2
|
||||
fi
|
||||
echo "droiddeck-proton: DirectAudio ready (Wine $major, $set)" >&2
|
||||
}
|
||||
"""
|
||||
|
||||
# Resolves the depot at launch time, so the tool can be registered before the depot exists and
|
||||
# survives the client updating or replacing it. Proton takes its base directory from
|
||||
# dirname(sys.argv[0]) without resolving it, so it is run from the depot itself.
|
||||
LAUNCHER_SH = """#!/bin/bash
|
||||
# DroidDeck's Proton ARM64: runs the ARM64 Proton the Steam client downloaded, without the
|
||||
# Steam Linux Runtime container its own manifest asks for (no user namespaces on Android).
|
||||
verb=$1; shift
|
||||
steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
|
||||
# Steam's overlay is preloaded into every game Valve launches, and used to be dropped here: it was
|
||||
# landing in front of open() and read() on /dev/input, letting Wine open the session's pad and
|
||||
# answering every read of it with nothing - a controller that never reports, and Wine's HID thread
|
||||
# spinning a core on it.
|
||||
#
|
||||
# Removing it was the wrong cure for an ordering problem. glibc processes LD_PRELOAD BEFORE
|
||||
# /etc/ld.so.preload, and the interposer lives in the latter, so the overlay was simply ahead of it.
|
||||
# Naming the interposer first in LD_PRELOAD puts it back in front and the overlay loads as Valve
|
||||
# intends. That matters beyond the overlay itself: every deviation from the launch Valve ships is a
|
||||
# difference this runtime would otherwise have to justify.
|
||||
for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do
|
||||
if [ -f "$fake" ]; then
|
||||
case ":${LD_PRELOAD:-}:" in
|
||||
@@ -359,9 +312,6 @@ for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do
|
||||
esac
|
||||
fi
|
||||
done
|
||||
# ld.so looks every library up along the game's search path (its own directory, Steam's runtime
|
||||
# and video directories, Proton's), and under proot each miss is a round trip to the tracer. With
|
||||
# the fast path, the audit module skips the misses it can prove (tools/proot/fastpath/audit.c).
|
||||
audit=/usr/local/lib/libblaudit.so
|
||||
if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
|
||||
case ":${LD_AUDIT:-}:" in
|
||||
@@ -369,8 +319,6 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
|
||||
*) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;;
|
||||
esac
|
||||
fi
|
||||
# The depot this tool is named after, newest across the libraries that hold it; the others in the
|
||||
# list stand in only when it is missing.
|
||||
depot=
|
||||
libraries=$(printf '%%s\\n' "$steam_root" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$steam_root/steamapps/libraryfolders.vdf" 2>/dev/null)
|
||||
for name in %s; do
|
||||
@@ -393,7 +341,9 @@ if [ -n "$depot" ]; then
|
||||
bl_directaudio "$depot"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_vacdiag "$@"
|
||||
bl_libpath
|
||||
BL_STORE_PROTON="$depot/proton"; export BL_STORE_PROTON
|
||||
bl_store_launch "$@"
|
||||
BL_STORE_ARGS=("$@")
|
||||
bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
@@ -405,20 +355,13 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
|
||||
|
||||
|
||||
def launcher_sh(sources=SOURCES):
|
||||
# Spliced in after the formatting, never through it: the function body contains ${major%%.*}
|
||||
# and a % format would eat that into a single %, leaving a shell expansion that silently does
|
||||
# something else.
|
||||
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
|
||||
|
||||
|
||||
LAUNCHER_SH = launcher_sh()
|
||||
|
||||
# A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of
|
||||
# that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot
|
||||
# is: its manifest declares require_tool_appid, and the client's overlay library has to come out of
|
||||
# LD_PRELOAD. Its own entry point is left untouched and called through this wrapper.
|
||||
EXTRA_WRAPPER = "droiddeck-proton-wrap"
|
||||
LEGACY_EXTRA_WRAPPER = "bannerlator-proton-wrap"
|
||||
ORIGINAL_SUFFIX = ".droiddeck-orig"
|
||||
@@ -431,16 +374,9 @@ EXTRA_MANIFEST_VDF = """"manifest"
|
||||
"compatmanager_layer_name" "proton"
|
||||
}
|
||||
""" % EXTRA_WRAPPER
|
||||
# %s is the tool's own entry point, read out of the manifest it shipped with.
|
||||
EXTRA_WRAPPER_SH = """#!/bin/bash
|
||||
# DroidDeck: runs a Proton installed into compatibilitytools.d without the Steam Linux Runtime
|
||||
# container its own manifest asks for - pressure-vessel needs unprivileged user namespaces, which
|
||||
# an Android app does not get, and the launch dies before Proton is reached.
|
||||
verb=$1; shift
|
||||
here=$(dirname "$0")
|
||||
# See droiddeck-proton: the interposer goes first in LD_PRELOAD rather than the overlay being
|
||||
# removed, because glibc reads LD_PRELOAD before /etc/ld.so.preload and the overlay was simply
|
||||
# ahead of it on /dev/input.
|
||||
for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do
|
||||
if [ -f "$fake" ]; then
|
||||
case ":${LD_PRELOAD:-}:" in
|
||||
@@ -449,7 +385,6 @@ for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do
|
||||
esac
|
||||
fi
|
||||
done
|
||||
# See droiddeck-proton: library lookups that cannot succeed are skipped with the fast path.
|
||||
audit=/usr/local/lib/libblaudit.so
|
||||
if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
|
||||
case ":${LD_AUDIT:-}:" in
|
||||
@@ -461,12 +396,12 @@ bl_components "$here"
|
||||
bl_directaudio "$here"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_vacdiag "$@"
|
||||
bl_libpath
|
||||
BL_STORE_PROTON="$here/%s"; export BL_STORE_PROTON
|
||||
bl_store_launch "$@"
|
||||
BL_STORE_ARGS=("$@")
|
||||
# Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be
|
||||
# started from its own tree.
|
||||
bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$BL_STORE_PROTON" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
"""
|
||||
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
|
||||
{
|
||||
@@ -664,8 +599,6 @@ def adopt_extras(tools):
|
||||
manifest = os.path.join(tool_dir, "toolmanifest.vdf")
|
||||
if not os.path.isdir(tool_dir) or not os.path.isfile(manifest):
|
||||
continue
|
||||
# The shipped manifest is kept, once, and stays the source of the entry point: re-running
|
||||
# must not read back our own rewritten commandline and wrap the wrapper.
|
||||
original = manifest + ORIGINAL_SUFFIX
|
||||
legacy = manifest + LEGACY_ORIGINAL_SUFFIX
|
||||
if not os.path.isfile(original) and os.path.isfile(legacy):
|
||||
@@ -688,12 +621,10 @@ def adopt_extras(tools):
|
||||
name = first_key(compat_vdf, ["compatibilitytools", "compat_tools"]) or entry
|
||||
wrapper = os.path.join(tool_dir, EXTRA_WRAPPER)
|
||||
try:
|
||||
# Formatted first, spliced second: the function carries a printf %s and a
|
||||
# ${major%%.*} of its own, and putting it through the format would eat both.
|
||||
body = (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
|
||||
write_changed(wrapper, body, 0o755)
|
||||
write_changed(manifest, EXTRA_MANIFEST_VDF)
|
||||
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
|
||||
@@ -707,19 +638,17 @@ def adopt_extras(tools):
|
||||
return adopted
|
||||
|
||||
|
||||
# Steam's own tools and runtimes live in steamapps beside the games; they are not titles and must
|
||||
# not be mapped to a compatibility tool.
|
||||
NOT_GAMES = frozenset((
|
||||
"228980", # Steamworks Common Redistributables
|
||||
"1070560", # Steam Linux Runtime 1.0 (scout)
|
||||
"1391110", # Steam Linux Runtime 2.0 (soldier)
|
||||
"1628350", # Steam Linux Runtime 3.0 (sniper)
|
||||
"1493710", # Proton Experimental
|
||||
"3127680", # FEX
|
||||
"4183110", # Steam Linux Runtime 4.0
|
||||
"4185400", # Steam Linux Runtime 4.0 - Arm64
|
||||
"4427310", # Proton Experimental (ARM64)
|
||||
"4628740", # Proton 11.0 (ARM64)
|
||||
"228980",
|
||||
"1070560",
|
||||
"1391110",
|
||||
"1628350",
|
||||
"1493710",
|
||||
"3127680",
|
||||
"4183110",
|
||||
"4185400",
|
||||
"4427310",
|
||||
"4628740",
|
||||
))
|
||||
|
||||
|
||||
@@ -769,6 +698,26 @@ def launch_programs(config):
|
||||
return found
|
||||
|
||||
|
||||
def launch_options(config):
|
||||
"""An app's launch options as Steam lists them: executable, arguments, working folder, type and oslist."""
|
||||
launch = config.get("launch") if isinstance(config, dict) else None
|
||||
found = []
|
||||
for key, option in launch.items() if isinstance(launch, dict) else ():
|
||||
if not isinstance(option, dict) or not option.get("executable"):
|
||||
continue
|
||||
settings = option.get("config") if isinstance(option.get("config"), dict) else {}
|
||||
found.append({
|
||||
"key": str(key),
|
||||
"executable": str(option["executable"]),
|
||||
"arguments": str(option.get("arguments", "")),
|
||||
"workingdir": str(option.get("workingdir", "")),
|
||||
"type": str(option.get("type", "")).lower(),
|
||||
"oslist": str(settings.get("oslist", "")).lower(),
|
||||
"betakey": str(settings.get("betakey", "")),
|
||||
})
|
||||
return found
|
||||
|
||||
|
||||
def appinfo_entries(path):
|
||||
import struct
|
||||
try:
|
||||
@@ -860,6 +809,7 @@ def appinfo_entries(path):
|
||||
"type": str(common.get("type", "")).lower(),
|
||||
"recommended": str(recommended),
|
||||
"launch": launch_programs(info.get("config")),
|
||||
"launch_options": launch_options(info.get("config")),
|
||||
}
|
||||
if app == STEAM_PLAY_MANIFESTS:
|
||||
extended = info.get("extended", {})
|
||||
@@ -896,17 +846,46 @@ def native_targets(steam_root, apps):
|
||||
return {}
|
||||
targets = {}
|
||||
for app, (oslist, osarch, kind) in appinfo_platforms(os.path.join(steam_root, "appcache", "appinfo.vdf"), wanted).items():
|
||||
if kind not in PLAYABLE_TYPES or "windows" in oslist or "linux" not in oslist:
|
||||
if kind not in PLAYABLE_TYPES or "linux" not in oslist:
|
||||
continue
|
||||
if "arm64" in osarch or "aarch64" in osarch:
|
||||
targets[app] = None
|
||||
continue
|
||||
if "windows" in oslist:
|
||||
targets[app] = NATIVE_CHOICE
|
||||
continue
|
||||
targets[app] = FEX_TOOL
|
||||
return targets
|
||||
|
||||
|
||||
def linux_runtime_tool(name):
|
||||
low = name.lower()
|
||||
return low == "fex" or low.startswith("steamlinuxruntime")
|
||||
def app_manifest(steam_root, app):
|
||||
for library in libraries(steam_root):
|
||||
try:
|
||||
with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f:
|
||||
return tokenize(f.read())
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def manifest_flags(tokens):
|
||||
for i in range(len(tokens) - 1):
|
||||
if tokens[i].lower() == '"stateflags"':
|
||||
value = tokens[i + 1].strip('"')
|
||||
return int(value) if value.isdigit() else 0
|
||||
return 0
|
||||
|
||||
|
||||
def tool_downloads(steam_root):
|
||||
"""(app, "install" or "update") for each tool the client has yet to install or bring up to date."""
|
||||
wanted = []
|
||||
for app in REQUIRED_TOOLS:
|
||||
tokens = app_manifest(steam_root, app)
|
||||
if tokens is None:
|
||||
wanted.append((app, "install"))
|
||||
elif not manifest_flags(tokens) & FULLY_INSTALLED or manifest_flags(tokens) & UPDATE_REQUIRED:
|
||||
wanted.append((app, "update"))
|
||||
return wanted
|
||||
|
||||
|
||||
def fex_missing(steam_root):
|
||||
@@ -985,21 +964,56 @@ def app_order(app):
|
||||
return (len(app), app)
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=()):
|
||||
DEFERRED_GAME_TOOL = object()
|
||||
NATIVE_CHOICE = object()
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
|
||||
native_choices=()):
|
||||
runnable = {n.lower() for n in runnable}
|
||||
installed = set(installed)
|
||||
picks = set(picks)
|
||||
native = native or {}
|
||||
overrides = overrides or {}
|
||||
managed = set(auto) if managed is None else set(managed)
|
||||
native_choices = set(native_choices)
|
||||
changes, kept = {}, {}
|
||||
if current.get("0", "") != default:
|
||||
changes["0"] = default
|
||||
for app in sorted((set(current) | installed | picks | set(auto)) - {"0"}, key=app_order):
|
||||
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides) | native_choices) - {"0"}, key=app_order):
|
||||
name = current.get(app, "")
|
||||
if app in overrides:
|
||||
target = overrides[app]
|
||||
if target is DEFERRED_GAME_TOOL:
|
||||
continue
|
||||
target = target or default
|
||||
if name != target:
|
||||
changes[app] = target
|
||||
if overrides[app] is None:
|
||||
kept[app] = target
|
||||
continue
|
||||
mine = auto.get(app)
|
||||
target = native.get(app, default)
|
||||
stale = unrunnable(name, runnable) or (app in native and linux_runtime_tool(name))
|
||||
if not name and app in native_choices:
|
||||
target = NATIVE_CHOICE
|
||||
stale = unrunnable(name, runnable)
|
||||
if name and not stale and (mine is None or name != mine):
|
||||
continue
|
||||
if target is NATIVE_CHOICE:
|
||||
if not name and (app in native_choices or app in current or app in managed):
|
||||
kept[app] = NATIVE_CHOICE
|
||||
continue
|
||||
target = default
|
||||
if target is None:
|
||||
if stale:
|
||||
target = default
|
||||
if name != target:
|
||||
changes[app] = target
|
||||
continue
|
||||
else:
|
||||
if name and app in managed and name == mine:
|
||||
changes[app] = None
|
||||
continue
|
||||
if not name and app not in installed and app not in picks:
|
||||
continue
|
||||
if name != target:
|
||||
@@ -1053,6 +1067,34 @@ def requested_tool(request, catalog):
|
||||
return None
|
||||
|
||||
|
||||
def game_requests(directory=None):
|
||||
value = read_json(state_path("games.json", directory))
|
||||
if value.get("version") != 1 or not isinstance(value.get("games"), dict):
|
||||
return {}
|
||||
return value["games"]
|
||||
|
||||
|
||||
def requested_games(requests, catalog, runnable=None):
|
||||
"""App id -> requested tool, None for inherit, or DEFERRED_GAME_TOOL while unavailable."""
|
||||
runnable = None if runnable is None else set(runnable)
|
||||
resolved = {}
|
||||
for app, request in requests.items():
|
||||
if not isinstance(app, str) or not re.fullmatch(r"[1-9][0-9]*", app) or int(app) > 0xFFFFFFFF:
|
||||
continue
|
||||
if request is None:
|
||||
resolved[app] = None
|
||||
continue
|
||||
if (not isinstance(request, dict) or not isinstance(request.get("dir"), str) or
|
||||
not request["dir"] or not isinstance(request.get("valve"), bool)):
|
||||
continue
|
||||
tool = requested_tool(request, catalog)
|
||||
if tool is None or runnable is not None and tool not in runnable:
|
||||
resolved[app] = DEFERRED_GAME_TOOL
|
||||
else:
|
||||
resolved[app] = tool
|
||||
return resolved
|
||||
|
||||
|
||||
def now_ms():
|
||||
import time
|
||||
return int(time.time() * 1000)
|
||||
@@ -1110,8 +1152,37 @@ def read_mapping(tokens, mapping):
|
||||
return current
|
||||
|
||||
|
||||
def read_config_mapping(config_path):
|
||||
"""Read per-app choices without creating or rewriting the client's mapping block."""
|
||||
try:
|
||||
with open(config_path, encoding="utf-8", errors="replace") as f:
|
||||
tokens = tokenize(f.read())
|
||||
except OSError:
|
||||
return None
|
||||
depth = 0
|
||||
for token in tokens:
|
||||
if token == "{":
|
||||
depth += 1
|
||||
elif token == "}":
|
||||
depth -= 1
|
||||
if depth < 0:
|
||||
return None
|
||||
if depth != 0:
|
||||
return None
|
||||
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
|
||||
if steam is None:
|
||||
return None
|
||||
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
|
||||
return read_mapping(tokens, mapping + steam + 1) if mapping is not None else {}
|
||||
|
||||
|
||||
def set_mapping(tokens, mapping, app, tool):
|
||||
block = find_block(tokens[mapping + 1:], [app])
|
||||
if tool is None:
|
||||
if block is not None:
|
||||
block += mapping + 1
|
||||
del tokens[block - 1:block_end(tokens, block) + 1]
|
||||
return
|
||||
if block is None:
|
||||
tokens[mapping + 1:mapping + 1] = [
|
||||
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"' if app == "0" else '"250"', "}"]
|
||||
@@ -1141,6 +1212,21 @@ def steam_running():
|
||||
return False
|
||||
|
||||
|
||||
def game_running():
|
||||
try:
|
||||
pids = [p for p in os.listdir("/proc") if p.isdigit()]
|
||||
except OSError:
|
||||
return False
|
||||
for pid in pids:
|
||||
try:
|
||||
with open("/proc/%s/cmdline" % pid, "rb") as f:
|
||||
if b"\0SteamLaunch\0AppId=" in f.read():
|
||||
return True
|
||||
except OSError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def live_helper_running(directory=None):
|
||||
try:
|
||||
with open(state_path("live.pid", directory)) as f:
|
||||
@@ -1151,7 +1237,8 @@ def live_helper_running(directory=None):
|
||||
return False
|
||||
|
||||
|
||||
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=()):
|
||||
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=(),
|
||||
linux_tool=FEX_TOOL):
|
||||
"""Writes the mapping: the "0" default and every title that follows it (see plan_mapping).
|
||||
With settle, the default itself is decided first (see choose_default): before the client
|
||||
starts, config.vdf holds what the client last kept, menu changes included."""
|
||||
@@ -1174,13 +1261,23 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
else:
|
||||
default = state.get("default") if state.get("default") in names else TOOL
|
||||
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
|
||||
changes, auto = plan_mapping(current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks)
|
||||
overrides = requested_games(game_requests(directory), catalog)
|
||||
managed = state.get("auto", {}).keys() if isinstance(state.get("auto"), dict) else ()
|
||||
native_choices = state.get("native_choices", ())
|
||||
native = native_targets(steam_root, set(apps) | set(picks) | set(managed) | set(native_choices))
|
||||
if linux_tool != FEX_TOOL:
|
||||
native = {app: linux_tool if tool == FEX_TOOL else tool for app, tool in native.items()}
|
||||
changes, auto = plan_mapping(
|
||||
current, apps, names, default, followers(state, current), native, picks,
|
||||
overrides, managed, native_choices)
|
||||
for app, tool in changes.items():
|
||||
set_mapping(tokens, mapping, app, tool)
|
||||
text = serialize(tokens)
|
||||
if text != serialize(tokenize(original)):
|
||||
write_changed(config_path, text)
|
||||
state["auto"] = auto
|
||||
state["auto"] = {app: tool for app, tool in auto.items() if tool is not NATIVE_CHOICE}
|
||||
state["native_choices"] = sorted(app for app, tool in auto.items() if tool is NATIVE_CHOICE)
|
||||
state.pop("native", None)
|
||||
state["tools"] = catalog
|
||||
state.setdefault("default", default)
|
||||
write_json(state_path("state.json", directory), state)
|
||||
@@ -1212,8 +1309,6 @@ def build_tool(tool_dir, depot, sources=SOURCES, name=TOOL):
|
||||
if os.path.islink(tool_dir):
|
||||
os.unlink(tool_dir)
|
||||
elif os.path.isdir(tool_dir) and set(os.listdir(tool_dir)) - set(OWN_FILES):
|
||||
# Earlier versions mirrored the depot in here as symlinks; start clean. A directory holding
|
||||
# only our own files is kept, and each file rewritten only when it changed.
|
||||
shutil.rmtree(tool_dir)
|
||||
os.makedirs(tool_dir, exist_ok=True)
|
||||
write_changed(os.path.join(tool_dir, "toolmanifest.vdf"), TOOL_MANIFEST_VDF)
|
||||
@@ -1238,8 +1333,71 @@ def remove_tool(tool_dir):
|
||||
shutil.rmtree(tool_dir)
|
||||
|
||||
|
||||
def local_tools(steam_root):
|
||||
"""The names of the compatibility tools installed in steam_root/compatibilitytools.d."""
|
||||
names = set()
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
try:
|
||||
entries = os.listdir(tools)
|
||||
except OSError:
|
||||
return names
|
||||
for entry in entries:
|
||||
try:
|
||||
with open(os.path.join(tools, entry, "compatibilitytool.vdf"), encoding="utf-8", errors="replace") as f:
|
||||
m = re.search(r'"compat_tools"\s*\{\s*"([^"]+)"', f.read())
|
||||
except OSError:
|
||||
continue
|
||||
if m:
|
||||
names.add(m.group(1).lower())
|
||||
return names
|
||||
|
||||
|
||||
def x64_repoint(steam_root, tool, live=False):
|
||||
"""The x86-64 client (droiddeck-steam-x64): its tools are arm64 wrappers that script makes and
|
||||
its Linux titles run as Linux builds (FEX), so only the entries the client aimed at a Proton it
|
||||
cannot start are repointed, to `tool`. Tools in its own compatibilitytools.d are kept: the
|
||||
wrappers include proton-cachyos-*-a64, which starts with "proton" like Valve's own.
|
||||
Returns the app ids repointed."""
|
||||
config = os.path.join(steam_root, "config", "config.vdf")
|
||||
if not tool or not os.path.isfile(config):
|
||||
return []
|
||||
with open(config, encoding="utf-8", errors="replace") as f:
|
||||
original = f.read()
|
||||
tokens = tokenize(original)
|
||||
mapping = mapping_block(tokens)
|
||||
if mapping is None:
|
||||
return []
|
||||
keep = local_tools(steam_root)
|
||||
moved = []
|
||||
current = read_mapping(tokens, mapping)
|
||||
if "0" not in current:
|
||||
set_mapping(tokens, mapping, "0", tool)
|
||||
for app, name in current.items():
|
||||
named = name.lower()
|
||||
# A tool named arm64 is never this client's (its wrappers are -a64), so this legacy name is always repointed.
|
||||
legacy = named == "droiddeck-proton-arm64"
|
||||
if (named.startswith("proton") or legacy) and named != tool.lower() \
|
||||
and (legacy or named not in keep):
|
||||
set_mapping(tokens, mapping, app, tool)
|
||||
if app != "0":
|
||||
moved.append(app)
|
||||
text = serialize(tokens)
|
||||
if text != serialize(tokenize(original)):
|
||||
write_changed(config, text)
|
||||
print("steam-compatibility: x86-64 client's Proton entries point at %s" % tool)
|
||||
# Steam reads a mapping changed while it runs only at its next start; the session restarts it (.bl-compat-pending).
|
||||
if moved and live:
|
||||
with open(os.path.join(os.path.expanduser("~"), ".bl-compat-pending"), "a") as f:
|
||||
f.write("".join("%s\n" % a for a in moved))
|
||||
print("steam-compatibility: repointed while the client runs: %s" % " ".join(moved))
|
||||
return moved
|
||||
|
||||
|
||||
def main():
|
||||
steam_root = sys.argv[1]
|
||||
if "--x64" in sys.argv[2:]:
|
||||
x64_repoint(steam_root, os.environ.get("BL_COMPAT_TOOL"), "--live" in sys.argv[2:])
|
||||
return
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
os.makedirs(tools, exist_ok=True)
|
||||
legacy = os.path.join(tools, LEGACY_TOOL)
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
/*
|
||||
* binfmt_misc for the desktop, which proot does not have: an exec of an x86 Linux program, a Windows
|
||||
* program, or a program or script on noexec shared storage goes to droiddeck-open --exec, which runs
|
||||
* it under FEX, Proton or its interpreter. x86 and Windows programs are caught before the exec: proot
|
||||
* loads a static x86 program as a native one, which dies on its first instruction, and execvp runs a
|
||||
* Windows program as a shell script. A program on noexec storage also passes access(X_OK), which KIO
|
||||
* and Qt ask before they start one. Only in the desktop session.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
@@ -27,7 +19,6 @@
|
||||
typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||
char *const[], char *const[]);
|
||||
|
||||
/* BINFMT_TEST: tools/tests builds it for the host, whose own x86 programs stand in for foreign ones. */
|
||||
#if defined(__aarch64__) || defined(BINFMT_TEST)
|
||||
|
||||
static int desktop(void) {
|
||||
@@ -35,7 +26,6 @@ static int desktop(void) {
|
||||
return value && value[0] == '1' && value[1] == 0;
|
||||
}
|
||||
|
||||
/* 1: x86 program or noexec storage, 2: Windows program, 3: script; 0 for anything else. */
|
||||
static int foreign(const char *path, int error) {
|
||||
if (!path || !strcmp(path, BINFMT_HANDLER)) return 0;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
@@ -52,7 +42,6 @@ static int foreign(const char *path, int error) {
|
||||
} else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) {
|
||||
kind = 3;
|
||||
}
|
||||
/* What the kernel refuses for its permissions stays refused; noexec storage has no execute bits to give. */
|
||||
struct statvfs vfs;
|
||||
int allowed = kind && (((st.st_mode & 0111) && error != EACCES) || (fstatvfs(fd, &vfs) == 0 && (vfs.f_flag & ST_NOEXEC)));
|
||||
close(fd);
|
||||
@@ -63,7 +52,6 @@ static int wanted(const char *path, int error) {
|
||||
return (error == ENOEXEC || error == ENOENT || error == EACCES) && desktop() && foreign(path, error);
|
||||
}
|
||||
|
||||
/* The program on PATH as execvp would find it, into [out]. */
|
||||
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;
|
||||
@@ -111,19 +99,16 @@ static int spawn_handler(pid_t *pid, const char *path, const posix_spawn_file_ac
|
||||
return real(pid, BINFMT_HANDLER, fa, attr, args, envp);
|
||||
}
|
||||
|
||||
/* Before an exec of [path]: an x86 or Windows program goes to the handler instead. */
|
||||
__attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, char *const argv[], char *const envp[]) {
|
||||
if (desktop() && foreign(path, ENOEXEC)) hand_off(path, argv, envp);
|
||||
}
|
||||
|
||||
/* After a failed exec of [path]: the handler takes it over, or the exec's own error stands. */
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error) {
|
||||
if (wanted(path, error)) hand_off(path, argv, envp);
|
||||
errno = error;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The same around execvp, for the program it finds on PATH. */
|
||||
__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) {
|
||||
char path[PATH_MAX];
|
||||
if (desktop() && lookup(file, path, sizeof path)) bl_binfmt_before(path, argv, envp);
|
||||
@@ -136,7 +121,6 @@ __attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *fil
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* After access(X_OK) of [path] was refused (pathcache.c): a program on noexec storage runs all the same. */
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode) {
|
||||
if (mode != X_OK || !desktop()) return 0;
|
||||
int runs = foreign(path, EACCES) != 0;
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
/*
|
||||
* The Steam client lists a whole content directory about ten times per file it creates, moves or
|
||||
* deletes, to match names case-insensitively. On Android's FUSE storage that made reserving space
|
||||
* quadratic. Listings under steamapps/ on FUSE are kept for at most DIR_TTL_NS and dropped on any
|
||||
* inotify event the client's own patched changes don't account for; directory timestamps alone
|
||||
* can't be trusted, as NTFS volumes report whole seconds. BL_NO_DIR_CACHE=1 turns it off.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
@@ -32,7 +25,6 @@
|
||||
#define FUSE_MAGIC 0x65735546
|
||||
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR)
|
||||
|
||||
/* The client is 64-bit; 32-bit builds only pass creates through. */
|
||||
#if __SIZEOF_POINTER__ == 8
|
||||
|
||||
_Static_assert(sizeof(struct dirent) == sizeof(struct dirent64), "dirent layouts differ");
|
||||
@@ -88,7 +80,6 @@ static long long now_ns(void) {
|
||||
return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
|
||||
}
|
||||
|
||||
/* A child shares the parent's inotify queue, so it stops keeping listings. */
|
||||
static void after_fork(void) {
|
||||
pthread_mutex_init(&lock, NULL);
|
||||
pthread_mutex_init(&oplock, NULL);
|
||||
@@ -100,7 +91,8 @@ static int enabled(void) {
|
||||
if (cached < 0) {
|
||||
const char *off = getenv("BL_NO_DIR_CACHE");
|
||||
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
|
||||
strstr(program_invocation_name, "steamrtarm64") != NULL && !(off && strcmp(off, "1") == 0);
|
||||
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
|
||||
strstr(program_invocation_name, "steamrt64") != NULL) && !(off && strcmp(off, "1") == 0);
|
||||
if (cached) pthread_atfork(NULL, NULL, after_fork);
|
||||
}
|
||||
return cached && !forked;
|
||||
@@ -162,7 +154,6 @@ static void unref(struct listing *l) {
|
||||
if (--l->refs == 0 && l->detached) destroy(l);
|
||||
}
|
||||
|
||||
/* The rest is called with lock held. */
|
||||
|
||||
static void release(int wd) {
|
||||
if (wd < 0 || notify < 0) return;
|
||||
@@ -179,7 +170,6 @@ static void detach(struct listing *l) {
|
||||
if (l->refs == 0) destroy(l);
|
||||
}
|
||||
|
||||
/* Takes the listing out of the table; freed now or when its last reader closes. */
|
||||
static void drop(int slot) {
|
||||
struct listing *l = table[slot];
|
||||
int wd = l->wd;
|
||||
@@ -195,7 +185,6 @@ static void changed(int wd) {
|
||||
if (handles[i] && (handles[i]->wd == wd || wd < 0)) __atomic_store_n(&handles[i]->dirty, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
/* Applies queued events; the expected ones are the client's own changes, already patched in. */
|
||||
static void pump(struct expect *x, int nx) {
|
||||
char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
|
||||
if (notify < 0 || forked) return;
|
||||
@@ -268,9 +257,10 @@ static void install(struct listing *l) {
|
||||
int slot = find(l->dev, l->ino);
|
||||
if (slot >= 0) {
|
||||
struct listing *old = table[slot];
|
||||
int old_wd = old->wd;
|
||||
table[slot] = l;
|
||||
detach(old);
|
||||
if (old->wd != l->wd) release(old->wd);
|
||||
if (old_wd != l->wd) release(old_wd);
|
||||
return;
|
||||
}
|
||||
int victim = -1;
|
||||
@@ -302,7 +292,6 @@ static DIR *wrap(struct handle *h) {
|
||||
|
||||
#define RECLEN(namelen) ((offsetof(struct dirent64, d_name) + (namelen) + 1 + 7) & ~(size_t)7)
|
||||
|
||||
/* The listing as packed dirent64 records, built once per version. */
|
||||
static int records(struct listing *l) {
|
||||
if (l->recs) return 0;
|
||||
size_t len = 0;
|
||||
@@ -326,7 +315,6 @@ static int records(struct listing *l) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Lock-free from here on unless noted: a stream is only ever used by one thread at a time. */
|
||||
|
||||
static struct handle *lookup(DIR *d) {
|
||||
return registered(d) >= 0 ? (struct handle *)d : NULL;
|
||||
@@ -356,7 +344,6 @@ REAL(symlink);
|
||||
REAL(readdir64_r);
|
||||
REAL(readdir_r);
|
||||
|
||||
/* Resolved before the client starts threads; the calls below only fill gaps for earlier callers. */
|
||||
__attribute__((constructor)) static void resolve(void) {
|
||||
NEXT(opendir);
|
||||
NEXT(readdir64);
|
||||
@@ -378,7 +365,6 @@ __attribute__((constructor)) static void resolve(void) {
|
||||
}
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
/* A reader of the kept listing when it is still current. */
|
||||
static DIR *hit(const struct stat *st, struct handle *h, long long now) {
|
||||
pthread_mutex_lock(&lock);
|
||||
if (!changing) pump(NULL, 0);
|
||||
@@ -401,7 +387,6 @@ static DIR *hit(const struct stat *st, struct handle *h, long long now) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Registers the stream and its watch before anything is read, so no change goes unseen. */
|
||||
static int track(struct handle *h, const char *path) {
|
||||
pthread_mutex_lock(&lock);
|
||||
h->wd = watch(path);
|
||||
@@ -411,7 +396,6 @@ static int track(struct handle *h, const char *path) {
|
||||
return d != NULL;
|
||||
}
|
||||
|
||||
/* Reads through the real stream, keeping what it returns. */
|
||||
static void filling(struct handle *h, DIR *real, const struct stat *st, long long now) {
|
||||
h->real = real;
|
||||
h->fill = calloc(1, sizeof(*h->fill));
|
||||
@@ -625,7 +609,6 @@ static int watching(const char *path) {
|
||||
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
|
||||
}
|
||||
|
||||
/* Called with oplock held: the client's tracked changes happen one at a time. */
|
||||
static void begin(void) {
|
||||
pthread_mutex_lock(&lock);
|
||||
pump(NULL, 0);
|
||||
@@ -639,7 +622,6 @@ static void before(struct side *s) {
|
||||
|
||||
enum { ADDED, REMOVED };
|
||||
|
||||
/* Patches the listing after the client's own change, or drops it when unsure. Called with lock held. */
|
||||
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct expect *x) {
|
||||
struct stat now;
|
||||
if (!s->known) return 0;
|
||||
@@ -795,7 +777,6 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
|
||||
return r; \
|
||||
}
|
||||
|
||||
/* A refused hard link to a lock file is taken as a symlink (links.c). */
|
||||
int bl_link_lock(const char *oldpath, const char *newpath, int result) __attribute__((visibility("hidden")));
|
||||
static int link_or_lock(const char *from, const char *to) { return bl_link_lock(from, to, next_link(from, to)); }
|
||||
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
/*
|
||||
* GEM handle emulation for the KGSL device presented as a DRM render node.
|
||||
*
|
||||
* Compositors and Mesa validate or convert dma-bufs with PRIME ioctls on the render node; KGSL
|
||||
* has no GEM. Handles only serve as tokens to these callers, so a table of duplicated dma-buf
|
||||
* descriptors stands in for the kernel's, and every other device is left to libdrm.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -19,7 +12,6 @@
|
||||
|
||||
#define MAX_HANDLES 4096
|
||||
|
||||
/* DRM_IOCTL_GEM_CLOSE from drm.h: _IOW('d', 0x09, struct drm_gem_close { u32 handle, pad; }). */
|
||||
struct gem_close {
|
||||
uint32_t handle;
|
||||
uint32_t pad;
|
||||
@@ -36,7 +28,7 @@ static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct handle_entry handle_entries[MAX_HANDLES];
|
||||
static uint32_t next_handle = 1;
|
||||
static dev_t kgsl_dev;
|
||||
static int kgsl_state; /* 0 unknown, 1 known, -1 absent */
|
||||
static int kgsl_state;
|
||||
|
||||
static int is_kgsl(int fd) {
|
||||
struct stat st;
|
||||
@@ -63,7 +55,7 @@ static int same_file_description(int a, int b) {
|
||||
}
|
||||
#ifdef SYS_kcmp
|
||||
int saved_errno = errno;
|
||||
long ret = syscall(SYS_kcmp, getpid(), getpid(), 0 /* KCMP_FILE */, a, b);
|
||||
long ret = syscall(SYS_kcmp, getpid(), getpid(), 0 , a, b);
|
||||
errno = saved_errno;
|
||||
return ret == 0;
|
||||
#else
|
||||
@@ -81,11 +73,6 @@ static int find_handle_locked(int fd, uint32_t handle) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* The old table used its slot index as the public handle. Once #275 started freeing slots,
|
||||
* rapidly recreated swapchains immediately reused those numbers. Keep storage slots reusable but
|
||||
* make the public token monotonic so a stale handle can fail instead of aliasing a newer buffer.
|
||||
*/
|
||||
static uint32_t alloc_handle_locked(void) {
|
||||
for (int tries = 0; tries <= MAX_HANDLES; tries++) {
|
||||
uint32_t candidate = next_handle++;
|
||||
@@ -157,7 +144,6 @@ int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Drops only a handle belonging to this KGSL file description. */
|
||||
static int release_handle(int fd, uint32_t handle) {
|
||||
int found = 0;
|
||||
pthread_mutex_lock(&lock);
|
||||
@@ -179,16 +165,6 @@ int drmCloseBufferHandle(int fd, uint32_t handle) {
|
||||
return release_handle(fd, handle) ? 0 : -EINVAL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Zink gives its handles back with the GEM_CLOSE ioctl itself, not drmCloseBufferHandle
|
||||
* (zink_bo.c, bo_destroy). KGSL refuses the ioctl, so the duplicated descriptor stayed open and
|
||||
* kept the whole buffer alive. Preserve #275's reclamation without letting another KGSL file
|
||||
* description release the token or making a new buffer immediately inherit a retired token.
|
||||
*
|
||||
* Caught at ioctl() (netif.c), which libdrm's drmIoctl calls, rather than by exporting drmIoctl:
|
||||
* every session process preloads this library, and exporting drmIoctl from it brought on a
|
||||
* judder replaying old frames in No Man's Sky on an Adreno 840 even with no handle released.
|
||||
*/
|
||||
__attribute__((visibility("hidden"))) int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) {
|
||||
if (request != GEM_CLOSE || !arg || !is_kgsl(fd)) {
|
||||
return 0;
|
||||
@@ -202,12 +178,6 @@ __attribute__((visibility("hidden"))) int bl_drm_gem_close(int fd, unsigned long
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* fork() carries over only the calling thread, so a lock another thread was holding at that
|
||||
* instant stays held in the child by a thread that is not there to release it. Taking it before
|
||||
* the fork makes the copy consistent; the parent then unlocks it and the child, whose one thread
|
||||
* never locked it, gets a fresh one. (WinNative 79aa7f68.)
|
||||
*/
|
||||
static void drm_lock_before_fork(void) { pthread_mutex_lock(&lock); }
|
||||
static void drm_unlock_after_fork(void) { pthread_mutex_unlock(&lock); }
|
||||
static void drm_reset_after_fork(void) { pthread_mutex_init(&lock, NULL); }
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
/* droiddeck-fsync: futex_waitv(2) in userspace, so Proton's own fsync runs where the app sandbox refuses the syscall.
|
||||
* Credit: fsync, the futex-based synchronization in Proton, by Elizabeth Figura and Paul Gofman;
|
||||
* futex_waitv(2) by André Almeida. */
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
|
||||
@@ -1,58 +1,29 @@
|
||||
/*
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0, with names
|
||||
* changed to this project's. The reasoning below is the original author's.
|
||||
*
|
||||
* The session's controllers, described to libudev's callers.
|
||||
*
|
||||
* The pads are evdev nodes the app backs with its own input rings, bound over /dev/input. Wine's
|
||||
* HID bus finds them there, but it identifies a node by resolving /sys/class/input/<name> and
|
||||
* asking libudev about the result: on Android that resolves to whatever real input device the
|
||||
* host numbered the same, whose device node libudev cannot read, so every pad is discarded before
|
||||
* its identity is ever looked at. The fallback is Wine's SDL bus, and SDL enumerates through udev
|
||||
* too, over a netlink socket the app sandbox refuses. A game was left with no controller at all
|
||||
* while the Steam client, which reads the nodes itself, had one.
|
||||
*
|
||||
* So the pads are described here instead: the resolved path is answered for the session's own
|
||||
* nodes, and libudev's accessors answer for that path from what the app already knows. They carry
|
||||
* the identity of the pad Steam Input would present if it could - it has no /dev/uinput here to
|
||||
* make one - which is the one identity Wine's own bus keeps rather than handing on to SDL.
|
||||
*
|
||||
* Only Wine's device host is answered, and only for the session's own nodes: the Steam client
|
||||
* enumerates the same nodes for itself and would take a pad wearing Steam Input's identity for one
|
||||
* of its own and ignore it. Every other caller, path and device object goes straight through.
|
||||
*
|
||||
* With libfakeinput's /dev/uinput stand-in (FAKE_EVDEV_UINPUT=1) Steam Input's own virtual pads
|
||||
* exist too, as event16 and up, and those are what Wine is meant to read: each is described with
|
||||
* the identity the client gave it, from the .uevent file libfakeinput writes beside the node.
|
||||
* While one exists the app's pads are described as what they are, an Xbox 360 controller, which
|
||||
* Wine's HID bus leaves alone - the game reads Steam Input's output, not the pad under it, as on
|
||||
* a Steam Deck. With none (Steam Input off for the game) they keep the virtual identity, so the
|
||||
* game still has a controller.
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <limits.h>
|
||||
#include <linux/input.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/sysmacros.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
/* The app opens one ring per configured controller; four is what its launcher offers. Nodes from
|
||||
* UINPUT_BASE up are the virtual pads made through libfakeinput's /dev/uinput stand-in. */
|
||||
#define RING_MAX 4
|
||||
#define UINPUT_BASE 16
|
||||
#define PAD_MAX 64
|
||||
#define EVENT_MINOR_BASE 64
|
||||
|
||||
/* BUS_VIRTUAL, and the identity Steam Input gives the gamepad it presents to a game. */
|
||||
#define PAD_UEVENT_FORMAT \
|
||||
"PRODUCT=6/28de/11ff/110\n" \
|
||||
"NAME=\"Generic HID Gamepad %d\"\n" \
|
||||
"PHYS=\"usb-fakeinput/input%d\"\n"
|
||||
|
||||
/* The identity libfakeinput gives the pad itself (FAKE_EVDEV_IDENTITY=xbox360). */
|
||||
#define PAD_PHYSICAL_UEVENT_FORMAT \
|
||||
"PRODUCT=3/45e/28e/110\n" \
|
||||
"NAME=\"Xbox 360 Controller (%d)\"\n" \
|
||||
@@ -70,11 +41,6 @@ static struct pad pads[PAD_MAX];
|
||||
static int pad_count;
|
||||
static pthread_mutex_t virtual_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
/*
|
||||
* The slots the app published rings for, named in FAKE_EVDEV_MEMFD_PATHS as "<slot>=<path>"
|
||||
* separated by semicolons. Without it the process has no pads of the session's and every call
|
||||
* here is a passthrough.
|
||||
*/
|
||||
static void discover_pads(void) {
|
||||
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
||||
const char *entry;
|
||||
@@ -113,7 +79,6 @@ static int uinput_enabled(void) {
|
||||
return enabled != NULL && atoi(enabled) != 0;
|
||||
}
|
||||
|
||||
/* Reads the .uevent libfakeinput wrote for virtual pad <node> into buf; 0 when there is none. */
|
||||
static int read_virtual_uevent(int node, char *buf, size_t size) {
|
||||
const char *dir = getenv("FAKE_EVDEV_DIR");
|
||||
char path[PATH_MAX];
|
||||
@@ -138,10 +103,6 @@ static int any_virtual_pad(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Brings the entry for event<node> up to date before Wine resolves it: a virtual pad comes and
|
||||
* goes with the client, and the app's pads change identity with it.
|
||||
*/
|
||||
static void refresh_pad(int node) {
|
||||
struct pad *pad;
|
||||
|
||||
@@ -168,7 +129,6 @@ static void refresh_pad(int node) {
|
||||
pthread_mutex_unlock(&virtual_lock);
|
||||
}
|
||||
|
||||
/* The pad a synthetic syspath names, or NULL when the path is not one of ours. */
|
||||
static struct pad *pad_for_syspath(const char *syspath) {
|
||||
int i;
|
||||
|
||||
@@ -180,7 +140,6 @@ static struct pad *pad_for_syspath(const char *syspath) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* A device object is ours exactly when it is one of the pads. */
|
||||
static struct pad *pad_for_device(void *device) {
|
||||
int i;
|
||||
|
||||
@@ -192,7 +151,6 @@ static struct pad *pad_for_device(void *device) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The pad /sys/class/input/<name> stands for, or NULL when the path names something else. */
|
||||
static struct pad *pad_for_syslink(const char *path) {
|
||||
static const char prefix[] = "/sys/class/input/";
|
||||
const char *name;
|
||||
@@ -213,7 +171,6 @@ static void *next_symbol(const char *name) { return dlsym(RTLD_NEXT, name); }
|
||||
char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *))
|
||||
__attribute__((visibility("hidden")));
|
||||
|
||||
/* Wine reaches libudev from its HID bus driver, which is the only caller these pads are for. */
|
||||
static int caller_is_winebus(void *caller) {
|
||||
Dl_info info;
|
||||
|
||||
@@ -221,6 +178,24 @@ static int caller_is_winebus(void *caller) {
|
||||
return strstr(info.dli_fname, "winebus.so") != NULL;
|
||||
}
|
||||
|
||||
/* Wine's HID haptics give every XInput rumble a 1000 ms cutoff and xinput only writes on a change,
|
||||
* but XInput motors hold their speed until the next XInputSetState; evdev's length 0 holds until
|
||||
* stopped. Only this library, preloaded first, sees winebus as the caller. The length is put back
|
||||
* because winebus compares its copy with the next state to decide whether to upload again. */
|
||||
__attribute__((visibility("hidden"))) int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd,
|
||||
unsigned long request, void *arg, void *caller,
|
||||
int *rc) {
|
||||
struct ff_effect *effect = arg;
|
||||
__u16 length;
|
||||
|
||||
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE || !caller_is_winebus(caller)) return 0;
|
||||
length = effect->replay.length;
|
||||
effect->replay.length = 0;
|
||||
*rc = real(fd, request, arg);
|
||||
effect->replay.length = length;
|
||||
return 1;
|
||||
}
|
||||
|
||||
char *realpath(const char *path, char *resolved) {
|
||||
static char *(*real_realpath)(const char *, char *);
|
||||
void *caller = __builtin_return_address(0);
|
||||
@@ -228,7 +203,6 @@ char *realpath(const char *path, char *resolved) {
|
||||
|
||||
if (pad != NULL) {
|
||||
if (resolved == NULL) return strdup(pad->syspath);
|
||||
/* PATH_MAX is what the caller promises when it passes a buffer. */
|
||||
memcpy(resolved, pad->syspath, strlen(pad->syspath) + 1);
|
||||
return resolved;
|
||||
}
|
||||
@@ -336,10 +310,6 @@ dev_t udev_device_get_devnum(void *device) {
|
||||
return real_get(device);
|
||||
}
|
||||
|
||||
/*
|
||||
* A pad has no bus behind it, so it stands in for its own input device and has no other parent.
|
||||
* The reference is a borrowed one either way.
|
||||
*/
|
||||
void *udev_device_get_parent_with_subsystem_devtype(void *device, const char *subsystem,
|
||||
const char *devtype) {
|
||||
static void *(*real_get)(void *, const char *, const char *);
|
||||
|
||||
@@ -1,16 +1,3 @@
|
||||
/*
|
||||
* Adreno revisions the runtime's Turnip does not know, reported as the revision it does.
|
||||
*
|
||||
* Retail SM8850 phones report their A840 as chip_id 0x44050A21 (KGSL gpu_model "Adreno840v2").
|
||||
* Mesa only lists 0x44050A31, so the runtime's glibc Turnip refuses the device outright
|
||||
* ("device (chip_id = 44050A21, gpu_id = 6860) is unsupported") and gamescope exits before Steam
|
||||
* starts. Banners-Turnip fixes its own builds by registering the v2 id on the same A840 GPU info
|
||||
* (patches/a840v2.py); answering KGSL's device-info query with the known id has the same effect
|
||||
* on any Turnip in the session, including the one the runtime was built with. A driver that
|
||||
* already knows the v2 id resolves the rewritten one to the same entry.
|
||||
*
|
||||
* Only the KGSL device-info property is touched. Its layout is the kernel's uapi (msm_kgsl.h).
|
||||
*/
|
||||
#define _GNU_SOURCE 1
|
||||
#include <stddef.h>
|
||||
#include <sys/ioctl.h>
|
||||
@@ -38,7 +25,7 @@ static const struct {
|
||||
unsigned int reported;
|
||||
unsigned int known;
|
||||
} CHIP_IDS[] = {
|
||||
{0x44050A21, 0x44050A31}, /* Adreno 840v2 -> Adreno 840 */
|
||||
{0x44050A21, 0x44050A31},
|
||||
};
|
||||
|
||||
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc) {
|
||||
|
||||
@@ -1,19 +1,3 @@
|
||||
/*
|
||||
* A zero-timeout KGSL timestamp wait answered as the poll it was meant to be.
|
||||
*
|
||||
* Turnip's KGSL backend emulates timeline semaphores with timestamps, and asks "has this one
|
||||
* retired yet?" by waiting on it with IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID and a timeout of 0.
|
||||
* KGSL reads a timeout of 0 as no timeout at all, so the poll blocks until the GPU gets there.
|
||||
* Mesa's timeline bookkeeping polls like that under a lock on every signalling submit, which put
|
||||
* vkd3d-proton, DXVK, gamescope and Zink in lock-step with the GPU: one frame queued, never two.
|
||||
* Found and measured by Bannerlator (PROGRESS_LOG 2026-09-29: a D3D12 demo went from 614 to
|
||||
* 4335 fps with the same answer given in its Vulkan adapter); the driver-side fix is on
|
||||
* Banners-Turnip, and this covers the drivers that do not carry it yet.
|
||||
*
|
||||
* The answer comes from the context's retired timestamp, compared the way KGSL compares them
|
||||
* (with wrap-around). Anything the read does not answer - an unknown context, a device that is not
|
||||
* KGSL - goes to the kernel as before. BL_NO_KGSL_POLL_FIX=1 turns it off.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <stdint.h>
|
||||
@@ -50,7 +34,6 @@ static int enabled(void) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
/* True when the call was answered here, with its result in *rc (and errno set on failure). */
|
||||
__attribute__((visibility("hidden"))) int bl_kgsl_poll(int (*real)(int, unsigned long, void *),
|
||||
int fd, unsigned long request, void *arg,
|
||||
int *rc) {
|
||||
|
||||
@@ -1,22 +1,3 @@
|
||||
/*
|
||||
* Lock files taken by hard link, which Android denies apps.
|
||||
*
|
||||
* libICE and libXau lock an authority file the classic way: create "<file>-c", then link() it to
|
||||
* "<file>-l" - the link either appears or fails because the other holder's is there. Android's
|
||||
* SELinux policy refuses hard links in an app's data, so the link fails for everyone, the lock is
|
||||
* never taken, and Plasma's session manager gives up at "Could not lock ICEAuthority file". With
|
||||
* no session manager there is no Plasma desktop.
|
||||
*
|
||||
* Only that convention is answered here: when the real link is refused and the new name ends in
|
||||
* "-l", a symlink stands in. Creating a symlink fails on an existing name just as a link does, so
|
||||
* the lock excludes as before, and the holder removes both names when it is done. Every other
|
||||
* link keeps the real answer: a program that links a file into place and then deletes the
|
||||
* original would be left with a dangling symlink.
|
||||
*
|
||||
* That pattern itself is answered for one caller that asks: with DROIDDECK_LINK_RENAME=1 (the
|
||||
* session sets it for localedef, which names a finished locale archive that way) a refused link
|
||||
* becomes a rename that will not replace an existing name, which is all the link promised there.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -38,9 +19,7 @@ static int lock_name(const char *path) {
|
||||
return n > 2 && strcmp(path + n - 2, "-l") == 0;
|
||||
}
|
||||
|
||||
/* The answer to link(oldpath, newpath), given the real call's: a refused lock link becomes a symlink. */
|
||||
__attribute__((visibility("hidden"))) int bl_link_lock(const char *oldpath, const char *newpath, int result) {
|
||||
/* libc's own symlink: dircache.c's wrapper may be holding its lock around this call. */
|
||||
static int (*real_symlink)(const char *, const char *);
|
||||
if (result == 0 || !refused(errno)) return result;
|
||||
if (moves_instead()) return renameat2(AT_FDCWD, oldpath, AT_FDCWD, newpath, RENAME_NOREPLACE);
|
||||
@@ -49,7 +28,6 @@ __attribute__((visibility("hidden"))) int bl_link_lock(const char *oldpath, cons
|
||||
return real_symlink(oldpath, newpath);
|
||||
}
|
||||
|
||||
/* 64-bit builds wrap link() in dircache.c, which hands its result to bl_link_lock. */
|
||||
#if __SIZEOF_POINTER__ != 8
|
||||
int link(const char *oldpath, const char *newpath) {
|
||||
static int (*real_link)(const char *, const char *);
|
||||
@@ -64,7 +42,6 @@ int linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath,
|
||||
int result = real_linkat(olddirfd, oldpath, newdirfd, newpath, flags);
|
||||
if (result != 0 && refused(errno) && flags == 0 && moves_instead())
|
||||
return renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
|
||||
/* A relative old name would resolve against the new name's directory as a symlink's target. */
|
||||
if (result != 0 && refused(errno) && lock_name(newpath) && oldpath[0] == '/' && flags == 0)
|
||||
return symlinkat(oldpath, newdirfd, newpath);
|
||||
return result;
|
||||
|
||||
@@ -1,24 +1,7 @@
|
||||
/*
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0, with names
|
||||
* changed to this project's. The reasoning below is the original author's.
|
||||
*
|
||||
* File locking for the game library on external storage.
|
||||
*
|
||||
* The user's games are bound in from /storage/emulated, which Android serves over FUSE, and that
|
||||
* filesystem implements no locking at all: flock() and fcntl()'s lock commands answer ENOSYS for
|
||||
* every file under it. The Steam client takes a shared lock on each content file as it validates
|
||||
* or updates a title and treats the refusal as a failure, so a download walks its progress back
|
||||
* and forth instead of finishing; a game reading its own data hits the same wall.
|
||||
*
|
||||
* Where the kernel can lock, it does: the real call runs first and its answer stands, so files on
|
||||
* the app's own f2fs storage keep genuine cross-process exclusion. Only the filesystem that cannot
|
||||
* lock at all is answered here, and granting is the honest reading of it - a filesystem with no
|
||||
* lock state has nothing to contend over, and the one other party that could contend is inside
|
||||
* this same session. Reporting failure instead buys no safety and costs the download.
|
||||
*
|
||||
* F_GETLK is the exception: it asks who holds a lock, and on a filesystem holding none the true
|
||||
* answer is "nobody", so it is reported unlocked rather than granted.
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -28,7 +11,6 @@
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* The filesystem refuses the whole operation, rather than declining this particular lock. */
|
||||
static int unsupported(int error) {
|
||||
return error == ENOSYS || error == ENOTSUP || error == EOPNOTSUPP;
|
||||
}
|
||||
@@ -44,12 +26,6 @@ int flock(int fd, int operation) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* fcntl()'s third argument is an int, a pointer, or absent depending on the command; only the
|
||||
* lock commands are of interest here and all of those take a struct flock *. Anything else is
|
||||
* passed straight through as a void * - wide enough for both an int and a pointer on every ABI
|
||||
* the runtime is built for.
|
||||
*/
|
||||
static int is_lock_command(int cmd) {
|
||||
switch (cmd) {
|
||||
case F_SETLK:
|
||||
@@ -104,6 +80,5 @@ int fcntl(int fd, int cmd, ...) {
|
||||
}
|
||||
|
||||
#if defined(__GLIBC__) && defined(F_SETLK64)
|
||||
/* glibc's large-file build redirects both names; the runtime is 64-bit, so they are the same call. */
|
||||
int fcntl64(int fd, int cmd, ...) __attribute__((alias("fcntl")));
|
||||
#endif
|
||||
+44
-24
@@ -1,11 +1,3 @@
|
||||
/*
|
||||
* Loopback socket ownership for Steam's IPC peer check.
|
||||
*
|
||||
* Steam validates a websocket peer by running lsof to find which process owns a 127.0.0.1 port.
|
||||
* The Android sandbox denies both /proc/net/tcp and sock_diag, so no tool can answer. Every Steam
|
||||
* process is preloaded with this library, so each records the ports it binds and connects, and the
|
||||
* lsof Steam spawns is answered from that shared registry instead of being run.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <arpa/inet.h>
|
||||
#include <spawn.h>
|
||||
@@ -14,6 +6,7 @@
|
||||
#include <linux/netlink.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
@@ -54,8 +47,6 @@ static int loopback_family(const struct sockaddr *address, socklen_t length) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Record that this process owns a loopback socket on its local port; peer is the far end's port,
|
||||
* 0 for a listening socket. */
|
||||
static void record_port(int fd, unsigned peer) {
|
||||
struct sockaddr_storage ss;
|
||||
socklen_t len = sizeof(ss);
|
||||
@@ -119,7 +110,6 @@ typedef int (*connect_fn)(int, const struct sockaddr *, socklen_t);
|
||||
typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
|
||||
static unsigned guarded_port(void);
|
||||
|
||||
/* udevmon.c: a stand-in for the netlink socket the sandbox refuses, bound here without the kernel. */
|
||||
__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd);
|
||||
|
||||
int bind(int fd, const struct sockaddr *addr, socklen_t len) {
|
||||
@@ -239,7 +229,6 @@ int connect(int fd, const struct sockaddr *addr, socklen_t len) {
|
||||
if (peer) record_port(fd, peer);
|
||||
int ret = real(fd, addr, len);
|
||||
if (ret == 0 || errno == EINPROGRESS) {
|
||||
/* The caller goes on to test for EINPROGRESS, which the bookkeeping must not disturb. */
|
||||
int saved = errno;
|
||||
record_port(fd, peer);
|
||||
errno = saved;
|
||||
@@ -267,7 +256,6 @@ int accept(int fd, struct sockaddr *addr, socklen_t *len) {
|
||||
return accept4(fd, addr, len, 0);
|
||||
}
|
||||
|
||||
/* binfmt.c: an exec of a program the kernel cannot run, handed to droiddeck-open in the desktop. */
|
||||
extern char **environ;
|
||||
typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||
char *const[], char *const[]);
|
||||
@@ -275,12 +263,11 @@ __attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, ch
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error);
|
||||
__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]);
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
|
||||
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]);
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
|
||||
spawn_fn real);
|
||||
|
||||
/* lsof would read the denied /proc/net/tcp; answer its -i TCP@host:port query from the registry
|
||||
* instead of executing it. Recognised only when invoked as lsof with that query. */
|
||||
static int maybe_answer_lsof(const char *path, char *const argv[]) {
|
||||
const char *base = strrchr(path, '/');
|
||||
base = base ? base + 1 : path;
|
||||
@@ -302,7 +289,7 @@ static int maybe_answer_lsof(const char *path, char *const argv[]) {
|
||||
snprintf(path_buf, sizeof(path_buf), "%s/p%u", net_dir(), (unsigned)atoi(port_str));
|
||||
int in = open(path_buf, O_RDONLY);
|
||||
if (in < 0) {
|
||||
_exit(1); /* lsof exit code for "nothing found" */
|
||||
_exit(1);
|
||||
}
|
||||
char buf[64];
|
||||
int n = read(in, buf, sizeof(buf) - 1);
|
||||
@@ -314,28 +301,53 @@ static int maybe_answer_lsof(const char *path, char *const argv[]) {
|
||||
int pid = 0, ppid = 0, uid = 0;
|
||||
unsigned peer = 0;
|
||||
sscanf(buf, "%d %d %d %u", &pid, &ppid, &uid, &peer);
|
||||
/* Steam splits the address on "->" and wants exactly two halves, taking the port it asked
|
||||
* about from the left one; only a listening socket has no far end. */
|
||||
char out[160];
|
||||
int m = peer ? snprintf(out, sizeof(out), "p%d\nR%d\nu%d\nn127.0.0.1:%u->127.0.0.1:%u\n",
|
||||
pid, ppid, uid, (unsigned)atoi(port_str), peer)
|
||||
: snprintf(out, sizeof(out), "p%d\nR%d\nu%d\nn127.0.0.1:%u\n",
|
||||
pid, ppid, uid, (unsigned)atoi(port_str));
|
||||
if (write(1, out, m) != m) { /* best effort */ }
|
||||
if (write(1, out, m) != m) { }
|
||||
_exit(0);
|
||||
}
|
||||
|
||||
int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||
static char **web_helper_redirect(const char *path, char *const argv[], const char **launcher) {
|
||||
const char *want = getenv("BL_X64_ARM_WEBHELPER");
|
||||
if (!want || !*want || !path) return NULL;
|
||||
const char *base = strrchr(path, '/');
|
||||
if (strcmp(base ? base + 1 : path, "steamwebhelper") != 0) return NULL;
|
||||
if (!strstr(path, "/steamrt64/")) {
|
||||
char cwd[PATH_MAX];
|
||||
size_t n;
|
||||
if (path[0] == '/' || !getcwd(cwd, sizeof(cwd))) return NULL;
|
||||
n = strlen(cwd);
|
||||
if (n < 10 || strcmp(cwd + n - 10, "/steamrt64") != 0) return NULL;
|
||||
}
|
||||
int argc = 0;
|
||||
while (argv && argv[argc]) argc++;
|
||||
char **out = calloc((size_t)argc + 2, sizeof(char *));
|
||||
if (!out) return NULL;
|
||||
out[0] = (char *)want;
|
||||
for (int i = 1; i < argc; i++) out[i] = argv[i];
|
||||
*launcher = want;
|
||||
return out;
|
||||
}
|
||||
|
||||
int execve(const char *path, char *const argv_in[], char *const envp[]) {
|
||||
char *const *argv = bl_webhelper_argv(path, argv_in);
|
||||
static int (*real)(const char *, char *const[], char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execve");
|
||||
maybe_answer_lsof(path, argv);
|
||||
const char *launcher = NULL;
|
||||
char **redirected = web_helper_redirect(path, argv, &launcher);
|
||||
if (redirected) {
|
||||
real(launcher, redirected, envp);
|
||||
free(redirected);
|
||||
}
|
||||
bl_binfmt_before(path, argv, envp);
|
||||
real(path, argv, envp);
|
||||
return bl_binfmt_retry(path, argv, envp, errno);
|
||||
}
|
||||
|
||||
/* popen(3) and posix_spawn(3) reach lsof without going through the execve symbol above. The
|
||||
* check is cheap, so a spawned lsof is answered here too by handling it in a short-lived child. */
|
||||
static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pid) {
|
||||
pid_t child = fork();
|
||||
if (child < 0) {
|
||||
@@ -351,7 +363,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
|
||||
return 0;
|
||||
}
|
||||
|
||||
int execvp(const char *file, char *const argv[]) {
|
||||
int execvp(const char *file, char *const argv_in[]) {
|
||||
char *const *argv = bl_webhelper_argv(file, argv_in);
|
||||
static int (*real)(const char *, char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
|
||||
maybe_answer_lsof(file, argv);
|
||||
@@ -360,10 +373,17 @@ int execvp(const char *file, char *const argv[]) {
|
||||
return bl_binfmt_after_search(file, argv, environ, errno);
|
||||
}
|
||||
|
||||
int execv(const char *path, char *const argv[]) {
|
||||
int execv(const char *path, char *const argv_in[]) {
|
||||
char *const *argv = bl_webhelper_argv(path, argv_in);
|
||||
static int (*real)(const char *, char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execv");
|
||||
maybe_answer_lsof(path, argv);
|
||||
const char *launcher = NULL;
|
||||
char **redirected = web_helper_redirect(path, argv, &launcher);
|
||||
if (redirected) {
|
||||
real(launcher, redirected);
|
||||
free(redirected);
|
||||
}
|
||||
bl_binfmt_before(path, argv, environ);
|
||||
real(path, argv);
|
||||
return bl_binfmt_retry(path, argv, environ, errno);
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
/*
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0, with names
|
||||
* changed to this project's. The reasoning below is the original author's.
|
||||
*
|
||||
* Network interfaces for a sandbox that hides them.
|
||||
*
|
||||
* Android denies an app the rtnetlink dump behind getifaddrs() and if_nameindex(), the hardware
|
||||
* address ioctl, and every table under /proc/net. Wine builds its adapter, address, route and
|
||||
* neighbour tables from exactly those, so a game saw a machine with no adapter, no address, no
|
||||
* gateway and no MAC, and one that checks its adapters before going online waited for good.
|
||||
* The app knows the real link from ConnectivityManager and writes it to /etc/droiddeck-net;
|
||||
* whatever the kernel refuses is answered from that file. Anything the kernel does answer wins.
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE 1
|
||||
#include <arpa/inet.h>
|
||||
#include <dlfcn.h>
|
||||
@@ -108,9 +99,6 @@ static int fresh(long long *at) {
|
||||
return then != 0 && now_ns() - then < FRESH_NS;
|
||||
}
|
||||
|
||||
/* Wine's network driver reads the link several times for each table it builds, and some games
|
||||
* have it build them all hundreds of times a second. The app rewrites the file when the device
|
||||
* changes network, so a reading stands for a second. */
|
||||
static pthread_mutex_t link_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct link link_read;
|
||||
static int link_ok;
|
||||
@@ -128,7 +116,6 @@ static int load_link(struct link *link) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* See drm.c: a fork must not leave the lock held by a thread the child does not have. */
|
||||
static void link_lock_before_fork(void) { pthread_mutex_lock(&link_lock); }
|
||||
static void link_unlock_after_fork(void) { pthread_mutex_unlock(&link_lock); }
|
||||
static void link_reset_after_fork(void) { pthread_mutex_init(&link_lock, NULL); }
|
||||
@@ -137,8 +124,6 @@ __attribute__((constructor)) static void install_link_fork_handlers(void) {
|
||||
pthread_atfork(link_lock_before_fork, link_unlock_after_fork, link_reset_after_fork);
|
||||
}
|
||||
|
||||
/* When the kernel's own list was of no use, it is not asked again for a second: each asking binds
|
||||
* a netlink socket, a stop in the tracer, only to be refused again. */
|
||||
static long long ifaddrs_unusable_at, nameindex_unusable_at;
|
||||
|
||||
static void prefix_mask(int family, unsigned prefix, unsigned char *out) {
|
||||
@@ -152,8 +137,6 @@ static int is_link_local(const struct link_addr *addr) {
|
||||
return addr->family == AF_INET6 && addr->bytes[0] == 0xfe && (addr->bytes[1] & 0xc0) == 0x80;
|
||||
}
|
||||
|
||||
/* One allocation per list. ifa_data of the head points at the head itself, which glibc never
|
||||
* does, so freeifaddrs() can tell the two kinds of list apart without keeping any state. */
|
||||
struct entry {
|
||||
struct ifaddrs ifa;
|
||||
struct sockaddr_storage addr, mask, extra;
|
||||
@@ -246,7 +229,6 @@ int getifaddrs(struct ifaddrs **out) {
|
||||
if (asked) __atomic_store_n(&ifaddrs_unusable_at, now_ns(), __ATOMIC_RELAXED);
|
||||
if (rc == 0 && list) real_freeifaddrs(list);
|
||||
|
||||
/* A leading slot keeps fill_entry()'s back link in bounds; the list starts after it. */
|
||||
struct entry *block = calloc((size_t) link.addr_count + 5, sizeof(*block));
|
||||
if (block == NULL) {
|
||||
errno = ENOMEM;
|
||||
@@ -277,7 +259,6 @@ void freeifaddrs(struct ifaddrs *list) {
|
||||
real_freeifaddrs(list);
|
||||
}
|
||||
|
||||
/* Names live in the same allocation as the array, right behind it; glibc strdup()s each one. */
|
||||
struct name_block {
|
||||
struct if_nameindex index[3];
|
||||
char names[2][IFNAMSIZ];
|
||||
@@ -353,7 +334,6 @@ char *if_indextoname(unsigned int index, char name[IF_NAMESIZE]) {
|
||||
static int mac_unusable(const struct ifreq *ifr) {
|
||||
const unsigned char *a = (const unsigned char *) ifr->ifr_hwaddr.sa_data;
|
||||
if (ifr->ifr_hwaddr.sa_family != ARPHRD_ETHER) return 1;
|
||||
/* Android hands out 02:00:00:00:00:00 where it hides the real address. */
|
||||
int rest = a[1] | a[2] | a[3] | a[4] | a[5];
|
||||
return (a[0] & 0x03) || (rest == 0 && (a[0] == 0 || a[0] == 0x02));
|
||||
}
|
||||
@@ -420,14 +400,15 @@ static int is_link_query(unsigned long request) {
|
||||
|| request == SIOCGIFBRDADDR;
|
||||
}
|
||||
|
||||
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); /* kgslid.c */
|
||||
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc);
|
||||
#include "../../quest/kgsl_compat.h"
|
||||
int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
/* Every DRM and evdev call comes through here, so the lookup is done once. Two threads racing
|
||||
* to store it store the same pointer. */
|
||||
int ioctl(int fd, unsigned long request, ...) {
|
||||
typedef int (*ioctl_fn)(int, unsigned long, void *);
|
||||
static ioctl_fn real;
|
||||
@@ -440,7 +421,8 @@ int ioctl(int fd, unsigned long request, ...) {
|
||||
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
|
||||
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
|
||||
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
|
||||
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = real(fd, request, arg);
|
||||
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
|
||||
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
|
||||
bl_kgsl_chip_id_fixup(request, arg, rc);
|
||||
if (arg == NULL || !is_link_query(request)) return rc;
|
||||
int saved = errno;
|
||||
@@ -537,7 +519,6 @@ static const char *denied_table(const char *path) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* A memfd rather than fmemopen(): the stream owns its contents, so fclose() frees everything. */
|
||||
static FILE *synthesize(const char *table) {
|
||||
struct link link;
|
||||
if (!load_link(&link)) return NULL;
|
||||
@@ -557,12 +538,11 @@ static FILE *synthesize(const char *table) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* tracer.c */
|
||||
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
|
||||
|
||||
static FILE *open_stream(fopen_fn real, const char *path, const char *mode) {
|
||||
static FILE *open_stream(fopen_fn real, const char *path, const char *mode, const void *caller) {
|
||||
int status = mode && mode[0] == 'r' && !strchr(mode, '+')
|
||||
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC) : -1;
|
||||
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC, caller) : -1;
|
||||
if (status >= 0) {
|
||||
FILE *copy = fdopen(status, "r");
|
||||
if (copy == NULL) close(status);
|
||||
@@ -580,11 +560,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode) {
|
||||
FILE *fopen(const char *path, const char *mode) {
|
||||
static fopen_fn real;
|
||||
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen");
|
||||
return open_stream(real, path, mode);
|
||||
return open_stream(real, path, mode, __builtin_return_address(0));
|
||||
}
|
||||
|
||||
FILE *fopen64(const char *path, const char *mode) {
|
||||
static fopen_fn real;
|
||||
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen64");
|
||||
return open_stream(real, path, mode);
|
||||
return open_stream(real, path, mode, __builtin_return_address(0));
|
||||
}
|
||||
@@ -1,9 +1,3 @@
|
||||
/*
|
||||
* noexec.c: FEX runs an x86 program and its libraries where they lie, on noexec shared storage too.
|
||||
* FEX maps them with the guest's PROT_EXEC, which the kernel refuses for a file on a noexec mount,
|
||||
* but it never runs those pages itself - it runs its own translation of them - so a mapping or an
|
||||
* mprotect refused for that alone is made without PROT_EXEC. Only in FEX's own processes.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -12,7 +6,6 @@
|
||||
#include <sys/statvfs.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* NOEXEC_TEST: tools/tests builds it for the host. */
|
||||
#if defined(__aarch64__) || defined(NOEXEC_TEST)
|
||||
|
||||
static int in_fex(void) {
|
||||
@@ -28,7 +21,6 @@ static int in_fex(void) {
|
||||
return known;
|
||||
}
|
||||
|
||||
/* After an mmap failed (fsync.c's mmap asks): whether to map it again without PROT_EXEC. */
|
||||
__attribute__((visibility("hidden"))) int bl_noexec_retry(int prot, int flags, int fd) {
|
||||
int error = errno;
|
||||
struct statvfs vfs;
|
||||
@@ -40,7 +32,6 @@ __attribute__((visibility("hidden"))) int bl_noexec_retry(int prot, int flags, i
|
||||
|
||||
static int (*real_mprotect)(void *, size_t, int);
|
||||
|
||||
/* Looked up before anything runs: Wine calls mprotect from its signal handlers, where dlsym is unsafe. */
|
||||
__attribute__((constructor)) static void noexec_init(void) {
|
||||
real_mprotect = (int (*)(void *, size_t, int))dlsym(RTLD_NEXT, "mprotect");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
/* droiddeck-ntsync: a userspace implementation of the /dev/ntsync interface for kernels without the driver.
|
||||
* Credit: ntsync, the kernel driver and its Wine client, by Elizabeth Figura. */
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -1243,7 +1241,6 @@ int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_rec
|
||||
ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
|
||||
static ssize_t (*real)(int, struct msghdr *, int);
|
||||
if (!real) real = (ssize_t (*)(int, struct msghdr *, int))dlsym(RTLD_NEXT, "recvmsg");
|
||||
/* udevmon.c's stand-in netlink sockets first: their messages are dressed as udevd's. */
|
||||
ssize_t answered;
|
||||
if (msg && bl_udevmon_recvmsg(fd, msg, flags, real, &answered)) return answered;
|
||||
ssize_t r = real(fd, msg, flags);
|
||||
|
||||
@@ -1,29 +1,7 @@
|
||||
/*
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0, with names
|
||||
* changed to this project's. The reasoning below is the original author's.
|
||||
*
|
||||
* The adjustments a session's opens need.
|
||||
*
|
||||
* O_NOATIME on the game library: the user's games are bound in from shared storage, which Android
|
||||
* serves over FUSE with every file owned by its media provider rather than by the app. O_NOATIME
|
||||
* is reserved for a file's owner, so the kernel refuses such an open outright with EPERM. The
|
||||
* Steam client opens every content file it reads that way, and treats the refusal as the file
|
||||
* being unreadable or missing: a validation reports corrupt or missing files and an update is
|
||||
* cancelled. The flag only asks the filesystem to skip an access-time update; the open is retried
|
||||
* without it. Every other refusal is passed through untouched, and a file the process may open
|
||||
* with the flag still is.
|
||||
*
|
||||
* The kernel's trace marker: tracefs is world-writable here, so the client's tier0 opens
|
||||
* /sys/kernel/tracing/trace_marker at startup - three times over, once per module that profiles -
|
||||
* and writes a "[%s] tgid=%d begin_ctx=%lld" line for every scope it enters. Nothing in the
|
||||
* session reads those markers, and they are one more thing that can land in the wrong file when
|
||||
* a descriptor number changes hands (tracer.c has the cause). They have been found appended to an
|
||||
* app manifest, which the client then cannot parse, to a download's state file, and to content
|
||||
* chunks, which it quarantines as corrupt. Refused the descriptor, tier0 writes nothing at all and
|
||||
* has nothing to lose.
|
||||
*
|
||||
* A process status is served without the container's tracer in it; see tracer.c.
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -33,7 +11,7 @@
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
|
||||
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
|
||||
@@ -55,7 +33,6 @@ static int retry_without_noatime(int fd, int flags) {
|
||||
return fd < 0 && errno == EPERM && (flags & O_NOATIME);
|
||||
}
|
||||
|
||||
/* Both spellings tier0 tries, the debugfs one first. */
|
||||
static int is_trace_marker(const char *path) {
|
||||
return path != NULL
|
||||
&& (strcmp(path, "/sys/kernel/tracing/trace_marker") == 0
|
||||
@@ -74,7 +51,7 @@ int open(const char *path, int flags, ...) {
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
|
||||
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
|
||||
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
|
||||
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
|
||||
if (real_open == NULL) {
|
||||
@@ -83,7 +60,6 @@ int open(const char *path, int flags, ...) {
|
||||
}
|
||||
fd = bl_dircache_create(AT_FDCWD, path, flags, mode, via_open);
|
||||
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
|
||||
/* A read-only file the Steam client rewrites (perms.c). */
|
||||
if (fd < 0 && bl_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
|
||||
return fd;
|
||||
}
|
||||
@@ -100,7 +76,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
|
||||
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
|
||||
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
|
||||
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
|
||||
if (real_openat == NULL) {
|
||||
@@ -113,6 +89,5 @@ int openat(int dirfd, const char *path, int flags, ...) {
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* The runtime is 64-bit, so the large-file names are the same calls. */
|
||||
int open64(const char *path, int flags, ...) __attribute__((alias("open")));
|
||||
int openat64(int dirfd, const char *path, int flags, ...) __attribute__((alias("openat")));
|
||||
@@ -1,18 +1,3 @@
|
||||
/*
|
||||
* Path lookups the Steam client repeats, answered from a short-lived cache.
|
||||
*
|
||||
* While it registers its compatibility tools after logon, the client resolves the same few
|
||||
* directories - its local tools under compatibilitytools.d and its own platform directory - with
|
||||
* realpath() and access() thousands of times a second. Each realpath() is one readlinkat() per
|
||||
* path component, and under proot every one of those is a trapped syscall with a round trip
|
||||
* through the tracer. Measured on an AYN Thor, that loop was 23 of the client's 31 seconds of
|
||||
* startup, with proot busy for 16 of them.
|
||||
*
|
||||
* Only the client itself uses the cache, never a game or a helper. Only successful answers are
|
||||
* kept, and only for a moment: a path that stops existing is noticed within PATH_CACHE_TTL_NS, and
|
||||
* one that starts existing is never hidden, since failures always go to the filesystem.
|
||||
* BL_NO_PATH_CACHE=1 turns it off.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -57,7 +42,8 @@ static int enabled(void) {
|
||||
if (cached >= 0) return cached;
|
||||
off = getenv("BL_NO_PATH_CACHE");
|
||||
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
|
||||
strstr(program_invocation_name, "steamrtarm64") != NULL &&
|
||||
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
|
||||
strstr(program_invocation_name, "steamrt64") != NULL) &&
|
||||
!(off != NULL && off[0] == '1');
|
||||
return cached;
|
||||
}
|
||||
@@ -152,7 +138,6 @@ static int (*next_faccessat(void))(int, const char *, int, int) {
|
||||
return real;
|
||||
}
|
||||
|
||||
/* binfmt.c: a program on noexec storage, which the desktop runs all the same. */
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode);
|
||||
|
||||
static int check_cwd(const char *path, int mode, int flags) {
|
||||
|
||||
@@ -1,20 +1,3 @@
|
||||
/*
|
||||
* Root's way past a read-only file, for the Steam client.
|
||||
*
|
||||
* The client runs as "root" inside the session - the rootfs names the app's own uid root, and
|
||||
* proot (-i) shows it that uid - but the kernel treats it as the ordinary user it is. The client
|
||||
* leaves many content files read-only (r-x------,
|
||||
* ~290 files of Proton Experimental (ARM64) alone), and when an update later rewrites one of them
|
||||
* it opens the file for writing expecting root's permission to override the mode. The kernel
|
||||
* refuses (EACCES), the client reports "Missing file permissions" and cancels the update
|
||||
* (2026-09-26: Proton Experimental (ARM64), "CFileWriter: errno: 13 ... wineopenxr.dll").
|
||||
*
|
||||
* So for the client's own processes, a refused write-open of a file this user owns is answered the
|
||||
* way root's would be: the owner's write bit is added - to the file, or to the directory a new
|
||||
* file is being created in - and the open is tried once more. chmod only succeeds on what the app
|
||||
* owns, so nothing it could not already change is touched. Games, Wine and everything else keep
|
||||
* ordinary permissions: only the processes started from the client's own directories take this.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
@@ -24,15 +7,10 @@
|
||||
#include <unistd.h>
|
||||
|
||||
static int in_steam_dirs(const char *path) {
|
||||
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL
|
||||
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL || strstr(path, "/Steam/steamrt64/") != NULL
|
||||
|| strstr(path, "/Steam/ubuntu12_64/") != NULL || strstr(path, "/Steam/linuxarm64/") != NULL);
|
||||
}
|
||||
|
||||
/*
|
||||
* The client and its helpers run from the Steam root's platform directories. The kernel's
|
||||
* /proc/self/exe names proot's loader for every process in the session, so the program's own
|
||||
* name - the path it was started by - is asked as well.
|
||||
*/
|
||||
static int is_steam_client(void) {
|
||||
static int cached = -1;
|
||||
char exe[PATH_MAX];
|
||||
@@ -52,10 +30,6 @@ static int grant_owner_write(int dirfd, const char *path) {
|
||||
return fchmodat(dirfd, path, (st.st_mode & 07777) | S_IWUSR, 0) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* After an open refused with EACCES: returns 1 when a write bit was added and the open is worth
|
||||
* one more try. errno is left as the open set it.
|
||||
*/
|
||||
__attribute__((visibility("hidden")))
|
||||
int bl_writable_retry(int dirfd, const char *path, int flags) {
|
||||
int saved = errno;
|
||||
@@ -67,7 +41,6 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
|
||||
if (faccessat(dirfd, path, F_OK, 0) == 0) {
|
||||
granted = grant_owner_write(dirfd, path);
|
||||
} else if (flags & O_CREAT) {
|
||||
/* A new file in a read-only directory. */
|
||||
slash = strrchr(path, '/');
|
||||
if (slash == NULL) {
|
||||
granted = grant_owner_write(dirfd, ".");
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/* In Deck mode (-steamos3) the x86-64 client's SteamOS audio manager passes libpulse the NULL operation of a
|
||||
* failed request, and libpulse aborts on it ("Assertion 'o' failed ... pa_operation_get_state()"). */
|
||||
#if defined(__x86_64__) || defined(__i386__)
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct pa_operation pa_operation;
|
||||
|
||||
#define PA_OPERATION_CANCELLED 2
|
||||
|
||||
/* A libpulse loaded with RTLD_LOCAL (Wine's winepulse.so) is not in RTLD_NEXT's scope. */
|
||||
static void *libpulse(const char *name) {
|
||||
void *fn = dlsym(RTLD_NEXT, name);
|
||||
if (!fn) {
|
||||
void *handle = dlopen("libpulse.so.0", RTLD_LAZY | RTLD_NOLOAD);
|
||||
if (handle) {
|
||||
fn = dlsym(handle, name);
|
||||
dlclose(handle);
|
||||
}
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
|
||||
int pa_operation_get_state(pa_operation *o) {
|
||||
static int (*next)(pa_operation *);
|
||||
if (!o)
|
||||
return PA_OPERATION_CANCELLED;
|
||||
if (!next)
|
||||
next = (int (*)(pa_operation *))libpulse("pa_operation_get_state");
|
||||
return next ? next(o) : PA_OPERATION_CANCELLED;
|
||||
}
|
||||
|
||||
void pa_operation_unref(pa_operation *o) {
|
||||
static void (*next)(pa_operation *);
|
||||
if (!o)
|
||||
return;
|
||||
if (!next)
|
||||
next = (void (*)(pa_operation *))libpulse("pa_operation_unref");
|
||||
if (next)
|
||||
next(o);
|
||||
}
|
||||
|
||||
void pa_operation_cancel(pa_operation *o) {
|
||||
static void (*next)(pa_operation *);
|
||||
if (!o)
|
||||
return;
|
||||
if (!next)
|
||||
next = (void (*)(pa_operation *))libpulse("pa_operation_cancel");
|
||||
if (next)
|
||||
next(o);
|
||||
}
|
||||
#else
|
||||
typedef int pulseguard_arm_build_has_nothing_to_do;
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#include "../../quest/kgsl_compat.c"
|
||||
+178
-10
@@ -1,22 +1,19 @@
|
||||
/*
|
||||
* get_robust_list(2) for the session's own threads.
|
||||
*
|
||||
* Android's app policy refuses the call, and Steam's cross-process mutex insists on seeing the
|
||||
* head glibc registered. The kernel's list protocol gives it away: a robust mutex this thread
|
||||
* holds is linked directly behind the registered head, so locking a private one and following
|
||||
* the link back finds the head without depending on libc's layout.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <linux/futex.h>
|
||||
#include <linux/magic.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/vfs.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef SYS_openat2
|
||||
@@ -25,6 +22,17 @@
|
||||
|
||||
#define BL_RESOLVE_BENEATH 0x08
|
||||
#define BL_RESOLVE_IN_ROOT 0x10
|
||||
// The kernel's MAXSYMLINKS.
|
||||
#define BL_MAX_SYMLINKS 40
|
||||
#define BL_PROC_ROOT_INO 1
|
||||
|
||||
#ifdef SYS_newfstatat
|
||||
#define BL_SYS_FSTATAT SYS_newfstatat
|
||||
typedef struct stat bl_stat;
|
||||
#else
|
||||
#define BL_SYS_FSTATAT SYS_fstatat64
|
||||
typedef struct stat64 bl_stat;
|
||||
#endif
|
||||
|
||||
struct bl_open_how {
|
||||
uint64_t flags;
|
||||
@@ -33,8 +41,22 @@ struct bl_open_how {
|
||||
};
|
||||
|
||||
static long (*real_syscall)(long, ...);
|
||||
static void *(*real_dlopen)(const char *, int);
|
||||
static int openat2_missing;
|
||||
|
||||
void *dlopen(const char *filename, int flags) {
|
||||
if (!real_dlopen) {
|
||||
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
|
||||
}
|
||||
const char *basename = filename ? strrchr(filename, '/') : NULL;
|
||||
basename = basename ? basename + 1 : filename;
|
||||
// Steam's deep binding bypasses the robust-list shim under PRoot.
|
||||
if (basename && strcmp(basename, "vrclient.so") == 0) {
|
||||
flags &= ~RTLD_DEEPBIND;
|
||||
}
|
||||
return real_dlopen(filename, flags);
|
||||
}
|
||||
|
||||
int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
|
||||
|
||||
static struct robust_list_head *thread_robust_head(void) {
|
||||
@@ -48,8 +70,6 @@ static struct robust_list_head *thread_robust_head(void) {
|
||||
if (pthread_mutex_lock(&mutex) != 0) {
|
||||
return NULL;
|
||||
}
|
||||
/* The mutex holds tids and lock words beside the link, so a word is only followed
|
||||
* through a read that fails instead of faulting on a non-pointer. */
|
||||
uintptr_t lo = (uintptr_t)&mutex, hi = lo + sizeof(mutex);
|
||||
for (uintptr_t p = lo; p + sizeof(void *) <= hi && !head; p += sizeof(void *)) {
|
||||
struct robust_list_head *candidate = *(struct robust_list_head **)p;
|
||||
@@ -71,6 +91,151 @@ static struct robust_list_head *thread_robust_head(void) {
|
||||
return head;
|
||||
}
|
||||
|
||||
// Magic links are procfs links below a process's directory; procfs's root holds only plain ones (self, thread-self, mounts).
|
||||
static int is_magic_link(int dirfd, char *link, size_t parent_len) {
|
||||
int fd = (int)real_syscall(SYS_openat, (long)dirfd, (long)link, (long)(O_PATH | O_NOFOLLOW | O_CLOEXEC), 0L);
|
||||
if (fd < 0) {
|
||||
return 0;
|
||||
}
|
||||
struct statfs fs;
|
||||
int procfs = real_syscall(SYS_fstatfs, (long)fd, (long)&fs) == 0 && fs.f_type == PROC_SUPER_MAGIC;
|
||||
real_syscall(SYS_close, (long)fd);
|
||||
if (!procfs) {
|
||||
return 0;
|
||||
}
|
||||
char saved = link[parent_len];
|
||||
link[parent_len] = 0;
|
||||
bl_stat parent;
|
||||
long result = real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)(parent_len ? link : "."), (long)&parent, 0L);
|
||||
link[parent_len] = saved;
|
||||
return result != 0 || parent.st_ino != BL_PROC_ROOT_INO;
|
||||
}
|
||||
|
||||
// RESOLVE_IN_ROOT walked one component at a time: absolute symlinks restart at dirfd and ".." stops there.
|
||||
static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
|
||||
char resolved[PATH_MAX];
|
||||
char pending[PATH_MAX];
|
||||
size_t resolved_len = 0;
|
||||
int symlinks = 0;
|
||||
int have_root = 0;
|
||||
int root_on_procfs = 0;
|
||||
dev_t root_dev = 0;
|
||||
// O_NOFOLLOW and O_CREAT | O_EXCL leave a final symlink alone, unless a trailing slash follows it.
|
||||
int nofollow = (flags & O_NOFOLLOW) || (flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
|
||||
const char *rest = path;
|
||||
for (;;) {
|
||||
while (*rest == '/') {
|
||||
rest++;
|
||||
}
|
||||
if (!*rest) {
|
||||
break;
|
||||
}
|
||||
const char *name = rest;
|
||||
const char *end = name;
|
||||
while (*end && *end != '/') {
|
||||
end++;
|
||||
}
|
||||
size_t len = (size_t)(end - name);
|
||||
rest = end;
|
||||
while (*rest == '/') {
|
||||
rest++;
|
||||
}
|
||||
int last = !*rest;
|
||||
int trailing_slash = last && rest != end;
|
||||
if (len == 1 && name[0] == '.') {
|
||||
continue;
|
||||
}
|
||||
if (len == 2 && name[0] == '.' && name[1] == '.') {
|
||||
while (resolved_len > 0 && resolved[resolved_len - 1] != '/') {
|
||||
resolved_len--;
|
||||
}
|
||||
if (resolved_len > 0) {
|
||||
resolved_len--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
size_t separator = resolved_len > 0;
|
||||
size_t candidate_len = resolved_len + separator + len;
|
||||
if (candidate_len + 1 >= PATH_MAX) {
|
||||
errno = ENAMETOOLONG;
|
||||
return -1;
|
||||
}
|
||||
if (separator) {
|
||||
resolved[resolved_len] = '/';
|
||||
}
|
||||
memcpy(resolved + resolved_len + separator, name, len);
|
||||
resolved[candidate_len] = 0;
|
||||
bl_stat st;
|
||||
int follow = !last || trailing_slash || !nofollow;
|
||||
long stat_result = follow ? real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)resolved, (long)&st, (long)AT_SYMLINK_NOFOLLOW) : -1;
|
||||
if (stat_result == 0 && S_ISLNK(st.st_mode)) {
|
||||
if (++symlinks > BL_MAX_SYMLINKS) {
|
||||
errno = ELOOP;
|
||||
return -1;
|
||||
}
|
||||
if (!have_root) {
|
||||
bl_stat root;
|
||||
struct statfs root_fs;
|
||||
if (real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)".", (long)&root, 0L) != 0) {
|
||||
return -1;
|
||||
}
|
||||
root_dev = root.st_dev;
|
||||
root_on_procfs = real_syscall(SYS_fstatfs, (long)dirfd, (long)&root_fs) == 0 && root_fs.f_type == PROC_SUPER_MAGIC;
|
||||
have_root = 1;
|
||||
}
|
||||
if ((st.st_dev != root_dev || root_on_procfs) && is_magic_link(dirfd, resolved, resolved_len)) {
|
||||
// RESOLVE_IN_ROOT refuses magic links.
|
||||
errno = EXDEV;
|
||||
return -1;
|
||||
}
|
||||
size_t rest_len = strlen(end);
|
||||
if (rest_len + 1 >= PATH_MAX) {
|
||||
errno = ENAMETOOLONG;
|
||||
return -1;
|
||||
}
|
||||
char *tail = pending + PATH_MAX - rest_len - 1;
|
||||
memmove(tail, end, rest_len + 1);
|
||||
long target_len = real_syscall(SYS_readlinkat, (long)dirfd, (long)resolved, (long)pending, (long)(PATH_MAX - rest_len));
|
||||
if (target_len <= 0) {
|
||||
if (target_len == 0) {
|
||||
errno = ENOENT;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
if ((size_t)target_len + rest_len >= PATH_MAX) {
|
||||
errno = ENAMETOOLONG;
|
||||
return -1;
|
||||
}
|
||||
memmove(pending + target_len, tail, rest_len + 1);
|
||||
if (pending[0] == '/') {
|
||||
resolved_len = 0;
|
||||
}
|
||||
rest = pending;
|
||||
continue;
|
||||
}
|
||||
if (last) {
|
||||
resolved_len = candidate_len;
|
||||
if (trailing_slash) {
|
||||
resolved[resolved_len++] = '/';
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (stat_result != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (!S_ISDIR(st.st_mode)) {
|
||||
errno = ENOTDIR;
|
||||
return -1;
|
||||
}
|
||||
resolved_len = candidate_len;
|
||||
}
|
||||
if (resolved_len == 0) {
|
||||
resolved[resolved_len++] = '.';
|
||||
}
|
||||
resolved[resolved_len] = 0;
|
||||
return real_syscall(SYS_openat, (long)dirfd, (long)resolved, (long)flags, mode);
|
||||
}
|
||||
|
||||
static long openat2_via_openat(const long *args) {
|
||||
const char *path = (const char *)args[1];
|
||||
const struct bl_open_how *how = (const struct bl_open_how *)args[2];
|
||||
@@ -78,6 +243,9 @@ static long openat2_via_openat(const long *args) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
if ((how->resolve & BL_RESOLVE_IN_ROOT) && (int)args[0] != AT_FDCWD) {
|
||||
return openat_in_root((int)args[0], path, (int)how->flags, (long)how->mode);
|
||||
}
|
||||
if (how->resolve & BL_RESOLVE_IN_ROOT) {
|
||||
while (*path == '/') {
|
||||
path++;
|
||||
|
||||
@@ -1,23 +1,3 @@
|
||||
/*
|
||||
* The free space a library reports.
|
||||
*
|
||||
* A library's games can live somewhere the folder that names the library does not. The card
|
||||
* library is exactly that: its steamapps/common is bound to the card, but the directory above it
|
||||
* belongs to the runtime image in the phone's own storage, and that directory is what the client
|
||||
* measures. So it offers both install locations with the phone's free space against each, and the
|
||||
* card's real figure - seventeen gigabytes more, on the device this was found on - never appears.
|
||||
*
|
||||
* The number is not only cosmetic: the client refuses an install it believes will not fit. Once
|
||||
* the phone fills up it would turn down a card install with room to spare, and say nothing about
|
||||
* why.
|
||||
*
|
||||
* Moving the whole library onto the card would fix the number and break something worse. The
|
||||
* prefixes under steamapps/compatdata want symlinks and file locks, and the card is served over
|
||||
* FUSE, which gives us neither - that is why they are kept in the runtime image in the first
|
||||
* place. So the question is answered where the content actually is: a query about a library root
|
||||
* named in BL_LIBRARY_SPACE is served from its steamapps/common, the bind that points at the
|
||||
* card. Every other path is passed through untouched.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <stddef.h>
|
||||
@@ -26,8 +6,6 @@
|
||||
#include <sys/statfs.h>
|
||||
#include <sys/statvfs.h>
|
||||
|
||||
/* A library root, or its steamapps, resolved to the directory that holds the games. Returns the
|
||||
* rewritten path in `buf`, or NULL when `path` is not one of ours and should be left alone. */
|
||||
static const char *content_of(const char *path, char *buf, size_t len) {
|
||||
const char *roots = getenv("BL_LIBRARY_SPACE");
|
||||
if (!path || !roots || !*roots)
|
||||
@@ -38,8 +16,6 @@ static const char *content_of(const char *path, char *buf, size_t len) {
|
||||
const char *end = strchr(roots, ':');
|
||||
size_t root_len = end ? (size_t)(end - roots) : strlen(roots);
|
||||
if (root_len > 0) {
|
||||
/* The root itself, or the steamapps directly beneath it. Anything deeper is already inside
|
||||
* a bind and answers for itself. */
|
||||
int match = (path_len == root_len && !strncmp(path, roots, root_len)) ||
|
||||
(path_len == root_len + 10 && !strncmp(path, roots, root_len) &&
|
||||
!strcmp(path + root_len, "/steamapps"));
|
||||
|
||||
@@ -1,13 +1,3 @@
|
||||
/*
|
||||
* Opt-in observations for file allocation and writes to the selected Steam library.
|
||||
*
|
||||
* The session enables them only when storage diagnostics are turned on. Counters are local to
|
||||
* each process, allocation details are capped, writes are sampled, and storage.log has a global
|
||||
* size limit because every Steam child shares it.
|
||||
*
|
||||
* LD_PRELOAD cannot see direct syscalls or libc-internal calls that bypass public symbols. A
|
||||
* missing entry therefore does not prove the operation did not happen.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -126,7 +116,6 @@ static void append_line(const char *line, size_t length) {
|
||||
syscall(SYS_close, (long)fd, 0L, 0L, 0L, 0L, 0L);
|
||||
goto done;
|
||||
}
|
||||
/* One small append write per complete line; no per-write log flood. */
|
||||
(void)syscall(SYS_write, (long)fd, (long)line, (long)length, 0L, 0L, 0L);
|
||||
syscall(SYS_close, (long)fd, 0L, 0L, 0L, 0L, 0L);
|
||||
done:
|
||||
@@ -156,7 +145,8 @@ static int steam_client(void) {
|
||||
static int cached = -1;
|
||||
if (cached < 0)
|
||||
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
|
||||
strstr(program_invocation_name, "steamrtarm64") != NULL;
|
||||
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
|
||||
strstr(program_invocation_name, "steamrt64") != NULL);
|
||||
return cached;
|
||||
}
|
||||
|
||||
@@ -223,7 +213,7 @@ int posix_fallocate(int fd, off_t offset, off_t length) {
|
||||
int call_errno = errno;
|
||||
uint64_t elapsed = now_ns() - start;
|
||||
allocation_line("posix_fallocate", result, call_errno, 0, offset, length, elapsed);
|
||||
errno = entry_errno; /* POSIX requires the error to be returned, leaving errno unchanged. */
|
||||
errno = entry_errno;
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -262,8 +252,6 @@ int ftruncate(int fd, off_t length) {
|
||||
int known = 0;
|
||||
if (steam_client()) {
|
||||
if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat");
|
||||
/* staging_file() reads /proc/self/fd, a round trip through proot: skip it for a shrink, which
|
||||
* is passed through untouched either way. */
|
||||
known = next_fstat != NULL && next_fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
|
||||
length >= st.st_size && staging_file(fd);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,3 @@
|
||||
/* System V semaphores and shared memory for programs in the Linux runtime.
|
||||
*
|
||||
* Android kernels are built without System V IPC, so semget/shmget fail with ENOSYS. Steam's tier0
|
||||
* creates its client-instance semaphore with semget and gives up when that fails. This library is
|
||||
* LD_PRELOADed into the session and keeps each object in a file under /dev/shm (a bound directory
|
||||
* the whole session shares): a semaphore set is an array of counters waited on with futexes, a
|
||||
* segment is a plain file that shmat maps. Objects are found by the inode of their file, which is
|
||||
* what the id is. semop applies its operations one by one (no all-or-nothing across a set) and
|
||||
* SEM_UNDO is accepted but not performed - enough for the client, which uses single-counter sets.
|
||||
* A message queue is a table of slots in its file: gamescope hands mangoapp (Deck mode's performance
|
||||
* overlay) each frame's timings through one. */
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
@@ -34,7 +23,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#define DIR_DEFAULT "/dev/shm/wnsysv"
|
||||
#define SEM_MAGIC 0x574e5345u /* "WNSE" */
|
||||
#define SEM_MAGIC 0x574e5345u
|
||||
#define MAX_OBJECTS 64
|
||||
|
||||
struct sem_header {
|
||||
@@ -43,9 +32,11 @@ struct sem_header {
|
||||
uint32_t key;
|
||||
uint32_t mode;
|
||||
int32_t creator_pid;
|
||||
int32_t pad[11];
|
||||
_Atomic uint32_t otime;
|
||||
_Atomic uint32_t ctime;
|
||||
int32_t pad[9];
|
||||
};
|
||||
/* The counters follow the header, one 32-bit word each (a futex word). */
|
||||
_Static_assert(sizeof(struct sem_header) == 64, "semaphore files written by older sessions keep their layout");
|
||||
|
||||
struct sem_map { int id; struct sem_header *hdr; size_t len; };
|
||||
struct shm_map { void *addr; size_t len; int id; };
|
||||
@@ -70,7 +61,6 @@ static int object_id(int fd) {
|
||||
return (int)(st.st_ino & 0x7fffffff);
|
||||
}
|
||||
|
||||
/* Open the object file of kind ("sem"/"shm") for key, creating it as flags ask. */
|
||||
static int open_object(const char *kind, key_t key, int flags, int *created) {
|
||||
char path[PATH_MAX];
|
||||
int oflags = O_RDWR | O_CLOEXEC;
|
||||
@@ -92,7 +82,6 @@ static int open_object(const char *kind, key_t key, int flags, int *created) {
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* The object file for an id, found by inode. */
|
||||
static int open_by_id(const char *kind, int id) {
|
||||
DIR *d = opendir(object_dir());
|
||||
if (!d) return -1;
|
||||
@@ -135,7 +124,6 @@ static long futex(void *addr, int op, int val, const struct timespec *timeout) {
|
||||
return syscall(SYS_futex, addr, op, val, timeout, NULL, 0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ semaphores */
|
||||
|
||||
static struct sem_map *sem_lookup(int id) {
|
||||
for (int i = 0; i < MAX_OBJECTS; i++)
|
||||
@@ -176,7 +164,8 @@ int semget(key_t key, int nsems, int semflg) {
|
||||
size_t len = sizeof(struct sem_header) + (size_t)nsems * sizeof(int32_t);
|
||||
if (ftruncate(fd, (off_t)len) != 0) { close(fd); return -1; }
|
||||
struct sem_header h = {.magic = SEM_MAGIC, .nsems = (uint32_t)nsems, .key = (uint32_t)key,
|
||||
.mode = (uint32_t)(semflg & 0777), .creator_pid = (int32_t)getpid()};
|
||||
.mode = (uint32_t)(semflg & 0777), .creator_pid = (int32_t)getpid(),
|
||||
.ctime = (uint32_t)time(NULL)};
|
||||
if (pwrite(fd, &h, sizeof(h), 0) != (ssize_t)sizeof(h)) { close(fd); return -1; }
|
||||
} else {
|
||||
struct sem_header h;
|
||||
@@ -220,8 +209,9 @@ int semtimedop(int semid, struct sembuf *sops, size_t nsops, const struct timesp
|
||||
} else if (sem_wait_op(w, sops[i].sem_op, sops[i].sem_flg, timeout) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (sops[i].sem_op < 0) futex(w, FUTEX_WAKE, INT_MAX, NULL); /* zero-waiters see the change */
|
||||
if (sops[i].sem_op < 0) futex(w, FUTEX_WAKE, INT_MAX, NULL);
|
||||
}
|
||||
atomic_store(&h->otime, (uint32_t)time(NULL));
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -256,6 +246,7 @@ int semctl(int semid, int semnum, int cmd, ...) {
|
||||
if (semnum < 0 || (uint32_t)semnum >= h->nsems) { errno = EINVAL; return -1; }
|
||||
atomic_store(&words[semnum], (int32_t)(intptr_t)arg.buf);
|
||||
futex(&words[semnum], FUTEX_WAKE, INT_MAX, NULL);
|
||||
atomic_store(&h->ctime, (uint32_t)time(NULL));
|
||||
return 0;
|
||||
case GETALL:
|
||||
for (uint32_t i = 0; i < h->nsems; i++) arg.array[i] = (unsigned short)atomic_load(&words[i]);
|
||||
@@ -265,6 +256,7 @@ int semctl(int semid, int semnum, int cmd, ...) {
|
||||
atomic_store(&words[i], arg.array[i]);
|
||||
futex(&words[i], FUTEX_WAKE, INT_MAX, NULL);
|
||||
}
|
||||
atomic_store(&h->ctime, (uint32_t)time(NULL));
|
||||
return 0;
|
||||
case GETPID: return h->creator_pid;
|
||||
case GETNCNT: case GETZCNT: return 0;
|
||||
@@ -275,17 +267,15 @@ int semctl(int semid, int semnum, int cmd, ...) {
|
||||
arg.buf->sem_perm.gid = arg.buf->sem_perm.cgid = getgid();
|
||||
arg.buf->sem_perm.mode = (unsigned short)h->mode;
|
||||
arg.buf->sem_nsems = h->nsems;
|
||||
arg.buf->sem_otime = (time_t)atomic_load(&h->otime);
|
||||
arg.buf->sem_ctime = (time_t)atomic_load(&h->ctime);
|
||||
return 0;
|
||||
case IPC_SET: return 0;
|
||||
case IPC_SET: atomic_store(&h->ctime, (uint32_t)time(NULL)); return 0;
|
||||
default: errno = EINVAL; return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ shared memory */
|
||||
|
||||
/* Linux keeps a removed segment attachable until the last detach, which X clients rely on: they
|
||||
* remove the segment right after asking the server to attach it. A removed segment is renamed out
|
||||
* of key lookup instead, and removed for good once it has been out of use for a while. */
|
||||
static int remove_shm(int id) {
|
||||
DIR *d = opendir(object_dir());
|
||||
if (!d) return -1;
|
||||
@@ -399,18 +389,18 @@ int shmctl(int shmid, int cmd, struct shmid_ds *buf) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ message queues */
|
||||
|
||||
/* Only what gamescope and mangoapp use: msgtyp 0 or > 0, IPC_NOWAIT and IPC_RMID. */
|
||||
#define MSG_MAGIC 0x574e4d51u /* "WNMQ" */
|
||||
|
||||
|
||||
#define MSG_MAGIC 0x574e4d51u
|
||||
#define MSG_SLOTS 32
|
||||
|
||||
struct msg_queue {
|
||||
uint32_t magic;
|
||||
_Atomic int32_t lock; /* 0 free, else the holder's pid */
|
||||
_Atomic int32_t changed; /* bumped on every send and receive; waiters sleep on it */
|
||||
_Atomic int32_t lock;
|
||||
_Atomic int32_t changed;
|
||||
uint64_t next_seq;
|
||||
struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS]; /* seq 0: free */
|
||||
struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS];
|
||||
};
|
||||
|
||||
static struct msg_queue *msg_map(int id) {
|
||||
@@ -425,7 +415,6 @@ static struct msg_queue *msg_map(int id) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* A process killed while holding the lock (Android ends sessions without warning) loses it. */
|
||||
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);
|
||||
@@ -519,12 +508,6 @@ int msgctl(int msqid, int cmd, struct msqid_ds *buf) {
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
* fork() carries over only the calling thread, so a lock another thread was holding at that
|
||||
* instant stays held in the child by a thread that is not there to release it. Taking it before
|
||||
* the fork makes the copy consistent; the parent then unlocks it and the child, whose one thread
|
||||
* never locked it, gets a fresh one. (WinNative 79aa7f68.)
|
||||
*/
|
||||
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); }
|
||||
|
||||
@@ -1,15 +1,3 @@
|
||||
/*
|
||||
* A trace instance for mangoapp where the kernel's tracefs is closed to the app.
|
||||
*
|
||||
* Valve's mangoapp (Deck mode's performance overlay) reads the GPU memory total on a Qualcomm
|
||||
* display driver (msm_dpu / msm_drm) from the gpu_mem_total event, through a tracefs instance of
|
||||
* its own - and aborts when tracefs_instance_create() fails, taking the whole overlay with it.
|
||||
* Android mounts tracefs for root and the readtracefs group only, so it always fails here.
|
||||
*
|
||||
* The real calls run first. Only when they fail is the instance placed in an empty directory of
|
||||
* the session's own, and reading its events answers with one gpu_mem_total record carrying the
|
||||
* total KGSL - the GPU driver of every Adreno under Android - reports to the app.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <limits.h>
|
||||
@@ -25,7 +13,6 @@ struct tracefs_instance;
|
||||
struct tep_handle;
|
||||
struct tep_event;
|
||||
|
||||
/* The head of libtraceevent 1.8's struct tep_record (the version tools/mangoapp/packages.txt pins). */
|
||||
struct tep_record {
|
||||
unsigned long long ts, offset;
|
||||
long long missed_events;
|
||||
@@ -35,7 +22,6 @@ struct tep_record {
|
||||
void *priv;
|
||||
};
|
||||
|
||||
/* The event as Android kernels declare it (trace/events/gpu_mem.h). */
|
||||
static const char gpu_mem_total_format[] =
|
||||
"name: gpu_mem_total\n"
|
||||
"ID: 1\n"
|
||||
|
||||
@@ -1,25 +1,13 @@
|
||||
/*
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0, with names
|
||||
* changed to this project's. The reasoning below is the original author's.
|
||||
*
|
||||
* A process status without the container's tracer in it.
|
||||
*
|
||||
* proot runs the session under ptrace, so every process here reads a TracerPid in its
|
||||
* /proc/<pid>/status. The Steam client takes that to mean a debugger is attached, and its arm64
|
||||
* build breaks into the supposed debugger with a bare "svc #0" after every failed assertion. That
|
||||
* is no breakpoint: the registers still hold the call Plat_IsInDebugSession() just made, close(),
|
||||
* with its own result, 1, as the argument - so each assertion closes descriptor 1. The number then
|
||||
* goes to whatever the client opens next, and its standard output is written into that: app
|
||||
* manifests and content chunks, its own connections, and the socket a game's Steam API talks
|
||||
* over, which is how a game that stayed silent while loading found its pipe dead.
|
||||
*
|
||||
* The tracer is part of the container, not something a program should react to, so the status
|
||||
* files are served with TracerPid 0.
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <ctype.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
@@ -34,7 +22,6 @@ static const char *skip_digits(const char *s) {
|
||||
return end == s ? NULL : end;
|
||||
}
|
||||
|
||||
/* /proc/{self,thread-self,<pid>}[/task/<tid>]/status */
|
||||
static int is_status_path(const char *path) {
|
||||
const char *rest;
|
||||
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return 0;
|
||||
@@ -46,10 +33,16 @@ static int is_status_path(const char *path) {
|
||||
return strcmp(rest, "/status") == 0;
|
||||
}
|
||||
|
||||
/* Chromium stands its hang watchdogs down when it sees a tracer, and the client's web helper does
|
||||
* not come up within their patience here: it is left reading the truth. */
|
||||
static int is_web_helper(void) {
|
||||
return strcmp(program_invocation_short_name, "steamwebhelper") == 0;
|
||||
static int is_web_helper(const void *caller) {
|
||||
if (strcmp(program_invocation_short_name, "steamwebhelper") != 0 &&
|
||||
strcmp(program_invocation_short_name, "vrwebhelper") != 0)
|
||||
return 0;
|
||||
const char *hide = getenv("BL_WEBHELPER_HIDE_TRACER");
|
||||
Dl_info info;
|
||||
if (hide && hide[0] == '1' && caller && dladdr(caller, &info) && info.dli_fname
|
||||
&& strstr(info.dli_fname, "libtier0_s.so"))
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int write_all(int fd, const char *data, size_t len) {
|
||||
@@ -63,15 +56,13 @@ static int write_all(int fd, const char *data, size_t len) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The descriptor to hand back for a read-only open of a status file, or -1 with errno untouched
|
||||
* when the path is something else or the copy cannot be made, and the real open should run. */
|
||||
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags) {
|
||||
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
char text[STATUS_MAX];
|
||||
size_t len = 0;
|
||||
int saved = errno;
|
||||
int out = -1;
|
||||
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper()) return -1;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper(caller)) return -1;
|
||||
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (in < 0) goto done;
|
||||
for (;;) {
|
||||
|
||||
@@ -1,29 +1,7 @@
|
||||
/*
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0, with the
|
||||
* symbol prefix changed to match this library. The reasoning below is the original author's.
|
||||
*
|
||||
* udev's netlink monitor, stood in for where the sandbox refuses the socket it is built on.
|
||||
*
|
||||
* The app sandbox denies a NETLINK_KOBJECT_UEVENT socket outright. libudev cannot create a
|
||||
* monitor without one, and SDL's HID layer cannot start without a monitor: every SDL_hid_init()
|
||||
* fails, the Steam client's controller code retries it hundreds of times a second, its main loop
|
||||
* stalls, and the client asserts out from under the running game. Refusing SDL the library
|
||||
* altogether (the earlier answer here) is what produced that failure.
|
||||
*
|
||||
* So the socket is answered instead: one end of a datagram socketpair stands in for the netlink
|
||||
* socket, its peer held open so it never reads as hung up, and the few calls libudev makes on
|
||||
* the socket that only a netlink one could answer are answered here. Nothing is ever written to
|
||||
* it, so the monitor is live and silent, which is the most the kernel would deliver in a
|
||||
* container anyway. The real socket is tried first, so this stays out of the way wherever a
|
||||
* monitor could genuinely be created.
|
||||
*
|
||||
* The stand-in can also carry events after all (bl_udevmon_inject, below): libfakeinput plugs
|
||||
* Steam's touch controller in and out of the client that way.
|
||||
*
|
||||
* Wine is left without one. Its HID bus reads the session's pads itself only when its SDL bus
|
||||
* cannot start, and that is the path inputudev.c describes them on. Given a monitor the SDL bus
|
||||
* comes up and takes the pads over from it.
|
||||
* Ported from WinNative (maxjivi05, feature/wayland-gamescope, 2026-09-18/19), GPL-3.0.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
@@ -39,9 +17,9 @@
|
||||
#include <unistd.h>
|
||||
|
||||
struct stand_in {
|
||||
int fd; /* the descriptor handed out, -1 when the slot is free */
|
||||
int peer; /* the other end, kept open */
|
||||
ino_t inode; /* identifies the socket after fd is closed and its number reused */
|
||||
int fd;
|
||||
int peer;
|
||||
ino_t inode;
|
||||
};
|
||||
|
||||
static struct stand_in stand_ins[16];
|
||||
@@ -62,8 +40,6 @@ static ino_t socket_inode(int fd) {
|
||||
return fstat(fd, &st) == 0 ? st.st_ino : 0;
|
||||
}
|
||||
|
||||
/* Whether fd is one of the stand-in sockets. A slot whose descriptor was closed and reused by
|
||||
* something else is retired on sight, so a later socket with the same number is not mistaken. */
|
||||
static int is_stand_in(int fd) {
|
||||
int found = 0;
|
||||
if (fd < 0)
|
||||
@@ -108,7 +84,6 @@ static int make_stand_in(int type) {
|
||||
errno = saved;
|
||||
return -1;
|
||||
}
|
||||
/* The peer is ours alone: it must not follow the socket into a child. */
|
||||
fcntl(sv[1], F_SETFD, FD_CLOEXEC);
|
||||
pthread_mutex_lock(&lock);
|
||||
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
|
||||
@@ -147,7 +122,6 @@ int socket(int domain, int type, int protocol) {
|
||||
return make_stand_in(type);
|
||||
}
|
||||
|
||||
/* For net.c's bind(): whether fd is a stand-in, which accepts any netlink address as bound. */
|
||||
__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd) {
|
||||
return is_stand_in(fd);
|
||||
}
|
||||
@@ -180,8 +154,6 @@ int setsockopt(int fd, int level, int optname, const void *optval, socklen_t opt
|
||||
static int (*real_setsockopt)(int, int, int, const void *, socklen_t);
|
||||
|
||||
if (is_stand_in(fd)) {
|
||||
/* Group membership and packet filters only mean something on a socket that receives; this
|
||||
* one never does, so they are accepted as set. The rest is genuine on a unix socket. */
|
||||
if (level == SOL_NETLINK)
|
||||
return 0;
|
||||
if (level == SOL_SOCKET && (optname == SO_ATTACH_FILTER || optname == SO_DETACH_FILTER))
|
||||
@@ -195,8 +167,6 @@ int setsockopt(int fd, int level, int optname, const void *optval, socklen_t opt
|
||||
return real_setsockopt(fd, level, optname, optval, optlen);
|
||||
}
|
||||
|
||||
/* udevd's message to the "udev" multicast group (systemd, device-monitor.c): this header, then the
|
||||
* properties as NUL-separated KEY=VALUE strings. */
|
||||
struct monitor_netlink_header {
|
||||
char prefix[8];
|
||||
unsigned magic;
|
||||
@@ -209,7 +179,6 @@ struct monitor_netlink_header {
|
||||
unsigned filter_tag_bloom_lo;
|
||||
};
|
||||
|
||||
/* systemd's string_hash32: MurmurHash2, seed 0. */
|
||||
static unsigned murmur_hash2(const char *key, size_t len) {
|
||||
const unsigned m = 0x5bd1e995;
|
||||
unsigned h = (unsigned)len;
|
||||
@@ -236,8 +205,6 @@ static unsigned murmur_hash2(const char *key, size_t len) {
|
||||
return h;
|
||||
}
|
||||
|
||||
/* Sends a device event to every stand-in in this process, as udevd would; returns how many got it.
|
||||
* For libfakeinput (found with dlsym), which knows when its devices come and go. */
|
||||
__attribute__((visibility("default"))) int bl_udevmon_inject(const char *action, const char *devpath,
|
||||
const char *subsystem, const char *devname,
|
||||
unsigned major, unsigned minor) {
|
||||
@@ -247,7 +214,7 @@ __attribute__((visibility("default"))) int bl_udevmon_inject(const char *action,
|
||||
action, 0, devpath, 0, subsystem, 0, devname, 0, major, 0, minor, 0,
|
||||
__atomic_add_fetch(&seqnum, 1, __ATOMIC_RELAXED));
|
||||
if (used <= 0 || (size_t)used >= sizeof(props)) return -1;
|
||||
used++; /* the last string's NUL */
|
||||
used++;
|
||||
struct monitor_netlink_header header;
|
||||
memset(&header, 0, sizeof(header));
|
||||
memcpy(header.prefix, "libudev", 8);
|
||||
@@ -269,10 +236,6 @@ __attribute__((visibility("default"))) int bl_udevmon_inject(const char *action,
|
||||
return sent;
|
||||
}
|
||||
|
||||
/* For ntsync.c's recvmsg(), which owns the symbol: 1 when fd is a stand-in, answered here (*result
|
||||
* is what recvmsg returns), 0 otherwise. A message is dressed as udevd's: libudev drops one that
|
||||
* does not come from the udev multicast group with root credentials. The sender address goes in
|
||||
* the room msg_namelen had before the call; a unix socket sets it to 0. */
|
||||
__attribute__((visibility("hidden"))) int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags,
|
||||
ssize_t (*real_recvmsg)(int, struct msghdr *, int),
|
||||
ssize_t *result) {
|
||||
@@ -286,7 +249,7 @@ __attribute__((visibility("hidden"))) int bl_udevmon_recvmsg(int fd, struct msgh
|
||||
struct sockaddr_nl nl;
|
||||
memset(&nl, 0, sizeof(nl));
|
||||
nl.nl_family = AF_NETLINK;
|
||||
nl.nl_groups = 2; /* udev's group */
|
||||
nl.nl_groups = 2;
|
||||
memcpy(msg->msg_name, &nl, sizeof(nl));
|
||||
msg->msg_namelen = sizeof(nl);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef WEBHELPER_DEFAULT
|
||||
#define WEBHELPER_DEFAULT "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
|
||||
#endif
|
||||
|
||||
static int is_webhelper_browser(const char *path, char *const argv[]) {
|
||||
if (!path || !argv) return 0;
|
||||
const char *base = strrchr(path, '/');
|
||||
base = base ? base + 1 : path;
|
||||
if (strcmp(base, "steamwebhelper")) return 0;
|
||||
for (int i = 1; argv[i]; i++)
|
||||
if (!strncmp(argv[i], "--type=", 7)) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static char *join_features(const char *have, const char *add) {
|
||||
size_t a = have ? strlen(have) : 0, b = strlen(add);
|
||||
char *out = malloc(a + b + 2);
|
||||
if (!out) return NULL;
|
||||
out[0] = 0;
|
||||
if (a) strcat(strcat(out, have), ",");
|
||||
return strcat(out, add);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]) {
|
||||
if (!is_webhelper_browser(path, argv)) return argv;
|
||||
const char *spec = getenv("BL_WEBHELPER_ARGS");
|
||||
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
|
||||
if (!strcmp(spec, "stock")) return argv;
|
||||
|
||||
int argc = 0;
|
||||
while (argv[argc]) argc++;
|
||||
char *tokens = strdup(spec);
|
||||
if (!tokens) return argv;
|
||||
int extra = 0;
|
||||
for (char *c = tokens; *c; c++)
|
||||
if (*c == ' ') extra++;
|
||||
char **out = calloc(argc + extra + 4, sizeof *out);
|
||||
if (!out) return argv;
|
||||
|
||||
const char *enable = NULL, *disable = NULL;
|
||||
int n = 0;
|
||||
for (int i = 0; i < argc; i++) {
|
||||
if (i && !strncmp(argv[i], "--enable-features=", 18)) enable = argv[i] + 18;
|
||||
else if (i && !strncmp(argv[i], "--disable-features=", 19)) disable = argv[i] + 19;
|
||||
else out[n++] = argv[i];
|
||||
}
|
||||
char *add_enable = NULL, *add_disable = NULL, *save = NULL;
|
||||
for (char *t = strtok_r(tokens, " ", &save); t; t = strtok_r(NULL, " ", &save)) {
|
||||
if (t[0] == '+' && t[1]) {
|
||||
char *joined = join_features(add_enable, t + 1);
|
||||
free(add_enable);
|
||||
add_enable = joined;
|
||||
} else if (t[0] == '-' && t[1] && t[1] != '-') {
|
||||
char *joined = join_features(add_disable, t + 1);
|
||||
free(add_disable);
|
||||
add_disable = joined;
|
||||
} else if (!strncmp(t, "--", 2)) {
|
||||
out[n++] = t;
|
||||
}
|
||||
}
|
||||
char *merged;
|
||||
if (add_enable && (merged = join_features(enable, add_enable))) enable = merged;
|
||||
if (add_disable && (merged = join_features(disable, add_disable))) disable = merged;
|
||||
char *flag;
|
||||
if (enable && (flag = malloc(strlen(enable) + 19))) out[n++] = strcat(strcpy(flag, "--enable-features="), enable);
|
||||
if (disable && (flag = malloc(strlen(disable) + 20))) out[n++] = strcat(strcpy(flag, "--disable-features="), disable);
|
||||
out[n] = NULL;
|
||||
return out;
|
||||
}
|
||||
@@ -1,26 +1,9 @@
|
||||
/*
|
||||
* The Steam client's own screen, in a Follow screen session.
|
||||
*
|
||||
* With two Xwayland servers the client sizes them through GAMESCOPE_XWAYLAND_MODE_CONTROL
|
||||
* ({server, width, height, allow_super_res} on the root window): the games' server (1) to a game's
|
||||
* Game Resolution, and its own (0) to what it recommends for the display - 1920x1080 on a Fold's
|
||||
* 2448x1848 inner panel. From then on it reads that 16:9 size back as the display's "native" one,
|
||||
* so its interface and every game it starts are 16:9 with bars on a near-square panel, and stay so
|
||||
* when the phone folds onto the cover screen.
|
||||
*
|
||||
* gamescope already keeps server 0 at the output's size and resizes it when the output changes (a
|
||||
* Steam Deck docking; here, the app resizing the output as the phone folds and unfolds). So in a
|
||||
* Follow screen session (BL_FOLLOW_OUTPUT=1) a request for server 0 is dropped and the client's
|
||||
* screen stays the panel's; requests for the games' servers pass through untouched. Any other
|
||||
* session, and any other property, is passed straight on.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Xlib's types, without needing its headers in the build image. */
|
||||
typedef struct _XDisplay Display;
|
||||
typedef unsigned long Atom;
|
||||
typedef unsigned long Window;
|
||||
@@ -48,12 +31,10 @@ int XChangeProperty(Display *dpy, Window w, Atom property, Atom type, int format
|
||||
static Display *atom_dpy;
|
||||
static Atom mode_control;
|
||||
if (!intern) intern = (intern_atom_fn)dlsym(RTLD_NEXT, "XInternAtom");
|
||||
/* Atoms belong to a connection; the client's is the one that writes this. */
|
||||
if (intern && atom_dpy != dpy) {
|
||||
mode_control = intern(dpy, "GAMESCOPE_XWAYLAND_MODE_CONTROL", 1);
|
||||
atom_dpy = dpy;
|
||||
}
|
||||
/* Format-32 property data is an array of long in Xlib. */
|
||||
const long *v = (const long *)data;
|
||||
if (mode_control && property == mode_control && v[0] == 0) {
|
||||
static int said;
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
|
||||
#ifndef MADV_PAGEOUT
|
||||
#define MADV_PAGEOUT 21
|
||||
#endif
|
||||
#ifndef ZR_CTL
|
||||
#define ZR_CTL "/tmp/.bl-zram"
|
||||
#endif
|
||||
#define ZR_SWAPPED (1ULL << 62)
|
||||
#define ZR_BATCH 512
|
||||
|
||||
static long (*zr_sys)(long, ...);
|
||||
static unsigned long zr_page;
|
||||
static int zr_busy;
|
||||
static int zr_pending;
|
||||
static char zr_maps[8192];
|
||||
static uint64_t zr_entries[ZR_BATCH];
|
||||
static struct iovec zr_iov[ZR_BATCH];
|
||||
static char zr_sink[ZR_BATCH];
|
||||
|
||||
static int zr_open(const char *path) {
|
||||
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
|
||||
}
|
||||
|
||||
static int zr_mode(void) {
|
||||
char c = 0;
|
||||
int fd = zr_open(ZR_CTL);
|
||||
if (fd < 0) return -1;
|
||||
long n = zr_sys(SYS_read, fd, &c, 1);
|
||||
zr_sys(SYS_close, fd);
|
||||
return n == 1 && (c == '0' || c == '1') ? c - '0' : -1;
|
||||
}
|
||||
|
||||
static unsigned long zr_hex(const char **p) {
|
||||
unsigned long v = 0;
|
||||
for (;; (*p)++) {
|
||||
char c = **p;
|
||||
if (c >= '0' && c <= '9') v = v * 16 + (unsigned long)(c - '0');
|
||||
else if (c >= 'a' && c <= 'f') v = v * 16 + (unsigned long)(c - 'a' + 10);
|
||||
else return v;
|
||||
}
|
||||
}
|
||||
|
||||
static int zr_eligible(const char *line, int compress, unsigned long *start, unsigned long *end) {
|
||||
const char *p = line;
|
||||
*start = zr_hex(&p);
|
||||
if (*p++ != '-') return 0;
|
||||
*end = zr_hex(&p);
|
||||
if (*p++ != ' ' || p[0] != 'r' || p[3] != 'p') return 0;
|
||||
if (!compress) return 1;
|
||||
if (p[1] != 'w') return 0;
|
||||
for (int field = 0; field < 4; field++) {
|
||||
while (*p && *p != ' ') p++;
|
||||
while (*p == ' ') p++;
|
||||
}
|
||||
return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0;
|
||||
}
|
||||
|
||||
static void zr_read_back(int pagemap, unsigned long start, unsigned long end) {
|
||||
pid_t self = (pid_t)zr_sys(SYS_getpid);
|
||||
struct iovec local = {zr_sink, 0};
|
||||
for (unsigned long addr = start; addr < end;) {
|
||||
unsigned long count = (end - addr) / zr_page;
|
||||
if (count > ZR_BATCH) count = ZR_BATCH;
|
||||
if (zr_sys(SYS_lseek, pagemap, (long)(addr / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return;
|
||||
long got = zr_sys(SYS_read, pagemap, zr_entries, count * sizeof(uint64_t));
|
||||
if (got < (long)sizeof(uint64_t)) return;
|
||||
unsigned long n = 0;
|
||||
for (unsigned long i = 0; i < (unsigned long)got / sizeof(uint64_t); i++) {
|
||||
if (!(zr_entries[i] & ZR_SWAPPED)) continue;
|
||||
zr_iov[n].iov_base = (void *)(addr + i * zr_page);
|
||||
zr_iov[n++].iov_len = 1;
|
||||
}
|
||||
for (unsigned long done = 0; done < n;) {
|
||||
local.iov_len = n - done;
|
||||
long r = zr_sys(SYS_process_vm_readv, self, &local, 1UL, zr_iov + done, n - done, 0UL);
|
||||
done += r > 0 ? (unsigned long)r : 1;
|
||||
}
|
||||
addr += (unsigned long)got / sizeof(uint64_t) * zr_page;
|
||||
}
|
||||
}
|
||||
|
||||
static void zr_walk(int compress) {
|
||||
int maps = zr_open("/proc/self/maps");
|
||||
if (maps < 0) return;
|
||||
int pagemap = compress ? -1 : zr_open("/proc/self/pagemap");
|
||||
if (!compress && pagemap < 0) {
|
||||
zr_sys(SYS_close, maps);
|
||||
return;
|
||||
}
|
||||
size_t have = 0;
|
||||
for (;;) {
|
||||
long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n <= 0) break;
|
||||
have += (size_t)n;
|
||||
zr_maps[have] = 0;
|
||||
char *line = zr_maps;
|
||||
char *nl;
|
||||
while ((nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
|
||||
*nl = 0;
|
||||
unsigned long s, e;
|
||||
if (zr_eligible(line, compress, &s, &e) && e > s) {
|
||||
if (compress) zr_sys(SYS_madvise, s, e - s, MADV_PAGEOUT);
|
||||
else zr_read_back(pagemap, s, e);
|
||||
}
|
||||
line = nl + 1;
|
||||
}
|
||||
have -= (size_t)(line - zr_maps);
|
||||
memmove(zr_maps, line, have);
|
||||
if (have == sizeof(zr_maps) - 1) have = 0;
|
||||
}
|
||||
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
|
||||
zr_sys(SYS_close, maps);
|
||||
}
|
||||
|
||||
static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)context;
|
||||
if (info == NULL || info->si_code != SI_USER) return;
|
||||
int saved = errno;
|
||||
__atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST);
|
||||
while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST)
|
||||
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
int mode = zr_mode();
|
||||
if (mode >= 0) zr_walk(mode);
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
static void zr_child(void) {
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
const char *name = program_invocation_short_name;
|
||||
if (strcmp(name, "steam") != 0 && strcmp(name, "steamwebhelper") != 0) return;
|
||||
void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD);
|
||||
if (libc == NULL) return;
|
||||
zr_sys = (long (*)(long, ...))dlsym(libc, "syscall");
|
||||
if (zr_sys == NULL) return;
|
||||
int fd = zr_open(ZR_CTL);
|
||||
if (fd < 0) return;
|
||||
zr_sys(SYS_close, fd);
|
||||
long page = sysconf(_SC_PAGESIZE);
|
||||
zr_page = page > 0 ? (unsigned long)page : 4096UL;
|
||||
struct sigaction old;
|
||||
if (sigaction(SIGURG, NULL, &old) != 0) return;
|
||||
if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return;
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = zr_handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child);
|
||||
}
|
||||
@@ -1,30 +1,3 @@
|
||||
/*
|
||||
* libssbs.so - keep PSTATE.SSBS set across signal returns, without rebuilding Wine.
|
||||
*
|
||||
* Wine's arm64 signal code writes PSTATE back from a Windows CONTEXT, whose Cpsr never carries
|
||||
* SSBS (bit 12). Every signal return through that code (exception fixups, NtSetContextThread on
|
||||
* another thread, the SIGUSR2 suspend path) therefore resumes the thread with SSBS clear, so the
|
||||
* CPU runs it with speculative store bypass disabled - slower on cores such as Oryon.
|
||||
* force_ssbs.diff (Sonicadvance1, FEX) fixes this inside ntdll; this library does the same from
|
||||
* outside, for Protons that cannot be rebuilt: the Valve, GE and CachyOS ARM64 builds DroidDeck
|
||||
* runs, which come prebuilt from Steam. Same source as Bannerlator's adapter (bionic), built here
|
||||
* for glibc.
|
||||
*
|
||||
* How: interpose sigaction()/signal() via LD_PRELOAD. Every handler is installed behind one
|
||||
* SA_SIGINFO trampoline that calls the real handler and then sets SSBS in the ucontext it is
|
||||
* about to return through. The kernel accepts SSBS from userspace on sigreturn and context-
|
||||
* switches it per thread, so the bit sticks until the next sigreturn. Handlers that never return
|
||||
* (siglongjmp) are unaffected either way.
|
||||
*
|
||||
* Env:
|
||||
* SSBS_ADAPTER_DISABLE=1 pass everything through untouched.
|
||||
* SSBS_ADAPTER_OBSERVE=1 wrap and count, but leave SSBS as the handler left it (the baseline).
|
||||
* SSBS_ADAPTER_DEBUG=1 log to stderr (implied by OBSERVE):
|
||||
* - "returned with SSBS clear": a handler was about to resume a thread without SSBS.
|
||||
* - "arrived with SSBS clear": a thread was RUNNING without SSBS when a signal reached it.
|
||||
* Under the adapter this should stop after each thread's first fixed return; if it keeps
|
||||
* counting, something other than a signal return is clearing the bit.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <signal.h>
|
||||
@@ -41,7 +14,6 @@ typedef void (*sigact_fn)(int, siginfo_t *, void *);
|
||||
typedef void (*sighand_fn)(int);
|
||||
typedef int (*sigaction_fn)(int, const struct sigaction *, struct sigaction *);
|
||||
|
||||
/* Per signal: the handler the program asked for, and whether it wanted SA_SIGINFO. */
|
||||
static _Atomic(void *) real_handler[MAX_SIG];
|
||||
static atomic_bool real_siginfo[MAX_SIG];
|
||||
|
||||
@@ -69,7 +41,6 @@ __attribute__((constructor)) static void ctor(void)
|
||||
if (debug) fprintf(stderr, "libssbs: loaded (%s)\n", disabled ? "disabled" : observe ? "observing only" : "active");
|
||||
}
|
||||
|
||||
/* 1, 2, 4, 8, ...: enough lines to see a trend without flooding the log. */
|
||||
static int milestone(unsigned long n) { return (n & (n - 1)) == 0; }
|
||||
|
||||
static void trampoline(int sig, siginfo_t *info, void *uc_v)
|
||||
@@ -130,7 +101,6 @@ int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact)
|
||||
|
||||
void *prev_h = atomic_load(&real_handler[sig]);
|
||||
int prev_info = atomic_load(&real_siginfo[sig]);
|
||||
/* Publish before installing so the trampoline never runs with a stale handler. */
|
||||
if (act && wrapped(new_h)) {
|
||||
atomic_store(&real_siginfo[sig], new_info);
|
||||
atomic_store_explicit(&real_handler[sig], new_h, memory_order_release);
|
||||
@@ -142,7 +112,6 @@ int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact)
|
||||
atomic_store(&real_handler[sig], prev_h);
|
||||
}
|
||||
|
||||
/* Report the caller's own handler, not the trampoline, so handler chaining keeps working. */
|
||||
if (ret == 0 && oldact && oldact->sa_sigaction == trampoline && prev_h) {
|
||||
if (prev_info) {
|
||||
oldact->sa_sigaction = (sigact_fn)prev_h;
|
||||
@@ -167,7 +136,6 @@ sighandler_t signal(int sig, sighandler_t handler)
|
||||
|
||||
sighandler_t bsd_signal(int sig, sighandler_t handler) { return signal(sig, handler); }
|
||||
|
||||
/* glibc's System V flavour: a one-shot handler with no restart. */
|
||||
sighandler_t sysv_signal(int sig, sighandler_t handler)
|
||||
{
|
||||
struct sigaction sa, old;
|
||||
|
||||
Reference in new issue
Block a user