mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 23:36:04 +00:00
chore: merge main into feat/lse-emu
This commit is contained in:
commit
83f9067a51
609 files changed
+46314
-8272
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
|
||||
|
||||
@@ -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, "")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}")
|
||||
@@ -321,6 +317,15 @@ def install_path(root, library):
|
||||
return letter.upper() + ":\\" + path[len(target):].strip("/").replace("/", "\\")
|
||||
|
||||
|
||||
def keeps_open(root):
|
||||
try:
|
||||
with open(os.path.join(drive_c(root), *CONFIG), encoding="utf-8-sig") as f:
|
||||
client = json.load(f).get("Client")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return False
|
||||
return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1]
|
||||
|
||||
|
||||
def write_config(root, library=None):
|
||||
path = os.path.join(drive_c(root), *CONFIG)
|
||||
key, value = LAUNCH_BEHAVIOR
|
||||
@@ -338,7 +343,7 @@ def write_config(root, library=None):
|
||||
return None
|
||||
client = config["Client"]
|
||||
changes = []
|
||||
if client.get(key) != value:
|
||||
if key not in client:
|
||||
client[key] = value
|
||||
changes.append("launch")
|
||||
if client.get("HardwareAcceleration") != "false":
|
||||
@@ -770,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 = []
|
||||
@@ -875,6 +854,9 @@ class Tidy:
|
||||
self.game_since = self.game_since if self.game_since is not None else now
|
||||
if own and not self.closed_for_game and now - self.game_since >= self.settle:
|
||||
self.closed_for_game, self.agent_seen, self.agent_lost = True, False, None
|
||||
if keeps_open(steam_root()):
|
||||
say("Battle.net is set to stay open as a game launches: left open")
|
||||
return False
|
||||
if any(is_client(argv) for _, argv in own) and any(shares_sign_in(argv) for argv in games):
|
||||
say("Battle.net stayed open beside a game signing in with its token: left open")
|
||||
return False
|
||||
@@ -1136,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)
|
||||
@@ -1226,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)
|
||||
@@ -1437,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
|
||||
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
|
||||
"libssl.so.3", "libcrypto.so.3",
|
||||
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
|
||||
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
|
||||
))
|
||||
PROVIDED_NEEDS = {
|
||||
"libwayland-client.so.0": ("libffi.so.8",),
|
||||
@@ -670,6 +670,8 @@ def guest_environment(fex, env):
|
||||
result.setdefault("FEX_SILENTLOG", "0")
|
||||
result.setdefault("FEX_OUTPUTLOG", "stderr")
|
||||
result.pop("GLIBC_TUNABLES", None)
|
||||
if "aarch64" in result.get("GCONV_PATH", ""):
|
||||
result["GCONV_PATH"] = ""
|
||||
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
|
||||
if fex["portable"]:
|
||||
result["FEX_PORTABLE"] = "1"
|
||||
|
||||
@@ -14,7 +14,6 @@ from pathlib import Path
|
||||
GAME_PREFIX = "DROIDDECK_GAME_"
|
||||
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
|
||||
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
|
||||
D3D9_DEFAULT_MEMORY_MB = 4096
|
||||
SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
|
||||
PACK_KEYS = ("WINESERVER", "DD_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
|
||||
@@ -86,9 +85,10 @@ def game_files(exe):
|
||||
|
||||
class Game:
|
||||
|
||||
def __init__(self, exe, args):
|
||||
def __init__(self, exe, args, app_id=""):
|
||||
self.exe = exe
|
||||
self.args = args
|
||||
self.app_id = app_id
|
||||
self.stem = os.path.splitext(os.path.basename(exe))[0].lower()
|
||||
self.files = game_files(exe)
|
||||
|
||||
@@ -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 kcd2_feature_level(game):
|
||||
if game.app_id == "1771300":
|
||||
return {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"}, [], "Kingdom Come: Deliverance II: D3D12 feature level 12_2 and shader model 6_9 (the detected level fails its startup check, and 12_0 alone stalls on the splash screen)"
|
||||
|
||||
|
||||
@fix
|
||||
def arkham_city_x87(game):
|
||||
if "batmanac.exe" in game.files:
|
||||
@@ -188,6 +200,12 @@ def protonfixes_off(game):
|
||||
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
|
||||
|
||||
|
||||
@fix
|
||||
def black_ops_ii_steam_exec(game):
|
||||
if game.app_id in ("202970", "202990", "212910") or game.stem in ("t6sp", "t6mp", "t6zm"):
|
||||
return {"WINESTEAMNOEXEC": "0"}, [], "Black Ops II: Steam exec handling on (the game does not start without it)"
|
||||
|
||||
|
||||
@fix
|
||||
def little_nightmares_threads(game):
|
||||
if game.stem == "littlenightmares":
|
||||
@@ -367,8 +385,8 @@ def offline_without_anticheat(command, env):
|
||||
return command[:2] + [game] + command[3:]
|
||||
|
||||
|
||||
def engine_fixes(exe, args):
|
||||
game = Game(exe, args)
|
||||
def engine_fixes(exe, args, app_id=""):
|
||||
game = Game(exe, args, app_id)
|
||||
env, extra, notes = {}, [], []
|
||||
for check in FIXES:
|
||||
found = check(game)
|
||||
@@ -453,18 +471,13 @@ def game_gpu(env, keep=False):
|
||||
return result
|
||||
|
||||
|
||||
def vram_cap(env):
|
||||
value = env.get("DD_VRAM_MB", "")
|
||||
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
|
||||
return env
|
||||
result = env.copy()
|
||||
cap = "dxgi.maxDeviceMemory = {0}; dxgi.maxSharedMemory = {0}".format(int(value))
|
||||
if int(value) < D3D9_DEFAULT_MEMORY_MB:
|
||||
cap += "; d3d9.maxAvailableMemory = {0}".format(int(value))
|
||||
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
|
||||
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
|
||||
result["DROIDDECK_VRAM_CAP"] = "1"
|
||||
result["DROIDDECK_VRAM_CAP_MB"] = value
|
||||
def split_game_gpu(entries):
|
||||
result = dict(entries)
|
||||
for key in GAME_SPLIT_KEYS:
|
||||
if GAME_PREFIX + key in result:
|
||||
value = result.pop(GAME_PREFIX + key)
|
||||
if key not in entries:
|
||||
result[key] = None if value == "" else value
|
||||
return result
|
||||
|
||||
|
||||
@@ -596,12 +609,12 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported environment configuration")
|
||||
result = env.copy()
|
||||
entries = dict(config.get("shared", {}))
|
||||
entries = split_game_gpu(config.get("shared", {}))
|
||||
for name, value in (fixes or {}).items():
|
||||
if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)):
|
||||
value = entries.get(name, env.get(name)) + ";" + value
|
||||
entries[name] = value
|
||||
game = config.get("games", {}).get(app_id, {})
|
||||
game = split_game_gpu(config.get("games", {}).get(app_id, {}))
|
||||
fix = (fixes or {}).get("WINEDLLOVERRIDES")
|
||||
if fix and isinstance(game.get("WINEDLLOVERRIDES"), str):
|
||||
own = game["WINEDLLOVERRIDES"]
|
||||
@@ -1395,7 +1408,7 @@ def main():
|
||||
death_stranding_allocator(app_id, command[2])
|
||||
ubisoft_overlay_off(env)
|
||||
project_zomboid_jvm(command)
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], [])
|
||||
if not gl_default:
|
||||
fixes.pop("vblank_mode", None)
|
||||
for note in notes:
|
||||
@@ -1439,7 +1452,6 @@ def main():
|
||||
if mic_enabled == "0":
|
||||
env["AUDIO_DIRECT_MIC"] = "0"
|
||||
env = directaudio_settings(env)
|
||||
env = vram_cap(env)
|
||||
note = render_path_defaults(command, env) if app_id else None
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
|
||||
+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 -- "$@"
|
||||
@@ -137,6 +137,7 @@ clear_stale_tmp() {
|
||||
[ -z "${DD_INSIDE:-}" ] && clear_stale_tmp
|
||||
if [ -z "${DD_INSIDE:-}" ]; then
|
||||
if [ "${DD_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.dd-zram; else rm -f /tmp/.dd-zram; fi
|
||||
rm -f /tmp/.dd-zram.hold
|
||||
dd if=/dev/zero of=/tmp/.dd-clock bs=8 count=1 conv=notrunc status=none
|
||||
fi
|
||||
|
||||
@@ -761,13 +762,6 @@ case $mode in
|
||||
fi
|
||||
if [ "${DD_ZRAM:-0}" = 1 ]; then
|
||||
step "zRAM compression: on"
|
||||
[ "${DD_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)"
|
||||
_dd_ram_cap=0
|
||||
case ${DD_RAM_CAP_MB:-} in
|
||||
''|0) ;;
|
||||
*[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$DD_RAM_CAP_MB'" ;;
|
||||
*) _dd_ram_cap=$((DD_RAM_CAP_MB * 1024)); step "RAM cap: ${DD_RAM_CAP_MB} MB" ;;
|
||||
esac
|
||||
(
|
||||
dd_zram_scan() {
|
||||
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
|
||||
@@ -844,284 +838,235 @@ case $mode in
|
||||
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
|
||||
}
|
||||
dd_memory_read() {
|
||||
local _k _v _u _kind _fields _avg _whole _frac _gpu_bytes _growth _saved_growth _saved_fall
|
||||
_saved_growth=${_dd_preserved_growth:-0} _saved_fall=${_dd_preserved_fall:-0}
|
||||
_dd_preserved_growth=0 _dd_preserved_fall=0
|
||||
_dd_mem_total=0 _dd_available=-1 _dd_swap_total=0 _dd_swap_free=-1
|
||||
_dd_psi_some=0 _dd_psi_full=0 _dd_gpu=0 _dd_unevictable=0 _dd_shmem=0
|
||||
local _k _v _u _kind _fields _name _type _size _used _orig _comp _mem _dt _fall
|
||||
local _stall=-1 _swap_total=0 _swap_free=0 _total=0 _room=0 _listed=0 _in=-1
|
||||
_dd_mem_total=0 _dd_available=-1
|
||||
while read -r _k _v _u; do
|
||||
case $_v in ''|*[!0-9]*) continue ;; esac
|
||||
case $_k in
|
||||
MemTotal:) _dd_mem_total=$_v ;;
|
||||
MemAvailable:) _dd_available=$_v ;;
|
||||
SwapTotal:) _dd_swap_total=$_v ;;
|
||||
SwapFree:) _dd_swap_free=$_v ;;
|
||||
Unevictable:) _dd_unevictable=$_v ;;
|
||||
Shmem:) _dd_shmem=$_v ;;
|
||||
SwapTotal:) _swap_total=$_v ;;
|
||||
SwapFree:) _swap_free=$_v ;;
|
||||
esac
|
||||
done 2>/dev/null < /proc/meminfo
|
||||
while read -r _name _type _size _used _u; do
|
||||
_listed=1
|
||||
case $_name in */zram[0-9]*) ;; *) continue ;; esac
|
||||
case $_size$_used in ''|*[!0-9]*) continue ;; esac
|
||||
_total=$((_total + _size)) _room=$((_room + _size - _used))
|
||||
done 2>/dev/null < /proc/swaps
|
||||
[ "$_listed" = 1 ] || _total=$_swap_total _room=$_swap_free
|
||||
_dd_swap_room=$((_total / 8))
|
||||
[ "$_dd_swap_room" -ge $((128 * 1024)) ] || _dd_swap_room=$((128 * 1024))
|
||||
_dd_swap_room=$((_room - _dd_swap_room))
|
||||
_dd_saving=600
|
||||
if [ -r /sys/block/zram0/mm_stat ] && read -r _orig _comp _mem _u 2>/dev/null < /sys/block/zram0/mm_stat; then
|
||||
case $_orig$_mem in
|
||||
''|*[!0-9]*) ;;
|
||||
*) [ "$_orig" -lt $((64 << 20)) ] || _dd_saving=$(((_orig - _mem) / (_orig / 1000))) ;;
|
||||
esac
|
||||
[ "$_dd_saving" -ge 167 ] || _dd_saving=167
|
||||
[ "$_dd_saving" -le 833 ] || _dd_saving=833
|
||||
fi
|
||||
if [ -r /proc/pressure/memory ]; then
|
||||
while read -r _kind _fields; do
|
||||
[ "$_kind" = some ] || [ "$_kind" = full ] || continue
|
||||
_avg=${_fields#avg10=} _avg=${_avg%% *}
|
||||
_whole=${_avg%%.*} _frac=${_avg#*.}
|
||||
[ "$_frac" = "$_avg" ] && _frac=00
|
||||
_frac=${_frac}00
|
||||
_frac=${_frac:0:2}
|
||||
case $_whole$_frac in ''|*[!0-9]*) continue ;; esac
|
||||
if [ "$_kind" = some ]; then
|
||||
_dd_psi_some=$((10#$_whole * 100 + 10#$_frac))
|
||||
else
|
||||
_dd_psi_full=$((10#$_whole * 100 + 10#$_frac))
|
||||
fi
|
||||
[ "$_kind" = some ] || continue
|
||||
_fields=${_fields##*total=}
|
||||
case $_fields in ''|*[!0-9]*) ;; *) _stall=$_fields ;; esac
|
||||
done 2>/dev/null < /proc/pressure/memory
|
||||
fi
|
||||
if [ -r /sys/class/kgsl/kgsl/page_alloc ]; then
|
||||
read -r _gpu_bytes _u < /sys/class/kgsl/kgsl/page_alloc
|
||||
case $_gpu_bytes in ''|*[!0-9]*) _gpu_bytes=0 ;; esac
|
||||
_dd_gpu=$((_gpu_bytes / 1024))
|
||||
while read -r _k _v; do
|
||||
[ "$_k" = pswpin ] || continue
|
||||
case $_v in ''|*[!0-9]*) ;; *) _in=$((_v * _dd_page_kb)) ;; esac
|
||||
break
|
||||
done 2>/dev/null < /proc/vmstat
|
||||
_dt=$((SECONDS - ${_dd_sample_at:-$SECONDS}))
|
||||
if [ -z "${_dd_sample_at:-}" ]; then
|
||||
_dd_rate=0 _dd_psi=0 _dd_returned=0
|
||||
elif [ "$_dt" -gt 0 ] && [ "$_dd_available" -ge 0 ]; then
|
||||
_fall=$(((_dd_sample_available - _dd_available + _dd_freed) / _dt))
|
||||
_dd_rate=$((_dd_rate * 3 / 4))
|
||||
[ "$_fall" -le "$_dd_rate" ] || _dd_rate=$_fall
|
||||
_dd_psi=0
|
||||
[ "$_stall" -lt 0 ] || [ "$_dd_sample_stall" -lt 0 ] || _dd_psi=$(((_stall - _dd_sample_stall) / (_dt * 100)))
|
||||
_dd_returned=$((_dt < 30 ? _dd_returned * (30 - _dt) / 30 : 0))
|
||||
[ "$_in" -lt "$_dd_sample_in" ] || [ "$_dd_sample_in" -lt 0 ] || _dd_returned=$((_dd_returned + _in - _dd_sample_in))
|
||||
fi
|
||||
_dd_psi=$_dd_psi_some
|
||||
[ "$_dd_psi_full" -gt "$_dd_psi" ] && _dd_psi=$_dd_psi_full
|
||||
if [ "${_dd_sample_at:-}" = "" ]; then
|
||||
_dd_growth=0 _dd_fall=0
|
||||
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu
|
||||
_dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem
|
||||
elif [ "$SECONDS" -gt "$_dd_sample_at" ]; then
|
||||
_dd_growth=0 _dd_fall=0
|
||||
_growth=$((_dd_gpu - _dd_sample_gpu)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
|
||||
_growth=$((_dd_unevictable - _dd_sample_unevictable)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
|
||||
_growth=$((_dd_shmem - _dd_sample_shmem)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
|
||||
_dd_fall=$((_dd_sample_available - _dd_available))
|
||||
[ "$_saved_growth" -gt "$_dd_growth" ] && _dd_growth=$_saved_growth
|
||||
[ "$_saved_fall" -gt "$_dd_fall" ] && _dd_fall=$_saved_fall
|
||||
if [ $((SECONDS - _dd_sample_at)) -ge 5 ]; then
|
||||
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu
|
||||
_dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem
|
||||
fi
|
||||
if [ "$_dd_available" -ge 0 ] && { [ -z "${_dd_sample_at:-}" ] || [ "$_dt" -gt 0 ]; }; then
|
||||
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_stall=$_stall _dd_sample_in=$_in _dd_freed=0
|
||||
fi
|
||||
_dd_real_available=$_dd_available
|
||||
[ "$_dd_real_available" -ge 0 ] && _dd_real_available=$((_dd_real_available - _dd_growth))
|
||||
_dd_headroom=$((_dd_mem_total / 5))
|
||||
[ "$_dd_headroom" -ge $((512 * 1024)) ] || _dd_headroom=$((512 * 1024))
|
||||
[ "$_dd_headroom" -le $((1536 * 1024)) ] || _dd_headroom=$((1536 * 1024))
|
||||
_dd_tier_headroom=$((_dd_mem_total / 4))
|
||||
[ "$_dd_tier_headroom" -ge $((768 * 1024)) ] || _dd_tier_headroom=$((768 * 1024))
|
||||
[ "$_dd_tier_headroom" -le $((2560 * 1024)) ] || _dd_tier_headroom=$((2560 * 1024))
|
||||
_dd_fall_headroom=$((_dd_tier_headroom * 2))
|
||||
[ "$_dd_fall_headroom" -ge $((_dd_mem_total * 2 / 5)) ] || _dd_fall_headroom=$((_dd_mem_total * 2 / 5))
|
||||
_dd_swap_reserve=$((_dd_swap_total / 5))
|
||||
[ "$_dd_swap_reserve" -ge $((256 * 1024)) ] || _dd_swap_reserve=$((256 * 1024))
|
||||
_dd_floor=$((_dd_mem_total / 8))
|
||||
[ "$_dd_floor" -ge $((640 * 1024)) ] || _dd_floor=$((640 * 1024))
|
||||
[ "$_dd_floor" -le $((1280 * 1024)) ] || _dd_floor=$((1280 * 1024))
|
||||
_dd_target=$((_dd_floor + _dd_rate * 10))
|
||||
}
|
||||
dd_memory_tight() {
|
||||
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] &&
|
||||
{ [ "$_dd_real_available" -lt "$_dd_headroom" ] ||
|
||||
{ [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_mem_total / 3)) ]; } ||
|
||||
{ [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt $((_dd_headroom * 2)) ]; }; }
|
||||
}
|
||||
dd_client_can_pageout() {
|
||||
dd_memory_read
|
||||
dd_zram_usage "${_dd_pids[@]}" > /dev/null
|
||||
[ "$_dd_mem_total" -gt 0 ] && dd_zram_has_room
|
||||
}
|
||||
dd_zram_has_room() {
|
||||
[ "$_dd_swap_total" -gt 0 ] &&
|
||||
[ $((_dd_swap_free - _dd_anon - ${_dd_client_reserve:-0})) -ge "$_dd_swap_reserve" ]
|
||||
}
|
||||
dd_client_can_readback() {
|
||||
dd_memory_read
|
||||
dd_zram_usage "${_dd_pids[@]}" > /dev/null
|
||||
[ "$_dd_mem_total" -gt 0 ] && ! dd_memory_tight && ! dd_memory_critical &&
|
||||
[ "$_dd_real_available" -ge $((_dd_swap * 2)) ] &&
|
||||
[ $((_dd_real_available - _dd_swap)) -ge "$_dd_headroom" ]
|
||||
}
|
||||
dd_client_pressure() {
|
||||
[ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ "$_dd_game" = 1 ] &&
|
||||
[ "${#_dd_pids[@]}" -gt 0 ] && { dd_memory_tight || dd_memory_critical; } || return 0
|
||||
[ "$_dd_pressure_at" -lt 0 ] ||
|
||||
[ $((SECONDS - _dd_pressure_at)) -ge "$_dd_pressure_backoff" ] || return 0
|
||||
[ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 30 ] || return 0
|
||||
_dd_pressure_at=$SECONDS
|
||||
if ! dd_client_can_pageout; then
|
||||
step "zRAM: pressure reclaim skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)"
|
||||
return 0
|
||||
dd_memory_need() {
|
||||
local _burst=$((_dd_rate * 2))
|
||||
_dd_need=0 _dd_hard=0 _dd_force=0
|
||||
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] || return 0
|
||||
_dd_need=$((_dd_target - _dd_available)) _dd_hard=$((_dd_floor - _dd_available))
|
||||
if [ "$_burst" -ge $((64 * 1024)) ] && [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] && [ "$_burst" -gt "$_dd_need" ]; then
|
||||
_dd_need=$_burst
|
||||
fi
|
||||
[ "$_dd_rss" -ge $((128 * 1024)) ] || return 0
|
||||
_dd_pressure_before=$_dd_rss
|
||||
if [ "${1:-}" = defer ]; then
|
||||
_dd_client_reserve=$_dd_anon
|
||||
_dd_client_pending=1
|
||||
fi
|
||||
dd_zram_send 1 "memory pressure, compressing the client (available $((_dd_available / 1024)) MB, swap free $((_dd_swap_free / 1024)) MB)" client "${1:-}"
|
||||
_dd_packed=$SECONDS
|
||||
if [ "${1:-}" = defer ]; then
|
||||
_dd_client_targets=("${_dd_zram_targets[@]}")
|
||||
else
|
||||
dd_client_pressure_result
|
||||
if [ "$_dd_psi" -ge 100 ] && [ "$_burst" -gt "$_dd_hard" ]; then
|
||||
_dd_hard=$_burst
|
||||
fi
|
||||
[ "$_dd_hard" -gt 0 ] || _dd_hard=0
|
||||
[ "$_dd_need" -ge "$_dd_hard" ] || _dd_need=$_dd_hard
|
||||
[ "$_dd_available" -ge $((_dd_floor / 2)) ] || _dd_force=1
|
||||
}
|
||||
dd_client_pressure_finish() {
|
||||
[ "${_dd_client_pending:-0}" = 1 ] || return 0
|
||||
dd_zram_finish 1 "${_dd_client_targets[@]}"
|
||||
dd_client_pressure_result "${_dd_client_targets[@]}"
|
||||
_dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=()
|
||||
}
|
||||
dd_client_pressure_result() {
|
||||
[ "${_dd_pageout_complete:-0}" = 1 ] || return 0
|
||||
if [ "$#" -gt 0 ]; then dd_zram_usage "$@" > /dev/null; else dd_zram_usage "${_dd_pids[@]}" > /dev/null; fi
|
||||
if [ $((_dd_pressure_before - _dd_rss)) -lt $((16 * 1024)) ]; then
|
||||
_dd_pressure_backoff=$((_dd_pressure_backoff * 2 > 300 ? 300 : _dd_pressure_backoff * 2))
|
||||
else
|
||||
_dd_pressure_backoff=30
|
||||
fi
|
||||
}
|
||||
dd_memory_critical() {
|
||||
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] &&
|
||||
{ [ "$_dd_real_available" -lt "$_dd_tier_headroom" ] ||
|
||||
{ [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_tier_headroom * 3 / 2)) ]; } ||
|
||||
{ [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; }; }
|
||||
}
|
||||
dd_session_pressure() {
|
||||
dd_memory_read
|
||||
dd_memory_critical || _dd_tier_backoff=30 _dd_tier_nogain=0
|
||||
[ "$_dd_game" = 1 ] && dd_memory_critical || return 0
|
||||
[ "${DD_ZRAM_IDLE:-1}" = 1 ] && dd_game_focused 0 || return 0
|
||||
local _wait=$_dd_tier_backoff _before _available_before _pids _targets _gain _min_gain
|
||||
[ "$_dd_available" -ge $((_dd_headroom / 2)) ] || [ "$_dd_tier_pushed" -lt 0 ] || _wait=30
|
||||
[ "$_dd_tier_at" -lt 0 ] || [ $((SECONDS - _dd_tier_at)) -ge "$_wait" ] || return 0
|
||||
if [ "$_dd_tier_at" -ge 0 ] && [ "$_dd_tier_pushed" -gt 0 ]; then
|
||||
dd_tier_readback
|
||||
if [ "$_dd_tier_back" -le $((_dd_tier_pushed / 2)) ]; then
|
||||
[ "${_dd_tier_nogain:-0}" = 1 ] || _dd_tier_backoff=30
|
||||
else
|
||||
_dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2))
|
||||
_dd_tier_at=$SECONDS _dd_tier_pushed=-1
|
||||
step "zRAM: the game read back most of its last page-out, next try in ${_dd_tier_backoff} s"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
_dd_tier_at=$SECONDS _dd_tier_pushed=0
|
||||
dd_zram_pick session
|
||||
dd_zram_usage "${_pids[@]}" > /dev/null
|
||||
[ "$_dd_rss" -ge $((256 * 1024)) ] || return 0
|
||||
if ! dd_zram_has_room; then
|
||||
step "zRAM: low-memory page-out skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)"
|
||||
return 0
|
||||
fi
|
||||
_targets=("${_pids[@]}") _before=$_dd_swap _available_before=$_dd_available
|
||||
dd_zram_send 1 "low memory (available $((_dd_real_available / 1024)) MB), compressing idle game memory" session
|
||||
dd_zram_usage "${_targets[@]}" > /dev/null
|
||||
_dd_tier_pushed=$((_dd_swap - _before))
|
||||
dd_tier_note "${_targets[@]}"
|
||||
if [ "${_dd_pageout_complete:-0}" = 1 ]; then
|
||||
dd_memory_read
|
||||
_gain=$((_dd_available - _available_before))
|
||||
_min_gain=$((_dd_tier_headroom / 16))
|
||||
[ "$_min_gain" -ge $((16 * 1024)) ] || _min_gain=$((16 * 1024))
|
||||
if [ "$_gain" -lt "$_min_gain" ]; then
|
||||
_dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2))
|
||||
_dd_tier_at=$SECONDS _dd_tier_nogain=1
|
||||
step "zRAM: low-memory page-out gained only $((_gain / 1024)) MB available, next try in ${_dd_tier_backoff} s"
|
||||
else
|
||||
_dd_tier_nogain=0
|
||||
fi
|
||||
fi
|
||||
}
|
||||
dd_proc_start() {
|
||||
local _s=
|
||||
_dd_start=
|
||||
read -r _s 2>/dev/null < "/proc/$1/stat" || return 1
|
||||
_s=${_s##*) }
|
||||
set -- $_s
|
||||
[ "$1" != Z ] && [ "$#" -ge 20 ] || return 1
|
||||
_dd_start=${20}
|
||||
}
|
||||
dd_tier_note() {
|
||||
local _p
|
||||
_dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
|
||||
for _p in "$@"; do
|
||||
dd_proc_start "$_p" || continue
|
||||
dd_zram_usage "$_p" > /dev/null
|
||||
_dd_tier_targets+=("$_p") _dd_tier_swaps+=("$_dd_swap") _dd_tier_starts+=("$_dd_start")
|
||||
done
|
||||
}
|
||||
dd_tier_readback() {
|
||||
local _i _back=0
|
||||
for _i in "${!_dd_tier_targets[@]}"; do
|
||||
dd_proc_start "${_dd_tier_targets[$_i]}" && [ "$_dd_start" = "${_dd_tier_starts[$_i]}" ] || continue
|
||||
dd_zram_usage "${_dd_tier_targets[$_i]}" > /dev/null
|
||||
[ "${_dd_tier_swaps[$_i]}" -le "$_dd_swap" ] || _back=$((_back + _dd_tier_swaps[_i] - _dd_swap))
|
||||
done
|
||||
_dd_tier_back=$_back
|
||||
}
|
||||
dd_watch_nap() {
|
||||
local _i
|
||||
if [ "$_dd_game" = 1 ] && [ "$_dd_available" -ge 0 ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; then
|
||||
for _i in 1 2 3 4 5; do
|
||||
nap 1
|
||||
dd_memory_read
|
||||
dd_memory_critical && return 0
|
||||
done
|
||||
else
|
||||
nap 5
|
||||
fi
|
||||
return 0
|
||||
dd_pid_key() {
|
||||
local _s
|
||||
_dd_key=$1
|
||||
read -r _s 2>/dev/null < "/proc/$1/stat" || return 0
|
||||
set -- ${_s##*) }
|
||||
_dd_key=$_dd_key.${20:-}
|
||||
}
|
||||
dd_session_others() {
|
||||
local _p
|
||||
local -A _known=()
|
||||
_dd_session=()
|
||||
for _p in "${_dd_others[@]}"; do
|
||||
grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null && _dd_session+=("$_p")
|
||||
dd_pid_key "$_p"
|
||||
[ -n "${_dd_preloaded[$_dd_key]:-}" ] ||
|
||||
grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null || continue
|
||||
_known[$_dd_key]=1
|
||||
dd_zram_usage "$_p" > /dev/null
|
||||
_dd_session+=("$_dd_anon $_p")
|
||||
done
|
||||
_dd_preloaded=()
|
||||
for _p in "${!_known[@]}"; do
|
||||
_dd_preloaded[$_p]=1
|
||||
done
|
||||
[ "${#_dd_session[@]}" -gt 0 ] || return 0
|
||||
mapfile -t _dd_session < <(printf '%s\n' "${_dd_session[@]}" | sort -rn)
|
||||
_dd_session=("${_dd_session[@]#* }")
|
||||
}
|
||||
dd_zram_pick() {
|
||||
if [ "$1" = game ]; then
|
||||
dd_session_others
|
||||
_pids=("${_dd_session[@]}")
|
||||
[ "${DD_ZRAM_CLIENT:-1}" != 1 ] || _pids+=("${_dd_pids[@]}")
|
||||
elif [ "$1" = session ]; then
|
||||
dd_session_others
|
||||
_pids=("${_dd_session[@]}")
|
||||
dd_memory_relieved() {
|
||||
local _k _v _u
|
||||
while read -r _k _v _u; do
|
||||
[ "$_k" = MemAvailable: ] || continue
|
||||
case $_v in ''|*[!0-9]*) return 1 ;; esac
|
||||
[ "$_v" -ge "$_dd_goal" ]
|
||||
return
|
||||
done 2>/dev/null < /proc/meminfo
|
||||
return 1
|
||||
}
|
||||
dd_zram_trim() {
|
||||
local _mode=$1 _left=$2 _p _k _n _i _acks=()
|
||||
shift 2
|
||||
_dd_trimmed=0
|
||||
for _k in "${!_dd_deaf[@]}"; do
|
||||
[ "${_dd_deaf[$_k]}" -gt "$SECONDS" ] || unset "_dd_deaf[$_k]"
|
||||
done
|
||||
for _p in "$@"; do
|
||||
[ "$_left" -ge 4096 ] && [ "$_dd_polls" -lt 250 ] && [ $((SECONDS - _dd_pass_at)) -lt 6 ] &&
|
||||
[ ! -e /tmp/.dd-zram.hold ] || break
|
||||
! dd_memory_relieved || break
|
||||
dd_pid_key "$_p"
|
||||
_k=$_dd_key
|
||||
[ "${_dd_deaf[$_k]:-0}" -le "$SECONDS" ] || continue
|
||||
dd_zram_usage "$_p" > /dev/null
|
||||
[ "$_dd_anon" -ge 8192 ] || continue
|
||||
printf %s - > "/tmp/.dd-zram.trim.$_p"
|
||||
_acks+=("/tmp/.dd-zram.trim.$_p")
|
||||
printf '%s %s\n' "$_mode" "$_left" > /tmp/.dd-zram
|
||||
kill -URG "$_p" 2>/dev/null || continue
|
||||
_dd_deaf[$_k]=$((SECONDS + 60))
|
||||
for ((_i = 0; _dd_polls < 250 && SECONDS - _dd_pass_at < 6; _i++, _dd_polls++)); do
|
||||
[ ! -e /tmp/.dd-zram.hold ] || { _dd_deaf[$_k]=0; break; }
|
||||
_n=
|
||||
read -r _n 2>/dev/null < "/tmp/.dd-zram.trim.$_p" || :
|
||||
case $_n in
|
||||
-) [ "$_i" -lt 25 ] || break ;;
|
||||
''|*[!0-9]*) ;;
|
||||
*) _dd_trimmed=$((_dd_trimmed + _n)) _left=$((_left - _n)) _dd_deaf[$_k]=0; break ;;
|
||||
esac
|
||||
nap 0.02
|
||||
done
|
||||
done
|
||||
[ ! -e /tmp/.dd-zram.hold ] || return 0
|
||||
printf '2 0\n' > /tmp/.dd-zram
|
||||
[ "${#_acks[@]}" = 0 ] || rm -f "${_acks[@]}"
|
||||
}
|
||||
dd_memory_relieve() {
|
||||
local _mode=2 _budget _gain=0 _rest _cap=$((256 * 1024)) _all=$((1024 * 1024))
|
||||
dd_memory_need
|
||||
_dd_polls=0 _dd_pass_at=$SECONDS
|
||||
if [ "$_dd_need" -le 0 ]; then
|
||||
_dd_rest=0
|
||||
return 0
|
||||
fi
|
||||
[ "$_dd_rest" = 0 ] || [ "$_dd_force" = 1 ] || [ "$SECONDS" -ge "$_dd_rest_until" ] ||
|
||||
[ "$_dd_available" -lt $((_dd_rest_available - _dd_floor / 8)) ] || return 0
|
||||
if [ "$_dd_swap_room" -lt $((64 * 1024)) ]; then
|
||||
if [ $((SECONDS - _dd_full_at)) -ge 60 ]; then
|
||||
_dd_full_at=$SECONDS
|
||||
step "memory: available $((_dd_available / 1024)) MB and zRAM has no room left"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
if [ "$_dd_force" = 1 ] && [ $((SECONDS - _dd_forced_at)) -ge 10 ]; then
|
||||
_mode=3 _dd_forced_at=$SECONDS _cap=$_all
|
||||
else
|
||||
_pids=("${_dd_pids[@]}")
|
||||
_cap=$((_cap - _dd_returned)) _all=$((_all - _dd_returned))
|
||||
fi
|
||||
if [ "${#_dd_pids[@]}" -gt 0 ] && [ "$_all" -ge 4096 ] &&
|
||||
{ [ "$_dd_hard" -gt 0 ] ||
|
||||
{ [ "$_dd_game" = 1 ] && [ "$_dd_focus" != 1 ] && [ $((SECONDS - _dd_back_at)) -ge 30 ]; }; }; then
|
||||
_budget=$((_dd_need * 1000 / _dd_saving))
|
||||
[ "$_budget" -le "$_all" ] || _budget=$_all
|
||||
[ "$_budget" -le "$_dd_swap_room" ] || _budget=$_dd_swap_room
|
||||
_dd_goal=$((_dd_available + _dd_need))
|
||||
dd_zram_trim "$_mode" "$_budget" "${_dd_pids[@]}"
|
||||
_gain=$((_dd_trimmed * _dd_saving / 1000))
|
||||
_dd_swap_room=$((_dd_swap_room - _dd_trimmed)) _all=$((_all - _dd_trimmed))
|
||||
[ "$_cap" -le "$_all" ] || _cap=$_all
|
||||
_dd_client_out=$((_dd_client_out + _dd_trimmed)) _dd_note_client=$((_dd_note_client + _dd_trimmed))
|
||||
[ "$_dd_trimmed" = 0 ] || _dd_trim_at=$SECONDS
|
||||
fi
|
||||
_rest=$((_dd_hard - _gain))
|
||||
if [ "$_rest" -gt 0 ] && [ "$_cap" -ge 4096 ] && [ "$_dd_swap_room" -ge $((64 * 1024)) ]; then
|
||||
[ "$_dd_session_at" = "$_dd_scan_at" ] || dd_session_others
|
||||
_dd_session_at=$_dd_scan_at
|
||||
_budget=$((_rest * 1000 / _dd_saving))
|
||||
[ "$_budget" -le "$_cap" ] || _budget=$_cap
|
||||
[ "$_budget" -le "$_dd_swap_room" ] || _budget=$_dd_swap_room
|
||||
_dd_goal=$((_dd_available + _dd_hard))
|
||||
dd_zram_trim "$_mode" "$_budget" "${_dd_session[@]}"
|
||||
_gain=$((_gain + _dd_trimmed * _dd_saving / 1000))
|
||||
_dd_note_session=$((_dd_note_session + _dd_trimmed))
|
||||
fi
|
||||
_dd_freed=$((_dd_freed + _gain))
|
||||
if [ "$_dd_hard" -gt 0 ] && [ "$_gain" -lt $((_dd_hard / 4)) ]; then
|
||||
_dd_rest=$((_dd_rest > 0 ? _dd_rest * 2 : 5))
|
||||
[ "$_dd_rest" -le 60 ] || _dd_rest=60
|
||||
_dd_rest_until=$((SECONDS + _dd_rest)) _dd_rest_available=$_dd_available
|
||||
else
|
||||
_dd_rest=0
|
||||
fi
|
||||
}
|
||||
dd_zram_wait() {
|
||||
local _p _left _start=$SECONDS
|
||||
while [ $((SECONDS - _start)) -lt 12 ]; do
|
||||
_left=0
|
||||
for _p in "$@"; do
|
||||
[ -s "/tmp/.dd-zram.ack.$_p" ] && continue
|
||||
[ -d "/proc/$_p" ] || continue
|
||||
[ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.dd-zram.ack.$_p" ] && continue
|
||||
_left=1
|
||||
done
|
||||
[ "$_left" = 1 ] || break
|
||||
nap 0.2
|
||||
done
|
||||
_dd_pageout_complete=1
|
||||
for _p in "$@"; do
|
||||
if [ -d "/proc/$_p" ] && [ ! -s "/tmp/.dd-zram.ack.$_p" ]; then _dd_pageout_complete=0; fi
|
||||
rm -f "/tmp/.dd-zram.ack.$_p"
|
||||
done
|
||||
dd_memory_note() {
|
||||
[ $((_dd_note_client + _dd_note_session)) -ge $((16 * 1024)) ] && [ $((SECONDS - _dd_noted_at)) -ge 5 ] || return 0
|
||||
step "memory: available $((_dd_available / 1024)) MB, falling $((_dd_rate / 1024)) MB/s, compressed $((_dd_note_client / 1024)) MB of the client and $((_dd_note_session / 1024)) MB of the session"
|
||||
_dd_note_client=0 _dd_note_session=0 _dd_noted_at=$SECONDS
|
||||
}
|
||||
dd_zram_send() {
|
||||
local _mode=$1 _what=$2 _which=$3 _pids _p
|
||||
dd_zram_pick "$_which"
|
||||
step "zRAM: $_what ($(dd_zram_usage "${_pids[@]}"))"
|
||||
for _p in "${_pids[@]}"; do rm -f "/tmp/.dd-zram.ack.$_p"; done
|
||||
printf '%s' "$_mode" > /tmp/.dd-zram
|
||||
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
|
||||
_dd_zram_targets=("${_pids[@]}")
|
||||
[ "${4:-}" != defer ] || return 0
|
||||
dd_zram_finish "$_mode" "${_pids[@]}"
|
||||
}
|
||||
dd_zram_finish() {
|
||||
local _mode=$1
|
||||
shift
|
||||
if [ "$_mode" = 1 ]; then dd_zram_wait "$@"; else nap 5; fi
|
||||
dd_zram_scan
|
||||
step "zRAM: done ($(dd_zram_usage "$@"))"
|
||||
dd_client_readback() {
|
||||
[ "$_dd_client_out" -gt 0 ] && [ "${#_dd_pids[@]}" -gt 0 ] || return 0
|
||||
[ "$_dd_game" = 0 ] || { [ -n "$_dd_away" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; } || return 0
|
||||
[ $((SECONDS - _dd_trim_at)) -ge 30 ] || return 0
|
||||
dd_zram_usage "${_dd_pids[@]}" > /dev/null
|
||||
if [ "$_dd_swap" -lt $((16 * 1024)) ]; then
|
||||
_dd_client_out=0
|
||||
return 0
|
||||
fi
|
||||
[ $((_dd_available - _dd_swap)) -ge $((_dd_target + _dd_floor)) ] || return 0
|
||||
step "memory: available $((_dd_available / 1024)) MB, reading $((_dd_swap / 1024)) MB of the client back"
|
||||
printf 0 > /tmp/.dd-zram || return 0
|
||||
kill -URG "${_dd_pids[@]}" 2>/dev/null || return 0
|
||||
_dd_freed=$((_dd_freed - _dd_swap * _dd_saving / 1000))
|
||||
_dd_client_out=0 _dd_back_at=$SECONDS
|
||||
}
|
||||
dd_game_focused() {
|
||||
if [ "${DD_DESKTOP:-}" = 1 ] || [ -z "${DD_LAUNCH_DIR:-}" ]; then
|
||||
@@ -1136,92 +1081,40 @@ case $mode in
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
dd_over_cap() {
|
||||
[ "$_dd_ram_cap" -gt 0 ] || return 1
|
||||
_dd_measured=$SECONDS
|
||||
dd_session_others
|
||||
dd_zram_usage "${_dd_pids[@]}" "${_dd_session[@]}" > /dev/null
|
||||
[ "$_dd_rss" -gt "$_dd_ram_cap" ]
|
||||
}
|
||||
dd_cap_due() {
|
||||
[ "$_dd_ram_cap" -gt 0 ] && { [ "$_dd_measured" -lt 0 ] || [ $((SECONDS - _dd_measured)) -ge 30 ]; }
|
||||
}
|
||||
_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_measured=-1 _dd_unpack=0 _dd_capped=-1 _dd_backoff=30
|
||||
_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_back=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
|
||||
_dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=() _dd_away=
|
||||
_dd_sample_at= _dd_sample_available=0 _dd_sample_gpu=0 _dd_sample_unevictable=0 _dd_sample_shmem=0
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
dd_zram_scan
|
||||
dd_memory_read
|
||||
if dd_cap_due; then
|
||||
if dd_over_cap; then
|
||||
if [ "$_dd_capped" -lt 0 ] || [ $((SECONDS - _dd_capped)) -ge "$_dd_backoff" ]; then
|
||||
dd_zram_usage "${_dd_pids[@]}" > /dev/null
|
||||
if [ "$_dd_rss" -ge $((512 * 1024)) ]; then
|
||||
dd_zram_send 1 "over the ${DD_RAM_CAP_MB} MB RAM cap, compressing the client" client
|
||||
[ "$_dd_game" = 1 ] && _dd_packed=$SECONDS
|
||||
else
|
||||
step "RAM cap: over, client already small ($((_dd_rss / 1024)) MB resident), skipping it"
|
||||
fi
|
||||
dd_over_cap && dd_zram_send 1 "still over the RAM cap, compressing the rest of the session" session
|
||||
if dd_over_cap; then
|
||||
_dd_backoff=$((_dd_backoff * 2 > 600 ? 600 : _dd_backoff * 2))
|
||||
step "RAM cap: still over after paging out, next try in ${_dd_backoff} s"
|
||||
else
|
||||
_dd_backoff=30
|
||||
fi
|
||||
_dd_capped=$SECONDS
|
||||
fi
|
||||
else
|
||||
_dd_backoff=30
|
||||
dd_memory_tick() {
|
||||
if [ $((SECONDS - _dd_scan_at)) -ge 5 ]; then
|
||||
_dd_scan_at=$SECONDS
|
||||
dd_zram_scan
|
||||
_dd_focus=1
|
||||
if [ "$_dd_game" = 1 ]; then
|
||||
dd_game_focused && _dd_focus=0 || _dd_focus=$?
|
||||
fi
|
||||
fi
|
||||
_dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall
|
||||
dd_client_pressure defer
|
||||
_dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall
|
||||
dd_session_pressure
|
||||
dd_client_pressure_finish
|
||||
_dd_focus=1
|
||||
[ "$_dd_game" = 1 ] && { dd_game_focused && _dd_focus=0 || _dd_focus=$?; }
|
||||
if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 0 ]; then
|
||||
_dd_away=
|
||||
if [ "$_dd_since" -lt 0 ] || [ "$_dd_since_apps" != "$_dd_apps" ]; then
|
||||
_dd_since=$SECONDS _dd_since_apps=$_dd_apps
|
||||
fi
|
||||
if [ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _dd_since)) -ge 20 ] && [ "${#_dd_pids[@]}" -gt 0 ] &&
|
||||
{ [ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 300 ]; } && dd_client_can_pageout; then
|
||||
dd_zram_send 1 "compressing the client" client
|
||||
_dd_packed=$SECONDS
|
||||
fi
|
||||
elif [ "$_dd_game" != 1 ]; then
|
||||
_dd_away=
|
||||
if [ "$_dd_packed" -ge 0 ]; then
|
||||
_dd_unpack=1
|
||||
fi
|
||||
_dd_since=-1 _dd_packed=-1 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
|
||||
else
|
||||
_dd_since=-1
|
||||
if [ "$_dd_focus" = 1 ]; then
|
||||
[ -n "${_dd_away-}" ] || _dd_away=$SECONDS
|
||||
if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 1 ]; then
|
||||
[ -n "$_dd_away" ] || _dd_away=$SECONDS
|
||||
else
|
||||
_dd_away=
|
||||
fi
|
||||
if [ "$_dd_packed" -ge 0 ]; then
|
||||
_dd_unpack=1
|
||||
fi
|
||||
fi
|
||||
if [ "$_dd_unpack" = 1 ] &&
|
||||
{ [ "$_dd_game" = 0 ] || { [ "${_dd_ram_cap:-0}" = 0 ] && [ -n "${_dd_away-}" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; }; } &&
|
||||
! dd_over_cap && dd_client_can_readback; then
|
||||
if [ "$_dd_game" = 0 ]; then
|
||||
dd_zram_send 0 "memory recovered, reading the client back" client
|
||||
else
|
||||
dd_zram_send 0 "the client is in front of the game, reading it back" client
|
||||
_dd_packed=-1
|
||||
fi
|
||||
_dd_unpack=0
|
||||
dd_memory_read
|
||||
[ ! -e /tmp/.dd-zram.hold ] || return 0
|
||||
dd_memory_relieve
|
||||
dd_memory_note
|
||||
[ "$_dd_need" -gt 0 ] || dd_client_readback
|
||||
}
|
||||
declare -A _dd_deaf=() _dd_preloaded=()
|
||||
_dd_scan_at=-5 _dd_session_at=-1 _dd_session=() _dd_focus=1 _dd_away=
|
||||
_dd_page_kb=$(($(getconf PAGESIZE 2>/dev/null || echo 4096) / 1024)) _dd_returned=0 _dd_polls=0 _dd_pass_at=0 _dd_goal=0
|
||||
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
|
||||
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
|
||||
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
dd_memory_tick
|
||||
if [ "$_dd_available" -ge 0 ] &&
|
||||
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
|
||||
nap 1
|
||||
else
|
||||
nap 5
|
||||
fi
|
||||
dd_watch_nap
|
||||
done
|
||||
) &
|
||||
fi
|
||||
@@ -1529,11 +1422,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()]
|
||||
|
||||
@@ -65,12 +65,14 @@ if [ -n "$repair" ]; then
|
||||
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
|
||||
done
|
||||
fi
|
||||
cache_only=
|
||||
[ "${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
|
||||
@@ -167,6 +169,46 @@ 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
|
||||
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"
|
||||
echo "$version" > "$cached"
|
||||
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
|
||||
|
||||
@@ -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
|
||||
@@ -116,7 +117,7 @@ def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
|
||||
return str(answer.get("reason") or "failed")
|
||||
|
||||
|
||||
def ask(channel, request, timeout=TIMEOUT):
|
||||
def ask(channel, request, timeout=TIMEOUT, claim=False):
|
||||
req_dir, resp_dir = channel / "req", channel / "resp"
|
||||
req_dir.mkdir(parents=True, exist_ok=True)
|
||||
resp_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -125,19 +126,33 @@ def ask(channel, request, timeout=TIMEOUT):
|
||||
tmp.write_text(json.dumps(request))
|
||||
os.rename(tmp, req_dir / (rid + ".json"))
|
||||
answer = resp_dir / (rid + ".json")
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
|
||||
def wait(seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = json.loads(answer.read_text())
|
||||
answer.unlink()
|
||||
return value
|
||||
except (OSError, ValueError):
|
||||
time.sleep(0.05)
|
||||
return None
|
||||
|
||||
value = wait(timeout)
|
||||
if value is not None:
|
||||
return value
|
||||
for pending in (req_dir / (rid + ".json"), resp_dir / (rid + ".taken")):
|
||||
abandoned = pending.with_name(rid + ".abandoned")
|
||||
try:
|
||||
value = json.loads(answer.read_text())
|
||||
answer.unlink()
|
||||
return value
|
||||
except (OSError, ValueError):
|
||||
time.sleep(0.05)
|
||||
try:
|
||||
(req_dir / (rid + ".json")).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
os.rename(pending, abandoned)
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
abandoned.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
return wait(CLAIMED_TIMEOUT) if claim else None
|
||||
|
||||
|
||||
def windows_path(unix):
|
||||
@@ -255,7 +270,8 @@ def create_prefix(compat_data, proton, timeout=120):
|
||||
|
||||
|
||||
CLOUD_TIMEOUT = 15.0
|
||||
CLOUD_STORES = ("gog", "epic")
|
||||
CLAIMED_TIMEOUT = 120.0
|
||||
CLOUD_STORES = ("gog", "epic", "ea", "ubisoft")
|
||||
STORE_GAME = 10
|
||||
RAN = 11
|
||||
RAN_FAILED = 12
|
||||
@@ -304,11 +320,14 @@ def exited(argv, code=0):
|
||||
if found is not None and launch_dir and str(found[1].get("store")) == "ea":
|
||||
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0)
|
||||
log("ea %s exited" % found[1].get("id"))
|
||||
return 0
|
||||
if found is None or not launch_dir or not cloud_on(found[1]):
|
||||
return 0
|
||||
store, game = str(found[1].get("store")), str(found[1].get("id"))
|
||||
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
|
||||
try:
|
||||
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
|
||||
except OSError as error:
|
||||
log("cloud %s %s up not requested (%s)" % (store, game, type(error).__name__))
|
||||
return 0
|
||||
log("cloud %s %s up requested" % (store, game))
|
||||
return 0
|
||||
|
||||
@@ -319,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"}
|
||||
|
||||
@@ -376,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]
|
||||
@@ -402,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"
|
||||
@@ -470,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()
|
||||
|
||||
|
||||
@@ -1601,7 +1684,7 @@ def main(argv):
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
prefix_id = os.path.basename(compat_data) if compat_data else ""
|
||||
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
|
||||
if launch_dir and cloud_on(sidecar):
|
||||
if launch_dir and cloud_on(sidecar) and store != "ea":
|
||||
made = create_prefix(compat_data, os.environ.get("DD_STORE_PROTON", ""))
|
||||
if made != "present":
|
||||
log("cloud %s %s prefix=%s" % (store, game, made))
|
||||
@@ -1632,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)
|
||||
@@ -1670,13 +1762,16 @@ def main(argv):
|
||||
log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data)))
|
||||
if store == "ea":
|
||||
prepare_ea(folder, sidecar, compat_data, launch_dir)
|
||||
return STORE_GAME
|
||||
if not cloud_on(sidecar):
|
||||
if store in CLOUD_STORES:
|
||||
log("cloud %s %s down result=skipped reason=off" % (store, game))
|
||||
return 0
|
||||
return STORE_GAME if store == "ea" else 0
|
||||
if launch_dir:
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
|
||||
try:
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT, claim=True)
|
||||
except OSError as error:
|
||||
log("cloud %s %s down result=failed reason=%s" % (store, game, type(error).__name__))
|
||||
return STORE_GAME
|
||||
if answer is None:
|
||||
log("cloud %s %s down result=timeout" % (store, game))
|
||||
else:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
@@ -11,6 +12,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import xml.etree.ElementTree as ElementTree
|
||||
|
||||
BIN = Path(__file__).resolve().parent
|
||||
RUNTIME = Path('/usr/local/lib/droiddeck-xbox')
|
||||
@@ -137,6 +139,117 @@ def register_classes(proton, prefix, env):
|
||||
print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr)
|
||||
|
||||
|
||||
def game_config(exe):
|
||||
path = Path(exe)
|
||||
if not path.is_absolute():
|
||||
return None
|
||||
for folder in list(path.parents)[:4]:
|
||||
config = folder / 'MicrosoftGame.config'
|
||||
if config.is_file():
|
||||
return config
|
||||
return None
|
||||
|
||||
|
||||
def windows_arguments(text):
|
||||
arguments, current, quoted, started, at = [], [], False, False, 0
|
||||
while at < len(text):
|
||||
char = text[at]
|
||||
if char == '\\':
|
||||
run = len(text) - at - len(text[at:].lstrip('\\'))
|
||||
at += run
|
||||
if at < len(text) and text[at] == '"':
|
||||
current.append('\\' * (run // 2))
|
||||
if run % 2:
|
||||
current.append('"')
|
||||
at += 1
|
||||
else:
|
||||
current.append('\\' * run)
|
||||
started = True
|
||||
continue
|
||||
if char == '"':
|
||||
if quoted and text[at + 1:at + 2] == '"':
|
||||
current.append('"')
|
||||
at += 2
|
||||
continue
|
||||
quoted = not quoted
|
||||
started = True
|
||||
elif char in ' \t' and not quoted:
|
||||
if started:
|
||||
arguments.append(''.join(current))
|
||||
current, started = [], False
|
||||
else:
|
||||
current.append(char)
|
||||
started = True
|
||||
at += 1
|
||||
if started:
|
||||
arguments.append(''.join(current))
|
||||
return arguments
|
||||
|
||||
|
||||
def install_actions(config):
|
||||
try:
|
||||
root = ElementTree.fromstring(config.read_bytes())
|
||||
except (OSError, ElementTree.ParseError):
|
||||
return []
|
||||
actions = []
|
||||
for registration in root.iter():
|
||||
if registration.tag.rsplit('}', 1)[-1] != 'CustomInstallActions':
|
||||
continue
|
||||
folder = next((node.text or '' for node in registration if node.tag.rsplit('}', 1)[-1] == 'Folder'), '')
|
||||
for node in registration.iter():
|
||||
if node.tag.rsplit('}', 1)[-1] != 'InstallAction':
|
||||
continue
|
||||
name, file = node.get('Name', ''), node.get('File', '')
|
||||
parts = [part for part in (folder.strip() + '\\' + file).replace('/', '\\').split('\\') if part]
|
||||
if not name or not file or any(part in ('.', '..') or ':' in part for part in parts):
|
||||
continue
|
||||
target = config.parent.joinpath(*parts)
|
||||
try:
|
||||
inside = target.resolve().is_relative_to(config.parent.resolve())
|
||||
except OSError:
|
||||
inside = False
|
||||
if inside and target.is_file() and target.suffix.lower() in ('.msi', '.exe'):
|
||||
actions.append((name, target, windows_arguments(node.get('Arguments', ''))))
|
||||
return actions
|
||||
|
||||
|
||||
def run_install_actions(proton, prefix, exe, env):
|
||||
config = game_config(exe)
|
||||
if config is None:
|
||||
return
|
||||
done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions'
|
||||
for name, target, arguments in install_actions(config):
|
||||
try:
|
||||
content = hashlib.sha256()
|
||||
with target.open('rb') as source:
|
||||
for block in iter(lambda: source.read(1 << 20), b''):
|
||||
content.update(block)
|
||||
identity = hashlib.sha256(name.encode('utf-8') + b'\0' + content.digest()).hexdigest()[:24]
|
||||
marker = done / ('%s-%s' % (''.join(c for c in name if c.isalnum() or c in '-_')[:64], identity))
|
||||
if marker.exists():
|
||||
continue
|
||||
except OSError as error:
|
||||
print('droiddeck-xbox: install action %s could not be read (%s); launching without it' % (name, error), file=sys.stderr)
|
||||
continue
|
||||
windows = 'Z:' + str(target).replace('/', '\\')
|
||||
if target.suffix.lower() == '.msi':
|
||||
command = [proton, 'run', 'msiexec', '/i', windows, *arguments]
|
||||
else:
|
||||
command = [proton, 'run', windows, *arguments]
|
||||
try:
|
||||
code = subprocess.run(command, stdout=sys.stderr, env=env, timeout=600).returncode
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
code = None
|
||||
if code != 0:
|
||||
print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr)
|
||||
continue
|
||||
try:
|
||||
done.mkdir(parents=True, exist_ok=True)
|
||||
marker.touch()
|
||||
except OSError as error:
|
||||
print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr)
|
||||
|
||||
|
||||
def view_drive(prefix, exe):
|
||||
path = Path(exe)
|
||||
view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None)
|
||||
@@ -184,6 +297,7 @@ def wine(argv, source_env=None):
|
||||
target.unlink()
|
||||
shutil.copyfile(RUNTIME / 'windows' / name, target)
|
||||
register_classes(command[0], prefix, env)
|
||||
run_install_actions(command[0], prefix, argv[0], env)
|
||||
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
|
||||
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
|
||||
exe, drive = view_drive(prefix, argv[0])
|
||||
@@ -390,7 +504,7 @@ def launch(command, env):
|
||||
raise RuntimeError('No Xbox account channel; start the game from DroidDeck')
|
||||
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190)
|
||||
if not reply or not reply.get('ok'):
|
||||
raise RuntimeError('Xbox account service is unavailable; sign in again and retry')
|
||||
raise RuntimeError((reply or {}).get('reason') or 'Xbox account service is unavailable; sign in again and retry')
|
||||
stopped = threading.Event()
|
||||
close = lambda: None
|
||||
try:
|
||||
@@ -404,7 +518,7 @@ def launch(command, env):
|
||||
context.chmod(0o600)
|
||||
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
|
||||
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
|
||||
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
|
||||
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'none')
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
owned_env.pop(name, None)
|
||||
if reply.get('playfab'):
|
||||
|
||||
@@ -1089,9 +1089,10 @@ NATIVE_CHOICE = object()
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
|
||||
native_choices=(), tools=None):
|
||||
native_choices=(), tools=None, removed=()):
|
||||
tools = tools or {}
|
||||
runnable = {n.lower() for n in runnable}
|
||||
removed = {n.lower() for n in removed} - runnable
|
||||
installed = set(installed)
|
||||
picks = set(picks) | {app for app, platforms in tools.items() if "linux" not in platforms}
|
||||
native = native or {}
|
||||
@@ -1121,7 +1122,7 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
|
||||
target = native.get(app, default)
|
||||
if not name and (app in native_choices or (app in current and app in FEX_DEFAULT_APPS)):
|
||||
target = NATIVE_CHOICE
|
||||
stale = unrunnable(name, runnable)
|
||||
stale = unrunnable(name, runnable) or name.lower() in removed
|
||||
if name and not stale and (mine is None or name != mine):
|
||||
continue
|
||||
if target is NATIVE_CHOICE:
|
||||
@@ -1163,6 +1164,26 @@ def followers(state, current):
|
||||
return {app: name for app, name in current.items() if app != "0" and name == TOOL}
|
||||
|
||||
|
||||
REPLACING = ".droiddeck-experimental-old"
|
||||
|
||||
|
||||
def removed_tools(state, catalog, directory=None):
|
||||
known = state.get("tools") if isinstance(state.get("tools"), list) else ()
|
||||
previous = {t.get("name") for t in known if isinstance(t, dict) and not t.get("valve") and t.get("name")}
|
||||
removed = previous - {t["name"] for t in catalog}
|
||||
if directory is None:
|
||||
return removed
|
||||
known_dirs = {t.get("name"): t.get("dir") for t in known if isinstance(t, dict)}
|
||||
return {name for name in removed if isinstance(known_dirs.get(name), str) and
|
||||
not os.path.lexists(os.path.join(directory, known_dirs[name])) and
|
||||
not os.path.lexists(os.path.join(directory, REPLACING, known_dirs[name]))}
|
||||
|
||||
|
||||
def removed_dirs(state, removed):
|
||||
known = state.get("tools") if isinstance(state.get("tools"), list) else ()
|
||||
return {t["dir"] for t in known if isinstance(t, dict) and not t.get("valve") and t.get("name") in removed and isinstance(t.get("dir"), str)} - {""}
|
||||
|
||||
|
||||
def tool_entry(name, display, path, valve):
|
||||
return {"name": name, "display": display, "dir": os.path.basename(path) if path else "", "valve": valve}
|
||||
|
||||
@@ -1248,15 +1269,19 @@ def valid_game_request(app, request):
|
||||
request["dir"] != "" and isinstance(request.get("valve"), bool)))
|
||||
|
||||
|
||||
def settle_game_requests(requests, state, current, catalog, missing_is_cleared=False):
|
||||
def settle_game_requests(requests, state, current, catalog, missing_is_cleared=False, removed=()):
|
||||
recorded = state.get("games_applied")
|
||||
if isinstance(recorded, dict):
|
||||
applied = dict(recorded)
|
||||
else:
|
||||
applied = dict(requests) if "tools" in state else {}
|
||||
by_name = {t["name"]: t for t in catalog}
|
||||
gone = removed_dirs(state, removed)
|
||||
out = dict(requests)
|
||||
for app, request in requests.items():
|
||||
if isinstance(request, dict) and request.get("valve") is False and isinstance(request.get("dir"), str) and request["dir"] in gone:
|
||||
del out[app]
|
||||
continue
|
||||
if not valid_game_request(app, request) or app not in applied or applied[app] != request:
|
||||
continue
|
||||
if request is None:
|
||||
@@ -1281,10 +1306,10 @@ def settle_game_requests(requests, state, current, catalog, missing_is_cleared=F
|
||||
return out, out != requests
|
||||
|
||||
|
||||
def settled_game_requests(state, current, catalog, missing_is_cleared=False, directory=None):
|
||||
def settled_game_requests(state, current, catalog, missing_is_cleared=False, directory=None, removed=()):
|
||||
for _ in range(2):
|
||||
requests, text = read_game_requests(directory)
|
||||
settled, moved = settle_game_requests(requests, state, current, catalog, missing_is_cleared)
|
||||
settled, moved = settle_game_requests(requests, state, current, catalog, missing_is_cleared, removed)
|
||||
if not moved or write_game_requests(settled, text, directory):
|
||||
return settled
|
||||
return None
|
||||
@@ -1579,7 +1604,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
set_mappings(tokens, mapping, moved)
|
||||
current.update(moved)
|
||||
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
|
||||
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
|
||||
removed = removed_tools(state, catalog, os.path.join(steam_root, "compatibilitytools.d"))
|
||||
requests = settled_game_requests(state, current, catalog, not steam_running(), directory, removed)
|
||||
overrides = requested_games(requests or {}, catalog)
|
||||
managed = state.get("auto", {}).keys() if isinstance(state.get("auto"), dict) else ()
|
||||
native_choices = state.get("native_choices", ())
|
||||
@@ -1590,7 +1616,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
current.setdefault(app, "")
|
||||
changes, auto = plan_mapping(
|
||||
current, apps, names, default, followers(state, current), native, picks,
|
||||
overrides, managed, native_choices, tool_platforms(steam_root))
|
||||
overrides, managed, native_choices, tool_platforms(steam_root), removed)
|
||||
set_mappings(tokens, mapping, changes)
|
||||
text = serialize(tokens)
|
||||
if text != serialize(tokenize(original)):
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -23,10 +23,11 @@
|
||||
#define MAX_ENTRIES 100000
|
||||
#define MAX_HANDLES 64
|
||||
#define MAX_UP 32
|
||||
#define MAX_ALIASES 4
|
||||
#define FUSE_MAGIC 0x65735546
|
||||
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR)
|
||||
#define ABOVE (IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR | IN_MASK_ADD)
|
||||
#define GONE (IN_DELETE_SELF | IN_MOVE_SELF | IN_IGNORED)
|
||||
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ATTRIB | IN_ONLYDIR)
|
||||
#define ABOVE (IN_DELETE_SELF | IN_MOVE_SELF | IN_ATTRIB | IN_ONLYDIR | IN_MASK_ADD)
|
||||
#define GONE (IN_DELETE_SELF | IN_MOVE_SELF | IN_ATTRIB | IN_IGNORED)
|
||||
#define LINKED (IN_DELETE_SELF | IN_MOVE_SELF | IN_DONT_FOLLOW | IN_MASK_ADD)
|
||||
|
||||
#if __SIZEOF_POINTER__ == 8
|
||||
@@ -54,6 +55,9 @@ struct listing {
|
||||
size_t len;
|
||||
char *where;
|
||||
int folds;
|
||||
int loose;
|
||||
char *alias[MAX_ALIASES];
|
||||
int aliases;
|
||||
};
|
||||
|
||||
struct handle {
|
||||
@@ -78,6 +82,7 @@ static struct listing *table[MAX_LISTINGS];
|
||||
static struct handle *handles[MAX_HANDLES];
|
||||
static int high_water;
|
||||
static int cached_listings;
|
||||
static int blind_listings;
|
||||
static int changing;
|
||||
static int notify = -1;
|
||||
static int forked;
|
||||
@@ -171,6 +176,7 @@ static void destroy(struct listing *l) {
|
||||
free(l->e);
|
||||
free(l->recs);
|
||||
free(l->where);
|
||||
for (int i = 0; i < MAX_ALIASES; i++) free(l->alias[i]);
|
||||
free(l);
|
||||
}
|
||||
|
||||
@@ -201,6 +207,7 @@ static void let_go(int wd, const int *up, int nup) {
|
||||
|
||||
static void detach(struct listing *l) {
|
||||
__atomic_sub_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
|
||||
if (l->blind || l->where == NULL) blind_listings--;
|
||||
l->detached = 1;
|
||||
if (l->refs == 0) destroy(l);
|
||||
}
|
||||
@@ -255,6 +262,7 @@ static void pump(struct expect *x, int nx) {
|
||||
changed(-1, 0);
|
||||
continue;
|
||||
}
|
||||
if ((ev->mask & IN_ATTRIB) && ev->len) continue;
|
||||
int k = 0;
|
||||
while (k < nx && !(x[k].wd == ev->wd && (ev->mask & x[k].mask) && ev->len && strcmp(ev->name, x[k].name) == 0)) k++;
|
||||
if (k < nx) {
|
||||
@@ -304,6 +312,7 @@ static int push(struct listing *l, ino_t ino, unsigned char type, const char *na
|
||||
static void install(struct listing *l) {
|
||||
l->detached = 0;
|
||||
__atomic_add_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
|
||||
if (l->blind || l->where == NULL) blind_listings++;
|
||||
int slot = find(l->dev, l->ino);
|
||||
if (slot >= 0) {
|
||||
struct listing *old = table[slot];
|
||||
@@ -416,10 +425,104 @@ __attribute__((constructor)) static void resolve(void) {
|
||||
}
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
static int named(const struct listing *l, const char *name) {
|
||||
for (size_t i = 0; i < l->n; i++)
|
||||
if (strcasecmp(l->e[i].name, name) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int folded_match(const char *where, const char *dir) {
|
||||
const char *at = strstr(where, "/steamapps");
|
||||
if (at == NULL) return 0;
|
||||
size_t n = (size_t)(at - where);
|
||||
return strncmp(where, dir, n) == 0 && strcasecmp(where + n, dir + n) == 0;
|
||||
}
|
||||
|
||||
static int same_dir(const struct listing *l, const char *dir) {
|
||||
struct stat st;
|
||||
int saved = errno;
|
||||
int same = stat(dir, &st) == 0 && st.st_dev == l->dev && st.st_ino == l->ino;
|
||||
errno = saved;
|
||||
return same;
|
||||
}
|
||||
|
||||
static int plain(const char *where, char *dir) {
|
||||
const char *at = strstr(where, "/steamapps");
|
||||
int saved = errno, fine = at != NULL;
|
||||
for (size_t from = fine ? (size_t)(at - where) + 1 : 0; fine && dir[from];) {
|
||||
size_t to = from + strcspn(dir + from, "/");
|
||||
char kept = dir[to];
|
||||
struct stat st;
|
||||
dir[to] = 0;
|
||||
fine = strcmp(dir + from, ".") != 0 && strcmp(dir + from, "..") != 0 && lstat(dir, &st) == 0 && !S_ISLNK(st.st_mode);
|
||||
dir[to] = kept;
|
||||
from = kept ? to + 1 : to;
|
||||
}
|
||||
errno = saved;
|
||||
return fine;
|
||||
}
|
||||
|
||||
static int aliased(struct listing *l, const char *dir) {
|
||||
for (int i = 0; i < MAX_ALIASES; i++)
|
||||
if (l->alias[i] && strcmp(l->alias[i], dir) == 0) return 1;
|
||||
if (!same_dir(l, dir)) return 0;
|
||||
char *copy = strdup(dir);
|
||||
if (copy && !plain(l->where, copy)) {
|
||||
free(copy);
|
||||
copy = NULL;
|
||||
}
|
||||
if (copy) {
|
||||
int at = l->aliases++ % MAX_ALIASES;
|
||||
free(l->alias[at]);
|
||||
l->alias[at] = copy;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static struct listing *listed(const char *dir, long long now) {
|
||||
for (int i = 0; i < MAX_LISTINGS; i++) {
|
||||
struct listing *l = table[i];
|
||||
if (l == NULL || l->where == NULL || l->blind || now - l->filled >= DIR_TTL_NS) continue;
|
||||
if (strcmp(l->where, dir) == 0) return l;
|
||||
if (l->folds && folded_match(l->where, dir)) return aliased(l, dir) ? l : NULL;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int watching(const char *path) {
|
||||
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
|
||||
}
|
||||
|
||||
static DIR *listed_open(struct handle *h, long long now) {
|
||||
DIR *d = NULL;
|
||||
if (__atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) == 0) return NULL;
|
||||
take(&lock);
|
||||
if (!changing) {
|
||||
pump(NULL, 0);
|
||||
struct listing *l = listed(h->path, now);
|
||||
if (l && records(l) == 0) {
|
||||
h->snap = l;
|
||||
l->refs++;
|
||||
l->used = now;
|
||||
d = wrap(h);
|
||||
if (d == NULL) {
|
||||
unref(l);
|
||||
h->snap = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
give(&lock);
|
||||
return d;
|
||||
}
|
||||
|
||||
static DIR *hit(const struct stat *st, struct handle *h, long long now) {
|
||||
take(&lock);
|
||||
if (!changing) pump(NULL, 0);
|
||||
int slot = find(st->st_dev, st->st_ino);
|
||||
if (slot >= 0 && table[slot]->loose && now - table[slot]->filled < DIR_TTL_NS) {
|
||||
stamp(table[slot], st);
|
||||
table[slot]->loose = 0;
|
||||
}
|
||||
if (slot >= 0 && same(table[slot], st) && now - table[slot]->filled < DIR_TTL_NS && records(table[slot]) == 0) {
|
||||
h->snap = table[slot];
|
||||
h->snap->refs++;
|
||||
@@ -509,8 +612,7 @@ static void untrack(struct handle *h) {
|
||||
DIR *opendir(const char *path) {
|
||||
NEXT(opendir);
|
||||
struct stat st;
|
||||
if (!eligible(path) || stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !on_fuse(st.st_dev, path))
|
||||
return next_opendir(path);
|
||||
if (!eligible(path)) return next_opendir(path);
|
||||
struct handle *h = calloc(1, sizeof(*h));
|
||||
char *copy = strdup(path);
|
||||
if (h == NULL || copy == NULL) {
|
||||
@@ -522,7 +624,14 @@ DIR *opendir(const char *path) {
|
||||
h->wd = -1;
|
||||
h->path = copy;
|
||||
long long now = now_ns();
|
||||
DIR *d = hit(&st, h, now);
|
||||
DIR *d = listed_open(h, now);
|
||||
if (d) return d;
|
||||
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !on_fuse(st.st_dev, path)) {
|
||||
free(h->path);
|
||||
free(h);
|
||||
return next_opendir(path);
|
||||
}
|
||||
d = hit(&st, h, now);
|
||||
if (d) return d;
|
||||
if (!track(h, path)) {
|
||||
free(h->path);
|
||||
@@ -699,7 +808,9 @@ void seekdir(DIR *d, long pos) {
|
||||
}
|
||||
}
|
||||
|
||||
struct side { char dir[PATH_MAX]; const char *name; struct stat before; int known; };
|
||||
struct side { char dir[PATH_MAX]; const char *name; struct stat before; int known; int trusted; };
|
||||
|
||||
struct made { int known; ino_t ino; unsigned char type; };
|
||||
|
||||
static int split(const char *path, struct side *s) {
|
||||
size_t n = strlen(path);
|
||||
@@ -713,10 +824,6 @@ static int split(const char *path, struct side *s) {
|
||||
return strchr(s->name, '/') == NULL && strcmp(s->name, ".") != 0 && strcmp(s->name, "..") != 0;
|
||||
}
|
||||
|
||||
static int watching(const char *path) {
|
||||
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
|
||||
}
|
||||
|
||||
static void begin(void) {
|
||||
take(&lock);
|
||||
pump(NULL, 0);
|
||||
@@ -725,13 +832,42 @@ static void begin(void) {
|
||||
}
|
||||
|
||||
static void before(struct side *s) {
|
||||
s->known = stat(s->dir, &s->before) == 0;
|
||||
take(&lock);
|
||||
struct listing *l = listed(s->dir, now_ns());
|
||||
int unlisted = l == NULL && blind_listings == 0;
|
||||
s->trusted = l != NULL;
|
||||
if (l) {
|
||||
memset(&s->before, 0, sizeof(s->before));
|
||||
s->before.st_dev = l->dev;
|
||||
s->before.st_ino = l->ino;
|
||||
s->before.st_size = l->size;
|
||||
s->before.st_nlink = l->nlink;
|
||||
s->before.st_mtim = l->mtime;
|
||||
s->before.st_ctim = l->ctime;
|
||||
}
|
||||
give(&lock);
|
||||
s->known = s->trusted || (!unlisted && stat(s->dir, &s->before) == 0);
|
||||
}
|
||||
|
||||
static unsigned char type_of(mode_t mode) {
|
||||
return S_ISDIR(mode) ? DT_DIR : S_ISLNK(mode) ? DT_LNK : S_ISREG(mode) ? DT_REG : DT_UNKNOWN;
|
||||
}
|
||||
|
||||
static int made_at(const struct side *s, const char *target, struct made *m) {
|
||||
struct stat t;
|
||||
if (s->trusted && m && m->known) return 1;
|
||||
if (lstat(target, &t) != 0) return 0;
|
||||
*m = (struct made){1, t.st_ino, type_of(t.st_mode)};
|
||||
return 1;
|
||||
}
|
||||
|
||||
enum { ADDED, REMOVED };
|
||||
|
||||
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct expect *x) {
|
||||
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct made *m,
|
||||
struct expect *x) {
|
||||
struct stat now;
|
||||
struct made local = {0};
|
||||
if (m == NULL) m = &local;
|
||||
if (!s->known) return 0;
|
||||
int slot = find(s->before.st_dev, s->before.st_ino);
|
||||
if (slot < 0) return 0;
|
||||
@@ -750,7 +886,7 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
|
||||
drop(slot);
|
||||
return 0;
|
||||
}
|
||||
if (stat(s->dir, &now) != 0 || now.st_ino != l->ino) {
|
||||
if (!s->trusted && (stat(s->dir, &now) != 0 || now.st_ino != l->ino)) {
|
||||
drop(slot);
|
||||
return 0;
|
||||
}
|
||||
@@ -771,6 +907,7 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
|
||||
copy->blind = l->blind;
|
||||
copy->where = l->where ? strdup(l->where) : NULL;
|
||||
copy->folds = l->folds;
|
||||
copy->loose = l->loose;
|
||||
copy->detached = 0;
|
||||
stamp(copy, &s->before);
|
||||
table[slot] = copy;
|
||||
@@ -781,18 +918,17 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
|
||||
l->recs = NULL;
|
||||
l->len = 0;
|
||||
int fine = 1, expected = 1;
|
||||
struct stat t;
|
||||
if (what == ADDED) {
|
||||
if (exact < l->n) {
|
||||
if (lstat(target, &t) == 0) l->e[exact].ino = t.st_ino;
|
||||
if (event == IN_MOVED_TO && made_at(s, target, m)) l->e[exact].ino = m->ino;
|
||||
expected = event == IN_MOVED_TO;
|
||||
} else if (folded < l->n || lstat(target, &t) != 0) {
|
||||
} else if (folded < l->n || !made_at(s, target, m)) {
|
||||
fine = 0;
|
||||
} else {
|
||||
unsigned char type = S_ISDIR(t.st_mode) ? DT_DIR : S_ISLNK(t.st_mode) ? DT_LNK : S_ISREG(t.st_mode) ? DT_REG : DT_UNKNOWN;
|
||||
fine = l->n < MAX_ENTRIES && push(l, t.st_ino, type, s->name) == 0;
|
||||
fine = l->n < MAX_ENTRIES && push(l, m->ino, m->type, s->name) == 0;
|
||||
}
|
||||
} else if (exact < l->n) {
|
||||
*m = (struct made){1, l->e[exact].ino, l->e[exact].type};
|
||||
free(l->e[exact].name);
|
||||
memmove(&l->e[exact], &l->e[exact + 1], (l->n - exact - 1) * sizeof(l->e[0]));
|
||||
l->n--;
|
||||
@@ -803,7 +939,8 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
|
||||
drop(slot);
|
||||
return 0;
|
||||
}
|
||||
stamp(l, &now);
|
||||
if (s->trusted) l->loose = 1;
|
||||
else stamp(l, &now);
|
||||
if (!expected) return 0;
|
||||
*x = (struct expect){l->wd, event, s->name};
|
||||
return 1;
|
||||
@@ -829,8 +966,11 @@ int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
|
||||
int fd = real(dirfd, path, flags, mode);
|
||||
int saved = errno;
|
||||
struct expect x;
|
||||
struct stat opened;
|
||||
struct made m = {0};
|
||||
if (fd >= 0 && s.trusted && fstat(fd, &opened) == 0) m = (struct made){1, opened.st_ino, type_of(opened.st_mode)};
|
||||
take(&lock);
|
||||
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &x);
|
||||
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &m, &x);
|
||||
give(&lock);
|
||||
end(&x, nx);
|
||||
give(&oplock);
|
||||
@@ -850,7 +990,7 @@ int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
|
||||
int saved = errno; \
|
||||
struct expect x; \
|
||||
take(&lock); \
|
||||
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, &x); \
|
||||
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, NULL, &x); \
|
||||
if (r == 0 && what == REMOVED) forget_below(path); \
|
||||
give(&lock); \
|
||||
end(&x, nx); \
|
||||
@@ -885,12 +1025,13 @@ ONE_PATH(remove, REMOVED, IN_DELETE, dd_descriptor_remove(path, next_remove))
|
||||
int r = call(from, to); \
|
||||
int saved = errno; \
|
||||
struct expect x[2]; \
|
||||
struct made m = {0}; \
|
||||
int nx = 0; \
|
||||
take(&lock); \
|
||||
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &x[nx]); \
|
||||
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &m, &x[nx]); \
|
||||
if (track_b) { \
|
||||
if (track_a && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
|
||||
nx += patch(&b, ADDED, event, r == 0, saved, to, &x[nx]); \
|
||||
if (track_a && !b.trusted && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
|
||||
nx += patch(&b, ADDED, event, r == 0, saved, to, &m, &x[nx]); \
|
||||
} \
|
||||
if (r == 0 && gone) { forget_below(from); forget_below(to); } \
|
||||
give(&lock); \
|
||||
@@ -907,37 +1048,6 @@ TWO_PATHS(rename, 1, IN_MOVED_TO, moved)
|
||||
TWO_PATHS(link, 0, IN_CREATE, link_or_lock)
|
||||
TWO_PATHS(symlink, 0, IN_CREATE, next_symlink)
|
||||
|
||||
static int named(const struct listing *l, const char *name) {
|
||||
for (size_t i = 0; i < l->n; i++)
|
||||
if (strcasecmp(l->e[i].name, name) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int folded_match(const char *where, const char *dir) {
|
||||
const char *at = strstr(where, "/steamapps");
|
||||
if (at == NULL) return 0;
|
||||
size_t n = (size_t)(at - where);
|
||||
return strncmp(where, dir, n) == 0 && strcasecmp(where + n, dir + n) == 0;
|
||||
}
|
||||
|
||||
static int same_dir(const struct listing *l, const char *dir) {
|
||||
struct stat st;
|
||||
int saved = errno;
|
||||
int same = stat(dir, &st) == 0 && st.st_dev == l->dev && st.st_ino == l->ino;
|
||||
errno = saved;
|
||||
return same;
|
||||
}
|
||||
|
||||
static int listed_absent(const char *dir, const char *name, long long now) {
|
||||
for (int i = 0; i < MAX_LISTINGS; i++) {
|
||||
struct listing *l = table[i];
|
||||
if (l == NULL || l->where == NULL || l->blind || now - l->filled >= DIR_TTL_NS) continue;
|
||||
if (strcmp(l->where, dir) == 0) return !named(l, name);
|
||||
if (l->folds && folded_match(l->where, dir)) return same_dir(l, dir) && !named(l, name);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int dd_dircache_absent(const char *path) __attribute__((visibility("hidden")));
|
||||
int dd_dircache_absent(const char *path) {
|
||||
struct side s;
|
||||
@@ -949,7 +1059,8 @@ int dd_dircache_absent(const char *path) {
|
||||
int absent = 0;
|
||||
if (!changing) {
|
||||
pump(NULL, 0);
|
||||
absent = listed_absent(s.dir, s.name, now);
|
||||
struct listing *l = listed(s.dir, now);
|
||||
absent = l != NULL && !named(l, s.name);
|
||||
}
|
||||
give(&lock);
|
||||
return absent;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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, ...) {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <pthread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -55,12 +56,16 @@ static unsigned hash_of(const char *s, int kind, int mode, int flags) {
|
||||
return h;
|
||||
}
|
||||
|
||||
static struct entry *slot(unsigned h) {
|
||||
return &table[(h ^ (h >> 16)) % PATH_CACHE_SLOTS];
|
||||
}
|
||||
|
||||
static int cacheable(const char *path) {
|
||||
return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled();
|
||||
}
|
||||
|
||||
static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) {
|
||||
struct entry *e = &table[h % PATH_CACHE_SLOTS];
|
||||
struct entry *e = slot(h);
|
||||
|
||||
if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL;
|
||||
if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL;
|
||||
@@ -68,7 +73,7 @@ static struct entry *find(const char *path, int kind, int mode, int flags, unsig
|
||||
}
|
||||
|
||||
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
|
||||
struct entry *e = &table[h % PATH_CACHE_SLOTS];
|
||||
struct entry *e = slot(h);
|
||||
char *copy = value != NULL ? strdup(value) : NULL;
|
||||
|
||||
if (value != NULL && copy == NULL) return;
|
||||
@@ -172,6 +177,10 @@ static int check_cwd(const char *path, int mode, int flags) {
|
||||
return result;
|
||||
}
|
||||
|
||||
static int absolute(const char *path) {
|
||||
return path != NULL && path[0] == '/';
|
||||
}
|
||||
|
||||
int access(const char *path, int mode) {
|
||||
return cached_access(path, mode, 0, check_cwd);
|
||||
}
|
||||
@@ -188,7 +197,7 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
|
||||
int (*real)(int, const char *, int, int);
|
||||
int err;
|
||||
|
||||
if (dirfd == AT_FDCWD) {
|
||||
if (dirfd == AT_FDCWD || absolute(path)) {
|
||||
return cached_access(path, mode, flags, check_cwd);
|
||||
}
|
||||
real = next_faccessat();
|
||||
@@ -202,3 +211,15 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int __xstat64(int version, const char *path, struct stat64 *out) {
|
||||
static int (*real)(int, const char *, struct stat64 *);
|
||||
|
||||
if (dd_dircache_absent && dd_dircache_absent(path)) {
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
}
|
||||
if (real == NULL) real = (int (*)(int, const char *, struct stat64 *))dlsym(RTLD_NEXT, "__xstat64");
|
||||
if (real != NULL) return real(version, path, out);
|
||||
return stat64(path, out);
|
||||
}
|
||||
@@ -100,7 +100,11 @@ static long path_statx(int dirfd, const char *path, int flags, unsigned int mask
|
||||
return next_statx(dirfd, path, flags, mask, out);
|
||||
}
|
||||
|
||||
void bl_inputudev_note_dlopen(const char *path, void *handle) __attribute__((weak, visibility("hidden")));
|
||||
|
||||
void *dlopen(const char *filename, int flags) {
|
||||
void *handle;
|
||||
|
||||
if (!real_dlopen) {
|
||||
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
|
||||
}
|
||||
@@ -109,7 +113,9 @@ void *dlopen(const char *filename, int flags) {
|
||||
if (basename && strcmp(basename, "vrclient.so") == 0) {
|
||||
flags &= ~RTLD_DEEPBIND;
|
||||
}
|
||||
return real_dlopen(filename, flags);
|
||||
handle = real_dlopen != NULL ? real_dlopen(filename, flags) : NULL;
|
||||
if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
int dd_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
|
||||
|
||||
@@ -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;
|
||||
|
||||
+419
-78
@@ -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>
|
||||
|
||||
|
||||
@@ -20,31 +24,220 @@
|
||||
#define ZR_CTL "/tmp/.dd-zram"
|
||||
#endif
|
||||
#define ZR_SWAPPED (1ULL << 62)
|
||||
#define ZR_PRESENT (1ULL << 63)
|
||||
#define ZR_BATCH 512
|
||||
#define ZR_CHUNK (1UL << 20)
|
||||
#define ZR_SLOTS 32768UL
|
||||
#define ZR_PROBES 16
|
||||
#define ZR_HEAT_MAX 3
|
||||
#define ZR_SKIP 32U
|
||||
#define ZR_INLINE_KB (32UL << 10)
|
||||
#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];
|
||||
static char zr_sink[ZR_BATCH];
|
||||
static struct zr_slot {
|
||||
unsigned long key;
|
||||
uint16_t gen;
|
||||
uint16_t pushed;
|
||||
uint16_t kept;
|
||||
uint8_t heat;
|
||||
uint8_t skip;
|
||||
} zr_slots[ZR_SLOTS];
|
||||
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);
|
||||
}
|
||||
|
||||
static int zr_mode(void) {
|
||||
char c = 0;
|
||||
int fd = zr_open(ZR_CTL);
|
||||
if (fd < 0) return -1;
|
||||
long n = zr_sys(SYS_read, fd, &c, 1);
|
||||
zr_sys(SYS_close, fd);
|
||||
return n == 1 && (c == '0' || c == '1') ? c - '0' : -1;
|
||||
static int zr_mode(unsigned long *want) {
|
||||
char text[24];
|
||||
long n = 0;
|
||||
int fd = zr_open(ZR_CTL ".hold");
|
||||
if (fd >= 0) {
|
||||
n = zr_sys(SYS_read, fd, text, sizeof(text));
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
if (n < 1) {
|
||||
fd = zr_open(ZR_CTL);
|
||||
if (fd < 0) return -1;
|
||||
n = zr_sys(SYS_read, fd, text, sizeof(text));
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
if (n < 1 || text[0] < '0' || text[0] > '3') return -1;
|
||||
unsigned long kb = 0;
|
||||
for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++)
|
||||
kb = kb * 10 + (unsigned long)(text[i] - '0');
|
||||
*want = kb / (zr_page / 1024);
|
||||
if (text[0] >= '2' && *want == 0) return -1;
|
||||
return text[0] - '0';
|
||||
}
|
||||
|
||||
static unsigned long zr_hex(const char **p) {
|
||||
@@ -69,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) {
|
||||
@@ -96,43 +289,131 @@ static void zr_read_back(int pagemap, unsigned long start, unsigned long end) {
|
||||
}
|
||||
}
|
||||
|
||||
static void zr_walk(int compress) {
|
||||
int maps = zr_open("/proc/self/maps");
|
||||
if (maps < 0) return;
|
||||
int pagemap = compress ? -1 : zr_open("/proc/self/pagemap");
|
||||
if (!compress && pagemap < 0) {
|
||||
zr_sys(SYS_close, maps);
|
||||
return;
|
||||
static unsigned long zr_count(int pagemap, unsigned long start, unsigned long end, uint64_t bit) {
|
||||
unsigned long count = 0;
|
||||
long size = (long)((end - start) / zr_page * sizeof(uint64_t));
|
||||
long got;
|
||||
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 == -EINTR);
|
||||
if (got != size) return ZR_FAILED;
|
||||
for (long i = 0; i < got / (long)sizeof(uint64_t); i++)
|
||||
if (zr_entries[i] & bit) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
static struct zr_slot *zr_slot(unsigned long addr, int create) {
|
||||
unsigned long key = addr / zr_page + 1;
|
||||
unsigned long home = key * 2654435761UL % ZR_SLOTS;
|
||||
for (unsigned long i = 0; i < ZR_PROBES; i++) {
|
||||
struct zr_slot *slot = &zr_slots[(home + i) % ZR_SLOTS];
|
||||
if (slot->key == key) return slot;
|
||||
if (slot->key == 0 && !create) return NULL;
|
||||
if (slot->key == 0) {
|
||||
slot->key = key;
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
if (!create) return NULL;
|
||||
zr_slots[home] = (struct zr_slot){.key = key};
|
||||
return &zr_slots[home];
|
||||
}
|
||||
|
||||
static unsigned long zr_trim(int pagemap, unsigned long start, unsigned long end,
|
||||
unsigned long want, int force, unsigned long lo, unsigned long hi) {
|
||||
unsigned long done = 0;
|
||||
for (unsigned long addr = start, next; addr < end && done < want; addr = next) {
|
||||
next = (addr | (ZR_CHUNK - 1)) + 1;
|
||||
if (next > end || next < addr) next = end;
|
||||
if (next <= lo || addr >= hi) continue;
|
||||
if (zr_visits == 0) break;
|
||||
zr_visits--;
|
||||
zr_cursor = next;
|
||||
if (addr < (unsigned long)(zr_slots + ZR_SLOTS) && next > (unsigned long)zr_slots) continue;
|
||||
unsigned long present = zr_count(pagemap, addr, next, ZR_PRESENT);
|
||||
if (present == ZR_FAILED) continue;
|
||||
struct zr_slot *slot = zr_slot(addr, 0);
|
||||
if (slot != NULL && slot->gen == zr_gen && slot->pushed > 0) {
|
||||
if (present > slot->kept && (present - slot->kept) * 4 > slot->pushed) {
|
||||
if (slot->heat < ZR_HEAT_MAX) slot->heat++;
|
||||
slot->skip = (uint8_t)(ZR_SKIP << slot->heat > 255 ? 255 : ZR_SKIP << slot->heat);
|
||||
slot->pushed = 0;
|
||||
} else if (slot->heat > 0) {
|
||||
slot->heat--;
|
||||
}
|
||||
}
|
||||
if (slot != NULL && slot->skip > 0 && !force) {
|
||||
slot->skip--;
|
||||
continue;
|
||||
}
|
||||
if (present == 0) continue;
|
||||
unsigned long from = addr < lo ? lo : addr;
|
||||
unsigned long left = present;
|
||||
while (from < next && done + present - left < want) {
|
||||
unsigned long budget = want - done - (present - left);
|
||||
unsigned long i = (from - addr) / zr_page;
|
||||
for (; i < (next - addr) / zr_page && budget > 0; i++)
|
||||
if (zr_entries[i] & ZR_PRESENT) budget--;
|
||||
unsigned long to = addr + i * zr_page;
|
||||
zr_sys(SYS_madvise, from, to - from, MADV_PAGEOUT);
|
||||
from = to;
|
||||
unsigned long now = zr_count(pagemap, addr, next, ZR_PRESENT);
|
||||
if (now == ZR_FAILED) break;
|
||||
left = now < present ? now : present;
|
||||
}
|
||||
if (from < next) zr_cursor = from;
|
||||
if (left >= present) continue;
|
||||
if (slot == NULL) slot = zr_slot(addr, 1);
|
||||
if (slot->gen != zr_gen) slot->pushed = 0;
|
||||
slot->gen = zr_gen;
|
||||
slot->pushed = (uint16_t)(slot->pushed + present - left);
|
||||
slot->kept = (uint16_t)left;
|
||||
done += present - left;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, unsigned long hi) {
|
||||
int maps = zr_open("/proc/self/maps");
|
||||
if (maps < 0) return 0;
|
||||
int pagemap = mode == 1 ? -1 : zr_open("/proc/self/pagemap");
|
||||
if (mode != 1 && pagemap < 0) {
|
||||
zr_sys(SYS_close, maps);
|
||||
return 0;
|
||||
}
|
||||
unsigned long done = 0;
|
||||
size_t have = 0;
|
||||
for (;;) {
|
||||
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 ((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, compress, &s, &e) && e > s) {
|
||||
if (compress) zr_sys(SYS_madvise, s, e - s, MADV_PAGEOUT);
|
||||
else zr_read_back(pagemap, s, e);
|
||||
if (zr_eligible(line, mode != 0, &s, &e) && e > s) {
|
||||
if (mode == 0) zr_read_back(pagemap, s, e);
|
||||
else if (mode == 1) zr_sys(SYS_madvise, s, e - s, MADV_PAGEOUT);
|
||||
else done += zr_trim(pagemap, s, e, want - done, mode == 3, lo, hi);
|
||||
}
|
||||
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);
|
||||
zr_sys(SYS_close, maps);
|
||||
return done;
|
||||
}
|
||||
|
||||
static void zr_ack(int done) {
|
||||
static const char suffix[] = ".ack.";
|
||||
char path[sizeof(ZR_CTL) + sizeof(suffix) + 20];
|
||||
static void zr_ack(long value, int trim) {
|
||||
const char *suffix = trim ? ".trim." : ".ack.";
|
||||
char path[sizeof(ZR_CTL) + sizeof(".trim.") + 20];
|
||||
char digits[20];
|
||||
size_t n = 0, d = 0;
|
||||
for (const char *p = ZR_CTL; *p; p++) path[n++] = *p;
|
||||
@@ -143,26 +424,113 @@ static void zr_ack(int done) {
|
||||
path[n] = 0;
|
||||
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
if (fd < 0) return;
|
||||
if (done) zr_sys(SYS_write, fd, "1", 1UL);
|
||||
for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10);
|
||||
for (n = 0; d > 0;) path[n++] = digits[--d];
|
||||
if (n > 0) zr_sys(SYS_write, fd, path, n);
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
|
||||
static void zr_request(void) {
|
||||
int mode = zr_mode();
|
||||
if (mode == 1) zr_ack(0);
|
||||
if (mode >= 0) zr_walk(mode);
|
||||
if (mode == 1) zr_ack(1);
|
||||
static void zr_request(int worker) {
|
||||
unsigned long want = 0;
|
||||
int mode = zr_mode(&want);
|
||||
if (mode < 0) return;
|
||||
if (!worker && want > ZR_INLINE_KB / (zr_page / 1024)) want = ZR_INLINE_KB / (zr_page / 1024);
|
||||
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
|
||||
if (mode > 0) zr_ack(-1, mode > 1);
|
||||
if (mode < 2) {
|
||||
zr_walk(mode, 1, 0, 0);
|
||||
zr_gen++;
|
||||
if (mode == 1) zr_ack(1, 0);
|
||||
return;
|
||||
}
|
||||
unsigned long from = zr_cursor;
|
||||
unsigned long done = zr_walk(mode, want, from, ~0UL);
|
||||
if (done < want && from > 0) done += zr_walk(mode, want - done, 0, from);
|
||||
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();
|
||||
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) {
|
||||
@@ -170,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();
|
||||
__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;
|
||||
@@ -206,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);
|
||||
}
|
||||
Reference in new issue
Block a user