mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Merge branch 'main' into fix/epic-gta5-error-window-hidden
This commit is contained in:
529 files changed
+31005
-5917
No files matched your search
@@ -1,26 +1,34 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
out=${1:?usage: build-x86-preloads.sh <linuxfs asset directory>}
|
||||
tools() {
|
||||
prefix=
|
||||
if [ "${X86_CROSS:-}" = 1 ]; then
|
||||
case $1 in i386) prefix=i686-linux-gnu- ;; *) prefix=x86_64-linux-gnu- ;; esac
|
||||
fi
|
||||
GCC=${prefix}gcc GXX=${prefix}g++ STRIP=${prefix}strip OBJDUMP=${prefix}objdump NM=${prefix}nm
|
||||
}
|
||||
for arch in x86_64 i386; do
|
||||
tools $arch
|
||||
case $arch in
|
||||
x86_64) bits=-m64 ;;
|
||||
i386) bits=-m32 ;;
|
||||
esac
|
||||
mkdir -p "$out/$arch"
|
||||
gcc $bits -shared -fPIC -O2 -Wall -pthread \
|
||||
$GCC $bits -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$out/$arch/libddsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
$GXX $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
|
||||
-o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||
strip --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"
|
||||
$STRIP --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"
|
||||
for lib in "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"; do
|
||||
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
|
||||
newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
|
||||
minor=${newest#GLIBC_2.}
|
||||
if [ "$minor" -gt 31 ]; then
|
||||
echo "$lib needs $newest; Steam Linux Runtime 3.0 has glibc 2.31" >&2
|
||||
exit 1
|
||||
fi
|
||||
if objdump -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
|
||||
if $OBJDUMP -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
|
||||
echo "$lib links the C++ runtime dynamically" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -28,37 +36,39 @@ for arch in x86_64 i386; do
|
||||
done
|
||||
for target in x86_64/faultreport i386/faultreport; do
|
||||
arch=${target%/*} name=${target#*/}
|
||||
tools $arch
|
||||
case $arch in
|
||||
x86_64) bits=-m64 ;;
|
||||
i386) bits=-m32 ;;
|
||||
esac
|
||||
lib=$out/$arch/lib$name.so
|
||||
gcc $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
|
||||
$GCC $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
|
||||
-o "$lib" tools/linuxfs/fex/$name.c
|
||||
strip --strip-unneeded "$lib"
|
||||
if objdump -p "$lib" | grep -q NEEDED || [ -n "$(nm -D --undefined-only "$lib" 2>/dev/null)" ]; then
|
||||
$STRIP --strip-unneeded "$lib"
|
||||
if $OBJDUMP -p "$lib" | grep -q NEEDED || [ -n "$($NM -D --undefined-only "$lib" 2>/dev/null)" ]; then
|
||||
echo "$lib must not need any library" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
tools x86_64
|
||||
lib=$out/x86_64/libwebkitinput.so
|
||||
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
|
||||
$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_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
|
||||
$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_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
|
||||
stub=$(mktemp -d)
|
||||
gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
|
||||
$GCC -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
|
||||
lib=$out/x86_64/libvulkan-thunk.so
|
||||
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
|
||||
$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
|
||||
-o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl
|
||||
rm -rf "$stub"
|
||||
strip --strip-unneeded "$lib"
|
||||
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
|
||||
if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|
||||
|| ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
|
||||
$STRIP --strip-unneeded "$lib"
|
||||
newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
|
||||
if ! $OBJDUMP -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|
||||
|| ! $OBJDUMP -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
|
||||
echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -24,7 +24,7 @@ if [ -n "${DD_DEBUG_DIR:-}" ]; then
|
||||
exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1
|
||||
echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}"
|
||||
fi
|
||||
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null
|
||||
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' ! -name 'droiddeck-display-buffers' -exec rm -rf {} + 2>/dev/null
|
||||
chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null
|
||||
export DD_DESKTOP=1
|
||||
@@ -115,6 +115,12 @@ fi
|
||||
if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
|
||||
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND
|
||||
export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
|
||||
# On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn
|
||||
# frames; its software renderer draws correctly.
|
||||
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0
|
||||
# The system driver's (PowerVR, Xclipse) libhybris Wayland swapchain needs the app compositor's Android-buffer
|
||||
# protocol, which KWin lacks: Plasma's clients present through DRI instead.
|
||||
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export LIBGL_KOPPER_DISABLE=true
|
||||
if [ -z "${KWIN_RENDER_NODES:-}" ]; then
|
||||
for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do
|
||||
if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
SYSTEM_DIR = "/usr/share/applications"
|
||||
@@ -10,8 +9,6 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
|
||||
USER_DIR = os.path.join(HOME, ".local/share/applications")
|
||||
MARK = "X-DroidDeck-GPU=1"
|
||||
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
|
||||
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
|
||||
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
|
||||
|
||||
|
||||
def enabled():
|
||||
@@ -27,33 +24,6 @@ def main_group(text):
|
||||
return lines[:start + 1], lines[start + 1:end], lines[end:]
|
||||
|
||||
|
||||
def split_program(exec_line):
|
||||
if exec_line.startswith('"'):
|
||||
end = exec_line.find('"', 1)
|
||||
if end < 0:
|
||||
return None, None
|
||||
return exec_line[:end + 1], exec_line[end + 1:]
|
||||
program, _, rest = exec_line.partition(" ")
|
||||
return program, (" " + rest) if rest else ""
|
||||
|
||||
|
||||
def chromium(exec_line):
|
||||
program, _ = split_program(exec_line)
|
||||
if not program:
|
||||
return False
|
||||
program = program.strip('"')
|
||||
path = program if os.path.isabs(program) else shutil.which(program)
|
||||
if not path:
|
||||
return False
|
||||
here = os.path.dirname(os.path.realpath(path))
|
||||
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
|
||||
|
||||
|
||||
def chromium_exec(exec_line):
|
||||
program, rest = split_program(exec_line)
|
||||
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
|
||||
|
||||
|
||||
def gpu_exec(exec_line):
|
||||
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
|
||||
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
|
||||
@@ -75,24 +45,8 @@ def wrap(text, gpu_on=True):
|
||||
if not exec_line or exec_line.startswith("droiddeck-gpu "):
|
||||
return None
|
||||
cats = set(filter(None, keys.get("Categories", "").split(";")))
|
||||
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
|
||||
browser = chromium(exec_line)
|
||||
if not gpu and not browser:
|
||||
if not (gpu_on and cats & {"Game", "Emulator"}):
|
||||
return None
|
||||
if browser:
|
||||
exec_line = chromium_exec(exec_line)
|
||||
if not gpu:
|
||||
def fix(lines):
|
||||
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
|
||||
for l in lines]
|
||||
out_group = fix(group)
|
||||
while out_group and not out_group[-1].strip():
|
||||
out_group.pop()
|
||||
out_group.append(MARK)
|
||||
out_rest = fix(rest)
|
||||
if out_rest and out_rest[0].strip():
|
||||
out_rest.insert(0, "")
|
||||
return "\n".join(head + out_group + out_rest) + "\n"
|
||||
out_group = []
|
||||
actions = keys.get("Actions", "")
|
||||
for l in group:
|
||||
@@ -111,8 +65,7 @@ def wrap(text, gpu_on=True):
|
||||
wrapped_rest = []
|
||||
for l in rest:
|
||||
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
|
||||
action = l[5:].strip()
|
||||
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
|
||||
l = "Exec=" + gpu_exec(l[5:].strip())
|
||||
wrapped_rest.append(l)
|
||||
if wrapped_rest and wrapped_rest[0].strip():
|
||||
wrapped_rest.insert(0, "")
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
Parts of the DwarFS project are licensed under the MIT license, while others are
|
||||
licensed under the GPL-3.0 license. In general, the code used to *read* DwarFS
|
||||
images is licensed under the MIT license, while the code used to *write* DwarFS
|
||||
images is licensed under the GPL-3.0 license. Also, all testing/benchmarking
|
||||
code is currently licensed under the GPL-3.0 license.
|
||||
|
||||
That means you can use `mkdwarfs` to create images and then use these images
|
||||
with only the MIT-licensed code.
|
||||
|
||||
The following libraries and associated header files are licensed under the
|
||||
MIT license:
|
||||
|
||||
- `dwarfs_common`
|
||||
- `dwarfs_compressor`
|
||||
- `dwarfs_decompressor`
|
||||
- `dwarfs_extractor`
|
||||
- `dwarfs_reader`
|
||||
|
||||
The following libraries and associated header files are licensed under the
|
||||
GPL-3.0 license:
|
||||
|
||||
- `dwarfs_rewrite`
|
||||
- `dwarfs_writer`
|
||||
|
||||
Each header and source file should contain an SPDX identifier near the top
|
||||
of the file.
|
||||
|
||||
Please also check the licenses of the projects that DwarFS depends on.
|
||||
|
||||
----
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) Marcus Holland-Moritz
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
||||
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread):
|
||||
|
||||
class WebSocket:
|
||||
|
||||
def __init__(self, url, timeout):
|
||||
def __init__(self, url, timeout, bounded=False):
|
||||
target = urllib.parse.urlsplit(url)
|
||||
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
|
||||
or target.username is not None or target.password is not None or target.fragment):
|
||||
@@ -442,6 +442,7 @@ class WebSocket:
|
||||
if target.query:
|
||||
path += "?" + target.query
|
||||
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
|
||||
self.deadline = time.monotonic() + timeout if bounded else None
|
||||
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
|
||||
try:
|
||||
self._handshake(path, hostport)
|
||||
@@ -457,6 +458,7 @@ class WebSocket:
|
||||
).encode())
|
||||
head = b""
|
||||
while b"\r\n\r\n" not in head:
|
||||
self._wait()
|
||||
chunk = self.s.recv(4096)
|
||||
if not chunk:
|
||||
raise OSError("DevTools closed the connection during the handshake")
|
||||
@@ -468,8 +470,17 @@ class WebSocket:
|
||||
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
|
||||
self.buffer = head.split(b"\r\n\r\n", 1)[1]
|
||||
|
||||
def _wait(self):
|
||||
if self.deadline is None:
|
||||
return
|
||||
left = self.deadline - time.monotonic()
|
||||
if left <= 0:
|
||||
raise socket.timeout("DevTools did not answer in time")
|
||||
self.s.settimeout(left)
|
||||
|
||||
def _read(self, n):
|
||||
while len(self.buffer) < n:
|
||||
self._wait()
|
||||
chunk = self.s.recv(65536)
|
||||
if not chunk:
|
||||
raise OSError("DevTools closed the connection")
|
||||
@@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5):
|
||||
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
|
||||
|
||||
|
||||
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
|
||||
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
|
||||
want = target or "SharedJSContext"
|
||||
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
||||
if not match:
|
||||
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
|
||||
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
|
||||
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
|
||||
INSPECTOR_URL = re.compile(r"ws://127\.0\.0\.1:([0-9]{4,5})/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
|
||||
|
||||
def inspector_url(url):
|
||||
found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None
|
||||
if not found or not 1024 <= int(found.group(1)) <= 65535:
|
||||
raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id")
|
||||
return url
|
||||
|
||||
|
||||
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
|
||||
command_line_api=False):
|
||||
if inspector is not None:
|
||||
url, name = inspector_url(inspector), "inspector"
|
||||
else:
|
||||
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
|
||||
want = target or "SharedJSContext"
|
||||
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
||||
if not match:
|
||||
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
|
||||
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
|
||||
url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title")
|
||||
try:
|
||||
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
|
||||
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
|
||||
"userGesture": True,
|
||||
}}))
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
message = json.loads(ws.recv())
|
||||
ws = WebSocket(url, timeout, bounded=True)
|
||||
except socket.timeout:
|
||||
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
|
||||
except OSError as e:
|
||||
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e)
|
||||
try:
|
||||
try:
|
||||
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
|
||||
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
|
||||
"userGesture": True, "includeCommandLineAPI": command_line_api,
|
||||
}}))
|
||||
except socket.timeout:
|
||||
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
|
||||
except OSError as e:
|
||||
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
|
||||
while True:
|
||||
try:
|
||||
message = json.loads(ws.recv())
|
||||
except socket.timeout:
|
||||
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
|
||||
except OSError as e:
|
||||
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
|
||||
if message.get("id") != 1:
|
||||
continue
|
||||
if "error" in message:
|
||||
@@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
|
||||
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
|
||||
raise AgentError("JS_EXCEPTION", text)
|
||||
value = result.get("result", {})
|
||||
return {"target": match[0].get("title"), "type": value.get("type"),
|
||||
return {"target": name, "type": value.get("type"),
|
||||
"value": value.get("value"), "description": value.get("description")}
|
||||
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
@@ -1157,7 +1196,7 @@ def handle(agent_dir, req):
|
||||
if not isinstance(expression, str) or not expression:
|
||||
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
|
||||
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
|
||||
request_timeout(req, 15))
|
||||
request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True)
|
||||
if kind == "steam-selection":
|
||||
return steam_selection(agent_dir, request_timeout(req, 5))
|
||||
if kind == "quit":
|
||||
@@ -1167,6 +1206,15 @@ def handle(agent_dir, req):
|
||||
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
|
||||
|
||||
|
||||
def reply(agent_dir, req):
|
||||
try:
|
||||
return dict(handle(agent_dir, req), ok=True)
|
||||
except AgentError as e:
|
||||
return {"ok": False, "error": {"code": e.code, "message": str(e)}}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
|
||||
|
||||
|
||||
def answer(agent_dir, path):
|
||||
rid = path.stem
|
||||
try:
|
||||
@@ -1186,12 +1234,7 @@ def answer(agent_dir, path):
|
||||
except OSError:
|
||||
pass
|
||||
if req is not None:
|
||||
try:
|
||||
result = dict(handle(agent_dir, req), ok=True)
|
||||
except AgentError as e:
|
||||
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
|
||||
except Exception as e:
|
||||
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
|
||||
result = reply(agent_dir, req)
|
||||
write_json(agent_dir / "resp" / (rid + ".json"), result)
|
||||
|
||||
|
||||
@@ -1218,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1):
|
||||
|
||||
|
||||
def main(argv):
|
||||
if argv and argv[0] == "--cdp-inspector":
|
||||
if len(argv) != 4:
|
||||
print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr)
|
||||
return 2
|
||||
print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2],
|
||||
"expression": argv[3], "commandLineApi": True})))
|
||||
return 0
|
||||
base = os.environ.get("DD_LAUNCH_DIR")
|
||||
if not base:
|
||||
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
|
||||
|
||||
@@ -9,6 +9,40 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;;
|
||||
esac
|
||||
fi
|
||||
if [ -n "${DDNATV_ROOT:-}" ]; then
|
||||
image=$(realpath -- "$image") || exit 127
|
||||
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
|
||||
mkdir -p "$cache" || exit 1
|
||||
exec 9>"$cache/.lock"
|
||||
flock 9 || exit 1
|
||||
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
|
||||
for dir in "$cache"/*/; do
|
||||
dir=${dir%/}
|
||||
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
|
||||
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
|
||||
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
|
||||
done
|
||||
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
|
||||
source=$(state "$image")
|
||||
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
|
||||
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
|
||||
echo "== appimage: unpacking $image"
|
||||
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
|
||||
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
|
||||
rm -rf -- "${work:?}"
|
||||
echo "droiddeck-appimage-exec: could not unpack $image" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$source" > "$work/source"
|
||||
rm -rf -- "${unpacked:?}"
|
||||
mv -- "$work" "$unpacked" || exit 1
|
||||
fi
|
||||
exec 8<"$unpacked/source"
|
||||
flock -s 8 || exit 1
|
||||
exec 9>&-
|
||||
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
|
||||
exec "$APPDIR/AppRun" "$@"
|
||||
fi
|
||||
if [ -x /usr/local/lib/droiddeck/uruntime ]; then
|
||||
export TARGET_APPIMAGE=$image
|
||||
exec /usr/local/lib/droiddeck/uruntime "$@"
|
||||
|
||||
@@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
|
||||
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
|
||||
export QT_QPA_PLATFORM=xcb
|
||||
fi
|
||||
arch=$(cat "$dir/arch" 2>/dev/null)
|
||||
if [ "$arch" = arm64 ]; then
|
||||
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
|
||||
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
|
||||
while IFS= read -r lib; do
|
||||
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
|
||||
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
|
||||
done
|
||||
fi
|
||||
fex=$(cat "$dir/fex" 2>/dev/null)
|
||||
case $fex in on|off) ;; *) fex=auto ;; esac
|
||||
run=("$APPDIR/AppRun")
|
||||
if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
case $fex:$(cat "$dir/arch" 2>/dev/null) in
|
||||
case $fex:$arch in
|
||||
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
|
||||
auto:arm64) ;;
|
||||
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
|
||||
|
||||
@@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask"
|
||||
WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00))
|
||||
CLIENT_AREA_ANIMATION = (4, 0x02)
|
||||
WALLPAPER_MAX = (1280, 720)
|
||||
FEX_REQUEST = "battlenet-fex.request"
|
||||
FEX_RESULT = "battlenet-fex.result"
|
||||
FEX_WAIT = 120
|
||||
START_GRACE = 90
|
||||
POLL = 2
|
||||
STOP_WAIT = 5
|
||||
@@ -82,8 +79,7 @@ AGENT_START = 90
|
||||
AGENT_HELPER = "agent.js"
|
||||
AGENT_RUNTIME = "agent-runtime"
|
||||
AGENT_LOG = "agent.log"
|
||||
AGENT_LOG_LIMIT = 4 << 20
|
||||
HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"]
|
||||
HEADLESS = "/usr/local/bin/droiddeck-headless"
|
||||
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
|
||||
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
|
||||
COUNTRY = re.compile(r"[A-Z]{3}")
|
||||
@@ -779,32 +775,6 @@ def write_menu(path=MENU):
|
||||
say("menu entry not written: %s" % error)
|
||||
|
||||
|
||||
def ask_fex(launch_dir, wait=FEX_WAIT):
|
||||
if not launch_dir or not os.path.isdir(launch_dir):
|
||||
say("not inside a DroidDeck session; FEX stays as Components has it")
|
||||
return None
|
||||
result = os.path.join(launch_dir, FEX_RESULT)
|
||||
request = os.path.join(launch_dir, FEX_REQUEST)
|
||||
try:
|
||||
os.unlink(result)
|
||||
except OSError:
|
||||
pass
|
||||
with open(request + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write("appid=%s\n" % APP_ID)
|
||||
os.replace(request + ".tmp", request)
|
||||
deadline = time.monotonic() + wait
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with open(result, encoding="utf-8") as f:
|
||||
answer = f.read().strip()
|
||||
except OSError:
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
os.unlink(result)
|
||||
return answer
|
||||
return None
|
||||
|
||||
|
||||
def wine_processes(pfx, proc="/proc"):
|
||||
want = os.path.realpath(pfx).rstrip("/")
|
||||
found = []
|
||||
@@ -1148,8 +1118,6 @@ def stop_leftovers(pfx):
|
||||
def open_client(root, reinstall=False):
|
||||
pfx = os.path.join(prefix(root), "pfx")
|
||||
write_menu()
|
||||
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
|
||||
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
|
||||
if running(pfx):
|
||||
say("Battle.net is already running in its prefix; waiting for it to close")
|
||||
wait_while_open(pfx, grace=0)
|
||||
@@ -1238,8 +1206,6 @@ def launch(root, code):
|
||||
try:
|
||||
own = None
|
||||
if lock is not None and not running(pfx):
|
||||
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
|
||||
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
|
||||
verb = None if stop_leftovers(pfx) else "run"
|
||||
configure(root, LIBRARY)
|
||||
own = start(launcher(root), verb)
|
||||
@@ -1449,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
|
||||
windows = install_path(root, folder)
|
||||
emit("STATE", "starting")
|
||||
base = os.path.join(CACHE, "agent-%s" % uid)
|
||||
os.makedirs(CACHE, exist_ok=True)
|
||||
for suffix in (".json", ".game", ".form", ".error"):
|
||||
try:
|
||||
os.unlink(base + suffix)
|
||||
except OSError:
|
||||
pass
|
||||
runtime = os.path.join(CACHE, AGENT_RUNTIME)
|
||||
os.makedirs(runtime, mode=0o700, exist_ok=True)
|
||||
env = agent_env()
|
||||
for name in ("DISPLAY", "WAYLAND_DISPLAY"):
|
||||
env.pop(name, None)
|
||||
env["XDG_RUNTIME_DIR"] = runtime
|
||||
cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
|
||||
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
|
||||
cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--",
|
||||
os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
|
||||
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
|
||||
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
|
||||
output = os.path.join(CACHE, AGENT_LOG)
|
||||
try:
|
||||
if os.path.getsize(output) > AGENT_LOG_LIMIT:
|
||||
os.replace(output, output + ".1")
|
||||
except OSError:
|
||||
pass
|
||||
before = {pid for pid, _ in wine_processes(pfx)}
|
||||
with open(output, "ab") as log:
|
||||
try:
|
||||
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
|
||||
except OSError as error:
|
||||
emit("ERROR", "stopped gamescope: %s" % error)
|
||||
return 1
|
||||
try:
|
||||
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
|
||||
except OSError as error:
|
||||
emit("ERROR", "stopped gamescope: %s" % error)
|
||||
return 1
|
||||
seen = None
|
||||
mark = None
|
||||
moved = time.monotonic()
|
||||
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#!/bin/bash
|
||||
set -u
|
||||
umask 077
|
||||
self=${BASH_SOURCE[0]}
|
||||
proc=${DD_PROC:-/proc}
|
||||
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
|
||||
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
|
||||
headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless}
|
||||
wait_s=${DD_CURSEFORGE_WAIT:-60}
|
||||
cmd=${1:-}
|
||||
dir=${2:-}
|
||||
flag=--inspect-publish-uid=stderr
|
||||
case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac
|
||||
if [ ! -d "$dir/app" ]; then
|
||||
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
running() {
|
||||
local p
|
||||
for p in "$proc"/[0-9]*; do
|
||||
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
started_at() {
|
||||
local stat
|
||||
stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
|
||||
stat=${stat##*) }
|
||||
set -- $stat
|
||||
echo "${20}"
|
||||
}
|
||||
|
||||
tracked() {
|
||||
local pid at launched
|
||||
read -r pid at launched 2>/dev/null < "$state/pid" || return 1
|
||||
case $pid in ''|*[!0-9]*) return 1 ;; esac
|
||||
kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1
|
||||
printf '%s %s\n' "$pid" "$launched"
|
||||
}
|
||||
|
||||
ours() {
|
||||
local pid launched
|
||||
read -r pid launched <<<"$(tracked)"
|
||||
[ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid"
|
||||
}
|
||||
|
||||
lock() {
|
||||
mkdir -p "$state" && chmod 700 "$state" || return 1
|
||||
exec 9>"$state/lock" || return 1
|
||||
flock 9
|
||||
}
|
||||
|
||||
inspector() {
|
||||
grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null
|
||||
}
|
||||
|
||||
start() {
|
||||
local url pid child=
|
||||
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
|
||||
if ! ours >/dev/null; then
|
||||
if tracked >/dev/null || running; then
|
||||
exec 9>&-
|
||||
echo busy
|
||||
return 3
|
||||
fi
|
||||
mv -f "$state/log" "$state/log.1" 2>/dev/null
|
||||
env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \
|
||||
"$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- &
|
||||
pid=$!
|
||||
child=$pid
|
||||
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
|
||||
fi
|
||||
exec 9>&-
|
||||
for _ in $(seq 1 $((wait_s * 2))); do
|
||||
if url=$(inspector); then
|
||||
echo "$url"
|
||||
hold "$child"
|
||||
return 0
|
||||
fi
|
||||
ours >/dev/null || break
|
||||
sleep 0.5
|
||||
done
|
||||
tail -n 20 "$state/log" >&2
|
||||
return 5
|
||||
}
|
||||
|
||||
hold() {
|
||||
local pid
|
||||
if [ -n "$1" ]; then
|
||||
wait "$1"
|
||||
return 0
|
||||
fi
|
||||
pid=$(ours) || return 0
|
||||
while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
stop() {
|
||||
local pid p
|
||||
lock || return 1
|
||||
pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; }
|
||||
kill -TERM -- "-$pid" 2>/dev/null
|
||||
for _ in $(seq 1 20); do
|
||||
kill -0 -- "-$pid" 2>/dev/null || break
|
||||
sleep 0.5
|
||||
done
|
||||
kill -KILL -- "-$pid" 2>/dev/null
|
||||
kill -KILL "$pid" 2>/dev/null
|
||||
for p in "$proc"/[0-9]*; do
|
||||
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
|
||||
done
|
||||
rm -f "$state/pid"
|
||||
exec 9>&-
|
||||
return 0
|
||||
}
|
||||
|
||||
case $cmd in
|
||||
start)
|
||||
start
|
||||
exit $?
|
||||
;;
|
||||
stop)
|
||||
stop
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
@@ -27,6 +27,7 @@ GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment.
|
||||
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PRELOADS = "/usr/local/lib/droiddeck-fex"
|
||||
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
|
||||
DWARFSEXTRACT = "/usr/local/lib/droiddeck/dwarfsextract"
|
||||
HOST_PRELOAD = "/etc/ld.so.preload"
|
||||
FEX_APPID = "3127680"
|
||||
OWN_FEX = "/usr/local"
|
||||
@@ -51,7 +52,7 @@ PROVIDED = frozenset((
|
||||
"libssl.so.3", "libcrypto.so.3",
|
||||
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
|
||||
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
|
||||
))
|
||||
PROVIDED_NEEDS = {
|
||||
"libwayland-client.so.0": ("libffi.so.8",),
|
||||
@@ -670,6 +671,8 @@ def guest_environment(fex, env):
|
||||
result.setdefault("FEX_SILENTLOG", "0")
|
||||
result.setdefault("FEX_OUTPUTLOG", "stderr")
|
||||
result.pop("GLIBC_TUNABLES", None)
|
||||
if "aarch64" in result.get("GCONV_PATH", ""):
|
||||
result["GCONV_PATH"] = ""
|
||||
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
|
||||
if fex["portable"]:
|
||||
result["FEX_PORTABLE"] = "1"
|
||||
@@ -822,6 +825,30 @@ def extracted():
|
||||
return os.path.isdir("squashfs-root")
|
||||
|
||||
|
||||
def dwarfs_image(image):
|
||||
try:
|
||||
offset = appimage_offset(image)
|
||||
with open(image, "rb") as f:
|
||||
f.seek(offset)
|
||||
return f.read(6) == b"DWARFS"
|
||||
except (OSError, ValueError, struct.error):
|
||||
return False
|
||||
|
||||
|
||||
def dwarfs_extract(image):
|
||||
clear_extracted()
|
||||
os.mkdir("squashfs-root")
|
||||
with open(image, "rb") as source:
|
||||
status = subprocess.call([DWARFSEXTRACT, "--input", "/proc/self/fd/%d" % source.fileno(),
|
||||
"--image-offset=%d" % appimage_offset(image), "--output", "squashfs-root",
|
||||
"--log-level=error"], stdout=subprocess.DEVNULL, pass_fds=(source.fileno(),))
|
||||
if status == 0 and extracted():
|
||||
return True
|
||||
say("dwarfsextract could not extract it (status %d)" % status)
|
||||
clear_extracted()
|
||||
return False
|
||||
|
||||
|
||||
def want_fex():
|
||||
with locked():
|
||||
update_own_fex()
|
||||
@@ -849,8 +876,12 @@ def extract(image):
|
||||
clear_extracted()
|
||||
x86 = elf_arch(image) in X86.values()
|
||||
if os.access(URUNTIME, os.X_OK):
|
||||
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||
env=dict(os.environ, TARGET_APPIMAGE=image))
|
||||
with open(image, "rb") as source:
|
||||
native = bool(os.environ.get("DDNATV_ROOT"))
|
||||
target = "/proc/self/fd/%d" % source.fileno() if native else image
|
||||
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||
env=dict(os.environ, TARGET_APPIMAGE=target),
|
||||
pass_fds=(source.fileno(),) if native else ())
|
||||
errors = run.stderr.decode("utf-8", "replace")
|
||||
sys.stderr.write(errors)
|
||||
status = run.returncode
|
||||
@@ -863,6 +894,10 @@ def extract(image):
|
||||
return 0
|
||||
say("uruntime could not extract it (status %d)" % status)
|
||||
clear_extracted()
|
||||
if os.access(DWARFSEXTRACT, os.X_OK) and dwarfs_image(image) and dwarfs_extract(image):
|
||||
if x86:
|
||||
want_fex()
|
||||
return 0
|
||||
fex = prepare() if x86 else None
|
||||
if fex is not None:
|
||||
status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL,
|
||||
@@ -880,7 +915,17 @@ def extract(image):
|
||||
want_fex()
|
||||
return 0
|
||||
say("unsquashfs could not extract it (status %d)" % status)
|
||||
elif fex is None:
|
||||
seven = shutil.which("7z")
|
||||
if seven:
|
||||
clear_extracted()
|
||||
status = subprocess.call([seven, "x", "-tSquashFS", "-y", "-osquashfs-root", image], stdout=subprocess.DEVNULL)
|
||||
if status == 0 and extracted():
|
||||
if x86:
|
||||
want_fex()
|
||||
return 0
|
||||
say("7-Zip could not extract it (status %d)" % status)
|
||||
clear_extracted()
|
||||
elif fex is None and not unsquashfs:
|
||||
say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs")
|
||||
return 1
|
||||
|
||||
|
||||
@@ -152,12 +152,24 @@ def deep_rock_gdk_raytracing(game):
|
||||
return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)"
|
||||
|
||||
|
||||
@fix
|
||||
def dragons_dogma_2_wine_detection(game):
|
||||
if game.app_id == "2054970" and not any(a.lower().startswith("/winedetectionenabled:") for a in game.args):
|
||||
return {}, ["/WineDetectionEnabled:False"], "Dragon's Dogma 2: the game's Wine detection off (its Wine path does not start)"
|
||||
|
||||
|
||||
@fix
|
||||
def ff7_rebirth_feature_level(game):
|
||||
if game.stem in ("ff7rebirth", "ff7rebirth_"):
|
||||
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)"
|
||||
|
||||
|
||||
@fix
|
||||
def hades2_feature_level(game):
|
||||
if game.stem == "hades2":
|
||||
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Hades II: D3D12 feature level 12_2 (on Adreno 6xx/7xx it finds no D3D12 adapter at the detected level)"
|
||||
|
||||
|
||||
@fix
|
||||
def kcd2_feature_level(game):
|
||||
if game.app_id == "1771300":
|
||||
@@ -230,6 +242,57 @@ def skip_red_launcher(command):
|
||||
return command
|
||||
|
||||
|
||||
DQM4_MESH_DETAIL = {"r.SkeletalMeshLODBias": "-4", "r.SkeletalMeshLODRadiusScale": "0.25"}
|
||||
|
||||
|
||||
def with_system_settings(text, settings):
|
||||
lines = text.splitlines()
|
||||
try:
|
||||
section = lines.index("[SystemSettings]")
|
||||
except ValueError:
|
||||
if lines and lines[-1].strip():
|
||||
lines.append("")
|
||||
lines.append("[SystemSettings]")
|
||||
section = len(lines) - 1
|
||||
end = next((i for i in range(section + 1, len(lines)) if lines[i].startswith("[")), len(lines))
|
||||
block = [line for line in lines[section + 1:end] if line.split("=", 1)[0].strip() not in settings]
|
||||
while block and not block[-1].strip():
|
||||
block.pop()
|
||||
block += ["%s=%s" % item for item in settings.items()]
|
||||
tail = lines[end:]
|
||||
return "\n".join(lines[:section + 1] + block + ([""] if tail else []) + tail) + "\n"
|
||||
|
||||
|
||||
# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch.
|
||||
def dragon_quest_monsters_4_mesh_detail(exe, env):
|
||||
project = Path(exe).stem.split("-", 1)[0]
|
||||
if not project.lower().startswith("dragonquestmonsters4"):
|
||||
return
|
||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||
config = prefix / "drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini"
|
||||
try:
|
||||
if not prefix.is_dir():
|
||||
return
|
||||
text = config.read_text(encoding="utf-8") if config.exists() else ""
|
||||
updated = with_system_settings(text, DQM4_MESH_DETAIL)
|
||||
if updated == text:
|
||||
return
|
||||
config.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle, staged = tempfile.mkstemp(prefix=".engine-", dir=config.parent)
|
||||
try:
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as target:
|
||||
target.write(updated)
|
||||
if config.exists():
|
||||
os.chmod(staged, config.stat().st_mode & 0o7777)
|
||||
os.replace(staged, config)
|
||||
except BaseException:
|
||||
os.unlink(staged)
|
||||
raise
|
||||
print("droiddeck-game-env: Dragon Quest Monsters 4: full-detail monster meshes", file=sys.stderr)
|
||||
except (OSError, UnicodeDecodeError) as error:
|
||||
print("droiddeck-game-env: Dragon Quest Monsters 4 mesh detail left as is (%s)" % error, file=sys.stderr)
|
||||
|
||||
|
||||
UBISOFT_LAUNCHER = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher"
|
||||
UBISOFT_SETTINGS = "drive_c/users/steamuser/AppData/Local/Ubisoft Game Launcher/settings.yaml"
|
||||
|
||||
@@ -1400,6 +1463,7 @@ def main():
|
||||
command = skip_red_launcher(command)
|
||||
if len(command) > 2:
|
||||
death_stranding_allocator(app_id, command[2])
|
||||
dragon_quest_monsters_4_mesh_detail(command[2], effective_env)
|
||||
ubisoft_overlay_off(env)
|
||||
project_zomboid_jvm(command)
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], [])
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
set -u
|
||||
runtime=${1:-}
|
||||
shift
|
||||
log=
|
||||
if [ "${1:-}" = --log ]; then
|
||||
log=${2:-}
|
||||
shift 2
|
||||
fi
|
||||
if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then
|
||||
echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2
|
||||
exit 2
|
||||
fi
|
||||
shift
|
||||
umask 077
|
||||
mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1
|
||||
if [ -n "$log" ]; then
|
||||
size=$(stat -c %s "$log" 2>/dev/null || echo 0)
|
||||
[ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1"
|
||||
exec >>"$log" 2>&1
|
||||
fi
|
||||
unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY
|
||||
export XDG_RUNTIME_DIR=$runtime
|
||||
exec gamescope --backend headless -w 640 -h 480 -- "$@"
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
|
||||
@@ -540,7 +540,7 @@ if [ -z "${DD_INSIDE:-}" ]; then
|
||||
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
|
||||
if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then
|
||||
args+=(-S stretch)
|
||||
export DD_STRETCHED=1
|
||||
export DD_STRETCHED=1 DD_STRETCH_OUTPUT="${width}x${height}" DD_STRETCH_GAME="${nested}x${nested_h}"
|
||||
fi
|
||||
if [ "${DD_REFRESH:-0}" -gt 0 ]; then
|
||||
args+=(-r "$DD_REFRESH")
|
||||
@@ -593,6 +593,12 @@ dd_xprop_set_all() {
|
||||
done
|
||||
[ "$ok" = 1 ]
|
||||
}
|
||||
dd_stretch_game_screen() {
|
||||
local idx w h super
|
||||
IFS=', ' read -r idx w h super <<<"$1"
|
||||
[ "$idx" = 1 ] && [ "${w}x${h}" = "$2" ] && [ "${super:-0}" = 0 ] || return 1
|
||||
xprop -root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL "$idx, ${3%x*}, ${3#*x}, 1" 2>/dev/null
|
||||
}
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
reap_orphans() {
|
||||
local round p stat pid left
|
||||
@@ -1205,7 +1211,7 @@ case $mode in
|
||||
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
|
||||
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
|
||||
atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP)
|
||||
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER)
|
||||
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER GAMESCOPE_XWAYLAND_MODE_CONTROL)
|
||||
prop_value() {
|
||||
case $1 in *'not found'*|*=) pv=$2; return ;; esac
|
||||
pv=${1#*=}
|
||||
@@ -1273,6 +1279,11 @@ case $mode in
|
||||
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
|
||||
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
|
||||
;;
|
||||
GAMESCOPE_XWAYLAND_MODE_CONTROL*)
|
||||
prop_value "$line" ""
|
||||
dd_stretch_game_screen "$pv" "$DD_STRETCH_OUTPUT" "$DD_STRETCH_GAME" \
|
||||
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
|
||||
;;
|
||||
esac
|
||||
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
) &
|
||||
@@ -1417,11 +1428,10 @@ case $mode in
|
||||
export STEAM_STEAMRT_RECURSION_GUARD=1
|
||||
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
|
||||
export SDL_VIDEO_X11_DGAMOUSE=0
|
||||
dd_steam_path=$PATH
|
||||
dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
|
||||
dd_steam_angle=vulkan
|
||||
dd_steam_presentation=()
|
||||
if [ "${DD_STEAM_GL_PRESENT:-}" = 1 ]; then
|
||||
dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
|
||||
export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true
|
||||
dd_steam_angle=gl
|
||||
dd_steam_presentation=(-cef-disable-gpu-compositing)
|
||||
|
||||
@@ -66,19 +66,32 @@ BRIGHTNESS_JS = r"""
|
||||
""".replace("__BINDING__", BRIGHTNESS_BINDING)
|
||||
|
||||
|
||||
def control_request(name, text, directory):
|
||||
path = os.path.join(directory, name)
|
||||
with open(path + ".tmp", "w") as target:
|
||||
target.write(text + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
|
||||
|
||||
def brightness_request(payload, directory=CONTROLS_DIR):
|
||||
try:
|
||||
value = float(payload)
|
||||
if not math.isfinite(value) or not 0 <= value <= 1:
|
||||
return
|
||||
path = os.path.join(directory, "brightness.request")
|
||||
with open(path + ".tmp", "w") as target:
|
||||
target.write(str(value) + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
control_request("brightness.request", str(value), directory)
|
||||
except (ValueError, TypeError, OSError):
|
||||
return
|
||||
|
||||
|
||||
def hdr_request(payload, directory=CONTROLS_DIR):
|
||||
if payload not in ("0", "1"):
|
||||
return
|
||||
try:
|
||||
control_request("hdr.request", payload, directory)
|
||||
except OSError:
|
||||
return
|
||||
|
||||
|
||||
INSTALL_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckCompat) return "present";
|
||||
@@ -256,6 +269,49 @@ TOUR_JS = r"""
|
||||
return "off";
|
||||
})()
|
||||
"""
|
||||
SET_SETTING_JS = r"""(field, value) => {
|
||||
const bytes = [];
|
||||
for (let n of [field * 8, value]) {
|
||||
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
|
||||
bytes.push(n);
|
||||
}
|
||||
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
|
||||
}"""
|
||||
HDR_BINDING = "droiddeckHdrChanged"
|
||||
HDR_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckHdr) return "present";
|
||||
const settings = window.settingsStore;
|
||||
if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" ||
|
||||
typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
|
||||
const write = __SET_SETTING__;
|
||||
const HOLD_MS = 3000;
|
||||
const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 };
|
||||
self.set = value => {
|
||||
if (typeof value !== "boolean") return true;
|
||||
self.known = value;
|
||||
if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true;
|
||||
self.pending = value;
|
||||
self.until = performance.now() + HOLD_MS;
|
||||
write(21015, value ? 1 : 0);
|
||||
return true;
|
||||
};
|
||||
self.check = () => {
|
||||
const value = settings.clientSettings.gamescope_hdr_enabled;
|
||||
if (typeof value !== "boolean") return;
|
||||
if (self.pending !== null) {
|
||||
if (value !== self.pending && performance.now() < self.until) return;
|
||||
self.pending = null;
|
||||
}
|
||||
if (value === self.known) return;
|
||||
self.known = value;
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0");
|
||||
};
|
||||
self.interval = setInterval(self.check, 500);
|
||||
window.__droiddeckHdr = self;
|
||||
return "installed";
|
||||
})()
|
||||
""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS)
|
||||
FRAME_LIMIT_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckFrameLimit) return "present";
|
||||
@@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r"""
|
||||
}
|
||||
if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
|
||||
const self = { timer: null };
|
||||
const write = value => {
|
||||
const bytes = [];
|
||||
for (let n of [21002 * 8, value]) {
|
||||
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
|
||||
bytes.push(n);
|
||||
}
|
||||
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
|
||||
};
|
||||
const write = value => (__SET_SETTING__)(21002, value);
|
||||
self.check = async () => {
|
||||
let rates;
|
||||
try {
|
||||
@@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r"""
|
||||
window.__droiddeckFrameLimit = self;
|
||||
return "installed";
|
||||
})()
|
||||
"""
|
||||
""".replace("__SET_SETTING__", SET_SETTING_JS)
|
||||
WINDOW_BINDING = "droiddeckWindowAction"
|
||||
WINDOW_TARGET = "createflags=18"
|
||||
WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8}
|
||||
@@ -923,6 +972,9 @@ class Helper:
|
||||
self.controls_installed = False
|
||||
self.frame_limit_state = None
|
||||
self.frame_limit_retry = 0
|
||||
self.hdr_state = None
|
||||
self.hdr_installed = False
|
||||
self.hdr_retry = 0
|
||||
self.windows = {}
|
||||
self.windows_retry = 0
|
||||
|
||||
@@ -983,6 +1035,29 @@ class Helper:
|
||||
except (Closed, OSError, ValueError):
|
||||
del self.windows[ident]
|
||||
|
||||
def sync_hdr(self):
|
||||
try:
|
||||
with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
|
||||
value = json.load(source).get("hdr")
|
||||
if not isinstance(value, bool):
|
||||
return
|
||||
if not self.hdr_installed:
|
||||
if time.monotonic() < self.hdr_retry:
|
||||
return
|
||||
self.page.call("Runtime.addBinding", {"name": HDR_BINDING})
|
||||
self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present")
|
||||
if not self.hdr_installed:
|
||||
self.hdr_retry = time.monotonic() + 10
|
||||
return
|
||||
if value != self.hdr_state:
|
||||
if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True:
|
||||
self.hdr_state = value
|
||||
else:
|
||||
self.hdr_state = None
|
||||
self.hdr_installed = False
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
|
||||
def sync_frame_limit(self):
|
||||
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
|
||||
return
|
||||
@@ -1095,6 +1170,9 @@ class Helper:
|
||||
self.controls_installed = False
|
||||
self.frame_limit_state = None
|
||||
self.frame_limit_retry = 0
|
||||
self.hdr_state = None
|
||||
self.hdr_installed = False
|
||||
self.hdr_retry = 0
|
||||
self.sync_controls()
|
||||
return True
|
||||
|
||||
@@ -1231,6 +1309,8 @@ class Helper:
|
||||
for e in events:
|
||||
if called(e, BRIGHTNESS_BINDING):
|
||||
brightness_request(e.get("params", {}).get("payload"))
|
||||
if called(e, HDR_BINDING):
|
||||
hdr_request(e.get("params", {}).get("payload"))
|
||||
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
|
||||
self.open_chooser(e["params"]["payload"])
|
||||
return events
|
||||
@@ -1260,6 +1340,7 @@ class Helper:
|
||||
while True:
|
||||
self.sync_controls()
|
||||
self.sync_frame_limit()
|
||||
self.sync_hdr()
|
||||
self.sync_windows()
|
||||
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
|
||||
sources += [page.ws for page in self.windows.values()]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import ctypes as C
|
||||
import functools
|
||||
import json
|
||||
@@ -71,6 +71,10 @@ def store_game(game):
|
||||
return bool(game.get("store"))
|
||||
|
||||
|
||||
def steam_program(game):
|
||||
return game.get("route") is not False
|
||||
|
||||
|
||||
def manifest_ids(steamapps, name):
|
||||
matches = []
|
||||
try:
|
||||
@@ -230,7 +234,7 @@ def remember_tried(steam_root, account, appids):
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")]
|
||||
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native") and steam_program(game)]
|
||||
if os.environ.get("DD_STEAM_OFFLINE") == "1" or not games:
|
||||
return
|
||||
candidates, sources = {}, {}
|
||||
@@ -526,6 +530,13 @@ def release(steam_root, game, stale, reason):
|
||||
print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}")
|
||||
|
||||
|
||||
def release_stale(steam_root, game, stale):
|
||||
try:
|
||||
release(steam_root, game, stale, "names another Steam app now")
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: earlier import not undone ({error})")
|
||||
|
||||
|
||||
PREFIX_LINKS = ".droiddeck-prefix-links.json"
|
||||
|
||||
|
||||
@@ -603,17 +614,18 @@ def route(steam_root, acct, games):
|
||||
if game.get("native"):
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
if not steam_program(game):
|
||||
release_stale(steam_root, game, lambda old: old == SPACEWAR)
|
||||
share_prefix(steam_root, game)
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
folder = game.get("folder", "")
|
||||
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
|
||||
stamp = source_stamp(game)
|
||||
recorded = sources.get(folder, sources.get(legacy_path(folder)))
|
||||
current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])
|
||||
named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR
|
||||
try:
|
||||
release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid),
|
||||
"names another Steam app now")
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: earlier import not undone ({error})")
|
||||
release_stale(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid))
|
||||
confirmed = named and current and owned.get(str(appid)) is True
|
||||
if confirmed:
|
||||
try:
|
||||
|
||||
@@ -65,12 +65,15 @@ if [ -n "$repair" ]; then
|
||||
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
|
||||
done
|
||||
fi
|
||||
cache_only=
|
||||
applied=
|
||||
[ "${1:-}" = --cache ] && cache_only=1
|
||||
sync=
|
||||
if [ "${1:-}" = --sync ]; then
|
||||
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
|
||||
manifest=steam_client_${sync}_linuxarm64
|
||||
fi
|
||||
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
@@ -130,6 +133,156 @@ fetch() {
|
||||
done
|
||||
}
|
||||
|
||||
# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries:
|
||||
# the shell here cannot open /dev/fd for process substitution from a background job.
|
||||
fetch_one() {
|
||||
local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait
|
||||
while :; do
|
||||
if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then
|
||||
echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0
|
||||
rm -f "$dest"
|
||||
finished=0 bad=$((bad + 1))
|
||||
[ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; }
|
||||
fi
|
||||
before=$(size_of "$dest")
|
||||
http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$?
|
||||
if [ "$rc" = 0 ]; then finished=1; continue; fi
|
||||
case "$rc:${http:-}" in
|
||||
22:416 | 33:*) rm -f "$dest" ;;
|
||||
22:4??)
|
||||
echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi
|
||||
if [ "$failures" -gt "${#delays[@]}" ]; then
|
||||
echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2
|
||||
return 1
|
||||
fi
|
||||
wait=${delays[$((failures > 0 ? failures - 1 : 0))]}
|
||||
step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s"
|
||||
sleep "$wait"
|
||||
done
|
||||
}
|
||||
|
||||
parallel=${DD_STEAM_PARALLEL:-4}
|
||||
case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac
|
||||
flock_command=${DD_STEAM_FLOCK:-flock}
|
||||
command -v "$flock_command" > /dev/null 2>&1 || parallel=1
|
||||
|
||||
# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into
|
||||
# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the
|
||||
# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover.
|
||||
unzip_alone() {
|
||||
local rc
|
||||
( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$?
|
||||
return $rc
|
||||
}
|
||||
|
||||
# Takes the next unclaimed line number from a counter under a flock, and prints 0 when none is left. mkdir was tried for this
|
||||
# and handed the same line to two workers now and then in the app's guest shell, so only the kernel's lock is trusted here.
|
||||
claim_next() {
|
||||
local n
|
||||
while :; do
|
||||
# A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none.
|
||||
n=$( { "$flock_command" 8 || exit 1
|
||||
n=$(cat "$state/next") || exit 1
|
||||
case $n in ''|*[!0-9]*) exit 1 ;; esac
|
||||
echo $((n + 1)) > "$state/next" || exit 1
|
||||
echo "$n"; } 8> "$state/claim.lock" ) || return 1
|
||||
[ "$n" -le "$count" ] || { echo 0; return; }
|
||||
if [ ! -e "$state/$n.done" ]; then
|
||||
: > "$state/claim.$n"
|
||||
echo "$n"
|
||||
return
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third
|
||||
# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a
|
||||
# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves
|
||||
# (claim_next) and only plain background jobs and wait on a pid are used, so nothing depends on job control.
|
||||
run_parallel() {
|
||||
local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size
|
||||
local -a blocks=() files=() sums=() sizes=() pids=()
|
||||
state=$work/parallel
|
||||
rm -rf "$state"
|
||||
mkdir -p "$state"
|
||||
echo 1 > "$state/next"
|
||||
while read -r block file sum size; do
|
||||
index=$((index + 1))
|
||||
blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size
|
||||
if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then
|
||||
: > "$state/$index.done"
|
||||
fi
|
||||
done < "$list"
|
||||
local count=$index total_bytes=0
|
||||
for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done
|
||||
local slot
|
||||
for slot in $(seq 1 "$parallel"); do
|
||||
(
|
||||
trap ': > "$state/exit.$slot"' EXIT
|
||||
while [ ! -e "$state/failed" ]; do
|
||||
# run_parallel is called in an || list, which switches set -e off in here: a failed claim has to be checked by hand.
|
||||
index=$(claim_next) || { : > "$state/failed"; exit 1; }
|
||||
[ "$index" -gt 0 ] || exit 0
|
||||
file=${files[index]}
|
||||
fetched=""
|
||||
for host in "${cdn_order[@]}"; do
|
||||
if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then
|
||||
fetched=$host
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$fetched" ]; then
|
||||
echo "droiddeck-steam-install: $file failed on every CDN" >&2
|
||||
: > "$state/failed"
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$unpack" ]; then
|
||||
unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; }
|
||||
: > "$dir/$file.unpacked"
|
||||
rm -f "$dir/$file"
|
||||
fi
|
||||
: > "$state/$index.done"
|
||||
done
|
||||
) &
|
||||
pids+=($!)
|
||||
done
|
||||
local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90}
|
||||
while :; do
|
||||
alive=0
|
||||
for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done
|
||||
got=0 n=0 current=""
|
||||
for index in $(seq 1 "$count"); do
|
||||
if [ -e "$state/$index.done" ]; then
|
||||
got=$((got + sizes[index])) n=$((n + 1))
|
||||
elif [ -e "$state/claim.$index" ]; then
|
||||
current=$index
|
||||
[ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}")))
|
||||
fi
|
||||
done
|
||||
mark=$((got / 1000000))
|
||||
if [ -n "$current" ] && [ "$mark" != "$shown" ]; then
|
||||
shown=$mark
|
||||
step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB"
|
||||
fi
|
||||
[ "$n" -lt "$count" ] || alive=0
|
||||
if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi
|
||||
# A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while
|
||||
# and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging.
|
||||
[ $((SECONDS - since)) -lt "$stall" ] || alive=0
|
||||
[ "$alive" = 1 ] || break
|
||||
sleep 1
|
||||
done
|
||||
local failed=""
|
||||
for slot in "${pids[@]}"; do wait "$slot" || failed=1; done
|
||||
[ ! -e "$state/failed" ] || failed=1
|
||||
rm -rf "$state"
|
||||
[ -z "$failed" ]
|
||||
}
|
||||
|
||||
fetch_manifest() {
|
||||
cdn=""
|
||||
for candidate in $cdn_list; do
|
||||
@@ -167,6 +320,66 @@ if ! fetch_manifest; then
|
||||
fallback=1
|
||||
fetch_manifest || exit 1
|
||||
fi
|
||||
if [ -n "$cache_only" ]; then
|
||||
cache=$steam_root/package
|
||||
cached=$cache/droiddeck-cached
|
||||
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
|
||||
awk -F'"' '
|
||||
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
|
||||
$2 == "file" { file[block] = $4 }
|
||||
$2 == "sha2" { sha[block] = $4 }
|
||||
$2 == "size" { size[block] = $4 }
|
||||
$2 == "zipvz" { vz[block] = $4 }
|
||||
$2 == "sha2vz" { vzsha[block] = $4 }
|
||||
END {
|
||||
for (b in file) {
|
||||
f = file[b]; h = sha[b]; n = size[b] + 0
|
||||
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
|
||||
print b, f, h, n
|
||||
}
|
||||
}
|
||||
' "$work/manifest" | sort > "$work/cache"
|
||||
mkdir -p "$cache"
|
||||
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
|
||||
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
|
||||
done_bytes=0
|
||||
i=0
|
||||
if [ "$parallel" -gt 1 ]; then
|
||||
run_parallel "$work/cache" "$cache" || exit 1
|
||||
else
|
||||
while read -r block file sum size; do
|
||||
i=$((i + 1))
|
||||
progress "$cache/$file" "$block"
|
||||
fetched=""
|
||||
for host in "${cdn_order[@]}"; do
|
||||
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
|
||||
fetched=$host
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
|
||||
done_bytes=$((done_bytes + size))
|
||||
done < "$work/cache"
|
||||
fi
|
||||
applier=
|
||||
trap 'kill "$applier" 2>/dev/null || :; wait "$applier" 2>/dev/null || :; rm -f "$cache/$manifest.installed" "$cached"; exit 143' TERM INT HUP
|
||||
echo "$version" > "$cached"
|
||||
preapply=${DD_STEAM_PREAPPLY:-/usr/local/bin/droiddeck-steam-preapply}
|
||||
if [ -x "$preapply" ] && command -v python3 >/dev/null 2>&1; then
|
||||
python3 "$preapply" "$cache" "$steam_root" "$work/manifest" "$manifest" &
|
||||
applier=$!
|
||||
if wait "$applier"; then
|
||||
cp -f "$work/manifest" "$cache/$manifest.manifest"
|
||||
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
|
||||
while read -r _ file _; do rm -f "$cache/$file"; done < "$work/cache"
|
||||
[ -f "$stamp" ] || applied=1
|
||||
else
|
||||
rm -f "$cache/$manifest.installed" "$cached"
|
||||
fi
|
||||
fi
|
||||
trap - TERM INT HUP
|
||||
[ -n "$applied" ] || exit 0
|
||||
fi
|
||||
if [ -n "$sync" ]; then
|
||||
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
|
||||
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
|
||||
@@ -175,6 +388,7 @@ if [ -n "$sync" ]; then
|
||||
fi
|
||||
echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client"
|
||||
fi
|
||||
if [ -z "$applied" ]; then
|
||||
total=$(grep -c . "$work/parts" 2>/dev/null || echo 0)
|
||||
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/parts")
|
||||
|
||||
@@ -186,6 +400,9 @@ for left in "$parts"/*; do
|
||||
grep -qF " $name " "$work/parts" || rm -rf "$left"
|
||||
done
|
||||
done_bytes=0
|
||||
if [ "$parallel" -gt 1 ]; then
|
||||
run_parallel "$work/parts" "$parts" unpack || exit 1
|
||||
else
|
||||
while read -r block file sum size; do
|
||||
i=$((${i:-0} + 1))
|
||||
if [ -f "$parts/$file.unpacked" ]; then
|
||||
@@ -206,6 +423,8 @@ while read -r block file sum size; do
|
||||
rm -f "$parts/$file"
|
||||
done_bytes=$((done_bytes + size))
|
||||
done < "$work/parts"
|
||||
fi
|
||||
fi
|
||||
find "$steam_root" -depth -name '*\\*' | while read -r odd; do
|
||||
fixed=${odd//\\//}
|
||||
mkdir -p "$(dirname "$fixed")"
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract Steam's cached update packages and record them the way Steam's own updater does."""
|
||||
import hashlib, lzma, os, re, stat, struct, sys, time, zipfile, io, zlib, calendar
|
||||
|
||||
OSVER = "-184"
|
||||
MTIME_OFFSET = 28800
|
||||
|
||||
|
||||
def blocks(manifest):
|
||||
out, cur, depth = {}, None, 0
|
||||
for line in manifest.splitlines():
|
||||
m = re.match(r'^(\t+)"([^"]+)"\s*(?:"([^"]*)")?\s*$', line)
|
||||
if m and m.group(3) is None and len(m.group(1)) == 1:
|
||||
cur = m.group(2)
|
||||
out[cur] = {}
|
||||
elif m and m.group(3) is not None and len(m.group(1)) == 2 and cur:
|
||||
out[cur][m.group(2)] = m.group(3)
|
||||
return out
|
||||
|
||||
|
||||
def unvz(d):
|
||||
if d[:3] != b"VZa" or d[-2:] != b"zv":
|
||||
raise ValueError("not a VZip")
|
||||
props = d[7]
|
||||
dict_size = struct.unpack("<I", d[8:12])[0]
|
||||
crc, size = struct.unpack("<II", d[-10:-2])
|
||||
f = [{"id": lzma.FILTER_LZMA1, "dict_size": dict_size,
|
||||
"lc": props % 9, "lp": (props // 9) % 5, "pb": props // 45}]
|
||||
out = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=f).decompress(d[12:-10], max_length=size)
|
||||
if len(out) != size or zlib.crc32(out) & 0xFFFFFFFF != crc:
|
||||
raise ValueError("bad VZip")
|
||||
return out
|
||||
|
||||
|
||||
def inside(root, path):
|
||||
return os.path.commonpath([root, path]) == root
|
||||
|
||||
|
||||
def main(package_dir, steam_root, manifest_path, name):
|
||||
steam_root = os.path.realpath(steam_root)
|
||||
manifest = open(manifest_path, encoding="utf-8", errors="replace").read()
|
||||
rows = {}
|
||||
for block, attrs in blocks(manifest).items():
|
||||
for key in ("zipvz", "file"):
|
||||
f = attrs.get(key)
|
||||
if f and os.path.isfile(os.path.join(package_dir, f)):
|
||||
break
|
||||
else:
|
||||
raise SystemExit(f"missing package for {block}")
|
||||
data = open(os.path.join(package_dir, f), "rb").read()
|
||||
zdata = unvz(data) if key == "zipvz" else data
|
||||
del data
|
||||
with zipfile.ZipFile(io.BytesIO(zdata)) as z:
|
||||
for info in z.infolist():
|
||||
rel = info.filename.replace("\\", "/")
|
||||
if rel.startswith("/") or ".." in rel.split("/"):
|
||||
raise SystemExit(f"unsafe path in {block}: {rel}")
|
||||
dest = os.path.join(steam_root, rel)
|
||||
if not inside(steam_root, os.path.realpath(os.path.dirname(dest.rstrip("/")))):
|
||||
raise SystemExit(f"path leaves the Steam root in {block}: {rel}")
|
||||
mode = (info.external_attr >> 16) & 0xFFFF
|
||||
mtime = calendar.timegm(info.date_time + (0, 0, 0)) + MTIME_OFFSET
|
||||
if rel.endswith("/"):
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
rows[rel] = (-1, mtime, 0)
|
||||
continue
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
if stat.S_ISLNK(mode):
|
||||
if os.path.lexists(dest):
|
||||
os.unlink(dest)
|
||||
os.symlink(z.read(info).decode(), dest)
|
||||
rows[rel] = (-2, mtime, info.CRC)
|
||||
continue
|
||||
with open(dest + ".dd-tmp", "wb") as out:
|
||||
out.write(z.read(info))
|
||||
os.chmod(dest + ".dd-tmp", (mode & 0o777) | 0o644 if mode else 0o644)
|
||||
os.replace(dest + ".dd-tmp", dest)
|
||||
rows[rel] = (info.file_size, mtime, info.CRC)
|
||||
del zdata
|
||||
body = "".join(f"{p},{s};{m};{c}\n" for p, (s, m, c) in sorted(rows.items(), key=lambda kv: kv[0].upper()))
|
||||
body += f"OSVER={OSVER}\nVERSION=3\n"
|
||||
sha = hashlib.sha1(body.encode()).hexdigest().upper()
|
||||
pkg = os.path.join(steam_root, "package")
|
||||
os.makedirs(pkg, exist_ok=True)
|
||||
tmp = os.path.join(pkg, name + ".installed.dd-tmp")
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
f.write(body + f"SHA1={sha}\n")
|
||||
os.replace(tmp, os.path.join(pkg, name + ".installed"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(*sys.argv[1:5])
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
"""Import added games while Steam is closed, preserving user-created shortcuts.
|
||||
|
||||
Usage: droiddeck-steam-shortcuts <steam_root> <added-games.json>
|
||||
@@ -125,6 +125,14 @@ RECORD = ".droiddeck-shortcuts.json"
|
||||
AWAY_LIMIT = 256
|
||||
FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions")
|
||||
FOLLOWED = ("StartDir", "LaunchOptions")
|
||||
# Guest mountpoints whose contents live on storage the user can unplug. The app creates
|
||||
# the mountpoint before binding it, so it outlives a removed card; libraries, store
|
||||
# volumes and added game folders get one mountpoint each under these families.
|
||||
REMOVABLE_ROOTS = ("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")
|
||||
REMOVABLE_FAMILIES = ("/mnt/droiddeck-lib", "/mnt/droiddeck-stores", "/root/Games")
|
||||
# Guest trees the app always has, whatever storage is in the device. A target that is
|
||||
# missing from one of these is gone even when its whole folder was removed.
|
||||
INTERNAL_ROOTS = ("/root/Games/Stores", "/root/.local/share/Steam")
|
||||
|
||||
|
||||
def unquoted(value):
|
||||
@@ -146,6 +154,46 @@ def read_record(path):
|
||||
}
|
||||
|
||||
|
||||
def under(path, root):
|
||||
return path == root or path.startswith(root + "/")
|
||||
|
||||
|
||||
def internal_target(target):
|
||||
path = os.path.normpath(target)
|
||||
return any(under(path, root) for root in INTERNAL_ROOTS)
|
||||
|
||||
|
||||
def removable_mount(target):
|
||||
"""The guest mountpoint holding target, when it is storage the user can unplug."""
|
||||
path = os.path.normpath(target)
|
||||
for root in REMOVABLE_ROOTS:
|
||||
if under(path, root):
|
||||
return root
|
||||
for family in REMOVABLE_FAMILIES:
|
||||
prefix = family + "/"
|
||||
if path.startswith(prefix):
|
||||
return prefix + path[len(prefix):].split("/", 1)[0]
|
||||
return None
|
||||
|
||||
|
||||
def storage_mounted(target):
|
||||
"""Whether the storage holding target is there this session.
|
||||
|
||||
The app creates a guest mountpoint before binding storage to it, so a mountpoint that
|
||||
lists nothing is one a removed card or volume left behind. A target under it may work
|
||||
again when that storage returns, so its absence is not proof the file is gone.
|
||||
"""
|
||||
if internal_target(target):
|
||||
return True
|
||||
mount = removable_mount(target)
|
||||
if mount is None:
|
||||
return True
|
||||
try:
|
||||
return bool(os.listdir(mount))
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def merge(fresh, current, state, seen):
|
||||
state = state if isinstance(state, dict) else {}
|
||||
rev = state.get("rev") if isinstance(state.get("rev"), int) else 0
|
||||
@@ -158,7 +206,16 @@ def merge(fresh, current, state, seen):
|
||||
entry = dict(current)
|
||||
entry["appid"] = fresh["appid"]
|
||||
exe = unquoted(fresh["Exe"])
|
||||
if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev):
|
||||
target = unquoted(current.get("Exe"))
|
||||
# A target Steam still points at after the file is gone starts nothing, so it is not
|
||||
# an edit to keep: the app's own exe replaces it (#694: a hand-typed Target outlived
|
||||
# the game update that removed the file, and every launch died before the game ran).
|
||||
# Only when its storage is mounted and it is missing from a tree the app always has or
|
||||
# from a folder that is still there. An absent folder under a mountpoint can equally be
|
||||
# unplugged storage, and that target may work again next session.
|
||||
gone = (bool(target) and not os.path.isfile(target) and storage_mounted(target) and
|
||||
(internal_target(target) or os.path.isdir(os.path.dirname(target))))
|
||||
if exe != target and (gone or exe != unquoted(base.get("Exe")) or seen == rev):
|
||||
entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"]
|
||||
for field in ("AppName", "icon"):
|
||||
if current.get(field) == base.get(field):
|
||||
|
||||
@@ -10,6 +10,7 @@ import tempfile
|
||||
DISPLAY = "External: gamescope|||Windowed"
|
||||
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
|
||||
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
|
||||
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
|
||||
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
|
||||
|
||||
|
||||
@@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text):
|
||||
return seed_value(text, SCREENSAVER_IN_GAME, '0')
|
||||
|
||||
|
||||
def seed_bouncing_logo(text):
|
||||
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
|
||||
|
||||
|
||||
def atomic_write(path, text):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
@@ -179,6 +184,11 @@ def initialize_screensaver(steam_root):
|
||||
'== steam: no screensaver over a running game')
|
||||
|
||||
|
||||
def initialize_screensaver_choice(steam_root):
|
||||
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
|
||||
'== steam: bouncing logo screensaver')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
status = 0
|
||||
try:
|
||||
@@ -186,7 +196,7 @@ if __name__ == '__main__':
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
|
||||
status = 1
|
||||
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
|
||||
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
|
||||
try:
|
||||
step(sys.argv[1])
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
|
||||
@@ -713,14 +713,67 @@ x64_webhelper_gpu() {
|
||||
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ]
|
||||
}
|
||||
|
||||
x64_thunk_appconfigs() {
|
||||
python3 - "$1" "$2" "$3" "$4" <<'PY' || true
|
||||
import json, os, sys, tempfile
|
||||
src, dst, cfg, on = sys.argv[1:5]
|
||||
want = json.loads(cfg)
|
||||
try:
|
||||
names = sorted(os.listdir(src))
|
||||
except OSError:
|
||||
names = []
|
||||
for name in names:
|
||||
if not name.endswith(".json"):
|
||||
continue
|
||||
try:
|
||||
db = json.load(open(os.path.join(src, name), encoding="utf-8")).get("ThunksDB") or {}
|
||||
if not any(k in want["ThunksDB"] and not v for k, v in db.items()):
|
||||
continue
|
||||
except (OSError, ValueError, AttributeError):
|
||||
continue
|
||||
path = os.path.join(dst, name)
|
||||
try:
|
||||
cur = json.load(open(path, encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
cur = None
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if cur is not None and cur != want:
|
||||
continue
|
||||
if on == "1" and cur is None:
|
||||
try:
|
||||
os.makedirs(dst, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=dst, prefix=".fex", suffix=".tmp")
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
f.write(cfg + "\n")
|
||||
os.link(tmp, path)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
elif on != "1" and cur is not None:
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
PY
|
||||
}
|
||||
|
||||
x64_env() {
|
||||
export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true
|
||||
mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env"
|
||||
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
|
||||
gpu_vars="GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR mesa_glthread"
|
||||
thunk_cfg='{"ThunksDB": {"GL": 1, "Vulkan": 1}}'
|
||||
rm -f "$X64_HOME/game-gpu.env"
|
||||
if x64_gpu; then
|
||||
printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json"
|
||||
printf '%s\n' "$thunk_cfg" > "$X64_HOME/thunks.json"
|
||||
{
|
||||
echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'"
|
||||
echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER"
|
||||
@@ -729,7 +782,10 @@ if x64_gpu; then
|
||||
done
|
||||
} > "$X64_HOME/game-gpu.env"
|
||||
fi
|
||||
if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then
|
||||
client_thunks=0
|
||||
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && client_thunks=1
|
||||
x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"
|
||||
if [ "$client_thunks" = 1 ]; then
|
||||
export FEX_THUNKCONFIG=$X64_HOME/thunks.json
|
||||
unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE
|
||||
else
|
||||
|
||||
@@ -5,6 +5,7 @@ import binascii
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
@@ -337,6 +338,13 @@ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/Ub
|
||||
ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar")
|
||||
SERVICE_WAIT = 300.0
|
||||
ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher"
|
||||
EPIC_SDK_SETUP = ROCKSTAR_FOLDER + "/Redistributables/SocialClub/Social-Club-Setup.exe"
|
||||
SDK_SOURCE = ".droiddeck-sdk-source"
|
||||
SDK_SETUP_LIMIT = 256 * 1024 * 1024
|
||||
EPIC_PARENT = Path("/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe")
|
||||
EPIC_PARENT_ON = 'set "DD_P=1"'
|
||||
EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
|
||||
EPIC_SERVICE_WAIT = 60.0
|
||||
ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas",
|
||||
"gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"}
|
||||
|
||||
@@ -394,10 +402,9 @@ def rockstar_sdk(folder, sidecar):
|
||||
return False
|
||||
|
||||
|
||||
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
|
||||
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None, launcher=True):
|
||||
pfx = Path(compat_data) / "pfx"
|
||||
launcher = r"C:\Program Files\Rockstar Games\Launcher"
|
||||
values = [(r"Rockstar Games\Launcher", launcher)]
|
||||
values = [(r"Rockstar Games\Launcher", r"C:\Program Files\Rockstar Games\Launcher")] if launcher else []
|
||||
if title:
|
||||
values.append(("Rockstar Games\\" + title, windows_path(str(folder))))
|
||||
entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values]
|
||||
@@ -420,23 +427,29 @@ def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def rockstar_runtime(folder, exe, compat_data, arch):
|
||||
def rockstar_runtime(folder, exe, compat_data, arch, installer=None):
|
||||
if arch == "x86":
|
||||
rockstar_runtime(folder, exe, compat_data, "x64")
|
||||
rockstar_runtime(folder, exe, compat_data, "x64", installer)
|
||||
pfx = Path(compat_data) / "pfx"
|
||||
target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club"
|
||||
if not target.resolve().is_relative_to(pfx.resolve()):
|
||||
raise ValueError("invalid Social Club destination")
|
||||
required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ())
|
||||
marker = target / ".droiddeck-installing"
|
||||
if all((target / name).is_file() for name in required) and not marker.exists():
|
||||
source_file, stamp = target / SDK_SOURCE, None
|
||||
if installer is not None:
|
||||
info = installer.stat()
|
||||
stamp = "%d %d %s" % (info.st_size, info.st_mtime_ns, installer)
|
||||
current = stamp is None or source_file.is_file() and not source_file.is_symlink() and source_file.read_text(errors="replace") == stamp
|
||||
if all((target / name).is_file() for name in required) and not marker.exists() and current:
|
||||
return "present"
|
||||
root = folder.resolve()
|
||||
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
|
||||
for sub in ("Redistributables", "Installers")]
|
||||
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None)
|
||||
if installer is None:
|
||||
return "game-runtime"
|
||||
root = folder.resolve()
|
||||
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
|
||||
for sub in ("Redistributables", "Installers")]
|
||||
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= SDK_SETUP_LIMIT), None)
|
||||
if installer is None:
|
||||
return "game-runtime"
|
||||
tool = shutil.which("7z")
|
||||
if not tool:
|
||||
return "no-unpacker"
|
||||
@@ -488,15 +501,67 @@ def rockstar_runtime(folder, exe, compat_data, arch):
|
||||
raise
|
||||
os.replace(stage_path, output)
|
||||
marker.unlink()
|
||||
if stamp is not None:
|
||||
source_file.unlink(missing_ok=True)
|
||||
source_file.write_text(stamp)
|
||||
return "installed"
|
||||
|
||||
|
||||
def fetch_service(service, store, launch_dir, ask_app=None):
|
||||
def epic_parent_switch(sidecar, env=None):
|
||||
own = sidecar.get("env") if isinstance(sidecar.get("env"), dict) else {}
|
||||
if EPIC_PARENT_SWITCH in own:
|
||||
return str(own[EPIC_PARENT_SWITCH]).replace('"', "")
|
||||
env = os.environ if env is None else env
|
||||
try:
|
||||
game_env = runpy.run_path(str(Path(__file__).resolve().with_name("droiddeck-game-env")))
|
||||
try:
|
||||
config = json.loads((Path(env.get("HOME") or "/root") / ".config/droiddeck/game-environment.json").read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
config = {"version": 1}
|
||||
env = game_env["apply_config"](env, config, game_env["game_id"](env))
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
pass
|
||||
return env.get(EPIC_PARENT_SWITCH, "")
|
||||
|
||||
|
||||
def wants_epic_parent(folder, switch):
|
||||
if switch in ("0", "1"):
|
||||
return switch == "1"
|
||||
try:
|
||||
return EPIC_PARENT_ON in (folder / LAUNCHER).read_text(errors="replace").splitlines()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def epic_rockstar_sdk(folder, sidecar, compat_data, proton):
|
||||
if not compat_data:
|
||||
return None
|
||||
pfx = Path(compat_data) / "pfx"
|
||||
root = folder.resolve()
|
||||
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
|
||||
if not exe.is_relative_to(root):
|
||||
return None
|
||||
setups = [(pfx / EPIC_SDK_SETUP, pfx)] + [(base / sub / "Social-Club-Setup.exe", root) for base in (root, exe.parent)
|
||||
for sub in ("Redistributables", "Installers")]
|
||||
setup = next((path for path, inside in setups if path.is_file() and path.resolve().is_relative_to(inside.resolve())
|
||||
and path.stat().st_size <= SDK_SETUP_LIMIT), None)
|
||||
if setup is None:
|
||||
return None
|
||||
made = "present" if (pfx / "user.reg").is_file() else create_prefix(compat_data, proton)
|
||||
if made not in ("created", "present"):
|
||||
return "prefix-" + made
|
||||
state = rockstar_runtime(folder, exe, compat_data, "x64", setup)
|
||||
if state in ("present", "installed") and not rockstar_registry(folder, None, compat_data, proton, sdk_arch="x64", launcher=False):
|
||||
return state + " registry-unavailable"
|
||||
return state
|
||||
|
||||
|
||||
def fetch_service(service, store, launch_dir, ask_app=None, timeout=SERVICE_WAIT):
|
||||
if service.is_file():
|
||||
return True
|
||||
if not launch_dir:
|
||||
return False
|
||||
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT)
|
||||
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=timeout)
|
||||
return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file()
|
||||
|
||||
|
||||
@@ -1650,6 +1715,15 @@ def main(argv):
|
||||
pass
|
||||
log("ubisoft %s: not prepared (%s), starting directly" % (game, e))
|
||||
if store == "epic":
|
||||
try:
|
||||
if launch_dir and not EPIC_PARENT.is_file() and wants_epic_parent(folder, epic_parent_switch(sidecar)):
|
||||
got = fetch_service(EPIC_PARENT, "epic", launch_dir, timeout=EPIC_SERVICE_WAIT)
|
||||
log("epic parent stand-in: " + ("staged" if got else "unavailable"))
|
||||
sdk = epic_rockstar_sdk(folder, sidecar, compat_data, os.environ.get("DD_STORE_PROTON", ""))
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired) as error:
|
||||
sdk = "failed (%s)" % type(error).__name__
|
||||
if sdk:
|
||||
log("epic rockstar sdk: " + sdk)
|
||||
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
|
||||
if not handled:
|
||||
drop_stale(folder)
|
||||
|
||||
@@ -21,6 +21,29 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t
|
||||
__attribute__((visibility("hidden")))
|
||||
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) {
|
||||
if (!file || !*file) return 0;
|
||||
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
|
||||
const char *paths = getenv("PATH");
|
||||
if (!paths) paths = "/bin:/usr/bin";
|
||||
char candidate[PATH_MAX];
|
||||
int found = 0;
|
||||
for (const char *p = paths;; ) {
|
||||
const char *end = strchrnul(p, ':');
|
||||
int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file)
|
||||
: snprintf(candidate, sizeof candidate, "%s", file);
|
||||
struct stat st;
|
||||
if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) {
|
||||
int runs = access(candidate, X_OK) == 0;
|
||||
if (runs || !found) memcpy(out, candidate, (size_t)n + 1);
|
||||
found = 1;
|
||||
if (runs) return 1;
|
||||
}
|
||||
if (!*end) return found;
|
||||
p = end + 1;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__aarch64__) || defined(BINFMT_TEST)
|
||||
|
||||
static int flag(const char *name) {
|
||||
@@ -32,17 +55,26 @@ static int handing_off(void) {
|
||||
return flag("DD_DESKTOP") || flag("DD_BINFMT");
|
||||
}
|
||||
|
||||
static int appimage(int fd, const unsigned char *head, ssize_t n) {
|
||||
Elf64_Ehdr eh;
|
||||
if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0;
|
||||
memcpy(&eh, head, sizeof eh);
|
||||
char magic[6];
|
||||
off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum;
|
||||
return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6));
|
||||
}
|
||||
|
||||
static int foreign(const char *path, int error) {
|
||||
if (!path || !strcmp(path, BINFMT_HANDLER)) return 0;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
struct stat st;
|
||||
unsigned char head[20];
|
||||
unsigned char head[sizeof(Elf64_Ehdr)];
|
||||
ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1;
|
||||
int kind = 0;
|
||||
if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) {
|
||||
unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8;
|
||||
kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0;
|
||||
kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0;
|
||||
} else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') {
|
||||
kind = 2;
|
||||
} else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) {
|
||||
@@ -58,21 +90,6 @@ static int wanted(const char *path, int error) {
|
||||
return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error);
|
||||
}
|
||||
|
||||
static int lookup(const char *file, char *out, size_t size) {
|
||||
if (!file || !*file) return 0;
|
||||
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
|
||||
const char *paths = getenv("PATH");
|
||||
if (!paths) paths = "/bin:/usr/bin";
|
||||
for (const char *p = paths;; ) {
|
||||
const char *end = strchrnul(p, ':');
|
||||
int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file);
|
||||
struct stat st;
|
||||
if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1;
|
||||
if (!*end) return 0;
|
||||
p = end + 1;
|
||||
}
|
||||
}
|
||||
|
||||
static int count(char *const argv[]) {
|
||||
int n = 0;
|
||||
while (argv && argv[n]) n++;
|
||||
@@ -117,12 +134,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char
|
||||
|
||||
__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) {
|
||||
char path[PATH_MAX];
|
||||
if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
|
||||
if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) {
|
||||
char path[PATH_MAX];
|
||||
if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
|
||||
if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
|
||||
errno = error;
|
||||
return -1;
|
||||
}
|
||||
@@ -144,7 +161,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char
|
||||
|
||||
int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
||||
char resolved[PATH_MAX];
|
||||
const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file;
|
||||
const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file;
|
||||
char *const *adjusted = dd_webhelper_argv(path, argv, envp);
|
||||
static int (*real)(const char *, char *const[], char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe");
|
||||
@@ -156,7 +173,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
||||
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr,
|
||||
char *const argv[], char *const envp[]) {
|
||||
char path[PATH_MAX];
|
||||
int found = lookup(file, path, sizeof path);
|
||||
int found = dd_program_lookup(file, path, sizeof path);
|
||||
char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp);
|
||||
static spawn_fn real, spawn;
|
||||
if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp");
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
#define CP_FDS 65536
|
||||
|
||||
static const int64_t *cp_shift;
|
||||
static int cp_state;
|
||||
static size_t cp_cond_byte;
|
||||
static unsigned char cp_cond_mask;
|
||||
static unsigned char cp_fds[CP_FDS / 8];
|
||||
@@ -94,25 +93,14 @@ static void cp_init(void) {
|
||||
}
|
||||
|
||||
static int64_t cp_offset(void) {
|
||||
const int64_t *shift;
|
||||
int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE);
|
||||
if (state == 0) {
|
||||
int expected = 0;
|
||||
if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
|
||||
cp_init();
|
||||
__atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (state != 2) return 0;
|
||||
shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
|
||||
const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
|
||||
if (!shift) return 0;
|
||||
int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED);
|
||||
return value > 0 ? value : 0;
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void cp_start(void) {
|
||||
cp_offset();
|
||||
cp_init();
|
||||
}
|
||||
|
||||
static int cp_mono(clockid_t clock) {
|
||||
|
||||
@@ -31,7 +31,7 @@ static int store_root(char *out, size_t size) {
|
||||
return n > 0 && (size_t)n < size ? n : -1;
|
||||
}
|
||||
|
||||
static int store_exists(void) {
|
||||
static __attribute__((noinline)) int store_exists(void) {
|
||||
char root[PATH_MAX];
|
||||
|
||||
if (store_seen) return 1;
|
||||
@@ -223,10 +223,18 @@ int fremovexattr(int fd, const char *name) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int watched(void) {
|
||||
int saved = errno, found;
|
||||
|
||||
found = dd_is_wineserver() && store_exists();
|
||||
errno = saved;
|
||||
return found;
|
||||
}
|
||||
|
||||
static int tracked(const char *path, char *out, size_t size) {
|
||||
int saved = errno, found;
|
||||
|
||||
found = dd_is_wineserver() && store_exists() && resolved(path, out, size) == 0;
|
||||
found = resolved(path, out, size) == 0;
|
||||
errno = saved;
|
||||
return found;
|
||||
}
|
||||
@@ -258,22 +266,30 @@ static void follow(const char *from, const char *to) {
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_unlink(const char *path, int (*real)(const char *)) {
|
||||
static __attribute__((noinline)) int removed(const char *path, int (*real)(const char *), int folder) {
|
||||
char target[PATH_MAX];
|
||||
int known = tracked(path, target, sizeof(target)), result = real(path);
|
||||
|
||||
if (result == 0 && known) forget(target, 0);
|
||||
if (result == 0 && known) forget(target, folder);
|
||||
return result;
|
||||
}
|
||||
|
||||
static __attribute__((noinline)) int moved(const char *from, const char *to, int (*real)(const char *, const char *)) {
|
||||
char old[PATH_MAX], new[PATH_MAX];
|
||||
int known = tracked(from, old, sizeof(old)), result = real(from, to);
|
||||
|
||||
if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new);
|
||||
return result;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) {
|
||||
char target[PATH_MAX];
|
||||
int known = tracked(path, target, sizeof(target)), result = real(path);
|
||||
int dd_descriptor_unlink(const char *path, int (*real)(const char *)) {
|
||||
return watched() ? removed(path, real, 0) : real(path);
|
||||
}
|
||||
|
||||
if (result == 0 && known) forget(target, 1);
|
||||
return result;
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) {
|
||||
return watched() ? removed(path, real, 1) : real(path);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
@@ -283,9 +299,5 @@ int dd_descriptor_remove(const char *path, int (*real)(const char *)) {
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) {
|
||||
char old[PATH_MAX], new[PATH_MAX];
|
||||
int known = tracked(from, old, sizeof(old)), result = real(from, to);
|
||||
|
||||
if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new);
|
||||
return result;
|
||||
return watched() ? moved(from, to, real) : real(from, to);
|
||||
}
|
||||
@@ -582,6 +582,16 @@ const char *udev_device_get_action(void *device) {
|
||||
return real_get(device);
|
||||
}
|
||||
|
||||
const char *udev_device_get_driver(void *device) {
|
||||
static const char *(*real_get)(void *);
|
||||
struct pad *pad = device_pad(device);
|
||||
|
||||
if (pad != NULL) return NULL;
|
||||
if (real_get == NULL) real_get = next_symbol("udev_device_get_driver");
|
||||
if (real_get == NULL) return NULL;
|
||||
return real_get(device);
|
||||
}
|
||||
|
||||
dev_t udev_device_get_devnum(void *device) {
|
||||
static dev_t (*real_get)(void *);
|
||||
struct pad *pad = device_pad(device);
|
||||
@@ -686,6 +696,54 @@ void *udev_device_get_sysattr_list_entry(void *device) {
|
||||
return real_get != NULL ? real_get(device) : NULL;
|
||||
}
|
||||
|
||||
void *udev_device_get_current_tags_list_entry(void *device) {
|
||||
static void *(*real_get)(void *);
|
||||
|
||||
if (device_pad(device) != NULL) return NULL;
|
||||
if (real_get == NULL) real_get = next_symbol("udev_device_get_current_tags_list_entry");
|
||||
return real_get != NULL ? real_get(device) : NULL;
|
||||
}
|
||||
|
||||
int udev_device_has_current_tag(void *device, const char *tag) {
|
||||
static int (*real_has)(void *, const char *);
|
||||
|
||||
if (device_pad(device) != NULL) return 0;
|
||||
if (real_has == NULL) real_has = next_symbol("udev_device_has_current_tag");
|
||||
return real_has != NULL ? real_has(device, tag) : 0;
|
||||
}
|
||||
|
||||
void *udev_device_get_devlinks_list_entry(void *device) {
|
||||
static void *(*real_get)(void *);
|
||||
|
||||
if (device_pad(device) != NULL) return NULL;
|
||||
if (real_get == NULL) real_get = next_symbol("udev_device_get_devlinks_list_entry");
|
||||
return real_get != NULL ? real_get(device) : NULL;
|
||||
}
|
||||
|
||||
unsigned long long udev_device_get_seqnum(void *device) {
|
||||
static unsigned long long (*real_get)(void *);
|
||||
|
||||
if (device_pad(device) != NULL) return 0;
|
||||
if (real_get == NULL) real_get = next_symbol("udev_device_get_seqnum");
|
||||
return real_get != NULL ? real_get(device) : 0;
|
||||
}
|
||||
|
||||
unsigned long long udev_device_get_usec_since_initialized(void *device) {
|
||||
static unsigned long long (*real_get)(void *);
|
||||
|
||||
if (device_pad(device) != NULL) return 0;
|
||||
if (real_get == NULL) real_get = next_symbol("udev_device_get_usec_since_initialized");
|
||||
return real_get != NULL ? real_get(device) : 0;
|
||||
}
|
||||
|
||||
int udev_device_set_sysattr_value(void *device, const char *sysattr, const char *value) {
|
||||
static int (*real_set)(void *, const char *, const char *);
|
||||
|
||||
if (device_pad(device) != NULL) return -EACCES;
|
||||
if (real_set == NULL) real_set = next_symbol("udev_device_set_sysattr_value");
|
||||
return real_set != NULL ? real_set(device, sysattr, value) : -ENOSYS;
|
||||
}
|
||||
|
||||
void *udev_device_new_from_devnum(void *udev, char type, dev_t devnum) {
|
||||
static void *(*real_new)(void *, char, dev_t);
|
||||
struct pad pad;
|
||||
@@ -1011,6 +1069,7 @@ static const struct udev_symbol udev_symbols[] = {
|
||||
{"udev_device_get_subsystem", (void *)udev_device_get_subsystem},
|
||||
{"udev_device_get_devtype", (void *)udev_device_get_devtype},
|
||||
{"udev_device_get_action", (void *)udev_device_get_action},
|
||||
{"udev_device_get_driver", (void *)udev_device_get_driver},
|
||||
{"udev_device_get_devnum", (void *)udev_device_get_devnum},
|
||||
{"udev_device_get_sysattr_value", (void *)udev_device_get_sysattr_value},
|
||||
{"udev_device_get_property_value", (void *)udev_device_get_property_value},
|
||||
@@ -1023,6 +1082,12 @@ static const struct udev_symbol udev_symbols[] = {
|
||||
{"udev_device_get_properties_list_entry", (void *)udev_device_get_properties_list_entry},
|
||||
{"udev_device_get_tags_list_entry", (void *)udev_device_get_tags_list_entry},
|
||||
{"udev_device_get_sysattr_list_entry", (void *)udev_device_get_sysattr_list_entry},
|
||||
{"udev_device_get_current_tags_list_entry", (void *)udev_device_get_current_tags_list_entry},
|
||||
{"udev_device_has_current_tag", (void *)udev_device_has_current_tag},
|
||||
{"udev_device_get_devlinks_list_entry", (void *)udev_device_get_devlinks_list_entry},
|
||||
{"udev_device_get_seqnum", (void *)udev_device_get_seqnum},
|
||||
{"udev_device_get_usec_since_initialized", (void *)udev_device_get_usec_since_initialized},
|
||||
{"udev_device_set_sysattr_value", (void *)udev_device_set_sysattr_value},
|
||||
{"udev_enumerate_new", (void *)udev_enumerate_new},
|
||||
{"udev_enumerate_ref", (void *)udev_enumerate_ref},
|
||||
{"udev_enumerate_unref", (void *)udev_enumerate_unref},
|
||||
@@ -1045,7 +1110,15 @@ static void *own_udev_symbol(const char *name) {
|
||||
}
|
||||
|
||||
static void *dlvsym_any(const char *name) {
|
||||
#if defined(__aarch64__)
|
||||
static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.34"};
|
||||
#elif defined(__x86_64__)
|
||||
static const char *versions[] = {"GLIBC_2.2.5", "GLIBC_2.34"};
|
||||
#elif defined(__i386__)
|
||||
static const char *versions[] = {"GLIBC_2.0", "GLIBC_2.34"};
|
||||
#else
|
||||
static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.2.5", "GLIBC_2.0", "GLIBC_2.34"};
|
||||
#endif
|
||||
size_t i;
|
||||
void *resolved = NULL;
|
||||
|
||||
@@ -1073,7 +1146,7 @@ static int steam_runtime_path(const char *path) {
|
||||
const char *name = strrchr(path, '/');
|
||||
size_t i;
|
||||
|
||||
if (name == NULL || strcmp(name + 1, "steam") != 0) return 0;
|
||||
if (name == NULL || (strcmp(name + 1, "steam") != 0 && strcmp(name + 1, "streaming_client") != 0)) return 0;
|
||||
for (i = 0; i < sizeof(runtimes) / sizeof(runtimes[0]); i++) {
|
||||
size_t length = strlen(runtimes[i]);
|
||||
|
||||
|
||||
@@ -111,6 +111,9 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
|
||||
static unsigned guarded_port(void);
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd);
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
|
||||
int (*real_bind)(int, const struct sockaddr *, socklen_t),
|
||||
int *rc);
|
||||
__attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr,
|
||||
socklen_t len, int *rc);
|
||||
__attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr,
|
||||
@@ -121,6 +124,7 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
|
||||
int nl_rc;
|
||||
if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind");
|
||||
if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc;
|
||||
if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc;
|
||||
if (dd_udevmon_stand_in(fd)) {
|
||||
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) {
|
||||
errno = EINVAL;
|
||||
@@ -273,6 +277,7 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f
|
||||
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
|
||||
__attribute__((visibility("hidden")))
|
||||
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
|
||||
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size);
|
||||
__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
|
||||
spawn_fn real);
|
||||
@@ -373,7 +378,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
|
||||
}
|
||||
|
||||
int execvp(const char *file, char *const argv_in[]) {
|
||||
char *const *argv = dd_webhelper_argv(file, argv_in, environ);
|
||||
char resolved[PATH_MAX];
|
||||
char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ);
|
||||
static int (*real)(const char *, char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
|
||||
maybe_answer_lsof(file, argv);
|
||||
|
||||
+111
-27
@@ -22,6 +22,7 @@
|
||||
#include <stdarg.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
@@ -520,6 +521,13 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
|
||||
fprintf(out, "%6s: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", link->name);
|
||||
} else if (strcmp(table, "arp") == 0) {
|
||||
fprintf(out, "IP address HW type Flags HW address Mask Device\n");
|
||||
} else if (strcmp(table, "tcp") == 0 || strcmp(table, "udp") == 0) {
|
||||
fprintf(out, " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n",
|
||||
table[0] == 'u' ? " ref pointer drops" : "");
|
||||
} else if (strcmp(table, "tcp6") == 0 || strcmp(table, "udp6") == 0) {
|
||||
fprintf(out, " sl local_address remote_address "
|
||||
"st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n",
|
||||
table[0] == 'u' ? " ref pointer drops" : "");
|
||||
} else {
|
||||
fprintf(out, "1\n");
|
||||
}
|
||||
@@ -527,7 +535,10 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
|
||||
|
||||
#define CARRIER_TABLE 5
|
||||
|
||||
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" };
|
||||
#define SOCKET_TABLES 6
|
||||
|
||||
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier",
|
||||
"tcp", "tcp6", "udp", "udp6" };
|
||||
static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])];
|
||||
|
||||
#define CARRIER_SLOTS 8
|
||||
@@ -564,8 +575,8 @@ static void remember_denial(int table, const char *path) {
|
||||
|
||||
static int denied_table(const char *path) {
|
||||
if (strncmp(path, "/proc/net/", 10) == 0) {
|
||||
for (int i = 0; i < CARRIER_TABLE; i++) {
|
||||
if (strcmp(path + 10, net_tables[i]) == 0) return i;
|
||||
for (int i = 0; i < (int) (sizeof(net_tables) / sizeof(net_tables[0])); i++) {
|
||||
if (i != CARRIER_TABLE && strcmp(path + 10, net_tables[i]) == 0) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -576,17 +587,17 @@ static int denied_table(const char *path) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
static FILE *synthesize(const char *table) {
|
||||
static FILE *synthesize(int table) {
|
||||
struct link link;
|
||||
if (!load_link(&link)) return NULL;
|
||||
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC);
|
||||
if (!load_link(&link) && table < SOCKET_TABLES) return NULL;
|
||||
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC | MFD_ALLOW_SEALING);
|
||||
if (fd < 0) return NULL;
|
||||
FILE *out = fdopen(fd, "w+");
|
||||
if (out == NULL) {
|
||||
close(fd);
|
||||
return NULL;
|
||||
}
|
||||
write_table(out, table, &link);
|
||||
write_table(out, net_tables[table], &link);
|
||||
if (fflush(out) != 0) {
|
||||
fclose(out);
|
||||
return NULL;
|
||||
@@ -610,11 +621,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
|
||||
path = dd_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+')));
|
||||
int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1;
|
||||
FILE *f;
|
||||
if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f;
|
||||
if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f;
|
||||
f = real(path, mode);
|
||||
if (f || table < 0) return f;
|
||||
int saved = errno;
|
||||
if ((f = synthesize(net_tables[table])) != NULL) {
|
||||
if ((f = synthesize(table)) != NULL) {
|
||||
if (saved == EACCES) remember_denial(table, path);
|
||||
return f;
|
||||
}
|
||||
@@ -622,6 +633,33 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
|
||||
|
||||
int dd_net_open(const char *path, int flags, int fd) {
|
||||
if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
|
||||
int table = denied_table(path);
|
||||
if (table < 0) return fd;
|
||||
int saved = errno;
|
||||
FILE *f = synthesize(table);
|
||||
if (f == NULL) {
|
||||
errno = saved;
|
||||
return fd;
|
||||
}
|
||||
char self[32];
|
||||
snprintf(self, sizeof(self), "/proc/self/fd/%d", fileno(f));
|
||||
int copy = open(self, O_RDONLY | (flags & O_CLOEXEC));
|
||||
if (copy < 0 && fcntl(fileno(f), F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) == 0) {
|
||||
copy = fcntl(fileno(f), flags & O_CLOEXEC ? F_DUPFD_CLOEXEC : F_DUPFD, 0);
|
||||
}
|
||||
fclose(f);
|
||||
if (copy < 0) {
|
||||
errno = saved;
|
||||
return fd;
|
||||
}
|
||||
if (saved == EACCES) remember_denial(table, path);
|
||||
return copy;
|
||||
}
|
||||
|
||||
FILE *fopen(const char *path, const char *mode) {
|
||||
static fopen_fn real;
|
||||
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen");
|
||||
@@ -664,6 +702,7 @@ struct nl_socket {
|
||||
unsigned references;
|
||||
int type;
|
||||
int cap_ack;
|
||||
uint64_t groups;
|
||||
struct nl_socket *next;
|
||||
};
|
||||
|
||||
@@ -685,13 +724,14 @@ struct nl_fd_page {
|
||||
|
||||
struct nl_metadata {
|
||||
uint64_t nonce;
|
||||
uint64_t groups;
|
||||
uint32_t port;
|
||||
uint32_t type;
|
||||
uint32_t cap_ack;
|
||||
char magic[12];
|
||||
};
|
||||
|
||||
_Static_assert(sizeof(struct nl_metadata) == 32, "netlink socket metadata ABI");
|
||||
_Static_assert(sizeof(struct nl_metadata) == 40, "netlink socket metadata ABI");
|
||||
|
||||
struct nl_packet {
|
||||
struct nl_packet *next;
|
||||
@@ -705,9 +745,9 @@ struct nl_reply {
|
||||
int overflow;
|
||||
};
|
||||
|
||||
static const char nl_client_magic[12] = "dd-nl-c-v1";
|
||||
static const char nl_peer_magic[12] = "dd-nl-p-v1";
|
||||
static const char nl_reservation_magic[12] = "dd-nl-r-v1";
|
||||
static const char nl_client_magic[12] = "dd-nl-c-v2";
|
||||
static const char nl_peer_magic[12] = "dd-nl-p-v2";
|
||||
static const char nl_reservation_magic[12] = "dd-nl-r-v2";
|
||||
static struct nl_socket *nl_sockets;
|
||||
static struct nl_fd *nl_fds;
|
||||
static struct nl_fd_page *nl_fd_pages[NL_FD_BUCKETS];
|
||||
@@ -910,13 +950,13 @@ static int nl_save_packets(int fd, struct nl_packet **packets) {
|
||||
}
|
||||
}
|
||||
|
||||
static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped) {
|
||||
static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped, uint64_t groups) {
|
||||
static int (*real_socket)(int, int, int);
|
||||
static int (*real_close)(int);
|
||||
if (real_socket == NULL) real_socket = (int (*)(int, int, int)) dlsym(RTLD_NEXT, "socket");
|
||||
if (real_close == NULL) real_close = (int (*)(int)) dlsym(RTLD_NEXT, "close");
|
||||
struct sockaddr_un client_addr, peer_addr;
|
||||
struct nl_metadata client, peer = { .port = port, .type = socket->type, .cap_ack = capped };
|
||||
struct nl_metadata client, peer = { .groups = groups, .port = port, .type = socket->type, .cap_ack = capped };
|
||||
if (!nl_address(fd, 0, &client_addr, &client, nl_client_magic)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
@@ -955,6 +995,7 @@ static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int
|
||||
socket->peer_inode = status.st_ino;
|
||||
socket->port = port;
|
||||
socket->cap_ack = capped;
|
||||
socket->groups = groups;
|
||||
errno = saved;
|
||||
return replayed;
|
||||
failed: {
|
||||
@@ -1025,7 +1066,7 @@ static struct nl_fd *nl_restore(int fd) {
|
||||
socket->device = status.st_dev;
|
||||
socket->inode = status.st_ino;
|
||||
socket->type = peer.type;
|
||||
if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack) != 0) {
|
||||
if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack, peer.groups) != 0) {
|
||||
free(socket);
|
||||
free(entry);
|
||||
return NULL;
|
||||
@@ -1159,7 +1200,7 @@ static int nl_peer_of(int fd) {
|
||||
if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) {
|
||||
if ((metadata.nonce == socket->peer_inode
|
||||
&& nl_identity(socket->peer, socket->device, socket->peer_inode))
|
||||
|| nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack) == 0) {
|
||||
|| nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack, metadata.groups) == 0) {
|
||||
if (socket->port != 0 && (socket->reservation < 0
|
||||
|| !nl_identity(socket->reservation, socket->device, socket->reservation_inode)))
|
||||
nl_reserve_port(socket, socket->port);
|
||||
@@ -1317,7 +1358,7 @@ static int nl_bind_port(int fd, unsigned requested, int automatic) {
|
||||
}
|
||||
if (other == NULL) {
|
||||
if (nl_reserve_port(socket, port) == 0) {
|
||||
result = nl_replace_peer(fd, socket, port, socket->cap_ack);
|
||||
result = nl_replace_peer(fd, socket, port, socket->cap_ack, socket->groups);
|
||||
if (result != 0) nl_close_reservation(socket);
|
||||
break;
|
||||
}
|
||||
@@ -1342,6 +1383,23 @@ static int nl_autobind(int fd) {
|
||||
return nl_bind_port(fd, 0, 1);
|
||||
}
|
||||
|
||||
static int nl_set_groups(int fd, uint64_t keep, uint64_t add) {
|
||||
int result = 0;
|
||||
pthread_mutex_lock(&nl_sockets_lock);
|
||||
struct nl_fd *entry = nl_find(fd);
|
||||
if (entry) {
|
||||
struct nl_socket *socket = entry->socket;
|
||||
struct sockaddr_un addr;
|
||||
struct nl_metadata metadata;
|
||||
uint64_t current = nl_address(fd, 1, &addr, &metadata, nl_peer_magic) ? metadata.groups : socket->groups;
|
||||
uint64_t groups = (current & keep) | add;
|
||||
if (groups != current || groups != socket->groups)
|
||||
result = nl_replace_peer(fd, socket, socket->port, socket->cap_ack, groups);
|
||||
}
|
||||
pthread_mutex_unlock(&nl_sockets_lock);
|
||||
return result;
|
||||
}
|
||||
|
||||
int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) {
|
||||
const struct sockaddr_nl *nl;
|
||||
if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd);
|
||||
@@ -1352,15 +1410,39 @@ int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) {
|
||||
return 1;
|
||||
}
|
||||
nl = (const struct sockaddr_nl *) addr;
|
||||
if (nl->nl_groups != 0) {
|
||||
errno = EACCES;
|
||||
*rc = -1;
|
||||
return 1;
|
||||
}
|
||||
*rc = nl_bind_port(fd, nl->nl_pid, 0);
|
||||
if (*rc == 0) *rc = nl_set_groups(fd, ~(uint64_t) UINT32_MAX, nl->nl_groups);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static unsigned nl_groups_of(int fd) {
|
||||
struct sockaddr_un addr;
|
||||
struct nl_metadata metadata;
|
||||
if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) return (unsigned) metadata.groups;
|
||||
unsigned groups = 0;
|
||||
pthread_mutex_lock(&nl_sockets_lock);
|
||||
struct nl_fd *entry = nl_find(fd);
|
||||
if (entry) groups = (unsigned) entry->socket->groups;
|
||||
pthread_mutex_unlock(&nl_sockets_lock);
|
||||
return groups;
|
||||
}
|
||||
|
||||
static int nl_membership(int fd, int option, const void *value, socklen_t len) {
|
||||
unsigned group;
|
||||
if (value == NULL || len < sizeof(group)) {
|
||||
errno = value == NULL ? EFAULT : EINVAL;
|
||||
return -1;
|
||||
}
|
||||
memcpy(&group, value, sizeof(group));
|
||||
if (group == 0 || group > RTNLGRP_MAX) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
if (group > 64) return 0;
|
||||
uint64_t bit = (uint64_t) 1 << (group - 1);
|
||||
return nl_set_groups(fd, ~bit, option == NETLINK_ADD_MEMBERSHIP ? bit : 0);
|
||||
}
|
||||
|
||||
int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) {
|
||||
struct sockaddr_nl nl;
|
||||
socklen_t size;
|
||||
@@ -1373,6 +1455,7 @@ int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) {
|
||||
memset(&nl, 0, sizeof(nl));
|
||||
nl.nl_family = AF_NETLINK;
|
||||
nl.nl_pid = nl_port_of(fd);
|
||||
nl.nl_groups = nl_groups_of(fd);
|
||||
size = *len < sizeof(nl) ? *len : (socklen_t) sizeof(nl);
|
||||
memcpy(addr, &nl, size);
|
||||
*len = sizeof(nl);
|
||||
@@ -1517,9 +1600,10 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t
|
||||
*rc = real(peer, level, option, value, len);
|
||||
return 1;
|
||||
}
|
||||
if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) {
|
||||
errno = option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP
|
||||
? EACCES : ENOPROTOOPT;
|
||||
if (option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP) {
|
||||
*rc = nl_membership(fd, option, value, len);
|
||||
} else if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) {
|
||||
errno = ENOPROTOOPT;
|
||||
*rc = -1;
|
||||
} else if (value == NULL || len < sizeof(int)) {
|
||||
errno = value == NULL ? EFAULT : EINVAL;
|
||||
@@ -1530,7 +1614,7 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t
|
||||
memcpy(&enabled, value, sizeof(enabled));
|
||||
pthread_mutex_lock(&nl_sockets_lock);
|
||||
struct nl_fd *entry = nl_find(fd);
|
||||
if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0) != 0) {
|
||||
if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0, entry->socket->groups) != 0) {
|
||||
pthread_mutex_unlock(&nl_sockets_lock);
|
||||
*rc = -1;
|
||||
return 1;
|
||||
|
||||
@@ -17,6 +17,7 @@ int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidde
|
||||
const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
|
||||
int dd_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int dd_vdec_open(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
|
||||
int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
|
||||
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
|
||||
|
||||
@@ -62,7 +63,7 @@ static int open_from(const char *path, int flags, mode_t mode, const void *calle
|
||||
fd = dd_dircache_create(AT_FDCWD, path, flags, mode, via_open);
|
||||
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
|
||||
if (fd < 0 && dd_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
|
||||
return fd;
|
||||
return dd_net_open(path, flags, fd);
|
||||
}
|
||||
|
||||
static int openat_from(int dirfd, const char *path, int flags, mode_t mode, const void *caller) {
|
||||
@@ -85,7 +86,7 @@ static int openat_from(int dirfd, const char *path, int flags, mode_t mode, cons
|
||||
fd = dd_dircache_create(dirfd, path, flags, mode, via_openat);
|
||||
if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
|
||||
if (fd < 0 && dd_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
|
||||
return fd;
|
||||
return dd_net_open(path, flags, fd);
|
||||
}
|
||||
|
||||
int open(const char *path, int flags, ...) {
|
||||
|
||||
@@ -72,15 +72,12 @@ static int read_only_copy(const char *data, size_t len, int flags) {
|
||||
return ro;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
static __attribute__((noinline)) int status_copy(const char *path, int flags, long pid) {
|
||||
char text[STATUS_MAX];
|
||||
size_t len = 0;
|
||||
int saved = errno;
|
||||
int out = -1;
|
||||
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller))
|
||||
return -1;
|
||||
// through the next open(): the native userland's hook gives the app's ids as root's there
|
||||
static int (*next_open)(const char *, int, ...) = NULL;
|
||||
if (!next_open) next_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
|
||||
@@ -116,3 +113,10 @@ done:
|
||||
errno = saved;
|
||||
return out;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller))
|
||||
return -1;
|
||||
return status_copy(path, flags, pid);
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <sys/stat.h>
|
||||
#include <endian.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct stand_in {
|
||||
@@ -40,6 +41,19 @@ static ino_t socket_inode(int fd) {
|
||||
return fstat(fd, &st) == 0 ? st.st_ino : 0;
|
||||
}
|
||||
|
||||
static struct stand_in *available_stand_in(void) {
|
||||
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
|
||||
struct stand_in *entry = &stand_ins[i];
|
||||
if (entry->fd == -1) return entry;
|
||||
if (entry->inode != socket_inode(entry->fd)) {
|
||||
close(entry->peer);
|
||||
entry->fd = -1;
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int is_stand_in(int fd) {
|
||||
int found = 0;
|
||||
if (fd < 0)
|
||||
@@ -86,14 +100,11 @@ static int make_stand_in(int type) {
|
||||
}
|
||||
fcntl(sv[1], F_SETFD, FD_CLOEXEC);
|
||||
pthread_mutex_lock(&lock);
|
||||
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
|
||||
if (stand_ins[i].fd == -1) {
|
||||
stand_ins[i].fd = sv[0];
|
||||
stand_ins[i].peer = sv[1];
|
||||
stand_ins[i].inode = socket_inode(sv[0]);
|
||||
pthread_mutex_unlock(&lock);
|
||||
return sv[0];
|
||||
}
|
||||
struct stand_in *entry = available_stand_in();
|
||||
if (entry != NULL) {
|
||||
*entry = (struct stand_in){.fd = sv[0], .peer = sv[1], .inode = socket_inode(sv[0])};
|
||||
pthread_mutex_unlock(&lock);
|
||||
return sv[0];
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
close(sv[0]);
|
||||
@@ -146,6 +157,58 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) {
|
||||
return is_stand_in(fd);
|
||||
}
|
||||
|
||||
static int subscribed(int fd) {
|
||||
#ifdef UDEVMON_TEST
|
||||
if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0;
|
||||
#endif
|
||||
struct sockaddr_nl nl;
|
||||
socklen_t len = sizeof(nl);
|
||||
memset(&nl, 0, sizeof(nl));
|
||||
return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0;
|
||||
}
|
||||
|
||||
/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none
|
||||
when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under
|
||||
the same descriptor, by a stand-in. */
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
|
||||
int (*real_bind)(int, const struct sockaddr *, socklen_t),
|
||||
int *rc) {
|
||||
int protocol = -1;
|
||||
socklen_t protocol_len = sizeof(protocol);
|
||||
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0;
|
||||
if (is_stand_in(fd) || is_wine_process()) return 0;
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT)
|
||||
return 0;
|
||||
*rc = real_bind(fd, addr, len);
|
||||
int refused = errno;
|
||||
if (subscribed(fd)) {
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
int status = fcntl(fd, F_GETFL);
|
||||
int descriptor = fcntl(fd, F_GETFD);
|
||||
int sv[2];
|
||||
if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) {
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
pthread_mutex_lock(&lock);
|
||||
struct stand_in *entry = available_stand_in();
|
||||
if (entry == NULL || dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) {
|
||||
pthread_mutex_unlock(&lock);
|
||||
close(sv[0]);
|
||||
close(sv[1]);
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
close(sv[0]);
|
||||
if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
|
||||
*entry = (struct stand_in){.fd = fd, .peer = sv[1], .inode = socket_inode(fd)};
|
||||
pthread_mutex_unlock(&lock);
|
||||
*rc = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
|
||||
static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
|
||||
struct sockaddr_nl nl;
|
||||
|
||||
@@ -29,6 +29,8 @@
|
||||
#define VDEC_BITSTREAM_SIZE (4u << 20)
|
||||
#define VDEC_PADDING 64
|
||||
#define VDEC_DUMB 64
|
||||
#define VDEC_CAP_MIN_WIDTH 4096u
|
||||
#define VDEC_CAP_MIN_HEIGHT 2304u
|
||||
|
||||
struct vd_dma_heap_alloc {
|
||||
uint64_t len;
|
||||
@@ -135,6 +137,8 @@ struct vdec {
|
||||
uint32_t n_cap_done;
|
||||
int out_on, cap_on;
|
||||
int sock, hw, hw_failed;
|
||||
int resizing;
|
||||
uint32_t stream_w, stream_h;
|
||||
int64_t pts;
|
||||
void *ctx, *packet, *frame;
|
||||
uint8_t *packet_data;
|
||||
@@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) {
|
||||
if (sock < 0) return -1;
|
||||
struct vdec_config c = {
|
||||
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
|
||||
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
|
||||
.width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width,
|
||||
.height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height,
|
||||
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
|
||||
};
|
||||
struct vdec_result r;
|
||||
@@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
|
||||
t.fourcc = p->pixelformat;
|
||||
t.width = p->width;
|
||||
t.height = p->height;
|
||||
t.stream_w = p->width;
|
||||
t.stream_h = p->height;
|
||||
} else {
|
||||
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
|
||||
if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH;
|
||||
if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT;
|
||||
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
|
||||
t.cap_width = (w + 15) & ~15u;
|
||||
t.cap_height = (h + 15) & ~15u;
|
||||
@@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
|
||||
if (apply) {
|
||||
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
|
||||
*v = t;
|
||||
if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0;
|
||||
}
|
||||
vd_fill_format(&t, f);
|
||||
return 0;
|
||||
@@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct vd_bits {
|
||||
const uint8_t *data;
|
||||
size_t size, pos;
|
||||
};
|
||||
|
||||
static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) {
|
||||
uint32_t value = 0;
|
||||
while (count--) {
|
||||
size_t byte = b->pos >> 3;
|
||||
value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u);
|
||||
b->pos++;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static uint32_t vd_get_ue(struct vd_bits *b) {
|
||||
unsigned zeros = 0;
|
||||
while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++;
|
||||
if (zeros >= 32) return 0;
|
||||
return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0);
|
||||
}
|
||||
|
||||
static int32_t vd_get_se(struct vd_bits *b) {
|
||||
uint32_t k = vd_get_ue(b);
|
||||
return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2);
|
||||
}
|
||||
|
||||
static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) {
|
||||
int32_t last = 8, next = 8;
|
||||
for (unsigned i = 0; i < size; i++) {
|
||||
if (next != 0) {
|
||||
int32_t delta = vd_get_se(b);
|
||||
if (delta < -128 || delta > 127) return -1;
|
||||
next = (last + delta + 256) % 256;
|
||||
}
|
||||
last = next == 0 ? last : next;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */
|
||||
static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
|
||||
uint8_t buf[512];
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; i < size && n < sizeof buf; i++) {
|
||||
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
|
||||
buf[n++] = rbsp[i];
|
||||
}
|
||||
struct vd_bits b = { buf, n, 0 };
|
||||
uint32_t profile = vd_get_bits(&b, 8);
|
||||
vd_get_bits(&b, 16);
|
||||
vd_get_ue(&b);
|
||||
uint32_t chroma = 1;
|
||||
if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 ||
|
||||
profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) {
|
||||
chroma = vd_get_ue(&b);
|
||||
if (chroma == 3) vd_get_bits(&b, 1);
|
||||
vd_get_ue(&b);
|
||||
vd_get_ue(&b);
|
||||
vd_get_bits(&b, 1);
|
||||
if (vd_get_bits(&b, 1)) {
|
||||
for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++)
|
||||
if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1;
|
||||
}
|
||||
}
|
||||
vd_get_ue(&b);
|
||||
uint32_t poc = vd_get_ue(&b);
|
||||
if (poc == 0) {
|
||||
vd_get_ue(&b);
|
||||
} else if (poc == 1) {
|
||||
vd_get_bits(&b, 1);
|
||||
vd_get_se(&b);
|
||||
vd_get_se(&b);
|
||||
uint32_t cycle = vd_get_ue(&b);
|
||||
for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b);
|
||||
}
|
||||
vd_get_ue(&b);
|
||||
vd_get_bits(&b, 1);
|
||||
uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1;
|
||||
if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1;
|
||||
uint32_t frame_mbs_only = vd_get_bits(&b, 1);
|
||||
if (b.pos > b.size * 8) return -1;
|
||||
*width = mbs_wide * 16;
|
||||
*height = map_units_high * 16 * (2 - frame_mbs_only);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */
|
||||
static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
|
||||
for (size_t i = 0; i + 4 < size; i++) {
|
||||
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue;
|
||||
size_t start = i + 4, end = start;
|
||||
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
|
||||
if (end + 2 >= size) end = size;
|
||||
return vd_parse_sps_h264(data + start, end - start, width, height);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */
|
||||
static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
|
||||
uint8_t buf[512];
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; i < size && n < sizeof buf; i++) {
|
||||
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
|
||||
buf[n++] = rbsp[i];
|
||||
}
|
||||
struct vd_bits b = { buf, n, 0 };
|
||||
vd_get_bits(&b, 4);
|
||||
uint32_t sub_layers = vd_get_bits(&b, 3);
|
||||
vd_get_bits(&b, 1);
|
||||
for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8);
|
||||
vd_get_bits(&b, 8);
|
||||
uint32_t profile_present = 0, level_present = 0;
|
||||
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
|
||||
profile_present |= vd_get_bits(&b, 1) << i;
|
||||
level_present |= vd_get_bits(&b, 1) << i;
|
||||
}
|
||||
if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2);
|
||||
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
|
||||
if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8);
|
||||
if (level_present >> i & 1) vd_get_bits(&b, 8);
|
||||
}
|
||||
vd_get_ue(&b);
|
||||
if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1);
|
||||
uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b);
|
||||
if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1;
|
||||
*width = (w + 15) & ~15u;
|
||||
*height = (h + 15) & ~15u;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
|
||||
for (size_t i = 0; i + 5 < size; i++) {
|
||||
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue;
|
||||
size_t start = i + 5, end = start;
|
||||
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
|
||||
if (end + 2 >= size) end = size;
|
||||
return vd_parse_sps_h265(data + start, end - start, width, height);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* A stream can change its picture size without telling the client: the host switches games or the window
|
||||
* becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which
|
||||
* the client polls; the capture buffers it already allocated stay at the old size until it reconfigures.
|
||||
*/
|
||||
static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) {
|
||||
uint32_t width, height;
|
||||
int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height)
|
||||
: vd_stream_size_h264(data, size, &width, &height);
|
||||
if (found != 0) return 0;
|
||||
uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height;
|
||||
if (width == known_w && height == known_h) return 0;
|
||||
vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h);
|
||||
if (width <= v->cap_width && height <= v->cap_height) {
|
||||
/* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */
|
||||
v->stream_w = width;
|
||||
v->stream_h = height;
|
||||
if (v->hw) vd_close_decoder(v);
|
||||
return 1;
|
||||
}
|
||||
v->width = v->stream_w = width;
|
||||
v->height = v->stream_h = height;
|
||||
v->resizing = 1;
|
||||
v->n_cap_done = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
|
||||
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
|
||||
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
|
||||
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
|
||||
uint32_t bytes = b->m.planes[0].bytesused;
|
||||
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
|
||||
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
|
||||
if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes);
|
||||
if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp);
|
||||
v->out_done[v->n_out_done++] = b->index;
|
||||
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
|
||||
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
|
||||
@@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
|
||||
return 0;
|
||||
}
|
||||
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
|
||||
if (v->n_cap_done == 0) return -EAGAIN;
|
||||
struct vd_done d = v->cap_done[0];
|
||||
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
|
||||
struct vd_done d;
|
||||
for (;;) {
|
||||
if (v->n_cap_done == 0) return -EAGAIN;
|
||||
d = v->cap_done[0];
|
||||
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
|
||||
struct stat st;
|
||||
struct vd_capture *c = &v->cap[d.index];
|
||||
if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break;
|
||||
}
|
||||
b->index = d.index;
|
||||
b->memory = V4L2_MEMORY_DMABUF;
|
||||
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
|
||||
|
||||
@@ -26,40 +26,83 @@ static char *join_features(const char *have, const char *add) {
|
||||
return strcat(out, add);
|
||||
}
|
||||
|
||||
static int electron_node_mode(char *const envp[]) {
|
||||
static const char variable[] = "ELECTRON_RUN_AS_NODE=";
|
||||
static const char *env_value(char *const envp[], const char *variable) {
|
||||
size_t n = strlen(variable);
|
||||
for (int i = 0; envp && envp[i]; i++)
|
||||
if (!strncmp(envp[i], variable, sizeof variable - 1))
|
||||
return envp[i][sizeof variable - 1] != 0;
|
||||
return 0;
|
||||
if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static char *const *chromium_argv(const char *path, char *const argv[]) {
|
||||
const char *slash = path ? strrchr(path, '/') : NULL;
|
||||
if (!slash || !argv || !argv[0]) return argv;
|
||||
int argc = 0;
|
||||
for (; argv[argc]; argc++)
|
||||
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
|
||||
size_t dir = (size_t)(slash - path) + 1;
|
||||
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
|
||||
if (!sandbox) return argv;
|
||||
memcpy(sandbox, path, dir);
|
||||
strcpy(sandbox + dir, "chrome-sandbox");
|
||||
int chromium = access(sandbox, F_OK) == 0;
|
||||
free(sandbox);
|
||||
if (!chromium) return argv;
|
||||
char **out = calloc((size_t)argc + 2, sizeof *out);
|
||||
static int electron_node_mode(char *const envp[]) {
|
||||
const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE");
|
||||
return mode && *mode;
|
||||
}
|
||||
|
||||
static int beside_chrome_sandbox(const char *path) {
|
||||
char *real = realpath(path, NULL);
|
||||
if (!real) return 0;
|
||||
int found = 0;
|
||||
for (int up = 0; up < 2 && !found; up++) {
|
||||
char *slash = strrchr(real, '/');
|
||||
if (!slash) break;
|
||||
*slash = 0;
|
||||
size_t dir = strlen(real);
|
||||
char *sandbox = malloc(dir + sizeof "/chrome-sandbox");
|
||||
if (!sandbox) break;
|
||||
memcpy(sandbox, real, dir);
|
||||
strcpy(sandbox + dir, "/chrome-sandbox");
|
||||
found = access(sandbox, F_OK) == 0;
|
||||
free(sandbox);
|
||||
}
|
||||
free(real);
|
||||
return found;
|
||||
}
|
||||
|
||||
static char *folder_of(const char *path) {
|
||||
char *real = realpath(path, NULL);
|
||||
char *slash = real ? strrchr(real, '/') : NULL;
|
||||
if (slash) *slash = 0;
|
||||
return real;
|
||||
}
|
||||
|
||||
static int started_by_its_own_app(const char *path) {
|
||||
char self[4096];
|
||||
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
|
||||
if (n <= 0) return 0;
|
||||
self[n] = 0;
|
||||
char *mine = folder_of(self), *theirs = folder_of(path);
|
||||
int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self);
|
||||
free(mine);
|
||||
free(theirs);
|
||||
return same;
|
||||
}
|
||||
|
||||
static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) {
|
||||
if (!path || !argv || !argv[0]) return argv;
|
||||
int argc = 0, sandbox = 1, ozone = 0;
|
||||
for (; argv[argc]; argc++) {
|
||||
if (!argc) continue;
|
||||
if (!strncmp(argv[argc], "--type=", 7)) return argv;
|
||||
if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0;
|
||||
if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1;
|
||||
}
|
||||
const char *display = env_value(envp, "DISPLAY");
|
||||
int x11 = !ozone && display && *display;
|
||||
if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv;
|
||||
char **out = calloc((size_t)argc + 3, sizeof *out);
|
||||
if (!out) return argv;
|
||||
out[0] = argv[0];
|
||||
out[1] = (char *)"--no-sandbox";
|
||||
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
|
||||
int n = 0;
|
||||
out[n++] = argv[0];
|
||||
if (sandbox) out[n++] = (char *)"--no-sandbox";
|
||||
if (x11) out[n++] = (char *)"--ozone-platform=x11";
|
||||
for (int i = 1; i < argc; i++) out[n++] = argv[i];
|
||||
return out;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) {
|
||||
if (electron_node_mode(envp)) return argv;
|
||||
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
|
||||
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp);
|
||||
const char *spec = getenv("DD_WEBHELPER_ARGS");
|
||||
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
|
||||
if (!strcmp(spec, "stock")) return argv;
|
||||
|
||||
+258
-54
@@ -1,8 +1,9 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#pragma GCC optimize("no-stack-protector", "no-tree-loop-distribute-patterns")
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
@@ -10,6 +11,9 @@
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#if defined(__i386__)
|
||||
#include <asm/ldt.h>
|
||||
#endif
|
||||
#include <unistd.h>
|
||||
|
||||
|
||||
@@ -31,13 +35,156 @@
|
||||
#define ZR_INLINE_CHUNKS 512UL
|
||||
#define ZR_FAILED (~0UL)
|
||||
#define ZR_FUTEX_WAIT 0
|
||||
#define ZR_FUTEX_WAKE 1
|
||||
#define ZR_STACK (128UL << 10)
|
||||
#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \
|
||||
CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID)
|
||||
#define ZR_TEXT(x) #x
|
||||
#define ZR_NR(x) ZR_TEXT(x)
|
||||
#define ZR_CALL(n, a, b, c, d, e, f, ...) \
|
||||
zr_call((long)(n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f))
|
||||
#define zr_sys(...) ZR_CALL(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0)
|
||||
|
||||
#if defined(__aarch64__)
|
||||
#define ZR_MMAP SYS_mmap
|
||||
__asm__(".pushsection .text\n"
|
||||
".p2align 2\n"
|
||||
".hidden zr_call\n"
|
||||
".type zr_call, %function\n"
|
||||
"zr_call:\n"
|
||||
" mov x8, x0\n"
|
||||
" mov x0, x1\n"
|
||||
" mov x1, x2\n"
|
||||
" mov x2, x3\n"
|
||||
" mov x3, x4\n"
|
||||
" mov x4, x5\n"
|
||||
" mov x5, x6\n"
|
||||
" svc #0\n"
|
||||
" ret\n"
|
||||
".size zr_call, . - zr_call\n"
|
||||
".hidden zr_clone\n"
|
||||
".type zr_clone, %function\n"
|
||||
"zr_clone:\n"
|
||||
" mov x5, x2\n"
|
||||
" mov x2, x3\n"
|
||||
" mov x3, x4\n"
|
||||
" mov x4, x5\n"
|
||||
" mov x8, #" ZR_NR(SYS_clone) "\n"
|
||||
" svc #0\n"
|
||||
" cbnz x0, 1f\n"
|
||||
" mov x29, xzr\n"
|
||||
" mov x30, xzr\n"
|
||||
" bl zr_thread\n"
|
||||
" mov x0, xzr\n"
|
||||
" mov x8, #" ZR_NR(SYS_exit) "\n"
|
||||
" svc #0\n"
|
||||
" brk #0\n"
|
||||
"1:\n"
|
||||
" ret\n"
|
||||
".size zr_clone, . - zr_clone\n"
|
||||
".popsection\n");
|
||||
#elif defined(__x86_64__)
|
||||
#define ZR_MMAP SYS_mmap
|
||||
__asm__(".pushsection .text\n"
|
||||
".p2align 4\n"
|
||||
".hidden zr_call\n"
|
||||
".type zr_call, @function\n"
|
||||
"zr_call:\n"
|
||||
" mov %rdi, %rax\n"
|
||||
" mov %rsi, %rdi\n"
|
||||
" mov %rdx, %rsi\n"
|
||||
" mov %rcx, %rdx\n"
|
||||
" mov %r8, %r10\n"
|
||||
" mov %r9, %r8\n"
|
||||
" mov 8(%rsp), %r9\n"
|
||||
" syscall\n"
|
||||
" ret\n"
|
||||
".size zr_call, . - zr_call\n"
|
||||
".hidden zr_clone\n"
|
||||
".type zr_clone, @function\n"
|
||||
"zr_clone:\n"
|
||||
" mov %rdx, %r10\n"
|
||||
" mov %rcx, %rdx\n"
|
||||
" mov $" ZR_NR(SYS_clone) ", %eax\n"
|
||||
" syscall\n"
|
||||
" test %rax, %rax\n"
|
||||
" jnz 1f\n"
|
||||
" xor %ebp, %ebp\n"
|
||||
" call zr_thread\n"
|
||||
" xor %edi, %edi\n"
|
||||
" mov $" ZR_NR(SYS_exit) ", %eax\n"
|
||||
" syscall\n"
|
||||
" hlt\n"
|
||||
"1:\n"
|
||||
" ret\n"
|
||||
".size zr_clone, . - zr_clone\n"
|
||||
".popsection\n");
|
||||
#elif defined(__i386__)
|
||||
#define ZR_MMAP SYS_mmap2
|
||||
__asm__(".pushsection .text\n"
|
||||
".p2align 4\n"
|
||||
".hidden zr_call\n"
|
||||
".type zr_call, @function\n"
|
||||
"zr_call:\n"
|
||||
" push %ebp\n"
|
||||
" push %edi\n"
|
||||
" push %esi\n"
|
||||
" push %ebx\n"
|
||||
" mov 20(%esp), %eax\n"
|
||||
" mov 24(%esp), %ebx\n"
|
||||
" mov 28(%esp), %ecx\n"
|
||||
" mov 32(%esp), %edx\n"
|
||||
" mov 36(%esp), %esi\n"
|
||||
" mov 40(%esp), %edi\n"
|
||||
" mov 44(%esp), %ebp\n"
|
||||
" int $0x80\n"
|
||||
" pop %ebx\n"
|
||||
" pop %esi\n"
|
||||
" pop %edi\n"
|
||||
" pop %ebp\n"
|
||||
" ret\n"
|
||||
".size zr_call, . - zr_call\n"
|
||||
".hidden zr_clone\n"
|
||||
".type zr_clone, @function\n"
|
||||
"zr_clone:\n"
|
||||
" push %ebx\n"
|
||||
" push %esi\n"
|
||||
" push %edi\n"
|
||||
" mov 16(%esp), %ebx\n"
|
||||
" mov 20(%esp), %ecx\n"
|
||||
" mov 24(%esp), %edi\n"
|
||||
" mov 28(%esp), %edx\n"
|
||||
" mov 32(%esp), %esi\n"
|
||||
" mov $" ZR_NR(SYS_clone) ", %eax\n"
|
||||
" int $0x80\n"
|
||||
" test %eax, %eax\n"
|
||||
" jnz 1f\n"
|
||||
" xor %ebp, %ebp\n"
|
||||
" call zr_thread\n"
|
||||
" xor %ebx, %ebx\n"
|
||||
" mov $" ZR_NR(SYS_exit) ", %eax\n"
|
||||
" int $0x80\n"
|
||||
" hlt\n"
|
||||
"1:\n"
|
||||
" pop %edi\n"
|
||||
" pop %esi\n"
|
||||
" pop %ebx\n"
|
||||
" ret\n"
|
||||
".size zr_clone, . - zr_clone\n"
|
||||
".popsection\n");
|
||||
#else
|
||||
#error "zram.c needs a raw system call for this architecture"
|
||||
#endif
|
||||
|
||||
long zr_call(long n, long a, long b, long c, long d, long e, long f) __attribute__((visibility("hidden")));
|
||||
long zr_clone(long flags, char *stack, int *child, int *parent, void *tls) __attribute__((visibility("hidden")));
|
||||
void zr_thread(void) __attribute__((visibility("hidden")));
|
||||
|
||||
static long (*zr_sys)(long, ...);
|
||||
static unsigned long zr_page;
|
||||
static int zr_busy;
|
||||
static int zr_pending;
|
||||
static int zr_worker;
|
||||
static unsigned zr_requests;
|
||||
static int zr_stack_busy;
|
||||
static int zr_tid;
|
||||
static long zr_filters;
|
||||
static char *zr_stack;
|
||||
static char zr_maps[8192];
|
||||
static uint64_t zr_entries[ZR_BATCH];
|
||||
static struct iovec zr_iov[ZR_BATCH];
|
||||
@@ -54,6 +201,18 @@ static uint16_t zr_gen = 1;
|
||||
static unsigned long zr_cursor;
|
||||
static unsigned long zr_visits;
|
||||
|
||||
static int zr_prefix(const char *text, const char *prefix) {
|
||||
while (*prefix)
|
||||
if (*text++ != *prefix++) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static char *zr_find(char *text, char c, size_t n) {
|
||||
for (; n > 0; n--, text++)
|
||||
if (*text == c) return text;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int zr_open(const char *path) {
|
||||
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
|
||||
}
|
||||
@@ -103,7 +262,7 @@ static int zr_eligible(const char *line, int compress, unsigned long *start, uns
|
||||
while (*p && *p != ' ') p++;
|
||||
while (*p == ' ') p++;
|
||||
}
|
||||
return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0;
|
||||
return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[anon:");
|
||||
}
|
||||
|
||||
static void zr_read_back(int pagemap, unsigned long start, unsigned long end) {
|
||||
@@ -137,7 +296,7 @@ static unsigned long zr_count(int pagemap, unsigned long start, unsigned long en
|
||||
do {
|
||||
if (zr_sys(SYS_lseek, pagemap, (long)(start / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return ZR_FAILED;
|
||||
got = zr_sys(SYS_read, pagemap, zr_entries, size);
|
||||
} while (got < 0 && errno == EINTR);
|
||||
} while (got == -EINTR);
|
||||
if (got != size) return ZR_FAILED;
|
||||
for (long i = 0; i < got / (long)sizeof(uint64_t); i++)
|
||||
if (zr_entries[i] & bit) count++;
|
||||
@@ -157,8 +316,7 @@ static struct zr_slot *zr_slot(unsigned long addr, int create) {
|
||||
}
|
||||
}
|
||||
if (!create) return NULL;
|
||||
memset(&zr_slots[home], 0, sizeof(zr_slots[home]));
|
||||
zr_slots[home].key = key;
|
||||
zr_slots[home] = (struct zr_slot){.key = key};
|
||||
return &zr_slots[home];
|
||||
}
|
||||
|
||||
@@ -228,13 +386,13 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
|
||||
size_t have = 0;
|
||||
while (done < want && zr_visits > 0) {
|
||||
long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n == -EINTR) continue;
|
||||
if (n <= 0) break;
|
||||
have += (size_t)n;
|
||||
zr_maps[have] = 0;
|
||||
char *line = zr_maps;
|
||||
char *nl;
|
||||
while (done < want && zr_visits > 0 && (nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
|
||||
while (done < want && zr_visits > 0 && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
|
||||
*nl = 0;
|
||||
unsigned long s, e;
|
||||
if (zr_eligible(line, mode != 0, &s, &e) && e > s) {
|
||||
@@ -245,7 +403,7 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
|
||||
line = nl + 1;
|
||||
}
|
||||
have -= (size_t)(line - zr_maps);
|
||||
memmove(zr_maps, line, have);
|
||||
for (size_t i = 0; i < have; i++) zr_maps[i] = line[i];
|
||||
if (have == sizeof(zr_maps) - 1) have = 0;
|
||||
}
|
||||
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
|
||||
@@ -291,15 +449,88 @@ static void zr_request(int worker) {
|
||||
zr_ack((long)(done * (zr_page / 1024)), 1);
|
||||
}
|
||||
|
||||
static void *zr_worker_main(void *unused) {
|
||||
(void)unused;
|
||||
prctl(PR_SET_NAME, "zr-worker", 0, 0, 0);
|
||||
for (;;) {
|
||||
while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST))
|
||||
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0);
|
||||
zr_request(1);
|
||||
static void zr_drain(int worker) {
|
||||
unsigned seen;
|
||||
do {
|
||||
seen = __atomic_load_n(&zr_requests, __ATOMIC_ACQUIRE);
|
||||
zr_request(worker);
|
||||
} while (!__atomic_compare_exchange_n(&zr_requests, &seen, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE));
|
||||
}
|
||||
|
||||
void zr_thread(void) {
|
||||
zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker");
|
||||
zr_drain(1);
|
||||
}
|
||||
|
||||
static void *zr_tls(void *desc) {
|
||||
#if defined(__aarch64__)
|
||||
(void)desc;
|
||||
return __builtin_thread_pointer();
|
||||
#elif defined(__x86_64__)
|
||||
(void)desc;
|
||||
void *self;
|
||||
__asm__("mov %%fs:0, %0" : "=r"(self));
|
||||
return self;
|
||||
#else
|
||||
struct user_desc *entry = desc;
|
||||
unsigned short selector;
|
||||
__asm__("mov %%gs, %0" : "=r"(selector));
|
||||
entry->entry_number = selector >> 3;
|
||||
return zr_sys(SYS_get_thread_area, entry) == 0 ? entry : NULL;
|
||||
#endif
|
||||
}
|
||||
|
||||
static long zr_field(const char *text, const char *key) {
|
||||
for (const char *line = text; *line; line++) {
|
||||
if ((line == text || line[-1] == '\n') && zr_prefix(line, key)) {
|
||||
long value = 0;
|
||||
for (const char *k = key; *k; k++) line++;
|
||||
while (*line == ' ' || *line == '\t') line++;
|
||||
for (; *line >= '0' && *line <= '9'; line++) value = value * 10 + (*line - '0');
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int zr_status(long *threads, long *filters) {
|
||||
int fd = zr_open("/proc/thread-self/status");
|
||||
if (fd < 0) return 0;
|
||||
long have = 0, n;
|
||||
while (have < (long)sizeof(zr_maps) - 1 &&
|
||||
((n = zr_sys(SYS_read, fd, zr_maps + have, sizeof(zr_maps) - 1 - (size_t)have)) > 0 || n == -EINTR))
|
||||
if (n > 0) have += n;
|
||||
zr_sys(SYS_close, fd);
|
||||
zr_maps[have] = 0;
|
||||
*threads = zr_field(zr_maps, "Threads:");
|
||||
*filters = zr_field(zr_maps, "Seccomp_filters:");
|
||||
return have > 0;
|
||||
}
|
||||
|
||||
static int zr_start(void) {
|
||||
long threads, filters;
|
||||
if (!zr_status(&threads, &filters) || threads < 2 || filters > zr_filters) return 0;
|
||||
if (zr_stack == NULL) {
|
||||
long base = zr_sys(ZR_MMAP, 0, ZR_STACK, PROT_READ | PROT_WRITE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
|
||||
if ((unsigned long)base > -4096UL) return 0;
|
||||
zr_stack = (char *)base;
|
||||
}
|
||||
struct { long sec, nsec; } wait = {0, 5000000};
|
||||
for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++)
|
||||
zr_sys(SYS_futex, &zr_stack_busy, ZR_FUTEX_WAIT, 1, &wait, NULL, 0);
|
||||
if (__atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE)) return 0;
|
||||
uint64_t desc[4] = {0};
|
||||
void *tls = zr_tls(desc);
|
||||
if (tls == NULL) return 0;
|
||||
uint64_t all = ~0ULL, previous;
|
||||
if (zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &all, &previous, sizeof(all)) != 0) return 0;
|
||||
__atomic_store_n(&zr_stack_busy, 1, __ATOMIC_RELEASE);
|
||||
long tid = zr_clone(ZR_THREAD, zr_stack + ZR_STACK, &zr_stack_busy, &zr_tid, tls);
|
||||
zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &previous, NULL, sizeof(previous));
|
||||
if (tid > 0) return 1;
|
||||
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
@@ -307,34 +538,23 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)context;
|
||||
if (info == NULL || info->si_code != SI_USER) return;
|
||||
int saved = errno;
|
||||
__atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST);
|
||||
if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) {
|
||||
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0);
|
||||
} else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST)
|
||||
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
zr_request(0);
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
static void zr_child(void) {
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD);
|
||||
if (libc == NULL) return;
|
||||
zr_sys = (long (*)(long, ...))dlsym(libc, "syscall");
|
||||
if (zr_sys == NULL) return;
|
||||
int fd = zr_open(ZR_CTL);
|
||||
if (fd < 0) return;
|
||||
zr_sys(SYS_close, fd);
|
||||
long page = sysconf(_SC_PAGESIZE);
|
||||
zr_page = page > 0 ? (unsigned long)page : 4096UL;
|
||||
long threads;
|
||||
if (!zr_status(&threads, &zr_filters)) zr_filters = -1;
|
||||
struct sigaction old;
|
||||
if (sigaction(SIGURG, NULL, &old) != 0) return;
|
||||
if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return;
|
||||
@@ -343,21 +563,5 @@ __attribute__((constructor)) static void zr_init(void) {
|
||||
sa.sa_sigaction = zr_handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(SIGURG, &sa, NULL) == 0) {
|
||||
pthread_atfork(NULL, NULL, zr_child);
|
||||
pthread_attr_t attr;
|
||||
if (pthread_attr_init(&attr) == 0) {
|
||||
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
pthread_t thread;
|
||||
sigset_t blocked;
|
||||
sigset_t previous;
|
||||
if (sigfillset(&blocked) == 0 &&
|
||||
pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) {
|
||||
if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0)
|
||||
__atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE);
|
||||
pthread_sigmask(SIG_SETMASK, &previous, NULL);
|
||||
}
|
||||
pthread_attr_destroy(&attr);
|
||||
}
|
||||
}
|
||||
if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child);
|
||||
}
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
wrapper=${1:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT}
|
||||
output=${2:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT}
|
||||
[ "$(tail -c 32 "$wrapper" | head -c 8)" = "SQUEEZE!" ] || { echo "unwrap-dwarfs.sh: $wrapper has no SQUEEZE! trailer" >&2; exit 1; }
|
||||
packed=$(tail -c 16 "$wrapper" | od -An -tu8 -N8 | tr -d ' ')
|
||||
[ "$packed" -gt 0 ] && [ "$packed" -le $(( $(wc -c < "$wrapper") - 32 )) ] || { echo "unwrap-dwarfs.sh: bad payload size in $wrapper" >&2; exit 1; }
|
||||
tail -c $((packed + 32)) "$wrapper" | head -c "$packed" | zstd -dcq > "$output"
|
||||
@@ -1,3 +1,7 @@
|
||||
URUNTIME_VERSION=v0.8.1
|
||||
URUNTIME_ASSET=uruntime-appimage-lite-aarch64
|
||||
URUNTIME_SHA256=8485ae20eb0bfd4eaeac38d7fd7f78e153b391c718cf33ff07879605683be1ea
|
||||
DWARFS_VERSION=v0.15.7
|
||||
DWARFS_ASSET=dwarfs-fuse-extract-0.15.7-Linux-aarch64
|
||||
DWARFS_SHA256=edb698186db6b162c755770ffabfcc05482bb7105a716fd943548e64244b0fd2
|
||||
DWARFS_PAYLOAD_SHA256=cc3b3e342ca6537139d8c90d3c0a00236cf786bb61bdccf019e5ed0ca5917a7a
|
||||
Reference in new issue
Block a user