mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
Merge branch 'main' into fix/gog-native-installer-extract
This commit is contained in:
commit
d006538f13
182 files changed
+9467
-698
No files matched your search
@@ -61,9 +61,9 @@ def build(full, lite, palm, output):
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--full', type=Path, default=Path('app/src/main/assets/models/hand_landmarker.task'))
|
||||
parser.add_argument('--full', type=Path, required=True)
|
||||
parser.add_argument('--lite', type=Path, required=True, help='Pinned hand_landmark_lite.tflite from storage.googleapis.com/mediapipe-assets/')
|
||||
parser.add_argument('--palm', type=Path, required=True, help='Pinned palm_detection_lite.tflite from storage.googleapis.com/mediapipe-assets/')
|
||||
parser.add_argument('--output', type=Path, default=Path('app/src/main/assets/models/hand_landmarker_lite.task'))
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
build(args.full, args.lite, args.palm, args.output)
|
||||
@@ -364,6 +364,7 @@ if ! restore_step comet "${comet_key}" "${comet_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
|
||||
save_step comet "${comet_key}" "${comet_out}"
|
||||
fi
|
||||
bash tools/packs/build.sh app/build/packs
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
|
||||
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
|
||||
|
||||
@@ -126,6 +126,7 @@ struct userdata {
|
||||
unsigned int decay_backoff, cb_count, wd_last_cb;
|
||||
int reopen_running, reopen_redo;
|
||||
int consuming, primed, starved;
|
||||
int suspended;
|
||||
volatile int dead;
|
||||
|
||||
/* what the IO thread last logged, so engine changes made on the AAudio thread get a line */
|
||||
@@ -302,6 +303,7 @@ static void out_error_cb(AAudioStream *aq, void *user, aaudio_result_t error) {
|
||||
struct userdata *u = user;
|
||||
|
||||
if (aq != __atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return;
|
||||
if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) return;
|
||||
/* A disconnected stream (headphones plugged or unplugged, a Bluetooth route coming or going)
|
||||
* can never be restarted: it has to be closed and a new one opened on the current route. */
|
||||
if (error != AAUDIO_ERROR_DISCONNECTED &&
|
||||
@@ -400,6 +402,8 @@ static void *reopen_thread(void *user) {
|
||||
pthread_mutex_lock(&u->lock);
|
||||
old = u->aq;
|
||||
__atomic_store_n(&u->aq, neu, __ATOMIC_SEQ_CST);
|
||||
if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST))
|
||||
AAudioStream_requestStop(neu);
|
||||
pthread_mutex_unlock(&u->lock);
|
||||
} else
|
||||
pa_log("directaudio-native-sink: reopen failed; keeping the old stream");
|
||||
@@ -575,6 +579,34 @@ static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offse
|
||||
return pa_sink_process_msg(o, code, data, offset, chunk);
|
||||
}
|
||||
|
||||
/* A started AAudio stream keeps audioserver's AudioMix wake lock held, so the device never
|
||||
* suspends while the session sleeps: stop it, and the IO thread's timer, until the sink reopens. */
|
||||
static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
|
||||
struct userdata *u = s->userdata;
|
||||
aaudio_result_t res = AAUDIO_OK;
|
||||
|
||||
if (new_state == PA_SINK_SUSPENDED && !u->suspended) {
|
||||
pthread_mutex_lock(&u->lock);
|
||||
__atomic_store_n(&u->suspended, 1, __ATOMIC_SEQ_CST);
|
||||
if (u->aq) AAudioStream_requestStop(u->aq);
|
||||
pthread_mutex_unlock(&u->lock);
|
||||
pa_rtpoll_set_timer_disabled(u->rtpoll);
|
||||
pa_log("directaudio-native-sink: suspended; output stopped");
|
||||
} else if (PA_SINK_IS_OPENED(new_state) && u->suspended) {
|
||||
pthread_mutex_lock(&u->lock);
|
||||
__atomic_store_n(&u->suspended, 0, __ATOMIC_SEQ_CST);
|
||||
u->primed = 0;
|
||||
__atomic_store_n(&u->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
|
||||
u->wd_last_tick_ns = 0;
|
||||
if (u->aq) res = AAudioStream_requestStart(u->aq);
|
||||
pthread_mutex_unlock(&u->lock);
|
||||
if (res != AAUDIO_OK || !u->aq) request_reopen(u, "resume");
|
||||
pa_rtpoll_set_timer_relative(u->rtpoll, 0);
|
||||
pa_log("directaudio-native-sink: resumed");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void thread_func(void *userdata) {
|
||||
struct userdata *u = userdata;
|
||||
|
||||
@@ -592,8 +624,10 @@ static void thread_func(void *userdata) {
|
||||
/* Half a burst between visits, never blocking on the stream: clients' audio reaches this
|
||||
* thread as messages pa_rtpoll_run handles, and a thread stuck in a write or a wait lets
|
||||
* them run dry (the crackle #338 fixed). */
|
||||
service_ring(u);
|
||||
pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC));
|
||||
if (!u->suspended) {
|
||||
service_ring(u);
|
||||
pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC));
|
||||
}
|
||||
|
||||
if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
|
||||
goto fail;
|
||||
@@ -727,6 +761,7 @@ int pa__init(pa_module *m) {
|
||||
goto fail;
|
||||
}
|
||||
u->sink->parent.process_msg = sink_process_msg;
|
||||
u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
|
||||
u->sink->userdata = u;
|
||||
pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
|
||||
pa_sink_set_rtpoll(u->sink, u->rtpoll);
|
||||
|
||||
@@ -9,7 +9,7 @@ for bad in libstdc++.so.6 libgcc_s.so.1; do
|
||||
done
|
||||
syms() { "${READELF:-readelf}" -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; }
|
||||
FAKE=$(syms "$D/libfakeinput.so")
|
||||
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
|
||||
for sym in open openat ioctl read readv close poll ppoll select stat fstat access scandir; do
|
||||
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
|
||||
done
|
||||
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
|
||||
|
||||
@@ -23,6 +23,7 @@ import json
|
||||
import math
|
||||
import re
|
||||
import os
|
||||
import select
|
||||
import selectors
|
||||
import signal
|
||||
import socket
|
||||
@@ -532,6 +533,111 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
|
||||
ws.close()
|
||||
|
||||
|
||||
KEYBOARD_BINDING = "droiddeckSteamKeyboard"
|
||||
KEYBOARD_CHECK_SECONDS = 30
|
||||
KEYBOARD_JS = r"""
|
||||
(() => {
|
||||
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
|
||||
self.check = () => {
|
||||
let showing = false;
|
||||
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
|
||||
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
|
||||
if (!value) continue;
|
||||
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
|
||||
self.watched.add(value);
|
||||
value.Subscribe(() => setTimeout(() => self.check()));
|
||||
}
|
||||
if (value.m_currentValue === true) showing = true;
|
||||
}
|
||||
if (showing !== self.last) {
|
||||
self.last = showing;
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(showing));
|
||||
}
|
||||
return showing;
|
||||
};
|
||||
self.timer = self.timer || setInterval(() => self.check(), 500);
|
||||
return self.check();
|
||||
})()
|
||||
""".replace("__BINDING__", KEYBOARD_BINDING)
|
||||
|
||||
|
||||
class KeyboardWatcher(threading.Thread):
|
||||
def __init__(self, agent_dir):
|
||||
super().__init__(daemon=True, name="keyboard")
|
||||
self.agent_dir = agent_dir
|
||||
self.path = agent_dir / "keyboard.json"
|
||||
self.showing = None
|
||||
self.seq = 0
|
||||
self.next_id = 0
|
||||
self.attached = False
|
||||
|
||||
def report(self, showing):
|
||||
if showing == self.showing:
|
||||
return
|
||||
self.showing = showing
|
||||
self.seq += 1
|
||||
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
|
||||
|
||||
def run(self):
|
||||
failures, last = 0, None
|
||||
while True:
|
||||
try:
|
||||
self.watch()
|
||||
except Exception as e:
|
||||
if self.attached:
|
||||
log("Steam keyboard: lost the client (%s); reattaching" % e)
|
||||
failures = 0
|
||||
elif str(e) != last:
|
||||
log("Steam keyboard: waiting for the client (%s)" % e)
|
||||
self.attached = False
|
||||
last = str(e)
|
||||
self.report(False)
|
||||
failures += 1
|
||||
time.sleep(min(2 * failures, 10))
|
||||
|
||||
def watch(self):
|
||||
targets = [t for t in cdp_targets(self.agent_dir)
|
||||
if t.get("title") == "SharedJSContext" and t.get("webSocketDebuggerUrl")]
|
||||
if not targets:
|
||||
raise AgentError("NO_TARGET", "No SharedJSContext yet")
|
||||
ws = WebSocket(targets[0]["webSocketDebuggerUrl"], 5)
|
||||
try:
|
||||
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
|
||||
self.report(self.install(ws))
|
||||
self.attached = True
|
||||
while True:
|
||||
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
|
||||
self.report(self.install(ws))
|
||||
continue
|
||||
self.event(json.loads(ws.recv()))
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
def install(self, ws):
|
||||
result = self.call(ws, "Runtime.evaluate", {"expression": KEYBOARD_JS, "returnByValue": True})
|
||||
if result.get("exceptionDetails"):
|
||||
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
|
||||
return result.get("result", {}).get("value") is True
|
||||
|
||||
def call(self, ws, method, params):
|
||||
self.next_id += 1
|
||||
ws.send(json.dumps({"id": self.next_id, "method": method, "params": params}))
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
message = json.loads(ws.recv())
|
||||
if message.get("id") == self.next_id:
|
||||
if "error" in message:
|
||||
raise AgentError("CDP_ERROR", json.dumps(message["error"]))
|
||||
return message.get("result", {})
|
||||
self.event(message)
|
||||
raise AgentError("TIMEOUT", "No answer to %s from DevTools" % method)
|
||||
|
||||
def event(self, message):
|
||||
params = message.get("params") or {}
|
||||
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
|
||||
self.report(params.get("payload") == "true")
|
||||
|
||||
|
||||
def steam_idle_inhibit(agent_dir, inhibit):
|
||||
expression = """(async want => {
|
||||
const toggle = () => new Promise(done => {
|
||||
@@ -918,6 +1024,8 @@ def serve(agent_dir, focus=True, poll=0.1):
|
||||
can_focus = focus and bool(os.environ.get("DISPLAY"))
|
||||
if can_focus:
|
||||
FocusWatcher(agent_dir / "focus.json").start()
|
||||
if focus:
|
||||
KeyboardWatcher(agent_dir).start()
|
||||
write_json(agent_dir / "hello.json", {"pid": os.getpid(), "version": VERSION, "started": int(time.time() * 1000),
|
||||
"displays": displays(), "focus": can_focus})
|
||||
log("serving %s (focus %s)" % (agent_dir, "on" if can_focus else "off"))
|
||||
|
||||
@@ -7,7 +7,21 @@ import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap")
|
||||
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
|
||||
|
||||
|
||||
def socket_name():
|
||||
name = os.environ.get("DROIDDECK_BWRAP_SOCKET", "")
|
||||
if not name:
|
||||
try:
|
||||
with open(SOCKET_FILE, encoding="utf-8") as f:
|
||||
name = f.read().strip()
|
||||
except OSError:
|
||||
pass
|
||||
return "\0" + (name or "com.droiddeck.launcher.bwrap")
|
||||
|
||||
|
||||
SOCKET = socket_name()
|
||||
VERSION = "bubblewrap 0.11.0 (droiddeck)"
|
||||
|
||||
NO_ARG = {
|
||||
|
||||
@@ -674,6 +674,7 @@ def launch(command, env, mode, decide=None):
|
||||
def game_environment(env):
|
||||
try:
|
||||
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
|
||||
env = game_env["game_gpu"](env)
|
||||
app = game_env["game_id"](env) or env.get("SteamAppId") or env.get("SteamGameId")
|
||||
if not app:
|
||||
return env
|
||||
|
||||
@@ -7,6 +7,7 @@ import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
|
||||
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
|
||||
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
|
||||
@@ -125,6 +126,35 @@ def skip_red_launcher(command):
|
||||
return command
|
||||
|
||||
|
||||
def offline_without_anticheat(command, env):
|
||||
"""Start the configured game executable when the player opts into launching without EAC."""
|
||||
if (env.get("DROIDDECK_ANTICHEAT_OFFLINE") != "1" or len(command) <= 2
|
||||
or command[1] != "waitforexitandrun"
|
||||
or not re.fullmatch(r"start_protected_game(?:_?x64|_?64)?\.exe",
|
||||
os.path.basename(command[2]), re.IGNORECASE)):
|
||||
return command
|
||||
folder = os.path.dirname(command[2])
|
||||
try:
|
||||
with open(os.path.join(folder, "EasyAntiCheat", "settings.json"), encoding="utf-8-sig") as source:
|
||||
executable = json.load(source).get("executable")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return command
|
||||
if not isinstance(executable, str) or not executable:
|
||||
return command
|
||||
relative = os.path.normpath(executable.replace("\\", "/"))
|
||||
game = os.path.join(folder, relative)
|
||||
if os.path.isabs(relative) or relative.startswith("..") or not os.path.isfile(game):
|
||||
return command
|
||||
# Resolve symlinks before accepting an executable inside the game directory.
|
||||
root = os.path.realpath(folder)
|
||||
if os.path.commonpath((root, os.path.realpath(game))) != root:
|
||||
return command
|
||||
if os.path.normcase(os.path.abspath(game)) == os.path.normcase(os.path.abspath(command[2])):
|
||||
return command
|
||||
print("droiddeck-game-env: started without Easy Anti-Cheat (offline only)", file=sys.stderr)
|
||||
return command[:2] + [game] + command[3:]
|
||||
|
||||
|
||||
def engine_fixes(exe, args):
|
||||
"""Environment and extra arguments a game needs because of what it is built with."""
|
||||
game = Game(exe, args)
|
||||
@@ -153,6 +183,18 @@ def win_components(compat, app_id):
|
||||
return ""
|
||||
|
||||
|
||||
def game_gpu(env):
|
||||
if GAME_TU_DEBUG not in env:
|
||||
return env
|
||||
result = env.copy()
|
||||
value = result.pop(GAME_TU_DEBUG)
|
||||
if value:
|
||||
result["TU_DEBUG"] = value
|
||||
else:
|
||||
result.pop("TU_DEBUG", None)
|
||||
return result
|
||||
|
||||
|
||||
def apply_config(env, config, app_id, fixes=None):
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported environment configuration")
|
||||
@@ -283,7 +325,7 @@ def main():
|
||||
command = sys.argv[1:]
|
||||
if not command:
|
||||
return 2
|
||||
env = os.environ.copy()
|
||||
env = game_gpu(os.environ.copy())
|
||||
mic_enabled = env.get("BL_MIC_ENABLED")
|
||||
mark_install_scripts(command, env)
|
||||
app_id = game_id(env)
|
||||
@@ -313,6 +355,8 @@ def main():
|
||||
env = apply_config(env, {"version": 1}, app_id, fixes)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
|
||||
command = offline_without_anticheat(command, env)
|
||||
if mic_enabled == "0":
|
||||
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
|
||||
env = force_ssbs(command, env)
|
||||
|
||||
@@ -188,6 +188,7 @@ present() { awk -F'\t' '
|
||||
}
|
||||
' - "$1"; }
|
||||
|
||||
regs=()
|
||||
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
@@ -195,8 +196,21 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
|
||||
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
|
||||
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
|
||||
[ -f "$reg" ] || continue
|
||||
[ -f "$reg" ] && regs+=("$reg")
|
||||
done
|
||||
declare -A regid=()
|
||||
if [ ${#regs[@]} -gt 0 ]; then
|
||||
while IFS=$'\t' read -r id name; do
|
||||
regid[$name]=$id
|
||||
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" 2>/dev/null)
|
||||
fi
|
||||
|
||||
for reg in "${regs[@]}"; do
|
||||
seeded=${reg%/*}/.droiddeck-redists
|
||||
checked=${reg%/*}/.droiddeck-redists-checked
|
||||
id=${regid[$reg]:-}
|
||||
prev=
|
||||
[ -f "$checked" ] && read -r prev <"$checked"
|
||||
legacy=${reg%/*}/.bannerlator-redists
|
||||
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
|
||||
mv -f "$legacy" "$seeded"
|
||||
@@ -210,12 +224,13 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
|
||||
done
|
||||
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
|
||||
id=
|
||||
had=()
|
||||
for line in "${kept[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${kept[@]}" >"$seeded"
|
||||
echo "== took Vulkan runtime markers out of $reg"
|
||||
fi
|
||||
if [ ${#had[@]} -gt 0 ]; then
|
||||
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
|
||||
declare -A held=()
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
|
||||
if [ ${#held[@]} -lt ${#had[@]} ]; then
|
||||
@@ -228,7 +243,11 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
fi
|
||||
missing=()
|
||||
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
|
||||
[ ${#missing[@]} -eq 0 ] && continue
|
||||
if [ ${#missing[@]} -eq 0 ]; then
|
||||
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
|
||||
continue
|
||||
fi
|
||||
rm -f "$checked"
|
||||
dated=$(mktemp) || continue
|
||||
touch -r "$reg" "$dated"
|
||||
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
|
||||
|
||||
@@ -4,6 +4,11 @@ export HOME=${HOME:-/root}
|
||||
mode=${1:-desktop}
|
||||
shift || true
|
||||
step() { echo "== STEP $(date -u +%H:%M:%S) $*"; }
|
||||
steam_setup_failed() {
|
||||
echo "== steam: the Steam client could not be set up (status $1)"
|
||||
[ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE"
|
||||
exit "$1"
|
||||
}
|
||||
if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
|
||||
mkdir -p "$(dirname "$BL_LOG")" 2>/dev/null
|
||||
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
||||
@@ -303,6 +308,9 @@ case $mode in
|
||||
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
|
||||
fi
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
|
||||
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
|
||||
export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11
|
||||
fi
|
||||
run_program() {
|
||||
local rc=0 child sig forwarded=0
|
||||
{ trap - INT QUIT; exec "$@"; } <&0 &
|
||||
@@ -350,6 +358,12 @@ case $mode in
|
||||
esac
|
||||
;;
|
||||
steam)
|
||||
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
|
||||
export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11
|
||||
fi
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
steam_x64=0
|
||||
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
|
||||
steam_cef_gpu=1
|
||||
@@ -358,10 +372,10 @@ case $mode in
|
||||
# droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients.
|
||||
_bl_x64_repair=0
|
||||
[ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1
|
||||
droiddeck-steam-install || exit $?
|
||||
droiddeck-steam-install || steam_setup_failed $?
|
||||
droiddeck-steam-install --sync steamdeck_publicbeta || step "could not update the arm64 client's parts; the x86-64 client keeps its own web helper"
|
||||
step "checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)"
|
||||
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || exit $?
|
||||
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || steam_setup_failed $?
|
||||
step "x86-64 Steam client ready"
|
||||
steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
|
||||
steam_client=(droiddeck-steam-x64 --exec)
|
||||
@@ -371,7 +385,7 @@ case $mode in
|
||||
fi
|
||||
else
|
||||
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
|
||||
droiddeck-steam-install || exit $?
|
||||
droiddeck-steam-install || steam_setup_failed $?
|
||||
step "Steam client ready"
|
||||
steam_root=$XDG_DATA_HOME/Steam
|
||||
if [ -f "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then
|
||||
|
||||
@@ -105,7 +105,7 @@ INSTALL_JS = r"""
|
||||
const body = [];
|
||||
uint(1, appid, body);
|
||||
const r = await send("CompatManager.GetCompatTools#1", body);
|
||||
if (!r.ok) throw new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")");
|
||||
if (!r.ok) throw Object.assign(new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")"), { eresult: r.eresult });
|
||||
return { selected: text(r.body, 3), fallback: text(r.body, 4), tools: (r.body[1] || []).map((t) => text(parse(t), 1)) };
|
||||
};
|
||||
self.set = async (appid, name) => {
|
||||
@@ -119,7 +119,13 @@ INSTALL_JS = r"""
|
||||
};
|
||||
self.many = async (apps) => {
|
||||
const out = {};
|
||||
for (const app of apps) out[app] = (await self.get(Number(app))).selected;
|
||||
for (const app of apps) {
|
||||
try {
|
||||
out[app] = (await self.get(Number(app))).selected;
|
||||
} catch (e) {
|
||||
if (e.eresult !== 128) throw e;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
window.__droiddeckCompat = self;
|
||||
@@ -555,11 +561,24 @@ class Helper:
|
||||
# "native" from earlier builds also lists dual-platform games nobody chose to run natively.
|
||||
prior_native = state.get("native_choices", ())
|
||||
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
|
||||
picked = COMPAT["picked_apps"](state)
|
||||
runnable = {t["name"].lower() for t in live}
|
||||
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"])
|
||||
overrides = COMPAT["requested_games"](
|
||||
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
|
||||
apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"])
|
||||
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
|
||||
refused = set(apps) - set(current)
|
||||
refused_native = native_choices & refused
|
||||
if refused:
|
||||
apps = [app for app in apps if app not in refused]
|
||||
installed = [app for app in installed if app not in refused]
|
||||
picks = [app for app in picks if app not in refused]
|
||||
prior_auto = {app: tool for app, tool in prior_auto.items() if app not in refused}
|
||||
if isinstance(state.get("auto"), dict):
|
||||
state["auto"] = prior_auto
|
||||
native_choices -= refused
|
||||
overrides = {app: tool for app, tool in overrides.items() if app not in refused}
|
||||
current["0"] = top["selected"]
|
||||
native = COMPAT["native_targets"](self.steam_root, apps)
|
||||
raw_mapping = COMPAT["read_config_mapping"](
|
||||
@@ -568,7 +587,7 @@ class Helper:
|
||||
for app in native_choices:
|
||||
current[app] = ""
|
||||
for app in set(native) - native_choices:
|
||||
if not current.get(app):
|
||||
if not current.get(app) and app not in picked:
|
||||
current.pop(app, None)
|
||||
else:
|
||||
for app in set(native) | native_choices:
|
||||
@@ -576,7 +595,8 @@ class Helper:
|
||||
# The client shows an explicit native choice as the tool it inherits, and writes config.vdf late.
|
||||
if raw_mapping[app] == "" or current.get(app) not in self.known:
|
||||
current[app] = raw_mapping[app]
|
||||
elif app in prior_auto or app in native_choices:
|
||||
elif app in prior_auto or app in native_choices or app in picked and (
|
||||
not current.get(app) or COMPAT["unrunnable"](current[app], runnable)):
|
||||
current[app] = ""
|
||||
elif not current.get(app):
|
||||
current.pop(app, None)
|
||||
@@ -590,8 +610,8 @@ class Helper:
|
||||
tool if tool is not None else "Steam native default"))
|
||||
state.update(
|
||||
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
|
||||
native_choices=sorted(app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]),
|
||||
tools=catalog, live=True)
|
||||
native_choices=sorted(refused_native | {app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]}),
|
||||
picked=COMPAT["picked_after"](current, changes), tools=catalog, live=True)
|
||||
state.pop("native", None)
|
||||
if waiting:
|
||||
state["pending"] = wanted
|
||||
|
||||
@@ -271,6 +271,23 @@ def provision_prefix(compat_data, wait=SERVER_WAIT):
|
||||
return state + (" server-running" if busy else "")
|
||||
|
||||
|
||||
def create_prefix(compat_data, proton, timeout=120):
|
||||
if not compat_data or not proton or not Path(proton).is_file():
|
||||
return "no-proton"
|
||||
reg = Path(compat_data) / "pfx/user.reg"
|
||||
if reg.is_file():
|
||||
return "present"
|
||||
try:
|
||||
Path(compat_data).mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run([proton, "run", "cmd.exe", "/d", "/c", "exit"], stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return "timeout"
|
||||
except OSError:
|
||||
return "failed"
|
||||
return "created" if reg.is_file() else "failed"
|
||||
|
||||
|
||||
CLOUD_TIMEOUT = 15.0
|
||||
CLOUD_STORES = ("gog", "epic")
|
||||
STORE_GAME = 10
|
||||
@@ -502,6 +519,10 @@ def main(argv):
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
prefix_id = os.path.basename(compat_data) if compat_data else ""
|
||||
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
if launch_dir and cloud_on(sidecar):
|
||||
made = create_prefix(compat_data, os.environ.get("BL_STORE_PROTON", ""))
|
||||
if made != "present":
|
||||
log("cloud %s %s prefix=%s" % (store, game, made))
|
||||
if store == "gog":
|
||||
prepare_gog(sidecar, compat_data, launch_dir)
|
||||
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
|
||||
|
||||
@@ -1042,6 +1042,16 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
|
||||
return changes, kept
|
||||
|
||||
|
||||
def picked_apps(state):
|
||||
picked = state.get("picked", ())
|
||||
return {app for app in picked if isinstance(app, str)} if isinstance(picked, list) else set()
|
||||
|
||||
|
||||
def picked_after(current, changes):
|
||||
return sorted(({app for app, tool in current.items() if tool} - set(changes) |
|
||||
{app for app, tool in changes.items() if tool}) - {"0"}, key=app_order)
|
||||
|
||||
|
||||
def followers(state, current):
|
||||
if "auto" in state:
|
||||
return state["auto"]
|
||||
@@ -1287,6 +1297,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
native = native_targets(steam_root, set(apps) | set(picks) | set(managed) | set(native_choices))
|
||||
if linux_tool != FEX_TOOL:
|
||||
native = {app: linux_tool if tool == FEX_TOOL else tool for app, tool in native.items()}
|
||||
for app in picked_apps(state) & set(native):
|
||||
current.setdefault(app, "")
|
||||
changes, auto = plan_mapping(
|
||||
current, apps, names, default, followers(state, current), native, picks,
|
||||
overrides, managed, native_choices)
|
||||
@@ -1297,6 +1309,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
write_changed(config_path, text)
|
||||
state["auto"] = {app: tool for app, tool in auto.items() if tool is not NATIVE_CHOICE}
|
||||
state["native_choices"] = sorted(app for app, tool in auto.items() if tool is NATIVE_CHOICE)
|
||||
state["picked"] = picked_after(current, changes)
|
||||
state.pop("native", None)
|
||||
state["tools"] = catalog
|
||||
state.setdefault("default", default)
|
||||
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the add-on packs the app downloads on first use instead of shipping in the APK:
|
||||
# proot.tar.zst the patched proot and its loader (built by tools/proot)
|
||||
# directaudio.tar.zst the Wine DirectAudio drivers (fetched by tools/directaudio/fetch.sh)
|
||||
# tracking.tar.zst hand-tracking models and the OpenCV/MediaPipe native libraries
|
||||
# xbox.tar.zst the Xbox backend (built by tools/xbox) for /usr/local/lib/droiddeck-xbox
|
||||
# comet.tar.zst the GOG Galaxy companion (built by tools/comet) for /usr/local/lib/droiddeck-comet
|
||||
# Only CI publishes these (.github/workflows/publish-packs.yml); the APK built from the same
|
||||
# directory pins each pack's SHA-256.
|
||||
# Usage: tools/packs/build.sh <out-dir>
|
||||
set -euo pipefail
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
repo=$(cd "$here/../.." && pwd)
|
||||
out=${1:?usage: build.sh <out-dir>}
|
||||
mkdir -p "$out"
|
||||
out=$(cd "$out" && pwd)
|
||||
linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib"
|
||||
# shellcheck source=tracking/release.env
|
||||
source "$here/tracking/release.env"
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }
|
||||
|
||||
fetch() {
|
||||
local url=$1 expected=$2 dest=$3
|
||||
curl -fsSL --retry 4 -o "$dest" "$url"
|
||||
local actual
|
||||
actual=$(sha256 "$dest")
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
echo "checksum mismatch for $url: $actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
pack() {
|
||||
local name=$1 src=$2
|
||||
shift 2
|
||||
for required in "$@"; do
|
||||
[ -f "$src/$required" ] || { echo "$name pack: $src/$required is missing" >&2; exit 1; }
|
||||
done
|
||||
python3 -I - "$src" "$work/$name.tar" <<'EOF'
|
||||
import os, sys, tarfile
|
||||
src, dest = sys.argv[1], sys.argv[2]
|
||||
files = []
|
||||
for base, dirs, names in os.walk(src):
|
||||
dirs.sort()
|
||||
for name in names:
|
||||
path = os.path.join(base, name)
|
||||
if os.path.islink(path) or not os.path.isfile(path):
|
||||
sys.exit(f"{path}: only regular files can be packed")
|
||||
files.append(os.path.relpath(path, src))
|
||||
with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar:
|
||||
for rel in sorted(files):
|
||||
path = os.path.join(src, rel)
|
||||
info = tar.gettarinfo(path, arcname=rel)
|
||||
info.mtime, info.uid, info.gid, info.uname, info.gname = 0, 0, 0, "", ""
|
||||
info.mode = 0o755 if os.stat(path).st_mode & 0o111 else 0o644
|
||||
with open(path, "rb") as f:
|
||||
tar.addfile(info, f)
|
||||
EOF
|
||||
zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
|
||||
echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')"
|
||||
}
|
||||
|
||||
mkdir "$work/tracking"
|
||||
fetch "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task" \
|
||||
fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1 "$work/tracking/hand_landmarker.task"
|
||||
fetch "https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task" \
|
||||
59929e1d1ee95287735ddd833b19cf4ac46d29bc7afddbbf6753c459690d574a "$work/tracking/pose_landmarker_lite.task"
|
||||
cp "$here/tracking/hand_landmarker_lite.task" "$work/tracking/"
|
||||
[ "$(sha256 "$work/tracking/hand_landmarker_lite.task")" = 173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8 ] || {
|
||||
echo "checksum mismatch for hand_landmarker_lite.task" >&2; exit 1; }
|
||||
fetch "https://repo1.maven.org/maven2/org/opencv/opencv/${OPENCV_VERSION}/opencv-${OPENCV_VERSION}.aar" \
|
||||
"$OPENCV_AAR_SHA256" "$work/opencv.aar"
|
||||
fetch "https://dl.google.com/dl/android/maven2/com/google/mediapipe/tasks-core/${MEDIAPIPE_VERSION}/tasks-core-${MEDIAPIPE_VERSION}.aar" \
|
||||
"$MEDIAPIPE_AAR_SHA256" "$work/tasks-core.aar"
|
||||
unzip -q -j "$work/opencv.aar" jni/arm64-v8a/libopencv_java4.so -d "$work/tracking"
|
||||
unzip -q -j "$work/tasks-core.aar" jni/arm64-v8a/libmediapipe_tasks_jni.so -d "$work/tracking"
|
||||
chmod 0644 "$work/tracking"/*
|
||||
|
||||
mkdir "$work/proot"
|
||||
install -m755 "$repo/app/src/main/jniLibs/arm64-v8a/libproot.so" "$repo/app/src/main/jniLibs/arm64-v8a/libproot-loader.so" "$work/proot/"
|
||||
pack proot "$work/proot" libproot.so libproot-loader.so
|
||||
pack directaudio "$repo/app/src/main/assets/directaudio" \
|
||||
linux-wine11/version.txt linux-wine11-systhread/version.txt
|
||||
pack tracking "$work/tracking" hand_landmarker.task hand_landmarker_lite.task pose_landmarker_lite.task \
|
||||
libopencv_java4.so libmediapipe_tasks_jni.so
|
||||
pack xbox "$linuxfs/droiddeck-xbox" version xodus-cli xodus-service
|
||||
pack comet "$linuxfs/droiddeck-comet" version comet
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"url": "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task",
|
||||
"sha256": "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1",
|
||||
"bytes": 7819105,
|
||||
"mediapipe": "com.google.mediapipe:tasks-vision:1.0.0",
|
||||
"opencv": "org.opencv:opencv:4.13.0",
|
||||
"documentation": "https://ai.google.dev/edge/mediapipe/solutions/vision/hand_landmarker",
|
||||
"runtime": "Two video-mode instances; CPU default; GPU requires separate performance acceptance"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"sha256": "173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8",
|
||||
"composition": "Lite palm detector and lite hand landmarks with matching Tasks tensor metadata and associated files from the full bundle",
|
||||
"palm_source": "https://storage.googleapis.com/mediapipe-assets/palm_detection_lite.tflite",
|
||||
"palm_source_sha256": "e9a4aaddf90dda56a87235303cf00e4c2d3fb28725f68fd88772997dac905c18",
|
||||
"landmark_source": "https://storage.googleapis.com/mediapipe-assets/hand_landmark_lite.tflite",
|
||||
"landmark_source_sha256": "d7fde8ac11f8ce03f8663775bfc323f4fc9f2a38062b4f4efa142874ef5b2a48",
|
||||
"metadata_source": "hand_landmarker.task",
|
||||
"metadata_source_sha256": "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1",
|
||||
"builder": "tools/build_hand_lite.py; mediapipe==0.10.21; deterministic ZIP_STORED bundle and embedded associated-file archives",
|
||||
"runtime": "com.google.mediapipe:tasks-vision:1.0.0; CPU by default; experimental stereo hand and wrist tracking"
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
OPENCV_VERSION=4.13.0
|
||||
OPENCV_AAR_SHA256=a8c9b0929d8d6367bb476320a1f36587db2b57ea18d8f7521ce509514903ca04
|
||||
MEDIAPIPE_VERSION=1.0.0
|
||||
MEDIAPIPE_AAR_SHA256=609c6fcfe59f58c9739194f65ae5882281c327710e1a616aa7f533a4d9238ca3
|
||||
@@ -55,6 +55,13 @@ Added for Flatpak:
|
||||
`linkat` fails with `EACCES` and Flatpak could not create its repo (`Creating repo: linkat:
|
||||
Permission denied`). `O_TMPFILE` answers `EOPNOTSUPP`, so libglnx writes a named temporary file
|
||||
and renames it, and a denied link answers `EPERM`, on which ostree's checkout copies instead.
|
||||
- `0017-android-execstack-denial.patch` - the same policy denies apps executable stacks, so the
|
||||
`mprotect(PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN)` with which `ld.so` makes the main
|
||||
stack executable for an object whose `PT_GNU_STACK` asks for it fails with `EACCES`, and the
|
||||
program stops before `main` ("cannot enable executable stack as shared object requires:
|
||||
Permission denied", `libQt5Gui.so.5` in ONLYOFFICE's Flatpak). The filter traces `mprotect` only
|
||||
for that exact request, and a denied one answers success: the stack stays non-executable, as
|
||||
Android keeps it anyway, and objects that only carry the flag load.
|
||||
Added by DroidDeck:
|
||||
|
||||
- `0011-kompat-utsname-only.patch` - `--kernel-release` (the guest's `DroidDeck` hostname) loads
|
||||
|
||||
@@ -141,6 +141,27 @@ static int traced_by_match(const char *key) {
|
||||
return found;
|
||||
}
|
||||
|
||||
static int program_32bit(const char *prog, int scripts) {
|
||||
char head[256];
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 1;
|
||||
long n = syscall(SYS_read, fd, head, sizeof head - 1);
|
||||
syscall(SYS_close, fd);
|
||||
if (n < 0) return 1;
|
||||
head[n] = 0;
|
||||
if (n >= 2 && head[0] == '#' && head[1] == '!') {
|
||||
if (scripts <= 0) return 1;
|
||||
char *p = head + 2;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
char *e = p;
|
||||
while (*e && *e != ' ' && *e != '\t' && *e != '\n' && *e != '\r') e++;
|
||||
if (e == p || (!*e && n == (long)sizeof head - 1)) return 1;
|
||||
*e = 0;
|
||||
return program_32bit(p, scripts - 1);
|
||||
}
|
||||
return !(n >= 5 && memcmp(head, "\x7f" "ELF", 4) == 0 && head[4] == 2);
|
||||
}
|
||||
|
||||
static int fex_runs_32bit(void) {
|
||||
if (strcmp(program_invocation_short_name, "FEX") != 0 && strcmp(program_invocation_short_name, "FEXInterpreter") != 0)
|
||||
return 0;
|
||||
@@ -153,12 +174,7 @@ static int fex_runs_32bit(void) {
|
||||
args[n] = 0;
|
||||
const char *prog = args + strlen(args) + 1;
|
||||
if (prog >= args + n || !*prog) return 1;
|
||||
unsigned char ident[5];
|
||||
fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 1;
|
||||
n = syscall(SYS_read, fd, ident, sizeof ident);
|
||||
syscall(SYS_close, fd);
|
||||
return !(n == 5 && memcmp(ident, "\x7f" "ELF", 4) == 0 && ident[4] == 2);
|
||||
return program_32bit(prog, 4);
|
||||
}
|
||||
|
||||
static int in_tracer(struct bind *bd) {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: DroidDeck <noreply@droiddeck.invalid>
|
||||
Date: Tue, 20 Oct 2026 12:00:00 -0400
|
||||
Subject: [PATCH] syscall: work around Android's denial of executable stacks
|
||||
|
||||
SELinux denies apps the execstack permission, so the mprotect with
|
||||
which ld.so makes the main stack executable for an object whose
|
||||
PT_GNU_STACK asks for it fails with EACCES, and the program does not
|
||||
start ("cannot enable executable stack as shared object requires:
|
||||
Permission denied", libQt5Gui.so.5 in ONLYOFFICE's Flatpak). The
|
||||
filter traces mprotect only for that exact request, and a denied one
|
||||
answers success: the stack stays non-executable, as Android keeps it.
|
||||
---
|
||||
diff --git a/src/syscall/exit.c b/src/syscall/exit.c
|
||||
index e87b7e1..71b36f5 100644
|
||||
--- a/src/syscall/exit.c
|
||||
+++ b/src/syscall/exit.c
|
||||
@@ -25,6 +25,7 @@
|
||||
#include <linux/net.h> /* SYS_*, */
|
||||
#include <linux/ioctl.h> /* _IOW, */
|
||||
#include <string.h> /* strlen(3), */
|
||||
+#include <sys/mman.h> /* PROT_*, */
|
||||
|
||||
#include "cli/note.h"
|
||||
#include "syscall/syscall.h"
|
||||
@@ -552,6 +553,13 @@ void translate_syscall_exit(Tracee *tracee)
|
||||
if ((int) syscall_result == -EACCES)
|
||||
poke_reg(tracee, SYSARG_RESULT, -EPERM);
|
||||
goto end;
|
||||
+
|
||||
+ case PR_mprotect:
|
||||
+ if ((int) syscall_result == -EACCES
|
||||
+ && (peek_reg(tracee, ORIGINAL, SYSARG_3) & (PROT_EXEC | PROT_GROWSDOWN))
|
||||
+ == (PROT_EXEC | PROT_GROWSDOWN))
|
||||
+ poke_reg(tracee, SYSARG_RESULT, 0);
|
||||
+ goto end;
|
||||
#endif
|
||||
|
||||
case PR_ioctl:
|
||||
diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c
|
||||
index d9be7b4..fca220b 100644
|
||||
--- a/src/syscall/seccomp.c
|
||||
+++ b/src/syscall/seccomp.c
|
||||
@@ -46,6 +46,7 @@
|
||||
#include <asm/termbits.h>
|
||||
#include <linux/fs.h>
|
||||
#include <assert.h> /* assert(3), */
|
||||
+#include <sys/mman.h> /* PROT_*, */
|
||||
|
||||
#include "syscall/seccomp.h"
|
||||
#include "tracee/tracee.h"
|
||||
@@ -316,6 +317,10 @@ static size_t trace_length_raw(Sysnum sysnum)
|
||||
return LENGTH_TRACE_PRLIMIT_STACK;
|
||||
case PR_ioctl:
|
||||
return LENGTH_TRACE_IOCTL;
|
||||
+#ifdef __ANDROID__
|
||||
+ case PR_mprotect:
|
||||
+ return LENGTH_TRACE_SYSCALL_IF_ARG;
|
||||
+#endif
|
||||
default:
|
||||
return LENGTH_TRACE_SYSCALL;
|
||||
}
|
||||
@@ -335,6 +340,11 @@ static int add_trace(struct sock_fprog *program, Sysnum sysnum, word_t syscall,
|
||||
return add_trace_prlimit_stack(program, syscall, flag);
|
||||
case PR_ioctl:
|
||||
return add_trace_ioctl_requests(program, syscall, flag);
|
||||
+#ifdef __ANDROID__
|
||||
+ case PR_mprotect:
|
||||
+ return add_trace_syscall_if_arg(program, syscall, 2,
|
||||
+ PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN, flag);
|
||||
+#endif
|
||||
default:
|
||||
return add_trace_syscall(program, syscall, flag);
|
||||
}
|
||||
@@ -599,6 +609,7 @@ static FilteredSysnum proot_sysnums[] = {
|
||||
{ PR_lstat64, 0 },
|
||||
#ifdef __ANDROID__
|
||||
{ PR_memfd_create, 0 },
|
||||
+ { PR_mprotect, FILTER_SYSEXIT },
|
||||
#endif
|
||||
{ PR_mkdir, 0 },
|
||||
{ PR_mkdirat, 0 },
|
||||
@@ -12,6 +12,14 @@ from zipfile import ZipFile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MANIFEST = Path('app/build/runtime-inputs.json')
|
||||
PACKS = Path('app/build/packs')
|
||||
# Runtime trees shipped as add-on packs (tools/packs/build.sh) rather than inside the APK.
|
||||
PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet',
|
||||
'assets/directaudio/': 'directaudio'}
|
||||
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so'),
|
||||
'lib/arm64-v8a/libproot-loader.so': ('proot', 'libproot-loader.so')}
|
||||
PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so']
|
||||
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet']
|
||||
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
|
||||
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
|
||||
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
|
||||
@@ -157,10 +165,49 @@ def verify(root=ROOT):
|
||||
return data
|
||||
|
||||
|
||||
def pack_digests(root, name):
|
||||
path = root / PACKS / (name + '.tar.zst')
|
||||
if not path.is_file():
|
||||
raise ValueError('Missing add-on pack ' + name + '. Run tools/packs/build.sh app/build/packs.')
|
||||
process = subprocess.Popen(['zstd', '-dc', str(path)], stdout=subprocess.PIPE)
|
||||
digests = {}
|
||||
try:
|
||||
with tarfile.open(fileobj=process.stdout, mode='r|') as archive:
|
||||
for member in archive:
|
||||
if member.isfile():
|
||||
digests[member.name] = hashlib.sha256(archive.extractfile(member).read()).hexdigest()
|
||||
finally:
|
||||
process.stdout.close()
|
||||
if process.wait():
|
||||
raise ValueError('Invalid add-on pack ' + name)
|
||||
return digests
|
||||
|
||||
|
||||
def check_apk(apk, root=ROOT):
|
||||
data = verify(root)
|
||||
packs = {name: pack_digests(root, name) for name in PACK_NAMES}
|
||||
with ZipFile(apk) as package:
|
||||
names = set(package.namelist())
|
||||
for library in PACKED_LIBRARIES:
|
||||
if library in names:
|
||||
raise ValueError('APK still carries ' + library + ', which the tracking pack provides')
|
||||
if library.rsplit('/', 1)[1] not in packs['tracking']:
|
||||
raise ValueError('Tracking pack missing ' + library)
|
||||
for name, output in data['outputs'].items():
|
||||
if name in PACKED_FILES:
|
||||
pack, rel = PACKED_FILES[name]
|
||||
if name in names:
|
||||
raise ValueError('APK still carries ' + name + ', which the ' + pack + ' pack provides')
|
||||
if packs[pack].get(rel) != output['sha256']:
|
||||
raise ValueError('Add-on pack ' + pack + ' is missing or has a stale ' + name)
|
||||
continue
|
||||
prefix = next((p for p in PACKED if name.startswith(p)), None)
|
||||
if prefix:
|
||||
if name in names:
|
||||
raise ValueError('APK still carries ' + name + ', which the ' + PACKED[prefix] + ' pack provides')
|
||||
if packs[PACKED[prefix]].get(name[len(prefix):]) != output['sha256']:
|
||||
raise ValueError('Add-on pack ' + PACKED[prefix] + ' is missing or has a stale ' + name)
|
||||
continue
|
||||
try:
|
||||
content = package.read(name)
|
||||
except KeyError:
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
|
||||
|
||||
|
||||
class BwrapSocketTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
self.shim = runpy.run_path(str(BWRAP))
|
||||
self.shim["socket_name"].__globals__["SOCKET_FILE"] = str(self.dir / "bwrap-socket")
|
||||
|
||||
def name(self, env):
|
||||
with mock.patch.dict(os.environ, env, clear=True):
|
||||
return self.shim["socket_name"]()
|
||||
|
||||
def test_flatpak_empty_environment_reaches_a_renamed_package(self):
|
||||
(self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n")
|
||||
self.assertEqual("\0com.antutu.benchmark.full.bwrap", self.name({}))
|
||||
|
||||
def test_the_environment_still_wins(self):
|
||||
(self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n")
|
||||
self.assertEqual("\0com.tencent.ig.bwrap", self.name({"DROIDDECK_BWRAP_SOCKET": "com.tencent.ig.bwrap"}))
|
||||
|
||||
def test_without_either_the_standard_package_is_asked(self):
|
||||
self.assertEqual("\0com.droiddeck.launcher.bwrap", self.name({}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -6,6 +6,7 @@ import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
@@ -77,6 +78,79 @@ class FakeDevTools(threading.Thread):
|
||||
conn.close()
|
||||
|
||||
|
||||
class FakeSteamClient(threading.Thread):
|
||||
|
||||
def __init__(self, showing):
|
||||
super().__init__(daemon=True)
|
||||
self.showing = showing
|
||||
self.server = socket.socket()
|
||||
self.server.bind(("127.0.0.1", 0))
|
||||
self.server.listen(4)
|
||||
self.port = self.server.getsockname()[1]
|
||||
self.seen = []
|
||||
self.conn = None
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.server.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def send(self, conn, message):
|
||||
payload = json.dumps(message).encode()
|
||||
header = bytes([0x81, 126]) + struct.pack(">H", len(payload)) if len(payload) > 125 else bytes([0x81, len(payload)])
|
||||
with self.lock:
|
||||
conn.sendall(header + payload)
|
||||
|
||||
def push(self, payload, name=None):
|
||||
self.send(self.conn, {"method": "Runtime.bindingCalled",
|
||||
"params": {"name": name or agent.KEYBOARD_BINDING, "payload": payload}})
|
||||
|
||||
def drop(self):
|
||||
self.conn.shutdown(socket.SHUT_RDWR)
|
||||
self.conn.close()
|
||||
|
||||
def serve(self, conn):
|
||||
stream = conn.makefile("rb")
|
||||
head = b""
|
||||
while not head.endswith(b"\r\n\r\n"):
|
||||
head += stream.read(1)
|
||||
request = head.decode()
|
||||
if request.startswith("GET /json"):
|
||||
body = json.dumps([{"title": "Steam Big Picture Mode", "url": "https://steamloopback.host/routes/",
|
||||
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/2" % self.port},
|
||||
{"title": "SharedJSContext", "url": "https://steamloopback.host/",
|
||||
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/1" % self.port}]).encode()
|
||||
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
||||
conn.close()
|
||||
return
|
||||
key = [l.split(":", 1)[1].strip() for l in request.split("\r\n") if l.lower().startswith("sec-websocket-key")][0]
|
||||
accept = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode()
|
||||
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: %s\r\n\r\n" % accept).encode())
|
||||
self.conn = conn
|
||||
try:
|
||||
while True:
|
||||
b0, b1 = stream.read(2)
|
||||
n = b1 & 0x7F
|
||||
if n == 126:
|
||||
n = struct.unpack(">H", stream.read(2))[0]
|
||||
elif n == 127:
|
||||
n = struct.unpack(">Q", stream.read(8))[0]
|
||||
mask = stream.read(4)
|
||||
data = stream.read(n)
|
||||
message = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
|
||||
self.seen.append(message)
|
||||
self.push("true", name="unrelated")
|
||||
result = {"result": {"type": "boolean", "value": self.showing}} if message["method"] == "Runtime.evaluate" else {}
|
||||
self.send(conn, {"id": message["id"], "result": result})
|
||||
except (OSError, ValueError):
|
||||
conn.close()
|
||||
|
||||
|
||||
class AgentTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
@@ -409,6 +483,144 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertIn(child.pid, agent.game_pids(424242))
|
||||
|
||||
|
||||
class SteamKeyboardTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.dir = Path(self.temp.name)
|
||||
|
||||
def state(self):
|
||||
try:
|
||||
return json.loads((self.dir / "keyboard.json").read_text())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
def wait_for(self, check):
|
||||
for _ in range(200):
|
||||
if check():
|
||||
return
|
||||
time.sleep(0.02)
|
||||
self.fail("timed out; keyboard.json is %s" % self.state())
|
||||
|
||||
def test_report_writes_only_changes(self):
|
||||
watcher = agent.KeyboardWatcher(self.dir)
|
||||
watcher.report(False)
|
||||
self.assertEqual({"steamKeyboard": False, "seq": 1}, self.state())
|
||||
watcher.report(False)
|
||||
watcher.report(True)
|
||||
self.assertEqual({"steamKeyboard": True, "seq": 2}, self.state())
|
||||
|
||||
def test_follows_the_clients_keyboard_and_rechecks_while_idle(self):
|
||||
client = FakeSteamClient(False)
|
||||
client.start()
|
||||
self.addCleanup(client.server.close)
|
||||
(self.dir / "cdp-port").write_text(str(client.port))
|
||||
watcher = agent.KeyboardWatcher(self.dir)
|
||||
failure = []
|
||||
with patch.object(agent, "KEYBOARD_CHECK_SECONDS", 0.3):
|
||||
thread = threading.Thread(target=lambda: failure.append(self.capture(watcher.watch)), daemon=True)
|
||||
thread.start()
|
||||
self.wait_for(lambda: self.state() == {"steamKeyboard": False, "seq": 1})
|
||||
self.assertEqual("Runtime.addBinding", client.seen[0]["method"])
|
||||
self.assertEqual(agent.KEYBOARD_BINDING, client.seen[0]["params"]["name"])
|
||||
self.assertIn("IsShowingVirtualKeyboard", client.seen[1]["params"]["expression"])
|
||||
self.assertIn(agent.KEYBOARD_BINDING, client.seen[1]["params"]["expression"])
|
||||
self.assertNotIn("__BINDING__", client.seen[1]["params"]["expression"])
|
||||
client.push("true")
|
||||
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True)
|
||||
client.push("false")
|
||||
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is False)
|
||||
client.showing = True
|
||||
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True)
|
||||
self.assertGreaterEqual(len([m for m in client.seen if m["method"] == "Runtime.evaluate"]), 2)
|
||||
client.drop()
|
||||
thread.join(5)
|
||||
self.assertFalse(thread.is_alive())
|
||||
self.assertIsInstance(failure[0], OSError)
|
||||
|
||||
def test_any_loss_reports_the_keyboard_closed_and_backs_off(self):
|
||||
watcher = agent.KeyboardWatcher(self.dir)
|
||||
watcher.report(True)
|
||||
|
||||
def attached_then_lost():
|
||||
watcher.attached = True
|
||||
raise OSError("DevTools closed the connection")
|
||||
|
||||
steps = iter([agent.AgentError("NO_DEVTOOLS", "no port"), agent.AgentError("NO_DEVTOOLS", "no port"),
|
||||
attached_then_lost, KeyError("SteamUIStore")])
|
||||
|
||||
def watch():
|
||||
step = next(steps, None)
|
||||
if step is None:
|
||||
raise SystemExit
|
||||
if callable(step):
|
||||
step()
|
||||
raise step
|
||||
|
||||
with patch.object(watcher, "watch", side_effect=watch), patch.object(agent.time, "sleep") as sleep, \
|
||||
patch.object(agent, "log") as log:
|
||||
with self.assertRaises(SystemExit):
|
||||
watcher.run()
|
||||
self.assertEqual({"steamKeyboard": False, "seq": 2}, self.state())
|
||||
self.assertEqual([2, 4, 2, 4], [c.args[0] for c in sleep.call_args_list])
|
||||
self.assertFalse(watcher.attached)
|
||||
self.assertEqual(3, log.call_count)
|
||||
|
||||
def test_no_shared_context_yet(self):
|
||||
with patch.object(agent, "cdp_targets", return_value=[{"title": "Steam", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]):
|
||||
with self.assertRaises(agent.AgentError) as caught:
|
||||
agent.KeyboardWatcher(self.dir).watch()
|
||||
self.assertEqual("NO_TARGET", caught.exception.code)
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node is not installed")
|
||||
def test_page_script_watches_every_window_with_or_without_subscribe(self):
|
||||
harness = r"""
|
||||
const assert = require('assert');
|
||||
globalThis.window = globalThis;
|
||||
const script = require('fs').readFileSync(process.argv[2], 'utf8');
|
||||
const calls = [];
|
||||
window.droiddeckSteamKeyboard = value => calls.push(value);
|
||||
const tick = ms => new Promise(done => setTimeout(done, ms));
|
||||
const value = subscribe => {
|
||||
const v = { m_currentValue: false, m_callbacks: [] };
|
||||
if (subscribe) v.Subscribe = cb => { v.m_callbacks.push(cb); return { Unsubscribe() {} }; };
|
||||
v.set = next => { v.m_currentValue = next; for (const cb of v.m_callbacks) cb(next); };
|
||||
return v;
|
||||
};
|
||||
(async () => {
|
||||
assert.strictEqual(eval(script), false);
|
||||
assert.deepStrictEqual(calls, ['false']);
|
||||
const main = value(true), overlay = value(false);
|
||||
globalThis.SteamUIStore = { WindowStore: { SteamUIWindows: [{ VirtualKeyboardManager: { IsShowingVirtualKeyboard: main } }] } };
|
||||
assert.strictEqual(eval(script), false);
|
||||
main.set(true);
|
||||
await tick(20);
|
||||
assert.deepStrictEqual(calls, ['false', 'true']);
|
||||
main.set(false);
|
||||
await tick(20);
|
||||
SteamUIStore.WindowStore.SteamUIWindows.push({}, { VirtualKeyboardManager: { IsShowingVirtualKeyboard: overlay } });
|
||||
overlay.m_currentValue = true;
|
||||
await tick(700);
|
||||
assert.deepStrictEqual(calls, ['false', 'true', 'false', 'true']);
|
||||
assert.strictEqual(eval(script), true);
|
||||
assert.strictEqual(main.m_callbacks.length, 1);
|
||||
clearInterval(window.__droiddeckKeyboard.timer);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
"""
|
||||
(self.dir / "keyboard.js").write_text(agent.KEYBOARD_JS)
|
||||
(self.dir / "harness.js").write_text(harness)
|
||||
result = subprocess.run(["node", str(self.dir / "harness.js"), str(self.dir / "keyboard.js")],
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
|
||||
@staticmethod
|
||||
def capture(call):
|
||||
try:
|
||||
call()
|
||||
except Exception as e:
|
||||
return e
|
||||
|
||||
|
||||
class VrFocusTest(unittest.TestCase):
|
||||
def test_scene_dashboard_and_external_focus_changes(self):
|
||||
focus = agent.VrSceneFocus()
|
||||
|
||||
@@ -18,24 +18,44 @@ READER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void)
|
||||
static int vector_count;
|
||||
|
||||
static ssize_t controller_read(int fd, void *buffer, size_t size)
|
||||
{
|
||||
if (!vector_count)
|
||||
return read(fd, buffer, size);
|
||||
struct iovec vectors[3] = {
|
||||
{buffer, sizeof(struct input_event)},
|
||||
{(char *)buffer + sizeof(struct input_event), 0},
|
||||
{(char *)buffer + sizeof(struct input_event), size - sizeof(struct input_event)},
|
||||
};
|
||||
if (vector_count == 1) {
|
||||
vectors[0].iov_len = size;
|
||||
return readv(fd, vectors, 1);
|
||||
}
|
||||
return readv(fd, vectors, 3);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0;
|
||||
struct input_event events[64];
|
||||
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0) {
|
||||
perror("open");
|
||||
return 1;
|
||||
}
|
||||
while (read(fd, events, sizeof(events)) > 0)
|
||||
while (controller_read(fd, events, sizeof(events)) > 0)
|
||||
;
|
||||
puts("ready");
|
||||
fflush(stdout);
|
||||
char go;
|
||||
if (read(0, &go, 1) != 1)
|
||||
return 1;
|
||||
ssize_t got = read(fd, events, sizeof(events));
|
||||
ssize_t got = controller_read(fd, events, sizeof(events));
|
||||
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
|
||||
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
|
||||
events[i].code, events[i].value);
|
||||
@@ -65,6 +85,146 @@ int main(void)
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
READV_CHECKS = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
struct input_event events[64];
|
||||
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0)
|
||||
return 1;
|
||||
while (read(fd, events, sizeof(events)) > 0)
|
||||
;
|
||||
struct iovec vector = {events, sizeof(events)};
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EAGAIN)
|
||||
return 2;
|
||||
if (readv(fd, NULL, 0) != 0)
|
||||
return 3;
|
||||
vector.iov_len = 0;
|
||||
if (readv(fd, &vector, 1) != 0)
|
||||
return 4;
|
||||
vector.iov_len = sizeof(struct input_event) - 1;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EINVAL)
|
||||
return 5;
|
||||
ssize_t (*invoke)(int, const struct iovec *, int) = readv;
|
||||
if (invoke(fd, NULL, -1) != -1 || errno != EINVAL)
|
||||
return 6;
|
||||
if (invoke(fd, NULL, 1025) != -1 || errno != EINVAL)
|
||||
return 7;
|
||||
if (invoke(fd, NULL, 1) != -1 || errno != EFAULT)
|
||||
return 8;
|
||||
long page = sysconf(_SC_PAGESIZE);
|
||||
void *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (area == MAP_FAILED)
|
||||
return 10;
|
||||
struct iovec *boundary = (struct iovec *)((char *)area + page - sizeof(struct iovec));
|
||||
*boundary = vector;
|
||||
if (mprotect((char *)area + page, page, PROT_NONE))
|
||||
return 11;
|
||||
if (invoke(fd, boundary, 2) != -1 || errno != EFAULT)
|
||||
return 12;
|
||||
if (invoke(fd, boundary + 1, 1) != -1 || errno != EFAULT)
|
||||
return 13;
|
||||
if (munmap(area, 2 * page))
|
||||
return 14;
|
||||
if (invoke(fd, boundary, 1) != -1 || errno != EFAULT)
|
||||
return 15;
|
||||
int pipefd[2];
|
||||
char text[5] = {0};
|
||||
struct iovec parts[2] = {{text, 1}, {text + 1, 3}};
|
||||
if (pipe(pipefd) || write(pipefd[1], "test", 4) != 4 ||
|
||||
readv(pipefd[0], parts, 2) != 4 || strcmp(text, "test"))
|
||||
return 9;
|
||||
puts("ok");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
READV_DESTINATION_CHECKS = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct input_event events[64];
|
||||
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0)
|
||||
return 1;
|
||||
if (argc > 1)
|
||||
while (read(fd, events, sizeof(events)) > 0)
|
||||
;
|
||||
puts("ready");
|
||||
fflush(stdout);
|
||||
char go;
|
||||
if (read(0, &go, 1) != 1)
|
||||
return 2;
|
||||
long page = sysconf(_SC_PAGESIZE);
|
||||
char *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (area == MAP_FAILED || mprotect(area + page, page, PROT_NONE))
|
||||
return 3;
|
||||
struct iovec vector = {area + page, sizeof(struct input_event)};
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 4;
|
||||
if (read(fd, vector.iov_base, vector.iov_len) != -1 || errno != EFAULT)
|
||||
return 5;
|
||||
if (mprotect(area, page, PROT_READ))
|
||||
return 6;
|
||||
vector.iov_base = area;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 7;
|
||||
if (mprotect(area, page, PROT_READ | PROT_WRITE) || munmap(area + page, page))
|
||||
return 8;
|
||||
vector.iov_base = area + page;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 9;
|
||||
vector.iov_base = area + page - 1;
|
||||
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
|
||||
return 15;
|
||||
vector.iov_base = area + page - sizeof(struct input_event);
|
||||
vector.iov_len = 2 * sizeof(struct input_event);
|
||||
if (readv(fd, &vector, 1) != sizeof(struct input_event))
|
||||
return 10;
|
||||
struct input_event *first = vector.iov_base;
|
||||
if (first->type != EV_KEY || first->code != BTN_A)
|
||||
return 11;
|
||||
struct iovec parts[2] = {{events, sizeof(struct input_event)}, {NULL, sizeof(struct input_event)}};
|
||||
if (readv(fd, parts, 2) != sizeof(struct input_event))
|
||||
return 12;
|
||||
if (events[0].type != (argc > 1 ? EV_ABS : EV_KEY) || events[0].code != (argc > 1 ? ABS_Y : BTN_B))
|
||||
return 13;
|
||||
vector.iov_base = events;
|
||||
vector.iov_len = sizeof(events);
|
||||
ssize_t got = readv(fd, &vector, 1);
|
||||
if (got != (argc > 1 ? 1 : 18) * sizeof(struct input_event) ||
|
||||
events[0].type != (argc > 1 ? EV_SYN : EV_KEY) || events[0].code != (argc > 1 ? SYN_REPORT : BTN_X))
|
||||
return 14;
|
||||
munmap(area, page);
|
||||
puts("ok");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
OVERLAY_READ = r"""
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
ssize_t read(int fd, void *buffer, size_t size)
|
||||
{
|
||||
struct iovec vector = {buffer, size};
|
||||
return readv(fd, &vector, 1);
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def can_build(bits):
|
||||
@@ -82,15 +242,16 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
|
||||
def ring(self):
|
||||
def ring(self, virtual=True):
|
||||
hooks = self.tmp / "hooks"
|
||||
hooks.mkdir()
|
||||
(hooks / "event16").touch()
|
||||
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
|
||||
(hooks / ("event16" if virtual else "event0")).touch()
|
||||
ring = bytearray(HEADER + CAPACITY * EVENT + (DESCRIPTION if virtual else 0))
|
||||
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 5, 0, 0)
|
||||
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
|
||||
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
|
||||
path = hooks / ".uinput-event16"
|
||||
if virtual:
|
||||
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
|
||||
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
|
||||
path = hooks / ".uinput-event16" if virtual else self.tmp / "ring0"
|
||||
path.write_bytes(bytes(ring))
|
||||
return hooks, path
|
||||
|
||||
@@ -106,11 +267,22 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
|
||||
return library, binary
|
||||
|
||||
def read_through(self, bits):
|
||||
library, reader = self.build(bits, READER, "reader")
|
||||
hooks, path = self.ring()
|
||||
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER):
|
||||
if not virtual:
|
||||
program = program.replace("event16", "event0")
|
||||
library, reader = self.build(bits, program, "reader")
|
||||
hooks, path = self.ring(virtual=virtual)
|
||||
env = dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks))
|
||||
process = subprocess.Popen([str(reader)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
|
||||
if not virtual:
|
||||
env["FAKE_EVDEV_MEMFD_PATHS"] = "0=" + str(path)
|
||||
if overlay:
|
||||
source = self.tmp / "overlay.c"
|
||||
source.write_text(OVERLAY_READ)
|
||||
overlay_library = self.tmp / "overlay.so"
|
||||
subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True)
|
||||
env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library)
|
||||
command = [str(reader)] + ([str(vectors)] if vectors else [])
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
|
||||
self.addCleanup(process.kill)
|
||||
self.assertEqual(process.stdout.readline(), "ready\n")
|
||||
with open(path, "r+b") as ring:
|
||||
@@ -131,6 +303,43 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
self.assertEqual(self.read_through("-m64"),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_reads_events_instead_of_the_backing_file(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=1),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_reads_the_original_controller_ring(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=1, virtual=False),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_an_overlay_read_fallback_to_readv_reads_events_without_recursion(self):
|
||||
self.assertEqual(self.read_through("-m64", overlay=True),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_reads_event_aligned_vectors_and_skips_empty_ones(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=3),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_a_32_bit_guest_reads_the_same_events_with_readv(self):
|
||||
self.assertEqual(self.read_through("-m32", vectors=1),
|
||||
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
|
||||
|
||||
def test_readv_preserves_nonblocking_errors_and_other_descriptors(self):
|
||||
library, probe = self.build("-m64", READV_CHECKS, "readv-checks")
|
||||
hooks, _ = self.ring()
|
||||
run = subprocess.run([str(probe)], capture_output=True, text=True, timeout=10,
|
||||
env=dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks)))
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
self.assertEqual(run.stdout, "ok\n")
|
||||
|
||||
def test_readv_keyframes_handle_destination_faults_and_partial_progress(self):
|
||||
self.assertEqual(self.read_through("-m64", program=READV_DESTINATION_CHECKS), "ok\n")
|
||||
|
||||
def test_readv_ring_events_handle_destination_faults_and_partial_progress(self):
|
||||
self.assertEqual(self.read_through("-m64", vectors=1, program=READV_DESTINATION_CHECKS), "ok\n")
|
||||
|
||||
def test_a_32_bit_guest_handles_readv_destination_faults(self):
|
||||
self.assertEqual(self.read_through("-m32", program=READV_DESTINATION_CHECKS), "ok\n")
|
||||
|
||||
def test_an_event_node_rejects_joydev_requests_so_sdl_reads_its_id(self):
|
||||
library, probe = self.build("-m64", PROBE, "probe")
|
||||
hooks, _ = self.ring()
|
||||
|
||||
@@ -101,6 +101,17 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(env["REMOVE"], "inherited")
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
|
||||
|
||||
def test_games_get_their_own_turnip_debug_and_a_game_profile_still_wins(self):
|
||||
gpu = MODULE["game_gpu"]
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "KEEP": "1"}), {"KEEP": "1"})
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "sysmem"}), {"TU_DEBUG": "sysmem"})
|
||||
self.assertEqual(gpu({"DROIDDECK_GAME_TU_DEBUG": "nolrz"}), {"TU_DEBUG": "nolrz"})
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem"}), {"TU_DEBUG": "sysmem"})
|
||||
config = {"version": 1, "games": {"42": {"TU_DEBUG": "sysmem"}}}
|
||||
env = gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""})
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
|
||||
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
|
||||
|
||||
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
|
||||
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
|
||||
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
|
||||
@@ -190,6 +201,64 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(other / "Other.exe").touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
|
||||
|
||||
def test_easy_anti_cheat_games_start_offline_only_when_opted_in(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
game = Path(tmp) / "ELDEN RING/Game"
|
||||
(game / "EasyAntiCheat").mkdir(parents=True)
|
||||
for name in ("start_protected_game.exe", "eldenring.exe"):
|
||||
(game / name).touch()
|
||||
(game / "EasyAntiCheat/settings.json").write_text('\ufeff{ "executable" : "eldenring.exe" }', encoding="utf-8")
|
||||
command = ["proton", "waitforexitandrun", str(game / "start_protected_game.exe"), "-arg"]
|
||||
offline = MODULE["offline_without_anticheat"]
|
||||
self.assertEqual(offline(command, {}), command)
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "0"}), command)
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}),
|
||||
["proton", "waitforexitandrun", str(game / "eldenring.exe"), "-arg"])
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "../../escape.exe" }')
|
||||
(Path(tmp) / "escape.exe").touch()
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "missing.exe" }')
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "link/escape.exe" }')
|
||||
outside = Path(tmp) / "outside"
|
||||
outside.mkdir()
|
||||
(outside / "escape.exe").touch()
|
||||
(game / "link").symlink_to(outside, target_is_directory=True)
|
||||
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
|
||||
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "eldenring.exe" }')
|
||||
plain = ["proton", "waitforexitandrun", str(game / "eldenring.exe")]
|
||||
self.assertEqual(offline(plain, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), plain)
|
||||
self.assertEqual(offline(["proton", "run", command[2]],
|
||||
{"DROIDDECK_ANTICHEAT_OFFLINE": "1"}),
|
||||
["proton", "run", command[2]])
|
||||
|
||||
def test_easy_anti_cheat_forwarding_through_entrypoint(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
game = home / "ELDEN RING/Game"
|
||||
(game / "EasyAntiCheat").mkdir(parents=True)
|
||||
bootstrapper = game / "start_protected_game.exe"
|
||||
target = game / "eldenring.exe"
|
||||
bootstrapper.touch()
|
||||
target.touch()
|
||||
(game / "EasyAntiCheat/settings.json").write_text(json.dumps({"executable": "eldenring.exe"}))
|
||||
proton = home / "fake-proton"
|
||||
proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n")
|
||||
proton.chmod(0o755)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
|
||||
env.pop("DROIDDECK_ANTICHEAT_OFFLINE", None)
|
||||
for setting, expected in (("1", target), ("0", bootstrapper), (None, bootstrapper)):
|
||||
with self.subTest(setting=setting):
|
||||
values = {} if setting is None else {"DROIDDECK_ANTICHEAT_OFFLINE": setting}
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": values}}))
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"),
|
||||
str(proton), "waitforexitandrun", str(bootstrapper), "-arg"],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(json.loads(result.stdout.strip()),
|
||||
["waitforexitandrun", str(expected), "-arg"])
|
||||
|
||||
def test_deep_rock_gdk_avoids_the_raytracing_pipeline_crash(self):
|
||||
game = "/game/FSD/Binaries/WinGDK/FSD-WinGDK-Shipping.exe"
|
||||
env, extra, notes = MODULE["engine_fixes"](game, [])
|
||||
|
||||
@@ -29,6 +29,32 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
self.source.parent.mkdir(parents=True)
|
||||
self.source.write_text('current source')
|
||||
self.audio(['pactl', 'modules/arm64/module-aaudio-sink.so', 'modules/arm64/module-directaudio-native-sink.so'])
|
||||
self.packs()
|
||||
|
||||
def pack(self, name, files):
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w') as archive:
|
||||
for rel, content in files.items():
|
||||
entry = tarfile.TarInfo(rel)
|
||||
entry.size = len(content)
|
||||
archive.addfile(entry, io.BytesIO(content))
|
||||
path = self.root / runtime.PACKS / (name + '.tar.zst')
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(), capture_output=True, check=True).stdout)
|
||||
|
||||
def packs(self):
|
||||
self.pack('tracking', {library.rsplit('/', 1)[1]: b'library' for library in runtime.PACKED_LIBRARIES})
|
||||
proot = {}
|
||||
for name, (pack, rel) in runtime.PACKED_FILES.items():
|
||||
proot[rel] = (self.root / runtime.outputs(self.root)[name]).read_bytes()
|
||||
self.pack('proot', proot)
|
||||
for prefix, name in runtime.PACKED.items():
|
||||
base = self.root / 'app/src/main' / prefix
|
||||
self.pack(name, {path.relative_to(base).as_posix(): path.read_bytes() for path in base.rglob('*') if path.is_file()})
|
||||
|
||||
@staticmethod
|
||||
def in_apk(name):
|
||||
return name not in runtime.PACKED_FILES and not any(name.startswith(prefix) for prefix in runtime.PACKED)
|
||||
|
||||
def audio(self, names):
|
||||
stream = io.BytesIO()
|
||||
@@ -40,6 +66,11 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
path = self.root / 'app/build/prepared-assets/pulseaudio.tzst'
|
||||
path.write_bytes(subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(), capture_output=True, check=True).stdout)
|
||||
|
||||
def test_an_apk_still_carrying_proot_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {'lib/arm64-v8a/libproot.so': b'prepared runtime'})
|
||||
with self.assertRaisesRegex(ValueError, 'proot pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_missing_proot_cannot_be_attested(self):
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'libproot.so'):
|
||||
@@ -82,6 +113,8 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'old.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if not self.in_apk(name):
|
||||
continue
|
||||
content = b'stale' if name == 'assets/linuxfs/libssbs.so' else (self.root / output['path']).read_bytes()
|
||||
package.writestr(name, content)
|
||||
with self.assertRaisesRegex(ValueError, 'stale runtime input'):
|
||||
@@ -93,9 +126,43 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'current.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
if self.in_apk(name):
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def current_apk(self, path, extra=None):
|
||||
runtime.record(self.root)
|
||||
data = runtime.verify(self.root)
|
||||
with ZipFile(path, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if self.in_apk(name):
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
for name, content in (extra or {}).items():
|
||||
package.writestr(name, content)
|
||||
return path
|
||||
|
||||
def test_an_apk_still_carrying_a_packed_tree_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {'assets/linuxfs/usr/local/lib/droiddeck-xbox/xodus-cli': b'prepared runtime'})
|
||||
with self.assertRaisesRegex(ValueError, 'xbox pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_an_apk_still_carrying_tracking_libraries_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {runtime.PACKED_LIBRARIES[0]: b'library'})
|
||||
with self.assertRaisesRegex(ValueError, 'tracking pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_a_stale_pack_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'current.apk')
|
||||
self.pack('comet', {'comet': b'old build', 'version': b'old'})
|
||||
with self.assertRaisesRegex(ValueError, 'comet is missing or has a stale'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_a_missing_pack_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'current.apk')
|
||||
(self.root / runtime.PACKS / 'xbox.tar.zst').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'Missing add-on pack xbox'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_windows_manifest_matches_portable_apk_paths(self):
|
||||
path_type = type(self.root)
|
||||
original_relative_to = path_type.relative_to
|
||||
@@ -114,6 +181,8 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'portable.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if not self.in_apk(name):
|
||||
continue
|
||||
self.assertNotIn('\\', name)
|
||||
self.assertNotIn('\\', output['path'])
|
||||
package.writestr(name, (self.root / output['path']).read_bytes())
|
||||
@@ -125,6 +194,8 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
apk = self.root / 'expanded.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
for name, output in data['outputs'].items():
|
||||
if not self.in_apk(name):
|
||||
continue
|
||||
content = (self.root / output['path']).read_bytes()
|
||||
if name.endswith('.gzip'):
|
||||
name = name.removesuffix('.gzip')
|
||||
|
||||
@@ -155,6 +155,26 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_an_unchanged_registry_is_not_read_again(self):
|
||||
self.game()
|
||||
self.run_seed()
|
||||
self.run_seed()
|
||||
shim = self.tmp / "bin"
|
||||
shim.mkdir()
|
||||
log = self.tmp / "awk.log"
|
||||
(shim / "awk").write_text('#!/bin/sh\nprintf "%%s\\n" "$*" >> "%s"\nexec %s "$@"\n' % (log, shutil.which("awk")))
|
||||
(shim / "awk").chmod(0o755)
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
|
||||
once = self.reg.read_text()
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(once, self.reg.read_text())
|
||||
self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "")
|
||||
replaced = self.reg.with_name("system.reg.new")
|
||||
replaced.write_text("WINE REGISTRY Version 2\n")
|
||||
os.replace(replaced, self.reg)
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
|
||||
|
||||
def test_the_prefix_date_is_kept(self):
|
||||
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
|
||||
self.run_seed()
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
def run_case():
|
||||
return re.search(r"^ run\)\n.*?^ ;;\n", SESSION.read_text(), re.M | re.S).group(0)
|
||||
|
||||
|
||||
def steam_display():
|
||||
return re.search(r"^ steam\)\n(.*?)^ steam_x64=0\n", SESSION.read_text(), re.M | re.S).group(1)
|
||||
|
||||
|
||||
class SessionRunDisplayTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
self.target = self.dir / "target.sh"
|
||||
self.target.write_text("printf '%s\\n' \"${WAYLAND_DISPLAY-unset}\" \"${XDG_SESSION_TYPE-unset}\""
|
||||
" > \"$1\"\n")
|
||||
|
||||
def display(self, **env):
|
||||
base = {k: v for k, v in os.environ.items()
|
||||
if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE",
|
||||
"BL_LAUNCH_DIR")}
|
||||
seen = self.dir / "seen"
|
||||
script = ("program_cores() { :; }\nmode=run\ncase $mode in\n" + run_case() + "esac\n"
|
||||
+ "echo unreachable\n")
|
||||
run = subprocess.run(["bash", "-c", script, "droiddeck-session", str(self.target), str(seen)],
|
||||
env={**base, **env}, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, run.returncode, run.stderr)
|
||||
self.assertNotIn("unreachable", run.stdout)
|
||||
return seen.read_text().splitlines()
|
||||
|
||||
def test_programs_under_gamescope_cannot_reach_a_wayland_server(self):
|
||||
self.assertEqual(["", "x11"], self.display(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
|
||||
WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
def test_without_gamescope_the_display_is_left_alone(self):
|
||||
self.assertEqual(["wayland-0", "wayland"], self.display(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
def steam_env(self, **env):
|
||||
base = {k: v for k, v in os.environ.items()
|
||||
if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE")}
|
||||
script = steam_display() + ('printf "%s\\n" "${WAYLAND_DISPLAY-unset}" "${XDG_SESSION_TYPE-unset}"'
|
||||
' "${MOZ_SHM_NO_SEALS-unset}" "${MOZ_DISABLE_CONTENT_SANDBOX-unset}"\n')
|
||||
run = subprocess.run(["bash", "-c", script], env={**base, **env}, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, run.returncode, run.stderr)
|
||||
return run.stdout.splitlines()
|
||||
|
||||
def test_steam_games_under_gamescope_cannot_reach_a_wayland_server(self):
|
||||
self.assertEqual(["", "x11", "1", "1"], self.steam_env(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
|
||||
WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
def test_steam_without_gamescope_keeps_the_display(self):
|
||||
self.assertEqual(["wayland-0", "wayland", "1", "1"],
|
||||
self.steam_env(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,82 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
SOURCE = SESSION.read_text()
|
||||
ARM64_BRANCH = SOURCE.index(' else\n step "checking the Steam client (first run')
|
||||
START = SOURCE.index(' droiddeck-steam-install || steam_setup_failed $?\n', ARM64_BRANCH)
|
||||
END = SOURCE.index(' step "Steam client ready"\n', START)
|
||||
HELPER = re.search(r'^steam_setup_failed\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group()
|
||||
INSTALL_BLOCK = HELPER + textwrap.dedent(SOURCE[START:END])
|
||||
RUN_GAMESCOPE = re.search(r'^run_gamescope\(\) \(\n.*?^\)\n', SOURCE, re.M | re.S).group()
|
||||
MARKER = '== steam: the Steam client could not be set up'
|
||||
|
||||
|
||||
class SteamClientSetupFailureTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
|
||||
def installer(self, status):
|
||||
script = self.root / 'droiddeck-steam-install'
|
||||
script.write_text('#!/bin/bash\n'
|
||||
'echo "curl: (35) Recv failure: Connection reset by peer" >&2\n'
|
||||
'exit ' + str(status) + '\n')
|
||||
script.chmod(0o755)
|
||||
|
||||
def env(self, **extra):
|
||||
base = {k: v for k, v in os.environ.items() if k != 'BL_STEAM_EXIT_FILE'}
|
||||
return dict(base, PATH=str(self.root) + os.pathsep + os.environ['PATH'],
|
||||
XDG_RUNTIME_DIR=str(self.root), **extra)
|
||||
|
||||
def run_block(self, status, exit_file=None):
|
||||
self.installer(status)
|
||||
extra = {'BL_STEAM_EXIT_FILE': str(exit_file)} if exit_file else {}
|
||||
return subprocess.run(['bash', '-c', INSTALL_BLOCK + 'echo continued\n'], env=self.env(**extra),
|
||||
capture_output=True, text=True, timeout=10)
|
||||
|
||||
def test_failed_install_reports_its_status_in_the_exit_file(self):
|
||||
exit_file = self.root / 'exit'
|
||||
result = self.run_block(1, exit_file)
|
||||
self.assertEqual(1, result.returncode)
|
||||
self.assertIn(MARKER + ' (status 1)', result.stdout)
|
||||
self.assertNotIn('continued', result.stdout)
|
||||
self.assertEqual('1\n', exit_file.read_text())
|
||||
|
||||
def test_failed_install_outside_gamescope_still_exits_with_its_status(self):
|
||||
result = self.run_block(50)
|
||||
self.assertEqual(50, result.returncode)
|
||||
self.assertIn(MARKER + ' (status 50)', result.stdout)
|
||||
|
||||
def test_ready_client_continues_without_a_report(self):
|
||||
exit_file = self.root / 'exit'
|
||||
result = self.run_block(0, exit_file)
|
||||
self.assertEqual(0, result.returncode)
|
||||
self.assertIn('continued', result.stdout)
|
||||
self.assertNotIn(MARKER, result.stdout)
|
||||
self.assertFalse(exit_file.exists())
|
||||
|
||||
def test_failed_install_survives_successful_compositor_shutdown(self):
|
||||
self.installer(1)
|
||||
compositor = self.root / 'gamescope'
|
||||
compositor.write_text('#!/bin/bash\n"$@"\nexit 0\n')
|
||||
compositor.chmod(0o755)
|
||||
child = self.root / 'session-child'
|
||||
child.write_text('#!/bin/bash\n' + INSTALL_BLOCK + 'exit 0\n')
|
||||
child.chmod(0o755)
|
||||
result = subprocess.run(['bash', '-c', RUN_GAMESCOPE + '\nrun_gamescope "$@"', 'session', str(child)],
|
||||
env=self.env(), capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(1, result.returncode)
|
||||
self.assertIn(MARKER, result.stdout)
|
||||
self.assertEqual(list(self.root.glob('droiddeck-steam-exit.??????')), [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -54,6 +54,7 @@ class FakeSocket {
|
||||
state.authed = dec.decode(h[40][0]) === "secret" && dec.decode(body[1][0]) === "secret";
|
||||
result = state.authed ? 1 : 5;
|
||||
} else if (!state.authed) result = 5;
|
||||
else if (method === "CompatManager.GetCompatTools#1" && ["16", "128"].includes(String(body[1][0]))) result = Number(body[1][0]);
|
||||
else if (method === "CompatManager.GetCompatTools#1") {
|
||||
const app = String(body[1] ? body[1][0] : 0n);
|
||||
for (const name of state.known) { const t = []; lenField(1, enc.encode(name), t); lenField(2, enc.encode(name + " shown"), t); lenField(1, t, out); }
|
||||
@@ -79,17 +80,19 @@ const install = require("fs").readFileSync(process.argv[4], "utf8");
|
||||
const before = await c.get(0);
|
||||
await c.set(0, "droiddeck-proton-11-arm64");
|
||||
await c.set(42, "");
|
||||
const after = await c.many(["0", "42", "43"]);
|
||||
const after = await c.many(["0", "42", "43", "128"]);
|
||||
const timedOut = await c.many(["0", "16"]).then(() => null, (e) => e.eresult);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
console.log(JSON.stringify({ before, after, log: state.log, notify: state.notify, url: state.socket.url }));
|
||||
console.log(JSON.stringify({ before, after, timedOut, log: state.log, notify: state.notify, url: state.socket.url }));
|
||||
})().catch((e) => { console.error(e.stack || String(e)); process.exit(1); });
|
||||
"""
|
||||
|
||||
|
||||
class FakePage:
|
||||
def __init__(self, mapping, known):
|
||||
def __init__(self, mapping, known, refused=()):
|
||||
self.mapping = dict(mapping)
|
||||
self.known = list(known)
|
||||
self.refused = set(refused)
|
||||
self.sets = []
|
||||
|
||||
def compat(self, call):
|
||||
@@ -98,8 +101,10 @@ class FakePage:
|
||||
if name == "get":
|
||||
return {"selected": self.mapping.get(str(args[0]), ""), "fallback": "proton_experimental", "tools": self.known}
|
||||
if name == "many":
|
||||
return {app: self.mapping.get(app, "") for app in args[0]}
|
||||
return {app: self.mapping.get(app, "") for app in args[0] if app not in self.refused}
|
||||
if name == "set":
|
||||
if str(args[0]) in self.refused:
|
||||
raise RuntimeError("SpecifyCompatTool %s failed (128)" % args[0])
|
||||
self.mapping[str(args[0])] = args[1]
|
||||
self.sets.append((str(args[0]), args[1]))
|
||||
return True
|
||||
@@ -202,6 +207,7 @@ assert.deepStrictEqual(calls, [['611670', 'custom args', -1, 100], ['2508200', '
|
||||
self.assertEqual(out["url"], "ws://127.0.0.1:4242/transportsocket/")
|
||||
self.assertEqual(out["before"], {"selected": TOOL, "fallback": "proton_experimental", "tools": [TOOL, TOOL_11, "proton_experimental"]})
|
||||
self.assertEqual(out["after"], {"0": TOOL_11, "42": "", "43": ""})
|
||||
self.assertEqual(out["timedOut"], 16)
|
||||
self.assertEqual(out["log"], ["0=" + TOOL_11, "42="])
|
||||
self.assertEqual(out["notify"], ["1", "2"])
|
||||
|
||||
@@ -264,6 +270,21 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertTrue(state["live"])
|
||||
self.assertEqual(self.helper.installed, ["10", "11"])
|
||||
|
||||
def test_an_app_the_client_refuses_is_dropped_instead_of_failing_the_sync(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": "proton_experimental"}, [TOOL, TOOL_11], refused={"1628350"})
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "1628350": TOOL}}))
|
||||
(self.state / "games.json").write_text(json.dumps({"version": 1, "games": {"1628350": {"valve": True, "dir": "Proton 11.0 (ARM64)"}}}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("11", TOOL)])
|
||||
self.assertEqual(state["auto"], {"10": TOOL, "11": TOOL})
|
||||
|
||||
def test_a_refused_apps_native_choice_is_kept(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11], refused={"20"})
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "native_choices": ["20"]}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], ["20"])
|
||||
|
||||
def test_app_request_moves_the_default_and_followers(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": "GE-Proton11-7"}, [TOOL, TOOL_11])
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL}}))
|
||||
@@ -488,6 +509,70 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
|
||||
def test_clearing_a_tool_picked_in_steam_keeps_the_native_build(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
|
||||
page.known.append(COMPAT["FEX_TOOL"])
|
||||
page.mapping[app] = COMPAT["FEX_TOOL"]
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"]))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertNotIn(app, state["auto"])
|
||||
|
||||
page.mapping[app] = ""
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
|
||||
restarted = LIVE["Helper"](str(self.steam), 1)
|
||||
restarted.page = page
|
||||
restarted.reconcile()
|
||||
self.assertEqual(page.sets, [])
|
||||
|
||||
def test_a_new_tool_for_a_picked_game_is_kept_before_the_client_writes_its_config(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]})
|
||||
page.mapping[app] = TOOL_11
|
||||
with mock.patch.dict(COMPAT, {"native_targets": lambda _root, apps: {app: COMPAT["FEX_TOOL"]} if app in apps else {}}):
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(page.mapping[app], TOOL_11)
|
||||
self.assertIn(app, state["picked"])
|
||||
|
||||
def test_a_cleared_picked_game_showing_a_stale_inherited_tool_stays_native(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]})
|
||||
page.mapping[app] = "proton"
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
|
||||
def test_a_clear_saved_after_the_helper_stopped_is_kept_at_the_next_start(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
|
||||
page.known.append(COMPAT["FEX_TOOL"])
|
||||
page.mapping[app] = COMPAT["FEX_TOOL"]
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"]))
|
||||
state = self.reconcile(page)
|
||||
self.assertIn(app, state["picked"])
|
||||
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
with mock.patch.dict(COMPAT["register_default"].__globals__, {"native_targets": COMPAT["native_targets"]}):
|
||||
COMPAT["register_default"](str(config), ["10", "11", app], settle=True, directory=str(self.state))
|
||||
self.assertNotIn(app, COMPAT["read_config_mapping"](str(config)))
|
||||
state = json.loads((self.state / "state.json").read_text())
|
||||
self.assertEqual(state["native_choices"], [app])
|
||||
self.assertNotIn(app, state["picked"])
|
||||
|
||||
def test_unmapped_dual_platform_game_gets_the_default_without_a_readable_config(self):
|
||||
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL}, "native_choices": ["11"]})
|
||||
(self.steam / "config/config.vdf").unlink()
|
||||
|
||||
@@ -226,6 +226,43 @@ class CloudHooks(unittest.TestCase):
|
||||
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
|
||||
self.assertEqual('cloud-up', asked[2][0]['op'])
|
||||
|
||||
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='epic', ident='fa4240e5')
|
||||
sidecar = json.loads((folder / store.SIDECAR).read_text())
|
||||
sidecar['epic'] = {'eos': False, 'offline': True}
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
compat = Path(root) / 'compatdata/1'
|
||||
order = []
|
||||
|
||||
def run(argv, **kwargs):
|
||||
order.append(argv)
|
||||
(compat / 'pfx').mkdir(parents=True)
|
||||
(compat / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
|
||||
env = {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'BL_STORE_PROTON': str(proton)}
|
||||
with patch.dict(os.environ, env), patch.object(store.subprocess, 'run', side_effect=run), \
|
||||
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: order.append(request) or {'result': 'ok'}):
|
||||
self.assertEqual(store.STORE_GAME, store.main([str(folder / store.LAUNCHER)]))
|
||||
self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c', 'exit'], order[0])
|
||||
self.assertEqual({'op': 'cloud-down', 'store': 'epic', 'id': 'fa4240e5'}, order[-1])
|
||||
self.assertEqual('present', store.create_prefix(str(compat), str(proton)))
|
||||
self.assertEqual(2, len(order))
|
||||
|
||||
def test_a_prefix_that_is_not_made_leaves_the_deferred_download(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
with patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
|
||||
self.assertEqual('failed', store.create_prefix(root + '/compatdata/1', str(proton)))
|
||||
with patch.object(store.subprocess, 'run', side_effect=__import__('subprocess').TimeoutExpired('proton', 1)):
|
||||
self.assertEqual('timeout', store.create_prefix(root + '/compatdata/1', str(proton)))
|
||||
self.assertEqual('no-proton', store.create_prefix(root + '/compatdata/1', root + '/missing'))
|
||||
self.assertEqual('no-proton', store.create_prefix('', str(proton)))
|
||||
|
||||
def test_cloud_off_or_amazon_runs_proton_as_before(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1')
|
||||
|
||||
@@ -5,7 +5,14 @@ service. It does not install the Nexus desktop launcher or x86 Linux Wine.
|
||||
`backend.lock.json` pins Xodus, the Nexus commit, Rust, and the ordered patch
|
||||
checksums. `runtime.lock.json` pins the Nexus Windows runtime release and each
|
||||
extracted PE DLL. `prepare.py` verifies both source revisions and all Nexus patch
|
||||
checksums before applying the two local transport/launch patches.
|
||||
checksums before applying the local transport, launch and library patches.
|
||||
|
||||
`droiddeck-library-subscriptions.patch` queries fresh subscription membership
|
||||
alongside product entitlements using the same Store session, account and market.
|
||||
Android can validate a Game Pass child's parent plan when that plan is absent
|
||||
from the product response. A failed membership query fails the refresh and
|
||||
preserves the previous library. Empty membership results add no plan evidence;
|
||||
valid plans already present in the product response retain their existing checks.
|
||||
|
||||
Build on AArch64 Ubuntu 24.04 with Rust from the lock, a C/C++ compiler, OpenSSL
|
||||
development headers, pkg-config, protoc, CMake, Git, Python 3 and xz:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
--- a/crates/xodus-cli/src/commands/library.rs
|
||||
+++ b/crates/xodus-cli/src/commands/library.rs
|
||||
@@ -96,6 +96,48 @@
|
||||
eprintln!("NEXUS_LIBRARY_DIAGNOSTIC_V1 {stage} {status} {count}");
|
||||
}
|
||||
|
||||
+const SUBSCRIPTION_PLANS: &[&str] = &[
|
||||
+ "CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B",
|
||||
+ "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD",
|
||||
+];
|
||||
+
|
||||
+fn subscription_rows(body: &Value) -> Result<Vec<Value>, &'static str> {
|
||||
+ let rows = body["entitlements"].as_object().ok_or("subscriptions-shape")?;
|
||||
+ if rows.len() > SUBSCRIPTION_PLANS.len() { return Err("subscriptions-count"); }
|
||||
+ let mut plans = Vec::new();
|
||||
+ for (id, row) in rows {
|
||||
+ if !SUBSCRIPTION_PLANS.contains(&id.as_str()) { return Err("subscriptions-product"); }
|
||||
+ let status = row["status"].as_str().ok_or("subscriptions-status")?;
|
||||
+ if status != "Active" { continue; }
|
||||
+ let expiry = row["endDate"].as_str().filter(|s| s.len() < 50)
|
||||
+ .filter(|s| chrono::DateTime::parse_from_rfc3339(s).is_ok()).ok_or("subscriptions-expiry")?;
|
||||
+ plans.push(json!({"productId":id,"status":status,"endDate":expiry}));
|
||||
+ }
|
||||
+ Ok(plans)
|
||||
+}
|
||||
+
|
||||
+async fn subscriptions(client: &reqwest::Client, ticket: &str, market: &str) -> Result<Vec<Value>, &'static str> {
|
||||
+ let url = format!("https://beige.xboxservices.com/PCGAFD/entitlements/subscriptions?market={market}&language=en-US&appVersion=0.2.3");
|
||||
+ let cv = format!("{}.0", STANDARD_NO_PAD.encode(uuid::Uuid::new_v4().as_bytes()));
|
||||
+ let mut response = client.post(url)
|
||||
+ .header("Authorization", ticket).header("X-MS-API-Version", "1.1")
|
||||
+ .header("Calling-App-Name", "Xodus-Nexus").header("MS-CV", cv)
|
||||
+ .json(&json!({"productIds":SUBSCRIPTION_PLANS}))
|
||||
+ .send().await.map_err(|_| "subscriptions-request")?;
|
||||
+ if !response.status().is_success() {
|
||||
+ diagnostic("subscriptions-http", response.status().as_u16(), 0);
|
||||
+ return Err("subscriptions-http");
|
||||
+ }
|
||||
+ if response.content_length().is_some_and(|n| n > 262_144) { return Err("subscriptions-size"); }
|
||||
+ let mut bytes = Vec::new();
|
||||
+ while let Some(chunk) = response.chunk().await.map_err(|_| "subscriptions-read")? {
|
||||
+ if bytes.len() + chunk.len() > 262_144 { return Err("subscriptions-size"); }
|
||||
+ bytes.extend_from_slice(&chunk);
|
||||
+ }
|
||||
+ let body: Value = serde_json::from_slice(&bytes).map_err(|_| "subscriptions-json")?;
|
||||
+ subscription_rows(&body)
|
||||
+}
|
||||
+
|
||||
async fn query(tokens: &TokenManager, market: &str) -> Result<Value, &'static str> {
|
||||
if market.len() != 2 || !market.bytes().all(|b| b.is_ascii_uppercase()) {
|
||||
return Err("market");
|
||||
@@ -155,6 +197,7 @@
|
||||
let page: Value = serde_json::from_slice(&bytes).map_err(|_| "entitlements-json")?;
|
||||
all.add(&page)?;
|
||||
if continuation.is_none() {
|
||||
+ let subscriptions = subscriptions(&client, &ticket, market).await?;
|
||||
if tokens.get_user().map_err(|_| "account-check")?.username != account {
|
||||
return Err("account-changed");
|
||||
}
|
||||
@@ -162,7 +205,7 @@
|
||||
for (reason, count) in &all.reasons { diagnostic(reason, 0, *count); }
|
||||
diagnostic(if all.skipped > 0 { "partial" } else { "complete" }, 0, all.skipped);
|
||||
return Ok(json!({"schema":1,"account":account,"market":market,
|
||||
- "checkedAt":chrono::Utc::now().to_rfc3339(),"skippedEntitlements":all.skipped,
|
||||
+ "checkedAt":chrono::Utc::now().to_rfc3339(),"skippedEntitlements":all.skipped,"subscriptions":subscriptions,
|
||||
"entitlements":all.entries.into_values().collect::<Vec<_>>()}));
|
||||
}
|
||||
}
|
||||
@@ -200,6 +243,26 @@
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
+ #[test]
|
||||
+ fn subscription_membership_is_separate_from_product_entitlements() {
|
||||
+ let body = json!({"entitlements":{"CFQ7TTC0KGQ8":{
|
||||
+ "status":"Active","endDate":"2099-01-01T00:00:00Z","autoRenew":true,"private":"not-output"}}});
|
||||
+ assert_eq!(subscription_rows(&body).unwrap(), vec![json!({"productId":"CFQ7TTC0KGQ8",
|
||||
+ "status":"Active","endDate":"2099-01-01T00:00:00Z"})]);
|
||||
+ assert!(subscription_rows(&json!({"entitlements":{}})).unwrap().is_empty());
|
||||
+ assert!(subscription_rows(&json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":"Expired"}}})).unwrap().is_empty());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn malformed_membership_is_an_error_not_an_empty_subscription_list() {
|
||||
+ for body in [json!({}), json!({"entitlements":[]}),
|
||||
+ json!({"entitlements":{"unknown":{"status":"Active"}}}),
|
||||
+ json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":true}}}),
|
||||
+ json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":"Active","endDate":"invalid"}}})] {
|
||||
+ assert!(subscription_rows(&body).is_err());
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
const A: &str = "9AAAAAAAAAAA";
|
||||
const B: &str = "9BBBBBBBBBBB";
|
||||
const C: &str = "9CCCCCCCCCCC";
|
||||
@@ -9,7 +9,8 @@ import sys
|
||||
recipe = Path(__file__).resolve().parent
|
||||
cache = Path(sys.argv[1]).resolve()
|
||||
lock = json.loads((recipe / 'backend.lock.json').read_text())
|
||||
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + (recipe / 'droiddeck-credentials.patch').read_bytes() + (recipe / 'droiddeck-launch-view.patch').read_bytes()).hexdigest()
|
||||
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch']
|
||||
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest()
|
||||
source = cache / ('source-' + identity[:16])
|
||||
if not (source / '.prepared').is_file():
|
||||
if source.exists():
|
||||
@@ -29,8 +30,8 @@ if not (source / '.prepared').is_file():
|
||||
file = nexus / 'assets' / patch['file']
|
||||
assert hashlib.sha256(file.read_bytes()).hexdigest() == patch['sha256']
|
||||
subprocess.run(['git', '-C', str(source), 'apply', str(file)], check=True)
|
||||
subprocess.run(['git', '-C', str(source), 'apply', str(recipe / 'droiddeck-credentials.patch')], check=True)
|
||||
subprocess.run(['git', '-C', str(source), 'apply', str(recipe / 'droiddeck-launch-view.patch')], check=True)
|
||||
for name in local_patches:
|
||||
subprocess.run(['git', '-C', str(source), 'apply', str(recipe / name)], check=True)
|
||||
(source / '.prepared').write_text(identity + '\n')
|
||||
assert (source / '.prepared').read_text().strip() == identity
|
||||
print(source)
|
||||
Reference in new issue
Block a user