Merge org main a5b035b2 (0.6.7 and later) into the non-Adreno test branch

13 conflicts, resolved as:
- build.yml: both checkout steps keep the MaliBridge submodule and take main's sparse checkout.
- SessionActivity: main moved the session drawer into SessionMenu(); its DrawerActions get the
  test branch's systemPowerVr line, the only test-branch change in that call.
- TurnipDriver: the Mali check stays first, then main's injected detector (non-Adreno: system driver).
- BwrapSpawner: the bridge ICD check stays first, then main's runtimeLib() lookup (Ubuntu 26.04 paths).
- SessionArtifacts.finishAbandoned: main's beforeGuestStart flow and recovery markers, plus the test
  branch's Android exit reasons in the recovery note and the low-memory notice (returns Boolean);
  main's in-loop return becomes break so the notice is still left.
- SessionService: pruneSystemVulkanRuntime() kept before main's finishSessionStop(..., collectEnded).
- strings.xml, test_game_environment.py: both sides' additions.
- build_local.sh, test_local.sh: main's docker_platform.sh; local-cross.Dockerfile: main's
  arm64-aware layout plus libvulkan-dev, image tag 24.04-v4.
- gamescope/release.env: the p23-nonadreno pin stays until this round's gamescope build.
- check_session_assets.py: the test branch's pattern (any usr/ target) covers main's.
Workflow step names checked: none lost from either side.
This commit is contained in:
The412Banner committed 2026-10-30 19:37:31 +00:00
commit 380a70b485
700 files changed
+50259 -2255

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ lib=$out/x86_64/libwebkitinput.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/webkitinput.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
exit 1
fi
+33 -1
View File
@@ -11,6 +11,7 @@ export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_S
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
export KWIN_USE_OVERLAYS=0
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
for conf in client client-rt; do
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
@@ -35,7 +36,7 @@ cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
Type=Application
Name=Steam x86-64 (FEX, experimental)
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
Exec=qterminal -e /usr/local/bin/droiddeck-steam-x64
Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
Icon=steam
Categories=System;
ENTRY
@@ -43,6 +44,20 @@ python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
mkdir -p /usr/local/share/applications
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
[Desktop Entry]
Type=Application
Name=Android keyboard
Exec=/usr/local/bin/droiddeck-ime
NoDisplay=true
X-KDE-Wayland-VirtualKeyboard=true
ENTRY
input_method=$(kreadconfig6 --file kwinrc --group Wayland --key InputMethod 2>/dev/null)
case $input_method in
''|*/droiddeck-ime.desktop) kwriteconfig6 --file kwinrc --group Wayland --key InputMethod /usr/local/share/applications/droiddeck-ime.desktop ;;
esac
python3 /usr/local/bin/droiddeck-open --install 2>&1 | sed 's/^/[open] /'
export APPIMAGE_EXTRACT_AND_RUN=1
[ -e /etc/xdg/kiorc ] || printf '[Executable scripts]\nbehaviourOnLaunch=execute\n' >/etc/xdg/kiorc 2>/dev/null
@@ -55,6 +70,19 @@ if [ ! -e "$HOME/.config/droiddeck-desktop-icons" ]; then
touch "$HOME/.config/droiddeck-desktop-icons"
fi
[ -f "$desktop_dir/Return.desktop" ] && cp -f /usr/share/applications/droiddeck-return-gaming.desktop "$desktop_dir/Return.desktop" 2>/dev/null
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
fi
skel_done=$HOME/.local/share/droiddeck/skel-copied
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
mkdir -p "${skel_done%/*}" && : > "$skel_done"
fi
if [ -x /usr/lib/snapd/snap-confine ] && [ ! -d /var/lib/pacman ]; then
/usr/local/bin/droiddeck-snapd >/dev/null 2>&1 &
export XDG_DATA_DIRS=/var/lib/snapd/desktop:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
export PATH=$PATH:/snap/bin
fi
update-mime-database /usr/share/mime >/dev/null 2>&1 &
[ -f /usr/share/icons/hicolor/icon-theme.cache ] || gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null &
[ -f /usr/share/glib-2.0/schemas/gschemas.compiled ] || glib-compile-schemas /usr/share/glib-2.0/schemas 2>/dev/null
@@ -82,6 +110,10 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
if [ -z "${KWIN_RENDER_NODES:-}" ] && [ -c /dev/dri/renderD0 ]; then
export KWIN_RENDER_NODES=/dev/dri/renderD0
fi
mkdir -p /run/droiddeck/kwin
printf '#!/bin/sh\nGALLIUM_THREAD=0 exec /usr/bin/kwin_wayland "$@"\n' > /run/droiddeck/kwin/kwin_wayland
chmod 755 /run/droiddeck/kwin/kwin_wayland
export PATH=/run/droiddeck/kwin:$PATH
fi
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
+54 -7
View File
@@ -1,6 +1,7 @@
#!/usr/bin/python3
import os
import re
import shutil
HOME = os.environ.get("HOME", "/root")
SYSTEM_DIR = "/usr/share/applications"
@@ -9,6 +10,8 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
USER_DIR = os.path.join(HOME, ".local/share/applications")
MARK = "X-DroidDeck-GPU=1"
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
def enabled():
@@ -25,6 +28,33 @@ def main_group(text):
return lines[:start + 1], lines[start + 1:end], lines[end:]
def split_program(exec_line):
if exec_line.startswith('"'):
end = exec_line.find('"', 1)
if end < 0:
return None, None
return exec_line[:end + 1], exec_line[end + 1:]
program, _, rest = exec_line.partition(" ")
return program, (" " + rest) if rest else ""
def chromium(exec_line):
program, _ = split_program(exec_line)
if not program:
return False
program = program.strip('"')
path = program if os.path.isabs(program) else shutil.which(program)
if not path:
return False
here = os.path.dirname(os.path.realpath(path))
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
def chromium_exec(exec_line):
program, rest = split_program(exec_line)
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
def gpu_exec(exec_line):
"""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."""
@@ -33,7 +63,7 @@ def gpu_exec(exec_line):
return "droiddeck-gpu " + exec_line
def wrap(text):
def wrap(text, gpu_on=True):
head, group, rest = main_group(text)
if group is None:
return None
@@ -42,14 +72,30 @@ def wrap(text):
if "=" in l and not l.lstrip().startswith("#"):
k, v = l.split("=", 1)
keys.setdefault(k.strip(), v)
cats = set(filter(None, keys.get("Categories", "").split(";")))
if not cats & {"Game", "Emulator"}:
return None
if keys.get("Type", "Application") != "Application" or keys.get("NoDisplay", "").lower() == "true":
return None
exec_line = keys.get("Exec", "").strip()
if not exec_line or exec_line.startswith("droiddeck-gpu "):
return None
cats = set(filter(None, keys.get("Categories", "").split(";")))
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
browser = chromium(exec_line)
if not gpu and not browser:
return None
if browser:
exec_line = chromium_exec(exec_line)
if not gpu:
def fix(lines):
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
for l in lines]
out_group = fix(group)
while out_group and not out_group[-1].strip():
out_group.pop()
out_group.append(MARK)
out_rest = fix(rest)
if out_rest and out_rest[0].strip():
out_rest.insert(0, "")
return "\n".join(head + out_group + out_rest) + "\n"
out_group = []
actions = keys.get("Actions", "")
for l in group:
@@ -68,7 +114,8 @@ def wrap(text):
wrapped_rest = []
for l in rest:
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
l = "Exec=" + gpu_exec(l[5:])
action = l[5:].strip()
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
wrapped_rest.append(l)
if wrapped_rest and wrapped_rest[0].strip():
wrapped_rest.insert(0, "")
@@ -87,7 +134,7 @@ def main():
on = enabled()
os.makedirs(USER_DIR, exist_ok=True)
written = set()
sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)] if on else []
sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)]
for source in sources:
for name in sorted(os.listdir(source)):
if not name.endswith(".desktop") or SKIP.match(name):
@@ -97,7 +144,7 @@ def main():
continue
try:
with open(os.path.join(source, name), encoding="utf-8", errors="replace") as f:
text = wrap(f.read())
text = wrap(f.read(), on)
except OSError:
continue
if text is None:
+43
View File
@@ -22,6 +22,7 @@ extern void webkit_web_view_run_javascript(void *view, const char *script, void
extern WebKitUserScript *webkit_user_script_new(const char *source, int frames, int time,
const char *const *allow, const char *const *block) __attribute__((weak));
extern void webkit_user_script_unref(WebKitUserScript *script) __attribute__((weak));
extern const char *g_getenv(const char *name) __attribute__((weak));
static const char NAV_SCRIPT[] =
"(()=>{let open=-1e9,arrowAt=-1e9,ringed=null,ringOutline='',ringOffset='',settleTimer=0,settling=false,redirecting=false;"
@@ -196,3 +197,45 @@ __attribute__((visibility("default"))) void webkit_user_content_manager_add_scri
}
next(manager, script);
}
static int starts(const char *text, const char *prefix)
{
while (*prefix)
if (*text++ != *prefix++)
return 0;
return 1;
}
static int fab_uri(const char *uri)
{
if (!uri)
return 0;
if (starts(uri, "https://"))
uri += 8;
else if (starts(uri, "http://"))
uri += 7;
else
return 0;
if (starts(uri, "www."))
uri += 4;
if (!starts(uri, "fab.com"))
return 0;
uri += 7;
return !*uri || *uri == '/' || *uri == '?' || *uri == '#' || *uri == ':';
}
static int hidden_launcher(void)
{
const char *hidden = g_getenv ? g_getenv("DROIDDECK_EPIC_HIDDEN") : 0;
return hidden && hidden[0] == '1' && !hidden[1];
}
__attribute__((visibility("default"))) void webkit_web_view_load_uri(void *view, const char *uri)
{
static void (*next)(void *, const char *);
if (!next && dlsym)
next = (void (*)(void *, const char *))dlsym((void *)-1l, "webkit_web_view_load_uri");
if (!next)
return;
next(view, hidden_launcher() && fab_uri(uri) ? "about:blank" : uri);
}
@@ -605,9 +605,56 @@ KEYBOARD_CHECK_SECONDS = 30
KEYBOARD_JS = r"""
(() => {
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
self.wrapped = self.wrapped || new WeakSet();
self.route = self.route === true;
self.wrap = vkm => {
if (!vkm || self.wrapped.has(vkm) || typeof vkm.ShowVirtualKeyboard !== "function") return;
self.wrapped.add(vkm);
const show = vkm.ShowVirtualKeyboard;
vkm.ShowVirtualKeyboard = function (ref, props, modal) {
if (self.route && !modal && typeof this.SetActiveVirtualKeyboardTarget === "function" &&
!this.BUseVRKeyboard?.() && !this.m_Instance?.IsDesktopOverlayWindow?.()) {
this.SetActiveVirtualKeyboardTarget(ref, props);
self.follow(this);
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
return;
}
return show.call(this, ref, props, modal);
};
};
self.editing = vkm => {
let el = null;
try { el = vkm?.m_ownerWindow?.document?.activeElement || null; } catch (e) {}
if (!el) return null;
return el.tagName === "TEXTAREA" || el.isContentEditable === true ||
(el.tagName === "INPUT" && !/^(button|checkbox|radio|range|submit|reset|file|image|color)$/i.test(el.type || ""));
};
self.follow = vkm => {
self.active = vkm;
self.missed = 0;
self.seen = false;
self.follower = self.follower || setInterval(() => {
if (!self.active) return;
const ref = self.active.m_currentVirtualKeyboardRef;
const editing = self.editing(self.active);
const valid = !!ref && (editing !== null ? editing :
(typeof ref.BIsElementValidForInput !== "function" || ref.BIsElementValidForInput()));
if (valid) self.seen = true;
if (self.route && ref && (valid || !self.seen)) {
self.missed = 0;
return;
}
if (++self.missed < 2) return;
self.active = null;
clearInterval(self.follower);
self.follower = null;
if (typeof window.__BINDING__ === "function") window.__BINDING__("dismiss");
}, 150);
};
self.check = () => {
let showing = false;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
self.wrap(win?.VirtualKeyboardManager);
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
if (!value) continue;
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
@@ -626,6 +673,29 @@ KEYBOARD_JS = r"""
return self.check();
})()
""".replace("__BINDING__", KEYBOARD_BINDING)
KEYBOARD_ROUTE_SECONDS = 0.5
KEYBOARD_ROUTE_JS = r"""
(route => {
const self = window.__droiddeckKeyboard;
if (!self) return false;
self.route = route;
if (!route) return true;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
const vkm = win?.VirtualKeyboardManager;
if (vkm?.m_bIsInlineVirtualKeyboardOpen?.m_currentValue === true && vkm?.m_bIsVirtualKeyboardModal?.m_currentValue !== true &&
typeof vkm.SetVirtualKeyboardHidden === "function") {
const ref = vkm.m_currentVirtualKeyboardRef, props = vkm.m_ActiveElementProps;
vkm.SetVirtualKeyboardHidden();
if (ref && typeof vkm.SetActiveVirtualKeyboardTarget === "function") {
vkm.SetActiveVirtualKeyboardTarget(ref, props);
if (typeof self.follow === "function") self.follow(vkm);
}
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
}
}
return true;
})(__ROUTE__)
""".replace("__BINDING__", KEYBOARD_BINDING)
class KeyboardWatcher(threading.Thread):
@@ -633,8 +703,14 @@ class KeyboardWatcher(threading.Thread):
super().__init__(daemon=True, name="keyboard")
self.agent_dir = agent_dir
self.path = agent_dir / "keyboard.json"
self.request_path = agent_dir / "keyboard-request.json"
self.dismiss_path = agent_dir / "keyboard-dismiss.json"
self.dismissals = 0
self.route_path = agent_dir / "keyboard-route"
self.showing = None
self.seq = 0
self.requests = 0
self.route = None
self.next_id = 0
self.attached = False
@@ -645,6 +721,30 @@ class KeyboardWatcher(threading.Thread):
self.seq += 1
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
def request(self):
self.requests += 1
write_json(self.request_path, {"seq": self.requests})
def dismiss(self):
self.dismissals += 1
write_json(self.dismiss_path, {"seq": self.dismissals})
def wanted_route(self):
try:
return self.route_path.read_text().strip() == "bottom"
except OSError:
return False
def apply_route(self, ws, force=False):
route = self.wanted_route()
if route == self.route and not force:
return
result = self.call(ws, "Runtime.evaluate", {
"expression": KEYBOARD_ROUTE_JS.replace("__ROUTE__", "true" if route else "false"), "returnByValue": True})
if result.get("exceptionDetails"):
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
self.route = route
def run(self):
failures, last = 0, None
while True:
@@ -671,10 +771,18 @@ class KeyboardWatcher(threading.Thread):
try:
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
self.report(self.install(ws))
self.apply_route(ws, force=True)
self.attached = True
installed = time.monotonic()
while True:
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
self.report(self.install(ws))
wait = min(KEYBOARD_ROUTE_SECONDS, KEYBOARD_CHECK_SECONDS)
if not ws.buffer and not select.select([ws.s], [], [], wait)[0]:
if time.monotonic() - installed >= KEYBOARD_CHECK_SECONDS:
self.report(self.install(ws))
self.apply_route(ws, force=True)
installed = time.monotonic()
else:
self.apply_route(ws)
continue
self.event(json.loads(ws.recv()))
finally:
@@ -702,7 +810,12 @@ class KeyboardWatcher(threading.Thread):
def event(self, message):
params = message.get("params") or {}
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
self.report(params.get("payload") == "true")
if params.get("payload") == "request":
self.request()
elif params.get("payload") == "dismiss":
self.dismiss()
else:
self.report(params.get("payload") == "true")
def steam_idle_inhibit(agent_dir, inhibit):
@@ -322,7 +322,14 @@ def wallpaper_bmp(width, height):
def reg_value(reg, key, name, value):
line = '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"'))
return reg_line(reg, key, name, '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"')))
def reg_dword(reg, key, name, number):
return reg_line(reg, key, name, '"%s"=dword:%08x' % (name, number))
def reg_line(reg, key, name, line):
try:
with open(reg, encoding="utf-8", errors="replace") as f:
rows = f.read().splitlines()
@@ -347,6 +354,16 @@ def desktop_size():
return 1280, 720
def desktop_dpi():
width, height = desktop_size()
return 96 * max(4, int(min(width / 1920.0, height / 1080.0) * 4)) // 4
def dpi(root):
reg = os.path.join(prefix(root), "pfx", "user.reg")
return os.path.isfile(reg) and reg_dword(reg, DESKTOP_KEY, "LogPixels", desktop_dpi())
def wallpaper(root):
width, height = desktop_size()
shrink = min(1.0, WALLPAPER_MAX[0] / width, WALLPAPER_MAX[1] / height)
@@ -492,6 +509,10 @@ def configure(root, library=None):
wallpaper(root)
except OSError as error:
say("Battle.net's desktop wallpaper not set: %s" % error)
try:
dpi(root)
except OSError as error:
say("Battle.net's desktop scale not set: %s" % error)
wow_settings(root)
if change == "first":
say("wrote Battle.net's first config: hardware acceleration off, streaming off, closing itself as it launches a game, "
@@ -1,5 +1,6 @@
#!/usr/bin/python3
import base64
import fcntl
import json
import os
import signal
@@ -87,6 +88,7 @@ class Spec:
self.info_fds = []
self.json_fds = []
self.keep_fds = []
self.lock_files = []
self.command = []
self.argv0 = None
@@ -159,6 +161,8 @@ def parse(argv):
read_fd(int(args[0]))
elif a == "--sync-fd":
s.keep_fds.append(int(args[0]))
elif a == "--lock-file":
s.lock_files.append(args[0])
elif a == "--info-fd":
s.info_fds.append(int(args[0]))
elif a == "--json-status-fd":
@@ -203,6 +207,31 @@ def remaps_nothing(s):
return True
def host_path(s, path):
for op in reversed(s.ops):
if op["t"] != "bind":
continue
dest = op["dest"].rstrip("/")
if path == dest or path.startswith(dest + "/"):
return op["src"].rstrip("/") + path[len(dest):]
return path
def hold_locks(s):
for path in s.lock_files:
try:
fd = os.open(host_path(s, path), os.O_RDONLY)
except OSError as e:
sys.stderr.write("bwrap: Can't open lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
try:
fcntl.lockf(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
except OSError as e:
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
os.set_inheritable(fd, True)
def report_pid(s, pid):
for fd in s.info_fds:
try:
@@ -282,7 +311,7 @@ def run_by_app(s):
if payload is None:
break
if kind == b"P":
report_pid(s, int(payload))
report_pid(s, os.getpid())
elif kind == b"O":
out.write(payload)
out.flush()
@@ -301,6 +330,7 @@ def run_by_app(s):
def main():
s = parse(expand(sys.argv[1:]))
hold_locks(s)
if remaps_nothing(s):
run_here(s)
else:
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
free_name() {
local dir=$1 name=$2 base ext n=2
[ -e "$dir/$name" ] || { echo "$name"; return; }
base=${name%.*} ext=
[ "$base" != "$name" ] && [ -n "$base" ] && ext=.${name##*.} || base=$name
while [ -e "$dir/$base ($n)$ext" ]; do n=$((n + 1)); done
echo "$base ($n)$ext"
}
share() {
local android=$HOME/Storage/$1 link=$HOME/$2 f
[ -d "$android" ] && [ -w "$android" ] || return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
if [ -L "$link" ]; then
rm -f "$link"
elif [ -d "$link" ]; then
shopt -s dotglob nullglob
for f in "$link"/*; do
mv -n -- "$f" "$android/$(free_name "$android" "${f##*/}")" || return 1
done
shopt -u dotglob nullglob
rmdir "$link" 2>/dev/null || mv "$link" "$link.old.$$" || return 1
elif [ -e "$link" ]; then
mv "$link" "$link.old.$$" || return 1
fi
ln -s "$android" "$link"
}
status=0
share Download Downloads || status=1
share Documents Documents || status=1
exit $status
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
set -u
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
cores="libretro-core-info libretro-beetle-pce-fast libretro-beetle-psx libretro-beetle-vb libretro-beetle-wswan
libretro-bsnes-mercury-performance libretro-desmume libretro-gambatte libretro-genesisplusgx libretro-mgba
libretro-nestopia libretro-sameboy libretro-snes9x"
case "${1:-}" in
install)
echo "== STEP RetroArch"
droiddeck-root /usr/bin/apt-get update -q || { echo "== FAIL apt-get update"; exit 1; }
droiddeck-root /usr/bin/apt-get install -y -q retroarch retroarch-assets $cores || { echo "== FAIL apt-get install"; exit 1; }
echo "== STEP PPSSPP"
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || { echo "== FAIL flathub"; exit 1; }
flatpak install --user -y --noninteractive flathub org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
printf '#!/bin/sh\nexec /usr/local/bin/droiddeck-flatpak-run org.ppsspp.PPSSPP "$@"\n' > /usr/local/bin/PPSSPPSDL.new &&
chmod 755 /usr/local/bin/PPSSPPSDL.new && mv -f /usr/local/bin/PPSSPPSDL.new /usr/local/bin/PPSSPPSDL || { echo "== FAIL PPSSPPSDL"; exit 1; }
;;
*)
echo "usage: droiddeck-emulators install" >&2
exit 2
;;
esac
@@ -100,6 +100,10 @@ CLIENT_ENV = {
"JSC_useDFGJIT": "0",
"JSC_useFTLJIT": "0",
}
HIDDEN_ENV = {
"DROIDDECK_EPIC_HIDDEN": "1",
"EGL_DISABLE_STORE_PREWARM": "1",
}
KEPT_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_MESSAGES", "TZ", "XDG_RUNTIME_DIR", "BL_LAUNCH_DIR")
LAUNCH_VERBS = ("waitforexitandrun", "run", "runinprefix")
EPIC_ARGS = ("-auth_", "-epic")
@@ -725,7 +729,7 @@ def fex_environment(fex, files, env):
return result
def client_environment(base, fex, files, display, bus, broker, a11y=None):
def client_environment(base, fex, files, display, bus, broker, a11y=None, hidden=False):
env = {name: base[name] for name in KEPT_ENV if base.get(name)}
env.setdefault("HOME", HOME)
env.setdefault("LANG", "C.UTF-8")
@@ -734,6 +738,8 @@ def client_environment(base, fex, files, display, bus, broker, a11y=None):
env["DBUS_SESSION_BUS_ADDRESS"] = bus
env[BROKER_ENV] = broker
env.update(CLIENT_ENV)
if hidden:
env.update(HIDDEN_ENV)
if a11y:
for name in A11Y_OFF:
env.pop(name, None)
@@ -1248,7 +1254,7 @@ class Session:
path = broker_path()
self.broker = Broker(path, self.mode, base)
write_json(instance_file(), {"pid": os.getpid(), "mode": self.mode, "bus": bus, "broker": path})
env = client_environment(base, fex, files, display, bus, path, self.a11y)
env = client_environment(base, fex, files, display, bus, path, self.a11y, hidden=self.mode == "hidden")
self.command = [fex["bin"], os.path.join(app_dir, "AppRun")]
self.env = env
say("starting the Epic Games Launcher %s (%s, display %s)" % (current.get("app"), self.mode, display))
@@ -5,6 +5,7 @@ step() { echo "== STEP $*"; }
fail() { echo "== FAIL $*"; exit 1; }
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
if command -v pacman >/dev/null 2>&1; then
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
while read -r pkg probe; do
[ -n "$pkg" ] || continue
@@ -77,7 +78,13 @@ done
mv -f "$WORK/installed.new" "$WORK/installed"
find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
else
command -v flatpak >/dev/null 2>&1 || fail "Flatpak is missing from the runtime"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
fi
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/lib/aarch64-linux-gnu/libflatpak.so.0 /usr/lib/aarch64-linux-gnu/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
[ -e "$f" ] || continue
ldd "$f" 2>&1 | grep -E 'not found|version .* not found'
done | sort -u)
[ -z "$missing" ] || { echo "$missing"; fail "Flatpak is missing libraries"; }
@@ -97,7 +104,7 @@ Description=Central repository of Flatpak applications
Icon=https://dl.flathub.org/repo/logo.svg
GPGKey=mQINBFlD2sABEADsiUZUOYBg1UdDaWkEdJYkTSZD68214m8Q1fbrP5AptaUfCl8KYKFMNoAJRBXn9FbE6q6VBzghHXj/rSnA8WPnkbaEWR7xltOqzB1yHpCQ1l8xSfH5N02DMUBSRtD/rOYsBKbaJcOgW0K21sX+BecMY/AI2yADvCJEjhVKrjR9yfRX+NQEhDcbXUFRGt9ZT+TI5yT4xcwbvvTu7aFUR/dH7+wjrQ7lzoGlZGFFrQXSs2WI0WaYHWDeCwymtohXryF8lcWQkhH8UhfNJVBJFgCY8Q6UHkZG0FxMu8xnIDBMjBmSZKwKQn0nwzwM2afskZEnmNPYDI8nuNsSZBZSAw+ThhkdCZHZZRwzmjzyRuLLVFpOj3XryXwZcSefNMPDkZAuWWzPYjxS80cm2hG1WfqrG0Gl8+iX69cbQchb7gbEb0RtqNskTo9DDmO0bNKNnMbzmIJ3/rTbSahKSwtewklqSP/01o0WKZiy+n/RAkUKOFBprjJtWOZkc8SPXV/rnoS2dWsJWQZhuPPtv3tefdDiEyp7ePrfgfKxuHpZES0IZRiFI4J/nAUP5bix+srcIxOVqAam68CbAlPvWTivRUMRVbKjJiGXIOJ78wAMjqPg3QIC0GQ0EPAWwAOzzpdgbnG7TCQetaVV8rSYCuirlPYN+bJIwBtkOC9SWLoPMVZTwQARAQABtC5GbGF0aHViIFJlcG8gU2lnbmluZyBLZXkgPGZsYXRodWJAZmxhdGh1Yi5vcmc+iQJUBBMBCAA+FiEEblwF2XnHba+TwIE1QYTdTZB6fK4FAllD2sACGwMFCRLMAwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQQYTdTZB6fK5RJQ/+Ptd4sWxaiAW91FFk7+wmYOkEe1NY2UDNJjEEz34PNP/1RoxveHDt43kYJQ23OWaPJuZAbu+fWtjRYcMBzOsMCaFcRSHFiDIC9aTp4ux/mo+IEeyarYt/oyKb5t5lta6xaAqg7rwt65jW5/aQjnS4h7eFZ+dAKta7Y/fljNrOznUp81/SMcx4QA5G2Pw0hs4Xrxg59oONOTFGBgA6FF8WQghrpR7SnEe0FSEOVsAjwQ13Cfkfa7b70omXSWp7GWfUzgBKyoWxKTqzMN3RQHjjhPJcsQnrqH5enUu4Pcb2LcMFpzimHnUgb9ft72DP5wxfzHGAWOUiUXHbAekfq5iFks8cha/RST6wkxG3Rf44Zn09aOxh1btMcGL+5xb1G0BuCQnA0fP/kDYIPwh9z22EqwRQOspIcvGeLVkFeIfubxpcMdOfQqQnZtHMCabV5Q/Rk9K1ZGc8M2hlg8gHbXMFch2xJ0Wu72eXbA/UY5MskEeBgawTQnQOK/vNm7t0AJMpWK26Qg6178UmRghmeZDj9uNRc3EI1nSbgvmGlpDmCxaAGqaGL1zW4KPW5yN25/qeqXcgCvUjZLI9PNq3Kvizp1lUrbx7heRiSoazCucvHQ1VHUzcPVLUKKTkoTP8okThnRRRsBcZ1+jI4yMWIDLOCT7IW3FePr+3xyuy5eEo9a25Ag0EWUPa7AEQALT/CmSyZ8LWlRYQZKYw417p7Z2hxqd6TjwkwM3IQ1irumkWcTZBZIbBgrSOg6CcXD2oWydCQHWi9qaxhuhEl2bJL5LskmBcMxVdQeD0LLHd8QUnbnnIby8ocvWN1alPfvJFjCUTrmD22U1ycOzRw2lIe4kiQONbOZtdWrVImQQSndjFlisitbmlWHvHm2lOOYy8+GJB7YffVV193hmnBSJffCy4bvkuLxsI+n1DhOzc7MPV3z6HGk4HiEcF0yyt9tCYhpsxHFdBoq2h771HfAcS0s98EVAqYMFnf9em+4cnYpdI6mhIfS1FQiKl6DBAYA8tT3ggla00DurPo0JwX/zN+PaO5h/6O9aCZwV7G6rbkgMuqMergXaf8oP38gr0z+MqWnkfM63Bodq68GP4l4hd02BoFBbDf38TMuGQB14+twJMdfbAxo2MbgluvQgfwHfZ2ca6gyEY+9s/YD1gugLjV+S6CB51WkFNe1z4tAPgJZNxUcKCbeaHNbthl8Hks/pY9RCEseX/EdfzF18epbSjJMPh4DPQXbUoFwmyuYcoBOPmvZHNl9hK7B/1RP8w1ZrXk8qdupC0SNbafX7270B7lMMVImzZetGsM9ypXJ6llhp3FwW09iseNyGJGPsr/dvTMGDXqOPfU/9SAS1LSTY4K9PbRtdrBE318YX8mIk5ABEBAAGJBHIEGAEIACYWIQRuXAXZecdtr5PAgTVBhN1NkHp8rgUCWUPa7AIbAgUJEswDAAJACRBBhN1NkHp8rsF0IAQZAQgAHRYhBFSmzd2JGfsgQgDYrFYnAunj7X7oBQJZQ9rsAAoJEFYnAunj7X7oR6AP/0KYmiAFeqx14Z43/6s2gt3VhxlSd8bmcVV7oJFbMhdHBIeWBp2BvsUf00I0Zl14ZkwCKfLwbbORC2eIxvzJ+QWjGfPhDmS4XUSmhlXxWnYEveSek5Tde+fmu6lqKM8CHg5BNx4GWIX/vdLi1wWJZyhrUwwICAxkuhKxuP2Z1An48930eslTD2GGcjByc27+9cIZjHKa07I/aLffo04V+oMT9/tgzoquzgpVV4jwekADo2MJjhkkPveSNI420bgT+Q7Fi1l0X1aFUniBvQMsaBa27PngWm6xE2ZYvh7nWCdd5g0c0eLIHxWwzV1lZ4Ryx4ITO/VL25ItECcjhTRdYa64sA62MYSaB0x3eR+SihpgP3wSNPFu3MJo6FKTFdi4CBAEmpWHFW7FcRmd+cQXeFrHLN3iNVWryy0HK/CUEJmiZEmpNiXecl4vPIIuyF0zgSCztQtKoMr+injpmQGC/rF/ELBVZTUSLNB350S0Ztvw0FKWDAJSxFmoxt3xycqvvt47rxTrhi78nkk6jATKGyvP55sO+K7Q7Wh0DXA69hvPrYW2eu8jGCdVGxi6HX7L1qcfEd0378S71dZ3g9o6KKl1OsDWWQ6MJ6FGBZedl/ibRfs8p5+sbCX3lQSjEFy3rx6n0rUrXx8U2qb+RCLzJlmC5MNBOTDJwHPcX6gKsUcXZrEQALmRHoo3SrewO41RCr+5nUlqiqV3AohBMhnQbGzyHf2+drutIaoh7Rj80XRh2bkkuPLwlNPf+bTXwNVGse4bej7B3oV6Ae1N7lTNVF4Qh+1OowtGjmfJPWo0z1s6HFJVxoIof9z58Msvgao0zrKGqaMWaNQ6LUeC9g9Aj/9Uqjbo8X54aLiYs8Z1WNc06jKP+gv8AWLtv6CR+l2kLez1YMDucjm7v6iuCMVAmZdmxhg5I/X2+OM3vBsqPDdQpr2TPDLX3rCrSBiS0gOQ6DwN5N5QeTkxmY/7QO8bgLo/Wzu1iilH4vMKW6LBKCaRx5UEJxKpL4wkgITsYKneIt3NTHo5EOuaYk+y2+Dvt6EQFiuMsdbfUjs3seIHsghX/cbPJa4YUqZAL8C4OtVHaijwGo0ymt9MWvS9yNKMyT0JhN2/BdeOVWrHk7wXXJn/ZjpXilicXKPx4udCF76meE+6N2u/T+RYZ7fP1QMEtNZNmYDOfA6sViuPDfQSHLNbauJBo/n1sRYAsL5mcG22UDchJrlKvmK3EOADCQg+myrm8006LltubNB4wWNzHDJ0Ls2JGzQZCd/xGyVmUiidCBUrD537WdknOYE4FD7P0cHaM9brKJ/M8LkEH0zUlo73bY4XagbnCqve6PvQb5G2Z55qhWphd6f4B6DGed86zJEa/RhS
REPO
if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; then
if ! flatpak remote-list --columns=name 2>/dev/null | grep -qx flathub; then
out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1)
rc=$?
echo "$out"
@@ -131,6 +131,12 @@ def arkham_city_x87(game):
@fix
def teardown_vsync(game):
if game.stem == "teardown":
return {"vblank_mode": "2"}, [], "Teardown: OpenGL keeps the game's own vsync"
@fix
def protonfixes_off(game):
if game.stem in ("blackops3", "darksoulsremastered"):
@@ -357,26 +363,99 @@ def game_cores(env):
print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr)
def cpu_topology(env):
def core_speeds(cores, root="/sys/devices/system/cpu"):
"""Each core's capacity, else its top clock; None when some core reports neither."""
for name in ("cpu_capacity", "cpufreq/cpuinfo_max_freq"):
speeds = {}
for core in cores:
try:
with open("%s/cpu%d/%s" % (root, core, name)) as f:
speeds[core] = int(f.read().strip())
except (OSError, ValueError):
break
else:
return speeds
return None
def fastest_first(cores):
"""The cores, fastest first; cores of equal or unknown speed keep their numeric order."""
cores = sorted(cores)
speeds = core_speeds(cores)
return sorted(cores, key=lambda core: -speeds[core]) if speeds else cores
def proton_cpu_limit(command, env):
"""This game's entry in Proton's own default_cpu_limit list: a core count, another value such as "P" as text, or None."""
app_id = env.get("SteamGameId", "")
if not command or not app_id.isdigit():
return None
try:
if os.path.getsize(command[0]) > 4 * 1024 * 1024:
return None
with open(command[0], encoding="utf-8", errors="replace") as f:
text = f.read()
except OSError:
return None
table = re.search(r"^default_cpu_limit = \{(.*?)^\}", text, re.M | re.S)
match = table and re.search(r'^\s*"%s"\s*:\s*"?(\w+)' % app_id, table.group(1), re.M)
if not match:
return None
value = match.group(1)
return int(value) if value.isdigit() else value
def cpu_topology(env, command=()):
"""Windows sees the game's cores fastest first, so a thread a game pins to CPU 0 runs on the fastest core."""
if "PROTON_CPU_TOPOLOGY" in env:
return
if "WINE_CPU_TOPOLOGY" in env:
if env["WINE_CPU_TOPOLOGY"]:
env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"]
return
if not (env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip()):
picked = bool(env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip())
fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None
if not (picked or fastest):
return
try:
cores = sorted(os.sched_getaffinity(0))
except OSError:
return
online = online_cores()
if not cores or set(cores) >= online or cores[-1] >= len(online):
if not cores or cores[-1] >= len(online):
return
picked = picked and not set(cores) >= online
if fastest:
limit = None if picked else proton_cpu_limit(command, env)
if isinstance(limit, str):
return
cores = fastest_first(cores)[:limit or None]
elif set(cores) >= online:
return
if cores == sorted(online):
return
env["WINE_CPU_TOPOLOGY"] = env["PROTON_CPU_TOPOLOGY"] = "%d:%s" % (len(cores), ",".join(map(str, cores)))
print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr)
def gl_vsync(env):
"""OpenGL stops waiting for each screen refresh; Steam's Frame Limit still holds the game through gamescope."""
# Wine asks for interval 1 on every GL window, and WineD3D's front-buffer drawing (DirectDraw,
# Direct3D 1-7) never lowers it, so those games ran at the refresh rate with no limit set.
if "vblank_mode" in env or game_id(env) is None:
return False
env["vblank_mode"] = "0"
return True
def game_images(env):
if game_id(env) is None:
return False
env.setdefault("GAMESCOPE_WSI_MIN_IMAGE_COUNT", "8")
env.setdefault("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT", "1")
return True
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -418,6 +497,59 @@ def apply_config(env, config, app_id, fixes=None):
return result
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
def game_debug_channels(*values):
"""Normalize Wine selectors, retaining custom channels before required diagnostics."""
selectors = {}
for value in values:
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
continue
for part in value.split(","):
part = part.strip()
match = WINE_DEBUG_SELECTOR.fullmatch(part)
if match is None:
continue
key = (match[1] or "", match[3])
# Move the last value to the end: global +/-all and per-class selectors
# have ordered semantics, so replacing a value in its old position is wrong.
selectors.pop(key, None)
selectors[key] = part
for channel in GAME_DEBUG_CHANNELS:
key = ("", channel)
selectors.pop(key, None)
selectors[key] = "+" + channel
formatted = ",".join(selectors.values())
if len(formatted) > 8192:
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
return formatted
def apply_game_debug_logs(env, config, debug_dir):
"""Apply app-owned diagnostics to a real game, without editing its launch command."""
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
return env
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
return env
result = dict(env)
result.update({
"PROTON_LOG": "1",
"PROTON_LOG_DIR": debug_dir,
"PROTON_CRASH_REPORT_DIR": debug_dir,
"DXVK_LOG_PATH": debug_dir,
"DXVK_LOG_LEVEL": "debug",
"VKD3D_DEBUG": "info",
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
def sync_config(config, app_id):
games = config.get("games", {})
return {
@@ -723,6 +855,7 @@ def main():
return 2
env = game_gpu(os.environ.copy())
mic_enabled = env.get("BL_MIC_ENABLED")
debug_dir = env.get("BL_DEBUG_DIR", "")
scripts = mark_install_scripts(command, env)
if scripts and install_scripts_done(scripts, env):
print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr)
@@ -733,12 +866,17 @@ def main():
digest = None
app_id = game_id(env)
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
if waiting:
game_images(env)
fixes = {}
if waiting:
command = skip_red_launcher(command)
ubisoft_overlay_off(env)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
if not gl_default:
fixes.pop("vblank_mode", None)
for note in notes:
print("droiddeck-game-env: " + note, file=sys.stderr)
command += extra
@@ -747,10 +885,13 @@ def main():
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
path = Path.home() / ".config/droiddeck/game-environment.json"
config = {}
try:
with path.open(encoding="utf-8") as source:
config = json.load(source)
if waiting:
if "vblank_mode" in config.get("shared", {}):
fixes.pop("vblank_mode", None)
env = apply_config(env, config, app_id, fixes)
else:
env = apply_config(env, sync_config(config, app_id), app_id)
@@ -759,6 +900,13 @@ def main():
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if waiting:
before_debug = env
env = apply_game_debug_logs(env, config, debug_dir)
if env is not before_debug:
print("droiddeck-game-env: game debug logs enabled for this launch", file=sys.stderr)
if gl_default and env.get("vblank_mode") == "0":
print("droiddeck-game-env: OpenGL does not wait for the screen refresh (vblank_mode=0)", file=sys.stderr)
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
env = game_logs(command, env, app_id)
@@ -767,7 +915,7 @@ def main():
env = vram_cap(env)
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env)
cpu_topology(env, command)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -0,0 +1,344 @@
#!/usr/bin/python3
"""GOG patch installers and the lease shared by maintenance and game launches."""
import fcntl
import errno
import json
import os
from pathlib import Path
import runpy
import subprocess
import sys
import tempfile
import time
BIN = Path(__file__).resolve().parent
IDLE = {"wineserver", "services.exe", "winedevice.exe", "explorer.exe", "rpcss.exe", "plugplay.exe",
"conhost.exe", "lsass.exe", "svchost.exe", "steam.exe", "wineboot.exe", "winemenubuilder.exe"}
def control(folder):
folder = Path(folder).resolve(strict=True)
root = folder / ".droiddeck-gog"
if root.is_symlink():
raise ValueError("GOG control directory is a symbolic link")
root.mkdir(exist_ok=True)
return root
def read(path):
if path.is_symlink():
raise ValueError("GOG metadata is a symbolic link")
return json.loads(path.read_text(encoding="utf-8"))
def write(path, value):
if path.is_symlink():
raise ValueError("GOG metadata is a symbolic link")
descriptor, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".new", dir=path.parent)
temporary = Path(name)
try:
with os.fdopen(descriptor, "w") as stream:
json.dump(value, stream)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
try:
os.fsync(directory)
except OSError as error:
if error.errno not in (errno.EINVAL, errno.ENOTSUP):
raise
finally:
os.close(directory)
finally:
temporary.unlink(missing_ok=True)
def lock_file(root):
return os.fdopen(os.open(root / "lease", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), "r+")
def generation(pid):
try:
return Path("/proc/%s/stat" % pid).read_text().rsplit(")", 1)[1].split()[19]
except (OSError, IndexError):
return None
def lease(folder, owner):
root = control(folder)
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_SH | fcntl.LOCK_NB)
sidecar = read(Path(folder) / ".droiddeck-store.json")
if sidecar.get("state", "installed") != "installed":
raise ValueError("Resume or recover the GOG update before playing")
journal = root / "operation.json"
if journal.exists() and read(journal).get("phase") != "download":
raise ValueError("GOG maintenance is incomplete")
start = generation(owner)
if start is None:
raise ValueError("Game launcher has exited")
print("ready", flush=True)
sys.stdout.close()
while generation(owner) == start:
time.sleep(0.25)
return 0
def desktop_environment(base, proc=Path("/proc")):
env = dict(base)
if env.get("DROIDDECK_GOG_DESKTOP") != "1":
return env
deadline = time.monotonic() + 45
while True:
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
try:
command = (entry / "cmdline").read_bytes().split(b"\0")[0]
if command != b"/usr/bin/plasmashell":
continue
values = dict(os.fsdecode(item).split("=", 1) for item in (entry / "environ").read_bytes().split(b"\0") if b"=" in item)
if values.get("BL_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"):
continue
if not values.get("DISPLAY") or values.get("WAYLAND_DISPLAY") == env.get("WAYLAND_DISPLAY"):
continue
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "BL_DESKTOP"):
if key in values:
env[key] = values[key]
return env
except (OSError, ValueError):
continue
if time.monotonic() >= deadline:
raise ValueError("The desktop display is not ready; resume the Linux session and verify recovery before retrying")
time.sleep(0.25)
def target_for(folder, appid, game):
run = runpy.run_path(str(BIN / "droiddeck-proton-run"))["main"].__globals__
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
target = run["shortcut_target"](str(int(appid) & 0xffffffff), str(game), str(folder), root)
target.install = str(folder)
return run, root, target
def runner(folder, appid, game, graphical=False):
run, root, target = target_for(folder, appid, game)
available = run["tools"](root)
name, _ = run["choose_tool"](target.appid, run["mapping"](root), available)
if name is None:
raise ValueError("No Proton tool is installed for this game")
tool, command = available[name]
base = desktop_environment(os.environ) if graphical else dict(os.environ)
env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1")
env["DROIDDECK_GOG_MAINTENANCE"] = "1"
# Installer copy routines use x87 integer loads/stores; reduced precision corrupts paths (FEX #5827).
env["FEX_X87REDUCEDPRECISION"] = "0"
env.pop("BL_STORE_EXIT", None)
return str(Path(tool) / command), env, target.compatdata
def active(prefix, proc=Path("/proc")):
result = []
prefix = os.path.realpath(os.path.join(prefix, "pfx"))
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
try:
env = dict(part.split(b"=", 1) for part in (entry / "environ").read_bytes().split(b"\0") if b"=" in part)
if os.path.realpath(os.fsdecode(env.get(b"WINEPREFIX", b""))) != prefix:
continue
args = (entry / "cmdline").read_bytes().split(b"\0")
name = os.fsdecode(args[0]).replace("\\", "/").rsplit("/", 1)[-1].lower()
if name not in IDLE:
result.append(int(entry.name))
except (OSError, ValueError):
continue
return result
def idle(folder, appid, game):
_, _, target = target_for(folder, appid, game)
if active(target.compatdata):
raise ValueError("Close the GOG game before maintenance")
return 0
def validate_installer(folder, installer):
root = control(folder)
path = Path(installer)
if path.is_symlink() or not path.resolve(strict=True).is_relative_to(root / "downloads") or path.suffix.lower() != ".exe":
raise ValueError("The patch executable is outside GOG download storage")
with path.open("rb") as stream:
if stream.read(2) != b"MZ":
raise ValueError("The GOG patch is not a Windows executable")
return path
def installer_arguments(path):
with path.open("rb") as stream:
data = stream.read(4 * 1024 * 1024)
return ["/NOGUI"] if b"Inno Setup Setup Data" in data else []
def start(folder, appid, installer, game):
root = control(folder)
validate_installer(folder, installer)
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
journal = read(root / "operation.json")
if journal.get("phase") != "patch-ready":
raise ValueError("The patch must be selected again before it can run")
idle(folder, appid, game)
journal["phase"] = "patch-starting"
write(root / "operation.json", journal)
write(root / "patch-status.json", {"state": "starting", "startedAt": time.time()})
with (root / "patch.log").open("ab") as log:
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "run", folder, appid, installer, game],
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True)
return 0
def status(folder):
root = control(folder)
path = root / "patch-status.json"
result = read(path)
ended = result.get("state") == "running" and generation(result.get("pid")) != result.get("generation")
abandoned = result.get("state") == "starting" and time.time() - result.get("startedAt", 0) > 60
if ended or abandoned:
result = {"state": "uncertain", "reason": "The patch helper ended without a confirmed result; verify recovery before retrying"}
write(path, result)
journal = read(root / "operation.json")
journal["phase"] = "patch-uncertain"
write(root / "operation.json", journal)
print(json.dumps(result), flush=True)
return 0
def run_patch(folder, appid, installer, game):
root = control(folder)
try:
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX)
path = validate_installer(folder, installer)
command, env, prefix = runner(folder, appid, game, True)
if active(prefix):
raise ValueError("Close the GOG game before applying the patch")
journal = read(root / "operation.json")
if journal.get("phase") != "patch-starting":
raise ValueError("The patch is already running or needs recovery")
journal["phase"] = "patch-applying"
write(root / "operation.json", journal)
sidecar_path = Path(folder) / ".droiddeck-store.json"
sidecar = read(sidecar_path)
sidecar["state"] = "updating"
write(sidecar_path, sidecar)
installed_path = root / "installed.json"
if installed_path.is_file():
installed = read(installed_path)
installed.update(verified=False, manifest={}, files=[])
write(installed_path, installed)
write(root / "patch-status.json", {"state": "running", "pid": os.getpid(), "generation": generation(os.getpid())})
os.makedirs(prefix, exist_ok=True)
setup = runpy.run_path(str(BIN / "droiddeck-store-launch"))["main"].__globals__
previous = dict(os.environ)
try:
os.environ.update(env)
pfx = Path(prefix) / "pfx"
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
if not (pfx / "drive_c/windows/system32/reg.exe").is_file():
raise ValueError("Proton did not initialize the game's registry tool")
result = setup["apply_gog_registry"](Path(folder), prefix, command, installation=journal.get("before"))
if not result.startswith(("ready", "written=")):
raise ValueError("GOG registry preparation failed; the patch was not applied")
prepare_setup(folder, command, env)
finally:
os.environ.clear(); os.environ.update(previous)
proc = subprocess.Popen([command, "run", str(path), *installer_arguments(path)], cwd=str(path.parent), env=env)
code = proc.wait()
quiet_at = time.monotonic()
while True:
if active(prefix):
quiet_at = time.monotonic()
elif time.monotonic() - quiet_at >= 2:
break
time.sleep(0.25)
journal["phase"] = "patch-uncertain"
write(root / "operation.json", journal)
if code:
raise ValueError("GOG patch installer exited with code %d; inspect patch.log" % code)
write(root / "patch-status.json", {"state": "done", "exitCode": code})
return 0
except Exception as error:
write(root / "patch-status.json", {"state": "failed", "reason": str(error)})
return 1
def prepare_setup(folder, command, env):
root = control(folder)
record_path = root / "installed.json"
if not record_path.is_file():
return
journal = read(root / "operation.json")
record = journal.get("before") or read(record_path)
manifest = record.get("manifest", {})
if not record.get("build"):
return
info_path = Path(folder) / ("goggame-%s.info" % record["id"])
language = read(info_path).get("language", "") if info_path.is_file() else ""
legacy = manifest.get("product", {})
products = manifest.get("products", []) if not legacy else [
{"productId": str(item["gameID"]), "temp_executable": item["executable"].lstrip("/\\")}
for item in legacy.get("support_commands", [])
if "Neutral" in item.get("languages", []) or record.get("language") in item.get("languages", []) or language in item.get("languages", [])]
for product in products:
if str(product.get("productId")) not in record.get("products", []):
continue
program = None
if manifest.get("scriptInterpreter"):
if not (Path(folder) / ("goggame-%s.script" % product["productId"])).is_file():
continue
program = Path(folder) / "support/__redist/ISI/scriptinterpreter.exe"
elif product.get("temp_executable"):
relative = product["temp_executable"].replace("\\", "/")
for candidate in (Path(folder) / "support" / str(product["productId"]) / relative, Path(folder) / relative):
if candidate.is_file():
program = candidate
break
if program is None:
continue
if not program.resolve(strict=True).is_relative_to(Path(folder).resolve()):
raise ValueError("GOG setup executable leaves the installation")
windows = "Z:" + str(Path(folder).resolve()).replace("/", "\\")
args = ["/VERYSILENT", "/DIR=" + windows, "/ProductId=" + str(product["productId"]),
"/galaxyclient", "/buildId=" + str(legacy.get("timestamp", record["build"])), "/versionName=" + record.get("version", ""),
"/lang-code=" + record.get("language", "en-US"), "/supportDir=" + windows + "\\support", "/nodesktopshortcut"]
if language:
args += ["/Language=" + language, "/LANG=" + language.lower()]
result = subprocess.run([command, "run", str(program), *args], env=env, cwd=folder, timeout=120)
if result.returncode:
raise ValueError("GOG installation setup failed; the patch was not applied")
def main(argv):
if len(argv) == 3 and argv[0] == "lease":
return lease(argv[1], int(argv[2]))
if len(argv) == 4 and argv[0] == "idle":
return idle(*argv[1:])
if len(argv) == 2 and argv[0] == "status":
return status(argv[1])
if len(argv) == 5 and argv[0] == "start":
return start(*argv[1:])
if len(argv) == 5 and argv[0] == "run":
return run_patch(*argv[1:])
raise ValueError("Invalid GOG maintenance command")
if __name__ == "__main__":
try:
sys.exit(main(sys.argv[1:]))
except Exception as error:
print("GOG maintenance: " + str(error), file=sys.stderr)
sys.exit(1)
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
import json
import os
import select
import socket
import struct
import sys
import time
DISPLAY_ID = 1
REGISTRY_ID = 2
METHOD_ID = 3
SETTLE = 0.15
def wl_string(value):
data = value.encode() + b"\0"
return struct.pack("<I", len(data)) + data + b"\0" * (-len(data) % 4)
def read_string(payload, offset):
(length,) = struct.unpack_from("<I", payload, offset)
start = offset + 4
text = payload[start:start + length - 1].decode(errors="replace")
return text, start + length + (-length % 4)
class Connection:
def __init__(self, sock):
self.sock = sock
self.buffer = b""
def send(self, obj, opcode, payload=b""):
self.sock.sendall(struct.pack("<II", obj, ((8 + len(payload)) << 16) | opcode) + payload)
def messages(self, timeout):
ready, _, _ = select.select([self.sock], [], [], timeout)
if not ready:
return []
data, _, _, _ = self.sock.recvmsg(65536, socket.CMSG_SPACE(16 * 4))
if not data:
raise EOFError
self.buffer += data
out = []
while len(self.buffer) >= 8:
obj, word = struct.unpack_from("<II", self.buffer)
size = word >> 16
if size < 8 or len(self.buffer) < size:
break
out.append((obj, word & 0xFFFF, self.buffer[8:size]))
self.buffer = self.buffer[size:]
return out
class Report:
def __init__(self, directory):
self.directory = directory
self.seq = 0
self.sent = None
def write(self, field, hint=0, purpose=0):
state = (field, purpose)
if state == self.sent or not self.directory:
return
self.sent = state
self.seq += 1
os.makedirs(self.directory, exist_ok=True)
target = os.path.join(self.directory, "ime.json")
temp = target + ".tmp"
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as handle:
json.dump({"textField": field, "hint": hint, "purpose": purpose, "seq": self.seq}, handle)
os.replace(temp, target)
print(f"droiddeck-ime: text field {'focused' if field else 'left'}", file=sys.stderr, flush=True)
def connect():
fd = os.environ.pop("WAYLAND_SOCKET", "")
if fd.isdigit():
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, fileno=int(fd))
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(os.path.join(os.environ["XDG_RUNTIME_DIR"], os.environ.get("WAYLAND_DISPLAY", "wayland-0")))
return sock
def main():
launch = os.environ.get("BL_LAUNCH_DIR", "")
report = Report(os.path.join(launch, "agent") if launch else "")
conn = Connection(connect())
conn.send(DISPLAY_ID, 1, struct.pack("<I", REGISTRY_ID))
contexts = {}
current = None
pending = None
while True:
timeout = None if pending is None else max(0.0, pending - time.monotonic())
try:
batch = conn.messages(timeout)
except (EOFError, ConnectionError):
report.write(False)
return 0
for obj, opcode, payload in batch:
if obj == DISPLAY_ID and opcode == 0:
_, code = struct.unpack_from("<II", payload)
message, _ = read_string(payload, 8)
print(f"droiddeck-ime: protocol error {code}: {message}", file=sys.stderr, flush=True)
report.write(False)
return 1
if obj == REGISTRY_ID and opcode == 0:
(name,) = struct.unpack_from("<I", payload)
interface, offset = read_string(payload, 4)
(version,) = struct.unpack_from("<I", payload, offset)
if interface == "zwp_input_method_v1":
conn.send(REGISTRY_ID, 0, struct.pack("<I", name) + wl_string(interface)
+ struct.pack("<II", min(version, 1), METHOD_ID))
elif obj == METHOD_ID and opcode == 0:
(context,) = struct.unpack_from("<I", payload)
contexts[context] = [0, 0]
current = context
pending = None
report.write(True)
elif obj == METHOD_ID and opcode == 1:
(context,) = struct.unpack_from("<I", payload)
contexts.pop(context, None)
conn.send(context, 0)
if context == current:
current = None
pending = time.monotonic() + SETTLE
elif obj in contexts and opcode == 2:
hint, purpose = struct.unpack_from("<II", payload)
contexts[obj] = [hint, purpose]
if obj == current:
report.write(True, hint, purpose)
if pending is not None and time.monotonic() >= pending:
pending = None
if current is None:
report.write(False)
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,93 @@
#!/usr/bin/python3
import os
import re
import stat
import sys
HOME = os.environ.get("HOME", "/root")
STEAM = os.path.join(HOME, ".local/share/Steam")
STORES = os.environ.get("DROIDDECK_STORES_ROOT", "/mnt/droiddeck-stores")
TOOLS = re.compile(r"^(Proton |Proton$|SteamLinuxRuntime|Steamworks Shared$)")
def libraries():
paths = [STEAM]
try:
with open(os.path.join(STEAM, "steamapps/libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
paths += [p.replace("\\\\", "\\") for p in re.findall(r'"path"\s+"([^"]+)"', f.read())]
except OSError:
pass
seen = []
for path in paths:
real = os.path.realpath(path)
if real not in seen:
seen.append(real)
return seen
def roots():
found = []
for library in libraries():
for name in ("common", "compatdata"):
found.append((os.path.join(library, "steamapps", name), name == "common"))
found.append((os.path.join(HOME, "Games"), False))
try:
found += [(entry.path, False) for entry in os.scandir(STORES) if entry.is_dir(follow_symlinks=False)]
except OSError:
pass
return [(path, skip_tools) for path, skip_tools in found if os.path.isdir(path)]
def fix(path, st, wanted):
if st.st_uid != os.geteuid() or st.st_mode & wanted == wanted:
return 0
try:
os.chmod(path, stat.S_IMODE(st.st_mode) | wanted)
return 1
except OSError:
return 0
def walk(top, skip_tools):
fixed = 0
stack = [(top, True)]
while stack:
directory, first = stack.pop()
try:
entries = list(os.scandir(directory))
except OSError:
continue
for entry in entries:
if first and skip_tools and TOOLS.match(entry.name):
continue
try:
st = entry.stat(follow_symlinks=False)
except OSError:
continue
if stat.S_ISDIR(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRWXU)
stack.append((entry.path, False))
elif stat.S_ISREG(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRUSR | stat.S_IWUSR)
return fixed
def main():
try:
os.nice(19)
except OSError:
pass
total = 0
for top, skip_tools in roots():
try:
fixed = fix(top, os.stat(top), stat.S_IRWXU) + walk(top, skip_tools)
except OSError:
continue
if fixed:
print(f"droiddeck-library-perms: {top}: {fixed} made writable")
total += fixed
print(f"droiddeck-library-perms: {total} files and folders made writable")
if __name__ == "__main__":
sys.exit(main())
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/python3
import array
import json
import os
import signal
import socket
import struct
import sys
SOCKET_FILE = "/etc/droiddeck/root-socket"
def socket_name():
name = os.environ.get("DROIDDECK_ROOT_SOCKET", "")
if not name:
try:
with open(SOCKET_FILE, encoding="utf-8") as f:
name = f.read().strip()
except OSError:
pass
return "\0" + (name or "com.droiddeck.launcher.root")
def frame(sock, kind, payload):
sock.sendall(kind.encode() + struct.pack(">i", len(payload)) + payload)
def read_exact(sock, n):
data = b""
while len(data) < n:
chunk = sock.recv(n - len(data))
if not chunk:
return None
data += chunk
return data
def main(argv):
if len(argv) < 2 or argv[1] in ("-h", "--help"):
print("usage: droiddeck-root [--check] command [arg ...]", file=sys.stderr)
return 2
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(socket_name())
except OSError as e:
print(f"droiddeck-root: DroidDeck's root service is not reachable: {e}", file=sys.stderr)
return 126
if argv[1] == "--check":
return 0
env = dict(os.environ)
for name in ("LD_PRELOAD", "PROOT_FASTPATH", "DROIDDECK_ROOT_SOCKET"):
env.pop(name, None)
for name in [k for k in env if k.startswith("PROOT_")]:
env.pop(name, None)
try:
cwd = os.getcwd()
except OSError:
cwd = "/root"
body = json.dumps({"argv": argv[1:], "env": env, "cwd": cwd}).encode()
fds = array.array("i", [0, 1, 2])
sock.sendmsg([b"R" + struct.pack(">i", len(body))], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
sock.sendall(body)
def forward(signum, _frame):
try:
frame(sock, "S", str(signum).encode())
except OSError:
pass
for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2):
signal.signal(signum, forward)
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
status = 1
while True:
try:
head = read_exact(sock, 5)
except InterruptedError:
continue
except OSError:
break
if head is None:
break
kind = chr(head[0])
payload = read_exact(sock, struct.unpack(">i", head[1:])[0]) or b""
if kind == "E":
print("droiddeck-root: " + payload.decode(errors="replace"), file=sys.stderr)
elif kind == "X":
status = int(payload.decode() or "1")
break
return status
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -24,22 +24,59 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
mv -f "$BL_LOG" "$BL_LOG.1"
fi
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
dd=$(command -v gnudd || echo dd)
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:-?} 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)"
fi
sync_timezone() {
local zone=${TZ:-}
case "$zone" in ''|/*|*..*) return 0 ;; esac
[ -f "/usr/share/zoneinfo/$zone" ] || return 0
if [ "$(readlink /etc/localtime 2>/dev/null)" != "/usr/share/zoneinfo/$zone" ]; then
ln -sfn "/usr/share/zoneinfo/$zone" /etc/localtime.droiddeck && mv -Tf /etc/localtime.droiddeck /etc/localtime || return 0
fi
[ "$(cat /etc/timezone 2>/dev/null)" = "$zone" ] || printf '%s\n' "$zone" > /etc/timezone
} 2>/dev/null
sync_timezone
write_system_bus_config() {
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>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<servicedir>/usr/share/droiddeck/system-services</servicedir>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
}
prepare_locale() {
local dir=/usr/lib/locale stamp=/usr/lib/locale/.droiddeck-archive want have= pkg
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
want=${pkg[0]##*/}
if [ -d /var/lib/pacman/local ]; then
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
want=${pkg[0]##*/}
else
want=libc6-$(dpkg-query -W -f='${Version}' libc6 2>/dev/null)
fi
[ -f "$stamp" ] && read -r have < "$stamp"
[ "$have" = "$want" ] && [ -f "$dir/locale-archive" ] && [ ! "$dir/locale-archive" -nt "$stamp" ] && return 0
[ -d "$dir/C.utf8" ] && command -v localedef >/dev/null 2>&1 || return 0
DROIDDECK_LINK_RENAME=1 localedef --add-to-archive --replace "$dir/C.utf8" >/dev/null 2>&1 || return 0
rm -f /usr/lib/gconv/gconv-modules.cache
rm -f /usr/lib/gconv/gconv-modules.cache /usr/lib/aarch64-linux-gnu/gconv/gconv-modules.cache
command -v iconvconfig >/dev/null 2>&1 && iconvconfig >/dev/null 2>&1
printf '%s\n' "$want" > "$stamp"
echo "== locale archive built for $want"
@@ -72,10 +109,37 @@ clear_stale_tmp() {
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${BL_INSIDE:-}" ]; then
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
rm -f /tmp/.bl-clock
head -c 8 /dev/zero > /tmp/.bl-clock
fi
steam_devtools() {
_bl_cdp=()
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
if timeout 5 python3 -c 'import socket, sys
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", int(sys.argv[1])))' "$1" 2>/dev/null; then
BL_CDP_PORT=$1
return 0
fi
echo "== steam: port $1 is held by another app; Decky cannot load this session and Steam's devtools use another port"
fi
BL_CDP_PORT=$((20000 + RANDOM % 30000))
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
}
steam_update_stuck() {
[ "$1" -lt 60 ] || steam_updates=0
local stamp
stamp=$(stat -c '%n %Y %s' "${steam_root:-}"/package/*.installed 2>/dev/null)
if [ "$1" -ge 60 ]; then
steam_updates=0
steam_installs=0
elif [ "$stamp" != "${steam_update_stamp-$stamp}" ] && [ "${steam_installs:-0}" -lt 5 ]; then
steam_updates=0
steam_installs=$((${steam_installs:-0} + 1))
fi
steam_update_stamp=$stamp
steam_updates=$((steam_updates + 1))
[ "$steam_updates" -ge 3 ]
}
@@ -313,6 +377,7 @@ rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
/usr/local/bin/droiddeck-desktop-bookmarks || true
/usr/local/bin/droiddeck-downloads || true
fi
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}
@@ -380,6 +445,20 @@ if [ -z "${BL_INSIDE:-}" ]; then
step "starting the desktop"
start_agent --no-focus
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
nap 0.1
done
if [ -S /run/dbus/system_bus_socket ]; then
droiddeck-login1 --with-netmanager &
echo "== desktop: system bus up, network and power services running"
else
echo "== desktop: the system bus did not come up"
fi
fi
cores=$(program_cores)
if [ -n "$cores" ]; then
echo "== desktop cores: $cores (the desktop and every program started from it)"
@@ -442,6 +521,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
args+=(--mangoapp)
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
# gamescope writes the frame times the app's HUD shows here (patch 0125).
mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames
export BL_INSIDE=1
# A fixed path: left to itself gamescope creates a new limiter state file on every start.
rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-*
@@ -644,7 +725,7 @@ case $mode in
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam and the hidden Epic Games Launcher are not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
@@ -654,16 +735,16 @@ case $mode in
(
bl_zram_scan() {
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id
local _d _c _args _name _a _id _fex
for _d in /proc/[0-9]*; do
[ "${_d##*/}" != "$BASHPID" ] || continue
_args=()
# Under FEX the program is FEX's first argument. AppId= is its own argument.
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
[ "${#_args[@]}" -gt 0 ] || continue
_name=${_args[0]}
_name=${_args[0]} _fex=0
if [ "${#_args[@]}" -gt 1 ]; then
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} ;; esac
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} _fex=1 ;; esac
fi
case ${_name##*/} in
reaper)
@@ -678,7 +759,13 @@ case $mode in
done
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*) _bl_others+=("${_d##*/}") ;;
*)
if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then
_bl_pids+=("${_d##*/}")
else
_bl_others+=("${_d##*/}")
fi
;;
esac
done
}
@@ -1025,23 +1112,7 @@ case $mode in
set -- "$@" "$_bl_url"
fi
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>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
system_bus=$!
for _ in $(seq 1 50); do
@@ -1129,14 +1200,9 @@ 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
steam_devtools 8080
export BL_CDP_PORT
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]; then
echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader"
else
export BL_CDP_GUARD=$BL_CDP_PORT
@@ -1197,6 +1263,8 @@ BUSCONF
fi
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
steam_updates=0
steam_installs=0
steam_update_stamp=$(stat -c '%n %Y %s' "$steam_root"/package/*.installed 2>/dev/null)
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
steam_other_game_running() {
local line value n open
@@ -1606,6 +1674,12 @@ BUSCONF
set --
continue
fi
if [ "$steam_x64" = 1 ] && [ "$rc" -eq 132 ] && [ -z "${_bl_x64_sigill:-}" ]; then
_bl_x64_sigill=1
echo "== steam: the x86-64 client stopped on an illegal instruction after it updated itself; starting it again once"
set --
continue
fi
[ "$rc" -eq 42 ] || break
if steam_update_stuck "$steam_ran"; then
echo "== steam: asked to restart for an update $steam_updates times and it is not installing; the session stops here rather than loop"
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
[ "${1:-}" = run ] || exec /usr/bin/snap "$@"
shift
while [ $# -gt 0 ]; do
case $1 in
--) shift; break ;;
-*) shift ;;
*) break ;;
esac
done
target=${1:?usage: snap run <snap>[.<app>] [args...]}
shift
name=${target%%.*}
app=${target#*.}
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
while [ $# -gt 0 ]; do
case $1 in
--classic) shift ;;
--base) shift 2 ;;
--*) shift ;;
*) break ;;
esac
done
tag=${1:?security tag}
shift
[ "${1##*/}" = snap-exec ] && shift
app=${1:-}
shift
name=${tag#snap.}
name=${name%%.*}
app=${app#*.}
[ -n "$app" ] || app=$name
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/python3
import os
import re
import shlex
import sys
import yaml
SNAP_DIR = "/snap"
HOST_DIRS = ("/etc", "/home", "/root", "/tmp", "/run", "/var/snap", "/var/lib/snapd", "/var/tmp", "/var/log",
"/media", "/mnt", "/snap", "/usr/src", "/lib/modules")
def load(name):
with open(f"{SNAP_DIR}/{name}/current/meta/snap.yaml") as f:
return yaml.safe_load(f) or {}
def expand(value, env):
return re.sub(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?", lambda m: env.get(m.group(1), ""), str(value))
def provider_path(path, provider, revision):
snap = f"{SNAP_DIR}/{provider}/{revision}"
for var, value in (("$SNAP_DATA", f"/var/snap/{provider}/{revision}"),
("$SNAP_COMMON", f"/var/snap/{provider}/common"), ("$SNAP", snap)):
if path == var or path.startswith(var + "/"):
return os.path.normpath(value + path[len(var):])
return os.path.normpath(f"{snap}/{path}")
def content_binds(name, meta, env):
out = []
for plug_name, plug in (meta.get("plugs") or {}).items():
if not isinstance(plug, dict) or plug.get("interface") != "content" or not plug.get("target"):
continue
provider = (plug.get("default-provider") or "").split(":")[0]
if not provider or not os.path.isdir(f"{SNAP_DIR}/{provider}/current"):
continue
try:
slots = load(provider).get("slots") or {}
except OSError:
continue
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{provider}/current"))
target = expand(plug["target"], env)
for slot_name, slot in slots.items():
if not isinstance(slot, dict) or slot.get("interface") != "content":
continue
if slot.get("content", slot_name) != plug.get("content", plug_name):
continue
nested = "source" in slot
reads = (slot.get("source") or {}).get("read") if nested else slot.get("read")
for path in reads or []:
source = provider_path(str(path), provider, revision)
out.append((plug_name, source, os.path.join(target, os.path.basename(source)) if nested else target))
if not nested:
break
break
return out
def main(argv):
if len(argv) < 3:
print("usage: droiddeck-snap-run SNAP APP [ARG...]", file=sys.stderr)
return 2
name, app, args = argv[1], argv[2], argv[3:]
meta = load(name)
spec = (meta.get("apps") or {}).get(app)
if spec is None:
print(f"error: snap \"{name}\" has no app \"{app}\"", file=sys.stderr)
return 1
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{name}/current"))
home = os.environ.get("HOME", "/root")
snap = f"{SNAP_DIR}/{name}/{revision}"
env = dict(os.environ)
for k in ("LD_PRELOAD", "LD_LIBRARY_PATH"):
env.pop(k, None)
env.update({
"SNAP": snap, "SNAP_NAME": name, "SNAP_INSTANCE_NAME": name, "SNAP_INSTANCE_KEY": "",
"SNAP_REVISION": revision, "SNAP_VERSION": str(meta.get("version", "")), "SNAP_ARCH": "arm64",
"SNAP_LIBRARY_PATH": "/var/lib/snapd/lib/gl:/var/lib/snapd/lib/gl32:/var/lib/snapd/void",
"SNAP_DATA": f"/var/snap/{name}/{revision}", "SNAP_COMMON": f"/var/snap/{name}/common",
"SNAP_USER_DATA": f"{home}/snap/{name}/{revision}", "SNAP_USER_COMMON": f"{home}/snap/{name}/common",
"SNAP_REAL_HOME": home, "SNAP_UID": str(os.getuid()), "SNAP_EUID": str(os.geteuid()),
"SNAP_COOKIE": "", "SNAP_CONTEXT": "", "SNAP_REEXEC": "0",
})
for d in (env["SNAP_USER_DATA"], env["SNAP_USER_COMMON"], env["SNAP_DATA"], env["SNAP_COMMON"]):
os.makedirs(d, exist_ok=True)
current = f"{home}/snap/{name}/current"
if os.path.realpath(current) != env["SNAP_USER_DATA"]:
try:
os.unlink(current)
except OSError:
pass
os.symlink(revision, current)
confinement = meta.get("confinement", "strict")
if confinement != "classic":
env["HOME"] = env["SNAP_USER_DATA"]
env["PATH"] = ":".join([f"{snap}/usr/sbin", f"{snap}/usr/bin", f"{snap}/sbin", f"{snap}/bin",
"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/games"])
env["LD_LIBRARY_PATH"] = env["SNAP_LIBRARY_PATH"]
for scope in (meta.get("environment") or {}, spec.get("environment") or {}):
for k, v in scope.items():
env[k] = expand(v, env)
command = shlex.split(expand(spec.get("command", ""), env))
if command and not command[0].startswith("/"):
command[0] = f"{snap}/{command[0]}"
chain = [c if c.startswith("/") else f"{snap}/{c}" for c in (meta.get("command-chain") or []) + (spec.get("command-chain") or [])]
program = chain + command + args
if confinement == "classic":
os.execvpe(program[0], program, env)
base = meta.get("base") or "core"
root = f"{SNAP_DIR}/{base}/current"
if not os.path.isdir(root):
print(f"error: the base snap \"{base}\" is not installed; run: snap install {base}", file=sys.stderr)
return 1
bwrap = ["/usr/local/bin/droiddeck-bwrap", "--bind", root, "/", "--dev-bind", "/dev", "/dev", "--proc", "/proc",
"--bind", "/sys", "/sys"]
for d in HOST_DIRS:
if os.path.isdir(d):
bwrap += ["--bind", d, d]
bwrap += ["--bind", "/", "/var/lib/snapd/hostfs"]
bwrap += ["--bind", "/dev/null", "/etc/ld.so.preload"]
binds = content_binds(name, meta, env)
for _, source, target in binds:
if os.path.isdir(source):
bwrap += ["--bind", source, target]
content = {k for k, v in (meta.get("plugs") or {}).items() if isinstance(v, dict) and v.get("interface") == "content"}
plugs = (set(meta.get("plugs") or {}) | set(spec.get("plugs") or [])) - content | {plug for plug, _, _ in binds}
env["DROIDDECK_SNAP_PLUGS"] = " ".join(sorted(plugs))
bwrap += ["--bind", "/usr/local/bin/droiddeck-snapctl", "/usr/lib/snapd/snapctl"]
bwrap += ["--chdir", os.getcwd() if os.path.isdir(os.getcwd()) else env["HOME"], "--clearenv"]
for k, v in env.items():
bwrap += ["--setenv", k, v]
os.execv(bwrap[0], bwrap + ["--"] + program)
if __name__ == "__main__":
sys.exit(main(sys.argv))
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
case $1 in
is-connected)
shift
while [ $# -gt 1 ]; do shift; done
case " $DROIDDECK_SNAP_PLUGS " in
*" ${1:-} "*) exit 0 ;;
esac
exit 1
;;
esac
exit 0
+542
View File
@@ -0,0 +1,542 @@
#!/usr/bin/python3
import datetime
import hashlib
import http.server
import json
import os
import re
import shutil
import socketserver
import subprocess
import sys
import threading
import urllib.parse
import urllib.request
STORE = "https://api.snapcraft.io/v2"
ARCH = "arm64"
SNAP_DIR = "/snap"
BIN_DIR = "/snap/bin"
LIB = "/var/lib/snapd"
STATE = LIB + "/droiddeck-state.json"
DESKTOP_DIR = LIB + "/desktop/applications"
SOCKETS = ("/run/snapd.socket", "/run/snapd-snap.socket")
FIND_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
"media,categories,store-url,download,type,channel,common-ids,links")
INFO_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
"media,categories,snap-id,store-url,download,type,channel-map,common-ids,links,created-at")
HEADERS = {"Snap-Device-Series": "16", "Snap-Device-Architecture": ARCH, "User-Agent": "snapd/2.70 droiddeck"}
lock = threading.RLock()
install_lock = threading.Lock()
changes = {}
change_seq = [0]
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def load_state():
try:
with open(STATE) as f:
return json.load(f)
except (OSError, ValueError):
return {"snaps": {}}
def save_state(state):
tmp = STATE + ".tmp"
with open(tmp, "w") as f:
json.dump(state, f, indent=1)
os.replace(tmp, STATE)
def store_get(path, params=None):
url = STORE + path + ("?" + urllib.parse.urlencode(params) if params else "")
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
def publisher(p):
p = p or {}
return {"id": p.get("id", ""), "username": p.get("username", ""), "display-name": p.get("display-name", ""),
"validation": p.get("validation", "unproven")}
def media_of(snap):
out = []
for m in snap.get("media") or []:
if m.get("type") in ("icon", "screenshot", "banner") and m.get("url"):
item = {"type": m["type"], "url": m["url"]}
if m.get("width"):
item["width"] = m["width"]
item["height"] = m.get("height", 0)
out.append(item)
return out
def icon_of(media):
return next((m["url"] for m in media if m["type"] == "icon"), "")
def from_store(name, snap, revision=None, channel=None):
media = media_of(snap)
rev = revision or snap.get("revision") or {}
out = {
"id": snap.get("snap-id", ""), "name": name, "title": snap.get("title") or name,
"summary": snap.get("summary", ""), "description": snap.get("description", ""),
"type": rev.get("type") or snap.get("type") or "app", "version": rev.get("version", ""),
"revision": str(rev.get("revision", "")), "channel": channel or "stable",
"confinement": rev.get("confinement") or "strict", "base": rev.get("base") or "",
"publisher": publisher(snap.get("publisher")), "developer": (snap.get("publisher") or {}).get("username", ""),
"license": snap.get("license", ""), "contact": snap.get("contact", ""), "website": snap.get("website", ""),
"media": media, "icon": icon_of(media), "store-url": snap.get("store-url", ""),
"download-size": (rev.get("download") or {}).get("size", 0), "status": "available",
"categories": [{"name": c.get("name", ""), "featured": bool(c.get("featured"))} for c in snap.get("categories") or []],
"common-ids": rev.get("common-ids") or snap.get("common-ids") or [],
"private": False, "devmode": False, "jailmode": False, "trymode": False, "apps": [],
}
return out
def installed_snap(name, entry):
snap = dict(entry["info"])
snap["status"] = "active"
snap["install-date"] = entry.get("installed", now())
snap["installed-size"] = entry.get("size", 0)
snap["revision"] = str(entry["revision"])
snap["version"] = entry.get("version", snap.get("version", ""))
snap["tracking-channel"] = entry.get("channel", "latest/stable")
snap["channel"] = entry.get("channel", "latest/stable")
snap["mounted-from"] = f"{LIB}/snaps/{name}_{entry['revision']}.snap"
snap["apps"] = [{"name": a, "snap": name, "desktop-file": f"{DESKTOP_DIR}/{name}_{a}.desktop"} for a in entry.get("apps", [])]
return snap
def find(query, section=None, name_exact=False):
if name_exact:
try:
info = store_get(f"/snaps/info/{query}", {"architecture": ARCH, "fields": INFO_FIELDS})
except Exception:
return []
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
and c["channel"]["risk"] == "stable"), None)
if not rev:
return []
return [from_store(info["name"], dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, "stable")]
params = {"architecture": ARCH, "fields": FIND_FIELDS}
if query:
params["q"] = query
if section:
params["category"] = section
if not query and not section:
params["featured"] = "true"
result = store_get("/snaps/find", params)
out = []
state = load_state()
for r in result.get("results", []):
snap = from_store(r["name"], dict(r.get("snap", {}), **{"snap-id": r.get("snap-id", "")}), r.get("revision"))
if r["name"] in state["snaps"]:
snap["status"] = "active"
snap["installed-size"] = state["snaps"][r["name"]].get("size", 0)
out.append(snap)
return out
def new_change(kind, summary, snaps):
with lock:
change_seq[0] += 1
cid = str(change_seq[0])
changes[cid] = {"id": cid, "kind": kind, "summary": summary, "status": "Doing", "ready": False,
"spawn-time": now(), "tasks": [{"id": cid + "-1", "kind": kind, "summary": summary, "status": "Doing",
"progress": {"label": "", "done": 0, "total": 1},
"spawn-time": now()}],
"data": {"snap-names": snaps}}
return cid
def progress(cid, label, done, total):
with lock:
task = changes[cid]["tasks"][0]
task["progress"] = {"label": label, "done": done, "total": max(total, 1)}
task["summary"] = changes[cid]["summary"]
def finish(cid, err=None):
with lock:
c = changes[cid]
c["status"] = "Error" if err else "Done"
c["ready"] = True
c["ready-time"] = now()
c["tasks"][0]["status"] = c["status"]
if err:
c["err"] = err
def root_run(argv):
if os.getuid() == 0:
return subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
return subprocess.run(["/usr/local/bin/droiddeck-root"] + argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
def snap_yaml(path):
try:
import yaml
with open(path) as f:
return yaml.safe_load(f) or {}
except Exception:
return {}
def download(cid, name, url, sha3, size, target):
tmp = target + ".partial"
h = hashlib.sha3_384()
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=120) as r, open(tmp, "wb") as out:
done = 0
while True:
chunk = r.read(1 << 20)
if not chunk:
break
out.write(chunk)
h.update(chunk)
done += len(chunk)
progress(cid, f"Download snap \"{name}\"", done, size)
if sha3 and h.hexdigest() != sha3:
os.unlink(tmp)
raise RuntimeError(f"{name}: downloaded snap does not match the store's sha3-384")
os.replace(tmp, target)
def write_desktop(name, rev, meta):
os.makedirs(DESKTOP_DIR, exist_ok=True)
gui = f"{SNAP_DIR}/{name}/{rev}/meta/gui"
apps = (meta.get("apps") or {})
for app, spec in apps.items():
source = os.path.join(gui, f"{app}.desktop")
if (spec or {}).get("daemon") or not os.path.isfile(source):
continue
command = name if app == name else f"{name}.{app}"
out = []
with open(source, encoding="utf-8", errors="replace") as f:
for line in f:
if line.startswith("Exec="):
args = line[5:].strip().split(" ", 1)
rest = (" " + args[1]) if len(args) > 1 else ""
line = f"Exec={BIN_DIR}/{command}{rest}\n"
elif line.startswith("Icon="):
line = "Icon=" + line[5:].replace("${SNAP}", f"{SNAP_DIR}/{name}/current")
out.append(line)
out.append(f"X-SnapInstanceName={name}\n")
target = f"{DESKTOP_DIR}/{name}_{app}.desktop"
with open(target + ".tmp", "w", encoding="utf-8") as f:
f.writelines(out)
os.replace(target + ".tmp", target)
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def link_bins(name, meta):
os.makedirs(BIN_DIR, exist_ok=True)
apps = []
for app, spec in (meta.get("apps") or {}).items():
if (spec or {}).get("daemon"):
continue
command = name if app == name else f"{name}.{app}"
path = os.path.join(BIN_DIR, command)
with open(path + ".tmp", "w") as f:
f.write(f"#!/bin/sh\nexec /usr/local/bin/droiddeck-snap-run {name} {app} \"$@\"\n")
os.chmod(path + ".tmp", 0o755)
os.replace(path + ".tmp", path)
apps.append(app)
return apps
def remove_tree(top):
if os.path.isdir(top) and not os.path.islink(top):
os.chmod(top, 0o700)
for root, dirs, _ in os.walk(top):
for d in dirs:
path = os.path.join(root, d)
if not os.path.islink(path):
os.chmod(path, 0o700)
shutil.rmtree(top, ignore_errors=True)
def install_one(cid, name, channel, state, parents=()):
if name in state["snaps"] or name in parents:
return
info = store_get(f"/snaps/info/{name}", {"architecture": ARCH, "fields": INFO_FIELDS})
risk = channel.split("/")[-1] if channel else "stable"
track = channel.split("/")[0] if channel and "/" in channel else "latest"
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
and c["channel"]["risk"] == risk and c["channel"]["track"] == track), None)
if not rev:
raise RuntimeError(f"snap \"{name}\" has no {track}/{risk} release for {ARCH}")
number = rev["revision"]
os.makedirs(f"{LIB}/snaps", exist_ok=True)
blob = f"{LIB}/snaps/{name}_{number}.snap"
d = rev.get("download") or {}
with lock:
changes[cid]["summary"] = f"Install \"{name}\" snap"
download(cid, name, d["url"], d.get("sha3-384"), d.get("size", 0), blob)
progress(cid, f"Unpack snap \"{name}\"", 0, 1)
target = f"{SNAP_DIR}/{name}/{number}"
remove_tree(target)
os.makedirs(os.path.dirname(target), exist_ok=True)
r = root_run(["unsquashfs", "-q", "-n", "-no-xattrs", "-f", "-excludes", "-d", target, blob, "dev"])
if r.returncode != 0:
raise RuntimeError(f"cannot unpack {name}: {r.stdout.strip()[-400:]}")
os.makedirs(f"{target}/dev", exist_ok=True)
current = f"{SNAP_DIR}/{name}/current"
if os.path.islink(current):
os.unlink(current)
os.symlink(str(number), current)
for sub in (f"/var/snap/{name}/{number}", f"/var/snap/{name}/common"):
os.makedirs(sub, exist_ok=True)
cur = f"/var/snap/{name}/current"
if os.path.islink(cur):
os.unlink(cur)
os.symlink(str(number), cur)
meta = snap_yaml(f"{target}/meta/snap.yaml")
entry = {"revision": number, "version": rev.get("version", ""), "channel": f"{track}/{risk}",
"installed": now(), "size": d.get("size", 0), "info": from_store(name, dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, f"{track}/{risk}"),
"base": meta.get("base") or ("core" if (meta.get("type") or "app") == "app" else ""), "apps": []}
base = meta.get("base")
if (meta.get("type") or "app") == "app":
install_one(cid, base or "core", "latest/stable", state, parents + (name,))
for plug in (meta.get("plugs") or {}).values():
if isinstance(plug, dict) and plug.get("interface") == "content" and plug.get("default-provider"):
provider = plug["default-provider"].split(":")[0]
install_one(cid, provider, "latest/stable", state, parents + (name,))
entry["apps"] = link_bins(name, meta)
write_desktop(name, number, meta)
state["snaps"][name] = entry
save_state(state)
def remove_one(name, state):
entry = state["snaps"].pop(name, None)
if not entry:
raise RuntimeError(f"snap \"{name}\" is not installed")
for app in entry.get("apps", []):
command = name if app == name else f"{name}.{app}"
try:
os.unlink(os.path.join(BIN_DIR, command))
except OSError:
pass
if os.path.isdir(DESKTOP_DIR):
for f in os.listdir(DESKTOP_DIR):
if f.startswith(name + "_") and f.endswith(".desktop"):
os.unlink(os.path.join(DESKTOP_DIR, f))
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
remove_tree(f"{SNAP_DIR}/{name}")
for f in os.listdir(f"{LIB}/snaps"):
if f.startswith(name + "_"):
os.unlink(os.path.join(f"{LIB}/snaps", f))
save_state(state)
def run_change(cid, action, names, channel):
with install_lock:
apply_change(cid, action, names, channel)
def apply_change(cid, action, names, channel):
try:
state = load_state()
for name in names:
if action == "install":
install_one(cid, name, channel or "latest/stable", state)
elif action == "remove":
remove_one(name, state)
elif action == "refresh":
old = state["snaps"].get(name)
if old:
remove_one(name, state)
install_one(cid, name, old.get("channel", "latest/stable"), state)
else:
raise RuntimeError(f"unsupported action {action}")
finish(cid)
except Exception as e:
finish(cid, str(e))
SECTIONS = ["featured", "art-and-design", "books-and-reference", "development", "devices-and-iot", "education",
"entertainment", "finance", "games", "health-and-fitness", "music-and-audio", "news-and-weather",
"personalisation", "photo-and-video", "productivity", "science", "security", "server-and-cloud",
"social", "utilities"]
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
pass
def address_string(self):
return "snapd"
def reply(self, body, code=200, kind="sync"):
payload = {"type": kind, "status-code": code, "status": http.client.responses.get(code, "")}
payload.update(body)
data = json.dumps(payload).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def ok(self, result):
self.reply({"result": result})
def error(self, code, message, kind=""):
self.reply({"result": {"message": message, "kind": kind}}, code, "error")
def body(self):
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b"{}"
try:
return json.loads(raw or b"{}")
except ValueError:
return {}
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
q = urllib.parse.parse_qs(url.query)
path = url.path
try:
if path == "/v2/system-info":
return self.ok({"series": "16", "version": "2.70+droiddeck", "build-id": "droiddeck", "os-release": {"id": "ubuntu", "version-id": "26.04"},
"on-classic": True, "managed": False, "kernel-version": os.uname().release,
"locations": {"snap-mount-dir": SNAP_DIR, "snap-bin-dir": BIN_DIR},
"refresh": {"timer": "00:00~24:00/4"}, "confinement": "partial",
"sandbox-features": {}, "architecture": ARCH})
if path == "/v2/snaps":
state = load_state()
wanted = (q.get("snaps", [""])[0] or "").split(",")
snaps = [installed_snap(n, e) for n, e in state["snaps"].items() if not wanted[0] or n in wanted]
return self.ok(snaps)
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
if m:
state = load_state()
if m.group(1) in state["snaps"]:
return self.ok(installed_snap(m.group(1), state["snaps"][m.group(1)]))
return self.error(404, f"snap not installed", "snap-not-found")
if path == "/v2/find":
name = q.get("name", [None])[0]
query = name or q.get("q", [""])[0]
section = q.get("section", [None])[0] or q.get("category", [None])[0]
if section == "featured":
section = None
select = q.get("select", [""])[0]
if select == "refresh":
return self.ok([])
if select == "private":
return self.ok([])
return self.ok(find(query, section, bool(name)))
if path in ("/v2/sections",):
return self.ok(SECTIONS)
if path == "/v2/categories":
return self.ok([{"name": s} for s in SECTIONS if s != "featured"])
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
if m:
with lock:
c = changes.get(m.group(1))
c = json.loads(json.dumps(c)) if c else None
return self.ok(c) if c else self.error(404, "cannot find change", "")
if path == "/v2/changes":
with lock:
return self.ok([json.loads(json.dumps(c)) for c in changes.values()])
m = re.fullmatch(r"/v2/icons/([^/]+)/icon", path)
if m:
return self.icon(m.group(1))
if path == "/v2/apps":
state = load_state()
apps = [{"snap": n, "name": a, "desktop-file": f"{DESKTOP_DIR}/{n}_{a}.desktop"}
for n, e in state["snaps"].items() for a in e.get("apps", [])]
return self.ok(apps)
if path in ("/v2/connections", "/v2/interfaces"):
return self.ok({"established": [], "plugs": [], "slots": []})
if path in ("/v2/aliases", "/v2/users", "/v2/notices", "/v2/assertions/model"):
return self.ok({} if path == "/v2/aliases" else [])
return self.error(404, f"not found: {path}")
except Exception as e:
return self.error(500, str(e))
def icon(self, name):
state = load_state()
entry = state["snaps"].get(name)
if not entry:
return self.error(404, "not installed", "snap-not-found")
for candidate in ("meta/gui/icon.png", "meta/gui/icon.svg"):
path = f"{SNAP_DIR}/{name}/current/{candidate}"
if os.path.isfile(path):
with open(path, "rb") as f:
data = f.read()
self.send_response(200)
self.send_header("Content-Type", "image/svg+xml" if path.endswith("svg") else "image/png")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
return self.error(404, "no icon", "")
def do_POST(self):
path = urllib.parse.urlsplit(self.path).path
body = self.body()
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
if m or path == "/v2/snaps":
names = [m.group(1)] if m else body.get("snaps") or []
action = body.get("action", "")
channel = body.get("channel") or ""
if channel and "/" not in channel:
channel = "latest/" + channel
if action not in ("install", "remove", "refresh"):
return self.error(400, f"unsupported action \"{action}\"")
cid = new_change(f"{action}-snap", f"{action.capitalize()} {', '.join(names)}", names)
threading.Thread(target=run_change, args=(cid, action, names, channel), daemon=True).start()
return self.reply({"change": cid}, 202, "async")
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
if m:
return self.error(400, "changes cannot be aborted")
if path in ("/v2/login", "/v2/logout", "/v2/snapctl"):
return self.error(400, "not supported by DroidDeck's snap service")
return self.error(404, f"not found: {path}")
def do_PUT(self):
return self.do_POST()
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
def get_request(self):
conn, _ = self.socket.accept()
return conn, ("snapd", 0)
def serve(path):
try:
os.unlink(path)
except OSError:
pass
server = Server(path, Handler)
os.chmod(path, 0o666)
server.serve_forever()
def main():
for d in (LIB, SNAP_DIR, BIN_DIR, DESKTOP_DIR, LIB + "/snaps"):
os.makedirs(d, exist_ok=True)
threads = [threading.Thread(target=serve, args=(p,), daemon=True) for p in SOCKETS]
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == "__main__":
sys.exit(main())
@@ -23,15 +23,20 @@ BRIGHTNESS_JS = r"""
if (window.__droiddeckBrightness) return "present";
const display = SteamClient.System?.Display;
if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
const self = { expected: null, updating: true, revision: 0 };
const self = { expected: null, updating: true, revision: 0, localAt: -Infinity };
// A held stick steps Steam faster than Android's readback returns; those stale readbacks would snap the slider back.
const HOLD_MS = 750;
// Returns "held" while a readback is being ignored, so the caller retries it after the hold.
self.set = value => {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return true;
if (performance.now() - self.localAt < HOLD_MS) return "held";
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return true;
self.expected = value;
self.updating = true;
const revision = ++self.revision;
setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500);
display.SetBrightness(value);
return true;
};
self.subscription = display.RegisterForBrightnessChanges(state => {
const value = state?.flBrightness;
@@ -39,6 +44,7 @@ BRIGHTNESS_JS = r"""
if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
if (self.updating) { self.updating = false; return; }
self.expected = value;
self.localAt = performance.now();
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
});
window.__droiddeckBrightness = self;
@@ -764,9 +770,10 @@ class Helper:
if not self.controls_installed:
return
if state != self.controls_state:
if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True:
applied = self.page.evaluate("window.__droiddeckBrightness ? window.__droiddeckBrightness.set(%s) : false" % json.dumps(value))
if applied is True:
self.controls_state = state
else:
elif applied != "held":
self.controls_installed = False
self.controls_state = None
except (OSError, ValueError, TypeError):
@@ -14,6 +14,7 @@ import urllib.parse
import urllib.request
STATE = ".droiddeck-games.json"
TRIED = ".droiddeck-import-tried.json"
WINNATIVE = ".winnative-steam/steamapps"
LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
@@ -179,10 +180,44 @@ def request_restart(steam_root):
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
def ask_restart(names, timeout=600, clock=None, sleep=None):
"""The app asks whether to restart the client now; anything but "now" leaves the import to the next start."""
clock, sleep = clock or time.monotonic, sleep or time.sleep
folder = Path(os.environ.get("HOME", "/root"), ".cache/droiddeck")
ask, answer = folder / "steam-import.json", folder / "steam-import.answer"
token = str(time.time_ns())
answer.unlink(missing_ok=True)
save_json(ask, {"token": token, "games": names})
try:
deadline = clock() + timeout
while clock() < deadline:
reply = read_json(answer, None)
if isinstance(reply, dict) and reply.get("token") == token:
return reply.get("choice") == "now"
sleep(1)
return False
finally:
ask.unlink(missing_ok=True)
answer.unlink(missing_ok=True)
def unimported(steam_root, snapshot, candidates):
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
config = Path(steam_root) / "userdata" / snapshot["account"] / "config"
routes = read_json(config / ".droiddeck-routes.json", {})
routed = set(routes.values()) if isinstance(routes, dict) else set()
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
tried = read_json(config / TRIED, [])
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
owned = {appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True}
if tried - routed != tried:
save_json(config / TRIED, sorted(tried - routed))
return sorted(owned - routed - tried)
def remember_tried(steam_root, account, appids):
config = Path(steam_root) / "userdata" / account / "config"
tried = read_json(config / TRIED, [])
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
save_json(config / TRIED, sorted(tried | set(appids)))
def watch(steam_root, listing):
@@ -193,7 +228,7 @@ def watch(steam_root, listing):
next_lookup = 0
last_status = None
probed, next_probe, failures = None, 0, 0
pending, requested = [], []
pending, requested, account = [], [], None
while True:
now = time.monotonic()
for game in games:
@@ -233,6 +268,7 @@ def watch(steam_root, listing):
snapshot["sources"] = sources
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
pending = unimported(steam_root, snapshot, candidates)
account = snapshot["account"]
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
status = "ownership check unavailable: " + str(error)
@@ -242,9 +278,14 @@ 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("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
names = sorted({game["name"] for game in games if candidates.get(game["folder"]) in pending})
try:
request_restart(steam_root)
remember_tried(steam_root, account, pending)
if ask_restart(names) and not game_running() and downloads_idle(steam_root):
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
request_restart(steam_root)
else:
print("droiddeck-steam-games: %s will be imported the next time the client starts" % pending, flush=True)
except (OSError, subprocess.TimeoutExpired) as error:
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
if status != last_status:
@@ -436,6 +477,7 @@ def route(steam_root, acct, games):
if seed_install(steam_root, game, appid):
routes[str(game["appid"])] = appid
continue
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
@@ -39,6 +39,7 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
exit 69
fi
[ "$url" = steam://exit ] && exit 0
export BL_INSIDE=1 BL_STEAM_UI=desktop
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
fi
@@ -6,6 +6,7 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
for arg in "$@"; do
case $arg in
steam://*) url=$arg ;;
-shutdown) url=steam://exit ;;
-gamepadui|-bigpicture) ui=bigpicture ;;
esac
done
@@ -799,13 +799,25 @@ x64_gpu_watch() {
x64_gpu_probe
}
x64_arm_webhelper_cpu_supported() {
local status=0
# Valve's native ARM web helper contains LSE atomics; missing CPU data cannot establish incompatibility.
awk -F: '
$1 ~ /^[[:space:]]*Features[[:space:]]*$/ {
if ($2 !~ /(^|[[:space:]])atomics([[:space:]]|$)/) unsupported = 1
}
END { exit unsupported ? 1 : 0 }
' /proc/cpuinfo 2>/dev/null || status=$?
[ "$status" != 1 ]
}
x64_exec() {
x64_env
cd "$STEAM_X64"
# The client checksums its files at start and reinstalls over edited ones, so the session shim (preload/net.c)
# swaps the web helper at exec. The arm64 helper only comes up against a client of the same build.
if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] &&
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ]; then
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ] && x64_arm_webhelper_cpu_supported; then
local chan x86_build arm_build
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true)
@@ -1049,4 +1061,4 @@ for attempt in 1 2 3 4 5; do
( x64_exec -clientbeta "$X64_CHANNEL" -no-cef-sandbox "${cef[@]}" "$@" ) >>"$LOG" 2>&1 || rc=$?
step "client exited rc=$rc"
[ "$rc" = 42 ] || break
done
done
@@ -40,6 +40,7 @@ import time
import subprocess
import tempfile
import hashlib
import threading
from pathlib import Path
LAUNCHER = ".droiddeck-launch.bat"
@@ -494,8 +495,27 @@ def gog_registry(folder):
return entries, skipped
def apply_gog_registry(folder, compat_data, proton, timeout=90):
def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=None):
entries, skipped = gog_registry(folder)
if installation:
product = str(installation["id"])
if not product.isdigit():
raise ValueError("Invalid GOG product identifier")
values = {"PATH": windows_path(str(folder))}
identity = Path(folder) / ("goggame-%s.id" % product)
if identity.is_file():
actual = json.loads(identity.read_text(encoding="utf-8-sig")).get("buildId")
if actual and installation.get("build") and str(actual) != str(installation["build"]):
raise ValueError("GOG build metadata changed before patch setup")
if installation.get("build"):
values["BUILDID"] = installation["build"]
if installation.get("version"):
values["VER"] = installation["version"]
for key, value in values.items():
entry = gog_entry({"root": "HKLM", "subkey": "Software\\GOG.com\\Games\\" + product,
"valueName": key, "valueData": value, "valueType": "string"}, {})
if entry:
entries.append(entry)
note = " skipped=%d" % skipped if skipped else ""
if not entries:
return "none" + note
@@ -512,7 +532,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
source = Path(tmp) / "registry.reg"
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
executable = pfx / "drive_c/windows/system32/reg.exe"
run = subprocess.run([proton, "run", str(executable) if executable.is_file() else "reg.exe", "import", windows_path(str(source)), "/reg:32"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
if run.returncode or not (pfx / "system.reg").is_file():
return "import-failed" + note
@@ -525,6 +546,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
if argv and argv[0] == "--exited":
rest, code = argv[1:], 0
if rest[:1] == ["--code"] and len(rest) > 1:
@@ -543,6 +566,18 @@ def main(argv):
return 0
folder, sidecar = found
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
if store == "gog":
helper = Path(__file__).resolve().with_name("droiddeck-gog-maintenance")
if helper.is_file():
child = subprocess.Popen([sys.executable, str(helper), "lease", str(folder), str(os.getppid())],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
start_new_session=True)
ready = child.stdout.readline().decode().strip()
child.stdout.close()
threading.Thread(target=child.wait, daemon=True).start()
if ready != "ready":
log("gog: close or recover the maintenance operation before playing")
return RAN_FAILED
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/python3
import os
import sys
REAL = "/usr/bin/systemd-run"
VALUED = {"-u", "--unit", "-p", "--property", "--description", "--slice", "-E", "--setenv",
"--working-directory", "--uid", "--gid", "--nice", "-H", "--host", "-M", "--machine",
"--on-active", "--on-boot", "--on-startup", "--on-unit-active", "--on-unit-inactive",
"--on-calendar", "--path-property", "--socket-property", "--timer-property", "--service-type",
"--shell", "--slice-inherit"}
def main(argv):
args = argv[1:]
if "--user" not in args:
os.execv(REAL, [REAL] + args)
env = dict(os.environ)
cwd = None
foreground = False
i = 0
while i < len(args):
a = args[i]
if a == "--":
i += 1
break
if not a.startswith("-"):
break
name, _, inline = a.partition("=")
value = inline if inline else (args[i + 1] if name in VALUED and i + 1 < len(args) else "")
if name in ("-E", "--setenv") and "=" in value:
k, _, v = value.partition("=")
env[k] = v
elif name == "--working-directory":
cwd = value
elif name in ("--scope", "--wait", "-W", "--pipe", "-P", "-t", "--pty"):
foreground = True
i += 1 if inline or name not in VALUED else 2
command = args[i:]
if not command:
os.execv(REAL, [REAL] + args)
if cwd:
os.chdir(cwd)
if foreground:
os.execvpe(command[0], command, env)
if os.fork() == 0:
os.setsid()
null = os.open(os.devnull, os.O_RDWR)
os.dup2(null, 0)
try:
os.execvpe(command[0], command, env)
except OSError:
os._exit(127)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
key=$1
shift
line=$(grep -m1 "^$key=" /etc/droiddeck/strings 2>/dev/null)
text=${line#*=}
[ -n "$line" ] || text=$key
printf "$text\n" "$@"
@@ -101,16 +101,18 @@ def registry_values(root):
return good
def expand(store, ids):
def expand(store, ids, saved=None):
"""The picks with everything they bundle, each once, a bundle's parts before it."""
out, seen = [], set()
saved = saved if isinstance(saved, dict) else {}
def visit(cid, depth):
if cid in seen or depth > 8:
return
seen.add(cid)
found = component(store, cid)
for dep in (found[2] if found else []):
parts = found[2] if found else [d for d in saved.get(cid, []) if valid_id(d)]
for dep in parts:
visit(dep, depth + 1)
out.append(cid)
@@ -444,7 +446,7 @@ def list_line(name, current, item, separator, add, at_end=True):
return reg_value_line(name, "expand_sz" if expand else "sz", separator.join(items))
def apply_registry(pfx, values, state):
def apply_registry(pfx, values, state, held=()):
"""Writes the picked components' registry values into the prefix and takes out the ones of
components turned off: a value goes back to what it was before, an entry added to a list such
as PATH just leaves the list. Returns (values written, notes)."""
@@ -478,6 +480,9 @@ def apply_registry(pfx, values, state):
for ident, record in old.items():
if ident in keep or not isinstance(record, dict) or not isinstance(record.get("key"), str):
continue
if record.get("cid") in held:
keep[ident] = record
continue
reg = files.get(record.get("hive"))
if reg is None:
keep[ident] = record
@@ -555,14 +560,44 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
copied = 0
installed = []
values = []
for cid in expand(store, ids):
held = set()
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
owners = set(state["files"].values())
registry_owners = {r.get("cid") for r in (state.get("registry") or {}).values() if isinstance(r, dict)}
inferred = set()
guessed = set(state.get("guessed") or []) if "requires" in state else set(ids)
loose = [c for c in recorded if c not in ids and (c in owners or c in registry_owners)]
for cid in ids:
if cid in guessed and component(store, cid) is None and cid in recorded:
saved_requires = dict(saved_requires, **{cid: loose})
inferred.add(cid)
kept_overrides, kept_requires = {}, {}
for cid in expand(store, ids, saved_requires):
found = component(store, cid)
if found is None:
notes.append("%s is not installed; skipped" % cid)
if cid in saved_requires or cid in recorded or cid in owners or cid in registry_owners:
held.add(cid)
if cid in saved_overrides:
names = [n for n in saved_overrides.get(cid, []) if isinstance(n, str)]
else:
names = sorted({Path(rel).stem.lower() for rel, owner in state["files"].items()
if owner == cid and rel.lower().endswith(".dll")})
overrides += names
kept_overrides[cid] = names
if isinstance(saved_requires.get(cid), list) and cid not in inferred:
kept_requires[cid] = saved_requires[cid]
notes.append("%s is not in the store; kept the files it placed until it is installed again" % cid)
else:
notes.append("%s is not installed; skipped" % cid)
continue
installed.append(cid)
names, files, _, registry = found
names, files, requires, registry = found
overrides += names
kept_overrides[cid] = list(names)
if requires:
kept_requires[cid] = list(requires)
values += [(cid, value) for value in registry]
for rel, src in files:
if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
@@ -572,6 +607,9 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
for rel, cid in state["files"].items():
if rel in keep:
continue
if cid in held:
keep[rel] = cid
continue
path = existing(pfx / rel)
saved = compat / BACKUP / rel
if saved.is_file():
@@ -587,10 +625,13 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
except FileNotFoundError:
pass
compat.mkdir(parents=True, exist_ok=True)
new_state = {"files": keep, "components": installed, "registry": state.get("registry", {})}
new_state = {"files": keep, "components": installed + sorted(held), "overrides": kept_overrides,
"requires": kept_requires, "registry": state.get("registry", {})}
if inferred:
new_state["guessed"] = sorted(inferred)
written = 0
if values or new_state["registry"]:
written, registry_notes = apply_registry(pfx, values, new_state)
written, registry_notes = apply_registry(pfx, values, new_state, held)
notes += registry_notes
save_state(compat, new_state)
if copied or removed or restored or written:
@@ -151,13 +151,13 @@ def view_drive(prefix, exe):
if os.path.lexists(link) and (os.path.exists(link) or not os.readlink(link).startswith(str(view.parent.parent) + '/')):
continue
devices.mkdir(parents=True, exist_ok=True)
staged.symlink_to(view)
staged.symlink_to(view.parent)
os.replace(staged, link)
except OSError:
if os.path.lexists(staged):
staged.unlink()
continue
return letter.upper() + ':\\' + str(path.relative_to(view)).replace('/', '\\'), link
return letter.upper() + ':\\' + str(path.relative_to(view.parent)).replace('/', '\\'), link
return exe, None
@@ -279,6 +279,18 @@ bl_vacdiag() {
}
"""
# Steam's shader pre-caching runs its D3D driver query through every Proton tool at each start, as
# "run <client>/bin/d3ddriverquery64.exe" in compatdata/0. Here it has never succeeded (exit 1 every time), and each
# run started Wine in compatdata/0, where the two Protons upgrade the prefix back and forth for many seconds while the
# game starts. Steam gets the same failure without starting Wine; other verbs and prefixes are left alone.
BL_DRIVER_QUERY_SKIP = """
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
echo "droiddeck-proton: Steam's D3D driver query is not run (it fails here and would start Wine in compatdata/0)" >&2
exit 1 ;;
esac
"""
BL_DIRECTAUDIO_SETUP = """
bl_is_steam_installscript_target() {
local target=${1:-}
@@ -411,7 +423,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
"verb=$1; shift", "verb=$1; shift\n" + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
@@ -458,6 +470,15 @@ bl_store_launch "$@"
BL_STORE_ARGS=("$@")
bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$BL_STORE_PROTON" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
"""
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP
+ BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
{
"compat_tools"
@@ -681,11 +702,7 @@ def adopt_extras(tools):
name = first_key(compat_vdf, ["compatibilitytools", "compat_tools"]) or entry
wrapper = os.path.join(tool_dir, EXTRA_WRAPPER)
try:
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(wrapper, extra_wrapper_sh(entry_point), 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
legacy_wrapper = os.path.join(tool_dir, LEGACY_EXTRA_WRAPPER)
+314
View File
@@ -0,0 +1,314 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#if defined(__aarch64__) || defined(BL_CLOCK_ANY_ARCH)
#ifndef CP_CTL
#define CP_CTL "/tmp/.bl-clock"
#endif
#ifndef FUTEX_LOCK_PI2
#define FUTEX_LOCK_PI2 13
#endif
#define CP_FDS 65536
static const int64_t *cp_shift;
static int cp_state;
static size_t cp_cond_byte;
static unsigned char cp_cond_mask;
static unsigned char cp_fds[CP_FDS / 8];
static int (*cp_gettime)(clockid_t, struct timespec *);
static int (*cp_nanosleep)(clockid_t, int, const struct timespec *, struct timespec *);
static int (*cp_cond_timedwait)(pthread_cond_t *, pthread_mutex_t *, const struct timespec *);
static int (*cp_cond_clockwait)(pthread_cond_t *, pthread_mutex_t *, clockid_t, const struct timespec *);
static int (*cp_sem_clockwait)(sem_t *, clockid_t, const struct timespec *);
static int (*cp_mutex_clocklock)(pthread_mutex_t *, clockid_t, const struct timespec *);
static int (*cp_rdlock)(pthread_rwlock_t *, clockid_t, const struct timespec *);
static int (*cp_wrlock)(pthread_rwlock_t *, clockid_t, const struct timespec *);
static int (*cp_join)(pthread_t, void **, clockid_t, const struct timespec *);
static int (*cp_tfd_create)(int, int);
static int (*cp_tfd_settime)(int, int, const struct itimerspec *, struct itimerspec *);
static void *cp_real(const char *name) {
return dlsym(RTLD_NEXT, name);
}
#define CP_REAL(var, name) (var ? var : (var = cp_real(name)))
static int cp_find_cond_bit(void) {
pthread_condattr_t attr;
pthread_cond_t mono, real;
const unsigned char *a = (const unsigned char *)&mono, *b = (const unsigned char *)&real;
int found = 0;
memset(&mono, 0, sizeof(mono));
memset(&real, 0, sizeof(real));
if (pthread_condattr_init(&attr) != 0) return 0;
if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0 && pthread_cond_init(&mono, &attr) == 0) {
if (pthread_cond_init(&real, NULL) == 0) {
for (size_t i = 0; i < sizeof(pthread_cond_t); i++) {
unsigned char diff = a[i] ^ b[i];
if (!diff) continue;
if (found || (diff & (diff - 1))) {
found = -1;
break;
}
cp_cond_byte = i;
cp_cond_mask = diff;
found = 1;
}
pthread_cond_destroy(&real);
}
pthread_cond_destroy(&mono);
}
pthread_condattr_destroy(&attr);
return found == 1;
}
static void cp_init(void) {
struct stat st;
void *map;
int fd;
if (strcmp(program_invocation_short_name, "plasmashell") != 0) return;
if (!cp_find_cond_bit()) return;
fd = open(CP_CTL, O_RDONLY | O_CLOEXEC);
if (fd < 0) return;
if (fstat(fd, &st) != 0 || st.st_size < (off_t)sizeof(int64_t)) {
close(fd);
return;
}
map = mmap(NULL, sizeof(int64_t), PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (map != MAP_FAILED) __atomic_store_n(&cp_shift, (const int64_t *)map, __ATOMIC_RELEASE);
}
static int64_t cp_offset(void) {
const int64_t *shift;
int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE);
if (state == 0) {
int expected = 0;
if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
cp_init();
__atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE);
}
return 0;
}
if (state != 2) return 0;
shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
if (!shift) return 0;
int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED);
return value > 0 ? value : 0;
}
__attribute__((constructor)) static void cp_start(void) {
cp_offset();
}
static int cp_mono(clockid_t clock) {
return clock == CLOCK_MONOTONIC || clock == CLOCK_MONOTONIC_RAW || clock == CLOCK_MONOTONIC_COARSE;
}
static void cp_move(struct timespec *ts, int64_t ns) {
int64_t total = (int64_t)ts->tv_nsec + ns % 1000000000LL;
ts->tv_sec += (time_t)(ns / 1000000000LL);
while (total < 0) {
total += 1000000000LL;
ts->tv_sec--;
}
while (total >= 1000000000LL) {
total -= 1000000000LL;
ts->tv_sec++;
}
ts->tv_nsec = (long)total;
}
static const struct timespec *cp_later(const struct timespec *ts, struct timespec *out, int64_t shift) {
if (!ts || !shift) return ts;
*out = *ts;
cp_move(out, shift);
return out;
}
static void cp_mark(int fd, int mono) {
if (fd < 0 || fd >= CP_FDS) return;
if (mono) __atomic_or_fetch(&cp_fds[fd / 8], (unsigned char)(1u << (fd % 8)), __ATOMIC_RELAXED);
else __atomic_and_fetch(&cp_fds[fd / 8], (unsigned char)~(1u << (fd % 8)), __ATOMIC_RELAXED);
}
static int cp_marked(int fd) {
return fd >= 0 && fd < CP_FDS && (__atomic_load_n(&cp_fds[fd / 8], __ATOMIC_RELAXED) & (1u << (fd % 8)));
}
static int cp_cond_mono(const pthread_cond_t *cond) {
return (((const volatile unsigned char *)cond)[cp_cond_byte] & cp_cond_mask) != 0;
}
int clock_gettime(clockid_t clock, struct timespec *ts) {
if (!CP_REAL(cp_gettime, "clock_gettime")) {
errno = ENOSYS;
return -1;
}
int rc = cp_gettime(clock, ts);
if (rc == 0 && cp_mono(clock)) {
int64_t shift = cp_offset();
if (shift) cp_move(ts, -shift);
}
return rc;
}
int clock_nanosleep(clockid_t clock, int flags, const struct timespec *req, struct timespec *rem) {
struct timespec moved;
if (!CP_REAL(cp_nanosleep, "clock_nanosleep")) return ENOSYS;
if ((flags & TIMER_ABSTIME) && cp_mono(clock)) req = cp_later(req, &moved, cp_offset());
return cp_nanosleep(clock, flags, req, rem);
}
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_cond_timedwait, "pthread_cond_timedwait")) return ENOSYS;
int64_t shift = cp_offset();
if (shift && cp_cond_mono(cond)) abstime = cp_later(abstime, &moved, shift);
return cp_cond_timedwait(cond, mutex, abstime);
}
int pthread_cond_clockwait(pthread_cond_t *cond, pthread_mutex_t *mutex, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_cond_clockwait, "pthread_cond_clockwait")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_cond_clockwait(cond, mutex, clock, abstime);
}
int sem_clockwait(sem_t *sem, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_sem_clockwait, "sem_clockwait")) {
errno = ENOSYS;
return -1;
}
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_sem_clockwait(sem, clock, abstime);
}
int pthread_mutex_clocklock(pthread_mutex_t *mutex, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_mutex_clocklock, "pthread_mutex_clocklock")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_mutex_clocklock(mutex, clock, abstime);
}
int pthread_rwlock_clockrdlock(pthread_rwlock_t *lock, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_rdlock, "pthread_rwlock_clockrdlock")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_rdlock(lock, clock, abstime);
}
int pthread_rwlock_clockwrlock(pthread_rwlock_t *lock, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_wrlock, "pthread_rwlock_clockwrlock")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_wrlock(lock, clock, abstime);
}
int pthread_clockjoin_np(pthread_t thread, void **result, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_join, "pthread_clockjoin_np")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_join(thread, result, clock, abstime);
}
int timerfd_create(int clock, int flags) {
if (!CP_REAL(cp_tfd_create, "timerfd_create")) {
errno = ENOSYS;
return -1;
}
int fd = cp_tfd_create(clock, flags);
cp_mark(fd, cp_mono(clock));
return fd;
}
static const struct itimerspec *cp_timer(int fd, int flags, const struct itimerspec *value, struct itimerspec *out) {
int64_t shift;
if (!value || !(flags & TFD_TIMER_ABSTIME) || !cp_marked(fd)) return value;
if ((value->it_value.tv_sec == 0 && value->it_value.tv_nsec == 0) || !(shift = cp_offset())) return value;
*out = *value;
cp_move(&out->it_value, shift);
return out;
}
int timerfd_settime(int fd, int flags, const struct itimerspec *value, struct itimerspec *old) {
struct itimerspec moved;
if (!CP_REAL(cp_tfd_settime, "timerfd_settime")) {
errno = ENOSYS;
return -1;
}
return cp_tfd_settime(fd, flags, cp_timer(fd, flags, value, &moved), old);
}
__attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) {
struct timespec moved;
struct itimerspec timer;
int64_t shift;
if (number == SYS_clock_gettime) {
*ret = real(number, args[0], args[1]);
if (*ret == 0 && args[1] && cp_mono((clockid_t)args[0]) && (shift = cp_offset()))
cp_move((struct timespec *)args[1], -shift);
return 1;
}
if (number == SYS_timerfd_create) {
*ret = real(number, args[0], args[1]);
cp_mark((int)*ret, cp_mono((clockid_t)args[0]));
return 1;
}
if (number == SYS_timerfd_settime) {
const struct itimerspec *value = cp_timer((int)args[0], (int)args[1], (const struct itimerspec *)args[2], &timer);
if (value == (const struct itimerspec *)args[2]) return 0;
*ret = real(number, args[0], args[1], (long)value, args[3]);
return 1;
}
if (number == SYS_clock_nanosleep) {
if (!((int)args[1] & TIMER_ABSTIME) || !cp_mono((clockid_t)args[0]) || !args[2] || !(shift = cp_offset())) return 0;
*ret = real(number, args[0], args[1], (long)cp_later((const struct timespec *)args[2], &moved, shift), args[3]);
return 1;
}
if (number == SYS_futex) {
int op = (int)args[1];
int cmd = op & FUTEX_CMD_MASK;
if (op & FUTEX_CLOCK_REALTIME) return 0;
if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI && cmd != FUTEX_LOCK_PI2) return 0;
if (!args[3] || !(shift = cp_offset())) return 0;
*ret = real(number, args[0], args[1], args[2], (long)cp_later((const struct timespec *)args[3], &moved, shift), args[4], args[5]);
return 1;
}
#ifdef SYS_futex_waitv
if (number == SYS_futex_waitv) {
if (!args[3] || (clockid_t)args[4] != CLOCK_MONOTONIC || !(shift = cp_offset())) return 0;
*ret = real(number, args[0], args[1], args[2], (long)cp_later((const struct timespec *)args[3], &moved, shift), args[4]);
return 1;
}
#endif
return 0;
}
#else
__attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) {
(void)number;
(void)args;
(void)real;
(void)ret;
return 0;
}
#endif
+41
View File
@@ -0,0 +1,41 @@
#define _GNU_SOURCE
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <unistd.h>
#define FUSE_MAGIC 0x65735546
#define SDCARDFS_MAGIC 0x5dca2df5
static int is_wineserver(void) {
static int cached = -1;
char exe[PATH_MAX];
const char *base;
ssize_t n;
if (cached >= 0) return cached;
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (n <= 0) {
cached = 0;
return cached;
}
exe[n] = '\0';
base = strrchr(exe, '/');
cached = strcmp(base ? base + 1 : exe, "wineserver") == 0;
return cached;
}
__attribute__((visibility("hidden")))
void bl_storage_owner(int fd, struct stat *st) {
struct statfs fs;
int saved = errno;
uid_t uid;
if (st != NULL && is_wineserver()) {
uid = getuid();
if (st->st_uid != uid && fstatfs(fd, &fs) == 0 && (fs.f_type == FUSE_MAGIC || fs.f_type == SDCARDFS_MAGIC)) st->st_uid = uid;
}
errno = saved;
}
+21 -2
View File
@@ -139,17 +139,31 @@ static int (*next_faccessat(void))(int, const char *, int, int) {
}
__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode);
__attribute__((visibility("hidden"))) int bl_writable_access(int dirfd, const char *path, int mode, int flags);
static int writable_as_owner(int (*real)(int, const char *, int, int), int dirfd, const char *path, int mode, int flags) {
if (!bl_writable_access(dirfd, path, mode, flags)) return -1;
if ((mode & ~W_OK) == 0 || real(dirfd, path, mode & ~W_OK, flags) == 0) return 0;
return -1;
}
static int check_cwd(const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int) = next_faccessat();
int result;
int err;
if (real == NULL) {
errno = ENOSYS;
return -1;
}
result = real(AT_FDCWD, path, mode, flags);
return result != 0 && errno == EACCES && bl_binfmt_runnable(path, mode) ? 0 : result;
if (result == 0) return 0;
err = errno;
if (err == EACCES && bl_binfmt_runnable(path, mode)) return 0;
errno = err;
if (writable_as_owner(real, AT_FDCWD, path, mode, flags) == 0) return 0;
errno = err;
return result;
}
int access(const char *path, int mode) {
@@ -166,6 +180,7 @@ int eaccess(const char *path, int mode) {
int faccessat(int dirfd, const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int);
int err;
if (dirfd == AT_FDCWD) {
return cached_access(path, mode, flags, check_cwd);
@@ -175,5 +190,9 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
errno = ENOSYS;
return -1;
}
return real(dirfd, path, mode, flags);
if (real(dirfd, path, mode, flags) == 0) return 0;
err = errno;
if (writable_as_owner(real, dirfd, path, mode, flags) == 0) return 0;
errno = err;
return -1;
}
+42 -1
View File
@@ -3,6 +3,7 @@
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -23,6 +24,34 @@ static int is_steam_client(void) {
return cached;
}
static int wine_name(const char *path) {
const char *base;
size_t n;
if (path == NULL) return 0;
base = strrchr(path, '/');
base = base ? base + 1 : path;
n = strlen(path);
return strncmp(base, "wine", 4) == 0 || strstr(path, "/lib/wine/") != NULL
|| (n > 4 && strcasecmp(path + n - 4, ".exe") == 0);
}
static int is_wine(void) {
static int cached = -1;
char exe[PATH_MAX];
ssize_t n;
if (cached >= 0) return cached;
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (n > 0) exe[n] = '\0';
cached = (n > 0 && wine_name(exe)) || wine_name(program_invocation_name);
return cached;
}
static int acts_as_root(void) {
return is_steam_client() || !is_wine();
}
static int grant_owner_write(int dirfd, const char *path) {
struct stat st;
@@ -37,7 +66,7 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
char parent[PATH_MAX];
const char *slash;
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !is_steam_client()) return 0;
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !acts_as_root()) return 0;
if (faccessat(dirfd, path, F_OK, 0) == 0) {
granted = grant_owner_write(dirfd, path);
} else if (flags & O_CREAT) {
@@ -53,3 +82,15 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
errno = saved;
return granted;
}
__attribute__((visibility("hidden")))
int bl_writable_access(int dirfd, const char *path, int mode, int flags) {
int saved = errno;
struct stat st;
int owned;
if (saved != EACCES || path == NULL || !(mode & W_OK) || !acts_as_root()) return 0;
owned = fstatat(dirfd, path, &st, flags & AT_SYMLINK_NOFOLLOW) == 0 && st.st_uid == geteuid();
errno = saved;
return owned;
}
+43 -8
View File
@@ -49,6 +49,7 @@ static int openat2_missing;
static int (*next_fstatat)(int, const char *, bl_stat *, int);
static int (*next_openat)(int, const char *, int, ...);
static ssize_t (*next_readlinkat)(int, const char *, char *, size_t);
static int (*next_statx)(int, const char *, int, unsigned int, struct statx *);
static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) {
(void)size;
@@ -68,6 +69,7 @@ __attribute__((constructor)) static void find_fastpath_calls(void) {
next_fstatat = (int (*)(int, const char *, bl_stat *, int))dlsym(fastpath, BL_FSTATAT_NAME);
next_openat = (int (*)(int, const char *, int, ...))dlsym(fastpath, "openat");
next_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(fastpath, "readlinkat");
next_statx = (int (*)(int, const char *, int, unsigned int, struct statx *))dlsym(fastpath, "statx");
}
}
@@ -92,6 +94,13 @@ static long path_readlink(int dirfd, const char *path, char *buf, size_t size) {
return next_readlinkat(dirfd, path, buf, size);
}
static long path_statx(int dirfd, const char *path, int flags, unsigned int mask, struct statx *out) {
if (!next_statx) {
return real_syscall(SYS_statx, (long)dirfd, (long)path, (long)flags, (long)mask, (long)out);
}
return next_statx(dirfd, path, flags, mask, out);
}
void *dlopen(const char *filename, int flags) {
if (!real_dlopen) {
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
@@ -329,7 +338,28 @@ static int execveat_is_execve(const long *args) {
return path[0] == '/' || (int)args[0] == AT_FDCWD;
}
static long openat2_call(const long *args) {
if (!real_syscall) {
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
}
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
long fd = real_syscall(SYS_openat2, 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);
}
int bl_openat2(int dirfd, const char *path, void *how, size_t size) __asm__("openat2");
int bl_openat2(int dirfd, const char *path, void *how, size_t size) {
long args[6] = {dirfd, (long)path, (long)how, (long)size, 0, 0};
return (int)openat2_call(args);
}
int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden")));
int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) __attribute__((visibility("hidden")));
long syscall(long number, ...) {
va_list ap;
@@ -356,22 +386,27 @@ long syscall(long number, ...) {
if (!real_syscall) {
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
}
if (bl_clock_syscall(number, args, real_syscall, &handled)) {
return handled;
}
if (bl_writewatch_syscall(number, args, real_syscall, &handled)) {
return handled;
}
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);
return openat2_call(args);
}
if (number == SYS_openat) {
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
}
if (number == BL_SYS_FSTATAT) {
return path_stat((int)args[0], (const char *)args[1], (bl_stat *)args[2], (int)args[3]);
}
if (number == SYS_readlinkat) {
return path_readlink((int)args[0], (const char *)args[1], (char *)args[2], (size_t)args[3]);
}
if (number == SYS_statx) {
return path_statx((int)args[0], (const char *)args[1], (int)args[2], (unsigned int)args[3], (struct statx *)args[4]);
}
if (number == SYS_execveat && execveat_is_execve(args)) {
return real_syscall(SYS_execve, args[1], args[2], args[3]);
}
+7 -1
View File
@@ -13,6 +13,7 @@
#include <unistd.h>
static int (*next_fstat)(int, struct stat *);
void bl_storage_owner(int fd, struct stat *st) __attribute__((visibility("hidden")));
static int (*next_fallocate)(int, int, off_t, off_t);
static int (*next_posix_fallocate)(int, off_t, off_t);
static ssize_t (*next_pwrite)(int, const void *, size_t, off_t);
@@ -285,12 +286,17 @@ int fstat(int fd, struct stat *out) {
if (next_fstat == NULL) { errno = ENOSYS; return -1; }
initialize();
errno = entry_errno;
if (!enabled) return next_fstat(fd, out);
if (!enabled) {
int result = next_fstat(fd, out);
if (result == 0) bl_storage_owner(fd, out);
return result;
}
uint64_t start = now_ns();
errno = entry_errno;
int result = next_fstat(fd, out);
int call_errno = errno;
uint64_t elapsed = now_ns() - start;
if (result == 0) bl_storage_owner(fd, out);
if (result == 0 && on_selected_device(fd, out)) {
add(&stats.fstat_calls, 1);
add(&stats.fstat_elapsed_ns, elapsed);
+24 -1
View File
@@ -1,6 +1,7 @@
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifndef WEBHELPER_DEFAULT
#define WEBHELPER_DEFAULT "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
@@ -25,8 +26,30 @@ static char *join_features(const char *have, const char *add) {
return strcat(out, add);
}
static char *const *chromium_argv(const char *path, char *const argv[]) {
const char *slash = path ? strrchr(path, '/') : NULL;
if (!slash || !argv || !argv[0]) return argv;
int argc = 0;
for (; argv[argc]; argc++)
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
size_t dir = (size_t)(slash - path) + 1;
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
if (!sandbox) return argv;
memcpy(sandbox, path, dir);
strcpy(sandbox + dir, "chrome-sandbox");
int chromium = access(sandbox, F_OK) == 0;
free(sandbox);
if (!chromium) return argv;
char **out = calloc((size_t)argc + 2, sizeof *out);
if (!out) return argv;
out[0] = argv[0];
out[1] = (char *)"--no-sandbox";
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
return out;
}
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]) {
if (!is_webhelper_browser(path, argv)) return argv;
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
const char *spec = getenv("BL_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;