Merge remote-tracking branch 'origin/main' into fix/steam-sd-preallocation

This commit is contained in:
xXJsonDeruloXx committed 2026-10-04 14:17:30 -04:00
commit 0d1d47e8b0
173 files changed
+15896 -9674

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
set -eu
out=${1:?usage: build-x86-preloads.sh <linuxfs asset directory>}
for arch in x86_64 i386; do
case $arch in
x86_64) bits=-m64 ;;
i386) bits=-m32 ;;
esac
mkdir -p "$out/$arch"
gcc $bits -shared -fPIC -O2 -Wall -pthread \
-o "$out/$arch/libblsession.so" tools/linuxfs/preload/*.c -ldl
g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
strip --strip-unneeded "$out/$arch/libblsession.so" "$out/$arch/libfakeinput.so"
for lib in "$out/$arch/libblsession.so" "$out/$arch/libfakeinput.so"; do
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
minor=${newest#GLIBC_2.}
if [ "$minor" -gt 31 ]; then
echo "$lib needs $newest; Steam Linux Runtime 3.0 has glibc 2.31" >&2
exit 1
fi
if objdump -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
echo "$lib links the C++ runtime dynamically" >&2
exit 1
fi
done
done
for name in faultreport thunkaudit; do
lib=$out/x86_64/lib$name.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/$name.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ -n "$(nm -D --undefined-only "$lib" 2>/dev/null)" ]; then
echo "$lib must not need any library" >&2
exit 1
fi
done
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"
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
exit 1
fi
+1 -1
View File
@@ -39,7 +39,7 @@ run lxqt-panel lxqt-panel
# The desktop was asked for with Steam in it (the front end's "Steam Desktop UI", Big Picture's
# "Switch to Desktop"): the client's desktop UI, as the menu's Steam entry opens it. A running
# client just gets the request; on a software desktop it goes back to the app as a Steam session.
[ "${BL_DESKTOP_STEAM:-0}" = 1 ] && run steam /usr/local/bin/bannerlator-steam-launch desktop
[ "${BL_DESKTOP_STEAM:-0}" = 1 ] && run steam /usr/local/bin/droiddeck-steam-launch desktop
# 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.
+7 -7
View File
@@ -1,7 +1,7 @@
#!/bin/bash
# The desktop session: labwc nested as a client of the app's compositor, with LXQt's panel and
# file manager started from its autostart, and Xwayland for the X11 programs (the Steam client,
# most emulators). Run by bannerlator-session in place of gamescope for mode "lxqt".
# most emulators). Run by droiddeck-session in place of gamescope for mode "lxqt".
# 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
@@ -114,16 +114,16 @@ if [ ! -f /var/cache/fontconfig/.droiddeck-built ] && command -v fc-cache >/dev/
echo "== fontconfig: cache rebuilt, default sans is $(fc-match sans-serif 2>/dev/null)"
fi
# The menu's "Steam" / "Steam Big Picture" entries and one entry per installed game: all of them
# hand off to the app (bannerlator-steam-launch), since the client cannot draw on this desktop.
# 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/bannerlator-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
ln -sf /usr/local/bin/bannerlator-steam-shim /usr/local/bin/steam 2>/dev/null
python3 /usr/local/bin/bannerlator-desktop-games 2>&1 | sed 's/^/[games] /'
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.
python3 /usr/local/bin/bannerlator-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/bannerlator-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
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 (their own gamescope on the app's
# compositor) while the desktop is on pixman, where they could not draw with the GPU.
# BL_DESKTOP_GPU=on/off overrides; each entry keeps "Run in a desktop window" either way.
+2 -2
View File
@@ -18,7 +18,7 @@ LOCAL_DIR = "/usr/local/share/applications"
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 (bannerlator-steam-launch).
# 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)
@@ -45,7 +45,7 @@ def gpu_exec(exec_line):
"""The Exec that runs a program on the GPU; a Flatpak app goes through its launcher, which
keeps it on gamescope's X server instead of the desktop's Wayland socket."""
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
exec_line = "/usr/local/bin/bannerlator-flatpak-run " + exec_line.split(" run ", 1)[1]
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
return "droiddeck-gpu " + exec_line
+1 -1
View File
@@ -20,7 +20,7 @@
</keyboard>
<mouse><doubleClickTime>500</doubleClickTime></mouse>
<!-- Programs opened on the desktop at a size that suits it. melonDS remembers a 1x window for the
front end's full-screen toggle (bannerlator-pad-defaults), too small for a desktop: here it
front end's full-screen toggle (droiddeck-pad-defaults), too small for a desktop: here it
opens at 800x600, centred (AutoPlace alone kept the top-left corner). Only the desktop reads this file, so the front end is unaffected. -->
<windowRules>
<windowRule title="melonDS*">
+144
View File
@@ -0,0 +1,144 @@
#if !defined(__x86_64__)
#error faultreport is built for x86_64 guests only
#endif
#define SYS_read 0
#define SYS_write 1
#define SYS_close 3
#define SYS_rt_sigaction 13
#define SYS_getpid 39
#define SYS_gettid 186
#define SYS_tgkill 234
#define SYS_openat 257
#define AT_FDCWD (-100)
#define SIGILL 4
#define SA_SIGINFO 0x4UL
#define SA_RESTORER 0x04000000UL
#define SA_NODEFER 0x40000000UL
#define SA_RESETHAND 0x80000000UL
struct kernel_sigaction {
void (*handler)(int, void *, void *);
unsigned long flags;
void (*restorer)(void);
unsigned long mask;
};
static long sys(long n, long a, long b, long c, long d)
{
long r;
register long r10 __asm__("r10") = d;
__asm__ volatile("syscall" : "=a"(r) : "a"(n), "D"(a), "S"(b), "d"(c), "r"(r10) : "rcx", "r11", "memory");
return r;
}
static char out[1024];
static unsigned long used;
static char maps[65536];
static void put(const char *s)
{
while (*s && used < sizeof(out) - 1)
out[used++] = *s++;
}
static void put_hex(unsigned long v, int digits)
{
char buf[17];
for (int i = digits - 1; i >= 0; i--) {
buf[i] = "0123456789abcdef"[v & 15];
v >>= 4;
}
buf[digits] = 0;
put(buf);
}
static unsigned long parse_hex(const char **p)
{
unsigned long v = 0;
for (;;) {
char c = **p;
if (c >= '0' && c <= '9') v = v * 16 + (c - '0');
else if (c >= 'a' && c <= 'f') v = v * 16 + (c - 'a' + 10);
else return v;
(*p)++;
}
}
static int find_mapping(unsigned long addr, const char **line, unsigned long *length, unsigned long *start, int *readable)
{
long fd = sys(SYS_openat, AT_FDCWD, (long)"/proc/self/maps", 0, 0);
if (fd < 0) return 0;
unsigned long have = 0;
long n;
while (have < sizeof(maps) - 1 && (n = sys(SYS_read, fd, (long)(maps + have), sizeof(maps) - 1 - have, 0)) > 0)
have += n;
sys(SYS_close, fd, 0, 0, 0);
maps[have] = 0;
const char *p = maps;
while (*p) {
const char *begin = p;
unsigned long lo = parse_hex(&p);
if (*p == '-') p++;
unsigned long hi = parse_hex(&p);
while (*p == ' ') p++;
int r = *p == 'r';
const char *end = begin;
while (*end && *end != '\n') end++;
if (addr >= lo && addr < hi) {
*line = begin;
*length = end - begin;
*start = lo;
*readable = r && addr + 16 <= hi;
return 1;
}
p = *end ? end + 1 : end;
}
return 0;
}
static void report(int sig, void *info, void *context)
{
(void)context;
unsigned long addr = *(unsigned long *)((char *)info + 16);
int code = *(int *)((char *)info + 8);
used = 0;
put("droiddeck-fex: SIGILL at 0x");
put_hex(addr, 12);
put(" (si_code ");
put_hex((unsigned long)code, 2);
put(")");
const char *line;
unsigned long length, start;
int readable;
if (find_mapping(addr, &line, &length, &start, &readable)) {
put(", offset 0x");
put_hex(addr - start, 8);
if (readable) {
put(", bytes");
for (int i = 0; i < 16; i++) {
put(" ");
put_hex(((unsigned char *)addr)[i], 2);
}
}
put("\n in ");
for (unsigned long i = 0; i < length && used < sizeof(out) - 2; i++)
out[used++] = line[i];
} else {
put(", outside any mapping");
}
put("\n");
sys(SYS_write, 2, (long)out, used, 0);
struct kernel_sigaction fallback = {0, 0, 0, 0};
sys(SYS_rt_sigaction, sig, (long)&fallback, 0, sizeof(fallback.mask));
sys(SYS_tgkill, sys(SYS_getpid, 0, 0, 0, 0), sys(SYS_gettid, 0, 0, 0, 0), sig, 0);
}
void faultreport_restore(void);
__asm__(".text\n.type faultreport_restore,@function\nfaultreport_restore:\nmov $15, %eax\nsyscall\nhlt\n");
__attribute__((constructor)) static void install(void)
{
struct kernel_sigaction action = {report, SA_SIGINFO | SA_NODEFER | SA_RESETHAND | SA_RESTORER, faultreport_restore, 0};
sys(SYS_rt_sigaction, SIGILL, (long)&action, 0, sizeof(action.mask));
}
+40
View File
@@ -0,0 +1,40 @@
#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;
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 VHSgunzo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -3,7 +3,7 @@
# 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
# bannerlator-steam-launch uses; the app ends this session and starts that one). Anything else -
# 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
@@ -1,69 +0,0 @@
#!/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.
# bannerlator-appimage-run /opt/appimages/user/<id> [args...]
set -u
dir=${1:?usage: bannerlator-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 "bannerlator-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
# 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
fi
flags=()
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
flags+=(--no-sandbox)
if [ -n "${DISPLAY:-}" ]; then
export XDG_SESSION_TYPE=x11
unset WAYLAND_DISPLAY
flags+=(--ozone-platform=x11)
fi
fi
echo "== appimage $ARGV0 ($APPDIR) ${flags[*]}"
cd "$APPDIR" || exit 1
# 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:*) "$APPDIR/AppRun" "${flags[@]}" "$@" ;;
*) unset DBUS_SESSION_BUS_ADDRESS
if command -v dbus-run-session >/dev/null 2>&1; then
dbus-run-session -- "$APPDIR/AppRun" "${flags[@]}" "$@"
else
"$APPDIR/AppRun" "${flags[@]}" "$@"
fi ;;
esac
rc=$?
# 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
for p in /proc/[0-9]*; do
exe=$(readlink "$p/exe" 2>/dev/null) || continue
case $exe in "$APPDIR"/*) return 0 ;; esac
done
return 1
}
while image_running; do sleep 2; done
exit $rc
@@ -1,37 +0,0 @@
#!/bin/bash
# A script added on the Desktop page (UserApps), run from its own folder:
# bannerlator-script-run /opt/droiddeck-apps/<id> [args...]
set -u
dir=${1:?usage: bannerlator-script-run <added app directory> [args...]}
shift
entry=$(cat "$dir/entry" 2>/dev/null) || { echo "bannerlator-script-run: $dir has no entry" >&2; exit 127; }
cd -P "$dir/files" 2>/dev/null || { echo "bannerlator-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)
case $first in '#!'*) read -r -a interp <<< "${first#'#!'}" ;; esac
echo "== script $entry in $folder (${interp[*]})"
case ${DBUS_SESSION_BUS_ADDRESS:-} in
unix:*) "${interp[@]}" "./$entry" "$@" ;;
*) unset DBUS_SESSION_BUS_ADDRESS
if command -v dbus-run-session >/dev/null 2>&1; then
dbus-run-session -- "${interp[@]}" "./$entry" "$@"
else
"${interp[@]}" "./$entry" "$@"
fi ;;
esac
rc=$?
# A launcher script often starts the game and returns; the session lasts while it runs.
running() {
local p exe
for p in /proc/[0-9]*; do
exe=$(readlink "$p/exe" 2>/dev/null) || continue
case $exe in "$folder"/*) return 0 ;; esac
done
return 1
}
while running; do sleep 2; done
exit $rc
@@ -1,641 +0,0 @@
#!/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.
#
# bannerlator-steam-compat <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 os
import re
import shutil
import sys
TOOL = "bannerlator-proton-arm64"
# Valve's own ARM64 Proton, by the name the client registers it under. Used only to bootstrap a
# fresh install: naming it is what makes the client offer it and fetch the depot.
SEED_TOOL = "proton-experimental-arm64"
# 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 = "bannerlator-proton"
# The extra Steam library the app mounts the installed games into (see bannerlator-steam-library).
# installed_apps() scans it too; it lives only in the sibling script, so define it here as well.
LIBRARY = "/mnt/bannerlator" # 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.
SOURCES = ("Proton Experimental (ARM64)", "Proton 11.0 (ARM64)")
# Written by us; everything else in the depot is symlinked through.
OWN_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", "bannerlator-proton")
# 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"
{
"%s"
{
"install_path" "."
"display_name" "Bannerlator Proton (ARM64)"
"from_oslist" "windows"
"to_oslist" "linux"
}
}
}
"""
TOOL_MANIFEST_VDF = """"manifest"
{
"version" "2"
"commandline" "/%s %%verb%%"
"use_sessions" "1"
"compatmanager_layer_name" "proton"
}
""" % 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.
BL_COMPONENTS_SETUP = """
bl_components() {
base=$1
cm_dir="${HOME:-/root}/.local/share/bannerlator-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=${cm_app##*/}
cm_tool=${base##*/}
cm_build=$(awk 'NR == 1 { print $2 }' "$base/version" 2>/dev/null)
cm_fixed=0
cm_checked=0
while IFS=$'\\t' read -r t want comp rel sum src; do
[ "$t" = "$cm_tool" ] && [ "$want" = "$cm_build" ] || continue
cm_checked=$((cm_checked + 1))
f="$base/$rel"
if [ -f "$f" ] && [ "$(sha256sum "$f" | cut -d' ' -f1)" = "$sum" ]; then continue; fi
if [ ! -f "$src" ]; then
echo "bannerlator-proton: components: $comp source missing ($src), left as it is" >&2
continue
fi
mkdir -p "$(dirname "$f")"
cp -f "$src" "$f.bl-new" && mv -f "$f.bl-new" "$f" || continue
case "$rel" in *.so) chmod 755 "$f" ;; *) chmod 644 "$f" ;; esac
cm_fixed=$((cm_fixed + 1))
done < "$cm_list"
[ "$cm_checked" -gt 0 ] && echo "bannerlator-proton: components: checked $cm_checked file(s) in $cm_tool for app $cm_app" >&2
if [ "$cm_fixed" -gt 0 ]; then
echo "bannerlator-proton: components: re-applied $cm_fixed of $cm_checked file(s) in $cm_tool before this launch" >&2
printf '%s\\t%s\\t%s\\n' "$(date +%s)" "$cm_tool" "$cm_fixed" >> "$cm_dir/reapplied.log"
fi
}
"""
# 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 "bannerlator-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
IFS=:
for dir in $LD_LIBRARY_PATH; do
case $dir in
"" | */steamrtarm64 | */steamrtarm64/*) ;;
*) kept=${kept:+$kept:}$dir ;;
esac
done
IFS=$old_ifs
if [ -n "$kept" ]; then export LD_LIBRARY_PATH="$kept"; else unset LD_LIBRARY_PATH; fi
}
"""
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
case " $* " in
*r_fullscreen*|*r_mode*|*r_customwidth*|*r_customheight*)
echo "bannerlator-proton: Quake-engine title; its launch options set the video mode, left as they are" >&2
return 0 ;;
esac
w=${BL_WIDTH:-1280}
h=${BL_HEIGHT:-720}
BL_EXTRA_ARGS=(+set r_fullscreen 0 +set r_mode -1 +set r_customwidth "$w" +set r_customheight "$h")
echo "bannerlator-proton: Quake-engine title: windowed at ${w}x${h}" >&2
}
"""
BL_DIRECTAUDIO_SETUP = """
bl_directaudio() {
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO/lib/wine" ] || return 0
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
major=${version#wine-}
major=${major%%.*}
if [ "$major" != "11" ]; then
echo "bannerlator-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
# Wine appends the per-architecture subdirectory to each entry, so the directory holding
# aarch64-unix/ and aarch64-windows/ is what goes here.
WINEDLLPATH="$BL_DIRECTAUDIO/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
export WINEDLLPATH
# 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.
reg="${STEAM_COMPAT_DATA_PATH:-}/pfx/user.reg"
if [ -f "$reg" ]; then
if ! grep -q '"Audio"="directaudio"' "$reg" 2>/dev/null; then
printf '\n[Software\\\\Wine\\\\Drivers] %s\n"Audio"="directaudio"\n' "$(date +%s)" >> "$reg"
echo "bannerlator-proton: DirectAudio selected in the prefix" >&2
fi
else
# A prefix that does not exist yet is created by Proton moments from now, after this runs, so
# the key lands on the NEXT launch of that game. Said out loud because silent audio on a first
# launch would otherwise look like a fault.
echo "bannerlator-proton: no prefix yet - DirectAudio takes effect the next time this game starts" >&2
fi
echo "bannerlator-proton: DirectAudio ready (Wine $major)" >&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
# Bannerlator 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.
fake=/usr/local/lib/libfakeinput.so
if [ -f "$fake" ]; then
case ":${LD_PRELOAD:-}:" in
*":$fake:"*) ;;
*) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;;
esac
fi
# The newest of the ARM64 depots the client has, by the build number that opens each one's version
# file: taking the first one found ran a stale Experimental over a newer 11.0. (WinNative.)
depot=
best=0
for name in %s; do
for library in "$steam_root" /mnt/droiddeck-sd; do
candidate="$library/steamapps/common/$name"
[ -d "$candidate/files/bin-arm64" ] && [ -x "$candidate/proton" ] || continue
build=0
read -r build _ 2>/dev/null < "$candidate/version"
case $build in "" | *[!0-9]*) build=0 ;; esac
if [ -z "$depot" ] || [ "$build" -gt "$best" ]; then
depot=$candidate
best=$build
fi
done
done
if [ -n "$depot" ]; then
bl_components "$depot"
bl_directaudio "$depot"
bl_game_cpus
bl_idtech3 "$@"
bl_libpath
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
fi
echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2
exit 1
""" % " ".join('"%s"' % n for n in SOURCES)
# Spliced in after the formatting above, 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.
LAUNCHER_SH = LAUNCHER_SH.replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
# 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 = "bannerlator-proton-wrap"
EXTRA_MANIFEST_VDF = """"manifest"
{
"version" "2"
"commandline" "/%s %%verb%%"
"use_sessions" "1"
"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
# Bannerlator: 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 bannerlator-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.
fake=/usr/local/lib/libfakeinput.so
if [ -f "$fake" ]; then
case ":${LD_PRELOAD:-}:" in
*":$fake:"*) ;;
*) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;;
esac
fi
bl_components "$here"
bl_directaudio "$here"
bl_game_cpus
bl_idtech3 "$@"
bl_libpath
# Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be
# started from its own tree.
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
"""
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
{
"compat_tools"
{
"%s"
{
"install_path" "."
"display_name" "%s (Bannerlator)"
"from_oslist" "windows"
"to_oslist" "linux"
}
}
}
"""
TOKEN = re.compile(r'\s*(?:"((?:[^"\\]|\\.)*)"|([{}])|//[^\n]*)')
def tokenize(text):
tokens = []
pos = 0
while pos < len(text):
m = TOKEN.match(text, pos)
if not m or m.end() == pos:
break
pos = m.end()
if m.group(2):
tokens.append(m.group(2))
elif m.group(1) is not None:
tokens.append('"' + m.group(1) + '"')
return tokens
def find_block(tokens, path):
"""Index of the '{' opening the block at path, or None."""
depth, want, i = 0, 0, 0
while i < len(tokens):
t = tokens[i]
if t == "{":
depth += 1
elif t == "}":
depth -= 1
if depth < want:
return None
elif depth == want and i + 1 < len(tokens) and tokens[i + 1] == "{":
if t.lower() == '"%s"' % path[want].lower():
if want == len(path) - 1:
return i + 1
want += 1
i += 1
return None
def block_end(tokens, start):
depth = 0
for i in range(start, len(tokens)):
if tokens[i] == "{":
depth += 1
elif tokens[i] == "}":
depth -= 1
if depth == 0:
return i
return len(tokens)
def serialize(tokens):
out, depth, i = [], 0, 0
while i < len(tokens):
t = tokens[i]
if t == "}":
depth -= 1
out.append("\t" * depth + "}")
i += 1
elif i + 1 < len(tokens) and tokens[i + 1] == "{":
out.append("\t" * depth + t)
out.append("\t" * depth + "{")
depth += 1
i += 2
else:
out.append("\t" * depth + t + "\t\t" + tokens[i + 1])
i += 2
return "\n".join(out) + "\n"
def write_changed(path, text, mode=None):
"""Writes `text` to `path` only when it differs, through a rename so a reader never sees half a
file. The session runs this script every 15 s for as long as the client does; rewriting files
that have not changed cost a python start's worth of writes each time, and config.vdf is the
client's own, which it may be writing at that moment. Returns whether anything was written."""
try:
with open(path, encoding="utf-8", errors="replace") as f:
same = f.read() == text
except OSError:
same = False
if not same:
tmp = path + ".bannerlator"
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
if mode is not None:
os.chmod(tmp, mode)
os.replace(tmp, path)
elif mode is not None and (os.stat(path).st_mode & 0o7777) != mode:
os.chmod(path, mode)
return not same
def first_key(path, section):
"""The single key naming a block inside `section`, or None. Used to keep a third-party tool's
own internal name, so a mapping the user already made against it keeps working."""
try:
with open(path, encoding="utf-8", errors="replace") as f:
tokens = tokenize(f.read())
except OSError:
return None
block = find_block(tokens, section)
if block is None:
return None
for i in range(block + 1, block_end(tokens, block)):
if tokens[i] == "}":
break
if i + 1 < len(tokens) and tokens[i + 1] == "{":
return tokens[i].strip('"')
return None
def manifest_entry_point(path):
"""The script a toolmanifest's commandline runs, relative to the tool directory."""
try:
with open(path, encoding="utf-8", errors="replace") as f:
tokens = tokenize(f.read())
except OSError:
return None
for i in range(len(tokens) - 1):
if tokens[i].lower() == '"commandline"':
command = tokens[i + 1].strip('"').split()
if command:
return command[0].lstrip("/")
return None
def adopt_extras(tools):
"""Makes every other Proton in compatibilitytools.d launchable here, and returns the tool names
to leave alone in CompatToolMapping - the whole point of installing one is to pick it per game,
so register_default must not repoint it back at ours."""
adopted = {}
try:
entries = sorted(os.listdir(tools))
except OSError:
return adopted
for entry in entries:
if entry == TOOL or entry.startswith("."):
continue
tool_dir = os.path.join(tools, entry)
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 + ".bannerlator-orig"
if not os.path.isfile(original):
try:
shutil.copy2(manifest, original)
except OSError:
continue
entry_point = manifest_entry_point(original)
if not entry_point or entry_point == EXTRA_WRAPPER:
entry_point = "proton"
if not os.path.exists(os.path.join(tool_dir, entry_point)):
print("bannerlator-steam-compat: %s has no %s; left alone" % (entry, entry_point))
continue
compat_vdf = os.path.join(tool_dir, "compatibilitytool.vdf")
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, 1)
write_changed(wrapper, body, 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, entry))
except OSError as e:
print("bannerlator-steam-compat: could not adopt %s (%s)" % (entry, e))
continue
adopted[name] = entry
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)
"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)
))
def installed_apps(steam_root):
"""App ids of the titles the client has installed, tools and runtimes excluded."""
apps = set()
for library in (steam_root, LIBRARY + "-sd"):
steamapps = os.path.join(library, "steamapps")
try:
names = os.listdir(steamapps)
except OSError:
continue
for name in names:
m = re.fullmatch(r"appmanifest_(\d+)\.acf", name)
if m and m.group(1) not in NOT_GAMES:
apps.add(m.group(1))
return sorted(apps, key=int)
def register_default(config_path, apps=(), name=None, protect=()):
"""Writes the mapping. `name` defaults to our own tool; the first-run seed passes Valve's."""
tool = name or TOOL
# Tool names the user may deliberately have chosen (see adopt_extras); never repointed.
keep = {n.lower() for n in protect}
with open(config_path, encoding="utf-8", errors="replace") as f:
original = f.read()
tokens = tokenize(original)
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
if steam is None:
return
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
entry = ['"0"', "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"', "}"]
if mapping is None:
end = block_end(tokens, steam)
tokens[end:end] = ['"CompatToolMapping"', "{"] + entry + ["}"]
else:
mapping += steam + 1
# Repoint every per-app entry the client aimed at a Proton it cannot actually start.
for i in range(mapping, block_end(tokens, mapping)):
named = tokens[i + 1].strip('"').lower()
if (tokens[i] == '"name"' and named.startswith("proton")
and named != tool.lower() and named not in keep):
tokens[i + 1] = '"%s"' % tool
if find_block(tokens[mapping + 1:], ["0"]) is None:
tokens[mapping + 1:mapping + 1] = entry
# The "0" default only decides how a title is installed, so it settles new downloads and
# leaves anything already installed as a Linux build running as one. An entry per installed
# app is what the client's own Compatibility checkbox writes, and is what makes it switch.
for app in apps:
if find_block(tokens[mapping + 1:], [app]) is not None:
continue
tokens[mapping + 1:mapping + 1] = [
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"250"', "}"]
# Nothing to change is the usual case on the session's beat: the client's own file is left alone.
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config_path, text)
def depot_build(depot):
"""The build number a depot's version file starts with; 0 when there is none."""
try:
with open(os.path.join(depot, "version"), encoding="utf-8", errors="replace") as f:
first = f.read().split(None, 1)
except OSError:
return 0
return int(first[0]) if first and first[0].isdigit() else 0
def find_source(steam_root):
"""The newest ARM64 Proton depot the client has downloaded (the one the launcher runs), or None."""
# bin-arm64 is what makes it the native build rather than the x86_64 one.
found = [os.path.join(root, "steamapps", "common", name)
for root in (steam_root, "/mnt/droiddeck-sd") for name in SOURCES
if os.path.isdir(os.path.join(root, "steamapps", "common", name, "files", "bin-arm64"))]
return max(found, key=depot_build) if found else None
def build_tool(tool_dir):
"""Our own manifests and the launcher. The depot is found at launch time, not here."""
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)
write_changed(os.path.join(tool_dir, "compatibilitytool.vdf"), COMPAT_TOOL_VDF % TOOL)
write_changed(os.path.join(tool_dir, LAUNCHER), LAUNCHER_SH, 0o755)
def main():
steam_root = sys.argv[1]
tools = os.path.join(steam_root, "compatibilitytools.d")
os.makedirs(tools, exist_ok=True)
build_tool(os.path.join(tools, TOOL))
extras = adopt_extras(tools)
for name, directory in sorted(extras.items()):
print("bannerlator-steam-compat: adopted %s as %s" % (directory, name))
depot = find_source(steam_root)
print("bannerlator-steam-compat: registered %s (%s)" % (
TOOL, "depot %s present" % os.path.basename(depot) if depot else
"no ARM64 Proton depot yet; the session asks the client to fetch it"))
config = os.path.join(steam_root, "config", "config.vdf")
if os.path.isfile(config):
apps = installed_apps(steam_root)
register_default(config, apps, protect=extras)
print("bannerlator-steam-compat: default and %d installed title(s) set to %s" % (len(apps), TOOL))
if __name__ == "__main__":
main()
+122
View File
@@ -0,0 +1,122 @@
#!/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
# 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
fi
flags=()
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
flags+=(--no-sandbox)
if [ -n "${DISPLAY:-}" ]; then
export XDG_SESSION_TYPE=x11
unset WAYLAND_DISPLAY
flags+=(--ozone-platform=x11)
fi
fi
qt=$(cat "$dir/qt" 2>/dev/null)
case $qt in wayland|xcb) ;; *) qt=auto ;; esac
wayland=${GAMESCOPE_WAYLAND_DISPLAY:-${WAYLAND_DISPLAY:-}}
if [ "$qt" = auto ] && [ -n "$wayland" ]; then
bundled=$(find "$APPDIR" -maxdepth 6 \( -name 'libQt6Quick.so.6*' -o -name libvulkan.so.1 -o -name 'libqwayland*.so' \) -printf '%f\n' 2>/dev/null)
if grep -q '^libQt6Quick\.so\.6' <<<"$bundled"; then
if grep -q '^libqwayland' <<<"$bundled" \
&& { grep -qx libvulkan.so.1 <<<"$bundled" || grep -qs QVulkanInstance "$APPDIR"/usr/bin/* "$APPDIR"/bin/*; }; then
qt=wayland
else
echo "== appimage: Qt Quick without Vulkan or Qt's Wayland plugin stays on X11 ($(tr '\n' ' ' <<<"$bundled"))"
fi
fi
fi
if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
export QT_QPA_PLATFORM='wayland;xcb' WAYLAND_DISPLAY=$wayland SDL_VIDEODRIVER=wayland XDG_SESSION_TYPE=wayland
[ "$wayland" = "${GAMESCOPE_WAYLAND_DISPLAY:-}" ] && export QT_WAYLAND_DISABLE_WINDOWDECORATION=1 DISABLE_GAMESCOPE_WSI=1
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
export QT_QPA_PLATFORM=xcb
fi
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("$APPDIR/AppRun")
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $fex:$(cat "$dir/arch" 2>/dev/null) in
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
auto:arm64) ;;
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
esac
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
if command -v dbus-run-session >/dev/null 2>&1; then
dbus-run-session -- "${run[@]}" "${flags[@]}" "$@"
else
"${run[@]}" "${flags[@]}" "$@"
fi ;;
esac
rc=$?
if [ "$rc" -gt 128 ]; then
echo "== appimage $ARGV0: ended by signal $((rc - 128)) ($(kill -l $((rc - 128)) 2>/dev/null))"
else
echo "== appimage $ARGV0: exited with status $rc"
fi
if [ "$rc" -ne 0 ] && [ -n "$started" ]; then
find "${HOME:-/root}/.local/share" "${HOME:-/root}/.config" "${HOME:-/root}/.cache" -maxdepth 4 -type f \
\( -iname '*.log' -o -iname '*log*.txt' \) -newer "$started" -size -64M 2>/dev/null | head -n 3 |
while IFS= read -r log; do
echo "== appimage $ARGV0: end of $log"
tail -n 40 "$log" | LC_ALL=C tr -cd '\11\12\40-\176' | cut -c1-400
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
exe=$(readlink "$p/exe" 2>/dev/null) || continue
case $exe in "$APPDIR"/*) return 0 ;; esac
case $exe in
*/FEX|*/FEXInterpreter)
arg=$(tr '\0' '\n' < "$p/cmdline" 2>/dev/null | sed -n 2p)
cwd=$(readlink "$p/cwd" 2>/dev/null)
case $arg in "$APPDIR"/*) return 0 ;; esac
case $cwd in "$APPDIR"|"$APPDIR"/*) return 0 ;; esac
;;
esac
done
return 1
}
while image_running; do sleep 2; done
exit $rc
@@ -4,7 +4,7 @@
# 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.
#
# bannerlator-desktop-games [steam root]
# droiddeck-desktop-games [steam root]
import os
import re
import sys
@@ -90,7 +90,7 @@ def write_entries():
safe = name.replace("\n", " ").strip() or str(appid)
body = (
"[Desktop Entry]\nType=Application\nName=%s\nComment=Steam game %d - opens in Steam under gamescope\n"
"Exec=/usr/local/bin/bannerlator-steam-launch desktop %d\nIcon=%s\nTerminal=false\n"
"Exec=/usr/local/bin/droiddeck-steam-launch desktop %d\nIcon=%s\nTerminal=false\n"
"Categories=Game;\nX-DroidDeck-AppId=%d\n" % (safe, appid, appid, icon_for(appid), appid)
)
path = os.path.join(APPS_DIR, "%s%d.desktop" % (PREFIX, appid))
@@ -123,7 +123,7 @@ def link_libraries():
def main():
wanted = write_entries()
link_libraries()
print("bannerlator-desktop-games: %d entr%s of ours, %d the client's" % (
print("droiddeck-desktop-games: %d entr%s of ours, %d the client's" % (
len(wanted), "y" if len(wanted) == 1 else "ies", len(client_entries())))
@@ -364,11 +364,21 @@ def load_packs(root):
return packs
def line_epoch(line):
fields = (line or "").split()
try:
return int(fields[0]) if fields else 0
except ValueError:
return 0
def match_kind(pack, measured):
if pack.get("revoked") or pack.get("ignored") or measured["builtin"]:
return None
stock = pack["stock"]
if stock[NTDLL] == measured["ntdll"] and stock[WINESERVER] == measured["wineserver"]:
if pack.get("version") != measured["token"] and line_epoch(pack.get("version_line")) > line_epoch(measured["version_line"]) > 0:
return None
return "exact"
if (pack.get("source_match") is True and measured["token"] and pack.get("version") == measured["token"]
and pack.get("exports") == measured["exports"]):
@@ -383,7 +393,7 @@ def find_pack(packs, measured):
kind = match_kind(pack, measured)
if kind is None:
continue
key = (kind == "exact", pack["rev"], pack["id"])
key = (kind == "exact", bool(measured["token"]) and pack.get("version") == measured["token"], pack["rev"], pack["id"])
if best_key is None or key > best_key:
best, best_key = pack, key
return best
@@ -789,6 +799,18 @@ def keep_live(root, command, env, tool):
return None
if not os.path.isfile(kept_command) or not server_running(prefix):
return None
kept_pack = row["env"].get("BL_SYNC_PACK")
if isinstance(kept_pack, str) and kept_pack and command[1:2] == ["waitforexitandrun"]:
try:
cache = HashCache(root)
try:
pack = find_pack(load_packs(root), measure(tool, cache))
finally:
cache.save()
except (OSError, ValueError):
pack = {"id": kept_pack}
if pack is None or pack["id"] != kept_pack:
return None
command, env = list(command), dict(env)
command[0] = kept_command
for name in LIVE_KEYS:
+659
View File
@@ -0,0 +1,659 @@
#!/usr/bin/python3
import contextlib
import fcntl
import filecmp
import gzip
import json
import os
import re
import runpy
import shutil
import struct
import subprocess
import sys
HOME = os.environ.get("HOME") or "/root"
STEAM_ROOT = os.path.join(HOME, ".local", "share", "Steam")
LIBRARIES = ("/mnt/droiddeck", "/mnt/droiddeck-sd")
STATE = os.path.join(HOME, ".local", "share", "droiddeck-fex")
CONFIG_DIR = os.path.join(STATE, "config")
DATA_DIR = os.path.join(STATE, "data")
CACHE_DIR = os.path.join(HOME, ".cache", "droiddeck-fex")
STATUS_FILE = os.path.join(STATE, "status.json")
WANTED = os.path.join(HOME, ".config", "droiddeck", "fex-wanted")
GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment.json")
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
PRELOADS = "/usr/local/lib/droiddeck-fex"
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"}
MARKER = ".droiddeck-fex"
LAYOUT = 1
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so")
FAULT_REPORT = "libfaultreport.so"
FAULT_REPORT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + FAULT_REPORT
THUNK_AUDIT = "libthunkaudit.so"
THUNK_AUDIT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + THUNK_AUDIT
VULKAN_PIN = "libvulkan-thunk.so"
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]")
BUNDLE_DEPTH = 3
THUNKS = {"GL": 1, "Vulkan": 1}
X86 = {3: "i386", 62: "x86_64"}
ARM = {40: "arm", 183: "arm64"}
SCAN_DEPTH = 4
SCAN_LIMIT = 4000
MODES = ("auto", "on", "off")
STEAM_VERBS = ("run", "waitforexitandrun")
ESCAPE = re.compile(rb"\\([0-7]{3})")
def say(message):
print("droiddeck-fex: %s" % message, file=sys.stderr, flush=True)
def read_text(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
except OSError:
return None
def write_if_changed(path, data, mode=0o644):
if isinstance(data, str):
data = data.encode("utf-8")
try:
with open(path, "rb") as f:
if f.read() == data:
return False
except OSError:
pass
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = "%s.%d.tmp" % (path, os.getpid())
with open(tmp, "wb") as f:
f.write(data)
os.chmod(tmp, mode)
os.replace(tmp, path)
return True
def copy_if_changed(source, target):
if os.path.isfile(target) and filecmp.cmp(source, target, shallow=False):
return False
os.makedirs(os.path.dirname(target), exist_ok=True)
tmp = "%s.%d.tmp" % (target, os.getpid())
shutil.copyfile(source, tmp)
os.chmod(tmp, 0o755)
os.replace(tmp, target)
return True
@contextlib.contextmanager
def locked():
os.makedirs(STATE, exist_ok=True)
with open(os.path.join(STATE, "lock"), "w") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def libraries():
roots = [STEAM_ROOT]
text = read_text(os.path.join(STEAM_ROOT, "steamapps", "libraryfolders.vdf")) or ""
roots += [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', text)]
roots += LIBRARIES
seen, found = set(), []
for root in roots:
real = os.path.realpath(root)
if real not in seen and os.path.isdir(os.path.join(root, "steamapps")):
seen.add(real)
found.append(root)
return found
def app_dir(appid):
for library in libraries():
steamapps = os.path.join(library, "steamapps")
match = re.search(r'"installdir"\s+"([^"]+)"', read_text(os.path.join(steamapps, "appmanifest_%s.acf" % appid)) or "")
for name in filter(None, (match.group(1) if match else None, INSTALL_DIRS.get(appid))):
path = os.path.join(steamapps, "common", name)
if os.path.isdir(path):
return path
return None
def first_dir(prefix, candidates):
for candidate in candidates:
path = os.path.join(prefix, candidate)
if os.path.isdir(path):
return path
return None
def fex_install():
prefixes = []
tool = app_dir(FEX_APPID)
if tool:
prefixes += [(os.path.join(tool, sub), True) for sub in ("usr", "", "files/usr", "files")]
prefixes.append(("/usr", False))
for prefix, portable in prefixes:
binary = next((os.path.join(prefix, "bin", name) for name in ("FEX", "FEXInterpreter")
if os.access(os.path.join(prefix, "bin", name), os.X_OK)), None)
if not binary:
continue
server = os.path.join(prefix, "bin", "FEXServer")
thunks_db = os.path.join(prefix, "share", "fex-emu", "ThunksDB.json")
return {
"bin": binary,
"server": server if os.access(server, os.X_OK) else shutil.which("FEXServer"),
"portable": portable,
"host_thunks": first_dir(prefix, ("lib/aarch64-linux-gnu/fex-emu/HostThunks", "lib/fex-emu/HostThunks", "lib64/fex-emu/HostThunks")),
"guest_thunks": first_dir(prefix, ("share/fex-emu/GuestThunks",)),
"thunks_db": thunks_db if os.path.isfile(thunks_db) else None,
}
return None
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)
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 = [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)
def unescape(raw):
return ESCAPE.sub(lambda match: bytes([int(match.group(1), 8)]), raw)
def in_root(root, link, target):
if not target.startswith(b"/"):
return target
relative = target.lstrip(b"/")
if relative == b"usr" or relative.startswith(b"usr/"):
relative = relative[4:]
return os.path.relpath(os.path.join(root, relative), os.path.dirname(link))
def materialize(platform):
mtree = os.path.join(platform, "usr-mtree.txt.gz")
info = os.stat(mtree)
stamp = "%d %d %d\n" % (LAYOUT, info.st_size, info.st_mtime_ns)
root = os.fsencode(os.path.join(platform, "files"))
marker = os.path.join(os.fsdecode(root), MARKER)
if read_text(marker) == stamp:
return False
links = []
with gzip.open(mtree, "rb") as source:
for line in source:
parts = line.split()
if not parts or parts[0].startswith(b"#"):
continue
fields = dict(part.split(b"=", 1) for part in parts[1:] if b"=" in part)
relative = os.path.normpath(unescape(parts[0]))
if os.path.isabs(relative) or relative == b".." or relative.startswith(b"../"):
continue
dest = os.path.join(root, relative)
kind = fields.get(b"type")
if kind == b"dir":
os.makedirs(dest, exist_ok=True)
elif kind == b"file" and b"contents" in fields:
blob = os.path.join(root, os.path.normpath(unescape(fields[b"contents"])))
links.append((dest, os.path.relpath(blob, os.path.dirname(dest))))
elif kind == b"link" and b"link" in fields:
links.append((dest, in_root(root, dest, unescape(fields[b"link"]))))
for dest, target in links:
if os.path.islink(dest):
if os.readlink(dest) == target:
continue
os.unlink(dest)
elif os.path.lexists(dest):
continue
os.makedirs(os.path.dirname(dest), exist_ok=True)
os.symlink(target, dest)
usr = os.path.join(root, b"usr")
if not os.path.lexists(usr):
os.symlink(b".", usr)
write_if_changed(marker, stamp)
return True
def host_preloads():
listed = read_text(HOST_PRELOAD) or ""
return [name for name in PRELOAD_NAMES if name in listed]
def install_preloads(root):
shipped = set()
for arch, libdir in GUEST_LIBDIRS:
for name in PRELOAD_NAMES:
source = os.path.join(PRELOADS, arch, name)
if os.path.isfile(source):
copy_if_changed(source, os.path.join(root, libdir, "droiddeck", name))
shipped.add(name)
for name in (FAULT_REPORT, 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))
wanted = [name for name in host_preloads() if name in shipped]
write_if_changed(os.path.join(root, "etc", "ld.so.preload"), "".join("/usr/$LIB/droiddeck/%s\n" % name for name in wanted))
def write_config(fex, root):
config = {"Config": {"RootFS": root}}
if fex["host_thunks"] and fex["guest_thunks"] and fex["thunks_db"]:
config["Config"]["ThunkHostLibs"] = fex["host_thunks"]
config["Config"]["ThunkGuestLibs"] = fex["guest_thunks"]
config["ThunksDB"] = dict(THUNKS)
write_if_changed(os.path.join(CONFIG_DIR, "ThunksConfig.json"), json.dumps({"ThunksDB": dict(THUNKS)}, indent=2) + "\n")
write_if_changed(os.path.join(CONFIG_DIR, "Config.json"), json.dumps(config, indent=2) + "\n")
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"
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)
break
def steam_running():
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/cmdline" % pid, "rb") as f:
first = f.read().split(b"\0", 1)[0]
except OSError:
continue
if first.endswith(b"steamrtarm64/steam"):
return True
return False
def request_install():
os.makedirs(os.path.dirname(WANTED), exist_ok=True)
write_if_changed(WANTED, "1\n")
if not steam_running():
return []
try:
compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility"))
return compat["request_fex"](STEAM_ROOT, set())
except Exception as error:
say("could not ask the client to install FEX (%s)" % error)
return []
def describe(fex, platform):
return {
"fex": fex["bin"] if fex else None,
"server": fex["server"] if fex else None,
"thunks": bool(fex and fex["host_thunks"] and fex["guest_thunks"] and fex["thunks_db"]),
"runtime": 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),
}
def prepare():
with locked():
fex = fex_install()
platform = runtime_platform()
status = describe(fex, platform)
if not status["ready"]:
missing = []
tool = app_dir(FEX_APPID)
if not fex and tool:
say("FEX is installed at %s but holds no FEX or FEXInterpreter in usr/bin, bin or files; it has: %s"
% (tool, ", ".join(sorted(os.listdir(tool))[:20])))
if not fex:
missing.append("FEX (Steam app %s)" % FEX_APPID)
elif not fex["server"]:
missing.append("FEXServer beside %s" % fex["bin"])
if not platform:
missing.append("Steam Linux Runtime 3.0 (sniper, Steam app %s)" % SNIPER_APPID)
requested = request_install()
say("x86 Linux programs need %s; %s" % (" and ".join(missing),
"the Steam client was asked to install it" if requested else "open Steam once and it is installed for you"))
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
return None
root = os.path.join(platform, "files")
if materialize(platform):
say("prepared %s as the x86 runtime" % os.path.basename(platform))
install_preloads(root)
write_config(fex, root)
fex["rootfs"] = root
try:
link_steam_sdk()
except OSError:
pass
status = describe(fex, platform)
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
with contextlib.suppress(OSError):
os.unlink(WANTED)
return fex
def elf_arch(path):
try:
with open(path, "rb") as f:
head = f.read(20)
except OSError:
return None
if len(head) < 20 or head[:4] != b"\x7fELF":
return None
machine = struct.unpack_from("<H" if head[5] == 1 else ">H", head, 18)[0]
return X86.get(machine) or ARM.get(machine) or "other"
def scan(folder):
counts = {"x86": 0, "arm": 0}
seen = 0
base = folder.rstrip("/").count("/")
for directory, dirs, files in os.walk(folder):
if directory.count("/") - base >= SCAN_DEPTH:
dirs[:] = []
for name in files:
seen += 1
if seen > SCAN_LIMIT:
return counts
arch = elf_arch(os.path.join(directory, name))
if arch in X86.values():
counts["x86"] += 1
elif arch in ARM.values():
counts["arm"] += 1
return counts
def needs_fex(path):
arch = elf_arch(path)
if arch is not None:
return arch in X86.values()
folder = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path))
counts = scan(folder)
return counts["x86"] > 0 and counts["arm"] == 0
def is_arm(path):
return elf_arch(path) in ARM.values()
def split_paths(value):
return [part for part in re.split(r"[:\s]+", value or "") if part]
def guest_environment(fex, env):
result = dict(env)
for directory in (CONFIG_DIR, DATA_DIR, CACHE_DIR):
os.makedirs(directory, exist_ok=True)
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
result["FEX_APP_DATA_LOCATION"] = DATA_DIR + "/"
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
else:
result.pop("FEX_PORTABLE", None)
for name in ("FEX_ROOTFS", "FEX_THUNKHOSTLIBS", "FEX_THUNKGUESTLIBS"):
if name in result and not os.path.exists(result[name]):
result.pop(name)
if fex.get("rootfs"):
result["FEX_ROOTFS"] = fex["rootfs"]
if fex.get("rootfs") and fex.get("host_thunks") and fex.get("guest_thunks") and fex.get("thunks_db"):
result["FEX_THUNKHOSTLIBS"] = fex["host_thunks"]
result["FEX_THUNKGUESTLIBS"] = fex["guest_thunks"]
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]
for name, parts in (("LD_PRELOAD", preload), ("LD_LIBRARY_PATH", library_path)):
if parts:
result[name] = ":".join(parts)
else:
result.pop(name, None)
return result
def version_names(path):
try:
with open(path, "rb") as f:
return set(VERSION_NAME.findall(f.read()))
except OSError:
return set()
def bundled_libraries(folder):
wanted = [name for name, _ in RUNTIME_LIBRARIES]
found = {}
seen = 0
base = folder.rstrip("/").count("/")
for directory, dirs, files in os.walk(folder):
seen += len(files)
if seen > SCAN_LIMIT:
break
if directory.count("/") - base >= BUNDLE_DEPTH:
dirs[:] = []
for name in wanted:
if name in files and name not in found:
found[name] = os.path.join(directory, name)
return found
def vulkan_thunk_loads(fex, folder):
needed = version_names(os.path.join(fex["guest_thunks"], VULKAN_THUNK))
if not needed:
return False
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)
if not {version for version in needed if version.startswith(prefix)} <= version_names(library):
return False
return True
def resolve(program, env):
if "/" in program:
return os.path.abspath(program)
return shutil.which(program, path=env.get("PATH")) or program
def launch(command, env, mode, decide=None):
program = resolve(command[0], env)
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
if not use:
return os.execvpe(command[0], command, env)
fex = prepare()
if fex is None:
return 126
guest = guest_environment(fex, env)
x86_64 = elf_arch(program) != "i386"
if os.path.isfile(os.path.join(PRELOADS, "x86_64", FAULT_REPORT)) and x86_64:
guest["LD_PRELOAD"] = ":".join([FAULT_REPORT_GUEST] + split_paths(guest.get("LD_PRELOAD")))
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)) \
and vulkan_thunk_loads(fex, folder):
guest["LD_AUDIT"] = ":".join([THUNK_AUDIT_GUEST] + split_paths(guest.get("LD_AUDIT")))
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)
def game_environment(env):
try:
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
app = game_env["game_id"](env) or env.get("SteamAppId") or env.get("SteamGameId")
if not app:
return env
with open(GAME_ENVIRONMENT, encoding="utf-8") as source:
return game_env["apply_config"](env, json.load(source), str(app))
except FileNotFoundError:
return env
except Exception as error:
say("game settings were not applied (%s)" % error)
return env
def appimage_offset(path):
with open(path, "rb") as f:
head = f.read(64)
if head[:4] != b"\x7fELF":
raise ValueError("not an ELF file")
order = "<" if head[5] == 1 else ">"
if head[4] == 2:
shoff, = struct.unpack_from(order + "Q", head, 0x28)
shentsize, shnum = struct.unpack_from(order + "HH", head, 0x3A)
else:
shoff, = struct.unpack_from(order + "I", head, 0x20)
shentsize, shnum = struct.unpack_from(order + "HH", head, 0x2E)
return shoff + shentsize * shnum
def clear_extracted():
for stale in ("squashfs-root", "AppDir"):
if os.path.islink(stale):
os.unlink(stale)
else:
shutil.rmtree(stale, ignore_errors=True)
def extracted():
if os.path.isdir("AppDir") and not os.path.lexists("squashfs-root"):
os.symlink("AppDir", "squashfs-root")
return os.path.isdir("squashfs-root")
def want_fex():
with locked():
status = describe(fex_install(), runtime_platform())
if not status["ready"]:
request_install()
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
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))
if status == 0 and extracted():
if x86:
want_fex()
return 0
say("uruntime could not extract it (status %d)" % status)
clear_extracted()
fex = prepare() if x86 else None
if fex is not None:
status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL,
env=guest_environment(fex, dict(os.environ)))
if status == 0 and extracted():
return 0
say("the image's own runtime could not extract it under FEX (status %d)" % status)
unsquashfs = shutil.which("unsquashfs")
if unsquashfs:
clear_extracted()
status = subprocess.call([unsquashfs, "-q", "-n", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
stdout=subprocess.DEVNULL)
if status == 0:
if x86:
want_fex()
return 0
say("unsquashfs could not extract it (status %d)" % status)
elif fex is None:
say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs")
return 1
def parse_run(args):
mode, decide = os.environ.get("DROIDDECK_FEX", "auto"), None
while args and args[0].startswith("--"):
option = args.pop(0)
if option == "--":
break
if option in ("--mode", "--for") and args:
value = args.pop(0)
if option == "--mode":
mode = value
else:
decide = value
else:
raise ValueError("unknown option %s" % option)
if mode not in MODES:
raise ValueError("--mode takes %s" % ", ".join(MODES))
return mode, decide, args
def main(argv):
if not argv:
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
return 2
action, args = argv[0], list(argv[1:])
if action == "steam":
if not args:
return 2
verb, command = args[0], args[1:]
if verb not in STEAM_VERBS:
return 0
if not command:
return 2
return launch(command, game_environment(dict(os.environ)), os.environ.get("DROIDDECK_FEX", "auto"))
if action == "run":
try:
mode, decide, command = parse_run(args)
except ValueError as error:
say(str(error))
return 2
if not command:
return 2
return launch(command, dict(os.environ), mode, decide)
if action == "needs":
if len(args) != 1:
return 2
needed = needs_fex(args[0])
print("fex" if needed else "native")
return 0 if needed else 1
if action == "extract":
if len(args) != 1:
return 2
return extract(args[0])
if action == "prepare":
return 0 if prepare() else 1
if action == "status":
with locked():
status = describe(fex_install(), runtime_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
say("unknown action %s" % action)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -3,10 +3,10 @@
# reaches the front end as numbers rather than a terminal's redrawn bar. Per-user installation,
# Flathub as the remote, this device's architecture.
#
# bannerlator-flatpak install <app-id> the app and whatever runtimes it needs
# bannerlator-flatpak uninstall <app-id> the app, then runtimes nothing uses any more
# bannerlator-flatpak update [<app-id>] one app, or everything with an update
# bannerlator-flatpak updates what has one (a "updates" line)
# droiddeck-flatpak install <app-id> the app and whatever runtimes it needs
# 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,
@@ -15,7 +15,7 @@ import json
import os
import sys
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/bannerlator-bwrap")
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
import gi # noqa: E402
@@ -216,7 +216,7 @@ def updates():
def main():
if len(sys.argv) < 2:
sys.stderr.write(__doc__ or "usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n")
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
return 2
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "update"):
@@ -229,7 +229,7 @@ def main():
return update(args[0] if args else None)
if cmd == "updates":
return updates()
sys.stderr.write("usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n")
sys.stderr.write("usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
return 2
@@ -1,8 +1,8 @@
#!/bin/bash
# A Flatpak app from the front end, full screen under gamescope like an emulator:
# bannerlator-flatpak-run <app-id> [args...]
# droiddeck-flatpak-run <app-id> [args...]
set -u
export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap
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} ;;
@@ -9,7 +9,7 @@
# 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.
#
# bannerlator-flatpak-setup install or repair; prints "== STEP ..." milestones
# droiddeck-flatpak-setup install or repair; prints "== STEP ..." milestones
set -u
export LANG=C.UTF-8
step() { echo "== STEP $*"; }
@@ -17,7 +17,7 @@ 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 bannerlator-bwrap stands in for it (FLATPAK_BWRAP).
# 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.
@@ -97,7 +97,7 @@ python3 -c 'import gi; gi.require_version("Flatpak", "1.0"); from gi.repository
|| fail "the store helper cannot load libflatpak from Python"
step "Adding Flathub"
export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap
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
@@ -2,9 +2,13 @@
import json
import os
import re
import runpy
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")
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
def game_id(env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
@@ -144,26 +148,91 @@ def apply_config(env, config, app_id, fixes=None):
return result
def sync_config(config, app_id):
games = config.get("games", {})
return {
"version": config.get("version"),
"shared": {name: value for name, value in config.get("shared", {}).items() if name in SYNC_KEYS},
"games": {app_id: {name: value for name, value in games.get(app_id, {}).items() if name in SYNC_KEYS}},
}
def load_sync():
try:
return runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-esync"))
except Exception as error:
print("droiddeck-game-env: sync selection failed (%s); stock launch" % error, file=sys.stderr)
return None
def select_sync(command, env, sync=None):
try:
sync = sync if sync is not None else load_sync()
if sync is None:
return command, env
chosen, chosen_env = sync["select"](command, env)
if chosen and all(isinstance(value, str) for value in chosen) and isinstance(chosen_env, dict):
return list(chosen), dict(chosen_env)
except Exception as error:
print("droiddeck-game-env: sync selection failed (%s); stock launch" % error, file=sys.stderr)
return command, env
def record_stock(sync, command, env):
try:
if sync is not None and "record" in sync:
sync["record"](command, env)
except Exception as error:
print("droiddeck-game-env: stock launch not recorded (%s)" % error, file=sys.stderr)
def without_pack(chosen_env, env):
result = dict(chosen_env)
for name in PACK_KEYS:
if name in env:
result[name] = env[name]
else:
result.pop(name, None)
return result
def main():
command = sys.argv[1:]
if not command:
return 2
env = os.environ.copy()
app_id = game_id(env)
if len(command) > 1 and command[1] == "waitforexitandrun" and app_id:
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
for note in notes:
print("bannerlator-game-env: " + note, file=sys.stderr)
command += extra
if app_id:
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
fixes = {}
if waiting:
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
for note in notes:
print("droiddeck-game-env: " + note, file=sys.stderr)
command += extra
path = Path.home() / ".config/droiddeck/game-environment.json"
try:
with path.open(encoding="utf-8") as source:
env = apply_config(env, json.load(source), app_id, fixes)
config = json.load(source)
if waiting:
env = apply_config(env, config, app_id, fixes)
else:
env = apply_config(env, sync_config(config, app_id), app_id)
except FileNotFoundError:
env = apply_config(env, {"version": 1}, app_id, fixes)
if waiting:
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("bannerlator-game-env: invalid configuration; using inherited environment", file=sys.stderr)
os.execvpe(command[0], command, env)
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
os.execvpe(launch[0], launch, launch_env)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
os.execvpe(launch[0], launch, launch_env)
if __name__ == "__main__":
@@ -126,7 +126,7 @@ class LoginManager:
def main():
directory = os.environ.get("BL_LAUNCH_DIR")
if not directory or not Path(directory).is_dir():
sys.exit("bannerlator-login1: no DroidDeck session directory")
sys.exit("droiddeck-login1: no DroidDeck session directory")
ready = Path(directory) / "steam-sleep-ready"
ready.unlink(missing_ok=True)
loop = GLib.MainLoop()
@@ -27,8 +27,8 @@ IP6 = ROOT + "/IP6Config/1"
AP = ROOT + "/AccessPoint/1"
PROFILE = SETTINGS + "/1"
UUID = "b1d0c8e4-57f0-4c0e-9d60-77696e6e6174"
SNAPSHOT = Path("/etc/bannerlator-network.json")
SCAN_REQUEST = Path("/etc/bannerlator-wifi-scan-request")
SNAPSHOT = Path("/etc/droiddeck-network.json")
SCAN_REQUEST = Path("/etc/droiddeck-wifi-scan-request")
OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
PROPERTIES = "org.freedesktop.DBus.Properties"
@@ -17,7 +17,7 @@ def seed(path, text, what, done="Player 1 on the controller"):
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write(text)
os.replace(path + ".tmp", path)
print(f"bannerlator-pad-defaults: {what}: {done} ({path})")
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
return True
@@ -97,7 +97,7 @@ def rpcs3_shader_mode():
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
f.write(text)
os.replace(cfg + ".tmp", cfg)
print(f"bannerlator-pad-defaults: RPCS3: shader mode {RPCS3_RECOMPILER} ({cfg})")
print(f"droiddeck-pad-defaults: RPCS3: shader mode {RPCS3_RECOMPILER} ({cfg})")
open(marker, "w").close()
@@ -144,7 +144,7 @@ def patch_ini_section(path, section, body, what, needle="SDL-", require=None, do
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(path + ".tmp", path)
print(f"bannerlator-pad-defaults: {what}: {done} ({path})")
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
# DuckStation: SDL-<n>/<name>, axes signed (src/util/sdl_input_source.cpp); Pad1 keys from
@@ -285,12 +285,12 @@ def duckstation():
# 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("bannerlator-pad-defaults: DuckStation: first-time setup already done here")
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("bannerlator-pad-defaults: DuckStation: no screensaver inhibit (no such service here)")
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")
@@ -300,10 +300,10 @@ def duckstation():
own = current if os.path.isabs(current) else os.path.join(os.path.dirname(ini), current)
if not (os.path.isdir(own) and os.listdir(own)):
ini_set(ini, "BIOS", "SearchDirectory", bios_folder(ps1))
print(f"bannerlator-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}")
print(f"droiddeck-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}")
if (ini_get(ini, "GPU", "Renderer") or "Automatic") == "Automatic":
ini_set(ini, "GPU", "Renderer", "Vulkan")
print("bannerlator-pad-defaults: DuckStation: renderer Vulkan")
print("droiddeck-pad-defaults: DuckStation: renderer Vulkan")
open(marker, "w").close()
@@ -451,7 +451,7 @@ def armsx2():
src = os.path.join(old, sub)
if os.path.isdir(src):
shutil.copytree(src, os.path.join(root, sub), dirs_exist_ok=True)
print(f"bannerlator-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})")
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 -
@@ -482,7 +482,7 @@ def armsx2():
require="SettingsVersion", done="games listed from the ROMs folder")
if ini_get(ini, "UI", "SetupWizardIncomplete") == "true":
ini_set(ini, "UI", "SetupWizardIncomplete", "false")
print("bannerlator-pad-defaults: ARMSX2: first-time setup already done here")
print("droiddeck-pad-defaults: ARMSX2: first-time setup already done here")
armsx2_bios(ini)
@@ -507,7 +507,7 @@ def armsx2_bios(ini):
us = [f for f in dumps if any(t in f.lower() for t in ("usa", "(us)", "(us,", "ntsc-u"))]
pick = (us or dumps)[0]
ini_set(ini, "Filenames", "BIOS", pick)
print(f"bannerlator-pad-defaults: ARMSX2: BIOS {pick}")
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
@@ -596,7 +596,7 @@ def dolphin_data():
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
src = os.path.join(work, "squashfs-root/usr/share/dolphin-emu")
if not os.path.isfile(os.path.join(src, "Sys/GC/font_western.bin")):
print("bannerlator-pad-defaults: Dolphin: could not unpack its data from the AppImage")
print("droiddeck-pad-defaults: Dolphin: could not unpack its data from the AppImage")
return
new = DOLPHIN_DATA + ".new"
shutil.rmtree(new, ignore_errors=True)
@@ -605,9 +605,9 @@ def dolphin_data():
f.write(stamp)
shutil.rmtree(DOLPHIN_DATA, ignore_errors=True)
os.rename(new, DOLPHIN_DATA)
print("bannerlator-pad-defaults: Dolphin: its data (fonts, per-game fixes) in " + DOLPHIN_DATA)
print("droiddeck-pad-defaults: Dolphin: its data (fonts, per-game fixes) in " + DOLPHIN_DATA)
except (OSError, subprocess.SubprocessError) as e:
print("bannerlator-pad-defaults: Dolphin: unpacking its data failed: %s" % e)
print("droiddeck-pad-defaults: Dolphin: unpacking its data failed: %s" % e)
finally:
shutil.rmtree(work, ignore_errors=True)
@@ -622,7 +622,7 @@ def dolphin():
wii_pad = os.path.join(d, "WiimoteNew.ini")
if ini_get(wii_pad, "Wiimote1", "Buttons/Home") == "`Guide`":
ini_set(wii_pad, "Wiimote1", "Buttons/Home", "`Shoulder R`")
print("bannerlator-pad-defaults: Dolphin (Wii): Home on the right shoulder button (guide = Dolphin's window)")
print("droiddeck-pad-defaults: Dolphin (Wii): Home on the right shoulder button (guide = Dolphin's window)")
hotkeys = os.path.join(d, "Hotkeys.ini")
if not os.path.isfile(hotkeys):
seed(hotkeys, DOLPHIN_HOTKEYS, "Dolphin", "the guide button shows Dolphin's window (Toggle Fullscreen)")
@@ -631,7 +631,7 @@ def dolphin():
if current is not None and DOLPHIN_GUIDE not in current:
ini_set(hotkeys, "Hotkeys", "General/Toggle Fullscreen",
(current + " | " if current else "") + DOLPHIN_GUIDE)
print("bannerlator-pad-defaults: Dolphin: the guide button shows Dolphin's window (Toggle Fullscreen)")
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.
@@ -647,7 +647,7 @@ def dolphin():
"[Core]\nGFXBackend = Vulkan\n"
"[General]\nISOPaths = 2\nISOPath0 = %s\nISOPath1 = %s\nRecursiveISOPaths = True\n"
"[Interface]\nSkipNKitWarning = True\n" % (gc, wii))
print("bannerlator-pad-defaults: Dolphin: first-time setup (Vulkan, games from %s and %s)" % (gc, wii))
print("droiddeck-pad-defaults: Dolphin: first-time setup (Vulkan, games from %s and %s)" % (gc, wii))
return
try:
count = int(ini_get(ini, "General", "ISOPaths") or "0")
@@ -679,7 +679,7 @@ def dolphin():
ini_set(ini, "General", "RecursiveISOPaths", "True")
changed.append("subfolders")
if changed:
print("bannerlator-pad-defaults: Dolphin: games from " + ", ".join(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):
@@ -691,7 +691,7 @@ def dolphin():
ini_set(ini, "Analytics", "Enabled", "False")
ini_set(ini, "Analytics", "PermissionAsked", "True")
open(marker, "w").close()
print("bannerlator-pad-defaults: Dolphin: Vulkan, no NKit warning")
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
@@ -954,7 +954,7 @@ def melonds():
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines).rstrip("\n") + "\n")
os.replace(path + ".tmp", path)
print(f"bannerlator-pad-defaults: melonDS: {'; '.join(done)} ({path})")
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
@@ -1041,7 +1041,7 @@ def retroarch():
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(cfg + ".tmp", cfg)
print(f"bannerlator-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})")
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
@@ -1090,11 +1090,11 @@ def switch_emulators():
f.write("\n".join(lines) + "\n")
os.replace(cfg + ".tmp", cfg)
open(marker, "w").close()
print(f"bannerlator-pad-defaults: {name}: Player 1 on the controller ({cfg})")
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"bannerlator-pad-defaults: {step.__name__}: {e}")
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")
@@ -1,12 +1,12 @@
#!/usr/bin/python3
# Installs a third-party Proton build into the client's compatibilitytools.d, so it appears in the
# Compatibility dropdown beside Bannerlator Proton (ARM64) and can be picked per game.
# Compatibility dropdown beside our own Proton ARM64 and can be picked per game.
#
# bannerlator-proton-extra <steam root> ge [--tag GE-Proton11-7]
# bannerlator-proton-extra <steam root> cachyos [--tag cachyos-11.0-20260703-slr]
# bannerlator-proton-extra <steam root> <url of an aarch64 tarball>
# bannerlator-proton-extra <steam root> /path/to/an/aarch64/tarball
# bannerlator-proton-extra <steam root> --list what is installed now
# 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/
@@ -16,7 +16,7 @@
# 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
# bannerlator-steam-compat's job (adopt_extras); this script only puts the tree in place and then
# 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
@@ -36,14 +36,14 @@ SOURCES = {
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
}
USER_AGENT = "bannerlator-proton-extra"
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
def log(*args):
print("bannerlator-proton-extra:", *args, flush=True)
print("droiddeck-proton-extra:", *args, flush=True)
def fetch_json(url):
@@ -77,7 +77,7 @@ def release_asset(source, tag):
sums = [u for n, u in assets.items()
if n.startswith(name.split(".tar")[0]) and "sha512" in n]
return tag, assets[name], (sums[0] if sums else None)
raise SystemExit("bannerlator-proton-extra: %s has no ARM64 asset" % tag)
raise SystemExit("droiddeck-proton-extra: %s has no ARM64 asset" % tag)
def download(url, path):
@@ -88,7 +88,7 @@ def download(url, path):
"curl", "-fL", "--retry", "5", "--retry-delay", "3", "--retry-connrefused",
"-C", "-", "-A", USER_AGENT, "-o", path, url])
if rc != 0:
raise SystemExit("bannerlator-proton-extra: download failed (curl %d)" % rc)
raise SystemExit("droiddeck-proton-extra: download failed (curl %d)" % rc)
log("downloaded %.0f MB" % (os.path.getsize(path) / 1048576.0))
@@ -109,7 +109,7 @@ def verify(path, sums_url):
h.update(chunk)
if h.hexdigest() != want:
os.unlink(path)
raise SystemExit("bannerlator-proton-extra: checksum mismatch; the download was deleted")
raise SystemExit("droiddeck-proton-extra: checksum mismatch; the download was deleted")
log("checksum ok")
@@ -118,7 +118,7 @@ def extract(tarball, into):
log("unpacking (a few minutes; nothing is shown while tar runs)")
rc = subprocess.call(["tar", "-xf", tarball, "-C", into])
if rc != 0:
raise SystemExit("bannerlator-proton-extra: tar failed (%d)" % rc)
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(".")]
@@ -128,7 +128,7 @@ def extract(tarball, into):
return path
if len(entries) == 1 and os.path.isdir(os.path.join(into, entries[0])):
return os.path.join(into, entries[0])
raise SystemExit("bannerlator-proton-extra: no Proton tree in the archive")
raise SystemExit("droiddeck-proton-extra: no Proton tree in the archive")
def installed(tools):
@@ -144,7 +144,7 @@ def installed(tools):
def main():
argv = sys.argv[1:]
if not argv:
raise SystemExit(__doc__ or "usage: bannerlator-proton-extra <steam root> ge|cachyos|<url>")
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|<url>")
steam_root = argv.pop(0)
tools = os.path.join(steam_root, "compatibilitytools.d")
os.makedirs(tools, exist_ok=True)
@@ -167,7 +167,7 @@ def main():
if what in SOURCES:
tag, url, sums = release_asset(what, tag) if tag else pick_asset(what)
if not url:
raise SystemExit("bannerlator-proton-extra: no ARM64 build published for %s" % what)
raise SystemExit("droiddeck-proton-extra: no ARM64 build published for %s" % what)
log("%s -> %s" % (what, tag))
elif what.startswith("http"):
url, sums = what, None
@@ -176,14 +176,15 @@ def main():
log("using %s" % what)
else:
raise SystemExit(
"bannerlator-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
"droiddeck-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
free = shutil.disk_usage(tools).free
if free < NEED_BYTES:
raise SystemExit("bannerlator-proton-extra: needs about %d GB free, has %.1f GB" % (
raise SystemExit("droiddeck-proton-extra: needs about %d GB free, has %.1f GB" % (
NEED_BYTES // (1024 ** 3), free / float(1024 ** 3)))
staging = os.path.join(tools, ".bannerlator-download")
shutil.rmtree(os.path.join(tools, ".bannerlator-download"), ignore_errors=True)
staging = os.path.join(tools, ".droiddeck-download")
os.makedirs(staging, exist_ok=True)
if local:
tarball = local
@@ -210,7 +211,7 @@ def main():
# 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(["bannerlator-steam-compat", steam_root])
subprocess.call(["steam-compatibility", steam_root])
if __name__ == "__main__":
+51
View File
@@ -0,0 +1,51 @@
#!/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)
case $first in '#!'*) read -r -a interp <<< "${first#'#!'}" ;; esac
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("${interp[@]}" "./$entry")
if [ -x /usr/local/bin/droiddeck-fex ]; then
run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$folder" -- "${interp[@]}" "./$entry")
fi
echo "== script $entry in $folder (${interp[*]}, FEX $fex)"
case ${DBUS_SESSION_BUS_ADDRESS:-} in
unix:*) "${run[@]}" "$@" ;;
*) unset DBUS_SESSION_BUS_ADDRESS
if command -v dbus-run-session >/dev/null 2>&1; then
dbus-run-session -- "${run[@]}" "$@"
else
"${run[@]}" "$@"
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
exe=$(readlink "$p/exe" 2>/dev/null) || continue
case $exe in "$folder"/*) return 0 ;; esac
case $exe in
*/FEX|*/FEXInterpreter)
arg=$(tr '\0' '\n' < "$p/cmdline" 2>/dev/null | sed -n 2p)
cwd=$(readlink "$p/cwd" 2>/dev/null)
case $arg in "$folder"/*) return 0 ;; esac
case $cwd in "$folder"|"$folder"/*) return 0 ;; esac
;;
esac
done
return 1
}
while running; do sleep 2; done
exit $rc
@@ -81,7 +81,11 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] || continue
seeded=$(dirname "$reg")/.bannerlator-redists
seeded=$(dirname "$reg")/.droiddeck-redists
legacy=$(dirname "$reg")/.bannerlator-redists
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
mv -f "$legacy" "$seeded"
fi
[ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue
dated=$(mktemp) || continue
touch -r "$reg" "$dated"
@@ -1,10 +1,10 @@
#!/bin/bash
# The Linux runtime's session. Bannerlator execs this under proot with the output size and mode;
# The Linux runtime's session. DroidDeck execs this under proot with the output size and mode;
# the first pass starts gamescope, which execs this script again inside it for the program:
# bannerlator-session desktop the file manager
# bannerlator-session run <path> a Linux program (AppImage, script or ELF)
# bannerlator-session steam [steam-url] the native Steam client
# bannerlator-session lxqt the LXQt/labwc desktop (DroidDeck's desktop package)
# droiddeck-session desktop the file manager
# droiddeck-session run <path> a Linux program (AppImage, script or ELF)
# droiddeck-session steam [steam-url] the native Steam client
# droiddeck-session lxqt the LXQt/labwc desktop (DroidDeck's desktop package)
# BL_WIDTH / BL_HEIGHT size the output, BL_FPS limits it, BL_LOG collects everything said here.
set -u
export HOME=${HOME:-/root}
@@ -22,8 +22,8 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
# A guest looping on an error writes gigabytes in minutes (an Xwayland proot had lost track of
# managed 9 GB of one line in 19 min): the log keeps its first BL_LOG_CAP bytes and the rest is
# drained, not refused - a writer that filled it must not die of SIGPIPE.
exec > >({ head -c "${BL_LOG_CAP:-268435456}" >>"$BL_LOG"; cat >/dev/null; }) 2>&1
echo "== bannerlator-session $(date) mode=$mode $*"
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
echo "== droiddeck-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
@@ -42,6 +42,16 @@ collect_steam_logs() {
[ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
# NOT copied, ever: loginusers.vdf, config.vdf and the ssfn* files, which hold the credentials
# themselves rather than a mention of them.
local sync_store=$HOME/.local/share/droiddeck-esync sync_file
if [ -d "$sync_store" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-esync" 2>/dev/null; then
for sync_file in launches.log tools.tsv wanted.tsv prefixes.json; do
[ -f "$sync_store/$sync_file" ] && cp "$sync_store/$sync_file" "$BL_DEBUG_DIR/droiddeck-esync/" 2>/dev/null
done
fi
local fex_state=$HOME/.local/share/droiddeck-fex
if [ -d "$fex_state" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-fex" 2>/dev/null; then
cp "$fex_state/status.json" "$fex_state/config/Config.json" "$BL_DEBUG_DIR/droiddeck-fex/" 2>/dev/null
fi
echo "== steam logs copied to $BL_DEBUG_DIR/steam"
}
# A session that is killed never reaches the copy below, and those are the sessions worth reading.
@@ -93,11 +103,11 @@ export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
/usr/local/bin/bannerlator-desktop-bookmarks || true
/usr/local/bin/droiddeck-desktop-bookmarks || true
fi
# Flatpak (the store's apps): its sandboxes through the app instead of bubblewrap, which needs the
# user namespaces Android keeps from apps, and its apps' menu entries and icons on the desktop.
export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
# The cores a program runs on outside Steam (the desktop and everything started from it, a
@@ -238,32 +248,41 @@ case $mode in
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
fi
# Player 1 on the controller in an emulator that has no profile of its own yet.
python3 /usr/local/bin/bannerlator-pad-defaults 2>&1 || true
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
fex=()
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $(od -An -tu2 -j18 -N2 "$target" 2>/dev/null | tr -d ' ') in
3|62) fex=(/usr/local/bin/droiddeck-fex run --mode on --) ;;
esac
fi
case ${target,,} in
*.appimage)
export APPIMAGE_EXTRACT_AND_RUN=1
chmod +x "$target" 2>/dev/null
exec "$target" "$@"
exec "${fex[@]}" "$target" "$@"
;;
*.sh)
if [ -x /usr/local/bin/droiddeck-fex ]; then
exec /usr/local/bin/droiddeck-fex run --for "$target" -- bash "$target" "$@"
fi
exec bash "$target" "$@"
;;
*)
chmod +x "$target" 2>/dev/null
cd "$(dirname "$target")" && exec "$target" "$@"
cd "$(dirname "$target")" && exec "${fex[@]}" "$target" "$@"
;;
esac
;;
steam)
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
bannerlator-steam-install || exit $?
droiddeck-steam-install || exit $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
# Register the card library (bound at /mnt/droiddeck-sd) with the client - internal storage is
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
# so it is in the Compatibility dropdown the first time the user looks. One per line, each the
# arguments to bannerlator-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
# arguments to droiddeck-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
# Hundreds of megabytes each, so it is only ever done on request, and the line is dropped once
# it has succeeded - a failed download stays and is retried next session.
if [ -s "$HOME/.bl-proton-extra" ]; then
@@ -272,7 +291,7 @@ case $mode in
while read -r _bl_extra || [ -n "$_bl_extra" ]; do
case ${_bl_extra# } in ""|"#"*) continue ;; esac
step "installing Proton '$_bl_extra' (large download, several minutes)"
if bannerlator-proton-extra "$steam_root" $_bl_extra; then
if droiddeck-proton-extra "$steam_root" $_bl_extra; then
step "installed Proton '$_bl_extra'"
else
step "Proton '$_bl_extra' failed; will retry next session"
@@ -323,27 +342,27 @@ case $mode in
fi
step "registering the app's game library with Steam"
bannerlator-steam-library "$steam_root" || true
droiddeck-steam-library "$steam_root" || true
step "setting up the ARM64 Proton compatibility tool"
bannerlator-steam-compat "$steam_root" || true
steam-compatibility "$steam_root" || true
if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
bannerlator-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
fi
# The user's own games, as non-Steam shortcuts under that tool; the list is written by the app
# each session (empty = the app's earlier entries are removed, the client's own are kept).
if [ -n "${BL_ADDED_GAMES:-}" ]; then
step "adding the app's own games to the client's library"
bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
# Steam runs a game's shared redistributables inside its prefix on first launch; marking
# them as already run keeps those x86 installers from starting under emulation at all.
bannerlator-seed-redists "$steam_root" || true
droiddeck-seed-redists "$steam_root" || true
# The compatibility tool runs Valve's arm64 Proton, which the client fetches like any depot.
# Asked for on the command line the first time, so a Windows title has it before it is needed.
if [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
step "asking the client to fetch the ARM64 Proton"
set -- "$@" steam://install/4427310
# Ported from Bannerlator (bannerlator-session, device-proven 2026-09-22). The client decides
# Ported from Bannerlator's session script (device-proven 2026-09-22). The client decides
# a title's compatibility tool when the title is installed and keeps that decision for the
# rest of its run, and the tool is set up before the client comes up. So once the depot has
# fully landed, restart the client once - its own -shutdown, then the loop below, which knows
@@ -357,7 +376,7 @@ case $mode in
# StateFlags 4 = fully installed; a moment more for the client to finish its bookkeeping.
if grep -q '"StateFlags"[[:space:]]*"4"' "$_bl_acf" 2>/dev/null; then
sleep 10
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
step "compatibility layer installed: restarting the Steam client once"
: > "$HOME/.bl-restart-once"
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
@@ -514,10 +533,10 @@ case $mode in
nap 5
beat=$((beat + 1))
[ "$((beat % 3))" -eq 0 ] || continue
bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true
droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true
if compat_due; then
: > "$compat_stamp"
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
fi
done
) &
@@ -542,9 +561,9 @@ case $mode in
# refuses what it cannot do, since the app has no say over Wi-Fi - answer what the client asks.
# The bus config is written here rather than shipped, so a runtime installed earlier gets this
# from the app's copy of the session scripts without a re-host. (WinNative, maxjivi05, e7a224ae.)
if command -v dbus-daemon >/dev/null 2>&1 && command -v bannerlator-netmanager >/dev/null 2>&1; then
mkdir -p /run/dbus /usr/local/share/bannerlator
cat > /usr/local/share/bannerlator/system-bus.conf <<'BUSCONF'
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
@@ -560,21 +579,21 @@ case $mode in
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
dbus-daemon --config-file=/usr/local/share/bannerlator/system-bus.conf --nofork --nopidfile &
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
system_bus=$!
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
sleep 0.1
done
if [ -S /run/dbus/system_bus_socket ]; then
bannerlator-netmanager &
droiddeck-netmanager &
netmanager=$!
echo "== network: system bus up, NetworkManager stand-in running"
# Steam blanks its main UI before calling login1.Suspend. Without the
# matching resume notification it stays black although the menus work.
# Own the name before Steam constructs its login1 proxy at startup.
rm -f "$BL_LAUNCH_DIR/steam-sleep-ready"
bannerlator-login1 &
droiddeck-login1 &
login_manager=$!
for ((_i = 0; _i < 50; _i++)); do
[ -f "$BL_LAUNCH_DIR/steam-sleep-ready" ] && break
@@ -598,26 +617,20 @@ BUSCONF
export STEAM_RUNTIME=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
# Native-Linux x86 games go through Valve's FEX compat tool, which runs FEX with FEX_PORTABLE=1
# - that makes FEX look for its config next to the binary, while the tool writes one into the
# app's compatdata instead. FEX therefore starts with no rootfs, every x86_64 library lookup
# falls through to the host, and the guest shell dies on libreadline before the game is reached.
# FEX_ROOTFS names it outright and is read whatever the config situation.
[ -d /usr/share/guestos/fex-mesa ] && export FEX_ROOTFS=/usr/share/guestos/fex-mesa
# Decky is optional and session scoped: the app's marker opts in, and this supervisor is
# reaped with the client session. Native ARM64 runs directly. A legacy x86_64 asset is used
# only when its recorded architecture and this guest's existing FEX installation agree.
# only when its recorded architecture says so and droiddeck-fex has FEX and its runtime ready.
decky_loader=$HOME/homebrew/services/PluginLoader
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && [ -x /usr/bin/FEX ] && [ -n "${FEX_ROOTFS:-}" ]; }; then
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then
(
decky_child=
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
trap decky_stop TERM INT HUP
decky_exits=0
while :; do
if [ "$decky_arch" = x86_64 ]; then /usr/bin/FEX "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
if [ "$decky_arch" = x86_64 ]; then /usr/local/bin/droiddeck-fex run --mode on -- "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
else "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
fi
decky_child=$!
@@ -640,6 +653,20 @@ BUSCONF
echo "== Decky: installed loader architecture is unsupported by this guest; not starting"
fi
fi
_bl_cdp=()
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
export BL_CDP_PORT=8080
else
export BL_CDP_PORT=$((20000 + RANDOM % 30000))
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
fi
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ]; then
echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader"
else
export BL_CDP_GUARD=$BL_CDP_PORT
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
droiddeck-steam-compat "$steam_root" 2>&1 &
# The client exits 42 when it has updated itself and wants a fresh start (steam.sh does this).
# BL_STEAM_UI=desktop = the client's desktop UI (a window, the library as a list), which the
# desktop's launchers ask for; gamescope shows one window at a time and the game takes over.
@@ -682,7 +709,7 @@ BUSCONF
steam_channel=${BL_STEAM_CHANNEL:-steamdeck_publicbeta}
steam_beta=$steam_root/package/beta
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
bannerlator-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
games_watcher=$!
fi
# Lossless Scaling (Steam app 993090): whether this account owns it, asked of the signed-in
@@ -694,7 +721,7 @@ BUSCONF
for ((_i = 0; _i < 60; _i++)); do
nap 30
[ -e "$owned" ] && exit 0
answer=$(bannerlator-steam-games probe "$steam_root" 993090 2>/dev/null) || continue
answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || continue
case $answer in
*'"993090": true'*) mkdir -p "${owned%/*}" && : > "$owned" && echo "== Lossless Scaling: owned" ;;
*) echo "== Lossless Scaling: not owned by this account" ;;
@@ -703,7 +730,7 @@ BUSCONF
done
) &
fi
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
# An update that cannot install asks for a restart (rc=42) every time; the count is capped so a
# session can never again loop in silence, which reads as a menu opening and closing by itself.
steam_updates=0
@@ -749,14 +776,17 @@ BUSCONF
echo "$steam_channel" > "$steam_beta"
fi
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" -clientbeta "$steam_channel" \
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
rc=$?
echo "== steam exited rc=$rc"
collect_steam_logs
if [ -f "$HOME/.config/droiddeck/fex-wanted" ] && [ -x /usr/local/bin/droiddeck-fex ]; then
/usr/local/bin/droiddeck-fex status >/dev/null 2>&1 || true
fi
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
if [ -f "$HOME/.bl-stop-requested" ]; then
rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once"
@@ -787,7 +817,7 @@ BUSCONF
wait "$games_watcher" 2>/dev/null || true
fi
if [ -n "${BL_DESKTOP:-}" ]; then
# Started from the desktop (bannerlator-steam-launch): the desktop's own programs share this
# Started from the desktop (droiddeck-steam-launch): the desktop's own programs share this
# script's parent, so reap_orphans - right under gamescope, where everything is the client's -
# is not for here. The helpers this run started (the cores and redistributables beats, the
# system bus and the NetworkManager stand-in) go with the client instead.
@@ -812,7 +842,7 @@ BUSCONF
exit "$rc"
;;
*)
echo "bannerlator-session: unknown mode '$mode'" >&2
echo "droiddeck-session: unknown mode '$mode'" >&2
exit 64
;;
esac
+496
View File
@@ -0,0 +1,496 @@
#!/usr/bin/python3
import base64
import ctypes
import json
import os
import runpy
import select
import signal
import socket
import struct
import sys
import time
HERE = os.path.dirname(os.path.realpath(__file__))
COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility"))
BINDING = "droiddeckCompatChanged"
INSTALL_JS = r"""
(() => {
if (window.__droiddeckCompat) return "present";
const enc = new TextEncoder(), dec = new TextDecoder();
const varint = (value, out) => { let n = BigInt(value); do { let b = Number(n & 0x7fn); n >>= 7n; if (n) b |= 0x80; out.push(b); } while (n); };
const key = (field, wire, out) => varint(field * 8 + wire, out);
const str = (field, s, out) => { const b = enc.encode(s); key(field, 2, out); varint(b.length, out); for (const x of b) out.push(x); };
const uint = (field, v, out) => { key(field, 0, out); varint(v, out); };
const fixed64 = (field, v, out) => { key(field, 1, out); let n = BigInt(v); for (let i = 0; i < 8; i++) { out.push(Number(n & 0xffn)); n >>= 8n; } };
const parse = (bytes) => {
const fields = {};
let i = 0;
const read = () => { let r = 0n, s = 0n, b; do { b = bytes[i++]; r |= BigInt(b & 0x7f) << s; s += 7n; } while (b & 0x80); return r; };
while (i < bytes.length) {
const k = Number(read()), field = k >> 3, wire = k & 7;
let v;
if (wire === 0) v = read();
else if (wire === 1) { v = 0n; for (let j = 0; j < 8; j++) v |= BigInt(bytes[i + j]) << BigInt(8 * j); i += 8; }
else if (wire === 2) { const n = Number(read()); v = bytes.subarray(i, i + n); i += n; }
else if (wire === 5) { v = bytes.subarray(i, i + 4); i += 4; }
else throw new Error("unexpected wire type " + wire);
(fields[field] = fields[field] || []).push(v);
}
return fields;
};
const text = (f, n) => f[n] ? dec.decode(f[n][0]) : "";
const self = { seq: 0, pending: new Map(), ws: null, opening: null, changes: 0 };
const frame = (method, body, auth) => {
const h = [];
fixed64(10, ++self.seq, h);
str(12, method, h);
if (auth) str(40, auth, h);
const out = new Uint8Array(8 + h.length + body.length);
const view = new DataView(out.buffer);
view.setUint32(0, (0x80000000 | 146) >>> 0, true);
view.setUint32(4, h.length, true);
out.set(h, 8);
out.set(body, 8 + h.length);
return [self.seq, out];
};
const onMessage = (event) => {
const bytes = new Uint8Array(event.data);
const length = new DataView(event.data).getUint32(4, true);
const header = parse(bytes.subarray(8, 8 + length));
const target = header[11] ? Number(header[11][0] & 0xffffffffn) : -1;
if (self.pending.has(target)) {
const done = self.pending.get(target);
self.pending.delete(target);
const result = header[13] ? Number(header[13][0]) : 2;
done(result === 1 ? { ok: true, body: parse(bytes.subarray(8 + length)) } : { ok: false, eresult: result, error: text(header, 14) });
return;
}
if (text(header, 12).startsWith("CompatManager.NotifyStateChanged")) {
self.changes++;
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(self.changes));
}
};
const send = (method, body, auth) => new Promise((resolve, reject) => {
const [id, out] = frame(method, Uint8Array.from(body), auth);
const timer = setTimeout(() => { self.pending.delete(id); reject(new Error(method + " timed out")); }, 10000);
self.pending.set(id, (r) => { clearTimeout(timer); resolve(r); });
self.ws.send(out);
});
const open = async () => {
const info = await SteamClient.WebUITransport.GetTransportInfo();
const ws = new WebSocket("ws://127.0.0.1:" + info.portClientdll + "/transportsocket/");
ws.binaryType = "arraybuffer";
await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = () => reject(new Error("the client's transport refused the connection")); });
ws.onmessage = onMessage;
ws.onclose = () => {
if (self.ws === ws) self.ws = null;
for (const done of self.pending.values()) done({ ok: false, eresult: 0, error: "connection closed" });
self.pending.clear();
};
self.ws = ws;
const body = [];
str(1, info.authKeyClientdll, body);
const r = await send("TransportAuth.Authenticate#1", body, info.authKeyClientdll);
if (!r.ok) { ws.close(); throw new Error("the client's transport refused authentication (" + r.eresult + ")"); }
};
const ready = async () => {
if (self.ws && self.ws.readyState === 1) return;
if (!self.opening) self.opening = open().finally(() => { self.opening = null; });
await self.opening;
};
self.get = async (appid) => {
await ready();
const body = [];
uint(1, appid, body);
const r = await send("CompatManager.GetCompatTools#1", body);
if (!r.ok) throw new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")");
return { selected: text(r.body, 3), fallback: text(r.body, 4), tools: (r.body[1] || []).map((t) => text(parse(t), 1)) };
};
self.set = async (appid, name) => {
await ready();
const body = [];
uint(1, appid, body);
str(2, name, body);
const r = await send("CompatManager.SpecifyCompatTool#1", body);
if (!r.ok) throw new Error("SpecifyCompatTool " + appid + " " + name + " failed (" + r.eresult + " " + r.error + ")");
return true;
};
self.many = async (apps) => {
const out = {};
for (const app of apps) out[app] = (await self.get(Number(app))).selected;
return out;
};
window.__droiddeckCompat = self;
return "installed";
})()
""".replace("__BINDING__", BINDING)
class Closed(Exception):
pass
def say(message):
print("droiddeck-steam-compat: %s" % message, flush=True)
def connect(port, timeout=5):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
sock.bind(("127.0.0.1", 0))
sock.connect(("127.0.0.1", port))
except OSError:
sock.close()
raise
return sock
def http_get(port, path):
sock = connect(port)
try:
sock.sendall(("GET %s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nConnection: close\r\n\r\n" % (path, port)).encode())
data = b""
length = None
while length is None or len(data) < length:
chunk = sock.recv(65536)
if not chunk:
break
data += chunk
if length is None and b"\r\n\r\n" in data:
head, _, rest = data.partition(b"\r\n\r\n")
for line in head.split(b"\r\n")[1:]:
name, _, value = line.partition(b":")
if name.strip().lower() == b"content-length":
length = int(value.strip())
if length is None:
length = float("inf")
data = rest
if not head.startswith(b"HTTP/1.1 200"):
raise OSError("devtools answered %r" % head[:40])
finally:
sock.close()
return json.loads(data.decode("utf-8", "replace"))
class WebSocket:
def __init__(self, port, path):
self.sock = connect(port)
key = base64.b64encode(os.urandom(16)).decode()
self.sock.sendall(("GET %s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, port, key)).encode())
self.buffer = b""
while b"\r\n\r\n" not in self.buffer:
self.fill()
head, _, self.buffer = self.buffer.partition(b"\r\n\r\n")
if not head.startswith(b"HTTP/1.1 101"):
raise OSError("devtools refused the websocket: %r" % head[:60])
self.sock.settimeout(None)
def fileno(self):
return self.sock.fileno()
def fill(self):
chunk = self.sock.recv(65536)
if not chunk:
raise Closed("devtools closed the connection")
self.buffer += chunk
def take(self, n):
while len(self.buffer) < n:
self.fill()
data, self.buffer = self.buffer[:n], self.buffer[n:]
return data
def send(self, text, opcode=1):
payload = text.encode() if isinstance(text, str) else text
mask = os.urandom(4)
n = len(payload)
if n < 126:
head = struct.pack("!BB", 0x80 | opcode, 0x80 | n)
elif n < 65536:
head = struct.pack("!BBH", 0x80 | opcode, 0xFE, n)
else:
head = struct.pack("!BBQ", 0x80 | opcode, 0xFF, n)
self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
def pending(self):
return len(self.buffer) > 0
def recv(self):
message = b""
while True:
first, second = self.take(2)
n = second & 0x7F
if n == 126:
n = struct.unpack("!H", self.take(2))[0]
elif n == 127:
n = struct.unpack("!Q", self.take(8))[0]
mask = self.take(4) if second & 0x80 else None
payload = self.take(n)
if mask:
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
opcode = first & 0x0F
if opcode == 8:
raise Closed("devtools closed the websocket")
if opcode == 9:
self.send(payload, 10)
continue
if opcode == 10:
continue
message += payload
if first & 0x80:
return message.decode("utf-8", "replace")
def close(self):
try:
self.sock.close()
except OSError:
pass
class Page:
def __init__(self, port, path):
self.ws = WebSocket(port, path)
self.next_id = 0
self.events = []
def call(self, method, params=None, timeout=30):
self.next_id += 1
mine = self.next_id
self.ws.send(json.dumps({"id": mine, "method": method, "params": params or {}}))
deadline = time.monotonic() + timeout
while True:
if not self.ws.pending():
left = deadline - time.monotonic()
if left <= 0 or not select.select([self.ws], [], [], left)[0]:
raise TimeoutError("%s timed out" % method)
message = json.loads(self.ws.recv())
if message.get("id") == mine:
if "error" in message:
raise RuntimeError("%s: %s" % (method, message["error"].get("message")))
return message.get("result", {})
if "method" in message:
self.events.append(message)
def evaluate(self, expression, timeout=30):
result = self.call("Runtime.evaluate", {"expression": expression, "awaitPromise": True, "returnByValue": True}, timeout)
if "exceptionDetails" in result:
details = result["exceptionDetails"]
raise RuntimeError((details.get("exception") or {}).get("description") or details.get("text") or "script failed")
return result.get("result", {}).get("value")
def compat(self, call):
return self.evaluate("%s;\nwindow.__droiddeckCompat.%s" % (INSTALL_JS, call))
def drain(self):
while True:
if not self.ws.pending() and not select.select([self.ws], [], [], 0)[0]:
break
message = json.loads(self.ws.recv())
if "method" in message:
self.events.append(message)
events, self.events = self.events, []
return events
def shared_context(port):
for target in http_get(port, "/json/list"):
if target.get("title") == "SharedJSContext" and target.get("webSocketDebuggerUrl"):
path = target["webSocketDebuggerUrl"].split("/", 3)[3]
return "/" + path
return None
class Watcher:
MASK = 0x00000008 | 0x00000080 | 0x00000100 | 0x00000200
def __init__(self, files):
self.files = files
self.fd = -1
try:
libc = ctypes.CDLL(None, use_errno=True)
fd = libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC)
dirs = sorted({os.path.dirname(f) for f in files if os.path.isdir(os.path.dirname(f))})
if fd >= 0 and dirs and all(libc.inotify_add_watch(fd, d.encode(), self.MASK) >= 0 for d in dirs):
self.fd = fd
elif fd >= 0:
os.close(fd)
except (OSError, AttributeError):
self.fd = -1
self.stamp = self.snapshot()
def snapshot(self):
stamp = []
for f in self.files:
for p in (f, os.path.dirname(f)):
try:
stamp.append(os.stat(p).st_mtime_ns)
except OSError:
stamp.append(0)
return stamp
def fileno(self):
return self.fd
def changed(self):
if self.fd < 0:
stamp = self.snapshot()
moved, self.stamp = stamp != self.stamp, stamp
return moved
names = set()
try:
while True:
data = os.read(self.fd, 65536)
if not data:
break
at = 0
while at + 16 <= len(data):
_, _, _, size = struct.unpack_from("iIII", data, at)
names.add(data[at + 16:at + 16 + size].split(b"\0", 1)[0].decode("utf-8", "replace"))
at += 16 + size
except BlockingIOError:
pass
wanted = {os.path.basename(f) for f in self.files}
return any(n in wanted or n.startswith("appmanifest_") for n in names)
class Helper:
def __init__(self, steam_root, port):
self.steam_root = steam_root
self.port = port
self.page = None
self.known = set()
self.installed = None
self.fex_asked = set()
def attach(self):
path = shared_context(self.port)
if path is None:
raise LookupError("no SharedJSContext yet")
page = Page(self.port, path)
try:
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.compat("get(0)")
except Exception:
page.ws.close()
raise
self.page = page
return True
def reconcile(self):
page = self.page
with COMPAT["locked"]():
state_file = COMPAT["state_path"]("state.json")
state = COMPAT["read_json"](state_file)
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
catalog = COMPAT["tool_catalog"](self.steam_root)
top = page.compat("get(0)")
self.known = set(top["tools"])
live = [t for t in catalog if t["name"] in self.known]
wanted = COMPAT["requested_tool"](request, catalog)
newer = isinstance(request.get("seq"), int) and request["seq"] > int(state.get("applied", 0) or 0)
waiting = newer and wanted is not None and wanted not in self.known
default, state = COMPAT["choose_default"](top["selected"], state, request, live, apply_request=not waiting)
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"])
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)
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)
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 request_waiting(self):
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
state = COMPAT["read_json"](COMPAT["state_path"]("state.json"))
return isinstance(request.get("seq"), int) and request["seq"] > int(state.get("applied", 0) or 0)
def serve(self, watcher):
with open(COMPAT["state_path"]("live.pid"), "w") as f:
f.write("%d\n" % os.getpid())
say("attached to the client on port %d" % self.port)
self.reconcile()
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]
due = False
if self.page.ws in ready:
due = any(e.get("method") == "Runtime.bindingCalled" and e.get("params", {}).get("name") == BINDING
for e in self.page.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()
if due:
time.sleep(0.3)
if watcher.fileno() >= 0 and select.select([watcher], [], [], 0)[0]:
watcher.changed()
self.page.drain()
self.reconcile()
def detach():
try:
os.unlink(COMPAT["state_path"]("live.pid"))
except OSError:
pass
with COMPAT["locked"]():
state_file = COMPAT["state_path"]("state.json")
state = COMPAT["read_json"](state_file)
if state.get("live"):
state["live"] = False
COMPAT["write_json"](state_file, state)
def main():
steam_root = sys.argv[1]
try:
port = int(os.environ.get("BL_CDP_PORT", ""))
except ValueError:
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")])
helper = Helper(steam_root, port)
failures = 0
last = None
while True:
try:
helper.attach()
failures = 0
last = None
helper.serve(watcher)
except Exception as e:
if helper.page is not None:
say("lost the client (%s); reattaching" % e)
helper.page.ws.close()
helper.page = None
detach()
elif str(e) != last:
say("waiting for the client (%s)" % e)
last = str(e)
failures += 1
time.sleep(min(2 * max(failures, 1), 10))
if __name__ == "__main__":
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
try:
sys.exit(main())
finally:
detach()
@@ -239,13 +239,13 @@ def watch(steam_root, listing):
status = last_status
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
requested = pending
print("bannerlator-steam-games: restarting the client once to import %s" % pending, flush=True)
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
try:
request_restart(steam_root)
except (OSError, subprocess.TimeoutExpired) as error:
print("bannerlator-steam-games: restart unavailable: %s" % error, flush=True)
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
if status != last_status:
print("bannerlator-steam-games: " + status, flush=True)
print("droiddeck-steam-games: " + status, flush=True)
last_status = status
time.sleep(30)
@@ -357,7 +357,7 @@ def route(steam_root, acct, games):
routes[str(game["appid"])] = appid
continue
except OSError as error:
print(f"bannerlator-steam-games: import unavailable ({error})")
print(f"droiddeck-steam-games: import unavailable ({error})")
shortcuts.append(game)
save_json(Path(acct) / "config/.droiddeck-routes.json", routes)
return shortcuts, routes
@@ -6,11 +6,15 @@ cdn=https://client-update.fastly.steamstatic.com
steam_channel=${BL_STEAM_CHANNEL:-steamdeck_publicbeta}
case "$steam_channel" in
publicbeta|steamdeck_publicbeta) ;;
*) echo "bannerlator-steam-install: unsupported Steam channel: $steam_channel" >&2; exit 1 ;;
*) echo "droiddeck-steam-install: unsupported Steam channel: $steam_channel" >&2; exit 1 ;;
esac
manifest=steam_client_${steam_channel}_linuxarm64
steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
stamp=$steam_root/package/bannerlator-installed
stamp=$steam_root/package/droiddeck-installed
legacy_stamp=$steam_root/package/bannerlator-installed
if [ -f "$legacy_stamp" ] && [ ! -f "$stamp" ]; then
mv -f "$legacy_stamp" "$stamp" || true
fi
[ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
@@ -24,7 +28,7 @@ awk -F'"' '
$2 == "sha2" { sha[block] = $4 }
END { for (b in file) if (b ~ /_all$/ || b ~ /_linuxarm64_linuxarm64$/) print b, file[b], sha[b] }
' "$work/manifest" | sort > "$work/parts"
[ -s "$work/parts" ] || { echo "bannerlator-steam-install: no client components in $manifest" >&2; exit 1; }
[ -s "$work/parts" ] || { echo "droiddeck-steam-install: no client components in $manifest" >&2; exit 1; }
total=$(grep -c . "$work/parts" 2>/dev/null || echo 0)
mkdir -p "$steam_root/package"
@@ -1,12 +1,12 @@
#!/bin/bash
# Starts the Steam client from inside a session (the desktop's menu entries and the per-game
# launchers bannerlator-desktop-games writes):
# bannerlator-steam-launch desktop [appid|steam-url] Steam's desktop UI, optionally a game
# bannerlator-steam-launch bigpicture [appid|steam-url] Big Picture
# 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
#
# On a desktop that draws with the GPU (labwc on vulkan or gles2 - the default since the GPU
# desktop) the client runs right there: a window on the desktop, through the desktop's Xwayland,
# with the same set-up a Steam session gives it (bannerlator-session steam, minus gamescope), and
# with the same set-up a Steam session gives it (droiddeck-session steam, minus gamescope), and
# its games open in windows of their own. A client already running there gets the request instead
# of a second one being started.
#
@@ -35,24 +35,24 @@ if [ "${BL_DESKTOP:-}" = 1 ] && [ -n "${WLR_RENDERER:-}" ] && [ "$WLR_RENDERER"
# One client at a time: the running one takes the request (a second start hands its command
# line over and exits). No game asked for = switch it to the UI that was clicked.
[ -n "$url" ] || { [ "$ui" = bigpicture ] && url=steam://open/bigpicture || url=steam://open/main; }
echo "bannerlator-steam-launch: the client is running on the desktop; handing it $url" | tee -a "$log"
echo "droiddeck-steam-launch: the client is running on the desktop; handing it $url" | tee -a "$log"
exec "$client" "$url"
fi
echo "bannerlator-steam-launch: starting the Steam client on the desktop ($ui${url:+, $url}); log: $log"
echo "droiddeck-steam-launch: starting the Steam client on the desktop ($ui${url:+, $url}); log: $log"
# BL_INSIDE: the session script's Steam start-up without gamescope in front of it. The desktop UI
# unless Big Picture was asked for; never Deck mode (its Quick Access Menu needs gamescope).
export BL_INSIDE=1 BL_STEAMDECK=0
if [ "$ui" = desktop ]; then export BL_STEAM_UI=desktop; else unset BL_STEAM_UI; fi
setsid /usr/local/bin/bannerlator-session steam ${url:+"$url"} >>"$log" 2>&1 < /dev/null &
setsid /usr/local/bin/droiddeck-session steam ${url:+"$url"} >>"$log" 2>&1 < /dev/null &
exit 0
fi
# The software desktop, or outside the desktop: ask the app for a Steam session.
dir=${BL_LAUNCH_DIR:-}
if [ -z "$dir" ] || [ ! -d "$dir" ]; then
echo "bannerlator-steam-launch: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2
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 "bannerlator-steam-launch: asked the app for Steam ($ui${url:+, $url})"
echo "droiddeck-steam-launch: asked the app for Steam ($ui${url:+, $url})"
@@ -2,7 +2,7 @@
# 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.
#
# bannerlator-steam-library <steam root>
# droiddeck-steam-library <steam root>
#
# Ported from WinNative's gamescope runtime (GPL-3.0).
import os
@@ -61,7 +61,7 @@ def register(steam_root, library, label):
os.makedirs(steamapps_dir, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(text)
print("bannerlator-steam-library: registered %s with %d game(s)" % (library, len(apps)))
print("droiddeck-steam-library: registered %s with %d game(s)" % (library, len(apps)))
return len(apps)
@@ -85,7 +85,7 @@ def rename(steam_root, old, new):
return
with open(path, "w", encoding="utf-8") as f:
f.write(old_path.sub(lambda m: m.group(1) + new + m.group(2), text))
print("bannerlator-steam-library: moved %s to %s" % (old, new))
print("droiddeck-steam-library: moved %s to %s" % (old, new))
def forget(steam_root, library):
@@ -115,7 +115,7 @@ def forget(steam_root, library):
if text != "\n".join(lines):
with open(path, "w", encoding="utf-8") as f:
f.write(text)
print("bannerlator-steam-library: forgot %s" % library)
print("droiddeck-steam-library: forgot %s" % library)
def relabel(steam_root, target, label):
@@ -151,7 +151,7 @@ def relabel(steam_root, target, label):
if changed:
with open(path, "w", encoding="utf-8") as f:
f.write("\n".join(out))
print("bannerlator-steam-library: labelled %s %r" % (target, label))
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
@@ -165,7 +165,7 @@ def relabel(steam_root, target, label):
if new != text:
with open(marker, "w", encoding="utf-8") as f:
f.write(new)
print("bannerlator-steam-library: labelled %s in its own marker too" % target)
print("droiddeck-steam-library: labelled %s in its own marker too" % target)
def main():
@@ -1,7 +1,7 @@
#!/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 bannerlator-steam-launch - which runs the client on the desktop itself when it draws with
# 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
@@ -14,6 +14,6 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
-gamepadui|-bigpicture) ui=bigpicture ;;
esac
done
exec /usr/local/bin/bannerlator-steam-launch "$ui" ${url:+"$url"}
exec /usr/local/bin/droiddeck-steam-launch "$ui" ${url:+"$url"}
fi
exec "${HOME:-/root}/.local/share/Steam/steamrtarm64/steam" "$@"
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Import added games while Steam is closed, preserving user-created shortcuts.
Usage: bannerlator-steam-shortcuts <steam_root> <added-games.json>
Usage: droiddeck-steam-shortcuts <steam_root> <added-games.json>
"""
import importlib.machinery
import importlib.util
@@ -163,7 +163,7 @@ def install_art(acct, games):
os.replace(dst + ".tmp", dst)
copied += 1
except OSError as e:
print("bannerlator-steam-shortcuts: could not copy art %s (%s)" % (name, e))
print("droiddeck-steam-shortcuts: could not copy art %s (%s)" % (name, e))
for name in list(manifest):
if name not in wanted:
try:
@@ -173,7 +173,7 @@ def install_art(acct, games):
with open(manifest_path, "w", encoding="utf-8") as f:
json.dump(wanted, f)
if copied:
print("bannerlator-steam-shortcuts: %d piece(s) of art placed" % copied)
print("droiddeck-steam-shortcuts: %d piece(s) of art placed" % copied)
def main():
@@ -185,11 +185,11 @@ def main():
with open(listing, encoding="utf-8") as f:
games = json.load(f)
except (OSError, ValueError) as e:
print("bannerlator-steam-shortcuts: no list (%s)" % e)
print("droiddeck-steam-shortcuts: no list (%s)" % e)
return 0
acct = account_dir(steam_root)
if not acct:
print("bannerlator-steam-shortcuts: no signed-in account yet; nothing written")
print("droiddeck-steam-shortcuts: no signed-in account yet; nothing written")
return 0
config = os.path.join(acct, "config")
os.makedirs(config, exist_ok=True)
@@ -200,9 +200,9 @@ def main():
with open(path, "rb") as f:
existing = parse(f.read()).get("shortcuts", {})
except (ValueError, IndexError, struct.error) as e:
print("bannerlator-steam-shortcuts: could not read the existing file (%s); keeping it unchanged" % e)
print("droiddeck-steam-shortcuts: could not read the existing file (%s); keeping it unchanged" % e)
return 1
helper = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bannerlator-steam-games")
helper = os.path.join(os.path.dirname(os.path.abspath(__file__)), "droiddeck-steam-games")
loader = importlib.machinery.SourceFileLoader("steam_games", helper)
spec = importlib.util.spec_from_loader(loader.name, loader)
routing = importlib.util.module_from_spec(spec)
@@ -225,25 +225,26 @@ def main():
entry["LaunchOptions"] = previous["LaunchOptions"]
ours.append(entry)
entries = {str(i): v for i, v in enumerate(kept + ours)}
tmp = path + ".bannerlator"
tmp = path + ".droiddeck"
with open(tmp, "wb") as f:
f.write(write({"shortcuts": entries}))
os.replace(tmp, path)
print("bannerlator-steam-shortcuts: %d added game(s) written, %d of the client's own kept" % (len(ours), len(kept)))
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/bannerlator-steam-compat"
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())])
print("bannerlator-steam-shortcuts: mapped them to %s" % compat.TOOL)
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
print("bannerlator-steam-shortcuts: compat mapping skipped (%s)" % e)
print("droiddeck-steam-shortcuts: compat mapping skipped (%s)" % e)
return 0
File diff suppressed because it is too large. Load diff
+653
View File
@@ -0,0 +1,653 @@
/* 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>
#include <fcntl.h>
#include <linux/futex.h>
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#ifndef SYS_futex_waitv
#define SYS_futex_waitv 449
#endif
#define FS_SLOTS 2048u
#define FS_WORDS (FS_SLOTS / 64u)
#define FS_BUCKETS 4096u
#define FS_KEYS 128u
#define FS_NOKEY 0xffffffffu
#define FS_SIZE32 2u
#define FS_PRIVATE 128u
#define FS_MAGIC 0x434e595346444444ull
#define FS_SWEEP_NS 1000000000ull
#define FS_POLL_NS 500000l
#define FS_NAP_MIN 10000000ull
#define FS_NAP_MAX 1000000000ull
#define FS_HEAD_SIZE 4096ul
struct fs_waitv {
uint64_t val;
uint64_t uaddr;
uint32_t flags;
uint32_t reserved;
};
struct fs_bucket {
uint64_t bits[FS_WORDS];
};
struct fs_slot {
uint32_t futex;
uint32_t count;
uint64_t owner;
uint32_t keys[FS_KEYS];
};
struct fs_head {
uint64_t magic;
uint32_t sweeper;
uint32_t pad;
uint64_t sweep_at;
uint64_t used[FS_WORDS];
};
#define FS_BUCKET_OFF FS_HEAD_SIZE
#define FS_SLOT_OFF (FS_BUCKET_OFF + (size_t)FS_BUCKETS * sizeof(struct fs_bucket))
#define FS_REGION (FS_SLOT_OFF + (size_t)FS_SLOTS * sizeof(struct fs_slot))
_Static_assert(sizeof(struct fs_head) <= FS_HEAD_SIZE, "fsync registry head");
struct fs_range {
uintptr_t lo;
uintptr_t hi;
uint64_t off;
};
struct fs_map {
uint32_t n;
struct fs_range r[];
};
static int fs_state = -1;
static char *fs_reg;
static int fs_fd = -1;
static struct fs_map *fs_cur;
static uint32_t fs_pid;
static pthread_mutex_t fs_mx = PTHREAD_MUTEX_INITIALIZER;
static pthread_key_t fs_key;
static pthread_once_t fs_once = PTHREAD_ONCE_INIT;
static __thread int32_t fs_tslot = -1;
static __thread int fs_busy;
static __thread uint32_t fs_tid;
static __thread uint32_t fs_nap_key;
static __thread uint32_t fs_nap_n;
static __thread uint64_t fs_nap_ns;
static __thread sigset_t fs_fork_mask;
static long (*fs_real_syscall)(long, ...);
static int (*fs_real_shm_open)(const char *, int, mode_t);
static int (*fs_real_shm_unlink)(const char *);
static void *(*fs_real_mmap)(void *, size_t, int, int, int, off_t);
static void *(*fs_real_mmap64)(void *, size_t, int, int, int, off64_t);
static int (*fs_real_munmap)(void *, size_t);
static int fs_on(void) {
if (fs_state < 0) {
const char *e = getenv("BL_FSYNC");
fs_state = e && e[0] == '1';
}
return fs_state;
}
static long fs_sys(long n, long a, long b, long c, long d, long e, long f) {
if (!fs_real_syscall) fs_real_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
return fs_real_syscall(n, a, b, c, d, e, f);
}
static void *fs_anon(size_t size) {
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
return fs_real_mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
static uint32_t fs_self(void) {
if (!fs_tid) fs_tid = (uint32_t)fs_sys(SYS_gettid, 0, 0, 0, 0, 0, 0);
return fs_tid;
}
static uint32_t fs_getpid(void) {
if (!fs_pid) fs_pid = (uint32_t)getpid();
return fs_pid;
}
static uint64_t fs_now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
static int fs_dead(uint32_t pid, uint32_t tid) {
int saved = errno, dead;
dead = pid && fs_sys(SYS_tgkill, pid, tid, 0, 0, 0, 0) == -1 && errno == ESRCH;
errno = saved;
return dead;
}
static uint64_t fs_owner(void) {
return (uint64_t)fs_getpid() << 32 | fs_self();
}
static void fs_block(sigset_t *old) {
sigset_t all;
sigfillset(&all);
pthread_sigmask(SIG_SETMASK, &all, old);
}
static inline struct fs_head *fs_head(void) {
return (struct fs_head *)fs_reg;
}
static inline struct fs_bucket *fs_bucket(uint32_t key) {
return (struct fs_bucket *)(fs_reg + FS_BUCKET_OFF) + ((key >> 4) & (FS_BUCKETS - 1));
}
static inline struct fs_slot *fs_slot(uint32_t s) {
return (struct fs_slot *)(fs_reg + FS_SLOT_OFF) + s;
}
static int fs_key_of(uint64_t addr, uint32_t *key) {
struct fs_map *m = __atomic_load_n(&fs_cur, __ATOMIC_ACQUIRE);
uint32_t lo = 0, hi;
if (!m) return 0;
hi = m->n;
while (lo < hi) {
uint32_t mid = (lo + hi) / 2;
if (addr < m->r[mid].lo) {
hi = mid;
} else if (addr >= m->r[mid].hi) {
lo = mid + 1;
} else {
uint64_t k = m->r[mid].off + (addr - m->r[mid].lo);
if (k >= FS_NOKEY) return 0;
*key = (uint32_t)k;
return 1;
}
}
return 0;
}
static int fs_overlaps(uintptr_t lo, uintptr_t hi) {
struct fs_map *m = __atomic_load_n(&fs_cur, __ATOMIC_ACQUIRE);
if (!m) return 0;
for (uint32_t i = 0; i < m->n; i++)
if (m->r[i].lo < hi && m->r[i].hi > lo) return 1;
return 0;
}
static void fs_rebuild_locked(uintptr_t lo, uintptr_t hi, const struct fs_range *add) {
struct fs_map *old, *m;
uint32_t n, k = 0;
int added = 0;
old = fs_cur;
n = old ? old->n : 0;
m = fs_anon(sizeof(*m) + (n + 1) * sizeof(struct fs_range));
if (m == MAP_FAILED) return;
for (uint32_t i = 0; i < n; i++) {
const struct fs_range *r = &old->r[i];
if (r->lo < hi && r->hi > lo) continue;
if (add && !added && add->lo < r->lo) {
m->r[k++] = *add;
added = 1;
}
m->r[k++] = *r;
}
if (add && !added) m->r[k++] = *add;
m->n = k;
__atomic_store_n(&fs_cur, m, __ATOMIC_RELEASE);
}
static void fs_rebuild(uintptr_t lo, uintptr_t hi, const struct fs_range *add) {
sigset_t old;
fs_block(&old);
pthread_mutex_lock(&fs_mx);
fs_rebuild_locked(lo, hi, add);
pthread_mutex_unlock(&fs_mx);
pthread_sigmask(SIG_SETMASK, &old, NULL);
}
static void fs_track(void *p, size_t len, int flags, int fd, off_t off) {
uintptr_t lo = (uintptr_t)p, hi = lo + len;
int saved = errno;
if (fs_fd >= 0 && fd == fs_fd && (flags & MAP_SHARED) && off >= 0) {
struct fs_range r = {lo, hi, (uint64_t)off};
fs_rebuild(lo, hi, &r);
} else if (fs_overlaps(lo, hi)) {
fs_rebuild(lo, hi, NULL);
}
errno = saved;
}
static void fs_unregister(uint32_t s, const uint32_t *keys, uint32_t n) {
uint64_t bit = 1ull << (s & 63);
for (uint32_t i = 0; i < n; i++) {
struct fs_bucket *b;
if (keys[i] == FS_NOKEY) continue;
b = fs_bucket(keys[i]);
__atomic_and_fetch(&b->bits[s >> 6], ~bit, __ATOMIC_SEQ_CST);
}
}
static void fs_release(uint32_t s, uint64_t owner) {
struct fs_slot *sl = fs_slot(s);
uint32_t n, keys[FS_KEYS];
if (!owner || !__atomic_compare_exchange_n(&sl->owner, &owner, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) return;
n = __atomic_load_n(&sl->count, __ATOMIC_RELAXED);
if (n > FS_KEYS) n = FS_KEYS;
for (uint32_t i = 0; i < n; i++) keys[i] = __atomic_load_n(&sl->keys[i], __ATOMIC_RELAXED);
fs_unregister(s, keys, n);
__atomic_store_n(&sl->count, 0, __ATOMIC_RELAXED);
__atomic_and_fetch(&fs_head()->used[s >> 6], ~(1ull << (s & 63)), __ATOMIC_RELEASE);
}
static void fs_sweep(int force) {
struct fs_head *h = fs_head();
uint64_t now = fs_now();
uint32_t me = fs_getpid(), cur = 0;
if (!force && now < __atomic_load_n(&h->sweep_at, __ATOMIC_RELAXED)) return;
if (!__atomic_compare_exchange_n(&h->sweeper, &cur, me, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
if (!fs_dead(cur, cur) || !__atomic_compare_exchange_n(&h->sweeper, &cur, me, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
return;
}
__atomic_store_n(&h->sweep_at, now + FS_SWEEP_NS, __ATOMIC_RELAXED);
for (uint32_t w = 0; w < FS_WORDS; w++) {
uint64_t u = __atomic_load_n(&h->used[w], __ATOMIC_ACQUIRE);
while (u) {
uint32_t s = w * 64 + (uint32_t)__builtin_ctzll(u);
struct fs_slot *sl = fs_slot(s);
u &= u - 1;
uint64_t owner = __atomic_load_n(&sl->owner, __ATOMIC_ACQUIRE);
if (fs_dead((uint32_t)(owner >> 32), (uint32_t)owner)) fs_release(s, owner);
}
}
__atomic_store_n(&h->sweeper, 0, __ATOMIC_RELEASE);
}
static int32_t fs_alloc(void) {
struct fs_head *h = fs_head();
fs_sweep(0);
for (int pass = 0; pass < 2; pass++) {
for (uint32_t w = 0; w < FS_WORDS; w++) {
uint64_t u = __atomic_load_n(&h->used[w], __ATOMIC_RELAXED);
while (~u) {
uint32_t b = (uint32_t)__builtin_ctzll(~u);
if (__atomic_compare_exchange_n(&h->used[w], &u, u | (1ull << b), 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) {
uint32_t s = w * 64 + b;
struct fs_slot *sl = fs_slot(s);
__atomic_store_n(&sl->count, 0, __ATOMIC_RELAXED);
__atomic_store_n(&sl->owner, fs_owner(), __ATOMIC_RELEASE);
return (int32_t)s;
}
}
}
fs_sweep(1);
}
return -1;
}
static void fs_thread_gone(void *p) {
uint32_t s = (uint32_t)((uintptr_t)p - 1);
if (fs_reg && s < FS_SLOTS && fs_tslot == (int32_t)s) {
fs_tslot = -1;
fs_busy = 0;
fs_release(s, fs_owner());
}
}
static void fs_key_init(void) {
pthread_key_create(&fs_key, fs_thread_gone);
}
static void fs_fork_prepare(void) {
fs_block(&fs_fork_mask);
pthread_mutex_lock(&fs_mx);
}
static void fs_fork_parent(void) {
pthread_mutex_unlock(&fs_mx);
pthread_sigmask(SIG_SETMASK, &fs_fork_mask, NULL);
}
static void fs_child(void) {
pthread_mutex_init(&fs_mx, NULL);
pthread_sigmask(SIG_SETMASK, &fs_fork_mask, NULL);
fs_pid = 0;
fs_tid = 0;
fs_busy = 0;
if (fs_tslot >= 0) {
fs_tslot = -1;
pthread_setspecific(fs_key, NULL);
}
}
__attribute__((constructor)) static void fs_init(void) {
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
if (!fs_real_mmap64) fs_real_mmap64 = (void *(*)(void *, size_t, int, int, int, off64_t))dlsym(RTLD_NEXT, "mmap64");
if (!fs_real_munmap) fs_real_munmap = (int (*)(void *, size_t))dlsym(RTLD_NEXT, "munmap");
if (fs_on()) pthread_atfork(fs_fork_prepare, fs_fork_parent, fs_child);
}
static int32_t fs_take(int *temp) {
if (fs_busy) {
*temp = 1;
return fs_alloc();
}
*temp = 0;
fs_busy = 1;
__atomic_signal_fence(__ATOMIC_SEQ_CST);
if (fs_tslot < 0) {
int32_t s = fs_alloc();
if (s < 0) {
fs_busy = 0;
return -1;
}
pthread_once(&fs_once, fs_key_init);
pthread_setspecific(fs_key, (void *)(uintptr_t)(s + 1));
fs_tslot = s;
}
return fs_tslot;
}
static void fs_give(int32_t s, int temp) {
if (temp) {
fs_release((uint32_t)s, fs_owner());
} else {
__atomic_signal_fence(__ATOMIC_SEQ_CST);
fs_busy = 0;
}
}
static int fs_changed(const struct fs_waitv *v, uint32_t n) {
for (uint32_t i = 0; i < n; i++)
if (__atomic_load_n((uint32_t *)(uintptr_t)v[i].uaddr, __ATOMIC_SEQ_CST) != (uint32_t)v[i].val) return (int)i;
return -1;
}
static int fs_past(const struct timespec *ts, int clk) {
struct timespec now;
if (!ts) return 0;
clock_gettime(clk, &now);
return now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec && now.tv_nsec >= ts->tv_nsec);
}
static uint64_t fs_clock_ns(int clk) {
struct timespec now;
clock_gettime(clk, &now);
return (uint64_t)now.tv_sec * 1000000000ull + (uint64_t)now.tv_nsec;
}
static uint64_t fs_ts_ns(const struct timespec *ts) {
return (uint64_t)ts->tv_sec * 1000000000ull + (uint64_t)ts->tv_nsec;
}
static long fs_poll(const struct fs_waitv *v, uint32_t n, const struct timespec *ts, int clk) {
int i = fs_changed(v, n);
if (i >= 0) {
errno = EAGAIN;
return -1;
}
for (;;) {
struct timespec nap = {0, FS_POLL_NS};
if (fs_past(ts, clk)) {
errno = ETIMEDOUT;
return -1;
}
if (nanosleep(&nap, NULL) == -1 && errno == EINTR) return -1;
if ((i = fs_changed(v, n)) >= 0) return i;
}
}
static long fs_waitv(const struct fs_waitv *v, uint32_t n, uint32_t flags, const struct timespec *ts, int clk) {
uint32_t keys[FS_KEYS];
struct fs_slot *sl;
struct timespec nap_ts;
const struct timespec *until = ts;
int temp, err = 0, op, napping = 0, wclk = clk, saved = errno;
int32_t s;
uint64_t bit, nap;
if (!v || !n || n > FS_KEYS || flags || (ts && clk != CLOCK_MONOTONIC && clk != CLOCK_REALTIME)) {
errno = EINVAL;
return -1;
}
for (uint32_t i = 0; i < n; i++) {
if ((v[i].flags & ~FS_PRIVATE) != FS_SIZE32 || v[i].reserved || (v[i].uaddr & 3)) {
errno = EINVAL;
return -1;
}
if ((v[i].flags & FS_PRIVATE) || !fs_key_of(v[i].uaddr, &keys[i])) keys[i] = FS_NOKEY;
}
if (!fs_reg || (s = fs_take(&temp)) < 0) return fs_poll(v, n, ts, clk);
sl = fs_slot((uint32_t)s);
bit = 1ull << (s & 63);
for (uint32_t i = 0; i < n; i++) __atomic_store_n(&sl->keys[i], keys[i], __ATOMIC_RELAXED);
__atomic_store_n(&sl->count, n, __ATOMIC_RELAXED);
__atomic_store_n(&sl->futex, 0, __ATOMIC_RELAXED);
for (uint32_t i = 0; i < n; i++) {
struct fs_bucket *b;
if (keys[i] == FS_NOKEY) continue;
b = fs_bucket(keys[i]);
__atomic_or_fetch(&b->bits[s >> 6], bit, __ATOMIC_SEQ_CST);
}
__atomic_thread_fence(__ATOMIC_SEQ_CST);
if (fs_changed(v, n) >= 0) err = EAGAIN;
nap = fs_nap_ns && fs_nap_n == n && fs_nap_key == keys[0] ? fs_nap_ns * 2 : FS_NAP_MIN;
if (nap > FS_NAP_MAX) nap = FS_NAP_MAX;
if (!ts || fs_ts_ns(ts) > fs_clock_ns(clk) + nap) {
uint64_t at = fs_clock_ns(CLOCK_MONOTONIC) + nap;
nap_ts.tv_sec = (time_t)(at / 1000000000ull);
nap_ts.tv_nsec = (long)(at % 1000000000ull);
until = &nap_ts;
wclk = CLOCK_MONOTONIC;
napping = 1;
}
op = FUTEX_WAIT_BITSET | (until && wclk == CLOCK_REALTIME ? FUTEX_CLOCK_REALTIME : 0);
while (!err && !__atomic_load_n(&sl->futex, __ATOMIC_ACQUIRE)) {
if (fs_sys(SYS_futex, (long)&sl->futex, op, 0, (long)until, 0, FUTEX_BITSET_MATCH_ANY) == -1 && errno != EAGAIN
&& !__atomic_load_n(&sl->futex, __ATOMIC_ACQUIRE))
err = errno;
}
fs_unregister((uint32_t)s, keys, n);
if (err && __atomic_exchange_n(&sl->futex, 1, __ATOMIC_ACQ_REL)) err = 0;
fs_give(s, temp);
if (err == ETIMEDOUT && napping) {
fs_nap_key = keys[0];
fs_nap_n = n;
fs_nap_ns = nap;
errno = EINTR;
return -1;
}
if (err != EINTR) fs_nap_ns = 0;
if (err) {
errno = err;
return -1;
}
errno = saved;
s = fs_changed(v, n);
return s < 0 ? 0 : s;
}
static long fs_wake(uint32_t key, int n) {
struct fs_bucket *b = fs_bucket(key);
long woken = 0;
__atomic_thread_fence(__ATOMIC_SEQ_CST);
if (n <= 0) return 0;
for (uint32_t w = 0; w < FS_WORDS; w++) {
uint64_t bits = __atomic_load_n(&b->bits[w], __ATOMIC_SEQ_CST);
while (bits) {
uint32_t s = w * 64 + (uint32_t)__builtin_ctzll(bits), c;
struct fs_slot *sl = fs_slot(s);
bits &= bits - 1;
c = __atomic_load_n(&sl->count, __ATOMIC_ACQUIRE);
if (c > FS_KEYS) c = FS_KEYS;
for (uint32_t i = 0; i < c; i++) {
if (__atomic_load_n(&sl->keys[i], __ATOMIC_RELAXED) != key) continue;
if (!__atomic_exchange_n(&sl->futex, 1, __ATOMIC_SEQ_CST)) {
int saved = errno;
fs_sys(SYS_futex, (long)&sl->futex, FUTEX_WAKE, 1, 0, 0, 0);
errno = saved;
if (++woken >= n) return woken;
}
break;
}
}
}
return woken;
}
void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
void bl_fsync_fds_closed(unsigned int first, unsigned int last) {
int fd = __atomic_load_n(&fs_fd, __ATOMIC_ACQUIRE);
if (fd >= 0 && (unsigned int)fd >= first && (unsigned int)fd <= last) __atomic_store_n(&fs_fd, -1, __ATOMIC_RELEASE);
}
int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
int bl_fsync_syscall(long number, const long *args, long *ret) {
if (number == SYS_futex_waitv) {
if (!fs_on()) return 0;
if (!args[0] && !args[1]) {
errno = EINVAL;
*ret = -1;
return 1;
}
*ret = fs_waitv((const struct fs_waitv *)args[0], (uint32_t)args[1], (uint32_t)args[2],
(const struct timespec *)args[3], (int)args[4]);
return 1;
}
if (number == SYS_futex && (int)args[1] == FUTEX_WAKE && fs_reg && __atomic_load_n(&fs_cur, __ATOMIC_RELAXED)) {
uint32_t key;
if (!fs_key_of((uint64_t)args[0], &key)) return 0;
*ret = fs_wake(key, (int)args[2]);
return 1;
}
return 0;
}
static int fs_fsync_name(const char *name) {
size_t n;
if (!name) return 0;
if (*name == '/') name++;
n = strlen(name);
return n > 11 && !strncmp(name, "wine-", 5) && !strcmp(name + n - 6, "-fsync");
}
static void fs_attach(const char *name, int fd, int create) {
char path[256];
struct stat st;
void *p;
int rfd;
if (fs_reg) {
fs_fd = fd;
return;
}
if (snprintf(path, sizeof(path), "%s-droiddeck", name) >= (int)sizeof(path)) return;
if (create) fs_real_shm_unlink(path);
rfd = fs_real_shm_open(path, O_RDWR | O_CREAT, 0644);
if (rfd < 0) {
fprintf(stderr, "droiddeck-fsync: cannot open %s: %s\n", path, strerror(errno));
return;
}
if (fstat(rfd, &st) == 0 && (size_t)st.st_size < FS_REGION && ftruncate(rfd, (off_t)FS_REGION) != 0) {
fprintf(stderr, "droiddeck-fsync: cannot size %s: %s\n", path, strerror(errno));
close(rfd);
return;
}
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
p = fs_real_mmap(NULL, FS_REGION, PROT_READ | PROT_WRITE, MAP_SHARED, rfd, 0);
close(rfd);
if (p == MAP_FAILED) {
fprintf(stderr, "droiddeck-fsync: cannot map %s: %s\n", path, strerror(errno));
return;
}
fs_reg = p;
fs_fd = fd;
if (create) {
__atomic_store_n(&fs_head()->magic, FS_MAGIC, __ATOMIC_RELEASE);
fprintf(stderr, "droiddeck-fsync: up and running.\n");
}
}
int shm_open(const char *name, int oflag, mode_t mode) {
int fd, saved;
if (!fs_real_shm_open) fs_real_shm_open = (int (*)(const char *, int, mode_t))dlsym(RTLD_NEXT, "shm_open");
if (!fs_real_shm_unlink) fs_real_shm_unlink = (int (*)(const char *))dlsym(RTLD_NEXT, "shm_unlink");
if (!fs_real_shm_open) {
errno = ENOSYS;
return -1;
}
fd = fs_real_shm_open(name, oflag, mode);
if (fd >= 0 && fs_on() && fs_fsync_name(name) && fs_real_shm_unlink) {
saved = errno;
fs_attach(name, fd, oflag & O_CREAT);
errno = saved;
}
return fd;
}
int shm_unlink(const char *name) {
int r, saved;
if (!fs_real_shm_unlink) fs_real_shm_unlink = (int (*)(const char *))dlsym(RTLD_NEXT, "shm_unlink");
if (!fs_real_shm_unlink) {
errno = ENOSYS;
return -1;
}
r = fs_real_shm_unlink(name);
if (fs_on() && fs_fsync_name(name)) {
char path[256];
saved = errno;
if (snprintf(path, sizeof(path), "%s-droiddeck", name) < (int)sizeof(path)) fs_real_shm_unlink(path);
errno = saved;
}
return r;
}
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
void *p;
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
p = fs_real_mmap(addr, len, prot, flags, fd, off);
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
return p;
}
void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off64_t off) {
void *p;
if (!fs_real_mmap64) fs_real_mmap64 = (void *(*)(void *, size_t, int, int, int, off64_t))dlsym(RTLD_NEXT, "mmap64");
p = fs_real_mmap64(addr, len, prot, flags, fd, off);
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
return p;
}
int munmap(void *addr, size_t len) {
uintptr_t lo = (uintptr_t)addr, hi = lo + len;
sigset_t old;
int r, saved;
if (!fs_real_munmap) fs_real_munmap = (int (*)(void *, size_t))dlsym(RTLD_NEXT, "munmap");
if (__builtin_expect(fs_fd < 0, 1) || !fs_overlaps(lo, hi)) return fs_real_munmap(addr, len);
fs_block(&old);
pthread_mutex_lock(&fs_mx);
r = fs_real_munmap(addr, len);
saved = errno;
if (r == 0) fs_rebuild_locked(lo, hi, NULL);
pthread_mutex_unlock(&fs_mx);
pthread_sigmask(SIG_SETMASK, &old, NULL);
errno = saved;
return r;
}
+2 -2
View File
@@ -89,7 +89,7 @@ static void discover_pads(void) {
if (pad->devnode[0] == '\0') {
snprintf(pad->sysname, sizeof(pad->sysname), "event%ld", slot);
snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/bannerlator%ld",
snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/droiddeck%ld",
slot);
snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%ld", slot);
snprintf(pad->uevent, sizeof(pad->uevent), PAD_UEVENT_FORMAT, (int)slot, (int)slot);
@@ -153,7 +153,7 @@ static void refresh_pad(int node) {
if (read_virtual_uevent(node, uevent, sizeof(uevent))) {
snprintf(pad->sysname, sizeof(pad->sysname), "event%d", node);
snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/bannerlator%d", node);
snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/droiddeck%d", node);
memcpy(pad->uevent, uevent, sizeof(uevent));
pad->devnum = makedev(13, EVENT_MINOR_BASE + (unsigned int)node);
snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%d", node);
+79 -3
View File
@@ -20,6 +20,8 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
static const char *net_dir(void) {
@@ -123,9 +125,75 @@ int listen(int fd, int backlog) {
return ret;
}
static unsigned local_port(int fd) {
struct sockaddr_storage ss;
socklen_t len = sizeof(ss);
if (getsockname(fd, (struct sockaddr *)&ss, &len) != 0) {
return 0;
}
return addr_port((struct sockaddr *)&ss, len);
}
static void bind_before_loopback_connect(int fd, const struct sockaddr *addr, socklen_t len) {
if (!addr || addr->sa_family != AF_INET || len < sizeof(struct sockaddr_in) ||
((const struct sockaddr_in *)addr)->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
return;
}
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
if (getsockname(fd, (struct sockaddr *)&ss, &slen) != 0 || ss.ss_family != AF_INET ||
((struct sockaddr_in *)&ss)->sin_port != 0) {
return;
}
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int saved = errno;
bind(fd, (struct sockaddr *)&local, sizeof(local));
errno = saved;
}
static unsigned guarded_port(void) {
static int port = -1;
if (port < 0) {
const char *value = getenv("BL_CDP_GUARD");
port = value && *value ? atoi(value) : 0;
if (port < 0 || port > 65535) port = 0;
}
return (unsigned)port;
}
static int guest_peer(int fd) {
unsigned peer = peer_port(fd);
if (peer == 0) {
return 0;
}
char path[300];
snprintf(path, sizeof(path), "%s/p%u", net_dir(), peer);
struct stat st;
if (stat(path, &st) != 0 || time(NULL) - st.st_mtime > 30) {
return 0;
}
int in = open(path, O_RDONLY);
if (in < 0) {
return 0;
}
char buf[64];
int n = read(in, buf, sizeof(buf) - 1);
close(in);
if (n <= 0) {
return 0;
}
buf[n] = '\0';
int pid = atoi(buf);
return pid > 0 && (kill(pid, 0) == 0 || errno != ESRCH);
}
int connect(int fd, const struct sockaddr *addr, socklen_t len) {
static connect_fn real;
if (!real) real = (connect_fn)dlsym(RTLD_NEXT, "connect");
bind_before_loopback_connect(fd, addr, len);
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. */
@@ -139,9 +207,17 @@ int connect(int fd, const struct sockaddr *addr, socklen_t len) {
int accept4(int fd, struct sockaddr *addr, socklen_t *len, int flags) {
static accept4_fn real;
if (!real) real = (accept4_fn)dlsym(RTLD_NEXT, "accept4");
int ret = real(fd, addr, len, flags);
if (ret >= 0) record_port(ret, peer_port(ret));
return ret;
for (;;) {
int ret = real(fd, addr, len, flags);
if (ret < 0) return ret;
unsigned guarded = guarded_port();
if (guarded && local_port(ret) == guarded && !guest_peer(ret)) {
close(ret);
continue;
}
record_port(ret, peer_port(ret));
return ret;
}
}
int accept(int fd, struct sockaddr *addr, socklen_t *len) {
+6 -4
View File
@@ -8,7 +8,7 @@
* 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/bannerlator-net;
* 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.
*/
#define _GNU_SOURCE 1
@@ -30,7 +30,7 @@
#include <sys/socket.h>
#include <unistd.h>
#define LINK_FILE "/etc/bannerlator-net"
#define LINK_FILE "/etc/droiddeck-net"
#define LO_NAME "lo"
#define LO_INDEX 1
#define LO_MTU 65536
@@ -352,6 +352,7 @@ static int is_link_query(unsigned long request) {
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); /* kgslid.c */
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")));
/* Every DRM and evdev call comes through here, so the lookup is done once. Two threads racing
* to store it store the same pointer. */
@@ -363,8 +364,9 @@ int ioctl(int fd, unsigned long request, ...) {
void *arg = va_arg(ap, void *);
va_end(ap);
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
int rc;
if (bl_ntsync_ioctl(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);
bl_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
@@ -466,7 +468,7 @@ static const char *denied_table(const char *path) {
static FILE *synthesize(const char *table) {
struct link link;
if (!load_link(&link)) return NULL;
int fd = memfd_create("bannerlator-net", MFD_CLOEXEC);
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC);
if (fd < 0) return NULL;
FILE *out = fdopen(fd, "w+");
if (out == NULL) {
File diff suppressed because it is too large. Load diff
+3
View File
@@ -35,6 +35,7 @@
int bl_status_without_tracer(const char *path, int flags) __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")));
static int retry_without_noatime(int fd, int flags) {
return fd < 0 && errno == EPERM && (flags & O_NOATIME);
@@ -61,6 +62,7 @@ int open(const char *path, int flags, ...) {
return -1;
}
if ((fd = bl_status_without_tracer(path, flags)) >= 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) {
errno = ENOSYS;
@@ -87,6 +89,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
return -1;
}
if ((fd = bl_status_without_tracer(path, flags)) >= 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) {
errno = ENOSYS;
+63
View File
@@ -9,6 +9,7 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <pthread.h>
#include <stdarg.h>
@@ -18,7 +19,23 @@
#include <sys/uio.h>
#include <unistd.h>
#ifndef SYS_openat2
#define SYS_openat2 437
#endif
#define BL_RESOLVE_BENEATH 0x08
#define BL_RESOLVE_IN_ROOT 0x10
struct bl_open_how {
uint64_t flags;
uint64_t mode;
uint64_t resolve;
};
static long (*real_syscall)(long, ...);
static int openat2_missing;
int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
static struct robust_list_head *thread_robust_head(void) {
pthread_mutexattr_t attr;
@@ -54,6 +71,35 @@ static struct robust_list_head *thread_robust_head(void) {
return head;
}
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];
if (!path || !how || (size_t)args[3] < sizeof(*how)) {
errno = EINVAL;
return -1;
}
if (how->resolve & BL_RESOLVE_IN_ROOT) {
while (*path == '/') {
path++;
}
if (!*path) {
path = ".";
}
} else if ((how->resolve & BL_RESOLVE_BENEATH) && *path == '/') {
errno = EXDEV;
return -1;
}
return real_syscall(SYS_openat, args[0], (long)path, (long)(int)how->flags, (long)how->mode);
}
static int execveat_is_execve(const long *args) {
const char *path = (const char *)args[1];
if (!path || (args[4] & (AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW))) {
return 0;
}
return path[0] == '/' || (int)args[0] == AT_FDCWD;
}
long syscall(long number, ...) {
va_list ap;
long args[6];
@@ -72,8 +118,25 @@ long syscall(long number, ...) {
*(size_t *)args[2] = sizeof(*head);
return 0;
}
long handled;
if (bl_fsync_syscall(number, args, &handled)) {
return handled;
}
if (!real_syscall) {
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
}
if (number == SYS_openat2) {
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
long fd = real_syscall(number, args[0], args[1], args[2], args[3]);
if (fd != -1 || errno != ENOSYS) {
return fd;
}
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
}
return openat2_via_openat(args);
}
if (number == SYS_execveat && execveat_is_execve(args)) {
return real_syscall(SYS_execve, args[1], args[2], args[3]);
}
return real_syscall(number, args[0], args[1], args[2], args[3], args[4], args[5]);
}
+3
View File
@@ -0,0 +1,3 @@
URUNTIME_VERSION=v0.8.1
URUNTIME_ASSET=uruntime-appimage-lite-aarch64
URUNTIME_SHA256=8485ae20eb0bfd4eaeac38d7fd7f78e153b391c718cf33ff07879605683be1ea