Merge remote-tracking branch 'origin/main' into fix/dotnet48-mono-gac

# Conflicts:
#	README.md
This commit is contained in:
maxjivi05 committed 2026-11-17 11:17:02 -05:00
commit 8217cb2513
654 files changed
+62296 -6256

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
# DroidDeck on-device agent
You run in DroidDeck's Agent tab, on the user's handheld, in DroidDeck's Linux userland (Ubuntu
under proot, aarch64). The user is often on a small screen: keep replies short. These notes come
from what tripped agents up on real devices.
## Where you run
- Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program
you start here is not in it and has no screen. Reach it with `droiddeckctl` (guide:
`/root/.local/share/droiddeck/ctl/agent-control.md`): `state`, `start steam`, `stop`, `launch`,
`quit`, `focus`, `screenshot`, `logs`, `pacing`, `thermal`, and `guest` to run a command in it.
- `droiddeckctl stop`, `start steam` and `resume` end or restart only the session. You keep
running, so restart it yourself when a change needs a new session.
- The session shares your filesystem. Steam is in `/root/.local/share/Steam` (its logs in
`logs/`), and the session's live logs are in the folder `state` gives as `session.logDir`.
`logs latest` makes a redacted, partial copy: read the live folder yourself. X properties,
gamescope and the session's processes are only reachable through `guest`.
## Commands
- `guest` runs one program, not a shell line: `droiddeckctl guest -- sh -c '...'` for pipes,
`$(...)` or `DISPLAY=:0 xprop ...`. Its answer is JSON; the output is in `stdout.text`.
- `screenshot` takes the path as an argument (`screenshot /tmp/top.png --display 0`); on a
dual-screen device see `droiddeckctl displays`. `prefs get` takes a file (`prefs get session`).
- `input` drives a game session that has drawn a frame. For the launcher's own screens use
`adb -s $ADB_SERIAL shell input keyevent KEYCODE_BACK` and similar.
- `droiddeck-scenario` replays a scripted test through `droiddeckctl` (`--help` for the format).
- Never kill by a command-line pattern (`pkill -f`, `pgrep -f` piped to `kill`): your own command
line holds the user's message, so the pattern matches you. End a game with `droiddeckctl quit`,
the session with `droiddeckctl stop`, anything else by its pid after checking what it is
(`ps -o pid,args -p <pid>`): a pid near a game can be the Steam client.
- `DEVICE_RESOLUTION_FAILED`: run `adb devices` and use the serial it lists.
- Do not chain `sleep` before a check. Start long work in the background. In Claude Code, its end
starts you again; other harnesses are not woken, so check it before ending your turn or tell the
user it is still running.
## What applies when
- Many session settings (black frame insertion, environment, Proton) are read when a session or
game starts. After changing one, restart the game or the session before judging it.
- With "Return after game" on (the default), quitting a game DroidDeck launched ends the whole
session; `start steam --wait --reuse` before the next launch. Launching a game that is already
running makes Steam show "Game already running" and `launch` time out.
- Session scripts are APK assets, copied into the rootfs at every session start over any local
edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only:
session scripts, native code and assets need a new APK, such as the pull request's CI test build
(DroidDeck > Updates > Test builds).
## Changing DroidDeck
The source is checked out at `/root/DroidDeck` once the Agent tab's build tools are set up.
- It often holds the user's uncommitted work and a stale local `main`. Branch from `origin/main`
in a worktree (`git worktree add -b <branch> ../<dir> origin/main`).
- `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the
build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in
the background and keep checking, so the user can talk to you meanwhile. The restart ends your
process, and the conversation continues on the new build.
- Python tests run from the repository root: `python3 -m unittest tools.tests.test_x`. Some fail on
the device on `origin/main` too; run them on a worktree of `origin/main` before blaming a change.
- Gradle unit tests rarely run on the device. Leave them to CI and say so rather than retrying.
- If `git push` asks for credentials, run `gh auth setup-git` once.
- Commits and pull requests you make are the user's own: no co-author line, AI credit or
generated-by note.
## This file
DroidDeck writes this block into your global instructions (`~/.claude/CLAUDE.md`,
`~/.codex/AGENTS.md`) before every turn, and its skills into `~/.claude/skills` and
`~/.codex/skills`. It replaces only its own block and its own skills (folders holding a `.droiddeck` file): the
user's rules go outside the block, and their skills stay, even one with the same name. Deleting a
skill's `.droiddeck` file keeps local edits to it. To change DroidDeck's, edit `tools/agent/AGENTS.md` and
`tools/agent/skills` in the source.
+45 -17
View File
@@ -1,24 +1,52 @@
#!/bin/bash
# GitHub sign-in through Android's browser on the bottom screen, with the one-time code typed in.
serial=${ADB_SERIAL:-127.0.0.1:5555}
adb connect "$serial" >/dev/null 2>&1
# Starts GitHub's device login, floats its code over Android's browser and opens the approval page.
url=https://github.com/login/device
inbox=${DD_AGENT_INBOX:-}
# DroidDeck takes $inbox/device-code within a few seconds when it can float the code.
float_code() {
[ -n "$inbox" ] && [ -d "$inbox" ] || return 1
rm -f "$inbox/device-code.result"
printf '%s %s\n' "$1" "$url" > "$inbox/device-code.part" && mv -f "$inbox/device-code.part" "$inbox/device-code" || return 1
i=0
while [ $i -lt 40 ] && [ -e "$inbox/device-code" ]; do
sleep 0.2
i=$((i + 1))
done
if [ -e "$inbox/device-code" ]; then
rm -f "$inbox/device-code"
return 1
fi
# DroidDeck writes "ok" or "failed" once it has tried to open the page; no answer counts as failed.
i=0
while [ $i -lt 50 ] && [ ! -e "$inbox/device-code.result" ]; do
sleep 0.2
i=$((i + 1))
done
result=$(cat "$inbox/device-code.result" 2>/dev/null)
rm -f "$inbox/device-code.result"
[ "$result" = ok ]
}
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
gh_pid=$GH_PID
typed=
while IFS= read -r line <&"${GH[0]}"; do
printf '%s\n' "$line"
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
shown=
while IFS= read -r line <&"$ghout"; do
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
if [ -n "$code" ] && [ -z "$typed" ]; then
typed=1
echo >&"${GH[1]}"
adb -s "$serial" shell "am start --display 2 -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1
# Chrome drops characters from `input text` and from fast key events on this page.
keys=
for ((i = 0; i < ${#code}; i++)); do
c=${code:i:1}
[ "$c" = - ] || keys+="input -d 2 keyevent KEYCODE_$c; sleep 0.4; "
done
(sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) &
# gh's own prompts would push the code out of the one line the setup card shows.
case "$line" in
*"one-time code"* | *"Press Enter"* | *"Open this URL"*) ;;
*) printf '%s\n' "$line" ;;
esac
if [ -n "$code" ] && [ -z "$shown" ]; then
shown=1
echo >&"$ghin"
printf 'GitHub device code: %s · github.com/login/device\n' "$code"
float_code "$code" || android-open "$url"
fi
done
wait "$gh_pid"
status=$?
[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
exit $status
+32 -11
View File
@@ -5,15 +5,23 @@
# compile what changed. Setup runs it once; it takes the longest.
# --explain logs why each task ran and Kotlin's build report, to find out what makes a build slow.
set -euo pipefail
pkg=com.droiddeck.launcher
pkg=${DROIDDECK_PACKAGE:-}
if [ -z "$pkg" ] && [[ ${DD_AGENT_INBOX:-} =~ ^/data/(user/[0-9]+|data)/([^/]+)/files/agent$ ]]; then
pkg=${BASH_REMATCH[2]}
fi
pkg=${pkg:-com.droiddeck.launcher}
serial=${ADB_SERIAL:-127.0.0.1:5555}
mode=build
explain=()
for arg in "$@"; do
case $arg in
--package=*) pkg=${arg#--package=} ;;
--no-restart) mode=no-restart ;;
--prepare) mode=prepare ;;
--explain) explain=(--info -Pkotlin.build.report.output=file) ;;
# Anything else used to start a full build and restart the app, --help included.
-h|--help) sed -n '2,6s/^# \{0,1\}//p' "$0"; exit 0 ;;
*) echo "dd-lab-build: unknown option $arg (see --help)" >&2; exit 2 ;;
esac
done
started=$(date +%s)
@@ -31,16 +39,18 @@ progress() { # stage [permille task done total eta]
fail() { progress failed 0 "$*"; echo "dd-lab-build: $*" >&2; exit 1; }
trap 'progress failed 0 stopped; exit 143' INT TERM
trap 'progress failed 0 "a command failed on line $LINENO"' ERR
[[ $pkg =~ ^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$ ]] || fail "invalid Android package: $pkg"
export DROIDDECK_PACKAGE=$pkg
device() { adb -s "$serial" shell "$@" | tr -d '\r'; }
# The app's agent loses every process it started when its turn ends, a build included, so it asks
# the app to run the build in a process of its own and follows that build here.
agent=/data/user/0/$pkg/files/agent
agent=${DD_AGENT_INBOX:-/data/user/0/$pkg/files/agent}
if [ -n "${DD_AGENT:-}" ] && [ -z "${DD_LAB_DETACHED:-}" ] && [ -d "$agent" ]; then
trap - ERR
log=$cache/dd-lab-build.log
rm -f "$progress_file"
python3 -c 'import json,os,sys; print(json.dumps({"cwd": os.getcwd(), "args": sys.argv[1:]}))' "$@" > "$agent/lab-request.part"
python3 -c 'import json,os,sys; print(json.dumps({"cwd": os.getcwd(), "args": [*sys.argv[1:], "--package=" + os.environ["DROIDDECK_PACKAGE"]]}))' "$@" > "$agent/lab-request.part"
mv "$agent/lab-request.part" "$agent/lab-request"
echo "DroidDeck runs this build itself, so it keeps going if this turn ends. Its log follows."
for _ in $(seq 1 30); do [ -f "$progress_file" ] && break; sleep 1; done
@@ -102,15 +112,14 @@ export DROIDDECK_SOURCE_COMMIT=$base DROIDDECK_BUILD_LABEL="lab on $installed_la
printf 'sdk.dir=%s\n' "$ANDROID_HOME" > local.properties
if [ ! -d "$ANDROID_HOME/platforms/android-34" ]; then
progress sdk
yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null
(set +o pipefail; yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null)
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null
fi
# A full Kotlin compile of the app needs about 2.5 GB of heap and Gradle about 1 GB; smaller devices get
# what they can spare. Both daemons end with this script's process when the build is done.
total_mb=$(awk '/^MemTotal:/ {print int($2 / 1024)}' /proc/meminfo)
heap=$(( total_mb / 2 )); [ $heap -gt 4096 ] && heap=4096; [ $heap -lt 2048 ] && heap=2048
heap=${DD_LAB_HEAP_MB:-$heap}
# A full Kotlin compile of the app runs out of memory with 2.4 GB of heap, and Gradle needs about 1 GB,
# so devices with less memory to spare swap rather than fail. Both daemons end with this script's
# process when the build is done.
heap=${DD_LAB_HEAP_MB:-4096}
kotlin_heap=$(( heap * 2 / 3 )); gradle_heap=$(( heap - kotlin_heap ))
# Only the Kotlin daemon compiles incrementally; in-process compiles always redo the whole app, and the
@@ -125,7 +134,19 @@ gradle=(./gradlew :app:processReleaseResources :app:mergeDexRelease --max-worker
-Pandroid.aapt2FromMavenOverride=$HOME/aapt2/aapt2 -Pkotlin.compiler.execution.strategy=daemon
-Pkotlin.daemon.jvmargs=-Xmx${kotlin_heap}m -Dorg.gradle.jvmargs=-Xmx${gradle_heap}m --console=plain)
progress planning
mapfile -t plan < <("${gradle[@]}" --dry-run -q 2>/dev/null | awk '/^:/ {print $1}' || true)
plan_file=$cache/dd-lab-build-plan
plan_key=$(
{
printf '%s\n' "$repo" "${gradle[@]}"
git ls-files -z -- '*gradle*' | xargs -0 -r sha256sum
} | sha256sum | cut -d ' ' -f1
)
if [ "$(head -n 1 "$plan_file" 2>/dev/null)" != "$plan_key" ]; then
plan_output=$("${gradle[@]}" --dry-run) || fail "Gradle planning failed: $plan_output"
{ printf '%s\n' "$plan_key"; awk '/^:/ {print $1}' <<<"$plan_output"; } > "$plan_file.part"
mv "$plan_file.part" "$plan_file"
fi
mapfile -t plan < <(tail -n +2 "$plan_file")
total=${#plan[@]}
# Each task's estimate is how long it took last time; a full compile of the app takes about 15 minutes.
@@ -221,6 +242,6 @@ device cmd package compile -m verify -f $pkg >/dev/null
progress restarting 1000 "$name"
echo "Restarting DroidDeck on the Lab build; it shows a notification when it is back"
# The app's own agent ends with the app, so it is told to carry on once the app is back.
if [ -n "${DD_AGENT:-}" ]; then mkdir -p "/data/user/0/$pkg/files/agent" && : > "/data/user/0/$pkg/files/agent/resume"; fi
if [ -n "${DD_AGENT:-}" ]; then mkdir -p "$agent" && : > "$agent/resume"; fi
device "nohup sh -c 'sleep 3; monkey -p $pkg -c android.intent.category.LAUNCHER 1' >/dev/null 2>&1 &"
for pid in $(device pidof $pkg); do kill "$pid" 2>/dev/null || true; done
+4 -2
View File
@@ -16,8 +16,10 @@ command -v claude >/dev/null || [ -x "$HOME/.local/bin/claude" ] ||
mkdir -p "$HOME/.local/bin"
for tool in dd-agent dd-lab-build dd-gh-login android-open; do install -m755 "$here/$tool" "$HOME/.local/bin/$tool"; done
# DroidDeck passes the live loopback adb port; a fixed one here would go stale whenever wireless debugging is toggled.
sed -i 's|ADB_SERIAL=127.0.0.1:5555 |ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" |' "$HOME/.bashrc" 2>/dev/null || true
grep -q 'droiddeck-agent-path' "$HOME/.bashrc" 2>/dev/null ||
printf '\n# droiddeck-agent-path\nexport PATH="$HOME/.local/bin:$PATH" ADB_SERIAL=127.0.0.1:5555 BROWSER="$HOME/.local/bin/android-open"\n' >> "$HOME/.bashrc"
printf '\n# droiddeck-agent-path\nexport PATH="$HOME/.local/bin:$PATH" ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" BROWSER="$HOME/.local/bin/android-open"\n' >> "$HOME/.bashrc"
# Google publishes aapt2 for x86-64 Linux only; it runs here under qemu-user with Ubuntu's x86-64 runtime.
x86=$HOME/x86root
@@ -61,7 +63,7 @@ if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then
mv "$sdk/cmdline-tools/cmdline-tools" "$sdk/cmdline-tools/latest"
fi
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64
yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null
(set +o pipefail; yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null)
"$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null
adb connect 127.0.0.1:5555 || true
+41
View File
@@ -0,0 +1,41 @@
---
name: diagnose-game
description: Find why a game crashed, hung or ran badly in DroidDeck, from session state and logs
---
1. `droiddeckctl state`: `session.phase`, `session.failure`, `session.focus.focusedApp` (769 is
Steam's own UI) and `session.logDir`.
2. Read that log folder directly; it is on your filesystem. Earlier sessions are its siblings:
`ls -t "$(dirname <logDir>)"`; the crash may be in the one before a restart. `logs latest`
makes a redacted, partial copy with renamed files: use it only to hand logs to someone.
- `games/<time>-<id>-<appid>/`, one folder per launch: `launch.txt` (exe, Proton, environment)
and `steam-<appid>.log` (Proton and Wine).
- `session.log` (the session script, `== ` lines), `wayland.log` (compositor), `app.log`,
`events.jsonl`, `crash.log` (Android's crash buffer at session end), `memory-pressure.log`
(low-memory kills), `graphics-report.txt`, `vulkan-summary.txt`, `steam/` (client logs).
- The game's own log is in its prefix,
`/root/.local/share/Steam/steamapps/compatdata/<appid>/pfx/drive_c/users/steamuser/`:
Unity writes `AppData/LocalLow/<company>/<game>/Player.log`, Unreal
`AppData/Local/<game>/Saved/Logs/`.
3. Find the fatal error, not the first `err:`. Every run logs harmless ones (`err:nsi` bind
errno 13, `err:hid`, `winebth`, `tabtip`, `overriding CPU configuration`), and `trace:seh`
first-chance exceptions are often handled. Look for the last exception before the process ends:
`grep -nE "EXCEPTION_ACCESS_VIOLATION|Unhandled exception|virtual_setup_exception|DEVICE_LOST|VK_ERROR" steam-<appid>.log`.
Same address in every launch means a deterministic fault; compare with an older launch that
worked before blaming a line.
4. For performance, `droiddeckctl pacing --seconds 20` (`fpsOnScreen`, `offCadencePercent`) and
`droiddeckctl thermal`: at `SEVERE` or worse the device is throttling, so say that first.
5. Explain the cause in plain words with the lines that show it (file and line number). Propose
the smallest reversible change and ask before applying it:
- Proton for one game: list `/root/.local/share/Steam/compatibilitytools.d` and
`steamapps/common/Proton*`, then
`droiddeckctl cdp eval 'SteamClient.Apps.SpecifyCompatTool(<appid>, "<tool dir name>")'`;
check `CompatToolMapping` in `config/config.vdf`.
- Launch options for one game: read them first,
`droiddeckctl cdp eval 'appDetailsStore.GetAppDetails(<appid>)?.strLaunchOptions'`, keep
them, then `SteamClient.Apps.SetAppLaunchOptions(<appid>, "VAR=1 %command%")`.
- For every game: `droiddeckctl env set KEY=VALUE` applies to the next session only
(`--persistent` keeps it); restart the session with `droiddeckctl stop` and `start steam`.
6. Relaunch and read the new launch folder before saying it is fixed. If Steam stays on
"Stopping", `droiddeckctl quit <appid>`, then look for leftover Wine processes with
`droiddeckctl guest -- sh -c 'ps -eo pid,args | grep -i wine'`; never kill the Steam client.
@@ -0,0 +1,41 @@
---
name: reproduce-with-input
description: Reproduce a reported game problem by launching the game and driving controller input
---
1. `droiddeckctl state` first. If the game already has focus, do not launch it again: Steam shows
"Game already running" and `launch` times out. With no session, `droiddeckctl start steam --wait`.
Then `droiddeckctl launch <appid> --wait` and `droiddeckctl wait focused <appid> --timeout 180`.
Check `droiddeckctl thermal` too: at `SEVERE` or worse, performance results mean little.
2. Look before acting: `droiddeckctl screenshot ./shot.png --display 0`, then read the image. On the
Retroid Pocket Duo the top screen is display 0 and the bottom is 2 (`droiddeckctl displays`).
A game shows black or loading frames for a while after it takes focus; take another shot a few
seconds later before calling it a black screen.
3. Drive it with `droiddeckctl input`: `pad a` (also `b x y lb rb start select l3 r3 guide qam`
and the D-pad `up down left right`; `--hold` in ms), `stick left 0 -1 --hold 800`,
`trigger right 1.0`, `key ENTER`, `text 'hello'`. Input goes to the game window that has
focus once the session has drawn a frame. The launcher's own screens need
`adb -s $ADB_SERIAL shell input keyevent ...` instead. Take a screenshot after each step that
should change the screen.
4. Measure: `droiddeckctl pacing --seconds 20` (`fpsOnScreen`, `offCadencePercent`). For flicker
or stutter a still cannot show, `droiddeckctl record ./clip.mp4 --seconds 8 --display 0`.
5. Make it replayable: write the steps as a scenario and run it with `droiddeck-scenario`
(installed beside `droiddeckctl`); `--help` documents the format. Give screenshot steps a display:
```json
{"name": "nfs-menu", "vars": {"appId": 47870}, "repeat": 1,
"before": [["start", "steam", "--wait", "--reuse", "--timeout", "240"]],
"steps": [["launch", "${appId}", "--wait"],
["wait", "focused", "${appId}", "--timeout", "180"],
{"sleep": 20}, ["input", "pad", "a"], {"sleep": 3},
{"screenshot": "after-a", "display": 0},
["pacing", "--seconds", "10"], {"assert": "fpsOnScreen", "exists": true}],
"after": [["quit", "${appId}"]]}
```
`droiddeck-scenario nfs-menu.json --out ./runs` writes `report.json` and, for a failed
run, a screenshot, focus and logs.
6. Report the steps that reproduce it and what you saw at each. Quit the game with
`droiddeckctl quit <appid>` unless the user is playing it. With "Return after game" on (the
default), quitting a game DroidDeck launched also ends the session, so `start steam` again
before the next launch.
+7
View File
@@ -433,6 +433,13 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
CARGO_TARGET_DIR="${cache_dir}/ubisoft-target" bash tools/ubisoft-launcher/build.sh "${upc_out}"
save_step ubisoft "${upc_key}" "${upc_out}"
fi
rockstar_out="${linuxfs_dir}/usr/local/lib/droiddeck-rockstar"
rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh)
if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then
command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}"
save_step rockstar "${rockstar_key}" "${rockstar_out}"
fi
fi
python3 tools/powervr/fetch.py
bash tools/packs/build.sh app/build/packs
@@ -65,6 +65,7 @@ PA_MODULE_USAGE(
#define DA_RING_CAP_MS_LOCAL 250
#define DA_FREEZE_GAP_NS 500000000ull
#define DA_CB_STALL_NS 1000000000ull
#define DA_HOST_RESTART_STALLS 3
#define DA_DECAY_QUIET_NS 10000000000ull
#define DA_DECAY_PUNISH_NS 5000000000ull
#define DA_DECAY_MAX_BACKOFF 32
@@ -106,6 +107,7 @@ struct userdata {
uint64_t last_cb_ns, last_xrun_ns, last_decay_ns, wd_last_tick_ns;
int32_t base_buf_frames, decay_floor;
unsigned int decay_backoff, cb_count, wd_last_cb;
uint64_t stall_state;
int reopen_running, reopen_redo;
int consuming, primed, starved;
int suspended;
@@ -154,6 +156,13 @@ static void limit(float *p, uint32_t samples) {
}
}
static void record_callback(struct userdata *u) {
uint64_t state = __atomic_load_n(&u->stall_state, __ATOMIC_SEQ_CST);
while (!__atomic_compare_exchange_n(&u->stall_state, &state,
((state >> 32) + 1) << 32, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {}
}
static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *audioData, int32_t numFrames) {
struct userdata *u = user;
struct da_ring *r = u->ring;
@@ -170,6 +179,8 @@ static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *
return AAUDIO_CALLBACK_RESULT_CONTINUE;
}
record_callback(u);
ridx = __atomic_load_n(&r->ridx, __ATOMIC_ACQUIRE);
avail = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE) - ridx;
if (!u->primed) {
@@ -412,10 +423,12 @@ static void request_reopen(struct userdata *u, const char *why) {
static void watchdog(struct userdata *u) {
uint64_t now = now_ns(), last_cb, prev_tick;
unsigned int cb;
uint64_t stalled;
if (!u->watchdog_on) return;
if (!__atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return;
stalled = __atomic_load_n(&u->stall_state, __ATOMIC_SEQ_CST);
prev_tick = u->wd_last_tick_ns;
u->wd_last_tick_ns = now;
cb = __atomic_load_n(&u->cb_count, __ATOMIC_SEQ_CST);
@@ -431,6 +444,13 @@ static void watchdog(struct userdata *u) {
if (!last_cb || now - last_cb < DA_CB_STALL_NS) return;
__atomic_store_n(&u->last_cb_ns, now, __ATOMIC_SEQ_CST);
if (__atomic_load_n(&u->cb_count, __ATOMIC_SEQ_CST) != cb) return;
if (!__atomic_compare_exchange_n(&u->stall_state, &stalled, stalled + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) return;
if ((uint32_t) (stalled + 1) >= DA_HOST_RESTART_STALLS) {
pa_log("directaudio-native-sink: no data callback after %u stream recoveries; restarting the audio host", (unsigned int) (stalled + 1));
_exit(EXIT_FAILURE);
return;
}
request_reopen(u, "data callback stalled");
}
+233 -5
View File
@@ -67,10 +67,11 @@ def adb_path(configured: str | None) -> str:
raise ControlError("adb not found; set ADB, ANDROID_HOME, or ANDROID_SDK_ROOT", "ADB_NOT_FOUND")
def run_adb(adb: str, serial: str, *args: str, timeout: float = 30) -> subprocess.CompletedProcess[bytes]:
def run_adb(adb: str, serial: str, *args: str, timeout: float = 30,
stdin: bytes | None = None) -> subprocess.CompletedProcess[bytes]:
try:
return subprocess.run(
[adb, "-s", serial, *args], capture_output=True, check=False, timeout=timeout
[adb, "-s", serial, *args], input=stdin, capture_output=True, check=False, timeout=timeout
)
except (OSError, subprocess.TimeoutExpired) as exc:
raise ControlError(str(exc), "ADB_FAILED") from exc
@@ -287,7 +288,9 @@ def displays(adb: str, serial: str) -> list[dict]:
def physical_display(adb: str, serial: str, logical: int | None) -> str | None:
if logical is None:
return None
found = displays(adb, serial)
main = next((d["physicalId"] for d in found if d["display"] == 0), None)
return main if len(found) > 1 else None
for d in displays(adb, serial):
if d["display"] == logical:
if not d["physicalId"]:
@@ -571,7 +574,7 @@ def unpack_logs(archive: Path, destination: Path, session_id: str) -> None:
def require_commands(adb: str, serial: str) -> dict:
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
if access.get("commands") is not True:
raise ControlError("Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
raise ControlError("Debugging tools are off: turn on Setup > Developer > Debugging tools on the device",
"AGENT_COMMANDS_DISABLED")
return access
@@ -596,6 +599,199 @@ def input_request(args: argparse.Namespace) -> dict:
raise ControlError(f"Unknown input type {kind}", "INVALID_INPUT")
PEN_MAX_MS = 30_000
UINPUT_SCALE = 16
UINPUT_PRESSURE = 4095
UINPUT_DISTANCE = 255
UINPUT_REGISTER_MS = 1000
UINPUT_TAIL_MS = 300
UINPUT_SYNC = "droiddeckctl-pen-done"
def pen_span(value: str) -> tuple[float, float]:
try:
low, high = map(float, value.split(":")) if ":" in value else (float(value),) * 2
except ValueError:
raise argparse.ArgumentTypeError(f"{value!r} is not a number or FROM:TO") from None
return low, high
def pen_times(start: float, duration: float, rate: float) -> list[float]:
steps = max(1, round(duration * rate / 1000))
return [start + duration * i / steps for i in range(steps + 1)]
def pen_lerp(span: tuple[float, float], fraction: float) -> float:
return span[0] + (span[1] - span[0]) * fraction
def pen_samples(args: argparse.Namespace) -> list[dict]:
op = args.pen_op
contact = op in ("tap", "stroke")
side = args.button if op == "button" else None
lead = 0 if op == "hover" else args.hover_ms
length = args.duration if op in ("hover", "stroke") else args.hold
total = 2 * lead + length
start = end = (args.x, args.y)
if op == "stroke":
end = (args.x2, args.y2)
elif op == "hover" and args.to:
end = tuple(args.to)
for name in ("duration", "hold", "hover_ms"):
if getattr(args, name, 0) < 0:
raise ControlError(f"--{name.replace('_', '-')} must not be negative", "INVALID_INPUT")
if not 1 <= args.rate <= 1000:
raise ControlError("--rate must be 1..1000 Hz", "INVALID_INPUT")
if total > PEN_MAX_MS:
raise ControlError(f"The gesture lasts {total} ms, more than {PEN_MAX_MS}", "INVALID_INPUT")
if not all(0 <= v <= 1 for v in start + end):
raise ControlError("Positions are fractions of the screen, 0..1", "INVALID_INPUT")
if contact and not all(0 <= p <= 1 for p in args.pressure):
raise ControlError("--pressure must be 0..1", "INVALID_INPUT")
if not all(-90 <= a <= 90 for a in args.tilt_x + args.tilt_y):
raise ControlError("--tilt-x and --tilt-y must be -90..90", "INVALID_INPUT")
if not 0 <= args.distance <= UINPUT_DISTANCE:
raise ControlError(f"--distance must be 0..{UINPUT_DISTANCE}", "INVALID_INPUT")
samples = []
def add(t: float, phase: str, x: float, y: float, pressure: float = 0.0, button: str | None = None) -> None:
progress = t / (total or 1)
samples.append({"t": round(t), "phase": phase, "x": x, "y": y, "pressure": pressure, "button": button,
"distance": args.distance, "tilt_x": pen_lerp(args.tilt_x, progress),
"tilt_y": pen_lerp(args.tilt_y, progress)})
if lead:
for t in pen_times(0, lead, args.rate)[:-1]:
add(t, "hover", *start)
middle = pen_times(lead, length, args.rate)
steps = len(middle) - 1
for i, t in enumerate(middle):
f = i / steps
x, y = pen_lerp((start[0], end[0]), f), pen_lerp((start[1], end[1]), f)
if contact:
add(t, "down" if i == 0 else "up" if i == steps else "move", x, y, pen_lerp(args.pressure, f))
else:
add(t, "hover", x, y, button=None if i == steps else side)
if lead:
for t in pen_times(lead + length, lead, args.rate)[1:]:
add(t, "hover", *end)
add(total, "out", *end)
return samples
def input_viewport(dump: str) -> dict:
blocks = re.findall(r"^[ \t]*Viewports:\n((?:[ \t]+Viewport .*\n?)+)", dump, re.M)
viewports = []
for line in re.findall(r"Viewport INTERNAL: (.*)", blocks[-1] if blocks else dump):
fields = dict(re.findall(r"(\w+)=(\[[^\]]*\]|[^,\s]+)", line))
size = re.fullmatch(r"\[(\d+), (\d+)\]", fields.get("deviceSize", ""))
frame = re.fullmatch(r"\[(-?\d+), (-?\d+), (-?\d+), (-?\d+)\]", fields.get("physicalFrame", ""))
if size and frame and re.fullmatch(r"-?\d+", fields.get("displayId", "")) and fields.get("orientation") in ("0", "1", "2", "3"):
viewports.append({"display": int(fields["displayId"]), "rotation": int(fields["orientation"]),
"size": [int(size.group(1)), int(size.group(2))],
"frame": [int(edge) for edge in frame.groups()], "active": fields.get("isActive") != "[0]"})
if not viewports:
raise ControlError("`dumpsys input` shows no internal display viewport to map the pen to", "NO_VIEWPORT")
viewport = next((v for v in viewports if v["display"] == 0), viewports[0])
if not viewport["active"]:
raise ControlError(f"Display {viewport['display']} is off, and Android ignores touchscreens on it; "
"wake the device first", "NO_VIEWPORT")
return viewport
def uinput_point(x: float, y: float, tilt_x: float, tilt_y: float, rotation: int, width: int,
height: int, frame: list[int]) -> tuple[int, int, int, int]:
left, top, right, bottom = frame
x = min(right - 1, round(left + x * (right - left)))
y = min(bottom - 1, round(top + y * (bottom - top)))
if rotation == 1:
return width - 1 - y, x, round(-tilt_y), round(tilt_x)
if rotation == 2:
return width - 1 - x, height - 1 - y, round(-tilt_x), round(-tilt_y)
if rotation == 3:
return y, height - 1 - x, round(tilt_y), round(-tilt_x)
return x, y, round(tilt_x), round(tilt_y)
def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict]:
rotation = viewport["rotation"]
natural = viewport["size"][::-1] if rotation % 2 else viewport["size"]
width, height = (n * UINPUT_SCALE for n in natural)
bounds = [edge * UINPUT_SCALE for edge in viewport["frame"]]
last_x = max(uinput_point(f, f, 0, 0, rotation, width, height, bounds)[0] for f in (0, 1))
tool_key = "BTN_TOOL_RUBBER" if tool == "eraser" else "BTN_TOOL_PEN"
def axis(code: str, low: int, high: int) -> dict:
return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}}
commands = [
{"id": 1, "command": "register", "name": "DroidDeck agent pen", "bus": "virtual", "configuration": [
{"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]},
{"type": "UI_SET_KEYBIT", "data": ["BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"]},
{"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_PRESSURE", "ABS_DISTANCE", "ABS_TILT_X", "ABS_TILT_Y"]},
{"type": "UI_SET_PROPBIT", "data": ["INPUT_PROP_DIRECT"]},
], "abs_info": [axis("ABS_X", 0, width - 1), axis("ABS_Y", 0, height - 1), axis("ABS_PRESSURE", 0, UINPUT_PRESSURE),
axis("ABS_DISTANCE", 0, UINPUT_DISTANCE), axis("ABS_TILT_X", -90, 90), axis("ABS_TILT_Y", -90, 90)]},
{"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS},
]
sent = {tool_key: 0, "BTN_TOUCH": 0, "BTN_STYLUS": 0, "BTN_STYLUS2": 0}
def frame(sample: dict, phase: str) -> list:
near, contact = phase != "out", phase in ("down", "move")
values = {tool_key: int(near), "BTN_TOUCH": int(contact), "BTN_STYLUS": int(sample["button"] == "primary"),
"BTN_STYLUS2": int(sample["button"] == "secondary")}
if near:
x, y, tilt_x, tilt_y = uinput_point(sample["x"], sample["y"], sample["tilt_x"], sample["tilt_y"],
rotation, width, height, bounds)
values.update(ABS_X=x, ABS_Y=y, ABS_PRESSURE=max(1, round(sample["pressure"] * UINPUT_PRESSURE)) if contact else 0,
ABS_DISTANCE=0 if contact else sample["distance"], ABS_TILT_X=tilt_x, ABS_TILT_Y=tilt_y)
events = []
for code, value in values.items():
if sent.get(code) != value:
events += ["EV_KEY" if code.startswith("BTN_") else "EV_ABS", code, value]
sent[code] = value
return events + ["EV_SYN", "SYN_REPORT", 0] if events else []
now = 0
for sample in samples:
events = frame(sample, "move") if sample["phase"] == "up" else []
events += frame(sample, sample["phase"])
if not events:
sent["ABS_X"] += 1 if sent["ABS_X"] < last_x else -1
events = ["EV_ABS", "ABS_X", sent["ABS_X"], "EV_SYN", "SYN_REPORT", 0]
if sample["t"] > now:
commands.append({"id": 1, "command": "delay", "duration": sample["t"] - now})
now = sample["t"]
commands.append({"id": 1, "command": "inject", "events": events})
return commands + [{"id": 1, "command": "delay", "duration": UINPUT_TAIL_MS},
{"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}]
def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
probe = run_adb(adb, serial, "shell",
"command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput")
if probe.returncode != 0:
raise ControlError((probe.stdout + probe.stderr).decode(errors="replace").strip() or "adb shell failed", "ADB_FAILED")
missing = probe.stdout.decode(errors="replace").split()
if "no-uinput" in missing:
raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE")
if "no-dev-uinput" in missing:
raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE")
viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace"))
script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport))
started = time.monotonic()
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(),
timeout=(UINPUT_REGISTER_MS + samples[-1]["t"] + UINPUT_TAIL_MS) / 1000 + 30)
elapsed = round((time.monotonic() - started) * 1000)
if UINPUT_SYNC not in result.stdout.decode(errors="replace"):
detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:]
raise ControlError(f"uinput stopped before the end of the gesture (exit {result.returncode})"
+ (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why",
"UINPUT_FAILED")
return {"ok": True, "command": "input", "type": "pen", "samples": len(samples), "ms": elapsed,
"viewport": {key: viewport[key] for key in ("display", "rotation", "size")}}
def xr_ppm_to_png(data: bytes, linear: bool = False) -> bytes:
header = re.match(rb"P6\n([0-9]+) ([0-9]+)\n255\n", data)
if not header:
@@ -824,6 +1020,8 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
"CDP_FAILED"), serial)
if command == "input":
if args.input_type == "pen":
return add_serial(pen_uinput(adb, serial, pen_samples(args), args.tool), serial)
return add_serial(checked(provider_call(adb, serial, "input", request=input_request(args), timeout=60),
"INPUT_FAILED"), serial)
@@ -1095,6 +1293,36 @@ def build_parser() -> argparse.ArgumentParser:
trigger.add_argument("trigger", choices=["left", "right"])
trigger.add_argument("value", type=float, nargs="?", default=1.0)
trigger.add_argument("--hold", type=int, default=200)
pen = kinds.add_parser("pen", help="a virtual pen at fractions of the screen as shown")
pen_ops = pen.add_subparsers(dest="pen_op", required=True)
pen_hover = pen_ops.add_parser("hover", help="come near at X Y, glide to --to X2 Y2 and leave")
pen_hover.add_argument("x", type=float)
pen_hover.add_argument("y", type=float)
pen_hover.add_argument("--to", type=float, nargs=2, metavar=("X2", "Y2"))
pen_hover.add_argument("--duration", type=int, default=300)
pen_tap = pen_ops.add_parser("tap", help="hover, touch down at X Y, lift and leave")
pen_tap.add_argument("x", type=float)
pen_tap.add_argument("y", type=float)
pen_tap.add_argument("--hold", type=int, default=60, help="ms in contact")
pen_stroke = pen_ops.add_parser("stroke", help="hover, draw a line from X Y to X2 Y2 and leave")
for name in ("x", "y", "x2", "y2"):
pen_stroke.add_argument(name, type=float)
pen_stroke.add_argument("--duration", type=int, default=300, help="ms in contact")
pen_button = pen_ops.add_parser("button", help="press and release a side button while hovering at X Y")
pen_button.add_argument("button", choices=["primary", "secondary"])
pen_button.add_argument("x", type=float)
pen_button.add_argument("y", type=float)
pen_button.add_argument("--hold", type=int, default=120, help="ms the button is down")
for op in (pen_tap, pen_stroke):
op.add_argument("--pressure", type=pen_span, default=(0.5, 0.5), metavar="P[:P]")
for op in (pen_tap, pen_stroke, pen_button):
op.add_argument("--hover-ms", type=int, default=80, help="ms of hover before and after")
for op in (pen_hover, pen_tap, pen_stroke, pen_button):
op.add_argument("--tool", choices=["pen", "eraser"], default="pen")
op.add_argument("--tilt-x", type=pen_span, default=(0.0, 0.0), metavar="DEG[:DEG]")
op.add_argument("--tilt-y", type=pen_span, default=(0.0, 0.0), metavar="DEG[:DEG]")
op.add_argument("--distance", type=int, default=0, help="while hovering, in device units 0..255")
op.add_argument("--rate", type=float, default=120, help="samples per second")
ui = commands.add_parser("ui", help="the app's own UI: dump nodes, click or type by test tag")
ui_ops = ui.add_subparsers(dest="ui_op", required=True)
@@ -1197,7 +1425,7 @@ def build_parser() -> argparse.ArgumentParser:
return parser
EXIT_ADB = {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE"}
EXIT_ADB = {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE", "UINPUT_UNAVAILABLE", "NO_VIEWPORT", "UINPUT_FAILED"}
EXIT_SESSION = {
"SESSION_ACTIVE", "NO_ACTIVE_SESSION", "SESSION_NOT_SUSPENDED", "SESSION_FAILED", "GUEST_EXIT",
"GUEST_START_FAILED", "RUNTIME_INSTALL_FAILED", "DESKTOP_INSTALL_FAILED", "ACTIVITY_START_FAILED",
+8
View File
@@ -350,3 +350,11 @@ motion while the seat is locked) with how the X pointer moves. A hinted constrai
after 30 moving frames on which the X pointer follows. Any constraint goes relative once the X pointer moves less than a quarter
of that motion on three frames within half a second, as it does when the game recentres it or clips it to a small rectangle
(PEAK). `tools/tests/test_gamescope_pointer_hold.py` compiles the rule from this patch.
## 0134 wlserver: a touch presses the emulated click button only once
In the Left, Right and Middle touch click modes every finger pressed the button, but a finger lifting releases it once
and clears the held flag. wlroots counts repeated presses of one button and sends the release only when the count
reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the
game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no
earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch.
@@ -0,0 +1,33 @@
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index d932df4..df352b0 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -3343,6 +3343,14 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
bump_input_counter();
}
+static bool touch_click_press( bool *pHeld, int nMode, uint32_t uButton )
+{
+ if ( uButton == 0 || nMode < 0 || nMode >= WLSERVER_BUTTON_COUNT || pHeld[ nMode ] )
+ return false;
+ pHeld[ nMode ] = true;
+ return true;
+}
+
void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamescope::IBackendConnector* connector )
{
assert( wlserver_is_lock_held() );
@@ -3389,12 +3397,10 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
uint32_t button = TouchClickModeToLinuxButton( eMode );
- if ( button != 0 && eMode < WLSERVER_BUTTON_COUNT )
+ if ( touch_click_press( wlserver.button_held, eMode, button ) )
{
wlr_seat_pointer_notify_button( wlserver.wlr.seat, time, button, WL_POINTER_BUTTON_STATE_PRESSED );
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
-
- wlserver.button_held[ eMode ] = true;
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
fi
SESSION=$(syms "$D/libblsession.so")
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle; do
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap mprotect drmPrimeFDToHandle drmCloseBufferHandle; do
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
done
if grep -qx drmIoctl <<<"$SESSION"; then
+6
View File
@@ -125,9 +125,15 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
chmod 755 /run/droiddeck/kwin/kwin_wayland
export PATH=/run/droiddeck/kwin:$PATH
fi
if /usr/local/bin/droiddeck-pipewire start; then
eval "$(/usr/local/bin/droiddeck-pipewire env)"
else
echo "== pipewire: not running; screen capture has no picture"
fi
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
rc=$?
/usr/local/bin/droiddeck-pipewire stop
echo "== droiddeck-desktop: Plasma ended ($rc)"
if [ "$rc" -eq 0 ] && [ -z "${BL_BOTTOM_DESKTOP:-}" ]; then
/usr/local/bin/droiddeck-steam-launch bigpicture
+8
View File
@@ -42,6 +42,14 @@ export BL_DESKTOP_GPU_CHILD=1
export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
export APPIMAGE_EXTRACT_AND_RUN=1
if ! command -v gamescopereaper >/dev/null 2>&1; then
for dir in /usr/games /usr/local/games /usr/bin; do
if [ -x "$dir/gamescopereaper" ]; then
export PATH=${PATH:+$PATH:}$dir
break
fi
done
fi
if [ "$window" = 1 ]; then
export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-}
SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
@@ -5,6 +5,7 @@ import json
import math
import os
import re
import runpy
import shutil
import signal
import subprocess
@@ -16,6 +17,7 @@ import urllib.request
HOME = os.environ.get("HOME") or "/root"
BIN = "/usr/local/bin"
PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run")
GAME_DEBUG = runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "droiddeck-game-debug"))
APP_ID = "2596113170"
INSTALLER_URL = "https://downloader.battle.net/download/getInstallerForGame?os=win&gameProgram=BATTLENET_APP&version=Live"
CLIENT_DIR = ("Program Files (x86)", "Battle.net")
@@ -41,6 +43,9 @@ FEX_WAIT = 120
START_GRACE = 90
POLL = 2
STOP_WAIT = 5
DRIVES = "defghijklmnopqruvwxy"
PRODUCT_DB = ("ProgramData", "Battle.net", "Agent", "product.db")
INSTALL_FOLDER = (1, 3, 1)
CLOSE_GRACE = 15
HANDOFF_WAIT = 120
GAME_SETTLE = 20
@@ -85,6 +90,8 @@ COUNTRY = re.compile(r"[A-Z]{3}")
REGION = re.compile(r"[A-Z]{2}")
REPORT = "BNET"
ETA_LIMIT = 30 * 86400
STALL = 600
MOVING = ("download_current", "download_total", "progress", "playable_progress", "state", "phase", "paused", "error")
DONE_STATE = 1004
REPORTED = ("progress", "playable_progress", "download_rate", "download_remaining", "estimated_time_in_sec", "state",
"playable", "paused", "download_complete", "installed", "error")
@@ -115,6 +122,23 @@ function field(text, name) {
return m ? m[1] : "";
}
function object(text, name) {
var start = new RegExp('"' + name + '"\\s*:\\s*\\{').exec(text);
if (!start) return "";
var from = start.index + start[0].length, depth = 0;
for (var i = from - 1; i < text.length; i++) {
if (text.charAt(i) == "{") depth++;
else if (text.charAt(i) == "}" && --depth == 0) return text.substring(from, i);
}
return "";
}
function job(text) {
if (/"error"\s*:\s*[1-9]/.test(text)) return false;
var bare = text.replace(/"extended_status"\s*:\s*\{[^}]*\}/, "");
return /"state"\s*:\s*\d+/.test(bare) || /"download_current"\s*:/.test(bare);
}
function install() {
// Blizzard's China repository moved to cn.patch.battlenet.com.cn; cn.patch.battle.net only redirects away from it.
var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";
@@ -123,7 +147,7 @@ function install() {
save(".form", form);
if (form.indexOf('"' + lang + '"') < 0) lang = "enUS";
var locale = lang.toLowerCase();
call("POST", "/install/" + uid, '{"account_country":"' + country + '","finalized":true,"game_dir":"' + dir + '","geo_ip_country":"' +
call("POST", "/install/" + uid, '{"account_country":"' + country + '","finalized":true,"game_dir":"' + dir.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '","geo_ip_country":"' +
region + '","language":["' + locale + '"],"selected_asset_locale":"' + locale + '","selected_locale":"' + locale +
'","shortcut":"none","tome_torrent":""}');
watch("/install/" + uid);
@@ -134,10 +158,13 @@ function watch(path) {
for (var i = 0; ; i++) {
var s = call("GET", path);
save(".json", s);
if (/"error"\s*:\s*[1-9]/.test(s)) break;
if (/"form"\s*:\s*\{/.test(s)) {
var refused = /"error"\s*:\s*(\d+)/.exec(object(s, "game_dir"));
if (refused && +refused[1] != 0) throw new Error(+refused[1] == 800 ? "the game folder already holds a game" : "Battle.net refused the game folder (error " + refused[1] + ")");
} else if (/"error"\s*:\s*[1-9]/.test(s)) break;
var state = /"state"\s*:\s*(\d+)/.exec(s.replace(/"extended_status"\s*:\s*\{[^}]*\}/, "")), complete = /"download_complete"\s*:\s*true/.test(s);
state = state ? +state[1] : 0;
if (state == 1000 || state == 1003 || !complete) started = true;
if (state == 1000 || state == 1003 || job(s) && !complete) started = true;
if (started && (state == 1004 || complete && /"playable"\s*:\s*true/.test(s))) break;
if (!started && state == 1004 && i >= 20) break;
if (!started && i >= 180) {
@@ -226,8 +253,72 @@ def installed(root):
return os.path.isfile(launcher(root))
def install_path(library):
return "Z:" + library.rstrip("/")
def dosdevices(root):
return os.path.join(prefix(root), "pfx", "dosdevices")
def volume_root(path):
device = os.stat(path).st_dev
while path != "/":
parent = os.path.dirname(path)
if os.stat(parent).st_dev != device:
break
path = parent
return path
def inside(path, folder):
return path == folder or path.startswith(folder.rstrip("/") + "/")
def mapped_drive(root, path, volume):
folder = dosdevices(root)
try:
names = sorted(os.listdir(folder))
except OSError:
return None
for name in names:
link = os.path.join(folder, name)
if len(name) == 2 and name[0].lower() in DRIVES and name[1] == ":" and os.path.islink(link):
target = os.path.realpath(link)
if inside(target, volume) and inside(path, target):
return name[0].lower(), target
return None
def map_drive(root, volume):
folder = dosdevices(root)
for letter in DRIVES:
link = os.path.join(folder, letter + ":")
if not os.path.lexists(link):
try:
os.makedirs(folder, exist_ok=True)
os.symlink(volume, link)
except OSError as error:
say("%s not mapped to a Wine drive: %s" % (volume, error))
return None
say("Wine drive %s: is %s" % (letter.upper(), volume))
return letter, volume
say("%s not mapped to a Wine drive: every letter is taken" % volume)
return None
def install_path(root, library):
library = library.rstrip("/") or "/"
try:
path = os.path.realpath(library)
volume = volume_root(path)
except OSError:
return "Z:" + library
if volume == "/":
return "Z:" + library
drive = mapped_drive(root, path, volume)
if drive is None and not wine_processes(os.path.join(prefix(root), "pfx")):
drive = map_drive(root, volume)
if drive is None:
return "Z:" + library
letter, target = drive
return letter.upper() + ":\\" + path[len(target):].strip("/").replace("/", "\\")
def write_config(root, library=None):
@@ -254,8 +345,8 @@ def write_config(root, library=None):
client["HardwareAcceleration"] = "false"
changes.append("acceleration")
if library and isinstance(client.setdefault("Install", {}), dict) \
and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(library):
client["Install"]["DefaultInstallPath"] = install_path(library)
and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(root, library).rstrip("\\"):
client["Install"]["DefaultInstallPath"] = install_path(root, library)
changes.append("library")
games = config.setdefault("Games", {})
for uid in CLIENT_32_BIT if isinstance(games, dict) else ():
@@ -417,13 +508,106 @@ def wallpaper(root):
def windows_path(root, path):
found = re.match(r"(?i)^([cz]):[\\/](.*)$", path.strip())
found = re.match(r"(?i)^([a-z]):[\\/](.*)$", path.strip())
if not found:
return None
parts = [part for part in re.split(r"[\\/]+", found.group(2)) if part]
if not parts or ".." in parts:
if ".." in parts:
return None
return os.path.join(drive_c(root) if found.group(1).lower() == "c" else "/", *parts)
letter = found.group(1).lower()
link = os.path.join(dosdevices(root), letter + ":")
if letter == "c":
target = drive_c(root)
elif os.path.islink(link):
target = os.path.realpath(link)
elif letter == "z":
target = "/"
else:
return None
return os.path.join(target, *parts)
def varint(data, at):
value = shift = 0
while at < len(data) and shift < 64:
byte = data[at]
at += 1
value |= (byte & 0x7F) << shift
if not byte & 0x80:
return value, at
shift += 7
raise ValueError("varint")
def encode_varint(value):
out = bytearray()
while value > 0x7F:
out.append(value & 0x7F | 0x80)
value >>= 7
out.append(value)
return bytes(out)
def rewrite_field(data, path, change):
out, at = bytearray(), 0
while at < len(data):
start = at
tag, at = varint(data, at)
kind = tag & 7
if kind == 0:
at = varint(data, at)[1]
elif kind == 1:
at += 8
elif kind == 5:
at += 4
elif kind == 2:
size, body = varint(data, at)
at = body + size
else:
raise ValueError("wire type")
if at > len(data):
raise ValueError("length")
if kind == 2 and tag >> 3 == path[0]:
value = data[body:at]
value = change(value) if len(path) == 1 else rewrite_field(value, path[1:], change)
out += encode_varint(tag) + encode_varint(len(value)) + value
else:
out += data[start:at]
return bytes(out)
def drive_folder(root, value):
try:
text = value.decode("utf-8")
except UnicodeDecodeError:
return value
if not re.match(r"(?i)^z:[\\/]", text):
return value
folder = windows_path(root, text)
if not folder or not os.path.isdir(folder):
return value
moved = install_path(root, folder)
return value if moved.startswith("Z:") else moved.replace("\\", "/").encode("utf-8")
def move_installs(root):
path = os.path.join(drive_c(root), *PRODUCT_DB)
try:
with open(path, "rb") as f:
data = f.read()
moved = rewrite_field(data, INSTALL_FOLDER, lambda value: drive_folder(root, value))
if moved == data or wine_processes(os.path.join(prefix(root), "pfx")):
return False
with open(path, "rb") as f:
if f.read() != data:
return False
except (OSError, ValueError):
return False
with open(path + ".tmp", "wb") as f:
f.write(moved)
shutil.copymode(path, path + ".tmp")
os.replace(path + ".tmp", path)
return True
def wow_folders(root):
@@ -517,6 +701,7 @@ def steam_running(proc="/proc"):
def proton_env():
env = dict(os.environ)
env = GAME_DEBUG["apply_game_debug_logs"](env)
if not steam_running():
env.setdefault("PROTON_SPOOF_STEAMINPUT_VIDPID", "1")
return env
@@ -533,6 +718,11 @@ def configure(root, library=None):
except OSError as error:
say("Battle.net's config not written: %s" % error)
return
try:
if move_installs(root):
say("Battle.net's installed games on a mapped volume now use its Wine drive")
except OSError as error:
say("Battle.net's installed games not moved to their Wine drive: %s" % error)
try:
wallpaper(root)
except OSError as error:
@@ -1211,7 +1401,7 @@ def summary(status):
return out
def agent_job(root, action, uid, product="", folder="", locale="enUS", country="USA", region="US", poll=None, wait=None):
def agent_job(root, action, uid, product="", folder="", locale="enUS", country="USA", region="US", poll=None, wait=None, stall=None):
pfx = os.path.join(prefix(root), "pfx")
if not installed(root) or agent_exe(root) is None:
emit("ERROR", "client")
@@ -1227,7 +1417,6 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
say("%s not made: %s" % (folder, error))
emit("ERROR", "folder")
return 2
windows = "Z:" + folder
told = None
while True:
processes = wine_processes(pfx)
@@ -1244,6 +1433,8 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
time.sleep(POLL if poll is None else poll)
with lock:
stop_leftovers(pfx)
if action == "install":
windows = install_path(root, folder)
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
for suffix in (".json", ".game", ".form", ".error"):
@@ -1266,6 +1457,7 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
os.replace(output, output + ".1")
except OSError:
pass
before = {pid for pid, _ in wine_processes(pfx)}
with open(output, "ab") as log:
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
@@ -1273,6 +1465,9 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
emit("ERROR", "stopped gamescope: %s" % error)
return 1
seen = None
mark = None
moved = time.monotonic()
stalled = False
while True:
done = child.poll() is not None
status = read_status(base + ".json")
@@ -1281,12 +1476,27 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
if brief != seen:
emit("PROGRESS", json.dumps(brief, sort_keys=True))
seen = brief
signature = tuple(brief.get(key) for key in MOVING)
if signature != mark:
mark = signature
moved = time.monotonic()
if done:
break
if action != "uninstall" and time.monotonic() - moved > (STALL if stall is None else stall):
say("the %s of %s made no progress for %d s; stopping it" % (action, uid, STALL if stall is None else stall))
stalled = True
child.kill()
child.wait()
break
time.sleep(POLL if poll is None else poll)
leftovers = wine_processes(pfx)
if leftovers and idle(leftovers):
stop(leftovers)
elif stalled:
stop([(pid, argv) for pid, argv in leftovers if pid not in before and program(argv) == AGENT])
if stalled:
emit("ERROR", "stalled")
return 6
answer = read_status(base + ".game")
game = answer or {}
status = read_status(base + ".json") or {}
@@ -4,7 +4,6 @@ import collections
import fcntl
import filecmp
import http.client
import io
import json
import os
import re
@@ -25,6 +24,7 @@ import urllib.request
HOME = os.environ.get("HOME") or "/root"
SELF = os.path.abspath(__file__)
BIN_DIR = os.path.dirname(SELF)
GAME_DEBUG = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-debug"))
STATE = os.path.join(HOME, ".local", "share", "droiddeck-epic")
CURRENT = os.path.join(STATE, "current.json")
APPS = os.path.join(STATE, "app")
@@ -72,6 +72,14 @@ APP_ID = "com.epicgames.eglv2"
DBUS_NAME = APP_ID + ".SingleInstance"
DBUS_PATH = "/" + APP_ID.replace(".", "/") + "/SingleInstance"
DBUS_METHOD = "org.SingleInstance.DBus.ExecuteCallback"
APP_BIN = "usr/bin/EpicGamesLauncher"
DEB_ICON = "usr/share/icons/hicolor/256x256@2/apps/EpicGamesLauncher.png"
ICON = "epic-games-launcher.png"
DESKTOP = "desktop"
DESKTOP_KEEP = ("usr/lib/x86_64-linux-gnu/", "usr/share/glib-2.0/schemas/")
DESKTOP_LIB = DESKTOP + "/usr/lib/x86_64-linux-gnu"
WEBKIT_DIR = "webkit2gtk-4.1"
WEBKIT_LIB = "libwebkit2gtk-4.1.so.0"
SKIPPED = ("lib/i386-linux-gnu", "lib32", "libx32", "i686-pc-linux-gnu", "share/doc", "include")
SETTINGS_SEED = {
"minimizeToTray": False,
@@ -254,6 +262,35 @@ def inside(root, path):
return real == root or real.startswith(root + os.sep)
def unpack_member(archive, member, staging, root, name, link):
target = os.path.join(staging, name)
if not inside(root, os.path.dirname(target)):
return False
if member.isdir():
os.makedirs(target, exist_ok=True)
return False
os.makedirs(os.path.dirname(target), exist_ok=True)
if not inside(root, os.path.dirname(target)):
return False
if member.issym():
remove(target)
os.symlink(link(target, member.linkname), target)
elif member.islnk():
source = safe_name(member.linkname)
source = os.path.join(staging, source) if source else None
if source and os.path.isfile(source) and inside(root, source):
remove(target)
shutil.copy2(source, target)
elif member.isfile():
remove(target)
with archive.extractfile(member) as src, open(target, "wb") as out:
shutil.copyfileobj(src, out, 1 << 20)
os.chmod(target, (member.mode & 0o777) | 0o600)
else:
return False
return True
def extract_runtime(tarball, dest):
staging = dest + ".staging"
remove(staging)
@@ -271,32 +308,12 @@ def extract_runtime(tarball, dest):
continue
if top == "files" and rest and skipped(rest):
continue
target = os.path.join(staging, name)
if not inside(root, os.path.dirname(target)):
continue
if member.isdir():
os.makedirs(target, exist_ok=True)
continue
os.makedirs(os.path.dirname(target), exist_ok=True)
if not inside(root, os.path.dirname(target)):
continue
if member.issym():
remove(target)
os.symlink(rooted_link(files_root, target, member.linkname) if top == "files" else member.linkname, target)
elif member.islnk():
source = safe_name(member.linkname)
source = os.path.join(staging, source) if source else None
if source and os.path.isfile(source) and inside(root, source):
remove(target)
shutil.copy2(source, target)
elif member.isfile():
remove(target)
with archive.extractfile(member) as src, open(target, "wb") as out:
shutil.copyfileobj(src, out, 1 << 20)
os.chmod(target, (member.mode & 0o777) | 0o600)
if top == "files":
link = lambda target, linkname: rooted_link(files_root, target, linkname)
else:
continue
count += 1
link = lambda target, linkname: linkname
if unpack_member(archive, member, staging, root, name, link):
count += 1
if not os.path.isfile(os.path.join(files_root, "lib", "x86_64-linux-gnu", "libc.so.6")) and \
not os.path.islink(os.path.join(files_root, "lib", "x86_64-linux-gnu", "libc.so.6")):
remove(staging)
@@ -306,63 +323,129 @@ def extract_runtime(tarball, dest):
return staging, count
def ar_members(path):
@contextlib.contextmanager
def deb_data(path, reason):
with open(path, "rb") as f:
if f.read(8) != b"!<arch>\n":
raise Failure("gles-format")
raise Failure(reason)
while True:
header = f.read(60)
if len(header) < 60:
return
raise Failure(reason)
name = header[:16].decode("ascii", "replace").strip().rstrip("/")
size = int(header[48:58].decode("ascii").strip())
data = f.read(size)
if size % 2:
f.read(1)
yield name, data
if name.startswith("data.tar"):
with tarfile.open(fileobj=f, mode="r|*") as archive:
yield archive
return
f.seek(size + size % 2, os.SEEK_CUR)
def is_deb(path):
try:
with open(path, "rb") as f:
return f.read(21) == b"!<arch>\ndebian-binary"
except OSError:
return False
def install_gles(deb, files_root):
libdir = os.path.join(files_root, "lib", "x86_64-linux-gnu")
os.makedirs(libdir, exist_ok=True)
for name, data in ar_members(deb):
if not name.startswith("data.tar"):
continue
with tarfile.open(fileobj=io.BytesIO(data), mode="r:*") as archive:
for member in archive:
base = os.path.basename(member.name)
if not base.startswith("libGLESv2.so"):
continue
target = os.path.join(libdir, base)
remove(target)
if member.issym():
os.symlink(os.path.basename(member.linkname), target)
elif member.isfile():
with archive.extractfile(member) as src, open(target, "wb") as out:
shutil.copyfileobj(src, out)
os.chmod(target, 0o644)
if os.path.exists(os.path.join(libdir, "libGLESv2.so.2")):
return
raise Failure("gles-missing")
with deb_data(deb, "gles-format") as archive:
for member in archive:
base = os.path.basename(member.name)
if not base.startswith("libGLESv2.so"):
continue
target = os.path.join(libdir, base)
remove(target)
if member.issym():
os.symlink(os.path.basename(member.linkname), target)
elif member.isfile():
with archive.extractfile(member) as src, open(target, "wb") as out:
shutil.copyfileobj(src, out)
os.chmod(target, 0o644)
if not os.path.exists(os.path.join(libdir, "libGLESv2.so.2")):
raise Failure("gles-missing")
def extract_app(image, dest):
def extract_deb(deb, dest, wanted=None):
root = os.path.realpath(dest)
def link(target, linkname):
if not linkname.startswith("/"):
return linkname
return os.path.relpath(os.path.join(dest, linkname.lstrip("/")), os.path.dirname(target))
count = 0
with deb_data(deb, "app-format") as archive:
for member in archive:
name = safe_name(member.name)
if name is None or (wanted is not None and not wanted(name)):
continue
if unpack_member(archive, member, dest, root, name, link):
count += 1
return count
def extract_app(image, dest, desktop=()):
staging = dest + ".staging"
remove(staging)
os.makedirs(staging)
status = subprocess.call([os.path.join(BIN_DIR, "droiddeck-fex"), "extract", os.path.abspath(image)],
cwd=staging, stdout=subprocess.DEVNULL)
root = os.path.realpath(os.path.join(staging, "squashfs-root"))
if status != 0 or not app_complete(root):
try:
if not is_deb(image):
raise Failure("app-format")
extract_deb(image, staging)
layer = os.path.join(staging, DESKTOP)
if not inside(os.path.realpath(staging), layer):
raise Failure("app-extract")
os.makedirs(layer, exist_ok=True)
for package in desktop:
if not is_deb(package):
raise Failure("desktop-format")
extract_deb(package, layer, lambda name: any(name.startswith(prefix) for prefix in DESKTOP_KEEP))
icon = os.path.join(staging, DEB_ICON)
if os.path.isfile(icon):
remove(os.path.join(staging, ICON))
shutil.copyfile(icon, os.path.join(staging, ICON))
if not app_complete(staging):
raise Failure("app-extract")
except Exception:
remove(staging)
raise Failure("app-extract")
raise
remove(dest)
os.rename(root, dest)
remove(staging)
os.rename(staging, dest)
def app_complete(root):
return os.path.isfile(os.path.join(root, "AppRun")) and os.path.isfile(os.path.join(root, "usr", "bin", "EpicGamesLauncher"))
if not os.path.isfile(os.path.join(root, APP_BIN)):
return False
return os.path.isfile(os.path.join(root, "AppRun")) or os.path.isfile(os.path.join(root, DESKTOP_LIB, WEBKIT_LIB))
def app_command(app_dir):
apprun = os.path.join(app_dir, "AppRun")
return apprun if os.path.isfile(apprun) else os.path.join(app_dir, APP_BIN)
def desktop_libs(app_dir):
path = os.path.join(app_dir, DESKTOP_LIB)
return path if os.path.isdir(path) else None
def link_webkit(files, libs):
target = os.path.join(files, "lib", "x86_64-linux-gnu", WEBKIT_DIR)
if os.path.isdir(target) and not os.path.islink(target):
return
source = os.path.join(libs, WEBKIT_DIR) if libs else None
if source is None or not os.path.isdir(source):
remove(target)
return
link = os.path.relpath(source, os.path.dirname(target))
if os.path.islink(target) and os.readlink(target) == link:
return
remove(target)
os.symlink(link, target)
def ready(path):
@@ -396,8 +479,11 @@ def install(options):
image = options.get("app")
if not image or not os.path.isfile(image):
raise Failure("no-app-image")
say("unpacking the Epic Games Launcher %s" % app)
extract_app(image, app_dir)
desktop = options.get("desktop") or []
if not all(os.path.isfile(package) for package in desktop):
raise Failure("no-desktop-package")
say("unpacking the Epic Games Launcher %s (%d desktop packages)" % (app, len(desktop)))
extract_app(image, app_dir, desktop)
mark_ready(app_dir)
if not ready(runtime_dir):
tarball, deb = options.get("runtime"), options.get("gles")
@@ -729,11 +815,16 @@ def fex_environment(fex, files, env):
return result
def client_environment(base, fex, files, display, bus, broker, a11y=None, hidden=False):
def client_environment(base, fex, files, display, bus, broker, a11y=None, hidden=False, libs=None):
env = {name: base[name] for name in KEPT_ENV if base.get(name)}
env.setdefault("HOME", HOME)
env.setdefault("LANG", "C.UTF-8")
env["PATH"] = SHIMS + ":/usr/bin:/bin"
if libs:
env["LD_LIBRARY_PATH"] = libs
data = os.path.normpath(os.path.join(os.path.dirname(libs), "..", "share"))
env["XDG_DATA_DIRS"] = data + ":/usr/local/share:/usr/share"
env["GSETTINGS_SCHEMA_DIR"] = os.path.join(data, "glib-2.0", "schemas")
env["DISPLAY"] = display
env["DBUS_SESSION_BUS_ADDRESS"] = bus
env[BROKER_ENV] = broker
@@ -1106,6 +1197,7 @@ def run_game(request, session_env, running=None):
exe = native_path(request.get("exe") or "")
args = request.get("args") or []
env = {k: v for k, v in session_env.items() if not k.startswith(("FEX_", "DROIDDECK_EPIC", "EGL_", "WEBKIT_"))}
env = GAME_DEBUG["apply_game_debug_logs"](env)
preload = env.pop(STEAM_PRELOAD, "")
if preload:
env["LD_PRELOAD"] = preload
@@ -1238,6 +1330,8 @@ class Session:
seed_settings()
install_shims()
install_preload(files)
libs = desktop_libs(app_dir)
link_webkit(files, libs)
fex_module()["install_fonts"](files)
clear_playing()
sync_installations()
@@ -1254,8 +1348,8 @@ class Session:
path = broker_path()
self.broker = Broker(path, self.mode, base)
write_json(instance_file(), {"pid": os.getpid(), "mode": self.mode, "bus": bus, "broker": path})
env = client_environment(base, fex, files, display, bus, path, self.a11y, hidden=self.mode == "hidden")
self.command = [fex["bin"], os.path.join(app_dir, "AppRun")]
env = client_environment(base, fex, files, display, bus, path, self.a11y, hidden=self.mode == "hidden", libs=libs)
self.command = [fex["bin"], app_command(app_dir)]
self.env = env
say("starting the Epic Games Launcher %s (%s, display %s)" % (current.get("app"), self.mode, display))
self.start_client()
@@ -1471,12 +1565,14 @@ def forward(bus, url):
return False
def parse_options(args, flags=()):
def parse_options(args, flags=(), lists=()):
options, rest = {}, []
while args:
arg = args.pop(0)
if arg.startswith("--") and arg[2:] in flags:
options[arg[2:]] = True
elif arg.startswith("--") and arg[2:] in lists and args:
options.setdefault(arg[2:], []).append(args.pop(0))
elif arg.startswith("--") and args:
options[arg[2:]] = args.pop(0)
else:
@@ -1830,7 +1926,7 @@ def main(argv):
if action == "xdg-open":
return shim_open(args)
if action == "install":
options, _ = parse_options(args)
options, _ = parse_options(args, lists=("desktop",))
try:
return install(options)
except (ValueError, tarfile.TarError, OSError) as error:
@@ -8,6 +8,7 @@ import os
import re
import runpy
import shutil
import stat
import struct
import subprocess
import sys
@@ -37,7 +38,9 @@ RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper"
SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")}
MARKER = ".droiddeck-fex"
LAYOUT = 1
ROOTFS_LAYOUT = 2
ROOTFS_LAYOUT = 4
BLOB_DIRS = re.compile(r"^(?:\.ref|[0-9a-f]{2})$")
ROOTFS_LIBRARY_DIRS = ("lib", "lib64")
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
PROVIDED = frozenset((
@@ -310,9 +313,38 @@ def provides_newer(base, provider):
return True
def mirror(source, provider, name, target):
def clone(source, target, parents=()):
real = os.path.realpath(source)
if real in parents or not os.path.lexists(real):
return
if os.path.isdir(real):
os.makedirs(target, exist_ok=True)
for entry in os.listdir(real):
clone(os.path.join(real, entry), os.path.join(target, entry), parents + (real,))
shutil.copystat(real, target)
return
shutil.copy2(real, target)
def remove_tree(path):
if os.path.islink(path) or not os.path.isdir(path):
with contextlib.suppress(FileNotFoundError):
os.unlink(path)
return
os.chmod(path, os.lstat(path).st_mode | stat.S_IRWXU)
for entry in os.listdir(path):
remove_tree(os.path.join(path, entry))
os.rmdir(path)
def stays_in_libraries(root, target, link):
resolved = os.path.normpath(os.path.join(os.path.relpath(target, root), link))
return resolved.split(os.sep)[0] in ROOTFS_LIBRARY_DIRS
def mirror(source, provider, name, target, root):
if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)):
os.symlink(os.path.realpath(os.path.join(provider, name)), os.path.join(target, name))
clone(os.path.join(provider, name), os.path.join(target, name))
return
path = os.path.join(source, name)
link = os.readlink(path) if os.path.islink(path) else None
@@ -322,10 +354,10 @@ def mirror(source, provider, name, target):
link = os.path.join(os.path.dirname(link), name)
if provider and GLIBC_BUILD.match(name):
return
if link and not link.startswith("/"):
if link and not link.startswith("/") and stays_in_libraries(root, target, link):
os.symlink(link, os.path.join(target, name))
else:
os.symlink(os.path.realpath(path), os.path.join(target, name))
clone(path, os.path.join(target, name))
def build_rootfs(base, provider):
@@ -337,12 +369,12 @@ def build_rootfs(base, provider):
return False
for entry in os.listdir(STATE):
if entry.startswith("rootfs."):
shutil.rmtree(os.path.join(STATE, entry), ignore_errors=True)
remove_tree(os.path.join(STATE, entry))
tmp = "%s.%d.tmp" % (rootfs, os.getpid())
os.makedirs(tmp)
for entry in os.listdir(base_files):
if entry not in ("lib", "lib64", "usr", MARKER):
os.symlink(os.path.realpath(os.path.join(base_files, entry)), os.path.join(tmp, entry))
if entry not in ("lib", "lib64", "usr", MARKER) and not BLOB_DIRS.match(entry):
clone(os.path.join(base_files, entry), os.path.join(tmp, entry))
os.symlink(".", os.path.join(tmp, "usr"))
for top in ("lib", "lib64"):
source = os.path.join(base_files, top)
@@ -353,15 +385,15 @@ def build_rootfs(base, provider):
provided = os.path.join(provider_files, top, entry)
os.makedirs(os.path.join(tmp, top, entry))
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}:
mirror(path, provided, name, os.path.join(tmp, top, entry))
mirror(path, provided, name, os.path.join(tmp, top, entry), tmp)
else:
mirror(source, None, entry, os.path.join(tmp, top))
mirror(source, None, entry, os.path.join(tmp, top), tmp)
write_if_changed(os.path.join(tmp, MARKER), stamp)
old = "%s.%d.old" % (rootfs, os.getpid())
if os.path.lexists(rootfs):
os.rename(rootfs, old)
os.rename(tmp, rootfs)
shutil.rmtree(old, ignore_errors=True)
remove_tree(old)
return True
@@ -441,7 +473,7 @@ def link_guest_sdk(root):
continue
os.makedirs(os.path.dirname(link), exist_ok=True)
if os.path.lexists(link):
os.unlink(link)
remove_tree(link)
os.symlink(directory, link)
@@ -513,8 +545,6 @@ def prepare(app=SNIPER_APPID):
root = os.path.join(platform, "files")
if materialize(platform):
say("prepared %s as the x86 runtime" % os.path.basename(platform))
install_preloads(root)
install_fonts(root)
provider = None
if app == SNIPER_APPID:
provider = graphics_platform()
@@ -531,6 +561,8 @@ def prepare(app=SNIPER_APPID):
say("built the x86 runtime from %s with the C and C++ libraries of %s"
% (os.path.basename(platform), os.path.basename(provider)))
root = os.path.join(STATE, "rootfs")
install_preloads(root)
install_fonts(root)
with contextlib.suppress(OSError):
link_guest_sdk(root)
write_config(fex, root)
@@ -0,0 +1,71 @@
#!/usr/bin/python3
import json
import os
import re
import sys
from pathlib import Path
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
def game_debug_channels(*values):
selectors = {}
for value in values:
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
continue
for part in value.split(","):
part = part.strip()
match = WINE_DEBUG_SELECTOR.fullmatch(part)
if match is None:
continue
key = (match[1] or "", match[3])
selectors.pop(key, None)
selectors[key] = part
for channel in GAME_DEBUG_CHANNELS:
key = ("", channel)
selectors.pop(key, None)
selectors[key] = "+" + channel
formatted = ",".join(selectors.values())
if len(formatted) > 8192:
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
return formatted
def load_config():
try:
path = Path(os.environ.get("HOME") or "/root") / ".config/droiddeck/game-environment.json"
with path.open(encoding="utf-8") as source:
return json.load(source)
except (OSError, ValueError):
return None
def session_debug_dir(env):
return env.get("BL_DEBUG_DIR", "")
def apply_game_debug_logs(env, config=None, debug_dir=None):
if config is None:
config = load_config()
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
return env
if debug_dir is None:
debug_dir = session_debug_dir(env)
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
return env
result = dict(env)
result.update({
"PROTON_LOG": "1",
"PROTON_LOG_DIR": debug_dir,
"PROTON_CRASH_REPORT_DIR": debug_dir,
"DXVK_LOG_PATH": debug_dir,
"DXVK_LOG_LEVEL": "debug",
"VKD3D_DEBUG": "info",
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
@@ -10,11 +10,17 @@ import sys
import tempfile
from pathlib import Path
GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
GAME_PREFIX = "DROIDDECK_GAME_"
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
D3D9_DEFAULT_MEMORY_MB = 4096
SYNC_KEYS = ("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")
GAME_DEBUG = runpy.run_path(str(Path(__file__).with_name("droiddeck-game-debug")))
game_debug_channels = GAME_DEBUG["game_debug_channels"]
apply_game_debug_logs = GAME_DEBUG["apply_game_debug_logs"]
session_debug_dir = GAME_DEBUG["session_debug_dir"]
# Prefixes several games share; the game itself is the Steam app being launched.
@@ -122,7 +128,8 @@ def godot_vulkan(game):
@fix
def godot_sentry(game):
sentry = sorted(n[:-4] for n in game.files if n.startswith("libsentry.windows.") and n.endswith(".dll"))
if is_godot(game) and sentry and ("coreclr.dll" in game.files or "godotsharp.dll" in game.files):
# Sentry.Godot.dll's module initializer P/Invokes the native DLL; without it GodotPlugins fails to start.
if is_godot(game) and sentry and ("coreclr.dll" in game.files or "godotsharp.dll" in game.files) and "sentry.godot.dll" not in game.files:
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@@ -144,6 +151,12 @@ def deep_rock_gdk_raytracing(game):
return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)"
@fix
def ff7_rebirth_feature_level(game):
if game.stem in ("ff7rebirth", "ff7rebirth_"):
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)"
@fix
def arkham_city_x87(game):
if "batmanac.exe" in game.files:
@@ -180,6 +193,21 @@ def little_nightmares_threads(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
def names_module(overrides, names):
for entry in (overrides or "").split(";"):
if "=" in entry and names & {re.sub(r"^\*|\.dll$", "", name.lower()) for name in re.split(r"[, \t]", entry.split("=", 1)[0])}:
return True
return False
def keyboard_helper_off(env):
if env.get("SteamDeck") == "1" or names_module(env.get("WINEDLLOVERRIDES"), {"tabtip.exe"}):
return None
own = env.get("WINEDLLOVERRIDES")
env["WINEDLLOVERRIDES"] = own + ";tabtip.exe=d" if own else "tabtip.exe=d"
return "tabtip.exe off (it only opens Steam's keyboard with SteamDeck=1, and its UI Automation calls crash games)"
def skip_red_launcher(command):
if len(command) > 2 and os.path.basename(command[2]).lower() == "redprelauncher.exe":
game = os.path.join(os.path.dirname(command[2]), "bin", "x64", "Cyberpunk2077.exe")
@@ -353,6 +381,36 @@ def engine_fixes(exe, args):
return env, extra, notes
DS_APP_IDS = {"1190460", "1850570"}
DS_SIZE = 86479872
DS_WINDOW_OFFSET = 0x38FE190
DS_WINDOW = bytes.fromhex("48895c240848896c2410488974241848897c242041564883ec70458bf1498bf0488bfa488be94885c9")
DS_ORIGINAL = bytes.fromhex("0f85a5000000")
DS_FIXED = bytes.fromhex("e9a600000090")
def death_stranding_allocator(app_id, exe):
# The game's bundled mimalloc tries one random address between 4 and 8 TiB and never falls back,
# but a 39-bit kernel cannot map anything above 512 GiB. Jumping straight to its aligned path avoids it.
if app_id not in DS_APP_IDS or os.path.basename(exe).lower() != "ds.exe":
return False
try:
with open(exe, "r+b") as game:
if os.fstat(game.fileno()).st_size != DS_SIZE:
return False
game.seek(DS_WINDOW_OFFSET)
seen = game.read(len(DS_WINDOW) + len(DS_ORIGINAL))
if seen[:len(DS_WINDOW)] != DS_WINDOW or seen[len(DS_WINDOW):] != DS_ORIGINAL:
return False
game.seek(DS_WINDOW_OFFSET + len(DS_WINDOW))
game.write(DS_FIXED)
except OSError as error:
print("droiddeck-game-env: Death Stranding allocator fix not applied (%s)" % error, file=sys.stderr)
return False
print("droiddeck-game-env: Death Stranding: memory allocator no longer needs a high address (39-bit kernels)", file=sys.stderr)
return True
def win_components(compat, app_id, proton=None, env=None):
if not compat:
return ""
@@ -378,16 +436,19 @@ def chromium_app(folder):
def game_gpu(env, keep=False):
if GAME_TU_DEBUG not in env:
if not any(GAME_PREFIX + key in env for key in GAME_SPLIT_KEYS):
return env
result = env.copy()
value = result.pop(GAME_TU_DEBUG)
if keep:
return result
if value:
result["TU_DEBUG"] = value
else:
result.pop("TU_DEBUG", None)
for key in GAME_SPLIT_KEYS:
if GAME_PREFIX + key not in result:
continue
value = result.pop(GAME_PREFIX + key)
if keep:
continue
if value:
result[key] = value
else:
result.pop(key, None)
return result
@@ -396,7 +457,9 @@ def vram_cap(env):
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
return env
result = env.copy()
cap = "dxgi.maxDeviceMemory = %d" % int(value)
cap = "dxgi.maxDeviceMemory = {0}; dxgi.maxSharedMemory = {0}".format(int(value))
if int(value) < D3D9_DEFAULT_MEMORY_MB:
cap += "; d3d9.maxAvailableMemory = {0}".format(int(value))
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
result["DROIDDECK_VRAM_CAP"] = "1"
@@ -537,7 +600,16 @@ def apply_config(env, config, app_id, fixes=None):
if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)):
value = entries.get(name, env.get(name)) + ";" + value
entries[name] = value
entries.update(config.get("games", {}).get(app_id, {}))
game = config.get("games", {}).get(app_id, {})
fix = (fixes or {}).get("WINEDLLOVERRIDES")
if fix and isinstance(game.get("WINEDLLOVERRIDES"), str):
own = game["WINEDLLOVERRIDES"]
combined = fix + ";" + own if own else fix
if len(combined) > 8192:
print("droiddeck-game-env: game WINEDLLOVERRIDES too long to add DroidDeck's overrides; using the game value only", file=sys.stderr)
combined = own
game = dict(game, WINEDLLOVERRIDES=combined)
entries.update(game)
for name, value in entries.items():
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
raise ValueError("invalid environment name")
@@ -602,55 +674,6 @@ def bridge_feature_level(env):
return "Mali bridge: VKD3D_FEATURE_LEVEL %s capped at 12_0 (no ray tracing or mesh shaders)" % was
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
def game_debug_channels(*values):
selectors = {}
for value in values:
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
continue
for part in value.split(","):
part = part.strip()
match = WINE_DEBUG_SELECTOR.fullmatch(part)
if match is None:
continue
key = (match[1] or "", match[3])
selectors.pop(key, None)
selectors[key] = part
for channel in GAME_DEBUG_CHANNELS:
key = ("", channel)
selectors.pop(key, None)
selectors[key] = "+" + channel
formatted = ",".join(selectors.values())
if len(formatted) > 8192:
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
return formatted
def apply_game_debug_logs(env, config, debug_dir):
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
return env
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
return env
result = dict(env)
result.update({
"PROTON_LOG": "1",
"PROTON_LOG_DIR": debug_dir,
"PROTON_CRASH_REPORT_DIR": debug_dir,
"DXVK_LOG_PATH": debug_dir,
"DXVK_LOG_LEVEL": "debug",
"VKD3D_DEBUG": "info",
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
def sync_config(config, app_id):
games = config.get("games", {})
return {
@@ -884,14 +907,11 @@ PE = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe"))
pe_machine = PE["pe_machine"]
def repair_foreign_system_dlls(prefix, proton, env=None):
def prefix_system_dlls(prefix, proton, env=None):
dist = Path(proton).parent / "files/lib/wine"
windows = Path(prefix) / "pfx/drive_c/windows"
machines_by_folder = PE["proton_pe_machines"](proton, env or {})
if machines_by_folder is None:
return []
repaired = []
for folder, (libdir, machines) in machines_by_folder.items():
for folder, (libdir, machines) in (machines_by_folder or {}).items():
builtins = dist / libdir
try:
builtin_names = {name.lower(): name for name in os.listdir(builtins)}
@@ -901,35 +921,83 @@ def repair_foreign_system_dlls(prefix, proton, env=None):
names = sorted(os.listdir(windows / folder))
except OSError:
continue
# Both restoration and repair may examine many DLLs. Index the backup
# names from this directory listing instead of listing it for each DLL.
backups = {}
for entry in names:
stem, marker, suffix = entry.partition(FOREIGN_SUFFIX)
if not marker or not stem.lower().endswith(".dll"):
continue
if not suffix:
serial = 0
elif suffix.startswith(".") and suffix[1:].isdigit():
serial = int(suffix[1:])
else:
continue
backups.setdefault(stem, []).append((serial, windows / folder / entry))
for copies in backups.values():
copies.sort()
for name in names:
path = windows / folder / name
builtin_name = builtin_names.get(name.lower())
source = builtins / builtin_name if builtin_name else builtins / name
if path.is_symlink() or not name.lower().endswith(".dll") or not source.is_file() or not path.is_file():
if name.lower().endswith(".dll") and source.is_file():
yield folder, name, windows / folder / name, source, machines, builtins, backups.get(name, ())
def newest_foreign_backup(backups):
return backups[-1][1] if backups else None
def restore_compatible_system_dlls(prefix, proton, env=None):
restored = []
for folder, name, path, source, machines, builtins, backups in prefix_system_dlls(prefix, proton, env):
if not path.is_symlink() or not path.is_file():
continue
try:
if not os.path.samefile(path, source):
continue
machine = pe_machine(path)
if machine is None or PE["machine_compatible"](path, machines, machine):
continue
link = windows / folder / (name + ".bl-new")
backup = windows / folder / (name + FOREIGN_SUFFIX)
serial = 1
while os.path.lexists(backup):
backup = windows / folder / (name + FOREIGN_SUFFIX + ".%d" % serial)
serial += 1
except OSError:
continue
backup = newest_foreign_backup(backups)
if backup is None or backup.is_symlink() or not backup.is_file():
continue
machine = pe_machine(backup)
if machine is None or not PE["machine_compatible"](backup, machines, machine, builtins, name):
continue
try:
os.replace(backup, path)
except OSError:
continue
restored.append("%s/%s (machine 0x%x)" % (folder, name, machine))
return restored
def repair_foreign_system_dlls(prefix, proton, env=None):
repaired = []
for folder, name, path, source, machines, builtins, backups in prefix_system_dlls(prefix, proton, env):
if path.is_symlink() or not path.is_file():
continue
machine = pe_machine(path)
if machine is None or PE["machine_compatible"](path, machines, machine, builtins):
continue
link = path.parent / (name + ".bl-new")
backup = path.parent / (name + FOREIGN_SUFFIX)
if backups:
backup = path.parent / (name + FOREIGN_SUFFIX + ".%d" % (backups[-1][0] + 1))
try:
os.symlink(os.path.relpath(source, path.parent), link)
os.replace(path, backup)
try:
os.symlink(os.path.relpath(source, path.parent), link)
os.replace(path, backup)
try:
os.replace(link, path)
except OSError:
if not os.path.lexists(path) and os.path.lexists(backup):
os.replace(backup, path)
raise
os.replace(link, path)
except OSError:
if link.is_symlink():
link.unlink()
continue
repaired.append("%s/%s (machine 0x%x)" % (folder, name, machine))
if not os.path.lexists(path) and os.path.lexists(backup):
os.replace(backup, path)
raise
except OSError:
if link.is_symlink():
link.unlink()
continue
repaired.append("%s/%s (machine 0x%x)" % (folder, name, machine))
return repaired
@@ -1229,7 +1297,7 @@ def main():
return 2
env = game_gpu(os.environ.copy())
mic_enabled = env.get("BL_MIC_ENABLED")
debug_dir = env.get("BL_DEBUG_DIR", "")
debug_dir = session_debug_dir(env)
prefix_path = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
app_id = game_id(env)
components = ""
@@ -1259,10 +1327,14 @@ def main():
components = win_components(prefix_path, app_id, command[0], effective_env)
if prefix_path and command:
try:
restored = restore_compatible_system_dlls(prefix_path, command[0], effective_env)
fixed = repair_foreign_system_dlls(prefix_path, command[0], effective_env)
except OSError as error:
fixed = []
restored = fixed = []
print("droiddeck-game-env: prefix system DLL check skipped (%s)" % error, file=sys.stderr)
if restored:
print("droiddeck-game-env: restored system DLLs this Proton's own programs do not load: %s" % ", ".join(restored),
file=sys.stderr)
if fixed:
print("droiddeck-game-env: replaced foreign-architecture system DLLs with this Proton's own: %s" % ", ".join(fixed),
file=sys.stderr)
@@ -1287,6 +1359,8 @@ def main():
fixes = {}
if waiting:
command = skip_red_launcher(command)
if len(command) > 2:
death_stranding_allocator(app_id, command[2])
ubisoft_overlay_off(env)
project_zomboid_jvm(command)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
@@ -1307,6 +1381,9 @@ def main():
if "vblank_mode" in config.get("shared", {}):
fixes.pop("vblank_mode", None)
env = apply_config(env, launch_config, app_id, fixes)
note = keyboard_helper_off(env)
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
else:
path = Path.home() / ".config/droiddeck/game-environment.json"
try:
@@ -17,6 +17,7 @@ PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run")
APPIMAGE_RUN = os.path.join(BIN, "droiddeck-appimage-run")
SCRIPT_RUN = os.path.join(BIN, "droiddeck-script-run")
STEAM_LAUNCH = os.path.join(BIN, "droiddeck-steam-launch")
STORE_LAUNCH = os.path.join(BIN, "droiddeck-store-launch")
PROGRAMS = os.path.join(BIN, "droiddeck-desktop-programs")
CACHE = os.path.join(HOME, ".cache", "droiddeck")
IMPORTS = {"appimage": ("/opt/appimages/user", "app"), "folder": ("/opt/droiddeck-apps", "entry")}
@@ -272,12 +273,32 @@ def steam_title(path):
return None
def exe_prefix(path):
try:
run = runpy.run_path(PROTON_RUN)
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
target = run["locate"](path, root)
return ["--prefix", target.appid, "--compatdata", target.compatdata]
except (OSError, ValueError, KeyError, IndexError):
return None
def store_launcher(path):
try:
return runpy.run_path(STORE_LAUNCH)["store_launcher"](path)
except (OSError, ValueError, KeyError):
return None
def command(path, args, what, window=False, appid=None):
folder = os.path.dirname(path)
if what == "steam":
return [STEAM_LAUNCH, "desktop", appid], folder
if what == "windows":
return [PROTON_RUN] + (["--window"] if window else []) + [path] + args, folder
launcher = None if args else store_launcher(path)
prefix = exe_prefix(path) if launcher else None
keep = prefix or []
return [PROTON_RUN] + (["--window"] if window else []) + keep + [launcher or path] + args, folder
if what == "x86 script":
return [FEX, "run", "--mode", "on", "--for", folder, "--"] + interpreter(path) + [path] + args, folder
if what == "script":
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/python3
import os
import signal
import struct
import sys
import time
from pathlib import Path
MAGIC = 0x46484444
HEADER = 128
POLL = 0.5
SETTLE = 3.0
WINDOW = 1.0
LATE = 1.5
PACED_LATE_SHARE = 0.02
RELEASE_LATE_SHARE = 0.05
SLOWER = 1.04
MAX_INTERVAL = 1e9 / 30
SPREAD = 0.08
BACKOFF = 30.0
BACKOFF_MAX = 600.0
def log(message):
print("droiddeck-pace-cores: " + message, flush=True)
def parse_cores(text):
cores = set()
for part in text.strip().split(","):
if not part:
continue
first, _, last = part.partition("-")
cores.update(range(int(first), int(last or first) + 1))
return cores
def efficient_cores(cpu=Path("/sys/devices/system/cpu"), own=None):
try:
online = parse_cores((cpu / "online").read_text())
except (OSError, ValueError):
online = set(range(os.cpu_count() or 0))
online &= own if own is not None else os.sched_getaffinity(0)
for name in ("cpu_capacity", "cpufreq/cpuinfo_max_freq"):
try:
speed = {core: int((cpu / f"cpu{core}/{name}").read_text()) for core in online}
except (OSError, ValueError):
continue
top = max(speed.values(), default=0)
return {core for core, value in speed.items() if value < top}
return set()
class Frames:
"""gamescope's per-frame feed for the HUD: frame intervals of the focused app, its pid and whether Steam is in front."""
def __init__(self, path):
self.path = Path(path)
self.count = None
def read(self):
try:
data = self.path.read_bytes()
except OSError:
return None
if len(data) < HEADER or struct.unpack_from("<I", data, 0)[0] != MAGIC:
return None
capacity, pid = struct.unpack_from("<II", data, 8)
count, = struct.unpack_from("<Q", data, 16)
steam, = struct.unpack_from("<I", data, 40)
last = self.count if self.count is not None else count
self.count = count
first = max(last, count - capacity)
intervals = [struct.unpack_from("<Q", data, HEADER + (i % capacity) * 16)[0] for i in range(first, count)]
return pid, bool(steam), intervals
def median(values):
ordered = sorted(values)
return ordered[len(ordered) // 2]
def late_share(intervals, period):
return sum(1 for value in intervals if value > LATE * period) / len(intervals)
def paced_interval(intervals):
"""The interval of a game a cap holds at 30 fps or more; a starved or uncapped game spreads."""
if len(intervals) < 2:
return None
ordered = sorted(intervals)
held = ordered[len(ordered) // 2]
if held > 1.04 * MAX_INTERVAL:
return None
if ordered[len(ordered) // 10] < (1 - SPREAD) * held or ordered[len(ordered) * 9 // 10] > (1 + SPREAD) * held:
return None
if late_share(intervals, held) > PACED_LATE_SHARE:
return None
return held
class Cores:
def get(self, tid):
return os.sched_getaffinity(tid)
def set(self, tid, cpus):
os.sched_setaffinity(tid, cpus)
class Parker:
"""Keeps one process's threads off the fastest cores and puts back what each had."""
def __init__(self, efficient, proc=Path("/proc"), cores=None):
self.efficient = efficient
self.proc = proc
self.cores = cores or Cores()
self.pid = None
self.before = {}
self.present = None
self.own = set()
def tasks(self, pid):
try:
return [int(tid) for tid in os.listdir(self.proc / str(pid) / "task") if tid.isdigit()]
except OSError:
return []
def park(self, pid):
self.pid = pid
tids = self.tasks(pid)
if self.present is None:
self.present = set(tids)
masks = {}
for tid in tids:
if tid not in self.before:
try:
masks[tid] = self.cores.get(tid)
except OSError:
continue
# A mask the game gave one of its own threads may be passed on by it, not by a parked thread.
self.own.update(frozenset(now) for tid, now in masks.items() if tid in self.present)
inherited = {}
for before, parked in self.before.values():
inherited[frozenset(parked)] = inherited.get(frozenset(parked), set()) | before
for tid, now in masks.items():
try:
wanted = now & self.efficient
if wanted and wanted != now:
self.cores.set(tid, wanted)
self.before[tid] = (now, wanted)
elif tid not in self.present and frozenset(now) in inherited and frozenset(now) not in self.own:
self.before[tid] = (inherited[frozenset(now)], now)
except OSError:
continue
def release(self):
for tid, (before, parked) in self.before.items():
try:
if self.cores.get(tid) == parked:
self.cores.set(tid, before)
except OSError:
continue
self.pid = None
self.present = None
self.own.clear()
self.before.clear()
class Governor:
def __init__(self, frames, parker, clock=time.monotonic):
self.frames = frames
self.parker = parker
self.clock = clock
self.pid = None
self.window = []
self.since = None
self.held = None
self.blocked = {}
def tick(self):
read = self.frames.read()
if read is None:
return
pid, steam, intervals = read
now = self.clock()
if steam or not pid or pid != self.pid:
if self.parker.pid is not None:
self.release(now, "focus left the game", backoff=False)
self.pid = None if steam else pid
self.window, self.since = [], now
return
self.window.extend((now, value) for value in intervals)
if self.parker.pid is None and not intervals:
self.window, self.since = [], now
return
if self.parker.pid is None:
self.consider(now)
else:
self.watch(now)
def consider(self, now):
self.window = [entry for entry in self.window if entry[0] >= now - SETTLE]
if now - self.since < SETTLE or now < self.blocked.get(self.pid, (0, 0))[0]:
return
intervals = [value for _, value in self.window]
if sum(intervals) < 0.9 * SETTLE * 1e9:
return
held = paced_interval(intervals)
if held is None:
return
self.held = held
self.parker.park(self.pid)
if self.parker.before:
self.window = []
self.since = now
log(f"pid {self.pid} holds {1e9 / held:.0f} fps, {len(self.parker.before)} thread(s) off the fastest cores")
else:
self.parker.release()
def watch(self, now):
self.parker.park(self.pid)
self.window = [entry for entry in self.window if entry[0] >= now - WINDOW]
intervals = [value for _, value in self.window]
if now - self.since < WINDOW:
return
if len(intervals) < 0.5 * WINDOW * 1e9 / self.held:
self.release(now, "frames stalled")
return
if late_share(intervals, self.held) > RELEASE_LATE_SHARE or median(intervals) > SLOWER * self.held:
self.release(now, "frames fell behind")
def release(self, now, why, backoff=True):
pid = self.parker.pid
self.parker.release()
if backoff:
_, wait = self.blocked.get(pid, (0, BACKOFF / 2))
wait = min(wait * 2, BACKOFF_MAX)
self.blocked[pid] = (now + wait, wait)
log(f"pid {pid} back on every core: {why}; not again for {wait:.0f} s")
else:
log(f"pid {pid} back on every core: {why}")
self.window, self.since = [], now
def stop(self, *_):
self.parker.release()
sys.exit(0)
def main(argv):
if len(argv) != 1:
print("usage: droiddeck-pace-cores <gamescope HUD frames file>", file=sys.stderr)
return 2
efficient = efficient_cores()
if not efficient:
return 0
governor = Governor(Frames(argv[0]), Parker(efficient))
for sig in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):
signal.signal(sig, governor.stop)
while True:
governor.tick()
time.sleep(POLL)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -20,9 +20,14 @@ unpack() {
{ rm -rf "$dir.new"; echo "droiddeck-pipewire: could not unpack $bundle" >&2; return 1; }
}
write_fragment() {
tmp=$1.$$
cat > "$tmp" && mv -f "$tmp" "$1" || { rm -f "$tmp"; return 1; }
}
access_config() {
mkdir -p "$dir/share/pipewire/pipewire.conf.d" "$dir/share/wireplumber/wireplumber.conf.d" || return 1
cat > "$dir/share/pipewire/pipewire.conf.d/droiddeck-access.conf" <<'EOF' || return 1
write_fragment "$dir/share/pipewire/pipewire.conf.d/droiddeck-access.conf" <<'EOF' || return 1
context.properties = {
module.access = false
}
@@ -34,7 +39,7 @@ context.modules = [
}
]
EOF
cat > "$dir/share/wireplumber/wireplumber.conf.d/droiddeck-access.conf" <<'EOF' || return 1
write_fragment "$dir/share/wireplumber/wireplumber.conf.d/droiddeck-access.conf" <<'EOF' || return 1
access.rules = [
{
matches = [ { pipewire.access = "unrestricted" } ]
@@ -54,8 +59,12 @@ env)
client_env
;;
start)
unpack || exit 1
access_config || { echo "droiddeck-pipewire: could not write the access settings" >&2; exit 1; }
mkdir -p "$(dirname "$dir")" 2>/dev/null
(
flock 9 || exit 1
unpack || exit 1
access_config || { echo "droiddeck-pipewire: could not write the access settings" >&2; exit 1; }
) 9> "$dir.lock" || exit 1
stop
mkdir -p "$state"
eval "$(client_env)"
@@ -315,8 +315,8 @@ def locate(program, root):
os.path.dirname(program), root, "own")
def fixed(program, root, appid):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
def fixed(program, root, appid, compatdata=None):
return Target(appid, compatdata or os.path.join(root, "steamapps", "compatdata", str(appid)),
os.path.dirname(program), root, "fixed")
@@ -451,6 +451,7 @@ def arguments(program, args, desktop=None, compatdata=None):
def main(argv):
window = False
prefix = None
compatdata = None
verb = VERB
game_id = None
desktop = None
@@ -461,6 +462,8 @@ def main(argv):
window = True
elif option == "--prefix" and argv and prefix_id(argv[0]):
prefix = argv.pop(0)
elif option == "--compatdata" and argv and os.path.isabs(argv[0]):
compatdata = argv.pop(0)
elif option == "--verb" and argv and argv[0] in VERBS:
verb = argv.pop(0)
elif option == "--game-id" and argv and argv[0].isdigit() and argv[0] != "0":
@@ -484,7 +487,7 @@ def main(argv):
say("%s is not an app id" % app)
return 2
if not argv and app is None:
say("usage: droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]")
say("usage: droiddeck-proton-run [--window] [--prefix ID [--compatdata DIR]] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]")
return 2
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
if options is None:
@@ -509,7 +512,7 @@ def main(argv):
if app is not None and int(app) >= STEAM_APP_LIMIT:
target = shortcut_target(app, program, start, root)
elif prefix:
target = fixed(program, root, prefix)
target = fixed(program, root, prefix, compatdata)
else:
target = locate(program, root)
available = tools(root)
@@ -56,18 +56,75 @@ libraries="$steam_root"
for library in $LIBRARIES; do libraries="$libraries
$library"; done
libraries=$(printf '%s\n%s\n' "$libraries" "$(sed -n 's/^[[:space:]]*"path"[[:space:]]*"\(.*\)"[[:space:]]*$/\1/p' "$steam_root/steamapps/libraryfolders.vdf" 2>/dev/null)" | awk 'NF && !seen[$0]++')
sig=$(while IFS= read -r library; do ls -l --time-style=+%s "$library"/steamapps/appmanifest_*.acf 2>/dev/null; done <<<"$libraries" | cksum)
if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then
{
printf '%s\n' "$sig"
while IFS= read -r library; do
[ -d "$library/steamapps/common" ] || continue
find "$library/steamapps/common" -mindepth 2 -maxdepth 5 -iname 'installscript*.vdf' \
-not -path '*/Steamworks Shared/*' 2>/dev/null
done <<<"$libraries" | sort -u
} >"$cache.tmp" && mv -f "$cache.tmp" "$cache"
games=$(while IFS= read -r library; do
library="$library" awk '
function flush() { if (dir != "") printf "%s|%s|%s|%s\t%s/steamapps/common/%s\n", file, build, updated, size, ENVIRON["library"], dir }
FNR == 1 { flush(); file = FILENAME; dir = build = updated = size = "" }
{
n = split($0, part, "\"")
for (i = 2; i + 2 <= n; i += 2) {
name = tolower(part[i])
if (name == "installdir" && dir == "") dir = part[i + 2]
else if (name == "buildid" && build == "") build = part[i + 2]
else if (name == "lastupdated" && updated == "") updated = part[i + 2]
else if (name == "sizeondisk" && size == "") size = part[i + 2]
else continue
i += 2
}
}
END { flush() }
' "$library"/steamapps/appmanifest_*.acf 2>/dev/null
done <<<"$libraries")
legacy=
[ -s "$cache" ] && ! grep -q $'\t' "$cache" && legacy=$(tail -n +2 "$cache"; echo .)
declare -A scanned=() current=()
read_scanned() {
scanned=()
while IFS=$'\t' read -r key _; do
[ -n "$key" ] && scanned[$key]=1
done < <(grep $'\t' "$cache" 2>/dev/null)
}
read_scanned
later=
fresh=()
while IFS=$'\t' read -r key dir; do
[ -n "$key" ] || continue
current[$key]=1
[ -z "${scanned[$key]:-}" ] || continue
if [ -z "$legacy" ] && [ -n "${DROIDDECK_SEED_SCRIPTS:-}${DROIDDECK_SEED_LATER:-}" ]; then
[ -z "${DROIDDECK_SEED_LATER:-}" ] || later=1
continue
fi
[ -d "$dir" ] || continue
scanned[$key]=1
if [ -n "$legacy" ] && [ "$cache" -nt "${key%%|*}" ]; then
found=$(printf '%s\n' "${legacy%.}" | dir="$dir" awk 'index($0, ENVIRON["dir"] "/") == 1')
else
found=$(find "$dir" -mindepth 1 -maxdepth 4 -iname 'installscript*.vdf' \
-not -path '*/Steamworks Shared/*' 2>/dev/null) || continue
found=$(printf '%s\n' "$found" | sort -u)
fi
fresh+=("$key" "$found")
done <<<"$games"
exec 9>"$cache.lock" && command -v flock >/dev/null 2>&1 && flock 9
if [ ${#fresh[@]} -gt 0 ]; then
read_scanned
for ((i = 0; i < ${#fresh[@]}; i += 2)); do
[ -z "${scanned[${fresh[i]}]:-}" ] || continue
printf '%s\n' "${fresh[i + 1]}" | key="${fresh[i]}" awk '{ print ENVIRON["key"] "\t" $0 }' >>"$cache"
done
fi
game_scripts() { { tail -n +2 "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; }
if [ -n "$later" ]; then
(DROIDDECK_SEED_LATER= DROIDDECK_SEED_SCRIPTS= DROIDDECK_SEED_DEFERRED=1 setsid "$0" "$steam_root" >/dev/null 2>&1 9>&- &)
fi
if [ -e "$cache" ]; then
keys=$(printf '%s\n' "${!current[@]}") awk -F'\t' '
BEGIN { n = split(ENVIRON["keys"], key, "\n"); for (i = 1; i <= n; i++) want[key[i]] = 1 }
NF > 1 && ($1 in want)
' "$cache" >"$cache.tmp" && { cmp -s "$cache.tmp" "$cache" && rm -f "$cache.tmp" || mv -f "$cache.tmp" "$cache"; }
fi
[ -z "${DROIDDECK_SEED_DEFERRED:-}" ] || ! pgrep -x wineserver >/dev/null 2>&1 || exit 0
game_scripts() { { cut -s -f2- "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; }
game_pairs=$(game_scripts | read_scripts)
[ -n "$(printf '%s' "$game_pairs" | tr -d '[:space:]')" ] && pairs=$(printf '%s\n%s\n' "$pairs" "$game_pairs" | sort -u | sed '/^$/d')
declare -A vulkan=()
@@ -132,8 +132,7 @@ clear_stale_tmp() {
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${BL_INSIDE:-}" ]; then
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
rm -f /tmp/.bl-clock
head -c 8 /dev/zero > /tmp/.bl-clock
dd if=/dev/zero of=/tmp/.bl-clock bs=8 count=1 conv=notrunc status=none
fi
steam_devtools() {
@@ -512,6 +511,12 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output"
fi
fi
if [ "$mode" = run ] && [ "${BL_GAME_WIDTH:-0}" -gt 0 ] && [ "${BL_GAME_HEIGHT:-0}" -gt 0 ]; then
nested=$BL_GAME_WIDTH
nested_h=$BL_GAME_HEIGHT
game_size=1
echo "== gamescope: the game runs at ${nested}x${nested_h}, scaled to the ${width}x${height} output with its proportions kept"
fi
backend=${BL_GAMESCOPE_BACKEND:-wayland}
case "$backend" in
wayland) ;;
@@ -529,7 +534,7 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: composites every frame (Mali bridge: the Steam UI flickers on separate planes)"
fi
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then
args+=(-S stretch)
export BL_STRETCHED=1
fi
@@ -812,19 +817,30 @@ case $mode in
fi
}
bl_zram_usage() {
local _p _k _v _u _rss=0 _swap=0
local _p _k _v _u _resident _anonymous _rss=0 _anon=0 _swap=0
for _p in "$@"; do
_resident=0 _anonymous=-1
while read -r _k _v _u; do
case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac
case $_v in ''|*[!0-9]*) continue ;; esac
case $_k in
VmRSS:) _resident=$_v ;;
RssAnon:) _anonymous=$_v ;;
VmSwap:) _swap=$((_swap + _v)) ;;
esac
done 2>/dev/null < "/proc/$_p/status"
[ "$_anonymous" -ge 0 ] || _anonymous=$_resident
_rss=$((_rss + _resident)) _anon=$((_anon + _anonymous))
done
_bl_rss=$_rss
_bl_rss=$_rss _bl_anon=$_anon
_bl_swap=$_swap
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
}
bl_memory_read() {
local _k _v _u _kind _fields _avg
_bl_mem_total=0 _bl_available=-1 _bl_swap_total=0 _bl_swap_free=-1 _bl_psi=0
local _k _v _u _kind _fields _avg _whole _frac _gpu_bytes _growth _saved_growth _saved_fall
_saved_growth=${_bl_preserved_growth:-0} _saved_fall=${_bl_preserved_fall:-0}
_bl_preserved_growth=0 _bl_preserved_fall=0
_bl_mem_total=0 _bl_available=-1 _bl_swap_total=0 _bl_swap_free=-1
_bl_psi_some=0 _bl_psi_full=0 _bl_gpu=0 _bl_unevictable=0 _bl_shmem=0
while read -r _k _v _u; do
case $_v in ''|*[!0-9]*) continue ;; esac
case $_k in
@@ -832,15 +848,50 @@ case $mode in
MemAvailable:) _bl_available=$_v ;;
SwapTotal:) _bl_swap_total=$_v ;;
SwapFree:) _bl_swap_free=$_v ;;
Unevictable:) _bl_unevictable=$_v ;;
Shmem:) _bl_shmem=$_v ;;
esac
done 2>/dev/null < /proc/meminfo
if [ -r /proc/pressure/memory ]; then
while read -r _kind _fields; do
[ "$_kind" = some ] || continue
_avg=${_fields#avg10=} _avg=${_avg%% *} _avg=${_avg%%.*}
case $_avg in ''|*[!0-9]*) ;; *) _bl_psi=$((10#$_avg)) ;; esac
[ "$_kind" = some ] || [ "$_kind" = full ] || continue
_avg=${_fields#avg10=} _avg=${_avg%% *}
_whole=${_avg%%.*} _frac=${_avg#*.}
[ "$_frac" = "$_avg" ] && _frac=00
_frac=${_frac}00
_frac=${_frac:0:2}
case $_whole$_frac in ''|*[!0-9]*) continue ;; esac
if [ "$_kind" = some ]; then
_bl_psi_some=$((10#$_whole * 100 + 10#$_frac))
else
_bl_psi_full=$((10#$_whole * 100 + 10#$_frac))
fi
done 2>/dev/null < /proc/pressure/memory
fi
if [ -r /sys/class/kgsl/kgsl/page_alloc ]; then
read -r _gpu_bytes _u < /sys/class/kgsl/kgsl/page_alloc
case $_gpu_bytes in ''|*[!0-9]*) _gpu_bytes=0 ;; esac
_bl_gpu=$((_gpu_bytes / 1024))
fi
_bl_psi=$_bl_psi_some
[ "$_bl_psi_full" -gt "$_bl_psi" ] && _bl_psi=$_bl_psi_full
if [ "${_bl_sample_at:-}" = "" ]; then
_bl_growth=0 _bl_fall=0
_bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu
_bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem
elif [ "$SECONDS" -gt "$_bl_sample_at" ]; then
_bl_growth=0 _bl_fall=0
_growth=$((_bl_gpu - _bl_sample_gpu)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth))
_growth=$((_bl_unevictable - _bl_sample_unevictable)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth))
_growth=$((_bl_shmem - _bl_sample_shmem)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth))
_bl_fall=$((_bl_sample_available - _bl_available))
[ "$_saved_growth" -gt "$_bl_growth" ] && _bl_growth=$_saved_growth
[ "$_saved_fall" -gt "$_bl_fall" ] && _bl_fall=$_saved_fall
_bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu
_bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem
fi
_bl_real_available=$_bl_available
[ "$_bl_real_available" -ge 0 ] && _bl_real_available=$((_bl_real_available - _bl_growth))
_bl_headroom=$((_bl_mem_total / 5))
[ "$_bl_headroom" -ge $((512 * 1024)) ] || _bl_headroom=$((512 * 1024))
[ "$_bl_headroom" -le $((1536 * 1024)) ] || _bl_headroom=$((1536 * 1024))
@@ -852,25 +903,29 @@ case $mode in
}
bl_memory_tight() {
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] &&
{ [ "$_bl_available" -lt "$_bl_headroom" ] ||
{ [ "$_bl_psi" -ge 1 ] && [ "$_bl_available" -lt $((_bl_mem_total / 3)) ]; }; }
{ [ "$_bl_real_available" -lt "$_bl_headroom" ] ||
{ [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_mem_total / 3)) ]; } ||
{ [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_headroom * 2)) ]; }; }
}
bl_client_can_pageout() {
bl_memory_read
bl_zram_usage "${_bl_pids[@]}" > /dev/null
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_swap_total" -gt 0 ] &&
[ $((_bl_swap_free - _bl_rss)) -ge "$_bl_swap_reserve" ]
[ "$_bl_mem_total" -gt 0 ] && bl_zram_has_room
}
bl_zram_has_room() {
[ "$_bl_swap_total" -gt 0 ] &&
[ $((_bl_swap_free - _bl_anon - ${_bl_client_reserve:-0})) -ge "$_bl_swap_reserve" ]
}
bl_client_can_readback() {
bl_memory_read
bl_zram_usage "${_bl_pids[@]}" > /dev/null
[ "$_bl_mem_total" -gt 0 ] && ! bl_memory_tight &&
[ "$_bl_available" -ge $((_bl_swap * 2)) ] &&
[ $((_bl_available - _bl_swap)) -ge "$_bl_headroom" ]
[ "$_bl_mem_total" -gt 0 ] && ! bl_memory_tight && ! bl_memory_critical &&
[ "$_bl_real_available" -ge $((_bl_swap * 2)) ] &&
[ $((_bl_real_available - _bl_swap)) -ge "$_bl_headroom" ]
}
bl_client_pressure() {
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ "$_bl_game" = 1 ] &&
[ "${#_bl_pids[@]}" -gt 0 ] && bl_memory_tight || return 0
[ "${#_bl_pids[@]}" -gt 0 ] && { bl_memory_tight || bl_memory_critical; } || return 0
[ "$_bl_pressure_at" -lt 0 ] ||
[ $((SECONDS - _bl_pressure_at)) -ge "$_bl_pressure_backoff" ] || return 0
[ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 30 ] || return 0
@@ -880,12 +935,29 @@ case $mode in
return 0
fi
[ "$_bl_rss" -ge $((128 * 1024)) ] || return 0
local _before=$_bl_rss
bl_zram_send 1 "memory pressure, compressing the client (available $((_bl_available / 1024)) MB, swap free $((_bl_swap_free / 1024)) MB)" client
_bl_pressure_before=$_bl_rss
if [ "${1:-}" = defer ]; then
_bl_client_reserve=$_bl_anon
_bl_client_pending=1
fi
bl_zram_send 1 "memory pressure, compressing the client (available $((_bl_available / 1024)) MB, swap free $((_bl_swap_free / 1024)) MB)" client "${1:-}"
_bl_packed=$SECONDS
if [ "${1:-}" = defer ]; then
_bl_client_targets=("${_bl_zram_targets[@]}")
else
bl_client_pressure_result
fi
}
bl_client_pressure_finish() {
[ "${_bl_client_pending:-0}" = 1 ] || return 0
bl_zram_finish 1 "${_bl_client_targets[@]}"
bl_client_pressure_result "${_bl_client_targets[@]}"
_bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=()
}
bl_client_pressure_result() {
[ "${_bl_pageout_complete:-0}" = 1 ] || return 0
bl_zram_usage "${_bl_pids[@]}" > /dev/null
if [ $((_before - _bl_rss)) -lt $((16 * 1024)) ]; then
if [ "$#" -gt 0 ]; then bl_zram_usage "$@" > /dev/null; else bl_zram_usage "${_bl_pids[@]}" > /dev/null; fi
if [ $((_bl_pressure_before - _bl_rss)) -lt $((16 * 1024)) ]; then
_bl_pressure_backoff=$((_bl_pressure_backoff * 2 > 300 ? 300 : _bl_pressure_backoff * 2))
else
_bl_pressure_backoff=30
@@ -893,15 +965,14 @@ case $mode in
}
bl_memory_critical() {
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] &&
{ [ "$_bl_available" -lt "$_bl_tier_headroom" ] ||
{ [ "$_bl_psi" -ge 1 ] && [ "$_bl_available" -lt $((_bl_tier_headroom * 3 / 2)) ]; }; }
}
bl_low_ram() {
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_mem_total" -le $((13 * 1024 * 1024)) ]
{ [ "$_bl_real_available" -lt "$_bl_tier_headroom" ] ||
{ [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 3 / 2)) ]; } ||
{ [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; }; }
}
bl_session_pressure() {
bl_memory_read
[ "$_bl_game" = 1 ] && bl_low_ram && bl_memory_critical || return 0
[ "$_bl_game" = 1 ] && bl_memory_critical || return 0
[ "${BL_ZRAM_IDLE:-1}" = 1 ] && bl_game_focused 0 || return 0
local _wait=$_bl_tier_backoff _before _pids _targets
[ "$_bl_available" -ge $((_bl_headroom / 2)) ] || [ "$_bl_tier_pushed" -lt 0 ] || _wait=30
[ "$_bl_tier_at" -lt 0 ] || [ $((SECONDS - _bl_tier_at)) -ge "$_wait" ] || return 0
@@ -917,21 +988,18 @@ case $mode in
fi
fi
_bl_tier_at=$SECONDS _bl_tier_pushed=0
bl_zram_pick game
bl_zram_pick session
bl_zram_usage "${_pids[@]}" > /dev/null
[ "$_bl_rss" -ge $((256 * 1024)) ] || return 0
if [ "$_bl_swap_total" -le 0 ] || [ $((_bl_swap_free - _bl_rss)) -lt "$_bl_swap_reserve" ]; then
if ! bl_zram_has_room; then
step "zRAM: low-memory page-out skipped, swap headroom too small ($((_bl_swap_free / 1024)) MB free)"
return 0
fi
_targets=("${_pids[@]}") _before=$_bl_swap
bl_zram_send 1 "low memory (available $((_bl_available / 1024)) MB), compressing idle game memory" game
bl_zram_send 1 "low memory (available $((_bl_real_available / 1024)) MB), compressing idle game memory" session
bl_zram_usage "${_targets[@]}" > /dev/null
_bl_tier_pushed=$((_bl_swap - _before))
bl_tier_note "${_targets[@]}"
if [ "${_bl_pageout_complete:-0}" = 1 ] && [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ "${#_bl_pids[@]}" -gt 0 ]; then
_bl_pressure_at=$SECONDS _bl_packed=$SECONDS
fi
}
bl_proc_start() {
local _s=
@@ -962,7 +1030,7 @@ case $mode in
}
bl_watch_nap() {
local _i
if [ "$_bl_game" = 1 ] && bl_low_ram && [ "$_bl_available" -ge 0 ] && [ "$_bl_available" -lt $((_bl_tier_headroom * 2)) ]; then
if [ "$_bl_game" = 1 ] && [ "$_bl_available" -ge 0 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; then
for _i in 1 2 3 4 5; do
nap 1
bl_memory_read
@@ -1018,10 +1086,16 @@ case $mode in
for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
printf '%s' "$_mode" > /tmp/.bl-zram
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
if [ "$_mode" = 1 ]; then bl_zram_wait "${_pids[@]}"; else nap 5; fi
_bl_zram_targets=("${_pids[@]}")
[ "${4:-}" != defer ] || return 0
bl_zram_finish "$_mode" "${_pids[@]}"
}
bl_zram_finish() {
local _mode=$1
shift
if [ "$_mode" = 1 ]; then bl_zram_wait "$@"; else nap 5; fi
bl_zram_scan
bl_zram_pick "$_which"
step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))"
step "zRAM: done ($(bl_zram_usage "$@"))"
}
bl_game_focused() {
if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then
@@ -1030,7 +1104,7 @@ case $mode in
local id
id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \
"$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1)
[ -n "$id" ] || return 1
[ -n "$id" ] || return "${1:-1}"
case " ${_bl_apps-} " in
*" $id "*) return 0 ;;
esac
@@ -1048,6 +1122,8 @@ case $mode in
}
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=()
_bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=()
_bl_sample_at= _bl_sample_available=0 _bl_sample_gpu=0 _bl_sample_unevictable=0 _bl_sample_shmem=0
while kill -0 $$ 2>/dev/null; do
bl_zram_scan
bl_memory_read
@@ -1074,8 +1150,11 @@ case $mode in
_bl_backoff=30
fi
fi
_bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall
bl_client_pressure defer
_bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall
bl_session_pressure
bl_client_pressure
bl_client_pressure_finish
if [ "$_bl_game" = 1 ] && bl_game_focused; then
if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then
_bl_since=$SECONDS _bl_since_apps=$_bl_apps
@@ -1105,6 +1184,10 @@ case $mode in
&& [ "${BL_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
/usr/local/bin/droiddeck-launcher-cores "$BL_LAUNCH_DIR/agent/focus.json" 2>&1 &
fi
if [ "${BL_PACE_CORES:-1}" != 0 ] && [ -n "${DROIDDECK_HUD_FRAMES:-}" ] && [ -z "${BL_DESKTOP:-}" ] \
&& [ -x /usr/local/bin/droiddeck-pace-cores ]; then
/usr/local/bin/droiddeck-pace-cores "$DROIDDECK_HUD_FRAMES" 2>&1 &
fi
if [ "$steam_x64" = 0 ]; then
step "registering the app's game library with Steam"
@@ -1118,7 +1201,7 @@ case $mode in
step "adding the app's own games to the client's library"
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
droiddeck-seed-redists "$steam_root" || true
DROIDDECK_SEED_LATER=1 droiddeck-seed-redists "$steam_root" || true
else
_bl_x64_tool=$(droiddeck-steam-x64 --default-tool)
if [ -n "$_bl_x64_tool" ]; then
@@ -1132,7 +1215,7 @@ case $mode in
if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
fi
droiddeck-seed-redists "$steam_root" || true
DROIDDECK_SEED_LATER=1 droiddeck-seed-redists "$steam_root" || true
fi
if [ -n "${BL_SHADER_PRECACHE:-}" ]; then
droiddeck-steam-shaders "$BL_SHADER_PRECACHE" "$XDG_DATA_HOME/Steam" \
@@ -1196,6 +1279,33 @@ case $mode in
pv=${pv# }
pv=${pv:-$2}
}
# Steam logs its saved Scaling Mode and Filter at startup but does not
# write them to gamescope until they are changed in the QAM, so a saved
# Fill shows in the menu while the game stays on Auto. Replay the values
# it logged since it last started, once, if gamescope has none yet.
scaling_restored=
restore_steam_scaling() {
local log="$steam_root/logs/systemperfmanager.txt" mode= filter= v
[ -n "$scaling_restored" ] && return 0
scaling_restored=1
xprop -root GAMESCOPE_NEW_SCALING_SCALER 2>/dev/null | grep -q '= ' && return 0
[ -f "$log" ] || return 0
while read -r v; do
case $v in
client*) mode= filter= ;;
mode\ *) mode=${v#mode } ;;
filter\ *) filter=${v#filter } ;;
esac
done < <(sed -n 's/.*\] Client version:.*/client/p; s/.*\] Set scaling mode: \([0-9]*\).*/mode \1/p; s/.*\] Set scaling filter: \([0-9]*\).*/filter \1/p' "$log")
case $mode in [1-5]) bl_xprop_set_all GAMESCOPE_NEW_SCALING_SCALER $((mode - 1)) \
&& echo "== scaling: applied the client's saved scaling mode $mode" ;; esac
case $filter in
1) v=0 ;; 2) v=1 ;; 3) v=2 ;; *) v= ;;
esac
[ -n "$v" ] && bl_xprop_set_all GAMESCOPE_NEW_SCALING_FILTER "$v" \
&& echo "== scaling: applied the client's saved scaling filter $filter"
return 0
}
tmode= app= prev=
while read -r line; do
case $line in
@@ -1214,6 +1324,7 @@ case $mode in
printf '%s\n' "$app" > "$BL_LAUNCH_DIR/steam-focused-app.tmp" && mv -f "$BL_LAUNCH_DIR/steam-focused-app.tmp" "$BL_LAUNCH_DIR/steam-focused-app"
fi
fi
case $pv in ''|0|769|*[!0-9]*) ;; *) restore_steam_scaling ;; esac
[ "$restore" = 1 ] || continue
case $pv in ''|*[!0-9]*) prev=; continue ;; esac
if [ "$prev" = 769 ] && [ "$pv" != 769 ]; then
@@ -1396,6 +1507,8 @@ case $mode in
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
trap decky_stop TERM INT HUP
decky_exits=0
# The guest has no "deck" user, which Decky otherwise requires at startup.
export UNPRIVILEGED_USER=root
while :; do
if [ "$decky_arch" = x86_64 ]; then /usr/local/bin/droiddeck-fex run --mode on -- "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
else "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
@@ -1458,6 +1571,9 @@ case $mode in
_bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing)
echo "== steam: browser UI in software (Mali bridge)"
elif [ "${_bl_cef[0]}" = -cef-force-gpu ]; then
# With Steam's own web helper layout the Deck UI's footer and overlays flicker on the bridge
# (Mali-G78 MP14). ANGLE on Vulkan without Chromium's Vulkan compositing draws them steadily.
: "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle="${BL_VKBRIDGE_CEF_ANGLE:-vulkan}")
fi
[ "${BL_VKBRIDGE_CEF_LOG:-0}" = 1 ] && _bl_cef+=(-cef-enable-logging=stderr -cef-v=1)
@@ -71,7 +71,11 @@ def store_game(game):
def manifest_ids(steamapps, name):
matches = []
for manifest in Path(steamapps).glob("appmanifest_*.acf"):
try:
manifests = list(Path(steamapps).glob("appmanifest_*.acf"))
except OSError:
return matches
for manifest in manifests:
try:
install = re.search(r'"installdir"\s*"([^"\\]*)"', manifest.read_text(), re.I)
if install and install[1] == name:
@@ -81,13 +85,21 @@ def manifest_ids(steamapps, name):
return matches
def identify(game):
def manifest_identity(game):
folder = Path(game["folder"])
steamapps = folder.parent.parent
for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]:
matches = [appid for appid in manifest_ids(library, folder.name) if appid != SPACEWAR]
if matches:
return matches[0] if len(matches) == 1 else None
return (matches[0], library) if len(matches) == 1 else None
return False
def identify(game):
folder = Path(game["folder"])
found = manifest_identity(game)
if found is not False:
return found[0] if found is not None else None
ids = set()
for parent in {folder, Path(game["exe"]).parent}:
try:
@@ -508,6 +520,57 @@ def release(steam_root, game, stale, reason):
print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}")
PREFIX_LINKS = ".droiddeck-prefix-links.json"
def steam_prefix(steam_root, game):
identity = manifest_identity(game)
if not identity or not identity[0]:
return None, None
appid, steamapps = identity
installed = steamapps == Path(game["folder"]).parent.parent
for library in [steamapps.parent] if installed else dict.fromkeys([steamapps.parent] + libraries(steam_root)):
prefix = library / "steamapps/compatdata" / str(appid)
if (prefix / "pfx/drive_c").is_dir():
return appid, str(prefix)
return appid, None
def share_prefix(steam_root, game):
shortcut = Path(steam_root) / "steamapps/compatdata" / str(game["appid"] & 0xFFFFFFFF)
record = Path(steam_root) / "steamapps" / PREFIX_LINKS
links = read_json(record, {})
if not isinstance(links, dict):
links = {}
before = dict(links)
key = str(shortcut)
name = game.get("name", "game")
appid, target = steam_prefix(steam_root, game)
try:
current = os.readlink(shortcut) if os.path.islink(shortcut) else None
if current is not None and links.get(key) == current and current != target:
if target is not None or (not os.path.exists(shortcut) and Path(current).parent.parent.is_dir()):
shortcut.unlink()
current = None
if current is None:
links.pop(key, None)
if current is None and os.path.lexists(shortcut):
if target is not None:
print(f"droiddeck-steam-games: {name} keeps its own prefix; Steam app {appid} saves are in {target}")
elif current is None and target is not None:
shortcut.parent.mkdir(parents=True, exist_ok=True)
shortcut.symlink_to(target)
links[key] = target
print(f"droiddeck-steam-games: {name} shares the saves prefix of Steam app {appid}")
except OSError as error:
print(f"droiddeck-steam-games: {name} keeps its own prefix ({error})")
if links != before:
try:
save_json(record, links)
except OSError as error:
print(f"droiddeck-steam-games: prefix links not recorded ({error})")
def route(steam_root, acct, games):
snapshot = read_json(Path(acct) / "config" / STATE, {})
if not isinstance(snapshot, dict):
@@ -557,6 +620,7 @@ def route(steam_root, acct, games):
elif named and seeded(steamapps, game, appid):
routes[str(game["appid"])] = appid
continue
share_prefix(steam_root, game)
shortcuts.append(game)
try:
park(steamapps)
@@ -449,7 +449,11 @@ mkdir -p "$srt_libs"
for d in "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/lib/x86_64-linux-gnu \
"$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/usr/lib/x86_64-linux-gnu; do
[ -d "$d" ] || continue
for f in "$d"/*.so*; do [ -e "$srt_libs/$(basename "$f")" ] || ln -s "$f" "$srt_libs/"; done
for f in "$d"/*.so*; do
[ -e "$f" ] || [ -L "$f" ] || continue
s="$srt_libs/$(basename "$f")"
{ [ -e "$s" ] || [ -L "$s" ]; } || ln -s "$f" "$srt_libs/"
done
done
FEX_ROOTFS=$ROOTFS /usr/local/bin/FEX "$ROOTFS/usr/sbin/ldconfig.real" -n "$srt_libs" >>"$LOG" 2>&1 || step "ldconfig on $srt_libs failed"
sniper_compat=$X64_HOME/sniper-compat
@@ -458,6 +462,7 @@ mkdir -p "$sniper_compat"
hb=$(ls "$srt_libs"/libharfbuzz.so.0.* 2>/dev/null | head -n 1)
if [ -n "$hb" ]; then ln -s "$hb" "$sniper_compat/libharfbuzz.so.0"; else step "warning: no HarfBuzz in Valve's runtime for the newer-runtime titles"; fi
for f in "$srt_libs"/*; do
[ -e "$f" ] || [ -L "$f" ] || continue
n=$(basename "$f")
if [ -e "$ROOTFS/usr/lib/x86_64-linux-gnu/$n" ] || [ -e "$ROOTFS/lib/x86_64-linux-gnu/$n" ]; then rm -f "$f"; fi
done
@@ -48,14 +48,14 @@ def sidecar_at(folder):
return sidecar
def find_store_game(argv):
def find_store_game(argv, depth=MAX_DEPTH):
for raw in argv:
arg = raw.strip().strip('"').strip("'").replace("\\", "/")
low = arg.lower()
if not (low.endswith(LAUNCHER) or low.endswith(".exe") or low.endswith(".bat")) or "/" not in arg:
continue
folder = Path(arg).parent
for _ in range(MAX_DEPTH):
for _ in range(depth):
sidecar = sidecar_at(folder)
if sidecar is not None:
return folder, sidecar
@@ -65,6 +65,21 @@ def find_store_game(argv):
return None
def store_launcher(path):
real = os.path.realpath(path)
for start in dict.fromkeys([os.path.abspath(path), real]):
found = find_store_game([start], depth=len(Path(start).parts))
if found is None:
continue
folder, sidecar = found
launcher, exe = str(sidecar.get("launcher") or ""), str(sidecar.get("exe") or "")
if not launcher or not exe or (folder / launcher).is_symlink() or not (folder / launcher).is_file():
continue
if os.path.realpath(folder / exe).lower() == real.lower():
return str(folder / launcher)
return None
def drop_stale(folder, now=None):
code = folder / EPIC_CODE
try:
@@ -271,6 +286,12 @@ def cloud_on(sidecar):
def exited(argv, code=0):
found = find_store_game(argv)
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
if found is not None and launch_dir and str(found[1].get("store")) == "rockstar":
ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": str(found[1].get("id"))}, timeout=1.0)
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH")
if compat_data:
(Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True)
return 0
if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \
and os.access(EPIC_CLIENT, os.X_OK):
try:
@@ -292,6 +313,241 @@ def exited(argv, code=0):
UBISOFT_DIR = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher"
UBISOFT_WINDOWS_DIR = "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\"
UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/UbisoftConnectInstaller.exe"
ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar")
SERVICE_WAIT = 300.0
ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher"
ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas",
"gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"}
def rockstar_sdk(folder, sidecar):
if str(sidecar.get("id")) in ("gta4", "lanoire"):
return True
root = folder.resolve()
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
if not exe.is_relative_to(root):
return False
for directory in {root, exe.parent}:
if directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll")
for p in directory.iterdir()):
return True
if str(sidecar.get("id")) in ROCKSTAR_TITLES:
return False
level = [root]
for _ in range(4):
children = []
for directory in level:
for path in directory.iterdir():
if path.is_symlink():
continue
if path.name.lower() == "title.rgl" and path.is_file() and path.resolve().is_relative_to(root) and 112 <= path.stat().st_size <= 1048576:
with path.open("rb") as source:
if source.read(4) == b"RGLM":
return True
if len(children) < 256 and path.is_dir() and path.resolve().is_relative_to(root):
children.append(path)
level = children
return False
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
pfx = Path(compat_data) / "pfx"
launcher = r"C:\Program Files\Rockstar Games\Launcher"
values = [(r"Rockstar Games\Launcher", launcher)]
if title:
values.append(("Rockstar Games\\" + title, windows_path(str(folder))))
entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values]
if sdk_arch:
entries.append((r"Software\Rockstar Games\Rockstar Games Social Club", r"C:\Program Files\Rockstar Games\Social Club"))
program = "Program Files (x86)" if sdk_arch == "x86" else "Program Files"
entries.append((r"Software\Wow6432Node\Rockstar Games\Rockstar Games Social Club", "C:\\" + program + r"\Rockstar Games\Social Club"))
reg = pfx / "system.reg"
if all(has_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries):
return True
if wait_for_server(pfx, 2):
return all(set_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries)
with tempfile.TemporaryDirectory(prefix="droiddeck-rockstar-") as temp:
path = Path(temp) / "install.reg"
text = "Windows Registry Editor Version 5.00\r\n\r\n"
text += "\r\n".join('[HKEY_LOCAL_MACHINE\\%s]\r\n"InstallFolder"="%s"\r\n' % (key, reg_escape(value)) for key, value in entries)
path.write_text(text, encoding="utf-16")
result = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(path))],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45)
return result.returncode == 0
def rockstar_runtime(folder, exe, compat_data, arch):
if arch == "x86":
rockstar_runtime(folder, exe, compat_data, "x64")
pfx = Path(compat_data) / "pfx"
target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club"
if not target.resolve().is_relative_to(pfx.resolve()):
raise ValueError("invalid Social Club destination")
required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ())
marker = target / ".droiddeck-installing"
if all((target / name).is_file() for name in required) and not marker.exists():
return "present"
root = folder.resolve()
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None)
if installer is None:
return "game-runtime"
tool = shutil.which("7z")
if not tool:
return "no-unpacker"
listing = subprocess.run([tool, "l", "-t7z", "-slt", "-ba", str(installer)], capture_output=True,
stdin=subprocess.DEVNULL, timeout=30)
if listing.returncode:
return "installer-unreadable"
entries, size = [], 0
for block in listing.stdout.decode("utf-8", "replace").split("\n\n"):
fields = dict(line.split(" = ", 1) for line in block.splitlines() if " = " in line)
name = fields.get("Path", "").replace("\\", "/")
if not name.startswith(arch + "/"):
continue
if ".." in name.split("/") or ":" in name or fields.get("Symbolic Link") or fields.get("Hard Link"):
raise ValueError("invalid Social Club archive path")
entry_size = int(fields.get("Size", "0"))
if entry_size < 0:
raise ValueError("invalid Social Club member size")
size += entry_size
entries.append(name)
if not entries or len(entries) > 2048 or size > 768 * 1024 * 1024:
raise ValueError("invalid Social Club archive size")
with tempfile.TemporaryDirectory(prefix="droiddeck-socialclub-") as temporary:
result = subprocess.run([tool, "x", "-t7z", "-y", "-o" + temporary, str(installer), arch + "/*"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, timeout=180)
source = Path(temporary) / arch
if result.returncode or not all((source / name).is_file() for name in required):
return "installer-incomplete"
target.mkdir(parents=True, exist_ok=True)
if marker.is_symlink():
raise ValueError("invalid Social Club install marker")
marker.touch()
for path in source.rglob("*"):
if path.is_symlink() or not path.resolve().is_relative_to(source.resolve()):
raise ValueError("invalid Social Club archive member")
if not path.is_file():
continue
output = target / path.relative_to(source)
if not output.resolve().is_relative_to(pfx.resolve()):
raise ValueError("invalid Social Club output path")
output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=output.parent, delete=False) as stage:
stage_path = Path(stage.name)
try:
with path.open("rb") as stream:
shutil.copyfileobj(stream, stage)
except BaseException:
stage_path.unlink(missing_ok=True)
raise
os.replace(stage_path, output)
marker.unlink()
return "installed"
def fetch_service(service, store, launch_dir, ask_app=None):
if service.is_file():
return True
if not launch_dir:
return False
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT)
return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file()
def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_app=None):
if not compat_data:
return "no-prefix"
target = Path(compat_data) / "pfx" / ROCKSTAR_FOLDER
if not target.resolve().is_relative_to((Path(compat_data) / "pfx").resolve()):
return "invalid-service-path"
config = target / "launch.json"
config.unlink(missing_ok=True)
legacy = str(sidecar.get("id")) in ROCKSTAR_TITLES
sdk = rockstar_sdk(folder, sidecar)
title = ROCKSTAR_TITLES.get(str(sidecar.get("id")))
if not launch_dir:
return "no-channel"
root = folder.resolve()
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
if not exe.is_relative_to(root):
return "invalid-game-path"
workdir = (folder / str(sidecar["workdir"])).resolve() if sidecar.get("workdir") is not None else exe.parent
if not workdir.is_relative_to(root) or not exe.is_file() or legacy and not any((p / "MTLX.dll").is_file() for p in (root, exe.parent)):
return "invalid-game-path"
args = sidecar.get("args") or []
if not isinstance(args, list) or any(not isinstance(arg, str) or "\0" in arg for arg in args):
return "invalid-game-arguments"
with exe.open("rb") as source:
if source.read(2) != b"MZ":
return "invalid-game-exe"
source.seek(0x3c)
raw = source.read(4)
if len(raw) != 4:
return "invalid-game-exe"
source.seek(int.from_bytes(raw, "little"))
signature = source.read(6)
if len(signature) != 6 or signature[:4] != b"PE\0\0" or signature[4:] not in (b"\x4c\x01", b"\x64\x86"):
return "invalid-game-exe"
service = ROCKSTAR_SERVICE / ("Launcher32.exe" if signature[4:] == b"\x4c\x01" else "Launcher64.exe")
if not fetch_service(service, "rockstar", launch_dir, ask_app):
return "no-service"
made = "present" if (Path(compat_data) / "pfx/user.reg").is_file() else create_prefix(compat_data, proton)
if made not in ("created", "present"):
return "prefix-" + made
arch = "x86" if signature[4:] == b"\x4c\x01" else "x64"
if sdk:
log("rockstar runtime: " + rockstar_runtime(folder, exe, compat_data, arch))
if not rockstar_registry(folder, title, compat_data, proton, sdk_arch=arch if sdk else None):
return "registry-unavailable"
target.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(prefix="Launcher-", suffix=".exe", dir=target, delete=False) as temporary:
temporary_path = Path(temporary.name)
try:
with service.open("rb") as source:
shutil.copyfileobj(source, temporary)
except BaseException:
temporary_path.unlink(missing_ok=True)
raise
os.replace(temporary_path, target / "Launcher.exe")
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "rockstar-launch", "store": "rockstar", "id": str(sidecar.get("id"))}, timeout=120.0)
if not isinstance(answer, dict) or not answer.get("ok"):
return "session-" + (str(answer.get("reason") or "refused") if isinstance(answer, dict) else "timeout")
if legacy and (not isinstance(answer.get("material"), str) or not re.fullmatch(r"[0-9A-Fa-f]{640}", answer["material"])):
return "invalid-material"
expires = answer.get("expiresAt")
if not isinstance(expires, int) or not time.time() * 1000 < expires <= time.time() * 1000 + 120_000:
return "invalid-expiry"
launch = {"folder": windows_path(str(root)), "exe": windows_path(str(exe)), "workdir": windows_path(str(workdir)),
"args": args, "expiresAt": expires}
if legacy:
launch.update(pipe=answer.get("pipe"), material=answer["material"])
if sdk:
session = answer.get("session")
if not isinstance(session, dict) or not isinstance(session.get("accountId"), str) \
or not re.fullmatch(r"[1-9][0-9]{0,19}", session["accountId"]) or int(session["accountId"]) > 2**64 - 1 \
or any(not isinstance(session.get(key), str) or not session[key] or "\0" in session[key]
or len(session[key].encode("utf-8")) > limit for key, limit in (("identity", 512), ("ticket", 49152))):
return "invalid-sdk-session"
launch["session"] = {key: session[key] for key in ("accountId", "identity", "ticket")}
if "titleId" in session:
if not isinstance(session["titleId"], str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", session["titleId"]):
return "invalid-sdk-title"
launch["session"]["titleId"] = session["titleId"]
if len(json.dumps(launch).encode("utf-8")) > 65536:
return "handoff-too-large"
with tempfile.NamedTemporaryFile(mode="w", prefix="launch-", suffix=".json", dir=target, delete=False) as temporary:
temporary_path = Path(temporary.name)
try:
json.dump(launch, temporary)
except BaseException:
temporary_path.unlink(missing_ok=True)
raise
os.replace(temporary_path, config)
return "ready"
UBISOFT_CACHE = Path("/root/.cache/droiddeck/ubisoft")
UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
UBISOFT_SERVICE = Path("/usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe")
@@ -477,7 +733,7 @@ def prepare_ubisoft(folder, sidecar, compat_data, launch_dir, proton="", ask_app
product = ubisoft_product(sidecar)
if product is None:
return "no-product"
if not UBISOFT_SERVICE.is_file():
if not fetch_service(UBISOFT_SERVICE, "ubisoft", launch_dir, ask_app):
return "no-service"
made = create_prefix(compat_data, proton) if not (Path(compat_data) / "pfx/user.reg").is_file() else "present"
if made not in ("present", "created"):
@@ -1326,6 +1582,19 @@ def main(argv):
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
if store == "rockstar":
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
if compat_data:
(Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True)
return STORE_GAME
try:
state = prepare_rockstar(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", ""))
except (OSError, ValueError, subprocess.TimeoutExpired):
state = "preparation-failed"
log("rockstar %s: %s" % (game, state))
if state != "ready" and launch_dir:
ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": game}, timeout=1.0)
return STORE_GAME if state == "ready" else RAN_FAILED
if store == "ubisoft":
try:
log("ubisoft %s: %s" % (game, prepare_ubisoft(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", ""))))
@@ -513,13 +513,15 @@ def save_state(compat, state):
os.replace(temp, compat / STATE)
def foreign_component(rel, path, machines):
def foreign_component(rel, path, machines, dist=None):
parts = Path(rel).parts
folder = parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None
if not machines or folder not in PE_MACHINES or not rel.lower().endswith(".dll"):
return False
machine = pe_machine(path)
return machine is not None and not machine_compatible(path, machines[folder][1], machine)
libdir, compatible = machines[folder]
builtins = dist / libdir if dist else None
return machine is not None and not machine_compatible(path, compatible, machine, builtins)
def pending_for(app_id, pending=PENDING):
@@ -580,6 +582,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
skipped = set()
placed_stems = set()
machines = PE["proton_pe_machines"](proton, env) if proton else None
dist = Path(proton).parent / "files/lib/wine" if proton else None
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
@@ -620,7 +623,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
kept_requires[cid] = list(requires)
values += [(cid, value) for value in registry]
for rel, src in files:
foreign = foreign_component(rel, src, machines)
foreign = foreign_component(rel, src, machines, dist)
if foreign:
skipped.add(Path(rel).stem.lower())
changed = False
@@ -641,7 +644,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
path = existing(pfx / rel)
saved = compat / BACKUP / rel
if saved.is_file():
if foreign_component(rel, saved, machines):
if foreign_component(rel, saved, machines, dist):
if path is not None and not path.is_symlink():
path.unlink()
continue
@@ -1,5 +1,5 @@
#!/usr/bin/python3
import re
import os
from pathlib import Path
@@ -76,18 +76,105 @@ def pe_has_arm64ec_metadata(path):
return False
# Only x64 code and members of the same runtime family import these, so an x64 copy loads in an
# ARM64EC prefix, and games check for a newer version than Wine's builtins report.
VC_RUNTIME = re.compile(r"(msvc[pr]\d.*|vcruntime\d.*|vcomp\d*|vcamp\d.*|vccorlib\d.*|concrt\d.*|mfcm?\d.*)\.dll",
re.IGNORECASE)
def pe_imports(path):
try:
with open(path, "rb") as source:
image = source.read()
except OSError:
return None
try:
if image[:2] != b"MZ":
return None
pe_offset = int.from_bytes(image[60:64], "little")
if image[pe_offset:pe_offset + 4] != b"PE\0\0":
return None
section_count = int.from_bytes(image[pe_offset + 6:pe_offset + 8], "little")
optional_size = int.from_bytes(image[pe_offset + 20:pe_offset + 22], "little")
optional = pe_offset + 24
magic = int.from_bytes(image[optional:optional + 2], "little")
directories = optional + (112 if magic == 0x20B else 96)
if directories > len(image):
return None
directory_count = int.from_bytes(image[directories - 4:directories], "little")
sections = []
for index in range(min(section_count, 96)):
entry = optional + optional_size + index * 40
if entry + 40 > len(image):
return None
sections.append((int.from_bytes(image[entry + 12:entry + 16], "little"),
max(int.from_bytes(image[entry + 8:entry + 12], "little"),
int.from_bytes(image[entry + 16:entry + 20], "little")),
int.from_bytes(image[entry + 20:entry + 24], "little")))
def offset(rva):
for address, size, raw in sections:
if address <= rva < address + size:
return rva - address + raw
return None
names = set()
for directory, step, field in ((1, 20, 12), (13, 32, 4)):
if directory >= directory_count:
continue
if directories + directory * 8 + 8 > len(image):
return None
rva = int.from_bytes(image[directories + directory * 8:directories + directory * 8 + 4], "little")
entry = offset(rva) if rva else None
if rva and entry is None:
return None
while entry is not None:
if entry + step > len(image):
return None
name_rva = int.from_bytes(image[entry + field:entry + field + 4], "little")
if not name_rva:
break
name = offset(name_rva)
end = image.find(b"\0", name) if name is not None else -1
if end < 0:
return None
names.add(image[name:end].decode("ascii", "replace").lower())
entry += step
return names
except (IndexError, ValueError):
return None
def machine_compatible(path, machines, machine=None):
PROGRAM_IMPORTS = {}
def program_imports(builtins):
key = str(builtins)
if key not in PROGRAM_IMPORTS:
try:
files = {name.lower(): Path(builtins) / name for name in os.listdir(builtins)}
except OSError:
files = None
pending = [name for name in files or () if name.endswith(".exe") and pe_machine(files[name]) in (None, 0xAA64)]
seen = set()
while pending and files is not None:
name = pending.pop()
if name in seen:
continue
seen.add(name)
if name in files:
imports = pe_imports(files[name])
if imports is None:
files = None
else:
pending.extend(imports)
PROGRAM_IMPORTS[key] = None if files is None else frozenset(name for name in seen if name.endswith(".dll"))
return PROGRAM_IMPORTS[key]
def machine_compatible(path, machines, machine=None, builtins=None, name=None):
machine = pe_machine(path) if machine is None else machine
if machine == 0x8664 and 0xA641 in machines and VC_RUNTIME.fullmatch(Path(path).name):
return True
if machine == 0x8664 and 0xA641 in machines:
if pe_has_arm64ec_metadata(path):
return True
imported = program_imports(builtins) if builtins is not None else None
return imported is not None and (name or Path(path).name).lower() not in imported
if machine == 0x8664 and pe_has_arm64ec_metadata(path):
return 0xA641 in machines
return False
return machine in machines
@@ -197,6 +197,172 @@ def wine(argv, source_env=None):
pass
# PlayFab Game Saves picks its provider from the Gaming Runtime unless HKLM\SOFTWARE\Microsoft\GamingServices
# ForceUseInprocGameSaves is set, and its in-process provider needs a save folder the title never passes on Windows.
# The runtime has no GRTS saves, so titles such as Forza Horizon 6 stop with E:0-17. xodus-nexus ships a proxy
# (scripts/runtime-compat/playfab-save-folder.c, MIT) that keeps the title's own SDK as nexus_pgs_native.dll and
# supplies both; this stages it the same way.
PGS_PROXY = RUNTIME / 'compat' / 'PlayFabGameSave.dll'
PGS_NATIVE = 'nexus_pgs_native.dll'
PGS_EXPORTS = (
'PFGameSaveFilesAddUserWithUiAsync', 'PFGameSaveFilesAddUserWithUiResult', 'PFGameSaveFilesGetFolder',
'PFGameSaveFilesGetFolderSize', 'PFGameSaveFilesGetRemainingQuota', 'PFGameSaveFilesGetSaveDescriptionForDebug',
'PFGameSaveFilesGetSaveDescriptionSizeForDebug', 'PFGameSaveFilesGetStatsJsonForDebug',
'PFGameSaveFilesGetStatsJsonSizeForDebug', 'PFGameSaveFilesInitialize', 'PFGameSaveFilesIsConnectedToCloud',
'PFGameSaveFilesPauseUploadForDebug', 'PFGameSaveFilesResetCloudAsync', 'PFGameSaveFilesResetCloudResult',
'PFGameSaveFilesResumeUploadForDebug', 'PFGameSaveFilesSetActiveDeviceChangedCallback',
'PFGameSaveFilesSetActiveDevicePollForceChangeForDebug', 'PFGameSaveFilesSetActiveDevicePollIntervalForDebug',
'PFGameSaveFilesSetForceNullPendingManifestForDebug', 'PFGameSaveFilesSetForceOutOfStorageErrorForDebug',
'PFGameSaveFilesSetForceSyncFailedErrorForDebug', 'PFGameSaveFilesSetMockDataFolderForDebug',
'PFGameSaveFilesSetMockDeviceIdForDebug', 'PFGameSaveFilesSetMockForceOfflineForDebug',
'PFGameSaveFilesSetMockManifestOffsetForDebug', 'PFGameSaveFilesSetMockRootFolderForDebug',
'PFGameSaveFilesSetSaveDescriptionAsync', 'PFGameSaveFilesSetSaveDescriptionResult',
'PFGameSaveFilesSetUiActiveDeviceContentionResponse', 'PFGameSaveFilesSetUiCallbacks',
'PFGameSaveFilesSetUiConflictResponse', 'PFGameSaveFilesSetUiOutOfStorageResponse',
'PFGameSaveFilesSetUiProgressResponse', 'PFGameSaveFilesSetUiSyncFailedResponse',
'PFGameSaveFilesSetWriteManifestsToDiskForDebug', 'PFGameSaveFilesUiProgressGetProgress',
'PFGameSaveFilesUninitializeAsync', 'PFGameSaveFilesUninitializeResult', 'PFGameSaveFilesUploadWithUiAsync',
'PFGameSaveFilesUploadWithUiResult',
)
def pe_exports(data):
"""(export address table size, [(name, ordinal index, forwarder or None) for each named export]) of an x64
PE image, or None. The table size also counts exports that have no name."""
def u16(offset):
return int.from_bytes(data[offset:offset + 2], 'little')
def u32(offset):
return int.from_bytes(data[offset:offset + 4], 'little')
def string(offset):
end = data.find(b'\0', offset)
return None if offset is None or end < 0 else data[offset:end].decode('ascii', 'replace')
if len(data) < 256 or data[:2] != b'MZ':
return None
pe = u32(60)
if data[pe:pe + 4] != b'PE\0\0' or u16(pe + 4) != 0x8664:
return None
count, optional_size = u16(pe + 6), u16(pe + 20)
optional = pe + 24
if optional_size < 120 or u16(optional) != 0x20B or u32(optional + 108) < 1:
return None
sections = optional + optional_size
def offset_of(address):
for index in range(count):
section = sections + index * 40
start, size, raw = u32(section + 12), u32(section + 16), u32(section + 20)
if start <= address < start + size and raw + address - start < len(data):
return raw + address - start
return None
directory_rva, directory_size = u32(optional + 112), u32(optional + 116)
directory = offset_of(directory_rva)
if directory is None or u32(directory + 16) != 1:
return None
functions, names = u32(directory + 20), u32(directory + 24)
function_table, name_table, ordinal_table = (offset_of(u32(directory + 28)), offset_of(u32(directory + 32)),
offset_of(u32(directory + 36)))
if None in (function_table, name_table, ordinal_table):
return None
exports = []
for index in range(names):
name = string(offset_of(u32(name_table + 4 * index)))
ordinal = u16(ordinal_table + 2 * index)
address = u32(function_table + 4 * ordinal) if ordinal < functions else 0
if name is None or not address:
return None
forward = string(offset_of(address)) if directory_rva <= address < directory_rva + directory_size else None
exports.append((name, ordinal, forward))
return functions, exports
def playfab_sdk(data):
"""The PlayFab Game Saves SDK the proxy was written for: exactly its 40 exports, all named, none forwarded."""
parsed = pe_exports(data)
if parsed is None or parsed[0] != len(PGS_EXPORTS):
return False
exports = parsed[1]
return ([(name, ordinal) for name, ordinal, _ in exports] == list(zip(PGS_EXPORTS, range(len(PGS_EXPORTS))))
and all(forward is None for _, _, forward in exports))
def playfab_proxy(data):
"""A save-folder proxy (this one or an earlier build): the same 40 exports, forwarding into nexus_pgs_native."""
parsed = pe_exports(data)
if parsed is None or parsed[0] != len(PGS_EXPORTS):
return False
exports = parsed[1]
return ([name for name, _, _ in exports] == list(PGS_EXPORTS)
and any((forward or '').startswith(PGS_NATIVE[:-4] + '.') for _, _, forward in exports))
def kept_sdk(native):
"""True when nexus_pgs_native.dll is a regular file holding a recognised SDK."""
return not native.is_symlink() and native.is_file() and playfab_sdk(native.read_bytes())
def replace_file(directory, name, data):
descriptor, temporary = tempfile.mkstemp(prefix='.droiddeck-pgs-', dir=directory)
try:
with os.fdopen(descriptor, 'wb') as file:
file.write(data)
file.flush()
os.fsync(file.fileno())
os.chmod(temporary, 0o644)
os.replace(temporary, Path(directory) / name)
except BaseException:
try:
os.unlink(temporary)
except OSError:
pass
raise
def stage_playfab_proxy(folder):
"""Put the save-folder proxy in front of every PlayFab Game Saves SDK in the game folder. Returns how many."""
try:
proxy = PGS_PROXY.read_bytes()
except OSError:
return 0
staged = 0
for root, _, files in os.walk(folder):
directory = Path(root)
for name in files:
if name.lower() != 'playfabgamesave.dll':
continue
path = directory / name
native = directory / PGS_NATIVE
try:
if path.is_symlink():
continue
data = path.read_bytes()
if playfab_sdk(data):
# A first launch, or a game update that brought a new SDK: the update's copy becomes the native one,
# but only in place of nothing or of an earlier SDK copy, never over an unknown file or a link.
if os.path.lexists(native) and not kept_sdk(native):
print('droiddeck-xbox: unknown %s next to the PlayFab Game Saves SDK in %s; left unchanged'
% (PGS_NATIVE, directory), file=sys.stderr)
continue
replace_file(directory, PGS_NATIVE, data)
elif not playfab_proxy(data):
print('droiddeck-xbox: PlayFab Game Saves SDK with unknown exports in %s; left unchanged' % directory,
file=sys.stderr)
continue
elif not kept_sdk(native):
print('droiddeck-xbox: PlayFab save proxy without its SDK in %s; left unchanged' % directory,
file=sys.stderr)
continue
if data != proxy:
replace_file(directory, name, proxy)
staged += 1
except OSError as error:
print('droiddeck-xbox: PlayFab save proxy not staged in %s (%s)' % (directory, error), file=sys.stderr)
return staged
def renew_lease(ask, channel, product, lease, stopped):
while not stopped.wait(15):
response = ask(channel, {'op': 'xbox-renew', 'id': product, 'lease': lease}, timeout=10)
@@ -243,6 +409,10 @@ def launch(command, env):
owned_env.pop(name, None)
if reply.get('playfab'):
owned_env['XODUS_XSTS_PLAYFAB'] = reply['playfab']
# The runtime mounts DLC only inside this backend-owned workspace (E_NOTIMPL without it).
mount_root = reply.get('mountRoot')
if isinstance(mount_root, str) and mount_root.startswith('/'):
owned_env['XODUS_MOUNT_ROOT'] = 'Z:' + mount_root.replace('/', '\\')
content = folder / '.xbox-content'
roots = []
if content.is_dir():
@@ -255,6 +425,12 @@ def launch(command, env):
pass
if roots:
owned_env['XODUS_CONTENT_ROOTS'] = ';'.join(roots)
# No DLL override for the proxy or the kept SDK: Wine has no builtin of either, so both load from the
# game folder as they are. Forcing them native-only (as Nexus does) made Forza Horizon 6 fail with E:0-0-4.
try:
stage_playfab_proxy(folder)
except Exception as error:
print('droiddeck-xbox: PlayFab save proxy skipped (%s)' % error, file=sys.stderr)
return wine([reply['exe']], owned_env)
finally:
stopped.set()
@@ -1540,7 +1540,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
auto = followers(state, current)
known = {app for app in state.get("owned", ()) if isinstance(app, str)} if isinstance(state.get("owned"), list) else set()
pinned = {app: current[app] for app in set(owned) - known
if current.get(app) in {TOOL, previous} | gone and app not in auto}
if app in current and current.get(app) in {TOOL, previous} | gone and app not in auto}
if pinned and isinstance(auto, dict):
state["auto"] = dict(auto, **pinned)
state["owned"] = sorted(set(owned), key=app_order)
-1
View File
@@ -81,7 +81,6 @@ static void cp_init(void) {
struct stat st;
void *map;
int fd;
if (strcmp(program_invocation_short_name, "plasmashell") != 0) return;
if (!cp_find_cond_bit()) return;
fd = open(CP_CTL, O_RDONLY | O_CLOEXEC);
if (fd < 0) return;
+291
View File
@@ -0,0 +1,291 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define DESCRIPTOR "user.wine.sd"
#define STORE "/.droiddeck-descriptors"
#define ENTRY_MAX (PATH_MAX * 2)
int bl_is_wineserver(void) __attribute__((visibility("hidden")));
static int store_seen;
static int kept(const char *name) {
return name != NULL && strcmp(name, DESCRIPTOR) == 0 && bl_is_wineserver();
}
static int store_root(char *out, size_t size) {
const char *prefix = getenv("WINEPREFIX");
int n;
if (prefix == NULL || prefix[0] != '/') return -1;
n = snprintf(out, size, "%s" STORE, prefix);
return n > 0 && (size_t)n < size ? n : -1;
}
static int store_exists(void) {
char root[PATH_MAX];
if (store_seen) return 1;
if (store_root(root, sizeof(root)) < 0) return 0;
store_seen = access(root, F_OK) == 0;
return store_seen;
}
static int entry_for(const char *path, char *out, size_t size, const char *suffix, int create) {
int used = store_root(out, size);
const char *part = path, *end;
if (used < 0 || path[0] != '/') return -1;
if (create && mkdir(out, 0700) != 0 && errno != EEXIST) return -1;
while (*part == '/') part++;
if (*part == '\0') return -1;
for (;;) {
size_t length;
const char *tail;
end = strchr(part, '/');
length = end ? (size_t)(end - part) : strlen(part);
tail = end ? ".d" : suffix;
if (length + strlen(tail) > NAME_MAX || used + length + strlen(tail) + 2 > size) return -1;
out[used++] = '/';
memcpy(out + used, part, length);
used += (int)length;
strcpy(out + used, tail);
used += (int)strlen(tail);
if (!end) break;
if (create && mkdir(out, 0700) != 0 && errno != EEXIST) return -1;
part = end + 1;
}
if (create) store_seen = 1;
return 0;
}
static int path_of(int fd, char *out, size_t size) {
char link[40];
ssize_t n;
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
n = readlink(link, out, size - 1);
if (n <= 0 || out[0] != '/') return -1;
out[n] = '\0';
return 0;
}
static int resolved(const char *path, char *out, size_t size) {
int fd, result;
if (path == NULL) return -1;
fd = open(path, O_PATH | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0) return -1;
result = path_of(fd, out, size);
close(fd);
return result;
}
static int entry_of(int fd, char *out, size_t size, int create) {
char path[PATH_MAX];
if (path_of(fd, path, sizeof(path)) != 0) return -1;
return entry_for(path, out, size, ".sd", create);
}
static ssize_t stored_read(int fd, void *value, size_t size) {
char entry[ENTRY_MAX];
struct stat st;
ssize_t got = 0;
int file;
if (entry_of(fd, entry, sizeof(entry), 0) != 0) return -2;
file = open(entry, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
if (file < 0) {
if (errno != ENOENT) return -2;
errno = ENODATA;
return -1;
}
if (fstat(file, &st) != 0) {
close(file);
return -2;
}
if (size == 0) {
close(file);
return (ssize_t)st.st_size;
}
if ((size_t)st.st_size > size) {
close(file);
errno = ERANGE;
return -1;
}
while (got < st.st_size) {
ssize_t n = read(file, (char *)value + got, (size_t)(st.st_size - got));
if (n <= 0) {
close(file);
return -2;
}
got += n;
}
close(file);
return got;
}
static int stored_write(int fd, const void *value, size_t size) {
char entry[ENTRY_MAX], fresh[ENTRY_MAX + 8];
size_t put = 0;
int file;
if (entry_of(fd, entry, sizeof(entry), 1) != 0) return -1;
snprintf(fresh, sizeof(fresh), "%s.new", entry);
file = open(fresh, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0600);
if (file < 0) return -1;
while (put < size) {
ssize_t n = write(file, (const char *)value + put, size - put);
if (n <= 0) {
close(file);
unlinkat(AT_FDCWD, fresh, 0);
return -1;
}
put += (size_t)n;
}
if (close(file) != 0 || renameat(AT_FDCWD, fresh, AT_FDCWD, entry) != 0) {
unlinkat(AT_FDCWD, fresh, 0);
return -1;
}
return 0;
}
ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) {
static ssize_t (*next)(int, const char *, void *, size_t);
ssize_t result;
if (next == NULL) next = dlsym(RTLD_NEXT, "fgetxattr");
if (next == NULL) {
errno = ENOSYS;
return -1;
}
result = next(fd, name, value, size);
if (result >= 0 || errno != ENOTSUP || !kept(name)) return result;
result = stored_read(fd, value, size);
if (result == -2) {
errno = ENOTSUP;
return -1;
}
return result;
}
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) {
static int (*next)(int, const char *, const void *, size_t, int);
int saved = errno, result;
if (next == NULL) next = dlsym(RTLD_NEXT, "fsetxattr");
if (next == NULL) {
errno = ENOSYS;
return -1;
}
result = next(fd, name, value, size, flags);
if (result == 0 || errno != ENOTSUP || !kept(name)) return result;
if (stored_write(fd, value, size) != 0) {
errno = ENOTSUP;
return -1;
}
errno = saved;
return 0;
}
int fremovexattr(int fd, const char *name) {
static int (*next)(int, const char *);
char entry[ENTRY_MAX];
int saved = errno, result;
if (next == NULL) next = dlsym(RTLD_NEXT, "fremovexattr");
if (next == NULL) {
errno = ENOSYS;
return -1;
}
result = next(fd, name);
if (result == 0 || errno != ENOTSUP || !kept(name)) return result;
if (entry_of(fd, entry, sizeof(entry), 0) != 0) {
errno = ENOTSUP;
return -1;
}
if (unlinkat(AT_FDCWD, entry, 0) != 0) {
errno = errno == ENOENT ? ENODATA : ENOTSUP;
return -1;
}
errno = saved;
return 0;
}
static int tracked(const char *path, char *out, size_t size) {
int saved = errno, found;
found = bl_is_wineserver() && store_exists() && resolved(path, out, size) == 0;
errno = saved;
return found;
}
static void forget(const char *path, int folder) {
char entry[ENTRY_MAX];
int saved = errno;
if (entry_for(path, entry, sizeof(entry), ".sd", 0) == 0) unlinkat(AT_FDCWD, entry, 0);
if (folder && entry_for(path, entry, sizeof(entry), ".d", 0) == 0) unlinkat(AT_FDCWD, entry, AT_REMOVEDIR);
errno = saved;
}
static void follow(const char *from, const char *to) {
static const char *const kinds[] = {".sd", ".d"};
char old[ENTRY_MAX], new[ENTRY_MAX];
int saved = errno;
for (size_t i = 0; i < 2; i++) {
if (entry_for(from, old, sizeof(old), kinds[i], 0) != 0) continue;
if (access(old, F_OK) != 0) {
if (i == 0 && entry_for(to, new, sizeof(new), kinds[i], 0) == 0) unlinkat(AT_FDCWD, new, 0);
continue;
}
if (entry_for(to, new, sizeof(new), kinds[i], 1) != 0 || renameat(AT_FDCWD, old, AT_FDCWD, new) != 0) {
if (i == 0) unlinkat(AT_FDCWD, old, 0);
}
}
errno = saved;
}
__attribute__((visibility("hidden")))
int bl_descriptor_unlink(const char *path, int (*real)(const char *)) {
char target[PATH_MAX];
int known = tracked(path, target, sizeof(target)), result = real(path);
if (result == 0 && known) forget(target, 0);
return result;
}
__attribute__((visibility("hidden")))
int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) {
char target[PATH_MAX];
int known = tracked(path, target, sizeof(target)), result = real(path);
if (result == 0 && known) forget(target, 1);
return result;
}
__attribute__((visibility("hidden")))
int bl_descriptor_remove(const char *path, int (*real)(const char *)) {
return bl_descriptor_rmdir(path, real);
}
__attribute__((visibility("hidden")))
int bl_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) {
char old[PATH_MAX], new[PATH_MAX];
int known = tracked(from, old, sizeof(old)), result = real(from, to);
if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new);
return result;
}
+61 -39
View File
@@ -83,6 +83,19 @@ static int notify = -1;
static int forked;
static struct { dev_t dev; int fuse; } devs[8];
static int ndevs;
// Libraries preloaded after this one can call back in while a lock is held (the native userland
// hook's inotify_add_watch calls mkdir() by name); such calls go straight to the next library.
static __thread int holding;
static void take(pthread_mutex_t *m) {
pthread_mutex_lock(m);
holding++;
}
static void give(pthread_mutex_t *m) {
holding--;
pthread_mutex_unlock(m);
}
static long long now_ns(void) {
struct timespec t;
@@ -109,32 +122,32 @@ static int enabled(void) {
}
static int eligible(const char *path) {
if (path == NULL || path[0] != '/' || !enabled()) return 0;
if (holding || path == NULL || path[0] != '/' || !enabled()) return 0;
const char *s = strstr(path, "/steamapps");
return s && (s[10] == '/' || s[10] == 0);
}
static int on_fuse(dev_t dev, const char *path) {
pthread_mutex_lock(&lock);
take(&lock);
for (int i = 0; i < ndevs; i++) {
if (devs[i].dev == dev) {
int fuse = devs[i].fuse;
pthread_mutex_unlock(&lock);
give(&lock);
return fuse;
}
}
pthread_mutex_unlock(&lock);
give(&lock);
struct statfs fs;
int saved = errno;
int fuse = statfs(path, &fs) == 0 && (unsigned long)fs.f_type == FUSE_MAGIC;
errno = saved;
pthread_mutex_lock(&lock);
take(&lock);
if (ndevs < 8) {
devs[ndevs].dev = dev;
devs[ndevs].fuse = fuse;
ndevs++;
}
pthread_mutex_unlock(&lock);
give(&lock);
return fuse;
}
@@ -404,7 +417,7 @@ __attribute__((constructor)) static void resolve(void) {
#pragma GCC diagnostic pop
static DIR *hit(const struct stat *st, struct handle *h, long long now) {
pthread_mutex_lock(&lock);
take(&lock);
if (!changing) pump(NULL, 0);
int slot = find(st->st_dev, st->st_ino);
if (slot >= 0 && same(table[slot], st) && now - table[slot]->filled < DIR_TTL_NS && records(table[slot]) == 0) {
@@ -413,7 +426,7 @@ static DIR *hit(const struct stat *st, struct handle *h, long long now) {
h->snap->used = now;
DIR *d = wrap(h);
if (d) {
pthread_mutex_unlock(&lock);
give(&lock);
return d;
}
unref(h->snap);
@@ -421,7 +434,7 @@ static DIR *hit(const struct stat *st, struct handle *h, long long now) {
} else if (slot >= 0) {
drop(slot);
}
pthread_mutex_unlock(&lock);
give(&lock);
return NULL;
}
@@ -462,11 +475,11 @@ static int above(struct handle *h, const char *path) {
}
static int track(struct handle *h, const char *path) {
pthread_mutex_lock(&lock);
take(&lock);
h->wd = watch(path, WATCHED);
DIR *d = h->wd >= 0 && above(h, path) ? wrap(h) : NULL;
if (d == NULL) let_go(h->wd, h->up, h->nup);
pthread_mutex_unlock(&lock);
give(&lock);
return d != NULL;
}
@@ -486,11 +499,11 @@ static void filling(struct handle *h, DIR *real, const struct stat *st, long lon
}
static void untrack(struct handle *h) {
pthread_mutex_lock(&lock);
take(&lock);
int i = registered((DIR *)h);
if (i >= 0) __atomic_store_n(&handles[i], NULL, __ATOMIC_RELEASE);
let_go(h->wd, h->up, h->nup);
pthread_mutex_unlock(&lock);
give(&lock);
}
DIR *opendir(const char *path) {
@@ -553,11 +566,11 @@ static void finish(struct handle *h) {
h->fill = NULL;
int current = stat(h->path, &st) == 0 && same(l, &st);
if (current) l->folds = folds(h->path, &st);
pthread_mutex_lock(&lock);
take(&lock);
if (!changing) pump(NULL, 0);
if (current && !__atomic_load_n(&h->dirty, __ATOMIC_RELAXED)) install(l);
else destroy(l);
pthread_mutex_unlock(&lock);
give(&lock);
}
static struct dirent64 *entry(struct handle *h) {
@@ -624,7 +637,8 @@ int readdir_r(DIR *d, struct dirent *out, struct dirent **result) {
int closedir(DIR *d) {
NEXT(closedir);
pthread_mutex_lock(&lock);
if (holding && registered(d) < 0) return next_closedir(d);
take(&lock);
int i = registered(d);
struct handle *h = i >= 0 ? handles[i] : NULL;
if (h) {
@@ -632,7 +646,7 @@ int closedir(DIR *d) {
if (h->snap) unref(h->snap);
let_go(h->wd, h->up, h->nup);
}
pthread_mutex_unlock(&lock);
give(&lock);
if (h == NULL) return next_closedir(d);
int r = 0;
if (h->real) r = next_closedir(h->real);
@@ -704,10 +718,10 @@ static int watching(const char *path) {
}
static void begin(void) {
pthread_mutex_lock(&lock);
take(&lock);
pump(NULL, 0);
changing = 1;
pthread_mutex_unlock(&lock);
give(&lock);
}
static void before(struct side *s) {
@@ -796,10 +810,10 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
}
static void end(struct expect *x, int nx) {
pthread_mutex_lock(&lock);
take(&lock);
pump(x, nx);
changing = 0;
pthread_mutex_unlock(&lock);
give(&lock);
}
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
@@ -809,17 +823,17 @@ int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
struct side s;
if (!(flags & O_CREAT) || (dirfd != AT_FDCWD && (path == NULL || path[0] != '/')) || !watching(path) || !split(path, &s))
return real(dirfd, path, flags, mode);
pthread_mutex_lock(&oplock);
take(&oplock);
begin();
before(&s);
int fd = real(dirfd, path, flags, mode);
int saved = errno;
struct expect x;
pthread_mutex_lock(&lock);
take(&lock);
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &x);
pthread_mutex_unlock(&lock);
give(&lock);
end(&x, nx);
pthread_mutex_unlock(&oplock);
give(&oplock);
errno = saved;
return fd;
}
@@ -829,26 +843,34 @@ int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
NEXT(name); \
struct side s; \
if (!watching(path) || !split(path, &s)) return call; \
pthread_mutex_lock(&oplock); \
take(&oplock); \
begin(); \
before(&s); \
int r = call; \
int saved = errno; \
struct expect x; \
pthread_mutex_lock(&lock); \
take(&lock); \
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, &x); \
if (r == 0 && what == REMOVED) forget_below(path); \
pthread_mutex_unlock(&lock); \
give(&lock); \
end(&x, nx); \
pthread_mutex_unlock(&oplock); \
give(&oplock); \
errno = saved; \
return r; \
}
ONE_PATH(mkdir, ADDED, IN_CREATE, next_mkdir(path, mode), mode_t mode)
ONE_PATH(rmdir, REMOVED, IN_DELETE, next_rmdir(path))
ONE_PATH(unlink, REMOVED, IN_DELETE, next_unlink(path))
ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
int bl_descriptor_unlink(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden")));
int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden")));
int bl_descriptor_remove(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden")));
int bl_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *))
__attribute__((visibility("hidden")));
static int moved(const char *from, const char *to) { return bl_descriptor_rename(from, to, next_rename); }
ONE_PATH(rmdir, REMOVED, IN_DELETE, bl_descriptor_rmdir(path, next_rmdir))
ONE_PATH(unlink, REMOVED, IN_DELETE, bl_descriptor_unlink(path, next_unlink))
ONE_PATH(remove, REMOVED, IN_DELETE, bl_descriptor_remove(path, next_remove))
#define TWO_PATHS(name, gone, event, call) \
int name(const char *from, const char *to) { \
@@ -856,7 +878,7 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
struct side a, b; \
int track_a = gone && watching(from) && split(from, &a), track_b = watching(to) && split(to, &b); \
if (!track_a && !track_b) return call(from, to); \
pthread_mutex_lock(&oplock); \
take(&oplock); \
begin(); \
if (track_a) before(&a); \
if (track_b) before(&b); \
@@ -864,16 +886,16 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
int saved = errno; \
struct expect x[2]; \
int nx = 0; \
pthread_mutex_lock(&lock); \
take(&lock); \
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &x[nx]); \
if (track_b) { \
if (track_a && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
nx += patch(&b, ADDED, event, r == 0, saved, to, &x[nx]); \
} \
if (r == 0 && gone) { forget_below(from); forget_below(to); } \
pthread_mutex_unlock(&lock); \
give(&lock); \
end(x, nx); \
pthread_mutex_unlock(&oplock); \
give(&oplock); \
errno = saved; \
return r; \
}
@@ -881,7 +903,7 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
int bl_link_lock(const char *oldpath, const char *newpath, int result) __attribute__((visibility("hidden")));
static int link_or_lock(const char *from, const char *to) { return bl_link_lock(from, to, next_link(from, to)); }
TWO_PATHS(rename, 1, IN_MOVED_TO, next_rename)
TWO_PATHS(rename, 1, IN_MOVED_TO, moved)
TWO_PATHS(link, 0, IN_CREATE, link_or_lock)
TWO_PATHS(symlink, 0, IN_CREATE, next_symlink)
@@ -923,13 +945,13 @@ int bl_dircache_absent(const char *path) {
for (const char *c = s.name; *c; c++)
if ((unsigned char)*c >= 0x80) return 0;
long long now = now_ns();
pthread_mutex_lock(&lock);
take(&lock);
int absent = 0;
if (!changing) {
pump(NULL, 0);
absent = listed_absent(s.dir, s.name, now);
}
pthread_mutex_unlock(&lock);
give(&lock);
return absent;
}
+35 -11
View File
@@ -30,6 +30,10 @@ static int is_lock_command(int cmd) {
switch (cmd) {
case F_SETLK:
case F_SETLKW:
#if defined(F_SETLK64) && F_SETLK64 != F_SETLK
case F_SETLK64:
case F_SETLKW64:
#endif
#ifdef F_OFD_SETLK
case F_OFD_SETLK:
#endif
@@ -45,6 +49,9 @@ static int is_lock_command(int cmd) {
static int is_lock_query(int cmd) {
switch (cmd) {
case F_GETLK:
#if defined(F_GETLK64) && F_GETLK64 != F_GETLK
case F_GETLK64:
#endif
#ifdef F_OFD_GETLK
case F_OFD_GETLK:
#endif
@@ -57,25 +64,18 @@ static int is_lock_query(int cmd) {
int bl_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden")));
void bl_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden")));
int fcntl(int fd, int cmd, ...) {
static int (*real_fcntl)(int, int, ...);
va_list ap;
void *arg;
static int fcntl_with(int (**real_fcntl)(int, int, ...), const char *name, int fd, int cmd, void *arg) {
int result;
va_start(ap, cmd);
arg = va_arg(ap, void *);
va_end(ap);
if (real_fcntl == NULL) real_fcntl = dlsym(RTLD_NEXT, "fcntl");
if (real_fcntl == NULL) {
if (*real_fcntl == NULL) *real_fcntl = dlsym(RTLD_NEXT, name);
if (*real_fcntl == NULL) {
errno = ENOSYS;
return -1;
}
void *nl_state = NULL;
int duplicate = cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC;
if (duplicate && bl_nl_before_dup(fd, &nl_state) != 0) return -1;
result = real_fcntl(fd, cmd, arg);
result = (*real_fcntl)(fd, cmd, arg);
if (duplicate) bl_nl_after_dup(nl_state, result);
if (result >= 0 || !unsupported(errno)) return result;
if (is_lock_command(cmd)) return 0;
@@ -86,6 +86,30 @@ int fcntl(int fd, int cmd, ...) {
return result;
}
int fcntl(int fd, int cmd, ...) {
static int (*real_fcntl)(int, int, ...);
va_list ap;
void *arg;
va_start(ap, cmd);
arg = va_arg(ap, void *);
va_end(ap);
return fcntl_with(&real_fcntl, "fcntl", fd, cmd, arg);
}
#if defined(__GLIBC__) && defined(F_SETLK64)
#ifdef __OFF_T_MATCHES_OFF64_T
int fcntl64(int fd, int cmd, ...) __attribute__((alias("fcntl")));
#else
int fcntl64(int fd, int cmd, ...) {
static int (*real_fcntl64)(int, int, ...);
va_list ap;
void *arg;
va_start(ap, cmd);
arg = va_arg(ap, void *);
va_end(ap);
return fcntl_with(&real_fcntl64, "fcntl64", fd, cmd, arg);
}
#endif
#endif
+100 -2
View File
@@ -1,9 +1,13 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/statvfs.h>
#include <sys/uio.h>
#include <unistd.h>
#if defined(__aarch64__) || defined(NOEXEC_TEST)
@@ -32,6 +36,100 @@ __attribute__((visibility("hidden"))) int bl_noexec_retry(int prot, int flags, i
static int (*real_mprotect)(void *, size_t, int);
struct span {
uintptr_t lo, hi;
int prot;
};
static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans, size_t cap) {
char buf[4096];
size_t used = 0, count = 0;
uintptr_t covered = start;
int file_backed = 0;
int fd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
for (;;) {
if (used >= sizeof buf - 1) used = 0;
ssize_t n = read(fd, buf + used, sizeof buf - 1 - used);
if (n <= 0) break;
used += (size_t)n;
buf[used] = 0;
char *line = buf, *nl;
while ((nl = strchr(line, '\n'))) {
*nl = 0;
char *p = line;
uintptr_t lo = strtoull(p, &p, 16), hi = strtoull(p + 1, &p, 16);
char perms[5] = {0};
int inode = 0;
if (*p == ' ') {
memcpy(perms, p + 1, 4);
char *field = p + 5;
strtoull(field, &field, 16);
inode = *field && (field = strchr(field + 1, ' ')) && strtoull(field, NULL, 10);
}
line = nl + 1;
if (hi <= covered || lo >= end) continue;
if (lo > covered || perms[3] != 'p' || count == cap) {
close(fd);
return 0;
}
spans[count].lo = covered;
spans[count].hi = hi < end ? hi : end;
file_backed |= inode;
spans[count].prot = (perms[0] == 'r' ? PROT_READ : 0) | (perms[1] == 'w' ? PROT_WRITE : 0) | (perms[2] == 'x' ? PROT_EXEC : 0);
covered = spans[count++].hi;
if (covered >= end) {
close(fd);
return file_backed ? count : 0;
}
}
used = strlen(line);
memmove(buf, line, used);
}
close(fd);
return 0;
}
static void restore(const struct span *spans, size_t count) {
for (size_t i = 0; i < count; i++)
if (!(spans[i].prot & PROT_READ)) real_mprotect((void *)spans[i].lo, spans[i].hi - spans[i].lo, spans[i].prot);
}
static int copy_to_anonymous(void *addr, size_t len, int prot) {
uintptr_t page = (uintptr_t)sysconf(_SC_PAGESIZE);
uintptr_t start = (uintptr_t)addr, end = (start + len + page - 1) & ~(page - 1);
struct span spans[64];
size_t count = 0, opened = 0;
if (start & (page - 1) || end <= start || !(count = private_range(start, end, spans, sizeof spans / sizeof *spans))) return -1;
size_t size = end - start;
int fd = memfd_create("noexec-image", MFD_CLOEXEC);
if (fd < 0) return -1;
if (ftruncate(fd, (off_t)size)) {
close(fd);
return -1;
}
void *copy = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (copy == MAP_FAILED) {
close(fd);
return -1;
}
while (opened < count && ((spans[opened].prot & PROT_READ) ||
!real_mprotect((void *)spans[opened].lo, spans[opened].hi - spans[opened].lo, spans[opened].prot | PROT_READ)))
opened++;
struct iovec local = {copy, size}, remote = {addr, size};
if (opened < count || process_vm_readv(getpid(), &local, 1, &remote, 1, 0) != (ssize_t)size || real_mprotect(copy, size, prot)) {
restore(spans, opened);
munmap(copy, size);
close(fd);
return -1;
}
int result = mmap(addr, size, prot, MAP_PRIVATE | MAP_FIXED, fd, 0) == addr ? 0 : -1;
if (result) restore(spans, count);
munmap(copy, size);
close(fd);
return result;
}
__attribute__((constructor)) static void noexec_init(void) {
real_mprotect = (int (*)(void *, size_t, int))dlsym(RTLD_NEXT, "mprotect");
}
@@ -39,8 +137,8 @@ __attribute__((constructor)) static void noexec_init(void) {
int mprotect(void *addr, size_t len, int prot) {
if (!real_mprotect) noexec_init();
int result = real_mprotect(addr, len, prot);
if (result && errno == EACCES && (prot & PROT_EXEC) && in_fex()) {
result = real_mprotect(addr, len, prot & ~PROT_EXEC);
if (result && errno == EACCES && (prot & PROT_EXEC)) {
result = in_fex() ? real_mprotect(addr, len, prot & ~PROT_EXEC) : copy_to_anonymous(addr, len, prot);
if (result) errno = EACCES;
}
return result;
+46 -14
View File
@@ -42,20 +42,15 @@ static int is_trace_marker(const char *path) {
|| strcmp(path, "/sys/kernel/debug/tracing/trace_marker") == 0);
}
int open(const char *path, int flags, ...) {
va_list ap;
mode_t mode;
static int open_from(const char *path, int flags, mode_t mode, const void *caller) {
int fd;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
if (is_trace_marker(path)) {
errno = EACCES;
return -1;
}
path = bl_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY);
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_status_without_tracer(path, flags, caller)) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if ((fd = bl_vdec_open(path, flags)) != -2) return fd;
@@ -70,20 +65,15 @@ int open(const char *path, int flags, ...) {
return fd;
}
int openat(int dirfd, const char *path, int flags, ...) {
va_list ap;
mode_t mode;
static int openat_from(int dirfd, const char *path, int flags, mode_t mode, const void *caller) {
int fd;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
if (is_trace_marker(path)) {
errno = EACCES;
return -1;
}
path = bl_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY);
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_status_without_tracer(path, flags, caller)) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if ((fd = bl_vdec_open(path, flags)) != -2) return fd;
@@ -98,5 +88,47 @@ int openat(int dirfd, const char *path, int flags, ...) {
return fd;
}
int open(const char *path, int flags, ...) {
va_list ap;
mode_t mode;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
return open_from(path, flags, mode, __builtin_return_address(0));
}
int openat(int dirfd, const char *path, int flags, ...) {
va_list ap;
mode_t mode;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
return openat_from(dirfd, path, flags, mode, __builtin_return_address(0));
}
#ifdef __OFF_T_MATCHES_OFF64_T
int open64(const char *path, int flags, ...) __attribute__((alias("open")));
int openat64(int dirfd, const char *path, int flags, ...) __attribute__((alias("openat")));
#else
int open64(const char *path, int flags, ...) {
va_list ap;
mode_t mode;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
return open_from(path, flags | O_LARGEFILE, mode, __builtin_return_address(0));
}
int openat64(int dirfd, const char *path, int flags, ...) {
va_list ap;
mode_t mode;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
return openat_from(dirfd, path, flags | O_LARGEFILE, mode, __builtin_return_address(0));
}
#endif
+4 -3
View File
@@ -12,7 +12,8 @@
#define FAT_MAGIC 0x4d44
#define EXFAT_MAGIC 0x2011bab0
static int is_wineserver(void) {
__attribute__((visibility("hidden")))
int bl_is_wineserver(void) {
static int cached = -1;
char exe[PATH_MAX];
const char *base;
@@ -43,7 +44,7 @@ void bl_storage_owner(int fd, struct stat *st) {
int saved = errno;
uid_t uid;
if (st != NULL && is_wineserver()) {
if (st != NULL && bl_is_wineserver()) {
uid = getuid();
if (st->st_uid != uid && has_no_unix_owner(fd)) st->st_uid = uid;
}
@@ -60,7 +61,7 @@ int fchmod(int fd, mode_t mode) {
return -1;
}
result = next_fchmod(fd, mode);
if (result != 0 && errno == EPERM && is_wineserver()) {
if (result != 0 && errno == EPERM && bl_is_wineserver()) {
if (has_no_unix_owner(fd)) {
errno = saved;
return 0;
+2 -1
View File
@@ -356,7 +356,8 @@ static void flush_summary(void) {
if (n > 0 && (size_t)n < sizeof(line)) append_line(line, (size_t)n);
}
#if defined(__USE_LARGEFILE64)
#if defined(__USE_LARGEFILE64) && defined(__OFF_T_MATCHES_OFF64_T)
_Static_assert(sizeof(struct stat) == sizeof(struct stat64), "stat64 alias needs one layout");
int fallocate64(int fd, int mode, off64_t offset, off64_t length) __attribute__((alias("fallocate")));
int posix_fallocate64(int fd, off64_t offset, off64_t length) __attribute__((alias("posix_fallocate")));
ssize_t pwrite64(int fd, const void *buffer, size_t count, off64_t offset) __attribute__((alias("pwrite")));
+8 -1
View File
@@ -12,7 +12,14 @@
#include <stdlib.h>
#include <string.h>
extern char **environ;
__attribute__((constructor)) static void bl_venus_keep_kopper(void) {
static const char name[] = "LIBGL_KOPPER_DISABLE=";
const char *debug = getenv("VN_DEBUG");
if (debug && strstr(debug, "vtest")) unsetenv("LIBGL_KOPPER_DISABLE");
if (!debug || !strstr(debug, "vtest") || !environ) return;
char **out = environ;
for (char **in = environ; *in; in++)
if (strncmp(*in, name, sizeof name - 1)) *out++ = *in;
*out = NULL;
}
+1
View File
@@ -38,6 +38,7 @@
#include <shadow.h>
#include <pthread.h>
#include <sys/wait.h>
#include <elf.h>
#include <sys/sendfile.h>
#include <sys/mman.h>
#include <sched.h>
+12 -1
View File
@@ -96,6 +96,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
int has_binds = 0;
int has_hostname = 0;
int has_link_root = 0;
int has_exec_loader = 0;
int has_preload_list = 0;
const char *preload_value = NULL;
while (envp && envp[count]) {
@@ -125,6 +126,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
else if (strncmp(e, "DDNATV_PRELOAD=", 15) == 0) has_preload_list = 1;
else if (strncmp(e, "DDNATV_HOSTNAME=", 16) == 0) has_hostname = 1;
else if (strncmp(e, "DDNATV_LINK_ROOT=", 17) == 0) has_link_root = 1;
else if (strncmp(e, "DDNATV_EXEC=", 12) == 0) has_exec_loader = 1;
else if (strncmp(e, "DPKG_DEB_THREADS_MAX=", 21) == 0) has_threads_max = 1;
else if (strncmp(e, "DEBIAN_FRONTEND=", 16) == 0) has_frontend = 1;
else if (strncmp(e, "DEBCONF_FRONTEND=", 17) == 0) has_debconf_frontend = 1;
@@ -136,7 +138,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
count++;
}
char **new_env = calloc(count + 24, sizeof(char *));
char **new_env = calloc(count + 25, sizeof(char *));
int dst = 0;
for (int i = 0; i < count; i++) {
if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
@@ -223,6 +225,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
new_env[dst++] = str;
}
}
if (!has_exec_loader && g_exec_loader[0] != '\0') {
size_t len = strlen(g_exec_loader);
char *str = malloc(12 + len + 1);
if (str) {
memcpy(str, "DDNATV_EXEC=", 12);
memcpy(str + 12, g_exec_loader, len + 1);
new_env[dst++] = str;
}
}
if (!has_link_root && g_link_root_len) {
char *str = malloc(17 + g_link_root_len + 1);
if (str) {
+106 -4
View File
@@ -135,12 +135,103 @@ static int in_exec_rehearsal(void) {
pthread_equal(pthread_self(), g_exec_rehearsal_thread);
}
// Android's own programs, and the app's extracted libraries, may still be executed directly.
static int exec_directly(const char *path) {
static const char *const prefixes[] = {"/system/", "/vendor/", "/apex/", "/product/", "/odm/", "/system_ext/", "/data/app/"};
if (g_exec_loader[0] == '\0' || !path || path[0] != '/' || strcmp(path, g_exec_loader) == 0) return 1;
for (size_t i = 0; i < sizeof(prefixes) / sizeof(prefixes[0]); i++)
if (strncmp(path, prefixes[i], strlen(prefixes[i])) == 0) return 1;
return 0;
}
// ENOENT when the program names a dynamic linker that is not there (a glibc program's
// "/lib/ld-linux-aarch64.so.1" on Android), as the kernel answers: callers try another way.
static int exec_interp_missing(int fd) {
Elf64_Ehdr eh;
if (syscall(SYS_pread64, fd, &eh, sizeof(eh), 0) != (long)sizeof(eh) || eh.e_ident[EI_CLASS] != ELFCLASS64 ||
eh.e_machine != EM_AARCH64 || (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) ||
eh.e_phentsize != sizeof(Elf64_Phdr) || eh.e_phnum == 0 || eh.e_phnum > 64)
return ENOEXEC;
for (int i = 0; i < eh.e_phnum; i++) {
Elf64_Phdr ph;
if (syscall(SYS_pread64, fd, &ph, sizeof(ph), (long)(eh.e_phoff + (Elf64_Off)i * sizeof(ph))) != (long)sizeof(ph))
return ENOEXEC;
if (ph.p_type != PT_INTERP) continue;
char interp[PATH_MAX];
if (ph.p_filesz == 0 || ph.p_filesz >= sizeof(interp) ||
syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz)
return ENOEXEC;
interp[ph.p_filesz] = 0;
int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
if (ifd < 0) return errno;
syscall(SYS_close, ifd);
return 0;
}
return 0;
}
// The errors execve() itself would give for [path], which the loader cannot report once it runs:
// a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at
// ENOEXEC.
static int exec_preflight(const char *path) {
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
if (fd < 0) return errno;
struct stat st;
int err = 0;
unsigned char magic[4];
if (syscall(SYS_fstat, fd, &st) != 0) err = errno;
else if (!S_ISREG(st.st_mode)) err = EACCES;
else if (syscall(SYS_faccessat, AT_FDCWD, path, X_OK, 0) != 0) err = EACCES;
else if (syscall(SYS_read, fd, magic, 2) == 2 && magic[0] == '#' && magic[1] == '!') err = -1;
else if (syscall(SYS_pread64, fd, magic, sizeof(magic), 0) != (long)sizeof(magic) ||
magic[0] != 0x7f || magic[1] != 'E' || magic[2] != 'L' || magic[3] != 'F') err = ENOEXEC;
else err = exec_interp_missing(fd);
syscall(SYS_close, fd);
return err;
}
// "libddexec.so <path> <argv...>"; NULL when [path] is executed directly, as a "#!" script the
// kernel hands to its interpreter is. *err is set when the exec would fail.
static char **loader_argv(const char *path, char *const argv[], int *err) {
*err = 0;
if (exec_directly(path)) return NULL;
int preflight = exec_preflight(path);
if (preflight == -1) return NULL;
*err = preflight;
if (*err) return NULL;
int argc = 0;
while (argv && argv[argc]) argc++;
char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 4));
if (!out) {
*err = ENOMEM;
return NULL;
}
out[0] = g_exec_loader;
out[1] = (char *)path;
int n = 2;
if (argc == 0) out[n++] = (char *)path;
for (int i = 0; i < argc; i++) out[n++] = argv[i];
out[n] = NULL;
return out;
}
static int run_execve(orig_execve_f_type f, const char *path, char *const argv[], char *const envp[]) {
if (in_exec_rehearsal()) {
errno = 0;
return 0;
}
return f(path, argv, envp);
int err;
char **via = loader_argv(path, argv, &err);
if (err) {
errno = err;
return -1;
}
if (!via) return f(path, argv, envp);
int ret = f(g_exec_loader, via, envp);
int saved_errno = errno;
free(via);
errno = saved_errno;
return ret;
}
// ldconfig does nothing in The native userland (its cache is for paths that ld.so opens without the hook), but the
@@ -701,6 +792,17 @@ static orig_posix_spawn_f_type real_posix_spawn(void) {
return orig_posix_spawn;
}
static int run_spawn(orig_posix_spawn_f_type f, pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]) {
int err;
char **via = loader_argv(path, argv, &err);
if (err) return err;
if (!via) return f(pid, path, file_actions, attrp, argv, envp);
int ret = f(pid, g_exec_loader, file_actions, attrp, via, envp);
free(via);
return ret;
}
static int ddnatv_posix_spawn(pid_t *pid, const char *path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp,
@@ -856,10 +958,10 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
ret = ENOMEM;
} else {
if (orig_posix_spawn) {
ret = orig_posix_spawn(pid, ld_so, file_actions, attrp, new_argv, new_envp);
ret = run_spawn(orig_posix_spawn, pid, ld_so, file_actions, attrp, new_argv, new_envp);
if (ret == EACCES && chmod(ld_so, 0755) == 0) {
// ld.so without its exec bit (an unusual restore): fix it once and retry
ret = orig_posix_spawn(pid, ld_so, file_actions, attrp, new_argv, new_envp);
ret = run_spawn(orig_posix_spawn, pid, ld_so, file_actions, attrp, new_argv, new_envp);
}
}
free(new_argv);
@@ -867,7 +969,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
} else {
if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target);
if (orig_posix_spawn) {
ret = orig_posix_spawn(pid, target, file_actions, attrp, argv, new_envp);
ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, argv, new_envp);
}
}
+2 -2
View File
@@ -700,7 +700,7 @@ char *getcwd(char *buf, size_t size) {
char *res = orig_getcwd ? orig_getcwd(buf, size) : NULL;
if (res) {
size_t len = strlen(res);
guest_path_of_mount_source(res, len, buf ? size : len + 1);
guest_path_of_mount_source(res, len, buf ? size : len + 1, NULL);
}
return res;
}
@@ -749,7 +749,7 @@ char *realpath(const char *path, char *resolved_path) {
}
}
}
if (res) guest_path_of_mount_source(res, strlen(res), resolved_path ? PATH_MAX : strlen(res) + 1);
if (res) guest_path_of_mount_source(res, strlen(res), resolved_path ? PATH_MAX : strlen(res) + 1, NULL);
return res;
}
+152 -8
View File
@@ -11,10 +11,28 @@
static char g_ddnatv_root[PATH_MAX] = {0};
static size_t g_ddnatv_root_len = 0;
// The path the kernel reports for [path] (/proc/self/fd, getcwd(), realpath()): for a targetSdk 30+
// app, Android's own /data/user/0 is a link to /data/data, so the app's paths are not what the kernel
// gives back for them. Into out, or path itself when it cannot be resolved; returns out's length.
static size_t ddnatv_kernel_path(const char *path, size_t len, char *out, size_t outsz) {
static char *(*libc_realpath)(const char *, char *) = NULL;
if (!libc_realpath) libc_realpath = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath");
char given[PATH_MAX];
if (len >= sizeof(given)) len = sizeof(given) - 1;
memcpy(given, path, len);
given[len] = '\0';
char resolved[PATH_MAX];
const char *use = (libc_realpath && libc_realpath(given, resolved)) ? resolved : given;
size_t n = strlen(use);
if (n >= outsz) n = outsz - 1;
memcpy(out, use, n);
out[n] = '\0';
return n;
}
static void ddnatv_set_root(const char *root, size_t len) {
if (!root) len = 0;
if (len > sizeof(g_ddnatv_root) - 1) len = sizeof(g_ddnatv_root) - 1;
if (len > 0) memcpy(g_ddnatv_root, root, len);
if (len > 0) len = ddnatv_kernel_path(root, len, g_ddnatv_root, sizeof(g_ddnatv_root));
g_ddnatv_root[len] = '\0';
g_ddnatv_root_len = len;
}
@@ -61,6 +79,11 @@ static void ddnatv_load_binds(const char *spec) {
if (colon) *colon = '\0';
if (src[0] != '/' || dst[0] != '/' || strcmp(dst, "/") == 0) continue;
struct ddnatv_bind *b = &g_binds[g_nbinds++];
char kernel_src[PATH_MAX];
if (strcmp(src, dst) != 0) {
ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src));
src = kernel_src;
}
b->src = strdup(src);
b->dst = strdup(dst);
b->src_len = strlen(src);
@@ -163,6 +186,108 @@ static long raw_readlinkat(int dirfd, const char *path, char *buf, size_t size)
static __thread int t_bind_link_depth = 0;
static void normalize_path(char *path);
#if defined(__aarch64__)
static long raw_link_dir(const char *link, char *out, size_t size) {
const char *slash = strrchr(link, '/');
if (!slash || (size_t)(slash - link) >= PATH_MAX) return -1;
char dir[PATH_MAX];
size_t dlen = slash == link ? 1 : (size_t)(slash - link);
memcpy(dir, link, dlen);
dir[dlen] = '\0';
register long x8 __asm__("x8") = 56;
register long x0 __asm__("x0") = AT_FDCWD;
register long x1 __asm__("x1") = (long)dir;
register long x2 __asm__("x2") = O_PATH | O_DIRECTORY | O_CLOEXEC;
register long x3 __asm__("x3") = 0;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
long fd = x0;
if (fd < 0) return -1;
char proc[32];
snprintf(proc, sizeof(proc), "/proc/self/fd/%ld", fd);
long n = raw_readlinkat(AT_FDCWD, proc, out, size - 1);
register long c8 __asm__("x8") = 57;
register long c0 __asm__("x0") = fd;
__asm__ volatile("svc #0" : "+r"(c0) : "r"(c8) : "memory");
if (n <= 0 || out[0] != '/') return -1;
out[n] = '\0';
return n;
}
static int climbs_past_root(const char *dir, const char *target) {
long depth = 0;
for (const char *p = dir; *p; p++)
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
for (const char *p = target; *p;) {
while (*p == '/') p++;
const char *end = p;
while (*end && *end != '/') end++;
size_t len = (size_t)(end - p);
if (len == 2 && p[0] == '.' && p[1] == '.') {
if (--depth < 0) return 1;
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
depth++;
}
p = end;
}
return 0;
}
static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted);
static const char *guest_path_of_host_dir(const char *dir, char *out, size_t size) {
const char *sub = get_rootfs_subpath(dir);
if (sub) {
ddnatv_copy_cstr(out, size, sub[0] ? sub : "/");
return out;
}
if (dir[0] != '/') return NULL;
size_t len = ddnatv_copy_cstr(out, size, dir);
int converted = 0;
guest_path_of_mount_source(out, len, size, &converted);
if (converted) return out;
for (int i = 0; i < g_nbinds; i++) {
const struct ddnatv_bind *b = &g_binds[i];
if (b->identity && is_path_prefix(dir, b->dst, b->dst_len)) {
ddnatv_copy_cstr(out, size, dir);
return out;
}
}
return NULL;
}
static int join_into_bind(const char *dir, const char *target, const char *rest, char *out, size_t size) {
char guest_dir_buf[PATH_MAX];
const char *guest_dir = guest_path_of_host_dir(dir, guest_dir_buf, sizeof(guest_dir_buf));
if (!guest_dir) return 0;
char joined[PATH_MAX];
size_t used = ddnatv_append(joined, sizeof(joined), 0, guest_dir, strlen(guest_dir));
used = ddnatv_append(joined, sizeof(joined), used, "/", 1);
used = ddnatv_append(joined, sizeof(joined), used, target, strlen(target));
if (used + 1 >= sizeof(joined)) return 0;
normalize_path(joined);
used = ddnatv_append(out, size, 0, joined, strlen(joined));
if (used + 1 >= size) return 0;
if (rest[0] == '/' && used > 0 && out[used - 1] == '/') rest++;
size_t rest_len = strlen(rest);
if (used + rest_len + 1 >= size) return 0;
ddnatv_append(out, size, used, rest, rest_len);
return out[0] == '/';
}
static int relative_link_into_bind(const char *link, const char *target, const char *rest, char *out, size_t size) {
char dir[PATH_MAX];
if (raw_link_dir(link, dir, sizeof(dir)) >= 0) return join_into_bind(dir, target, rest, out, size);
const char *slash = strrchr(link, '/');
if (!slash) return 0;
size_t dlen = (size_t)(slash - link);
memcpy(dir, link, dlen);
dir[dlen] = '\0';
return join_into_bind(dir, target, rest, out, size);
}
#endif
// A mount stand-in can hold symbolic links with absolute guest targets (/sys/class/hidraw/hidraw16 ->
// /sys/devices/droiddeck/...): proot follows them inside the guest, the kernel on Android's own /sys.
// A link met on the way to a deeper path is replaced by its target, mapped again; the last component is
@@ -180,10 +305,13 @@ static const char *resolve_bind_links(const char *host, size_t src_len, char *bu
long n = raw_readlinkat(AT_FDCWD, prefix, target, sizeof(target) - 1);
if (n <= 0) continue;
target[n] = '\0';
if (target[0] != '/') continue;
char guest[PATH_MAX];
size_t used = ddnatv_append(guest, sizeof(guest), 0, target, (size_t)n);
ddnatv_append(guest, sizeof(guest), used, host + i, len - i);
if (target[0] != '/') {
if (!relative_link_into_bind(prefix, target, host + i, guest, sizeof(guest))) continue;
} else {
size_t used = ddnatv_append(guest, sizeof(guest), 0, target, (size_t)n);
ddnatv_append(guest, sizeof(guest), used, host + i, len - i);
}
t_bind_link_depth++;
const char *mapped = rewrite_path_in_root(guest, buffer, bufsize);
if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped);
@@ -243,7 +371,21 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
}
// Already inside The native userland rootfs
if (get_rootfs_subpath(path) != NULL) {
const char *sub = get_rootfs_subpath(path);
if (sub != NULL) {
if (sub[0] == '/' && t_bind_link_depth < 8) {
for (int i = 0; i < g_nbinds; i++) {
const struct ddnatv_bind *b = &g_binds[i];
if (b->identity || sub[1] != b->dst[1] || !is_path_prefix(sub, b->dst, b->dst_len)) continue;
char guest[PATH_MAX];
ddnatv_copy_cstr(guest, sizeof(guest), sub);
t_bind_link_depth++;
const char *mapped = rewrite_path_in_root(guest, buffer, bufsize);
if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped);
t_bind_link_depth--;
return buffer;
}
}
return resolve_drive_links(path, buffer, bufsize);
}
@@ -446,7 +588,8 @@ static int is_proc_fd_link(const char *path) {
// reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for
// Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit.
// Rewrites buf[0..len) in place when the guest path fits in cap; returns the new length.
static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap) {
static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted) {
if (converted) *converted = 0;
const struct ddnatv_bind *best = NULL;
for (int i = 0; i < g_nbinds; i++) {
const struct ddnatv_bind *b = &g_binds[i];
@@ -460,6 +603,7 @@ static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap) {
memmove(buf + best->dst_len, buf + best->src_len, rest);
memcpy(buf, best->dst, best->dst_len);
buf[best->dst_len + rest] = '\0';
if (converted) *converted = 1;
return best->dst_len + rest;
}
@@ -469,7 +613,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
buf[ret] = '\0';
ret = (ssize_t)link_root_guest_target(buf, (size_t)ret);
}
ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz);
ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL);
// 1. Strip g_ddnatv_root if target starts with it
if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) {
+7 -2
View File
@@ -7,6 +7,9 @@
#ifndef DDNATV_HOST_TEST
static char g_real_exe[PATH_MAX] = {0};
// DDNATV_EXEC: the app's libddexec.so. A targetSdk 29+ app may not execve() its data files; this
// executable maps one and starts it as the kernel would ("libddexec.so <file> <argv0> [args...]").
static char g_exec_loader[PATH_MAX] = {0};
// DDNATV_PRELOAD: guest paths of libraries every program loads before the hook (what
// /etc/ld.so.preload does for programs run by the rootfs's own ld.so), and the same as host paths.
static char *g_preload_guest = NULL;
@@ -34,12 +37,14 @@ static void init_ddnatv_hook(void) {
}
}
ddnatv_load_binds(getenv("DDNATV_BINDS"));
const char *exec_loader = getenv("DDNATV_EXEC");
if (exec_loader && exec_loader[0] == '/' && strlen(exec_loader) < sizeof(g_exec_loader))
ddnatv_copy_cstr(g_exec_loader, sizeof(g_exec_loader), exec_loader);
const char *hostname = getenv("DDNATV_HOSTNAME");
if (hostname && hostname[0] && strlen(hostname) < sizeof(g_hostname)) ddnatv_copy_cstr(g_hostname, sizeof(g_hostname), hostname);
const char *link_root = getenv("DDNATV_LINK_ROOT");
if (link_root && link_root[0] == '/' && strlen(link_root) < sizeof(g_link_root)) {
ddnatv_copy_cstr(g_link_root, sizeof(g_link_root), link_root);
g_link_root_len = strlen(g_link_root);
g_link_root_len = ddnatv_kernel_path(link_root, strlen(link_root), g_link_root, sizeof(g_link_root));
while (g_link_root_len > 1 && g_link_root[g_link_root_len - 1] == '/') g_link_root[--g_link_root_len] = 0;
}
const char *preload = getenv("DDNATV_PRELOAD");
+2
View File
@@ -78,6 +78,8 @@ pack xbox "$linuxfs/droiddeck-xbox" version xodus-cli xodus-service
pack comet "$linuxfs/droiddeck-comet" version comet
pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt
[ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe
[ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe
[ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll
mkdir "$work/butler"
fetch "https://broth.itch.zone/butler/linux-arm64/${BUTLER_VERSION}/archive/default" \
+19 -2
View File
@@ -3,8 +3,8 @@
Built by `tools/proot/build.sh` with the NDK on top of termux/proot `4dba3afb` (Termux's
5.1.107-70 package, the proot the Linux runtime ships at `opt/android-host/proot`; every
`file.c:line` site in that binary matches this commit). talloc is linked in statically from
Samba's release tarball, so the apk carries one self-contained `libproot.so` plus
`libproot-loader.so`, and `LinuxRuntime` prefers them over the runtime's copy.
Samba's release tarball, so the proot add-on pack carries one self-contained `libproot.so`, which
Android's linker runs from app data, and the apk carries `libproot-loader.so`, which proot execs.
Ported from WinNative (`feature/proot-enhancements`, e7af0f24):
@@ -162,9 +162,26 @@ Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-per
`ENOSYS`, because its arguments are host paths; the fast path then stops for that process and
repeats the call through a plain `svc`, which the guest's filter traps with the guest path.
`bench/guest-trap.c` installs a tagged `openat` trap and checks its handler answers the call.
The kernel and filesystems also return `ENOSYS` themselves: Android's FUSE daemon has no
`symlink`, so `symlinkat` on a storage card fails with it. The fast path therefore asks again
with the same call number and invalid arguments. A trap answers `ENOSYS` again and the fast path
stops for the process; any other error means the call reached the kernel, so only that one call
is repeated through a plain `svc` and the fast path stays on.
Old kernel fixes:
- `0028-fchdir-open-directory.patch` - `fchdir` resolved the directory again from its guest path,
one `lstat` per path component, then an `lstat` and an `O_PATH` open of the result. The
descriptor is already open, so `/proc/<pid>/fd/<n>` gives its host path and one `stat` through
that link confirms it is a live directory. The guest path it maps to is checked to map back to
the same host path, and the parent of the binding it falls under is checked to still resolve
to itself, so the cwd PRoot records is the one the old walk produced; a deleted directory, a
path outside the guest, a binding whose ancestor became a symlink, or anything else that does
not round-trip takes the old walk. Listing a directory in Wine does `fchdir` there and back: on a memory card behind
Android's FUSE daemon the old walk cost about 4 ms per call in the single tracer thread, 8.4 s
of an 8.8 s tracer total across one program start, and is now under 0.1 ms.
`bench/fchdir.py [directory...]` checks the cwd after `fchdir` to plain, bound, symlinked,
renamed and deleted directories and prints the per-call cost.
- `0015-lost-fork-events.patch` - works around a problem reported on Xiaomi's msm 4.14 kernel:
the kernel sometimes reports a new process or thread but gives its ID as zero. Without that ID,
PRoot cannot finish setting it up, which can leave the session stuck. The patch searches `/proc`
+105
View File
@@ -0,0 +1,105 @@
import errno
import os
import sys
import tempfile
import time
def report(label, check):
try:
print(label, check())
except OSError as error:
print(label, "ERR", errno.errorcode.get(error.errno, error.errno))
def enter(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fchdir(fd)
return os.getcwd(), os.readlink("/proc/self/cwd"), os.path.samefile(".", path)
finally:
os.close(fd)
def enter_file(base):
fd = os.open(base + "/real/file", os.O_RDONLY)
try:
os.fchdir(fd)
finally:
os.close(fd)
def enter_deleted(base):
os.mkdir(base + "/gone")
fd = os.open(base + "/gone", os.O_RDONLY)
os.rmdir(base + "/gone")
try:
os.fchdir(fd)
return "ok"
finally:
os.close(fd)
os.chdir("/")
def enter_renamed(base):
os.mkdir(base + "/before")
fd = os.open(base + "/before", os.O_RDONLY)
os.rename(base + "/before", base + "/after")
try:
os.fchdir(fd)
return os.getcwd() == base + "/after"
finally:
os.close(fd)
os.chdir("/")
os.rmdir(base + "/after")
def relative(base):
fd = os.open(base, os.O_RDONLY)
os.fchdir(fd)
os.close(fd)
seen = os.path.exists("real/file"), os.path.exists("link/file")
os.chdir("real")
inside = os.getcwd() == base + "/real"
os.chdir("..")
return seen + (inside, os.getcwd() == base)
def cost(path, rounds=300):
fd = os.open(path, os.O_RDONLY)
back = os.open("/", os.O_RDONLY)
start = time.perf_counter()
for _ in range(rounds):
os.fchdir(fd)
os.fchdir(back)
elapsed = time.perf_counter() - start
os.close(fd)
os.close(back)
return round(elapsed / rounds / 2 * 1e6, 1)
def main():
extra = sys.argv[1:]
base = tempfile.mkdtemp(prefix="fchdir-")
os.mkdir(base + "/real")
os.symlink(base + "/real", base + "/link")
os.mkdir(base + "/dot.")
open(base + "/real/file", "w").close()
for path in ["/", "/tmp", "/usr/lib", "/proc/self", "/dev", base + "/real", base + "/link", base + "/dot."] + extra:
report(path, lambda: enter(path))
report("file", lambda: enter_file(base))
report("deleted", lambda: enter_deleted(base))
report("renamed", lambda: enter_renamed(base))
report("badfd", lambda: os.fchdir(987))
report("relative", lambda: relative(base))
os.chdir("/")
for path in ["/usr/lib"] + extra:
print("fchdir_us", path, cost(path))
os.unlink(base + "/real/file")
os.unlink(base + "/link")
os.rmdir(base + "/dot.")
os.rmdir(base + "/real")
os.rmdir(base)
main()
+243 -25
View File
@@ -41,7 +41,7 @@ typedef long (*stub_fn)(long nr, long a, long b, long c, long d, long e, long f)
static stub_fn fp_sys;
static int fp_on;
struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; int dropped; };
struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; int dropped; int fuse; };
static struct bind binds[MAX_BINDS];
static int nbinds;
static char root[PATH_MAX];
@@ -59,10 +59,10 @@ static int optional_syscall(long nr) {
nr == SYS_openat2 || nr == SYS_renameat2;
}
static long sc(long nr, long a, long b, long c, long d, long e) {
if (fp_refused) return -ENOSYS;
if (fp_refused && nr != SYS_close) return -ENOSYS;
long r = fp_sys(nr, a, b, c, d, e, 0);
if (r == -ENOSYS && !optional_syscall(nr)) {
__atomic_store_n(&fp_on, 0, __ATOMIC_RELAXED);
if (fp_sys(nr, -1, -1, -1, -1, -1, 0) == -ENOSYS) __atomic_store_n(&fp_on, 0, __ATOMIC_RELAXED);
fp_refused = 1;
}
return r;
@@ -133,7 +133,8 @@ static long tracer;
static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t bind_lock;
static pthread_mutex_t long_lock;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); }
static pthread_mutex_t dir_lock = PTHREAD_MUTEX_INITIALIZER;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); pthread_mutex_init(&dir_lock, NULL); }
static int traced_by_match(const char *key) {
static char buf[32768];
@@ -414,6 +415,212 @@ static int host_bind(const char *h) {
return -1;
}
static unsigned hash_of(const char *s);
static long long now_ns(void);
#define DIRS 64
#define DIR_FD_FLOOR 1000
struct dirslot { unsigned hash, epoch; int fd, refs; dev_t dev; ino_t ino; long tag; long long stamp; char path[PATH_MAX]; char seen[PATH_MAX]; };
static struct dirslot dirs[DIRS];
static unsigned dir_epoch;
struct near { long fd; int slot, own; const char *name; };
static int fuse_bind(const char *h) {
int i = host_bind(h);
if (i < 0) return -1;
int f = __atomic_load_n(&binds[i].fuse, __ATOMIC_ACQUIRE);
if (!f) {
struct statfs fs;
f = sc(SYS_statfs, (long)binds[i].host, (long)&fs, 0, 0, 0) == 0 && fs.f_type == 0x65735546 ? 1 : 2;
__atomic_store_n(&binds[i].fuse, f, __ATOMIC_RELEASE);
}
return f == 1 ? i : -1;
}
static long fd_path(long fd, char *out) {
char link[40];
snprintf(link, sizeof link, "/proc/self/fd/%ld", fd);
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, PATH_MAX - 1, 0);
if (n <= 0 || n >= PATH_MAX - 1) return -1;
out[n] = 0;
return 0;
}
static int fd_id(long fd, dev_t *dev, ino_t *ino) {
struct stat st;
if (sc(SYS_newfstatat, fd, (long)"", (long)&st, AT_EMPTY_PATH, 0) != 0) return -1;
*dev = st.st_dev;
*ino = st.st_ino;
return 0;
}
static long dir_tag(void) {
static uint64_t state;
uint64_t z = __atomic_add_fetch(&state, 0x9e3779b97f4a7c15ULL, __ATOMIC_RELAXED), seed = 0;
const void *random = (const void *)getauxval(AT_RANDOM);
if (random) memcpy(&seed, random, sizeof seed);
z += seed;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return (long)((z ^ (z >> 31)) & 0xffffffffffULL) + 1;
}
static int dir_owned(const struct dirslot *e) {
dev_t dev;
ino_t ino;
return e->fd > 0 && sc(SYS_lseek, e->fd, 0, SEEK_CUR, 0, 0) == e->tag
&& fd_id(e->fd, &dev, &ino) == 0 && dev == e->dev && ino == e->ino;
}
static int dir_fresh(struct dirslot *e, const char *dir) {
long long t = now_ns();
if (t - __atomic_load_n(&e->stamp, __ATOMIC_RELAXED) < ttl_ns) return 1;
struct stat st;
if (sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, 0, 0) != 0 || st.st_dev != e->dev || st.st_ino != e->ino) {
__atomic_add_fetch(&dir_epoch, 1, __ATOMIC_RELEASE);
return 0;
}
__atomic_store_n(&e->stamp, t, __ATOMIC_RELAXED);
return 1;
}
static void dirs_drop(const char *host) {
size_t len = strlen(host);
if (pthread_mutex_trylock(&dir_lock) != 0) {
__atomic_add_fetch(&dir_epoch, 1, __ATOMIC_RELEASE);
return;
}
for (int i = 0; i < DIRS; i++)
if (dirs[i].path[0] && under(dirs[i].path, host, len)) dirs[i].path[0] = 0;
pthread_mutex_unlock(&dir_lock);
}
static void near_put(struct near *n) {
if (n->own) sc(SYS_close, n->fd, 0, 0, 0, 0);
else if (n->slot >= 0) __atomic_sub_fetch(&dirs[n->slot].refs, 1, __ATOMIC_RELEASE);
n->fd = AT_FDCWD;
n->slot = -1;
n->own = 0;
}
static int dir_cached(const char *dir, struct near *n) {
unsigned h = hash_of(dir);
struct dirslot *e = &dirs[h % DIRS];
if (pthread_mutex_trylock(&dir_lock) != 0) return 0;
int hit = e->fd >= 0 && e->hash == h && e->path[0] && strcmp(e->path, dir) == 0
&& e->epoch == __atomic_load_n(&dir_epoch, __ATOMIC_ACQUIRE);
if (hit) __atomic_add_fetch(&e->refs, 1, __ATOMIC_ACQUIRE);
pthread_mutex_unlock(&dir_lock);
if (!hit) return 0;
char now[PATH_MAX];
if (fd_path(e->fd, now) == 0 && strcmp(now, e->seen) == 0 && dir_fresh(e, dir)) {
n->fd = e->fd;
n->slot = (int)(e - dirs);
n->own = 0;
return 1;
}
__atomic_sub_fetch(&e->refs, 1, __ATOMIC_RELEASE);
if (pthread_mutex_trylock(&dir_lock) == 0) {
if (e->hash == h && strcmp(e->path, dir) == 0) e->path[0] = 0;
pthread_mutex_unlock(&dir_lock);
}
return 0;
}
static int dir_keep(const char *dir, long fd, struct near *n) {
long high = sc(SYS_fcntl, fd, F_DUPFD_CLOEXEC, DIR_FD_FLOOR, 0, 0);
sc(SYS_close, fd, 0, 0, 0, 0);
if (high < 0) return -1;
n->fd = high;
n->slot = -1;
n->own = 1;
char seen[PATH_MAX];
dev_t dev;
ino_t ino;
long tag = dir_tag();
struct stat st;
if (fd_id(high, &dev, &ino) < 0 || strlen(dir) >= PATH_MAX
|| sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, 0, 0) != 0 || st.st_dev != dev || st.st_ino != ino) {
near_put(n);
return -1;
}
if (fd_path(high, seen) < 0 || sc(SYS_lseek, high, tag, SEEK_SET, 0, 0) != tag) return 0;
unsigned h = hash_of(dir);
struct dirslot *e = &dirs[h % DIRS];
if (pthread_mutex_trylock(&dir_lock) != 0) return 0;
if (__atomic_load_n(&e->refs, __ATOMIC_ACQUIRE) == 0) {
if (dir_owned(e)) sc(SYS_close, e->fd, 0, 0, 0, 0);
e->hash = h;
e->epoch = __atomic_load_n(&dir_epoch, __ATOMIC_ACQUIRE);
e->tag = tag;
e->stamp = now_ns();
e->fd = (int)high;
e->dev = dev;
e->ino = ino;
e->refs = 1;
strcpy(e->path, dir);
strcpy(e->seen, seen);
n->slot = (int)(e - dirs);
n->own = 0;
}
pthread_mutex_unlock(&dir_lock);
return 0;
}
static int dir_get(char *dir, size_t floor, struct near *n) {
size_t len = strlen(dir), at = len;
while (!dir_cached(dir, n)) {
if (at <= floor) {
long fd = sc(SYS_openat, AT_FDCWD, (long)dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0);
if (fd < 0 || dir_keep(dir, fd, n) < 0) return -1;
break;
}
char *slash = strrchr(dir, '/');
if (!slash || (size_t)(slash - dir) < floor) return -1;
*slash = 0;
at = slash - dir;
}
while (at < len) {
dir[at] = '/';
const char *name = dir + at + 1;
size_t next = at + 1 + strlen(name);
long fd = sc(SYS_openat, n->fd, (long)name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, 0, 0);
near_put(n);
if (fd < 0 || dir_keep(dir, fd, n) < 0) return -1;
at = next;
}
return 0;
}
static long near_get(const char *host, struct near *n) {
n->fd = AT_FDCWD;
n->slot = -1;
n->own = 0;
n->name = host;
if (ttl_ns <= 0 || host[0] != '/') return n->fd;
int i = fuse_bind(host);
if (i < 0) return n->fd;
const char *slash = strrchr(host, '/');
size_t plen = slash - host;
if (plen < binds[i].hlen || !slash[1] || plen >= PATH_MAX) return n->fd;
char dir[PATH_MAX];
memcpy(dir, host, plen);
dir[plen] = 0;
if (dir_get(dir, binds[i].hlen, n) < 0) {
near_put(n);
return n->fd;
}
n->name = slash + 1;
return n->fd;
}
static long hsc(long nr, const char *host, long a, long b, long c) {
struct near n;
long fd = near_get(host, &n);
long rs = sc(nr, fd, (long)n.name, a, b, c);
near_put(&n);
return rs;
}
static int guest_text(const char *h, char *g) {
if (h[0] == '/' && under(h, root, rootlen)) return to_guest(h, g, PATH_MAX);
int i = h[0] == '/' ? host_bind(h) : -1;
@@ -556,7 +763,7 @@ static long proc_readlink(const struct res *r, char *text, size_t size, int *cha
return name[0] == 'e' ? own_exe(text) : own_cwd(text);
}
char h[PATH_MAX];
long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)h, sizeof h - 1, 0);
long t = hsc(SYS_readlinkat, r->host, (long)h, sizeof h - 1, 0);
if (t < 0) return t;
if (t >= (long)sizeof h - 1) return FP_SLOW;
if (size && (size_t)t > size) t = size;
@@ -579,7 +786,7 @@ static long proc_link(struct res *r, char *text, int final) {
if (!under(r->host, "/proc", 5)) return FP_SLOW;
r->moving = 1;
if (!strcmp(r->guest, "/proc/self") || !strcmp(r->guest, "/proc/thread-self")) {
long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)text, PATH_MAX - 1, 0);
long t = hsc(SYS_readlinkat, r->host, (long)text, PATH_MAX - 1, 0);
if (t <= 0 || t >= PATH_MAX - 1) return FP_SLOW;
text[t] = 0;
return t;
@@ -628,7 +835,7 @@ static long walk(struct res *r, const char *text, int follow, int last) {
if (reserved(r->guest)) return FP_SLOW;
struct bind *through;
if (to_host(r->guest, r->host, &through) < 0) return FP_SLOW;
long s = sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
long s = hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
if (s < 0) {
int glue = glue_above_binding(r->guest, glen + n);
if (glue < 0) return FP_SLOW;
@@ -648,13 +855,13 @@ static long walk(struct res *r, const char *text, int follow, int last) {
t = proc_link(r, target, final && last);
if (t == FP_SLOW) return FP_SLOW;
if (t == 0) {
if (sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, 0, 0) < 0) return FP_SLOW;
if (hsc(SYS_newfstatat, r->host, (long)&r->st, 0, 0) < 0) return FP_SLOW;
r->magic = 1;
r->exists = 1;
return 0;
}
} else {
t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)target, sizeof target - 1, 0);
t = hsc(SYS_readlinkat, r->host, (long)target, sizeof target - 1, 0);
if (t <= 0 || t >= (long)sizeof target - 1) return FP_SLOW;
target[t] = 0;
if (detranslated(target, r->host) == FP_SLOW) return FP_SLOW;
@@ -676,7 +883,7 @@ static long walk(struct res *r, const char *text, int follow, int last) {
}
if (!stated) {
if (to_host(r->guest, r->host, NULL) < 0) return FP_SLOW;
long s = sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
long s = hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
if (s < 0 && strcmp(r->guest, "/") != 0 && glue_above_binding(r->guest, strlen(r->guest))) return FP_SLOW;
if (s < 0) return s == -ENOENT ? FP_SLOW : s;
}
@@ -699,7 +906,7 @@ static long bound_literal(const char *literal, struct res *r) {
struct bind *bd;
if (reserved(literal) || bind_of(literal, &bd) < 0 || !bd || bd->glen != strlen(literal) || bd->glen < 2) return FP_SLOW;
if (snprintf(r->host, PATH_MAX, "%s", bd->host) >= PATH_MAX) return FP_SLOW;
if (sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0) < 0 || S_ISLNK(r->st.st_mode)) return FP_SLOW;
if (hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0) < 0 || S_ISLNK(r->st.st_mode)) return FP_SLOW;
snprintf(r->guest, PATH_MAX, "%s", literal);
r->exists = 1;
r->moving = 0;
@@ -822,8 +1029,8 @@ static long fp_open(int dirfd, const char *path, int flags, mode_t mode) {
long rs = resolve(dirfd, path, follow | MAY_BE_UNSEEN, &r);
if (rs < 0) return rs;
if (rs == 1 && !(flags & O_CREAT)) return -ENOENT;
if (rs == UNSEEN) return sc(SYS_openat, AT_FDCWD, (long)r.host, flags, (flags & O_CREAT) ? mode : 0, 0);
return sc(SYS_openat, AT_FDCWD, (long)r.host, flags | (follow && !r.magic ? O_NOFOLLOW : 0), (flags & O_CREAT) ? mode : 0, 0);
if (rs == UNSEEN) return hsc(SYS_openat, r.host, flags, (flags & O_CREAT) ? mode : 0, 0);
return hsc(SYS_openat, r.host, flags | (follow && !r.magic ? O_NOFOLLOW : 0), (flags & O_CREAT) ? mode : 0, 0);
}
static int do_openat(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, ...)) {
@@ -864,7 +1071,7 @@ static long fp_stat(int dirfd, const char *path, int flags, struct stat *st) {
long rs = resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
if (rs < 0) return rs;
if (rs == 1) return -ENOENT;
if (rs == UNSEEN) return sc(SYS_newfstatat, AT_FDCWD, (long)r.host, (long)st, flags, 0);
if (rs == UNSEEN) return hsc(SYS_newfstatat, r.host, (long)st, flags, 0);
*st = r.st;
return 0;
}
@@ -1007,7 +1214,7 @@ static long fp_access(int dirfd, const char *path, int mode, int flags) {
? resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r) : FP_SLOW;
if (rs == 1) rs = -ENOENT;
if (rs == 0 && S_ISLNK(r.st.st_mode)) rs = FP_SLOW;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_faccessat, AT_FDCWD, (long)r.host, mode, 0, 0);
if (rs == 0 || rs == UNSEEN) rs = hsc(SYS_faccessat, r.host, mode, 0, 0);
return rs;
}
@@ -1030,7 +1237,7 @@ static long link_text(const struct res *r, char *text, size_t size, int *changed
*changed = 0;
if (in_proc != under(r->host, "/proc", 5)) return FP_SLOW;
if (in_proc) return proc_readlink(r, text, size, changed);
long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)text, PATH_MAX - 1, 0);
long t = hsc(SYS_readlinkat, r->host, (long)text, PATH_MAX - 1, 0);
if (t < 0) return t;
if (t >= PATH_MAX - 1) return FP_SLOW;
if (size && (size_t)t > size) t = size;
@@ -1135,7 +1342,7 @@ char *__getcwd_chk(char *buf, size_t size, size_t room) {
static long fp_mkdir(int dirfd, const char *path, mode_t mode) {
struct res r;
long rs = resolve(dirfd, path, MAY_BE_UNSEEN, &r);
if (rs == 0 || rs == 1 || rs == UNSEEN) rs = sc(SYS_mkdirat, AT_FDCWD, (long)r.host, mode, 0, 0);
if (rs == 0 || rs == 1 || rs == UNSEEN) rs = hsc(SYS_mkdirat, r.host, mode, 0, 0);
return rs;
}
int mkdirat(int dirfd, const char *path, mode_t mode) {
@@ -1172,7 +1379,7 @@ static long fp_unlink(int dirfd, const char *path, int flags) {
if (rs == 0 && (flags & AT_REMOVEDIR) && strcmp(r.guest, "/") == 0) rs = FP_SLOW;
if (rs == 0 || rs == UNSEEN) {
int changes_paths = (flags & AT_REMOVEDIR) || rs == UNSEEN || S_ISLNK(r.st.st_mode);
rs = sc(SYS_unlinkat, AT_FDCWD, (long)r.host, flags, 0, 0);
rs = hsc(SYS_unlinkat, r.host, flags, 0, 0);
if (rs == 0 && changes_paths) forget();
}
return rs;
@@ -1196,9 +1403,14 @@ static long fp_rename(int olddirfd, const char *old, int newdirfd, const char *n
if (rt < 0) rs = rt;
else if (rt == 0 && S_ISDIR(to.st.st_mode)) rs = FP_SLOW;
else {
rs = flags ? sc(SYS_renameat2, AT_FDCWD, (long)from.host, AT_FDCWD, (long)to.host, flags)
: sc(SYS_renameat, AT_FDCWD, (long)from.host, AT_FDCWD, (long)to.host, 0);
if (rs == 0) forget();
struct near a, b;
near_get(from.host, &a);
near_get(to.host, &b);
rs = flags ? sc(SYS_renameat2, a.fd, (long)a.name, b.fd, (long)b.name, flags)
: sc(SYS_renameat, a.fd, (long)a.name, b.fd, (long)b.name, 0);
near_put(&a);
near_put(&b);
if (rs == 0 && (S_ISLNK(from.st.st_mode) || (rt == 0 && S_ISLNK(to.st.st_mode)))) forget();
}
}
return rs;
@@ -1236,7 +1448,10 @@ static long fp_chmod(int dirfd, const char *path, mode_t mode, int flags) {
struct res r;
long rs = flags ? FP_SLOW : resolve(dirfd, path, 1 | MAY_BE_UNSEEN, &r);
if (rs == 1) rs = -ENOENT;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_fchmodat, AT_FDCWD, (long)r.host, mode, 0, 0);
if (rs == 0 || rs == UNSEEN) {
rs = hsc(SYS_fchmodat, r.host, mode, 0, 0);
if (rs == 0) dirs_drop(r.host);
}
return rs;
}
int fchmodat(int dirfd, const char *path, mode_t mode, int flags) {
@@ -1249,7 +1464,10 @@ static long fp_chown(int dirfd, const char *path, uid_t uid, gid_t gid, int flag
struct res r;
long rs = flags & ~AT_SYMLINK_NOFOLLOW ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
if (rs == 1) rs = -ENOENT;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_fchownat, AT_FDCWD, (long)r.host, (long)uid, (long)gid, flags);
if (rs == 0 || rs == UNSEEN) {
rs = hsc(SYS_fchownat, r.host, (long)uid, (long)gid, flags);
if (rs == 0) dirs_drop(r.host);
}
return rs;
}
int fchownat(int dirfd, const char *path, uid_t uid, gid_t gid, int flags) {
@@ -1267,7 +1485,7 @@ static long fp_utimens(int dirfd, const char *path, const struct timespec times[
} else {
rs = flags & ~AT_SYMLINK_NOFOLLOW ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
if (rs == 1) rs = -ENOENT;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_utimensat, AT_FDCWD, (long)r.host, (long)times, flags, 0);
if (rs == 0 || rs == UNSEEN) rs = hsc(SYS_utimensat, r.host, (long)times, flags, 0);
}
return rs;
}
@@ -1509,7 +1727,7 @@ static long socket_address(const struct sockaddr *addr, socklen_t len, int follo
char *slash = strrchr(r.host, '/');
if (!slash || slash == r.host) return FP_SLOW;
*slash = 0;
*dir = sc(SYS_openat, AT_FDCWD, (long)r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0);
*dir = hsc(SYS_openat, r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0);
if (*dir < 0) return FP_SLOW;
hlen = snprintf(out->sun_path, room, "/proc/self/fd/%ld/%s", *dir, slash + 1);
if (hlen >= room) { sc(SYS_close, *dir, 0, 0, 0, 0); *dir = -1; return FP_SLOW; }
@@ -0,0 +1,108 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Thu, 12 Nov 2026 22:00:00 -0500
Subject: [PATCH] fchdir: take the path of the open directory instead of resolving
it again component by component
---
--- a/src/syscall/enter.c
+++ b/src/syscall/enter.c
@@ -46,8 +46,66 @@
#include "tracee/abi.h"
#include "path/path.h"
#include "path/canon.h"
+#include "path/binding.h"
#include "arch.h"
+static int translate_open_directory(Tracee *tracee, char path[PATH_MAX], int fd, struct stat *statl)
+{
+ char guest[PATH_MAX];
+ char mount[PATH_MAX];
+ char parent[PATH_MAX];
+ char link[32];
+ char *slash;
+ const Binding *binding;
+ size_t length;
+ int status;
+
+ status = readlink_proc_pid_fd(tracee->pid, fd, path);
+ if (status < 0 || path[0] != '/')
+ return 1;
+
+ strcpy(guest, path);
+ status = detranslate_path(tracee, guest, NULL);
+ if (status < 0)
+ return 1;
+
+ binding = get_binding(tracee, GUEST, guest);
+ if (binding == NULL)
+ return 1;
+
+ strcpy(parent, binding->guest.path);
+ slash = strrchr(parent, '/');
+ if (slash != NULL && slash != parent) {
+ if ((size_t) (slash - parent) + 3 > PATH_MAX)
+ return 1;
+
+ strcpy(slash, "/.");
+ strcpy(mount, "/");
+ status = canonicalize(tracee, parent, true, mount, 0);
+ if (status < 0 || strcmp(mount, parent) != 0)
+ return 1;
+ }
+
+ status = substitute_binding(tracee, GUEST, guest);
+ if (status < 0 || strcmp(guest, path) != 0)
+ return 1;
+
+ status = snprintf(link, sizeof(link), "/proc/%d/fd/%d", tracee->pid, fd);
+ if (status < 0 || (size_t) status >= sizeof(link))
+ return 1;
+
+ status = stat(link, statl);
+ if (status < 0 || !S_ISDIR(statl->st_mode) || statl->st_nlink == 0)
+ return 1;
+
+ length = strlen(path);
+ if (length + 2 >= PATH_MAX)
+ return 1;
+
+ strcpy(path + (length == 1 ? 0 : length), "/.");
+ return 0;
+}
+
/**
* Translate @path and put the result in the @tracee's memory address
* space pointed to by the @reg argument of the current syscall. See
@@ -193,13 +251,16 @@
dirfd = peek_reg(tracee, CURRENT, SYSARG_1);
}
- status = translate_path(tracee, path, dirfd, oldpath, true);
- if (status < 0)
- break;
+ if (syscall_number == PR_chdir
+ || translate_open_directory(tracee, path, dirfd, &statl) != 0) {
+ status = translate_path(tracee, path, dirfd, oldpath, true);
+ if (status < 0)
+ break;
- status = lstat(path, &statl);
- if (status < 0)
- break;
+ status = lstat(path, &statl);
+ if (status < 0)
+ break;
+ }
/* Check this directory is accessible. */
if ((statl.st_mode & S_IXUSR) == 0)
@@ -208,7 +269,7 @@
- if (getenv("PROOT_FASTPATH") != NULL) {
+ if (syscall_number == PR_chdir && getenv("PROOT_FASTPATH") != NULL) {
int fd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC);
+3 -2
View File
@@ -17,8 +17,9 @@ $(cat signed/SHA256SUMS.txt)
gh release delete "$tag" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null || true
gh release create "$tag" -R "$CI_REPO" --target main --prerelease \
--title "main ${GITHUB_SHA::7}" --notes "$notes" signed/*
gh release list -R "$CI_REPO" -L 200 --json tagName,publishedAt \
--jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.publishedAt) | reverse | .['"$KEEP"':][] | .tagName' |
cutoff=$(date -u -d "-${KEEP_DAYS} days" +%Y-%m-%dT%H:%M:%SZ)
gh release list -R "$CI_REPO" -L 1000 --exclude-drafts --json tagName,publishedAt \
--jq '.[] | select((.tagName | startswith("main-")) and .publishedAt < "'"$cutoff"'") | .tagName' |
while IFS= read -r old; do
if [ "$old" = "$tag" ]; then
continue
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Deletes test builds nobody can still need: a closed PR's at once, a merged PR's once a Preview build carries the merge."""
from __future__ import annotations
import argparse
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from update_catalog import ApiError, GitHub, current_file, in_preview, previous_catalog, q # noqa: E402
TEST_TAG = re.compile(r"^pr-([1-9][0-9]*)(\.0)?$")
def retired(pull: dict, source: GitHub, repo: str, preview_commit: str | None) -> bool:
if pull.get("state") == "open":
return False
if not pull.get("merged_at"):
return True
return in_preview(source, repo, pull, preview_commit)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--source-repo", default=os.environ.get("GITHUB_REPOSITORY", "Droid-Deck/DroidDeck"))
parser.add_argument("--ci-repo", default="Droid-Deck/DroidDeck-CI")
parser.add_argument("--pr", type=int, help="only this PR's test build")
args = parser.parse_args()
source = GitHub(os.environ.get("SOURCE_GITHUB_TOKEN", ""))
ci = GitHub(os.environ["CI_GITHUB_TOKEN"])
catalog = previous_catalog(current_file(ci, args.ci_repo, "catalog.json")) or {}
preview_commit = (catalog.get("preview") or {}).get("commit")
failed = False
for release in ci.get_all(f"/repos/{args.ci_repo}/releases"):
tag = release.get("tag_name") or ""
match = TEST_TAG.fullmatch(tag)
if not match or (args.pr and int(match.group(1)) != args.pr):
continue
number = int(match.group(1))
try:
pull = source.get(f"/repos/{args.source_repo}/pulls/{number}")
if not retired(pull, source, args.source_repo, preview_commit):
print(f"Keeping {tag}: PR #{number} is {'open' if pull.get('state') == 'open' else 'merged, not yet in a Preview build'}")
continue
ci.request("DELETE", f"/repos/{args.ci_repo}/releases/{release['id']}")
try:
ci.request("DELETE", f"/repos/{args.ci_repo}/git/refs/tags/{q(tag)}")
except ApiError as e:
if e.status not in (404, 422):
raise
print(f"Deleted {tag}")
except ApiError as e:
print(f"{tag}: {e}", file=sys.stderr)
failed = True
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+33 -8
View File
@@ -14,20 +14,23 @@ ROOT = Path(__file__).resolve().parents[2]
MANIFEST = Path('app/build/runtime-inputs.json')
PACKS = Path('app/build/packs')
PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet',
'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft',
'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar',
'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt',
'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'}
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so'),
'lib/arm64-v8a/libproot-loader.so': ('proot', 'libproot-loader.so')}
# DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker.
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')}
# The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory.
PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': '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', 'butler', 'powervr', 'ubisoft']
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt']
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/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'tools/gpuload',
'tools/gpuload', 'app/src/main/resources/rockstar/legacy-cipher.bin',
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
'app/src/main/cpp/venc/venc_proto.h',
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
@@ -109,7 +112,8 @@ def required():
['comet', 'GalaxyCommunication.exe', 'update-permissions.exe', 'LICENSE', 'version']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xbox/' + name for name in
['xodus-cli', 'xodus-service', 'version', 'backend.lock.json', 'runtime.lock.json', 'LICENSE.xodus', 'LICENSE.nexus', 'LICENSE.LGPL-2.1', 'LICENSE.nghttp2',
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll']]
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll',
'compat/PlayFabGameSave.dll', 'LICENSE.runtime-compat']]
for driver in ['linux-wine11', 'linux-wine11-systhread']:
paths += ['assets/directaudio/' + driver + '/' + name for name in
['aarch64-unix/winedirectaudio.so', 'aarch64-windows/winedirectaudio.drv',
@@ -210,12 +214,30 @@ def pack_digests(root, name):
return digests
def windows_binaries(package):
found = []
for info in package.infolist():
if info.is_dir():
continue
with package.open(info) as entry:
if entry.read(2) == b'MZ':
found.append(info.filename)
return found
def check_apk(apk, root=ROOT):
data = verify(root)
packs = {name: pack_digests(root, name) for name in PACK_NAMES
if name != 'ubisoft' or (root / PACKS / 'ubisoft.tar.zst').is_file()}
if name not in ('ubisoft', 'rockstar', 'dirt') or (root / PACKS / (name + '.tar.zst')).is_file()}
for name, rel in PROOT_LOADER.items():
if packs['proot'].get(rel) != data['outputs'][name]['sha256']:
raise ValueError('Add-on pack proot is missing or has a stale ' + rel)
with ZipFile(apk) as package:
names = set(package.namelist())
for name in sorted(names):
prefix = next((p for p in PACKED if name.startswith(p)), None)
if prefix:
raise ValueError('APK still carries ' + name + ', which the ' + PACKED[prefix] + ' pack provides')
for library in PACKED_LIBRARIES:
if library in names:
raise ValueError('APK still carries ' + library + ', which the tracking pack provides')
@@ -242,6 +264,9 @@ def check_apk(apk, root=ROOT):
raise ValueError('APK missing ' + name)
if hashlib.sha256(content).hexdigest() != output['sha256']:
raise ValueError('APK has stale runtime input: ' + name)
found = windows_binaries(package)
if found:
raise ValueError('APK carries Windows executables, which ship in add-on packs: ' + ', '.join(found))
if __name__ == '__main__':
+26 -12
View File
@@ -27,7 +27,7 @@ if [ "$pkg" = "$P" ]; then
else
python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
"$P.pairingguide=$pkg.pairingguide" "$P.pin=$pkg.pin" \
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" \
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
@@ -40,23 +40,37 @@ if [ "$pkg" != "$P" ]; then
&& die "$variant: the manifest still names $P in an authority or task"
fi
"$BUILD_TOOLS/zipalign" -p -f 4 "$work/renamed.apk" "$work/aligned.apk"
"$BUILD_TOOLS/apksigner" rotate --out "$work/lineage" \
--old-signer --ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \
--ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD --set-rollback false \
--new-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \
--ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD
"$BUILD_TOOLS/apksigner" sign \
--ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \
--ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD \
--next-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \
--ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD \
--lineage "$work/lineage" --rotation-min-sdk-version 28 \
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --v4-signing-enabled false \
--out "$out" "$work/aligned.apk"
rm -f "$out.idsig"
sign() {
"$BUILD_TOOLS/apksigner" sign \
--ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \
--ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD \
--next-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \
--ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD \
--lineage "$work/lineage" --rotation-min-sdk-version 28 \
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --v4-signing-enabled false \
--out "$2" "$1"
rm -f "$2.idsig"
}
companion=assets/shortcuts.apk
if unzip -l "$work/renamed.apk" "$companion" >/dev/null 2>&1; then
mkdir -p "$work/companion/assets"
unzip -p "$work/renamed.apk" "$companion" > "$work/companion-in.apk"
sign "$work/companion-in.apk" "$work/companion/$companion"
companion_v3=$("$BUILD_TOOLS/apksigner" verify --min-sdk-version 28 --print-certs "$work/companion/$companion" | sed -n 's/^.*Signer.* certificate SHA-256 digest: //p' | sort -u)
[ "$companion_v3" = "$expected" ] || die "$variant: the system keys companion is not signed with DroidDeck's key"
(cd "$work/companion" && zip -q -0 "$work/renamed.apk" "$companion")
fi
"$BUILD_TOOLS/zipalign" -p -f 4 "$work/renamed.apk" "$work/aligned.apk"
sign "$work/aligned.apk" "$out"
"$BUILD_TOOLS/apksigner" verify --min-sdk-version 26 "$out" >/dev/null || die "$variant: does not verify"
listing=$(unzip -l "$out")
+184 -44
View File
@@ -17,6 +17,7 @@ API = "https://api.github.com"
SHA256 = re.compile(r"^[0-9a-f]{64}$")
PR_TAG = re.compile(r"^pr-([1-9][0-9]*)$")
MAIN_TAG = re.compile(r"^main-([0-9a-f]{7,40})$")
MERGED_PR = re.compile(r"\[PR #([1-9][0-9]*)\]\(")
class ApiError(RuntimeError):
@@ -53,6 +54,20 @@ class GitHub:
def get(self, path: str):
return self.request("GET", path)
def get_all(self, path: str, limit: int = 1000) -> list:
items = []
page = 1
sep = "&" if "?" in path else "?"
while len(items) < limit:
batch = self.get(f"{path}{sep}per_page=100&page={page}")
if not batch:
break
items.extend(batch)
if len(batch) < 100:
break
page += 1
return items
def put(self, path: str, body):
return self.request("PUT", path, body)
@@ -100,15 +115,20 @@ def parse_variants(text: str) -> list[tuple[str, str]]:
return out
def published_millis(release: dict, prefer_updated: bool = False) -> int:
value = (
release.get("updated_at") if prefer_updated else None
) or release.get("published_at") or release.get("created_at")
def iso_millis(value: str | None) -> int:
if not value:
return 0
return int(dt.datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000)
def published_millis(release: dict, prefer_updated: bool = False) -> int:
return iso_millis(
(release.get("updated_at") if prefer_updated else None)
or release.get("published_at")
or release.get("created_at")
)
def paragraphs(markdown: str) -> list[str]:
return [p.strip() for p in re.split(r"\n\s*\n", markdown.replace("\r", "")) if p.strip()]
@@ -164,8 +184,12 @@ def source_meta(source: GitHub, repo: str, ref: str):
return code, version, variants, signer
def asset_for_suffix(assets: list[dict], suffix: str, all_suffixes: list[str]):
def asset_for_suffix(assets: list[dict], suffix: str, all_suffixes: list[str], commit: str = ""):
others = [s for s in all_suffixes if s and s != suffix]
# A test build's release briefly holds the previous push's APKs too; the one named for this commit wins.
current = f"-{commit[:7].lower()}{suffix}.apk" if len(commit) >= 7 else None
if current:
assets = sorted(assets, key=lambda a: not (a.get("name") or "").lower().endswith(current))
for asset in assets:
name = asset.get("name", "")
if not name.endswith(f"{suffix}.apk"):
@@ -195,11 +219,12 @@ def release_entry(
title: str,
summary: str,
prefer_updated: bool = False,
extra: dict | None = None,
):
suffixes = [suffix for _, suffix in variants]
apks = {}
for package, suffix in variants:
asset = asset_for_suffix(release.get("assets") or [], suffix, suffixes)
asset = asset_for_suffix(release.get("assets") or [], suffix, suffixes, commit)
if not asset:
continue
asset.update(
@@ -220,28 +245,35 @@ def release_entry(
"versionCode": version_code,
"publishedAt": published_millis(release, prefer_updated),
"url": release.get("html_url") or "",
**(extra or {}),
"apks": apks,
}
def complete_apks(preview: dict, variants: list[tuple[str, str]]) -> bool:
apks = preview.get("apks") or {}
return set(apks) == {package for package, _ in variants} and all(
SHA256.fullmatch((apk.get("sha256") or "").lower()) and SHA256.fullmatch((apk.get("signerSha256") or "").lower())
for apk in apks.values()
)
def newest_complete(ordered: list[dict], variants: list[tuple[str, str]]) -> dict | None:
"""The Preview to offer and to judge merges by: the newest one whose APKs have all been uploaded."""
return next((p for p in ordered if complete_apks(p, variants)), None)
def preview_history_entry(release: dict, preview: dict, variants: list[tuple[str, str]]):
tag = release.get("tag_name") or ""
tag_match = MAIN_TAG.fullmatch(tag)
commit = (preview.get("commit") or "").lower()
expected_packages = {package for package, _ in variants}
apks = preview.get("apks") or {}
if (
release.get("draft")
or not release.get("prerelease")
or not tag_match
or not re.fullmatch(r"[0-9a-f]{40}", commit)
or not commit.startswith(tag_match.group(1))
or set(apks) != expected_packages
or any(
not SHA256.fullmatch((apk.get("sha256") or "").lower())
or not SHA256.fullmatch((apk.get("signerSha256") or "").lower())
for apk in apks.values()
)
or not complete_apks(preview, variants)
):
return None
return {
@@ -289,8 +321,84 @@ def stable_app_release(releases: list[dict]) -> dict | None:
return max(apps, key=lambda r: r.get("published_at") or r.get("created_at") or "", default=None)
def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) -> dict:
stable_release = stable_app_release(source.get(f"/repos/{source_repo}/releases?per_page=100"))
def merged_pr(release: dict) -> int:
ps = paragraphs(release.get("body") or "")
match = MERGED_PR.search(ps[0]) if ps else None
return int(match.group(1)) if match else 0
class Cache:
"""Commit facts carried over from the published catalog, so a run only asks GitHub about new builds."""
def __init__(self, previous: dict | None):
self.commits: dict[str, dict] = {}
for entry in (previous or {}).get("previews") or []:
commit = (entry.get("commit") or "").lower()
if commit and entry.get("committedAt"):
self.commits[commit] = {"author": entry.get("author") or "", "committedAt": entry["committedAt"]}
def commit(self, gh: GitHub, repo: str, sha: str) -> dict:
sha = sha.lower()
if sha not in self.commits:
try:
obj = gh.get(f"/repos/{repo}/commits/{q(sha)}")
self.commits[sha] = {
"author": (obj.get("author") or {}).get("login") or "",
"committedAt": iso_millis(((obj.get("commit") or {}).get("committer") or {}).get("date")),
}
except ApiError:
self.commits[sha] = {"author": "", "committedAt": 0}
return self.commits[sha]
MERGED_GRACE_DAYS = 3
def in_preview(source: GitHub, repo: str, pull: dict, preview_commit: str | None, now_millis: int | None = None) -> bool:
"""Whether the newest Preview build was built from a main that already holds the PR's merge.
A merge that main's build skips (documentation only) never reaches a Preview build, so after
MERGED_GRACE_DAYS it counts as carried anyway.
"""
merge = pull.get("merge_commit_sha") or ""
merged_at = iso_millis(pull.get("merged_at"))
if not merged_at or not merge:
return False
now = now_millis if now_millis is not None else int(time.time() * 1000)
if now - merged_at > MERGED_GRACE_DAYS * 86_400_000:
return True
if not preview_commit:
return False
try:
status = source.get(f"/repos/{repo}/compare/{q(merge)}...{q(preview_commit)}").get("status")
except ApiError:
return False
return status in ("ahead", "identical")
def keeps_test_build(pull: dict) -> bool:
"""An open PR keeps its test build; a merged one keeps it until a Preview build carries the merge."""
if pull.get("draft") or (pull.get("base") or {}).get("ref") != "main":
return False
return pull.get("state") == "open" or bool(pull.get("merged_at"))
def unique_previews(previews: list[dict]) -> list[dict]:
ordered = sorted(previews, key=lambda r: (r.get("committedAt") or r["publishedAt"], r["publishedAt"]), reverse=True)
result = []
seen = set()
for preview in ordered:
commit = preview["commit"].lower()
if commit in seen:
continue
seen.add(commit)
result.append(preview)
return result
def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, previous: dict | None = None) -> dict:
cache = Cache(previous)
stable_release = stable_app_release(source.get_all(f"/repos/{source_repo}/releases", limit=300))
stable = None
if stable_release:
@@ -307,12 +415,15 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
signer,
title,
summary,
extra={"committedAt": cache.commit(source, source_repo, stable_commit)["committedAt"]},
)
releases = ci.get(f"/repos/{ci_repo}/releases?per_page=100")
main_code, _, main_variants, main_signer = source_meta(source, source_repo, "main")
releases = ci.get_all(f"/repos/{ci_repo}/releases")
previews = []
preview_history = []
tests = []
merged_pulls: dict[int, dict | None] = {}
for release in releases:
if release.get("draft"):
continue
@@ -322,12 +433,20 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
commit = main_commit(release)
if not commit:
continue
try:
code, _, variants, signer = source_meta(source, source_repo, commit)
except ApiError:
continue
code_text = release_body_value(release.get("body") or "", "VersionCode")
if code_text and code_text.isdigit():
code, variants, signer = int(code_text), main_variants, main_signer
else:
try:
code, _, variants, signer = source_meta(source, source_repo, commit)
except ApiError:
continue
facts = cache.commit(source, source_repo, commit)
title, summary = ci_description(release)
preview = release_entry(release, commit, 0, None, code, variants, signer, title, summary)
preview = release_entry(
release, commit, 0, None, code, variants, signer, title, summary,
extra={"mergedPr": merged_pr(release), "author": facts["author"], "committedAt": facts["committedAt"]},
)
previews.append(preview)
history_entry = preview_history_entry(release, preview, variants)
if history_entry:
@@ -345,21 +464,20 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
pull = source.get(f"/repos/{source_repo}/pulls/{pr}")
except ApiError:
continue
if pull.get("state") != "open" or pull.get("draft") or pull.get("base", {}).get("ref") != "main":
if not keeps_test_build(pull):
continue
commit = release_body_value(body, "Commit")
if not commit or not re.fullmatch(r"[0-9a-f]{7,40}", commit):
continue
base_ref = release_body_value(body, "Base") or pull["base"]["sha"]
try:
base_code, _, variants, signer = source_meta(source, source_repo, base_ref)
except ApiError:
continue
version_code_text = release_body_value(body, "VersionCode")
if version_code_text and version_code_text.isdigit():
version_code = int(version_code_text)
else:
version_code = base_code
base_ref = release_body_value(body, "Base") or pull["base"]["sha"]
try:
version_code = source_meta(source, source_repo, base_ref)[0]
except ApiError:
continue
try:
changed = source.get(f"/repos/{source_repo}/pulls/{pr}/files?per_page=100")
if any(item.get("filename") == "app/build.gradle" for item in changed):
@@ -368,6 +486,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
except (ApiError, KeyError):
pass
title, summary = ci_description(release)
merged_pulls[pr] = pull if pull.get("state") != "open" else None
tests.append(
release_entry(
release,
@@ -375,52 +494,72 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
pr,
None,
version_code,
variants,
signer,
main_variants,
main_signer,
title,
summary,
prefer_updated=True,
extra={
"author": (pull.get("user") or {}).get("login") or "",
"headCommit": (pull.get("head") or {}).get("sha") or "",
"builtAt": max(
(iso_millis(a.get("updated_at") or a.get("created_at"))
for a in release.get("assets") or [] if (a.get("name") or "").endswith(".apk")),
default=0,
),
},
)
)
previews.sort(key=lambda r: r["publishedAt"], reverse=True)
ordered = unique_previews(previews)
usable = newest_complete(ordered, main_variants)
newest = usable["commit"] if usable else None
tests = [t for t in tests if not (merged_pulls.get(t["pr"]) and in_preview(source, source_repo, merged_pulls[t["pr"]], newest))]
tests.sort(key=lambda r: r["publishedAt"], reverse=True)
return {
"schema": 1,
"sourceRepo": source_repo,
"ciRepo": ci_repo,
"generatedAt": int(time.time() * 1000),
"mainVersionCode": main_code,
"stable": stable,
"preview": previews[0] if previews else None,
"preview": usable,
"recentPreviews": recent_previews(preview_history),
"previews": ordered,
"tests": tests,
}
def current_file(ci: GitHub, repo: str, path: str):
def current_file(ci: GitHub, repo: str, path: str, branch: str = "main"):
try:
return ci.get(f"/repos/{repo}/contents/{q(path)}?ref=main")
return ci.get(f"/repos/{repo}/contents/{q(path)}?ref={q(branch)}")
except ApiError as e:
if e.status == 404:
return None
raise
def publish_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, path: str):
def previous_catalog(old: dict | None) -> dict | None:
try:
return json.loads(base64.b64decode(old["content"])) if old and old.get("content") else None
except Exception:
return None
def publish_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, path: str, branch: str = "main"):
for attempt in range(4):
catalog = build_catalog(source, ci, source_repo, ci_repo)
content = (json.dumps(catalog, indent=2, sort_keys=False) + "\n").encode()
old = current_file(ci, ci_repo, path)
old = current_file(ci, ci_repo, path, branch)
catalog = build_catalog(source, ci, source_repo, ci_repo, previous_catalog(old))
content = (json.dumps(catalog, separators=(",", ":")) + "\n").encode()
body = {
"message": "ci: refresh DroidDeck update catalog",
"content": base64.b64encode(content).decode(),
"branch": "main",
"branch": branch,
}
if old:
body["sha"] = old["sha"]
try:
old_bytes = base64.b64decode(old["content"])
old_json = json.loads(old_bytes)
old_json = dict(previous_catalog(old) or {})
old_json.pop("generatedAt", None)
new_json = dict(catalog)
new_json.pop("generatedAt", None)
@@ -431,7 +570,7 @@ def publish_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str,
pass
try:
ci.put(f"/repos/{ci_repo}/contents/{q(path)}", body)
print(f"published https://raw.githubusercontent.com/{ci_repo}/main/{path}")
print(f"published https://raw.githubusercontent.com/{ci_repo}/{branch}/{path}")
return catalog
except ApiError as e:
if e.status not in (409, 422) or attempt == 3:
@@ -445,6 +584,7 @@ def main():
parser.add_argument("--source-repo", default="Droid-Deck/DroidDeck")
parser.add_argument("--ci-repo", default="Droid-Deck/DroidDeck-CI")
parser.add_argument("--path", default="catalog.json")
parser.add_argument("--branch", default="main")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
@@ -455,7 +595,7 @@ def main():
else:
if not os.environ.get("CI_GITHUB_TOKEN"):
raise SystemExit("CI_GITHUB_TOKEN is required to publish")
publish_catalog(source, ci, args.source_repo, args.ci_repo, args.path)
publish_catalog(source, ci, args.source_repo, args.ci_repo, args.path, args.branch)
if __name__ == "__main__":
+22 -2
View File
@@ -2,13 +2,33 @@
import json
import os
import subprocess
import sys
import time
from urllib.parse import urlencode
from check_authorship import check_revision, event_violations
def api(path, *args):
return json.loads(subprocess.check_output(["gh", "api", path, *args], text=True))
RATE_LIMIT_WAIT = 1800
def rate_limit_wait():
try:
reset = json.loads(subprocess.check_output(["gh", "api", "rate_limit"], text=True))["resources"]["core"]["reset"]
except (subprocess.CalledProcessError, KeyError, ValueError):
return 60
return max(5, min(RATE_LIMIT_WAIT, reset - time.time() + 5))
def api(path, *args, attempts=3):
for attempt in range(attempts):
done = subprocess.run(["gh", "api", path, *args], text=True, capture_output=True)
if done.returncode == 0:
return json.loads(done.stdout)
if "--method" in args or "rate limit" not in done.stderr.lower() or attempt == attempts - 1:
sys.stderr.write(done.stderr)
raise subprocess.CalledProcessError(done.returncode, done.args, done.stdout, done.stderr)
time.sleep(rate_limit_wait())
def compilation_state(run, jobs):
+1
View File
@@ -0,0 +1 @@
/target/
+105
View File
@@ -0,0 +1,105 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "droiddeck-rockstar-launcher"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "droiddeck-rockstar-launcher"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-only"
publish = false
[[bin]]
name = "Launcher"
path = "src/main.rs"
[dependencies]
serde_json = "1"
[profile.release]
opt-level = "s"
lto = true
panic = "abort"
strip = true
+36
View File
@@ -0,0 +1,36 @@
# Rockstar launcher service
`Launcher.exe` starts the selected installed game and serves its launcher pipes. The Android app obtains title authorization from Rockstar. Refresh credentials stay in Android Keystore-backed storage.
The handoff is mode 0600, expires after 90 seconds and is deleted before starting the game. Legacy launches carry server-issued launch material. SDK launches also carry a short-lived ROS ticket and account identity; those values are kept in memory after the handoff is consumed and are not logged. Pipes reject remote clients and check the client process against the launched child. No game files are patched.
GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path.
The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified.
GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides.
Raw launcher identity requests use `INIT:<nonce>:` with a terminating colon. Framed requests carry their payload length. The reply echoes the complete challenge after `TINI:launcher:`; partial reads do not complete a raw request.
`build.sh` builds 32-bit and 64-bit executables with the GNU Windows targets for the `rockstar` add-on pack. The app downloads the pack after Rockstar sign-in, or when a launch finds the service missing, and stages it in the Linux runtime. `legacy-cipher.bin` contains the fixed client protocol tables, not account credentials or APK signing keys.
Run the protocol tests with:
```sh
cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml
```
The optional `capture` example records a first-party launcher reply to a new local file. Run it on Windows or Wine while launching the corresponding game in Rockstar's launcher:
```powershell
cargo run --release --example capture --manifest-path tools/rockstar-launcher/Cargo.toml -- --pipe GTA-VC_Pipe --output 'C:\captures\reply.bin'
```
On Linux, cross-compile the example and run it in the same Wine prefix as Rockstar's launcher:
```sh
cargo build --release --locked --example capture --target x86_64-pc-windows-gnu --manifest-path tools/rockstar-launcher/Cargo.toml
WINEPREFIX=/path/to/launcher-prefix wine tools/rockstar-launcher/target/x86_64-pc-windows-gnu/release/examples/capture.exe --pipe GTA-VC_Pipe --output 'Z:\tmp\reply.bin'
```
Captures contain live launch material. Keep them outside source control; the tool prints only the message tag and payload length.
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
out=${1:-"$here/../../app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar"}
mkdir -p "$out"
for target in i686-pc-windows-gnu x86_64-pc-windows-gnu; do
rustup target add "$target" >/dev/null 2>&1 || true
cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target"
name=Launcher64.exe
[[ "$target" == i686-* ]] && name=Launcher32.exe
install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/Launcher.exe" "$out/$name"
done
@@ -0,0 +1,65 @@
#[cfg(windows)]
fn main() -> std::io::Result<()> {
use droiddeck_rockstar_launcher::{pipe::Pipe, Frame, Length};
use std::fs::OpenOptions;
use std::io::{self, Read, Write};
use std::time::Duration;
struct Recording<'a> {
source: &'a mut Pipe,
output: &'a mut std::fs::File,
}
impl Read for Recording<'_> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let size = self.source.read(buffer)?;
self.output.write_all(&buffer[..size])?;
Ok(size)
}
}
let args: Vec<_> = std::env::args_os().collect();
let output = args
.windows(2)
.find(|pair| pair[0] == "--output")
.map(|pair| pair[1].clone())
.map(std::path::PathBuf::from)
.unwrap_or(std::env::current_exe()?.with_file_name("reference-reply.bin"));
let mut file = OpenOptions::new()
.create_new(true)
.write(true)
.open(output)?;
let pipe_name = args
.windows(2)
.find(|pair| pair[0] == "--pipe")
.map(|pair| pair[1].to_string_lossy().into_owned())
.unwrap_or_else(|| "GTA-VC_Pipe".to_owned());
let mut pipe = Pipe::connect(&pipe_name, Duration::from_secs(90))?;
Frame {
tag: *b"COLE",
payload: Vec::new(),
nul_terminated: true,
}
.write(&mut pipe, Length::Total)?;
let reply = Frame::read(
&mut Recording {
source: &mut pipe,
output: &mut file,
},
Length::Body,
);
file.sync_all()?;
let reply = reply?;
println!(
"Received {} ({} payload bytes)",
String::from_utf8_lossy(&reply.tag),
reply.payload.len()
);
Ok(())
}
#[cfg(not(windows))]
fn main() {
eprintln!("The reference pipe client runs on Windows or Wine.");
std::process::exit(1);
}
@@ -0,0 +1,80 @@
#[cfg(windows)]
fn run() -> Result<(), Box<dyn std::error::Error>> {
use droiddeck_rockstar_launcher::{pipe::Pipe, sdk::Message, Frame, Length};
use std::io::{Read, Write};
for (path, framed) in [
(b"\\\\.\\pipe\\ProbeLauncherPipe\0".as_slice(), true),
(b"\\\\.\\pipe\\RawProbeLauncher_Pipe\0".as_slice(), false),
] {
let name = std::str::from_utf8(&path[9..path.len() - 1])?;
let mut pipe = Pipe::connect(name, std::time::Duration::from_secs(10))?;
let request = b"INIT:42:";
if framed {
let mut bytes = (request.len() as u32).to_le_bytes().to_vec();
bytes.extend_from_slice(request);
pipe.write_all(&bytes)?;
let response = Frame::read(&mut pipe, Length::Body)?;
if response.tag != *b"TINI" || response.payload != b"launcher:42:" {
return Err("invalid framed launcher identity reply".into());
}
} else {
pipe.write_all(b"INIT:4")?;
std::thread::sleep(std::time::Duration::from_millis(20));
pipe.write_all(b"2:")?;
let mut response = vec![0; b"TINI:launcher:42:".len()];
pipe.read_exact(&mut response)?;
if response != b"TINI:launcher:42:" {
return Err("invalid raw launcher identity reply".into());
}
}
}
let args: Vec<_> = std::env::args().collect();
let instance: u32 = args
.iter()
.find_map(|arg| arg.strip_prefix("-processInstance="))
.ok_or("missing instance")?
.parse()?;
let output = args
.windows(2)
.find(|pair| pair[0] == "--result")
.map(|pair| &pair[1])
.ok_or("missing result path")?;
let mut pipe = Pipe::connect(
&format!("chrome.rgsc_gameinst_{instance}"),
std::time::Duration::from_secs(10),
)?;
if Message::read(&mut pipe)?.kind != 0xffff {
return Err("missing transport hello".into());
}
Message {
routing: i32::MAX,
kind: 0x40000,
flags: 2,
payload: 4u32.to_le_bytes().to_vec(),
}
.write(&mut pipe)?;
let expected = [0x30002, 0x30003, 0x30004, 0x30000];
for kind in expected {
let message = Message::read(&mut pipe)?;
if message.kind != kind || message.routing != i32::MAX || message.flags != 2 {
return Err("unexpected SDK message envelope".into());
}
if kind == 0x30002 && message.payload != [3, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
{
return Err("unexpected fixture account".into());
}
if kind == 0x30000 && message.payload != 4u32.to_le_bytes() {
return Err("launcher hello lost its context".into());
}
}
std::fs::write(output, "SDK handshake accepted")?;
Ok(())
}
fn main() {
#[cfg(windows)]
if let Err(error) = run() {
eprintln!("SDK probe failed: {error}");
std::process::exit(1);
}
}
+170
View File
@@ -0,0 +1,170 @@
use std::collections::BTreeSet;
use std::io::{self, Read};
const LIMIT: usize = 4096;
fn invalid() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
"invalid launcher identity request",
)
}
fn collect(bytes: &[u8], names: &mut BTreeSet<String>) {
let prefix = br"\\.\pipe\";
for (index, window) in bytes.windows(prefix.len()).enumerate() {
if window != prefix {
continue;
}
let tail = &bytes[index + prefix.len()..];
let Some(end) = tail.iter().take(97).position(|byte| *byte == 0) else {
continue;
};
let name = &tail[..end];
if !name.is_empty()
&& name
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(byte))
{
let name = std::str::from_utf8(name).unwrap();
if name.ends_with("LauncherPipe") || name.ends_with("Launcher_Pipe") {
names.insert(name.to_owned());
}
}
}
}
pub fn pipe_names(reader: &mut impl Read) -> io::Result<Vec<String>> {
let mut names = BTreeSet::new();
let mut carry = Vec::new();
let mut chunk = [0; 65536];
let mut total = 0usize;
loop {
let count = reader.read(&mut chunk)?;
if count == 0 {
break;
}
total += count;
if total > 256 * 1024 * 1024 {
return Err(invalid());
}
carry.extend_from_slice(&chunk[..count]);
collect(&carry, &mut names);
for offset in 0..2 {
let ascii: Vec<_> = carry[offset..]
.chunks_exact(2)
.map(|pair| if pair[1] == 0 { pair[0] } else { 0 })
.collect();
collect(&ascii, &mut names);
}
if names.len() > 4 {
return Err(invalid());
}
carry.drain(..carry.len().saturating_sub(256));
}
Ok(names.into_iter().collect())
}
pub fn exchange(reader: &mut impl Read) -> io::Result<Vec<u8>> {
let mut header = [0; 4];
reader.read_exact(&mut header)?;
let framed = header != *b"INIT";
let mut request = if framed {
let size = u32::from_le_bytes(header) as usize;
if !(6..=LIMIT).contains(&size) {
return Err(invalid());
}
let mut bytes = vec![0; size];
reader.read_exact(&mut bytes)?;
bytes
} else {
let mut bytes = header.to_vec();
let mut byte = [0];
reader.read_exact(&mut byte)?;
if byte[0] != b':' {
return Err(invalid());
}
bytes.push(b':');
loop {
reader.read_exact(&mut byte)?;
if !(32..127).contains(&byte[0]) || bytes.len() >= 261 {
return Err(invalid());
}
bytes.push(byte[0]);
if byte[0] == b':' {
break;
}
}
bytes
};
if request.last() == Some(&0) {
request.pop();
}
let challenge = request.strip_prefix(b"INIT:").ok_or_else(invalid)?;
if challenge.is_empty()
|| !framed && challenge == b":"
|| challenge.len() > 256
|| !challenge.iter().all(|byte| (32..127).contains(byte))
{
return Err(invalid());
}
let mut reply = b"TINI:launcher:".to_vec();
reply.extend_from_slice(challenge);
if framed {
let mut bytes = (reply.len() as u32).to_le_bytes().to_vec();
bytes.extend_from_slice(&reply);
Ok(bytes)
} else {
Ok(reply)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn discovers_ascii_and_wide_pipe_names_across_chunks() {
let mut bytes = vec![0; 65530];
bytes.extend_from_slice(br"\\.\pipe\GameLauncherPipe");
bytes.push(0);
for value in "\\\\.\\pipe\\OtherLauncher_Pipe\0".encode_utf16() {
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes.extend_from_slice(br"\\.\pipe\..\outsideLauncherPipe");
bytes.push(0);
assert_eq!(
pipe_names(&mut Cursor::new(bytes)).unwrap(),
["GameLauncherPipe", "OtherLauncher_Pipe"]
);
}
#[test]
fn identity_replies_echo_only_a_valid_challenge() {
struct Split<R>(R);
impl<R: Read> Read for Split<R> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let size = buffer.len().min(2);
self.0.read(&mut buffer[..size])
}
}
assert_eq!(
exchange(&mut Split(Cursor::new(b"INIT:123456789:\0"))).unwrap(),
b"TINI:launcher:123456789:"
);
let request = b"INIT:nonce:123:";
let mut bytes = (request.len() as u32).to_le_bytes().to_vec();
bytes.extend_from_slice(request);
let reply = exchange(&mut Cursor::new(bytes)).unwrap();
assert_eq!(
u32::from_le_bytes(reply[..4].try_into().unwrap()) as usize,
reply.len() - 4
);
assert_eq!(&reply[4..], b"TINI:launcher:nonce:123:");
assert!(exchange(&mut Cursor::new(b"INIT:")).is_err());
assert!(exchange(&mut Cursor::new(b"INIT:a\0b")).is_err());
assert!(exchange(&mut Cursor::new(b"INIT:unterminated")).is_err());
assert!(exchange(&mut Cursor::new([255; 4])).is_err());
}
}
+351
View File
@@ -0,0 +1,351 @@
use std::io::{self, Read, Write};
#[cfg(windows)]
pub mod pipe;
pub mod identity;
pub mod sdk;
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
const OVERHEAD: usize = 4 + 4 + 1;
pub fn wait_for_game(
child: &mut std::process::Child,
handshake: std::sync::mpsc::Receiver<io::Result<()>>,
) -> io::Result<std::process::ExitStatus> {
use std::sync::mpsc::RecvTimeoutError;
loop {
match handshake.recv_timeout(std::time::Duration::from_millis(10)) {
Ok(Ok(())) => return child.wait(),
result @ (Ok(Err(_)) | Err(RecvTimeoutError::Disconnected)) => {
let error = match result {
Ok(Err(error)) => error,
_ => io::Error::new(
io::ErrorKind::BrokenPipe,
"Rockstar handshake worker stopped",
),
};
let _ = child.kill();
child.wait()?;
return Err(error);
}
Err(RecvTimeoutError::Timeout) => {
if let Some(status) = child.try_wait()? {
return Ok(status);
}
}
}
}
}
#[derive(Clone, Copy)]
pub enum Length {
Total,
Body,
}
impl Length {
fn header_bytes(self) -> usize {
match self {
Self::Total => 0,
Self::Body => 4,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Frame {
pub tag: [u8; 4],
pub payload: Vec<u8>,
pub nul_terminated: bool,
}
fn invalid(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
impl Frame {
pub fn read(reader: &mut impl Read, length: Length) -> io::Result<Self> {
let mut header = [0; 4];
reader.read_exact(&mut header)?;
let size = (u32::from_le_bytes(header) as usize)
.checked_add(length.header_bytes())
.ok_or_else(|| invalid("invalid Rockstar pipe frame length"))?;
if !(OVERHEAD..=MAX_FRAME_BYTES).contains(&size) {
return Err(invalid("invalid Rockstar pipe frame length"));
}
let mut body = vec![0; size - header.len()];
reader.read_exact(&mut body)?;
let nul_terminated = body.last() == Some(&0);
let end = body.len() - usize::from(nul_terminated);
if body[4] != b':' || body[..4].contains(&b':') || body[..end].contains(&0) {
return Err(invalid("invalid Rockstar pipe frame envelope"));
}
Ok(Self {
tag: body[..4].try_into().unwrap(),
payload: body[5..end].to_vec(),
nul_terminated,
})
}
pub fn write(&self, writer: &mut impl Write, length: Length) -> io::Result<()> {
let size = self
.payload
.len()
.checked_add(OVERHEAD + usize::from(self.nul_terminated))
.filter(|size| *size <= MAX_FRAME_BYTES)
.ok_or_else(|| invalid("Rockstar pipe frame exceeds size limit"))?;
if self.tag.contains(&0) || self.tag.contains(&b':') || self.payload.contains(&0) {
return Err(invalid("Rockstar pipe frame contains a delimiter"));
}
let mut encoded = Vec::with_capacity(size);
encoded.extend_from_slice(&((size - length.header_bytes()) as u32).to_le_bytes());
encoded.extend_from_slice(&self.tag);
encoded.push(b':');
encoded.extend_from_slice(&self.payload);
if self.nul_terminated {
encoded.push(0);
}
writer.write_all(&encoded)?;
writer.flush()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launcher_era_reply_uses_total_length_and_a_terminator() {
let mut bytes = Vec::new();
Frame {
tag: *b"DUNN",
payload: vec![b'A'; 640],
nul_terminated: true,
}
.write(&mut bytes, Length::Total)
.unwrap();
assert_eq!(bytes.len(), 650);
assert_eq!(&bytes[..9], &[138, 2, 0, 0, b'D', b'U', b'N', b'N', b':']);
assert_eq!(bytes[649], 0);
}
use std::io::Cursor;
#[test]
#[ignore]
fn sleeping_game() {
std::thread::sleep(std::time::Duration::from_secs(30));
}
fn sleeping_child() -> std::process::Child {
std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::sleeping_game", "--ignored"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap()
}
#[test]
fn failed_handshake_terminates_and_reaps_the_game() {
let mut child = sleeping_child();
let (sender, receiver) = std::sync::mpsc::channel();
sender
.send(Err(io::Error::new(io::ErrorKind::TimedOut, "test timeout")))
.unwrap();
let start = std::time::Instant::now();
assert_eq!(
wait_for_game(&mut child, receiver).unwrap_err().kind(),
io::ErrorKind::TimedOut
);
assert!(start.elapsed() < std::time::Duration::from_secs(3));
assert!(child.try_wait().unwrap().is_some());
}
#[test]
fn stopped_handshake_worker_terminates_and_reaps_the_game() {
let mut child = sleeping_child();
let (sender, receiver) = std::sync::mpsc::channel();
drop(sender);
assert_eq!(
wait_for_game(&mut child, receiver).unwrap_err().kind(),
io::ErrorKind::BrokenPipe
);
assert!(child.try_wait().unwrap().is_some());
}
#[test]
fn an_exited_game_does_not_wait_for_its_handshake() {
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "no_test_with_this_name"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let (_sender, receiver) = std::sync::mpsc::channel();
assert!(wait_for_game(&mut child, receiver).unwrap().success());
}
struct Fragmented<T>(T);
impl<T: Read> Read for Fragmented<T> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let size = buffer.len().min(1);
self.0.read(&mut buffer[..size])
}
}
impl<T: Write> Write for Fragmented<T> {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
self.0.write(&buffer[..buffer.len().min(1)])
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
#[test]
fn reads_observed_greeting_across_partial_reads() {
let bytes = b"\x0a\0\0\0COLE:\0";
assert_eq!(
Frame::read(&mut Fragmented(&bytes[..]), Length::Total).unwrap(),
Frame {
tag: *b"COLE",
payload: Vec::new(),
nul_terminated: true,
}
);
}
#[test]
fn writes_the_observed_total_length_even_with_partial_writes() {
let mut bytes = Fragmented(Vec::new());
Frame {
tag: *b"COLE",
payload: Vec::new(),
nul_terminated: true,
}
.write(&mut bytes, Length::Total)
.unwrap();
assert_eq!(bytes.0, b"\x0a\0\0\0COLE:\0");
}
#[test]
fn keeps_colons_in_payload_and_leaves_the_next_frame_unread() {
let frame = Frame {
tag: *b"DUNN",
payload: b"one:two".to_vec(),
nul_terminated: false,
};
let mut bytes = Vec::new();
frame.write(&mut bytes, Length::Total).unwrap();
bytes.extend_from_slice(b"\x0a\0\0\0COLE:\0");
let mut reader = Cursor::new(bytes);
assert_eq!(Frame::read(&mut reader, Length::Total).unwrap(), frame);
assert_eq!(
Frame::read(&mut reader, Length::Total).unwrap().tag,
*b"COLE"
);
}
#[test]
fn rejects_invalid_lengths_before_reading_a_body() {
for size in [0u32, 4, 8, MAX_FRAME_BYTES as u32 + 1, u32::MAX] {
let mut reader = Cursor::new(size.to_le_bytes());
assert_eq!(
Frame::read(&mut reader, Length::Total).unwrap_err().kind(),
io::ErrorKind::InvalidData
);
assert_eq!(reader.position(), 4);
}
}
#[test]
fn rejects_truncated_or_malformed_frames() {
for bytes in [&b"\x0a\0\0"[..], &b"\x0a\0\0\0COLE:"[..]] {
assert_eq!(
Frame::read(&mut &bytes[..], Length::Total)
.unwrap_err()
.kind(),
io::ErrorKind::UnexpectedEof
);
}
for bytes in [
b"\x0a\0\0\0COLE=\0",
b"\x0a\0\0\0CO:E:x",
b"\x0a\0\0\0CO\0E:\0",
] {
assert_eq!(
Frame::read(&mut &bytes[..], Length::Total)
.unwrap_err()
.kind(),
io::ErrorKind::InvalidData
);
}
}
#[test]
fn rejects_invalid_output_before_writing_any_bytes() {
let mut bytes = Vec::new();
for frame in [
Frame {
tag: *b"DUNN",
payload: vec![b'x'; MAX_FRAME_BYTES],
nul_terminated: false,
},
Frame {
tag: *b"DUNN",
payload: b"one\0two".to_vec(),
nul_terminated: false,
},
Frame {
tag: *b"CO:E",
payload: Vec::new(),
nul_terminated: false,
},
] {
assert!(frame.write(&mut bytes, Length::Total).is_err());
assert!(bytes.is_empty());
}
}
#[test]
fn accepts_the_observed_unterminated_launch_reply_shape() {
let payload = vec![b'A'; 640];
let mut bytes = 645u32.to_le_bytes().to_vec();
bytes.extend_from_slice(b"DUNN:");
bytes.extend_from_slice(&payload);
let frame = Frame::read(&mut Fragmented(&bytes[..]), Length::Body).unwrap();
assert_eq!(bytes.len(), 649);
assert_eq!(frame.tag, *b"DUNN");
assert_eq!(frame.payload, payload);
assert!(!frame.nul_terminated);
let mut encoded = Vec::new();
frame.write(&mut encoded, Length::Body).unwrap();
assert_eq!(encoded, bytes);
}
#[test]
fn presents_a_complete_reply_to_the_pipe_in_one_write() {
struct Writes(Vec<usize>);
impl Write for Writes {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0.push(bytes.len());
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let mut writer = Writes(Vec::new());
Frame {
tag: *b"DUNN",
payload: vec![b'A'; 640],
nul_terminated: false,
}
.write(&mut writer, Length::Body)
.unwrap();
assert_eq!(writer.0, vec![649]);
}
}
+275
View File
@@ -0,0 +1,275 @@
#![cfg_attr(windows, windows_subsystem = "windows")]
#[cfg(windows)]
fn log(message: &str) {
use std::io::Write;
let Ok(exe) = std::env::current_exe() else {
return;
};
let path = exe.with_file_name("launcher.log");
if let Ok(metadata) = std::fs::symlink_metadata(&path) {
if !metadata.is_file() || metadata.len() > 65536 {
return;
}
}
if let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
let _ = writeln!(file, "{message}");
}
}
#[cfg(windows)]
fn run() -> Result<i32, Box<dyn std::error::Error>> {
use droiddeck_rockstar_launcher::{
pipe::Listener,
sdk::{Message, Session},
wait_for_game, Frame, Length,
};
use std::io::{Read, Write};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
let config_path = std::env::current_exe()?.with_file_name("launch.json");
let mut data = Vec::new();
std::fs::File::open(&config_path)?
.take(65537)
.read_to_end(&mut data)?;
std::fs::remove_file(&config_path)?;
if data.len() > 65536 {
return Err("launch handoff exceeds size limit".into());
}
let config: serde_json::Value = serde_json::from_slice(&data)?;
let text = |key| {
config
.get(key)
.and_then(|value| value.as_str())
.ok_or("missing launch field")
};
let expires = config
.get("expiresAt")
.and_then(|value| value.as_u64())
.ok_or("missing launch expiry")?;
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
if expires <= now || expires - now > 120_000 {
return Err("launch handoff expired".into());
}
let legacy = if config.get("pipe").is_some() {
let pipe_name = text("pipe")?.to_owned();
if !matches!(
pipe_name.as_str(),
"GTA3_Pipe" | "GTA-VC_Pipe" | "GTA_SA_Pipe" | "GTAIV_Pipe" | "LANOIRE_Pipe"
) {
return Err("invalid Rockstar launch pipe".into());
}
let material = text("material")?.as_bytes().to_vec();
if material.len() != 640 || !material.iter().all(u8::is_ascii_hexdigit) {
return Err("invalid launch material".into());
}
Some((pipe_name, material))
} else {
None
};
let session = config
.get("session")
.map(|value| -> Result<Session, Box<dyn std::error::Error>> {
let account = value
.get("accountId")
.and_then(|v| v.as_str())
.ok_or("missing SDK account")?
.parse::<u64>()?;
let identity = value
.get("identity")
.and_then(|v| v.as_str())
.ok_or("missing SDK identity")?;
let ticket = value
.get("ticket")
.and_then(|v| v.as_str())
.ok_or("missing SDK ticket")?;
let session = Session::new(account, identity.to_owned(), ticket.to_owned())?;
Ok(if let Some(title) = value.get("titleId") {
session.with_title(title.as_str().ok_or("invalid SDK title")?.to_owned())?
} else {
session
})
})
.transpose()?;
if legacy.is_none() && session.is_none() {
return Err("missing launch protocol".into());
}
let root = std::fs::canonicalize(text("folder")?)?;
let exe = std::fs::canonicalize(text("exe")?)?;
let workdir = std::fs::canonicalize(text("workdir")?)?;
if !exe.is_file()
|| !exe.starts_with(&root)
|| !workdir.starts_with(&root)
|| legacy.is_some()
&& !root.join("MTLX.dll").is_file()
&& !exe.parent().unwrap_or(&root).join("MTLX.dll").is_file()
{
return Err("invalid Rockstar game path".into());
}
if let Some(index) =
std::env::args().position(|arg| arg.eq_ignore_ascii_case("-launchTitleInFolder"))
{
let folder = std::env::args()
.nth(index + 1)
.ok_or("missing game folder")?;
if std::fs::canonicalize(folder)? != root {
return Err("Rockstar launch folder mismatch".into());
}
}
let args = config
.get("args")
.and_then(|value| value.as_array())
.ok_or("missing game arguments")?;
let args: Result<Vec<&str>, _> = args
.iter()
.map(|value| value.as_str().ok_or("invalid game argument"))
.collect();
log("launch handoff accepted");
let legacy = legacy
.map(|(name, material)| {
let terminated = matches!(name.as_str(), "GTAIV_Pipe" | "LANOIRE_Pipe");
Listener::new(&name, Duration::from_secs(90))
.map(|listener| (listener, material, terminated))
})
.transpose()?;
let instance = std::process::id();
let sdk_listener = if session.is_some() {
Some(Listener::new(
&format!("chrome.rgsc_gameinst_{instance}"),
Duration::from_secs(90),
)?)
} else {
None
};
let mut identity_listeners = Vec::new();
if session.is_some() {
for name in
droiddeck_rockstar_launcher::identity::pipe_names(&mut std::fs::File::open(&exe)?)?
{
identity_listeners.push(Listener::new(&name, Duration::from_secs(90))?);
}
}
log("launcher pipes created");
let mut command = std::process::Command::new(exe);
command.current_dir(workdir).args(args?);
if session.is_some() {
command.arg(format!("-processInstance={instance}"));
}
let mut child = command.spawn()?;
let pid = child.id();
log("game process started");
for listener in identity_listeners {
std::thread::spawn(move || {
let serve = || -> std::io::Result<()> {
let mut pipe = listener.accept()?.with_deadline(Duration::from_secs(90));
if pipe.client_pid()? != pid {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"unexpected launcher identity client",
));
}
let reply = droiddeck_rockstar_launcher::identity::exchange(&mut pipe)?;
pipe.write_all(&reply)?;
log("launcher identity challenge complete");
pipe = pipe.with_timeout(Duration::from_secs(86400));
let mut progress = [0; 4096];
while matches!(pipe.read(&mut progress), Ok(size) if size > 0) {}
Ok(())
};
if let Err(error) = serve() {
log(&format!("launcher identity exchange ended: {error}"));
}
});
}
let (result, handshake) = std::sync::mpsc::sync_channel(1);
std::thread::spawn(move || {
let serve = || -> std::io::Result<()> {
if let Some((listener, material, terminated)) = legacy {
let mut pipe = listener.accept()?;
log("legacy launcher pipe connected");
if pipe.client_pid()? != pid {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"unexpected Rockstar pipe client",
));
}
let request = Frame::read(&mut pipe, Length::Total)?;
if request.tag != *b"COLE" || !request.payload.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"unexpected Rockstar greeting",
));
}
Frame {
tag: *b"DUNN",
payload: material,
nul_terminated: terminated,
}
.write(
&mut pipe,
if terminated {
Length::Total
} else {
Length::Body
},
)?;
log("legacy launcher handshake complete");
}
if let (Some(listener), Some(session)) = (sdk_listener, session) {
let mut pipe = listener.accept()?.with_deadline(Duration::from_secs(90));
if pipe.client_pid()? != pid {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"unexpected Rockstar SDK client",
));
}
Message::hello(instance).write(&mut pipe)?;
let mut authenticated = false;
loop {
let request = match Message::read(&mut pipe) {
Ok(request) => request,
Err(_) if authenticated => return Ok(()),
Err(error) => return Err(error),
};
let responses = session.respond(&request)?;
let sends_login = request.kind == 0x40000;
for response in responses {
response.write(&mut pipe)?;
}
if sends_login && !authenticated {
authenticated = true;
pipe = pipe.with_timeout(Duration::from_secs(86400));
log("SDK login sent");
let _ = result.send(Ok(()));
}
}
}
Ok(())
};
let outcome = serve();
if let Err(error) = &outcome {
log(&format!("launcher handshake failed: {error}"));
}
let _ = result.send(outcome);
});
Ok(wait_for_game(&mut child, handshake)?.code().unwrap_or(1))
}
fn main() {
#[cfg(windows)]
let code = match run() {
Ok(code) => code,
Err(error) => {
log(&format!("launch failed: {error}"));
eprintln!("Rockstar launch failed: {error}");
1
}
};
#[cfg(not(windows))]
let code = 1;
std::process::exit(code);
}
+450
View File
@@ -0,0 +1,450 @@
use std::ffi::c_void;
use std::io::{self, Read, Write};
use std::os::windows::ffi::OsStrExt;
use std::ptr::{null, null_mut};
use std::time::{Duration, Instant};
type Handle = *mut c_void;
const INVALID_HANDLE: Handle = -1isize as Handle;
const ERROR_IO_PENDING: i32 = 997;
const ERROR_MORE_DATA: i32 = 234;
#[repr(C)]
struct Overlapped {
internal: usize,
internal_high: usize,
offset: u32,
offset_high: u32,
event: Handle,
}
#[link(name = "kernel32")]
extern "system" {
fn CreateNamedPipeW(
name: *const u16,
open: u32,
mode: u32,
max: u32,
output: u32,
input: u32,
timeout: u32,
security: *const c_void,
) -> Handle;
fn ConnectNamedPipe(handle: Handle, overlapped: *mut Overlapped) -> i32;
fn GetNamedPipeClientProcessId(handle: Handle, pid: *mut u32) -> i32;
fn CreateFileW(
name: *const u16,
access: u32,
share: u32,
security: *const c_void,
creation: u32,
flags: u32,
template: Handle,
) -> Handle;
fn WaitNamedPipeW(name: *const u16, timeout: u32) -> i32;
fn CreateEventW(security: *const c_void, manual: i32, initial: i32, name: *const u16)
-> Handle;
fn CloseHandle(handle: Handle) -> i32;
fn ReadFile(
handle: Handle,
buffer: *mut u8,
size: u32,
read: *mut u32,
overlapped: *mut Overlapped,
) -> i32;
fn WriteFile(
handle: Handle,
buffer: *const u8,
size: u32,
written: *mut u32,
overlapped: *mut Overlapped,
) -> i32;
fn WaitForSingleObject(handle: Handle, timeout: u32) -> u32;
fn CancelIoEx(handle: Handle, overlapped: *mut Overlapped) -> i32;
fn GetOverlappedResult(
handle: Handle,
overlapped: *mut Overlapped,
transferred: *mut u32,
wait: i32,
) -> i32;
}
struct OwnedHandle(Handle);
unsafe impl Send for OwnedHandle {}
impl Drop for OwnedHandle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
pub struct Pipe {
handle: OwnedHandle,
timeout: Duration,
deadline: Option<Instant>,
}
pub struct Listener(Pipe);
impl Listener {
pub fn new(name: &str, timeout: Duration) -> io::Result<Self> {
if name.is_empty() || name.contains(['\\', '/', '\0']) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid pipe name",
));
}
let path = format!(r"\\.\pipe\{name}");
let wide: Vec<_> = std::ffi::OsStr::new(&path)
.encode_wide()
.chain(Some(0))
.collect();
let handle = unsafe {
CreateNamedPipeW(
wide.as_ptr(),
3 | 0x4000_0000 | 0x0008_0000,
8,
1,
65536,
65536,
0,
null(),
)
};
if handle == INVALID_HANDLE {
return Err(io::Error::last_os_error());
}
Ok(Self(Pipe {
handle: OwnedHandle(handle),
timeout,
deadline: None,
}))
}
pub fn accept(self) -> io::Result<Pipe> {
let event = unsafe { CreateEventW(null(), 1, 0, null()) };
if event.is_null() {
return Err(io::Error::last_os_error());
}
let event = OwnedHandle(event);
let mut overlapped = Overlapped {
internal: 0,
internal_high: 0,
offset: 0,
offset_high: 0,
event: event.0,
};
if unsafe { ConnectNamedPipe(self.0.handle.0, &mut overlapped) } != 0 {
return Ok(self.0);
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(535) {
return Ok(self.0);
}
if error.raw_os_error() != Some(ERROR_IO_PENDING) {
return Err(error);
}
let wait = unsafe {
WaitForSingleObject(
event.0,
self.0.timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
)
};
let mut transferred = 0;
if wait != 0 {
let error = if wait == 258 {
io::Error::new(io::ErrorKind::TimedOut, "waiting for Rockstar game")
} else {
io::Error::last_os_error()
};
unsafe {
CancelIoEx(self.0.handle.0, &mut overlapped);
GetOverlappedResult(self.0.handle.0, &mut overlapped, &mut transferred, 1);
}
return Err(error);
}
if unsafe { GetOverlappedResult(self.0.handle.0, &mut overlapped, &mut transferred, 0) }
== 0
{
return Err(io::Error::last_os_error());
}
Ok(self.0)
}
}
impl Pipe {
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self.deadline = None;
self
}
pub fn with_deadline(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self.deadline = Some(Instant::now() + timeout);
self
}
pub fn client_pid(&self) -> io::Result<u32> {
let mut pid = 0;
if unsafe { GetNamedPipeClientProcessId(self.handle.0, &mut pid) } == 0 || pid == 0 {
return Err(io::Error::last_os_error());
}
Ok(pid)
}
pub fn connect(name: &str, timeout: Duration) -> io::Result<Self> {
if name.is_empty() || name.contains(['\\', '/', '\0']) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid pipe name",
));
}
let path = format!(r"\\.\pipe\{name}");
let wide: Vec<_> = std::ffi::OsStr::new(&path)
.encode_wide()
.chain(Some(0))
.collect();
let deadline = Instant::now() + timeout;
loop {
let handle = unsafe {
CreateFileW(
wide.as_ptr(),
0xc000_0000,
0,
null(),
3,
0x4000_0000,
null_mut(),
)
};
if handle != INVALID_HANDLE {
return Ok(Self {
handle: OwnedHandle(handle),
timeout,
deadline: None,
});
}
let error = io::Error::last_os_error();
if !matches!(error.raw_os_error(), Some(2 | 231)) {
return Err(error);
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"waiting for Rockstar pipe",
));
}
unsafe {
WaitNamedPipeW(wide.as_ptr(), remaining.as_millis().min(50) as u32);
}
std::thread::sleep(remaining.min(Duration::from_millis(2)));
}
}
fn transfer(&self, buffer: *mut u8, size: usize, writing: bool) -> io::Result<usize> {
if size == 0 {
return Ok(0);
}
let timeout = self
.deadline
.map(|deadline| deadline.saturating_duration_since(Instant::now()))
.unwrap_or(self.timeout);
if timeout.is_zero() {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"Rockstar pipe deadline exceeded",
));
}
let event = unsafe { CreateEventW(null(), 1, 0, null()) };
if event.is_null() {
return Err(io::Error::last_os_error());
}
let event = OwnedHandle(event);
let mut overlapped = Overlapped {
internal: 0,
internal_high: 0,
offset: 0,
offset_high: 0,
event: event.0,
};
let mut transferred = 0;
let size = size.min(u32::MAX as usize) as u32;
let ok = unsafe {
if writing {
WriteFile(
self.handle.0,
buffer,
size,
&mut transferred,
&mut overlapped,
)
} else {
ReadFile(
self.handle.0,
buffer,
size,
&mut transferred,
&mut overlapped,
)
}
};
if ok != 0 {
return Ok(transferred as usize);
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERROR_MORE_DATA) && !writing && transferred > 0 {
return Ok(transferred as usize);
}
if error.raw_os_error() != Some(ERROR_IO_PENDING) {
return Err(error);
}
let wait = unsafe {
WaitForSingleObject(
event.0,
timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
)
};
if wait != 0 {
let error = if wait == 258 {
io::Error::new(io::ErrorKind::TimedOut, "Rockstar pipe operation timed out")
} else {
io::Error::last_os_error()
};
unsafe {
CancelIoEx(self.handle.0, &mut overlapped);
GetOverlappedResult(self.handle.0, &mut overlapped, &mut transferred, 1);
}
return Err(error);
}
let ok =
unsafe { GetOverlappedResult(self.handle.0, &mut overlapped, &mut transferred, 0) };
if ok != 0 {
return Ok(transferred as usize);
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERROR_MORE_DATA) && !writing && transferred > 0 {
return Ok(transferred as usize);
}
Err(error)
}
}
impl Read for Pipe {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
self.transfer(buffer.as_mut_ptr(), buffer.len(), false)
}
}
impl Write for Pipe {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
self.transfer(buffer.as_ptr() as *mut u8, buffer.len(), true)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Frame, Length};
use std::sync::mpsc;
use std::time::{SystemTime, UNIX_EPOCH};
fn name() -> String {
format!(
"dd-rockstar-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
)
}
#[test]
fn initialization_deadline_survives_partial_reads() {
let name = name();
let listener = Listener::new(&name, Duration::from_secs(2)).unwrap();
let worker = std::thread::spawn(move || {
let mut server = listener
.accept()
.unwrap()
.with_deadline(Duration::from_millis(150));
let mut byte = [0];
server.read_exact(&mut byte).unwrap();
std::thread::sleep(Duration::from_millis(180));
assert_eq!(
server.read(&mut byte).unwrap_err().kind(),
io::ErrorKind::TimedOut
);
});
let mut client = Pipe::connect(&name, Duration::from_secs(2)).unwrap();
client.write_all(&[1]).unwrap();
worker.join().unwrap();
}
#[test]
fn real_pipe_exchanges_both_framing_modes_and_identifies_the_client() {
let name = name();
let listener = Listener::new(&name, Duration::from_secs(2)).unwrap();
let worker = std::thread::spawn(move || {
let mut server = listener.accept().unwrap();
assert_eq!(server.client_pid().unwrap(), std::process::id());
assert_eq!(
Frame::read(&mut server, Length::Total).unwrap().tag,
*b"COLE"
);
Frame {
tag: *b"DUNN",
payload: vec![b'A'; 640],
nul_terminated: false,
}
.write(&mut server, Length::Body)
.unwrap();
});
let mut client = Pipe::connect(&name, Duration::from_secs(2)).unwrap();
Frame {
tag: *b"COLE",
payload: Vec::new(),
nul_terminated: true,
}
.write(&mut client, Length::Total)
.unwrap();
let response = Frame::read(&mut client, Length::Body).unwrap();
assert_eq!(response.payload.len(), 640);
assert!(!response.nul_terminated);
worker.join().unwrap();
}
#[test]
fn timed_out_accept_releases_the_first_pipe_instance() {
let name = name();
let listener = Listener::new(&name, Duration::from_millis(20)).unwrap();
assert!(matches!(listener.accept(), Err(error) if error.kind() == io::ErrorKind::TimedOut));
assert!(Listener::new(&name, Duration::from_millis(20)).is_ok());
}
#[test]
fn timed_out_read_cancels_the_pending_operation() {
let name = name();
let listener = Listener::new(&name, Duration::from_secs(2)).unwrap();
let (done, wait) = mpsc::channel();
let worker = std::thread::spawn(move || {
let _server = listener.accept().unwrap();
wait.recv_timeout(Duration::from_secs(2)).unwrap();
});
let mut client = Pipe::connect(&name, Duration::from_millis(30)).unwrap();
assert_eq!(
client.read(&mut [0u8; 4]).unwrap_err().kind(),
io::ErrorKind::TimedOut
);
done.send(()).unwrap();
worker.join().unwrap();
}
}
+328
View File
@@ -0,0 +1,328 @@
use std::io::{self, Read, Write};
const HEADER: usize = 16;
const MAX_BYTES: usize = 64 * 1024;
const CONTROL: i32 = i32::MAX;
#[derive(PartialEq, Eq)]
pub struct Message {
pub routing: i32,
pub kind: u32,
pub flags: u32,
pub payload: Vec<u8>,
}
impl std::fmt::Debug for Message {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Message")
.field("routing", &self.routing)
.field("kind", &self.kind)
.field("flags", &self.flags)
.field("payload_bytes", &self.payload.len())
.finish()
}
}
fn invalid() -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, "invalid Rockstar SDK message")
}
impl Message {
pub fn read(reader: &mut impl Read) -> io::Result<Self> {
let mut header = [0; HEADER];
reader.read_exact(&mut header)?;
let size = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
if size > MAX_BYTES - HEADER {
return Err(invalid());
}
let mut payload = vec![0; size];
reader.read_exact(&mut payload)?;
Ok(Self {
routing: i32::from_le_bytes(header[4..8].try_into().unwrap()),
kind: u32::from_le_bytes(header[8..12].try_into().unwrap()),
flags: u32::from_le_bytes(header[12..16].try_into().unwrap()),
payload,
})
}
pub fn write(&self, writer: &mut impl Write) -> io::Result<()> {
if self.payload.len() > MAX_BYTES - HEADER {
return Err(invalid());
}
let mut bytes = Vec::with_capacity(HEADER + self.payload.len());
bytes.extend_from_slice(&(self.payload.len() as u32).to_le_bytes());
bytes.extend_from_slice(&self.routing.to_le_bytes());
bytes.extend_from_slice(&self.kind.to_le_bytes());
bytes.extend_from_slice(&self.flags.to_le_bytes());
bytes.extend_from_slice(&self.payload);
writer.write_all(&bytes)
}
fn control(kind: u32, payload: Payload) -> Self {
Self {
routing: CONTROL,
kind,
flags: 2,
payload: payload.0,
}
}
pub fn hello(pid: u32) -> Self {
Self {
routing: -2,
kind: 0xffff,
flags: 2,
payload: pid.to_le_bytes().to_vec(),
}
}
}
#[derive(Default)]
struct Payload(Vec<u8>);
impl Payload {
fn raw(mut self, bytes: &[u8]) -> Self {
self.0.resize((self.0.len() + 3) & !3, 0);
self.0.extend_from_slice(bytes);
self
}
fn u32(self, value: u32) -> Self {
self.raw(&value.to_le_bytes())
}
fn u64(self, value: u64) -> Self {
self.raw(&value.to_le_bytes())
}
fn string(self, value: &str) -> Self {
self.u32(value.len() as u32).raw(value.as_bytes())
}
}
pub struct Session {
account: u64,
identity: String,
ticket: String,
title: Option<String>,
api: std::cell::Cell<u32>,
}
impl Session {
pub fn new(account: u64, identity: String, ticket: String) -> io::Result<Self> {
if account == 0
|| identity.is_empty()
|| identity.len() > 512
|| ticket.is_empty()
|| ticket.len() > 48 * 1024
|| identity.contains('\0')
|| ticket.contains('\0')
{
return Err(invalid());
}
Ok(Self {
account,
identity,
ticket,
title: None,
api: std::cell::Cell::new(3),
})
}
pub fn with_title(mut self, title: String) -> io::Result<Self> {
if title.is_empty()
|| title.len() > 64
|| !title.as_bytes()[0].is_ascii_lowercase()
|| !title
.bytes()
.all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == b'_')
{
return Err(invalid());
}
self.title = Some(title);
Ok(self)
}
fn app_sync(&self, challenge: u64) -> io::Result<Message> {
let mut payload = Payload::default().u32(u32::from(self.title.is_some()));
if let Some(title) = &self.title {
payload = payload
.u64(u64::MAX)
.u64(0)
.u64(0)
.string(title)
.u32(1)
.u32(1)
.string("");
}
let mut inner = Vec::new();
Message::control(0x80006, payload).write(&mut inner)?;
Ok(Message::control(
0x80002,
Payload::default().u64(challenge).string(&base64(&inner)),
))
}
pub fn login(&self) -> Vec<Message> {
let offset = u32::from(self.api.get() >= 4);
vec![
Message::control(
0x30001 + offset,
Payload::default().u32(3).u64(self.account).u32(0),
),
Message::control(
0x30002 + offset,
Payload::default()
.u64(self.account)
.u32(0)
.string(&self.identity),
),
Message::control(
0x30003 + offset,
Payload::default()
.string(&self.identity)
.string(&self.ticket),
),
]
}
pub fn respond(&self, message: &Message) -> io::Result<Vec<Message>> {
match message.kind {
0x80000 => {
if message.payload.len() != 8 {
return Err(invalid());
}
let challenge = u64::from_le_bytes(message.payload[..8].try_into().unwrap());
Ok(vec![self.app_sync(challenge)?])
}
0x40000 => {
if message.payload.len() < 4 {
return Err(invalid());
}
let context = u32::from_le_bytes(message.payload[..4].try_into().unwrap());
self.api.set(context);
let mut result = self.login();
result.push(Message::control(0x30000, Payload::default().u32(context)));
Ok(result)
}
0x40005 | 0x40007 => Ok(vec![Message::control(
0x30004 + u32::from(self.api.get() >= 4),
Payload::default(),
)]),
_ => Ok(Vec::new()),
}
}
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut output = String::with_capacity(bytes.len().div_ceil(3) * 4);
for part in bytes.chunks(3) {
let value = ((part[0] as u32) << 16)
| ((part.get(1).copied().unwrap_or(0) as u32) << 8)
| part.get(2).copied().unwrap_or(0) as u32;
output.push(ALPHABET[(value >> 18) as usize] as char);
output.push(ALPHABET[((value >> 12) & 63) as usize] as char);
output.push(if part.len() > 1 {
ALPHABET[((value >> 6) & 63) as usize] as char
} else {
'='
});
output.push(if part.len() > 2 {
ALPHABET[(value & 63) as usize] as char
} else {
'='
});
}
output
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn app_sync_echoes_challenge_without_inventing_owned_titles() {
let session = Session::new(123, "name".into(), "ticket".into()).unwrap();
let request = Message::control(0x80000, Payload::default().u64(42));
let response = session.respond(&request).unwrap().remove(0);
assert_eq!(response.kind, 0x80002);
assert_eq!(&response.payload[..8], &42u64.to_le_bytes());
assert_eq!(&response.payload[12..], b"BAAAAP///38GAAgAAgAAAAAAAAA=");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert!(session.with_title("../game".into()).is_err());
}
#[test]
fn transport_hello_matches_wire_layout() {
let mut bytes = Vec::new();
Message::hello(0x1234).write(&mut bytes).unwrap();
assert_eq!(
bytes,
[4, 0, 0, 0, 254, 255, 255, 255, 255, 255, 0, 0, 2, 0, 0, 0, 52, 18, 0, 0]
);
}
#[test]
fn login_preserves_string_lengths_and_alignment() {
let session = Session::new(0x1122334455667788, "a@b".into(), "ticket".into()).unwrap();
let login = session.login();
assert_eq!(
login[0].payload,
[3, 0, 0, 0, 136, 119, 102, 85, 68, 51, 34, 17, 0, 0, 0, 0]
);
assert_eq!(
login[1].payload,
[136, 119, 102, 85, 68, 51, 34, 17, 0, 0, 0, 0, 3, 0, 0, 0, 97, 64, 98]
);
assert_eq!(
login[2].payload,
[3, 0, 0, 0, 97, 64, 98, 0, 6, 0, 0, 0, 116, 105, 99, 107, 101, 116]
);
}
#[test]
fn init_sends_authenticated_state_before_launcher_hello() {
let session = Session::new(123, "name".into(), "ticket".into()).unwrap();
for (api, expected) in [
(3, [0x30001, 0x30002, 0x30003, 0x30000]),
(4, [0x30002, 0x30003, 0x30004, 0x30000]),
] {
let request = Message::control(0x40000, Payload::default().u32(api));
let result = session.respond(&request).unwrap();
assert_eq!(result.iter().map(|m| m.kind).collect::<Vec<_>>(), expected);
assert_eq!(
result[0].payload,
[3, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(result[3].payload, api.to_le_bytes());
}
}
#[test]
fn malformed_frames_and_sessions_are_rejected() {
assert!(Session::new(0, "name".into(), "ticket".into()).is_err());
assert!(Session::new(123, "name".into(), "".into()).is_err());
let session = Session::new(123, "name".into(), "ticket".into()).unwrap();
assert!(session
.respond(&Message::control(0x40000, Payload::default()))
.is_err());
assert!(Message::read(&mut Cursor::new(vec![255; 16])).is_err());
assert!(Message::read(&mut Cursor::new(vec![0; 15])).is_err());
}
#[test]
fn concatenated_messages_remain_separate() {
let session = Session::new(123, "name".into(), "ticket".into()).unwrap();
let mut bytes = Vec::new();
for message in session.login() {
message.write(&mut bytes).unwrap();
}
let mut reader = Cursor::new(bytes);
for message in session.login() {
assert_eq!(Message::read(&mut reader).unwrap(), message);
}
}
}
+490
View File
@@ -0,0 +1,490 @@
#include "mali_compat.h"
#include <assert.h>
#include <spirv/unified1/spirv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *interface);
struct object { void *dispatch; };
static int instance_table, device_table;
static struct object mock_instance = {&instance_table};
static struct object mock_lacking = {&instance_table}, mock_capable = {&instance_table};
static struct object mock_device = {&device_table}, mock_command_buffer = {&device_table};
static VkBool32 driver_saw_dual_source;
static uint32_t *driver_code;
static size_t driver_code_count;
static VkPipelineColorBlendAttachmentState driver_attachments[4];
static uint32_t driver_attachment_count;
static VkColorBlendEquationEXT driver_equations[4];
static uint32_t driver_equation_count;
#define MAIN 1
#define VOID 2
#define FUNCTION 3
#define FLOAT 4
#define VEC4 5
#define OUTPUT_VEC4 6
#define COLOR 7
#define SECOND 8
#define ONE 9
#define ONES 10
#define OUTPUT_FLOAT 11
#define UINT 12
#define ZERO 13
#define LABEL 14
#define CHANNEL 15
#define BOUND 16
struct spirv { uint32_t w[256]; size_t n; };
static void op(struct spirv *s, SpvOp code, uint32_t count, const uint32_t *operands)
{
s->w[s->n++] = (count + 1) << 16 | code;
for (uint32_t i = 0; i < count; i++)
s->w[s->n++] = operands[i];
}
#define OP(s, code, ...) \
do { \
const uint32_t operands_[] = {__VA_ARGS__}; \
op(s, code, sizeof(operands_) / sizeof(operands_[0]), operands_); \
} while (0)
static void fragment_shader(struct spirv *s, uint32_t version, bool dual_source)
{
s->n = 0;
const uint32_t header[5] = {SpvMagicNumber, version, 0, BOUND, 0};
memcpy(s->w, header, sizeof(header));
s->n = 5;
OP(s, SpvOpCapability, SpvCapabilityShader);
OP(s, SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450);
OP(s, SpvOpEntryPoint, SpvExecutionModelFragment, MAIN, 0x6e69616d, 0, COLOR, SECOND);
OP(s, SpvOpExecutionMode, MAIN, SpvExecutionModeOriginUpperLeft);
OP(s, SpvOpDecorate, COLOR, SpvDecorationLocation, 0);
if (dual_source) {
OP(s, SpvOpDecorate, COLOR, SpvDecorationIndex, 0);
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 0);
OP(s, SpvOpDecorate, SECOND, SpvDecorationIndex, 1);
} else {
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 1);
}
OP(s, SpvOpTypeVoid, VOID);
OP(s, SpvOpTypeFunction, FUNCTION, VOID);
OP(s, SpvOpTypeFloat, FLOAT, 32);
OP(s, SpvOpTypeVector, VEC4, FLOAT, 4);
OP(s, SpvOpTypePointer, OUTPUT_VEC4, SpvStorageClassOutput, VEC4);
OP(s, SpvOpTypePointer, OUTPUT_FLOAT, SpvStorageClassOutput, FLOAT);
OP(s, SpvOpTypeInt, UINT, 32, 0);
OP(s, SpvOpConstant, FLOAT, ONE, 0x3f800000);
OP(s, SpvOpConstantComposite, VEC4, ONES, ONE, ONE, ONE, ONE);
OP(s, SpvOpConstant, UINT, ZERO, 0);
OP(s, SpvOpVariable, OUTPUT_VEC4, COLOR, SpvStorageClassOutput);
OP(s, SpvOpVariable, OUTPUT_VEC4, SECOND, SpvStorageClassOutput);
OP(s, SpvOpFunction, VOID, MAIN, SpvFunctionControlMaskNone, FUNCTION);
OP(s, SpvOpLabel, LABEL);
OP(s, SpvOpStore, COLOR, ONES);
OP(s, SpvOpStore, SECOND, ONES);
OP(s, SpvOpAccessChain, OUTPUT_FLOAT, CHANNEL, SECOND, ZERO);
OP(s, SpvOpStore, CHANNEL, ONE);
s->w[s->n++] = 1u << 16 | SpvOpReturn;
s->w[s->n++] = 1u << 16 | SpvOpFunctionEnd;
}
static const uint32_t *find(const uint32_t *w, size_t count, SpvOp code, uint32_t position, uint32_t value)
{
for (size_t i = 5; i < count; i += w[i] >> 16) {
if ((w[i] & 0xffff) == code && (w[i] >> 16) > position && w[i + position] == value)
return &w[i];
}
return NULL;
}
static uint32_t storage_of(const uint32_t *w, size_t count, uint32_t pointer_type)
{
const uint32_t *type = find(w, count, SpvOpTypePointer, 1, pointer_type);
assert(type);
return type[2];
}
static bool in_interface(const uint32_t *w, size_t count, uint32_t id)
{
const uint32_t *entry = find(w, count, SpvOpEntryPoint, 2, MAIN);
assert(entry);
for (uint32_t i = 5; i < entry[0] >> 16; i++) {
if (entry[i] == id)
return true;
}
return false;
}
static void save(const char *directory, const char *name, const uint32_t *words, size_t count)
{
if (!directory)
return;
char path[512];
snprintf(path, sizeof(path), "%s/%s", directory, name);
FILE *file = fopen(path, "wb");
assert(file);
assert(fwrite(words, sizeof(uint32_t), count, file) == count);
fclose(file);
}
static void check_stripped(const uint32_t *w, size_t count, bool second_listed)
{
assert(!spirv_uses_dual_source(w, count));
const uint32_t *second = find(w, count, SpvOpVariable, 2, SECOND);
const uint32_t *color = find(w, count, SpvOpVariable, 2, COLOR);
assert(second && second[3] == SpvStorageClassPrivate);
assert(storage_of(w, count, second[1]) == SpvStorageClassPrivate);
assert(color && color[3] == SpvStorageClassOutput && color[1] == OUTPUT_VEC4);
assert(!find(w, count, SpvOpDecorate, 1, SECOND));
const uint32_t *location = find(w, count, SpvOpDecorate, 1, COLOR);
assert(location && location[2] == SpvDecorationLocation && location[3] == 0);
const uint32_t *channel = find(w, count, SpvOpAccessChain, 2, CHANNEL);
assert(channel && storage_of(w, count, channel[1]) == SpvStorageClassPrivate);
assert(storage_of(w, count, OUTPUT_FLOAT) == SpvStorageClassOutput);
assert(in_interface(w, count, COLOR));
assert(in_interface(w, count, SECOND) == second_listed);
}
static void test_spirv(const char *directory)
{
struct spirv dual, plain;
struct spirv_code out;
fragment_shader(&dual, 0x00010000, true);
save(directory, "dual-1.0.spv", dual.w, dual.n);
assert(spirv_uses_dual_source(dual.w, dual.n));
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
check_stripped(out.words, out.count, false);
save(directory, "stripped-1.0.spv", out.words, out.count);
free(out.words);
fragment_shader(&dual, 0x00010400, true);
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
check_stripped(out.words, out.count, true);
save(directory, "stripped-1.4.spv", out.words, out.count);
free(out.words);
fragment_shader(&plain, 0x00010000, false);
save(directory, "plain-1.0.spv", plain.w, plain.n);
assert(!spirv_uses_dual_source(plain.w, plain.n));
assert(spirv_strip_dual_source(plain.w, plain.n, &out));
assert(out.count == plain.n && !memcmp(out.words, plain.w, plain.n * sizeof(uint32_t)));
free(out.words);
uint32_t truncated[5] = {SpvMagicNumber, 0x00010000, 0, BOUND, 0};
assert(!spirv_uses_dual_source(truncated, 5));
assert(!spirv_strip_dual_source(truncated, 5, &out));
}
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance)
{
*instance = (VkInstance)&mock_instance;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_instance(VkInstance instance, const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_extensions(VkPhysicalDevice physical, const char *layer, uint32_t *count,
VkExtensionProperties *properties)
{
*count = 0;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features)
{
memset(features, 0, sizeof(*features));
features->dualSrcBlend = physical == (VkPhysicalDevice)&mock_capable;
}
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features)
{
mock_features(physical, &features->features);
}
static void VKAPI_CALL mock_properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *properties)
{
memset(properties, 0, sizeof(*properties));
strcpy(properties->deviceName, "mock");
properties->limits.maxFragmentDualSrcAttachments = physical == (VkPhysicalDevice)&mock_capable;
}
static void VKAPI_CALL mock_properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *properties)
{
mock_properties(physical, &properties->properties);
}
static void VKAPI_CALL mock_memory_properties(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties *properties)
{
memset(properties, 0, sizeof(*properties));
}
static void VKAPI_CALL mock_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out)
{
memset(&out->formatProperties, 0, sizeof(out->formatProperties));
}
static VkResult VKAPI_CALL mock_image_format_properties2(VkPhysicalDevice physical,
const VkPhysicalDeviceImageFormatInfo2 *info,
VkImageFormatProperties2 *properties)
{
return VK_ERROR_FORMAT_NOT_SUPPORTED;
}
static VkResult VKAPI_CALL mock_create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDevice *device)
{
driver_saw_dual_source = info->pEnabledFeatures && info->pEnabledFeatures->dualSrcBlend;
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext) {
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
((const VkPhysicalDeviceFeatures2 *)p)->features.dualSrcBlend)
driver_saw_dual_source = VK_TRUE;
}
VkPhysicalDeviceFeatures supported;
mock_features(physical, &supported);
if (driver_saw_dual_source && !supported.dualSrcBlend)
return VK_ERROR_FEATURE_NOT_PRESENT;
*device = (VkDevice)&mock_device;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {}
static void capture_code(const uint32_t *words, size_t size)
{
free(driver_code);
driver_code_count = size / sizeof(uint32_t);
driver_code = malloc(size);
memcpy(driver_code, words, size);
}
static VkResult VKAPI_CALL mock_create_shader_module(VkDevice device, const VkShaderModuleCreateInfo *info,
const VkAllocationCallbacks *allocator, VkShaderModule *module)
{
capture_code(info->pCode, info->codeSize);
*module = (VkShaderModule)0x1000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_shader_module(VkDevice device, VkShaderModule module,
const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkGraphicsPipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
const VkPipelineColorBlendStateCreateInfo *blend = infos[0].pColorBlendState;
driver_attachment_count = blend->attachmentCount;
memcpy(driver_attachments, blend->pAttachments, blend->attachmentCount * sizeof(*driver_attachments));
const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext;
assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
capture_code(module->pCode, module->codeSize);
pipelines[0] = (VkPipeline)0x2000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count,
const VkColorBlendEquationEXT *equations)
{
for (uint32_t i = 0; i < count; i++)
driver_equations[first + i] = equations[i];
if (first + count > driver_equation_count)
driver_equation_count = first + count;
}
#define MOCK(name, function) if (!strcmp(requested, name)) return (PFN_vkVoidFunction)function
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gipa(VkInstance instance, const char *requested)
{
MOCK("vkCreateInstance", mock_create_instance);
MOCK("vkDestroyInstance", mock_destroy_instance);
MOCK("vkCreateDevice", mock_create_device);
MOCK("vkEnumerateDeviceExtensionProperties", mock_extensions);
MOCK("vkGetPhysicalDeviceFeatures", mock_features);
MOCK("vkGetPhysicalDeviceFeatures2", mock_features2);
MOCK("vkGetPhysicalDeviceProperties", mock_properties);
MOCK("vkGetPhysicalDeviceProperties2", mock_properties2);
MOCK("vkGetPhysicalDeviceMemoryProperties", mock_memory_properties);
MOCK("vkGetPhysicalDeviceFormatProperties2", mock_format_properties2);
MOCK("vkGetPhysicalDeviceImageFormatProperties2", mock_image_format_properties2);
return NULL;
}
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const char *requested)
{
MOCK("vkDestroyDevice", mock_destroy_device);
MOCK("vkCreateShaderModule", mock_create_shader_module);
MOCK("vkDestroyShaderModule", mock_destroy_shader_module);
MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines);
MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation);
return NULL;
}
static PFN_vkGetInstanceProcAddr layer_gipa;
static PFN_vkGetDeviceProcAddr layer_gdpa;
static VkResult create_device(VkPhysicalDevice physical, const void *chain, const VkPhysicalDeviceFeatures *enabled,
VkDevice *device)
{
VkLayerDeviceLink link = {NULL, mock_gipa, mock_gdpa};
VkLayerDeviceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, chain, VK_LAYER_LINK_INFO, {&link}};
VkDeviceCreateInfo info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &loader, 0, 0, NULL, 0, NULL, 0, NULL, enabled};
PFN_vkCreateDevice create = (PFN_vkCreateDevice)layer_gipa((VkInstance)&mock_instance, "vkCreateDevice");
return create(physical, &info, NULL, device);
}
static void destroy_device(VkDevice device)
{
((PFN_vkDestroyDevice)layer_gdpa(device, "vkDestroyDevice"))(device, NULL);
}
static const VkPipelineColorBlendAttachmentState dual_attachment = {
VK_TRUE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_OP_ADD, 0xf,
};
static const VkPipelineColorBlendAttachmentState plain_attachment = {
VK_TRUE, VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_OP_ADD, 0xf,
};
static void create_pipeline(VkDevice device, VkPipelineColorBlendAttachmentState *attachments,
VkShaderModuleCreateInfo *module)
{
VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, module, 0,
VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL};
VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_LOGIC_OP_COPY, 2, attachments, {0}};
VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1,
.pStages = &stage, .pColorBlendState = &blend};
VkPipeline pipeline;
PFN_vkCreateGraphicsPipelines create =
(PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines");
assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS);
assert(stage.pNext == module && blend.pAttachments == attachments);
}
static bool same_attachment(const VkPipelineColorBlendAttachmentState *a, const VkPipelineColorBlendAttachmentState *b)
{
return !memcmp(a, b, sizeof(*a));
}
static void test_lacking_device(void)
{
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_lacking;
VkPhysicalDeviceFeatures features;
((PFN_vkGetPhysicalDeviceFeatures)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures"))(physical,
&features);
assert(features.dualSrcBlend);
VkPhysicalDeviceFeatures2 queried = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
((PFN_vkGetPhysicalDeviceFeatures2)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures2"))(physical,
&queried);
assert(queried.features.dualSrcBlend);
VkPhysicalDeviceProperties properties;
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
physical, &properties);
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS);
assert(!driver_saw_dual_source && enabled.dualSrcBlend);
destroy_device(device);
VkPhysicalDeviceFeatures2 chained = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, NULL, {.dualSrcBlend = VK_TRUE}};
assert(create_device(physical, &chained, NULL, &device) == VK_SUCCESS);
assert(!driver_saw_dual_source && chained.features.dualSrcBlend);
struct spirv dual;
fragment_shader(&dual, 0x00010300, true);
VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, dual.n * sizeof(uint32_t),
dual.w};
VkShaderModule handle;
assert(((PFN_vkCreateShaderModule)layer_gdpa(device, "vkCreateShaderModule"))(device, &module, NULL, &handle) ==
VK_SUCCESS);
check_stripped(driver_code, driver_code_count, false);
((PFN_vkDestroyShaderModule)layer_gdpa(device, "vkDestroyShaderModule"))(device, handle, NULL);
VkPipelineColorBlendAttachmentState attachments[2] = {dual_attachment, plain_attachment};
create_pipeline(device, attachments, &module);
check_stripped(driver_code, driver_code_count, false);
assert(module.pCode == dual.w && spirv_uses_dual_source(module.pCode, module.codeSize / sizeof(uint32_t)));
assert(driver_attachment_count == 2);
assert(driver_attachments[0].srcColorBlendFactor == VK_BLEND_FACTOR_ONE);
assert(driver_attachments[0].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_attachments[0].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
assert(driver_attachments[0].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_attachments[0].colorWriteMask == 0xf && driver_attachments[0].blendEnable);
assert(same_attachment(&driver_attachments[1], &plain_attachment));
assert(same_attachment(&attachments[0], &dual_attachment));
VkColorBlendEquationEXT equations[2] = {
{VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD},
{VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_OP_ADD},
};
VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer;
PFN_vkCmdSetColorBlendEquationEXT set_equation =
(PFN_vkCmdSetColorBlendEquationEXT)layer_gdpa(device, "vkCmdSetColorBlendEquationEXT");
assert(set_equation != (PFN_vkCmdSetColorBlendEquationEXT)mock_set_blend_equation);
set_equation(cmd, 1, 2, equations);
assert(driver_equation_count == 3);
assert(driver_equations[1].srcColorBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
assert(driver_equations[1].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_equations[1].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE);
assert(!memcmp(&driver_equations[2], &equations[1], sizeof(equations[1])));
assert(equations[0].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR);
destroy_device(device);
}
static void test_capable_device(void)
{
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_capable;
VkPhysicalDeviceProperties properties;
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
physical, &properties);
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS && driver_saw_dual_source);
assert(layer_gdpa(device, "vkCreateGraphicsPipelines") == (PFN_vkVoidFunction)mock_create_graphics_pipelines);
assert(layer_gdpa(device, "vkCreateShaderModule") == (PFN_vkVoidFunction)mock_create_shader_module);
assert(layer_gdpa(device, "vkCmdSetColorBlendEquationEXT") == (PFN_vkVoidFunction)mock_set_blend_equation);
destroy_device(device);
}
int main(int argc, char **argv)
{
test_spirv(argc > 1 ? argv[1] : NULL);
setenv("WINEPREFIX", "/nonexistent", 1);
unsetenv("DROIDDECK_MALI_COMPAT");
unsetenv("DROIDDECK_MALI_COMPAT_TRACE");
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
layer_gipa = negotiate.pfnGetInstanceProcAddr;
layer_gdpa = negotiate.pfnGetDeviceProcAddr;
VkLayerInstanceLink link = {NULL, mock_gipa, NULL};
VkLayerInstanceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO, {&link}};
VkInstanceCreateInfo info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &loader};
VkInstance instance;
PFN_vkCreateInstance create_instance = (PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance");
assert(create_instance(&info, NULL, &instance) == VK_SUCCESS);
test_lacking_device();
test_capable_device();
((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL);
free(driver_code);
printf("mali compat layer ok\n");
return 0;
}
+158
View File
@@ -0,0 +1,158 @@
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define BTN_LEFT 0x110
#define BTN_RIGHT 0x111
#define BTN_MIDDLE 0x112
#define INPUT_SPACE_W 1920
#define INPUT_SPACE_H 1080
#include "input_msg.inc"
#include "pen_state.inc"
enum { MOTION, PRESS, RELEASE };
struct event { int kind; uint32_t button; double x, y; int raw_valid; };
struct constraint { int is_lock; };
static struct constraint *g_active_constraint;
static struct surface *g_grab;
static int g_raw_valid;
static struct event events[16];
static int nevents, logs;
static uint32_t held;
static void scene_size(int *w, int *h) { *w = 3840; *h = 2160; }
static void vkp_output_size(int *w, int *h) { *w = 0; *h = 0; }
static int vkp_output_to_scene(double ox, double oy, double *x, double *y) {
(void)ox; (void)oy; (void)x; (void)y;
return 0;
}
static void pointer_event(double x, double y, uint32_t button, int pressed) {
assert(!button && !pressed && nevents < 16);
events[nevents++] = (struct event){MOTION, 0, x, y, g_raw_valid};
g_raw_valid = 1;
}
static void pointer_button(uint32_t button, int pressed) {
assert(button >= BTN_LEFT && button <= BTN_MIDDLE && nevents < 16);
uint32_t bit = 1u << (button - BTN_LEFT);
if (pressed) assert(!(held & bit));
else assert(held & bit);
held = pressed ? held | bit : held & ~bit;
events[nevents++] = (struct event){pressed ? PRESS : RELEASE, button, 0, 0, g_raw_valid};
}
static void pen_log_target(void) { logs++; }
#include "pen.inc"
static void pen(int flags, double x, double y) {
struct input_msg m = {13, flags, (int)(x * 256), (int)(y * 256), 0};
nevents = 0;
deliver_pen(&m);
}
static void motion(int i, double x, double y) {
assert(events[i].kind == MOTION && events[i].x == x && events[i].y == y);
}
static void button(int i, int kind, uint32_t code) {
assert(events[i].kind == kind && events[i].button == code);
}
static void expect(int count, uint32_t buttons) {
assert(nevents == count && held == buttons);
assert(g_pen.buttons == (int)buttons);
}
#define L (1u << 0)
#define R (1u << 1)
#define M (1u << 2)
int main(int argc, char **argv) {
assert(argc == 2);
const char *c = argv[1];
if (!strcmp(c, "hover")) {
pen(PEN_IN, 100.5, 50.25);
expect(1, 0); motion(0, 201, 100.5);
pen(PEN_IN, 2000, -4);
expect(1, 0); motion(0, 3839, 0);
assert(g_pen.in && logs == 2);
pen(0, 2000, -4);
expect(0, 0);
assert(!g_pen.in && logs == 2);
} else if (!strcmp(c, "tip")) {
pen(PEN_IN, 10, 10);
expect(1, 0);
pen(PEN_IN | PEN_TIP, 10, 10);
expect(2, L); motion(0, 20, 20); button(1, PRESS, BTN_LEFT);
pen(PEN_IN | PEN_TIP, 11, 10);
expect(1, L); motion(0, 22, 20);
pen(PEN_IN, 12, 10);
expect(2, 0); motion(0, 24, 20); button(1, RELEASE, BTN_LEFT);
pen(PEN_IN | PEN_TIP, 12, 10);
pen(PEN_IN, 12, 10);
pen(0, 12, 10);
expect(0, 0);
} else if (!strcmp(c, "buttons")) {
pen(PEN_IN | PEN_RIGHT, 10, 10);
expect(2, R); motion(0, 20, 20); button(1, PRESS, BTN_RIGHT);
pen(PEN_IN | PEN_RIGHT | PEN_MIDDLE, 10, 10);
expect(2, R | M); button(1, PRESS, BTN_MIDDLE);
pen(PEN_IN | PEN_MIDDLE | PEN_TIP, 11, 10);
expect(3, L | M); motion(0, 22, 20); button(1, PRESS, BTN_LEFT); button(2, RELEASE, BTN_RIGHT);
pen(PEN_IN | PEN_RIGHT, 12, 10);
expect(4, R); motion(0, 24, 20); button(1, PRESS, BTN_RIGHT);
button(2, RELEASE, BTN_LEFT); button(3, RELEASE, BTN_MIDDLE);
pen(PEN_IN, 12, 10);
expect(2, 0); button(1, RELEASE, BTN_RIGHT);
} else if (!strcmp(c, "out")) {
pen(PEN_IN | PEN_TIP | PEN_RIGHT | PEN_MIDDLE, 10, 10);
expect(4, L | R | M); motion(0, 20, 20);
button(1, PRESS, BTN_LEFT); button(2, PRESS, BTN_RIGHT); button(3, PRESS, BTN_MIDDLE);
pen(PEN_TIP | PEN_RIGHT | PEN_MIDDLE, 30, 30);
expect(3, 0);
button(0, RELEASE, BTN_LEFT); button(1, RELEASE, BTN_RIGHT); button(2, RELEASE, BTN_MIDDLE);
assert(!g_pen.in && !g_pen.buttons);
pen(0, 30, 30);
expect(0, 0);
} else if (!strcmp(c, "lock")) {
struct constraint lock = {1}, confine = {0};
g_active_constraint = &lock;
pen(PEN_IN, 10, 10);
expect(0, 0);
assert(g_pen.in && logs == 1);
pen(PEN_IN | PEN_TIP, 11, 10);
expect(1, L); button(0, PRESS, BTN_LEFT);
pen(PEN_IN | PEN_TIP, 40, 10);
expect(0, L);
pen(PEN_IN | PEN_RIGHT, 40, 10);
expect(2, R); button(0, PRESS, BTN_RIGHT); button(1, RELEASE, BTN_LEFT);
pen(0, 40, 10);
expect(1, 0); button(0, RELEASE, BTN_RIGHT);
g_active_constraint = &confine;
pen(PEN_IN, 10, 10);
expect(1, 0); motion(0, 20, 20);
} else if (!strcmp(c, "lost")) {
pen(PEN_IN | PEN_TIP, 10, 10);
expect(2, L); motion(0, 20, 20); button(1, PRESS, BTN_LEFT);
pen(0, 10, 10);
expect(1, 0); button(0, RELEASE, BTN_LEFT);
pen(PEN_IN | PEN_TIP | PEN_MIDDLE, 10, 10);
expect(3, L | M);
pen(PEN_IN, 50, 10);
expect(3, 0); motion(0, 100, 20); button(1, RELEASE, BTN_LEFT); button(2, RELEASE, BTN_MIDDLE);
} else {
assert(!strcmp(c, "raw"));
g_raw_valid = 1;
pen(PEN_IN, 10, 10);
assert(!events[0].raw_valid && g_raw_valid);
pen(PEN_IN, 11, 10);
assert(events[0].raw_valid);
pen(PEN_IN | PEN_TIP, 12, 10);
assert(events[0].raw_valid && events[1].raw_valid);
pen(0, 12, 10);
assert(!g_raw_valid);
g_raw_valid = 1;
pen(0, 12, 10);
assert(g_raw_valid);
}
puts("PASS");
}
+182
View File
@@ -0,0 +1,182 @@
#include <assert.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define BTN_LEFT 0x110
#define BTN_RIGHT 0x111
#define BTN_MIDDLE 0x112
#define INPUT_SPACE_W 1920
#define INPUT_SPACE_H 1080
#define WL_POINTER_FRAME_SINCE_VERSION 5
#define WL_POINTER_BUTTON_STATE_RELEASED 0
#define WL_POINTER_BUTTON_STATE_PRESSED 1
#include "input_msg.inc"
#include "pen_state.inc"
typedef int32_t wl_fixed_t;
struct wl_client { int id; };
struct wl_resource { struct wl_client *client; };
struct wl_display { int unused; };
struct surface { struct wl_resource *resource; int placed, x, y; };
struct seat_pointer { struct wl_resource *ptr, *focus; };
struct constraint { int is_lock; struct surface *surface; };
static struct wl_client client_a, client_b;
static struct wl_resource surface_a = {&client_a}, surface_b = {&client_b};
static struct wl_resource pointer_a = {&client_a}, pointer_b = {&client_b};
static struct surface a = {&surface_a, 1, 0, 0}, b = {&surface_b, 1, 1000, 0};
static struct seat_pointer g_ptrs[2] = {{&pointer_a, NULL}, {&pointer_b, NULL}};
static int g_nptrs = 2;
static struct wl_display *g_display;
static struct constraint *g_active_constraint;
static struct surface *g_desktop, *g_grab, *g_key_target, *g_ime_click;
static double g_ptr_x, g_ptr_y, g_raw_x, g_raw_y;
static int g_ptr_known, g_raw_valid;
static atomic_int g_cursor_composite;
enum { ENTER, LEAVE, PRESS, RELEASE };
struct event { int kind; struct wl_resource *pointer, *surface; uint32_t button; };
static struct event events[32];
static int nevents;
static void record(int kind, struct wl_resource *pointer, struct wl_resource *surface, uint32_t button) {
assert(nevents < 32);
events[nevents++] = (struct event){kind, pointer, surface, button};
}
static void scene_size(int *w, int *h) { *w = 2000; *h = 1000; }
static void vkp_output_size(int *w, int *h) { *w = 0; *h = 0; }
static int vkp_output_to_scene(double ox, double oy, double *x, double *y) {
(void)ox; (void)oy; (void)x; (void)y;
return 0;
}
static struct surface *toplevel_at(double x, double y) {
(void)y;
return x < 1000 ? &a : &b;
}
static void confine_clamp(struct constraint *k, double *x, double *y) { (void)k; (void)x; (void)y; }
static void schedule_render(void) {}
static void publish_query_state(void) {}
static void constraints_focus_entered(struct wl_resource *target, struct wl_client *client) {
(void)target; (void)client;
}
static void droiddeck_text_input_refocus(void) {}
static void pen_log_target(void) {}
static struct surface *dying;
static void wl_display_flush_clients(struct wl_display *display) {
(void)display;
if (!dying || !nevents || events[nevents - 1].kind != RELEASE) return;
if (g_grab == dying) g_grab = NULL;
if (g_pen.grab == dying) g_pen.grab = NULL;
dying = NULL;
}
static uint32_t now_ms(void) { return 0; }
static uint32_t wl_display_next_serial(struct wl_display *display) { (void)display; return 0; }
static int wl_resource_get_version(struct wl_resource *r) { (void)r; return 7; }
static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->client; }
static wl_fixed_t wl_fixed_from_double(double d) { return (wl_fixed_t)(d * 256); }
static int send_relative_motion(struct wl_client *client, double dx, double dy) {
(void)client; (void)dx; (void)dy;
return 0;
}
static void wl_pointer_send_enter(struct wl_resource *p, uint32_t serial, struct wl_resource *s,
wl_fixed_t x, wl_fixed_t y) {
(void)serial; (void)x; (void)y;
record(ENTER, p, s, 0);
}
static void wl_pointer_send_leave(struct wl_resource *p, uint32_t serial, struct wl_resource *s) {
(void)serial;
record(LEAVE, p, s, 0);
}
static void wl_pointer_send_motion(struct wl_resource *p, uint32_t t, wl_fixed_t x, wl_fixed_t y) {
(void)p; (void)t; (void)x; (void)y;
}
static void wl_pointer_send_frame(struct wl_resource *p) { (void)p; }
static void wl_pointer_send_button(struct wl_resource *p, uint32_t serial, uint32_t t, uint32_t button,
uint32_t state) {
(void)serial; (void)t;
record(state == WL_POINTER_BUTTON_STATE_PRESSED ? PRESS : RELEASE, p, NULL, button);
}
#include "pointer.inc"
#include "pen.inc"
static void pen(int flags, double x) {
struct input_msg m = {13, flags, (int)(x * INPUT_SPACE_W / 2000 * 256), 100 * 256, 0};
nevents = 0;
deliver_pen(&m);
}
static void focus(int i, struct wl_resource *pointer, struct wl_resource *surface) {
assert(i < nevents && events[i].kind == ENTER && events[i].pointer == pointer && events[i].surface == surface);
}
static void left(int i, struct wl_resource *pointer, struct wl_resource *surface) {
assert(i < nevents && events[i].kind == LEAVE && events[i].pointer == pointer && events[i].surface == surface);
}
static void button(int i, int kind, uint32_t code) {
assert(i < nevents && events[i].kind == kind && events[i].pointer == &pointer_a && events[i].button == code);
}
static void hover_away(void) {
assert(!g_grab);
pen(PEN_IN, 1500);
assert(nevents == 2);
left(0, &pointer_a, &surface_a); focus(1, &pointer_b, &surface_b);
}
int main(int argc, char **argv) {
assert(argc == 2);
const char *c = argv[1];
pen(PEN_IN, 500);
assert(nevents == 1);
focus(0, &pointer_a, &surface_a);
pen(PEN_IN | PEN_TIP, 500);
assert(nevents == 1 && g_grab == &a);
button(0, PRESS, BTN_LEFT);
if (!strcmp(c, "side")) {
pen(PEN_IN | PEN_TIP | PEN_RIGHT, 600);
assert(nevents == 1 && g_grab == &a);
button(0, PRESS, BTN_RIGHT);
pen(PEN_IN | PEN_TIP, 700);
assert(nevents == 1 && g_grab == &a);
button(0, RELEASE, BTN_RIGHT);
pen(PEN_IN | PEN_TIP, 1500);
assert(nevents == 0 && g_grab == &a);
pen(PEN_IN, 1500);
assert(nevents == 1);
button(0, RELEASE, BTN_LEFT);
} else if (!strcmp(c, "swap")) {
pen(PEN_IN | PEN_RIGHT, 600);
assert(nevents == 2 && g_grab == &a);
button(0, PRESS, BTN_RIGHT); button(1, RELEASE, BTN_LEFT);
pen(PEN_IN | PEN_RIGHT, 1500);
assert(nevents == 0 && g_grab == &a);
pen(PEN_IN, 1500);
assert(nevents == 1);
button(0, RELEASE, BTN_RIGHT);
} else if (!strcmp(c, "mouse")) {
pointer_button(BTN_RIGHT, 1);
pointer_button(BTN_RIGHT, 0);
pen(PEN_IN | PEN_TIP, 1500);
assert(nevents == 0 && g_grab == &a);
pen(PEN_IN, 1500);
assert(nevents == 1);
button(0, RELEASE, BTN_LEFT);
} else {
assert(!strcmp(c, "gone"));
pen(PEN_IN | PEN_TIP | PEN_RIGHT, 600);
assert(nevents == 1 && g_grab == &a);
dying = &a;
pen(PEN_IN | PEN_TIP, 700);
assert(nevents == 1 && !dying && !g_grab && !g_pen.grab);
button(0, RELEASE, BTN_RIGHT);
pen(PEN_IN, 700);
assert(nevents == 1);
button(0, RELEASE, BTN_LEFT);
}
hover_away();
puts("PASS");
}
+365 -1
View File
@@ -47,6 +47,47 @@ class LogTest(Temp):
self.assertRegex(log.read_text(), r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d \[\d+\] second\n$")
class StoreDebugEnvironmentTest(Temp):
def config(self, enabled):
config = self.tmp / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text(json.dumps({"version": 1, "gameDebugLogs": enabled}))
def env(self, values=None):
debug_dir = self.tmp / "session"
debug_dir.mkdir(exist_ok=True)
base = {"HOME": str(self.tmp), "BL_DEBUG_DIR": str(debug_dir)}
base.update(values or {})
return base
def test_store_proton_command_gets_debug_defaults_when_enabled(self):
self.config(True)
with mock.patch.dict(os.environ, self.env(), clear=True):
result = BNET["proton_env"]()
self.assertEqual(result["PROTON_LOG"], "1")
self.assertEqual(result["DXVK_LOG_LEVEL"], "debug")
self.assertEqual(result["PROTON_LOG_DIR"], str(self.tmp / "session"))
self.assertIn("+seh", result["WINEDEBUG"])
def test_store_proton_command_keeps_debug_off_when_disabled(self):
self.config(False)
with mock.patch.dict(os.environ, self.env(), clear=True):
result = BNET["proton_env"]()
self.assertNotIn("PROTON_LOG", result)
self.assertNotIn("DXVK_LOG_LEVEL", result)
def test_store_proton_command_keeps_user_debug_values(self):
self.config(True)
values = {"PROTON_LOG": "0", "DXVK_LOG_LEVEL": "none", "WINEDEBUG": "-all", "PROTON_LOG_DIR": "/custom"}
with mock.patch.dict(os.environ, self.env(values), clear=True):
result = BNET["proton_env"]()
self.assertEqual(result["PROTON_LOG"], "1")
self.assertEqual(result["DXVK_LOG_LEVEL"], "debug")
self.assertEqual(result["PROTON_LOG_DIR"], str(self.tmp / "session"))
self.assertIn("+seh", result["WINEDEBUG"])
self.assertIn("-all", result["WINEDEBUG"])
class IdTest(unittest.TestCase):
def test_the_prefix_id_is_the_shortcut_id_the_app_names(self):
self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000)
@@ -198,6 +239,155 @@ class ConfigAndMenuTest(Temp):
self.assertEqual(path.stat().st_mtime_ns, mtime)
class DriveTest(Temp):
def setUp(self):
super().setUp()
self.root = str(self.tmp / "Steam")
self.devices = Path(BNET["dosdevices"](self.root))
self.card = self.tmp / "card"
self.library = self.card / "Games/Battle.net"
self.library.mkdir(parents=True)
self.running = []
patcher = mock.patch.dict(BNET, {"say": lambda message: None, "wine_processes": lambda pfx, proc="/proc": list(self.running),
"volume_root": lambda path: str(self.card) if BNET["inside"](path, str(self.card)) else "/"})
patcher.start()
self.addCleanup(patcher.stop)
def test_a_volume_ends_where_the_device_changes(self):
devices = {"/": 1, "/mnt": 1, "/mnt/card": 7, "/mnt/card/Games": 7, "/mnt/card/Games/Battle.net": 7, "/root": 1, "/root/Games": 1}
with mock.patch.object(os, "stat", lambda path: mock.Mock(st_dev=devices[path])):
volume_root = runpy.run_path(str(BIN / "droiddeck-battlenet"))["volume_root"]
self.assertEqual(volume_root("/mnt/card/Games/Battle.net"), "/mnt/card")
self.assertEqual(volume_root("/mnt/card"), "/mnt/card")
self.assertEqual(volume_root("/root/Games"), "/")
self.assertEqual(volume_root("/"), "/")
def test_a_library_on_the_root_volume_keeps_its_path_and_gets_no_drive(self):
library = self.tmp / "root/Games/Battle.net"
library.mkdir(parents=True)
self.assertEqual(BNET["install_path"](self.root, str(library) + "/"), "Z:" + str(library))
self.assertFalse(self.devices.exists())
def test_a_library_on_another_volume_gets_a_drive_at_the_volume_root(self):
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
self.assertEqual(os.readlink(self.devices / "d:"), str(self.card))
self.assertEqual(BNET["install_path"](self.root, str(self.library / "World of Warcraft")), "D:\\Games\\Battle.net\\World of Warcraft")
self.assertEqual(BNET["install_path"](self.root, str(self.card)), "D:\\")
self.assertEqual(sorted(os.listdir(self.devices)), ["d:"])
def test_drives_in_use_and_the_ones_proton_owns_are_left_alone(self):
self.devices.mkdir(parents=True)
os.symlink("/somewhere/else", self.devices / "d:")
os.symlink(str(self.card), self.devices / "s:")
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "E:\\Games\\Battle.net")
self.assertEqual(os.readlink(self.devices / "d:"), "/somewhere/else")
for letter in BNET["DRIVES"]:
if not os.path.lexists(self.devices / (letter + ":")):
os.symlink("/somewhere/else", self.devices / (letter + ":"))
os.unlink(self.devices / "e:")
os.symlink("/somewhere/else", self.devices / "e:")
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library))
self.assertNotIn("s", BNET["DRIVES"])
self.assertNotIn("t", BNET["DRIVES"])
def test_a_running_prefix_gets_no_new_drive_but_uses_the_ones_it_started_with(self):
self.running = [(5, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])]
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library))
self.assertFalse(self.devices.exists())
self.running = []
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
self.running = [(5, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])]
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
def test_a_drive_mapped_inside_the_volume_is_reused(self):
self.devices.mkdir(parents=True)
os.symlink(str(self.card / "Games"), self.devices / "g:")
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "G:\\Battle.net")
self.assertEqual(sorted(os.listdir(self.devices)), ["g:"])
def test_the_config_stores_the_drive_path_once(self):
path = self.tmp / ("Steam/steamapps/compatdata/%s/pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config"
% BNET["APP_ID"])
BNET["write_config"](self.root)
self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library")
self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Games\\Battle.net")
self.assertIsNone(BNET["write_config"](self.root, str(self.library)))
def test_registered_paths_resolve_through_their_drive(self):
BNET["install_path"](self.root, str(self.library))
self.assertEqual(BNET["windows_path"](self.root, "D:/Games/Battle.net/World of Warcraft"),
str(self.library / "World of Warcraft"))
self.assertEqual(BNET["windows_path"](self.root, "Z:\\mnt\\card\\World of Warcraft"), "/mnt/card/World of Warcraft")
self.assertEqual(BNET["windows_path"](self.root, "C:/Program Files (x86)/World of Warcraft"),
os.path.join(BNET["drive_c"](self.root), "Program Files (x86)/World of Warcraft"))
self.assertIsNone(BNET["windows_path"](self.root, "E:/Games/X"))
self.assertIsNone(BNET["windows_path"](self.root, "D:/../etc"))
self.assertEqual(BNET["windows_path"](self.root, "D:\\"), str(self.library.parent.parent))
def field(self, number, value):
varint = BNET["encode_varint"]
return varint(number << 3 | 2) + varint(len(value)) + value
def product(self, uid, folder, filler=b""):
settings = self.field(1, folder.encode()) + self.field(2, b"us") + b"\x18\x02" + filler
return self.field(1, self.field(1, uid.encode()) + self.field(2, uid.encode()) + self.field(3, settings)
+ b"\x21" + bytes(8) + b"\x2d" + bytes(4))
def database(self, *products):
path = Path(BNET["drive_c"](self.root)) / "ProgramData/Battle.net/Agent/product.db"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"".join(products) + self.field(7, b"tail"))
path.chmod(0o600)
return path
def test_games_registered_through_the_root_drive_move_to_their_volume_drive(self):
game = self.library / "World of Warcraft"
game.mkdir()
other = self.tmp / "root/Games/Other"
other.mkdir(parents=True)
client = self.product("battle.net", "C:/Program Files (x86)/Battle.net")
local = self.product("other", "Z:" + str(other))
gone = self.product("gone", "Z:" + str(self.card / "Missing"))
path = self.database(client, self.product("wow", "Z:" + str(game), bytes(200)), local, gone)
self.assertTrue(BNET["move_installs"](self.root))
self.assertEqual(path.read_bytes(), client + self.product("wow", "D:/Games/Battle.net/World of Warcraft", bytes(200))
+ local + gone + self.field(7, b"tail"))
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
self.assertEqual(os.readlink(self.devices / "d:"), str(self.card))
self.assertFalse(BNET["move_installs"](self.root))
def test_registrations_stay_while_the_prefix_runs_or_the_database_is_unreadable(self):
game = self.library / "World of Warcraft"
game.mkdir()
path = self.database(self.product("wow", "Z:" + str(game)))
before = path.read_bytes()
self.running = [(5, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])]
self.assertFalse(BNET["move_installs"](self.root))
self.assertEqual(path.read_bytes(), before)
self.running = []
for broken in (before[:-3], b"\x0a\xff", b"\x0b\x01"):
path.write_bytes(broken)
self.assertFalse(BNET["move_installs"](self.root))
self.assertEqual(path.read_bytes(), broken)
os.unlink(path)
self.assertFalse(BNET["move_installs"](self.root))
def test_a_database_written_while_it_was_being_read_is_left_as_written(self):
game = self.library / "World of Warcraft"
game.mkdir()
path = self.database(self.product("wow", "Z:" + str(game)))
newer = path.read_bytes() + self.field(7, b"newer")
def processes(pfx, proc="/proc"):
path.write_bytes(newer)
return []
with mock.patch.dict(BNET, {"wine_processes": processes}):
self.assertFalse(BNET["move_installs"](self.root))
self.assertEqual(path.read_bytes(), newer)
self.assertTrue(BNET["move_installs"](self.root))
class GamepadTest(Temp):
def registry(self, *entries):
rows = ["WINE REGISTRY Version 2"]
@@ -772,7 +962,7 @@ class Harness(Temp):
"stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))),
"start": lambda exe, verb=None: self.calls.append(("start", os.path.basename(exe), verb)) or self.Proton(),
"spawn": lambda program, verb, args=(): self.calls.append(("spawn", os.path.basename(program), verb, list(args))),
"acquire": lambda folder=None: self.lock,
"acquire": lambda folder=None: self.lock, "volume_root": lambda path: "/",
"POLL": 0, "READY_SETTLE": 0, "GAME_GRACE": 0, "CLIENT_WAIT": 0,
})
patcher.start()
@@ -1170,6 +1360,7 @@ class AgentTest(Temp):
script = BNET["AGENT_SCRIPT"]
self.assertIn("port = a(0), action = a(1), uid = a(2), product = a(3), dir = a(4)", script)
self.assertIn("lang = a(5), country = a(6), region = a(7), out = a(8)", script)
self.assertIn(r'''"game_dir":"' + dir.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '","geo''', script)
self.assertIn('"--internalclienttools"', (BIN / "droiddeck-battlenet").read_text())
def test_the_driver_asks_blizzards_chinese_repository_for_chinese_installs(self):
@@ -1230,6 +1421,40 @@ class AgentJobTest(Harness):
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
def test_an_install_on_another_volume_is_handed_over_by_its_drive_once_the_prefix_is_stopped(self):
self.install()
card = self.tmp / "card"
folder = str(card / "Games/Battle.net/Warcraft Rumble")
self.files = {".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}),
".game": json.dumps({"installed": True, "install_dir": "D:/Games/Battle.net/Warcraft Rumble", "local_version": "1",
"binaries": {"game": {"relative_path": "WarcraftRumble.exe"}}})}
self.states = [[(7, self.AGENT)]]
events = []
real_map = BNET["map_drive"]
def acquire(folder=None):
events.append("lock")
return self.lock
def stop(pfx):
events.append(("stop", not self.lock.closed))
self.states = [[]]
return True
def map_drive(root, volume):
events.append(("map", not self.lock.closed))
return real_map(root, volume)
with mock.patch.dict(BNET, {"volume_root": lambda path: str(card), "stop_leftovers": stop, "map_drive": map_drive,
"acquire": acquire}):
code = BNET["agent_job"](self.root, "install", "gryphon", "gryphon", folder, "enUS", "USA", "US", poll=0)
self.assertEqual(code, 0)
self.assertEqual(events, ["lock", ("stop", True), ("map", True)])
self.assertTrue(self.lock.closed)
cmd = self.started[0]
self.assertEqual(cmd[cmd.index("--") + 6], "D:\\Games\\Battle.net\\Warcraft Rumble")
self.assertEqual(os.readlink(os.path.join(BNET["dosdevices"](self.root), "d:")), str(card))
def test_an_agent_error_is_reported_with_its_code(self):
self.install()
self.files = {".json": json.dumps({"error": 2421, "progress": 0.0})}
@@ -1257,6 +1482,138 @@ class AgentJobTest(Harness):
self.assertEqual(BNET["agent_job"](self.root, "update", "gryphon", poll=0), 1)
self.assertEqual(self.lines[-1][0], "ERROR")
def test_a_job_that_stops_moving_is_ended_as_stalled_and_its_agent_stopped(self):
self.install()
self.files = {".json": json.dumps({"state": 1003, "paused": True, "download_current": [10, 0, 0], "download_total": [99, 0, 0]})}
killed = []
stopped = []
class Hung:
returncode = None
def __init__(self, cmd, **kwargs):
base = cmd[-1][2:].replace("\\", "/")
with open(base + ".json", "wb") as f:
f.write(self_files[".json"].encode("utf-16"))
def poll(self):
return None
def kill(self):
killed.append(True)
def wait(self):
return -9
self_files = self.files
with mock.patch.object(BNET["subprocess"], "Popen", Hung), \
mock.patch.dict(BNET, {"wine_processes": lambda pfx: [(5, ["agent.exe"])], "stop": lambda p: stopped.append(p)}):
code = BNET["agent_job"](self.root, "install", "s1", "s1", str(self.tmp / "S1"), "enUS", "USA", "US", poll=0, stall=0.05)
self.assertEqual(code, 6)
self.assertEqual(killed, [True])
self.assertEqual(stopped, [[(5, ["agent.exe"])]])
self.assertEqual(self.lines[-1], ("ERROR", "stalled"))
def test_a_stalled_job_leaves_a_game_or_client_in_the_prefix_running(self):
self.install()
self.files = {".json": json.dumps({"state": 1003, "download_current": [10, 0, 0], "download_total": [99, 0, 0]})}
stopped = []
calls = []
class Hung:
returncode = None
def __init__(self, cmd, **kwargs):
calls.append(True)
def poll(self):
return None
def kill(self):
pass
def wait(self):
return -9
def processes(pfx):
if not calls:
return [(3, ["agent.exe"])]
return [(3, ["agent.exe"]), (5, ["Agent.exe"]), (6, ["wineserver"]), (7, ["Wow.exe"])]
with mock.patch.object(BNET["subprocess"], "Popen", Hung), \
mock.patch.dict(BNET, {"wine_processes": processes, "stop": lambda p: stopped.append(p)}):
code = BNET["agent_job"](self.root, "install", "s1", "s1", str(self.tmp / "S1"), "enUS", "USA", "US", poll=0, stall=0.05)
self.assertEqual(code, 6)
self.assertEqual(stopped, [[(5, ["Agent.exe"])]])
def test_only_a_changing_rate_or_estimate_does_not_hold_off_the_stall(self):
self.install()
clock = [0.0]
class Spinning:
returncode = None
def __init__(self, cmd, **kwargs):
self.base = cmd[-1][2:].replace("\\", "/")
self.polls = 0
def poll(self):
self.polls += 1
if self.polls > 10:
raise AssertionError("the stall timeout never ended the job")
clock[0] += 10
with open(self.base + ".json", "wb") as f:
f.write(json.dumps({"state": 1003, "download_current": [4, 0, 0], "download_total": [9, 0, 0],
"download_rate": self.polls, "estimated_time_in_sec": self.polls}).encode("utf-16"))
return None
def kill(self):
pass
def wait(self):
return -9
fake = mock.Mock(monotonic=lambda: clock[0], sleep=lambda s: None)
with mock.patch.object(BNET["subprocess"], "Popen", Spinning), mock.patch.dict(BNET, {"time": fake, "stop": lambda p: None}):
code = BNET["agent_job"](self.root, "update", "gryphon", poll=0, stall=25)
self.assertEqual(code, 6)
self.assertEqual(self.lines[-1], ("ERROR", "stalled"))
def test_a_moving_job_is_not_ended_as_stalled(self):
self.install()
done = json.dumps({"installed": True, "playable": True, "install_dir": "Z:/g", "local_version": "2"})
clock = [0.0]
class Moving:
returncode = 0
def __init__(self, cmd, **kwargs):
self.base = cmd[-1][2:].replace("\\", "/")
self.polls = 0
def poll(self):
self.polls += 1
clock[0] += 10
with open(self.base + ".json", "wb") as f:
f.write(json.dumps({"state": 1003, "download_current": [self.polls, 0, 0], "download_total": [9, 0, 0]}).encode("utf-16"))
if self.polls < 6:
return None
with open(self.base + ".game", "wb") as f:
f.write(done.encode("utf-16"))
return 0
fake = mock.Mock(monotonic=lambda: clock[0], sleep=lambda s: None)
with mock.patch.object(BNET["subprocess"], "Popen", Moving), mock.patch.dict(BNET, {"time": fake}):
code = BNET["agent_job"](self.root, "update", "gryphon", poll=0, stall=15)
self.assertEqual(code, 0)
self.assertNotIn(("ERROR", "stalled"), self.lines)
def test_only_a_real_job_reply_counts_as_started(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn("if (state == 1000 || state == 1003 || job(s) && !complete) started = true;", script)
self.assertIn('return /"state"\\s*:\\s*\\d+/.test(bare) || /"download_current"\\s*:/.test(bare);', script)
self.assertIn('if (/"error"\\s*:\\s*[1-9]/.test(text)) return false;', script)
def test_the_driver_only_stops_once_the_agent_has_really_run(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn("if (started && (state == 1004 || complete && /\"playable\"\\s*:\\s*true/.test(s))) break;", script)
@@ -1352,5 +1709,12 @@ class AgentJobTest(Harness):
self.assertEqual(calls, [("install", "gryphon", "gryphon", "/g/Rumble", "enUS", "USA", "US"), ("update", "wow_classic")])
class BattleNetFormTest(Temp):
def test_the_driver_waits_on_the_install_form_and_names_a_folder_that_is_taken(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn(r'if (/"form"\s*:\s*\{/.test(s)) {', script)
self.assertIn("the game folder already holds a game", script)
if __name__ == "__main__":
unittest.main()
+1
View File
@@ -121,6 +121,7 @@ step() { :; }
bl_zram_scan() { :; }
bl_memory_read() { :; }
bl_client_pressure() { :; }
bl_client_pressure_finish() { :; }
bl_session_pressure() { :; }
bl_client_can_pageout() { return 0; }
bl_client_can_readback() { [ "${readback:-1}" = 1 ]; }
+141 -2
View File
@@ -1,19 +1,34 @@
import os
from pathlib import Path
import queue
import re
import shlex
import shutil
import struct
import subprocess
import tempfile
import threading
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
def clock_reset_command(control):
script = (PRELOAD.parent / "overlay/usr/local/bin/droiddeck-session").read_text()
start = script.index('if [ -z "${BL_INSIDE:-}" ]; then\n if [ "${BL_ZRAM:-0}"')
end = script.index("\nfi", start) + len("\nfi")
paths = {"/tmp/.bl-clock": shlex.quote(str(control)),
"/tmp/.bl-zram": shlex.quote(str(control.parent / "zram"))}
pattern = "|".join(re.escape(token) for token in paths)
return 'BL_INSIDE=; BL_ZRAM=0; ' + re.sub(pattern, lambda match: paths[match.group(0)], script[start:end])
PROGRAM = r"""
#define _GNU_SOURCE
#include <linux/futex.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/timerfd.h>
@@ -36,12 +51,26 @@ static int64_t start;
static void begin(void) { start = ns(CLOCK_BOOTTIME); }
static void end(const char *name) { printf("%s %lld\n", name, (long long)((ns(CLOCK_BOOTTIME) - start) / 1000000LL)); }
static unsigned long long memory_probe(void) {
static volatile unsigned char memory[4 * 1024 * 1024];
unsigned long long checksum = 0;
for (size_t i = 0; i < sizeof(memory); i += 4096) memory[i] = (unsigned char)(i / 4096 + 1);
for (size_t i = 0; i < sizeof(memory); i += 4096) checksum += memory[i];
return checksum;
}
int main(void) {
const int64_t wait = 60000000LL;
printf("gap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL));
struct timespec raw;
syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &raw);
printf("rawgap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ((int64_t)raw.tv_sec * 1000000000LL + raw.tv_nsec)) / 1000000LL));
printf("memory %llu\n", memory_probe());
if (getenv("CLOCK_PAUSE_WAIT")) { puts("ready"); fflush(stdout); getchar(); }
if (getenv("CLOCK_PAUSE_WAIT")) {
printf("livegap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL));
printf("livememory %llu\n", memory_probe());
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_condattr_t attr;
@@ -124,14 +153,124 @@ class ClockPausePreloadTest(unittest.TestCase):
self.assertGreaterEqual(paused[name], 50, name)
self.assertLess(paused[name], 1000, name)
def test_other_programs_keep_the_real_clock(self):
def test_program_without_preload_keeps_the_real_clock(self):
plain = self.run_program(self.other, 0, preload=False)
paused = self.run_program(self.other, SHIFT_MS)
paused = self.run_program(self.other, SHIFT_MS, preload=False)
self.assertAlmostEqual(paused["gap"], plain["gap"], delta=50)
for name in ("cond_mono", "clockwait", "sem", "nanosleep", "timerfd", "futex"):
self.assertGreaterEqual(paused[name], 50, name)
self.assertLess(paused[name], 1000, name)
def test_every_session_program_stops_monotonic_clock_and_keeps_memory_access(self):
plain = self.run_program(self.other, 0)
paused = self.run_program(self.other, SHIFT_MS)
self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50)
self.assertAlmostEqual(paused["rawgap"] - plain["rawgap"], SHIFT_MS, delta=50)
self.assertEqual(plain["memory"], 130560)
self.assertEqual(paused["memory"], 130560)
def test_running_session_program_observes_pause_offset_update(self):
self.check_running_offset_update(False)
def test_session_reset_preserves_live_guest_mapping(self):
self.check_running_offset_update(True)
def check_running_offset_update(self, reset):
self.control.write_bytes(struct.pack("<q", 0))
env = dict(os.environ)
env["LD_PRELOAD"] = str(self.preload)
env["CLOCK_PAUSE_WAIT"] = "1"
with tempfile.TemporaryFile(mode="w+") as errors:
process = subprocess.Popen([str(self.other)], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=errors, text=True)
lines = queue.Queue()
def read_handshake():
for _ in range(4):
line = process.stdout.readline()
lines.put(line)
if not line:
break
threading.Thread(target=read_handshake, daemon=True).start()
try:
handshake = []
for _ in range(4):
try:
line = lines.get(timeout=5)
except queue.Empty:
line = ""
if not line:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
errors.seek(0)
self.fail(f"child handshake timed out or ended early (exit {process.returncode}): {errors.read()}")
handshake.append(line.strip())
self.assertEqual(handshake[3], "ready")
self.assertTrue(handshake[0].startswith("gap "))
initial_gap = int(handshake[0].split()[1])
rawgap = handshake[1]
memory = handshake[2]
self.assertTrue(rawgap.startswith("rawgap "))
self.assertEqual(memory, "memory 130560")
if reset:
inode = self.control.stat().st_ino
subprocess.run(["bash", "-c", clock_reset_command(self.control)],
check=True, timeout=5)
self.assertEqual(self.control.stat().st_ino, inode)
self.assertEqual(self.control.read_bytes(), struct.pack("<q", 0))
with self.control.open("r+b") as control:
control.write(struct.pack("<q", SHIFT_MS * 1000000))
control.flush()
process.stdin.write("\n")
process.stdin.flush()
output, _ = process.communicate(timeout=5)
errors.seek(0)
self.assertEqual(process.returncode, 0, errors.read())
values = dict(line.split() for line in output.splitlines())
self.assertAlmostEqual(int(values["livegap"]) - initial_gap, SHIFT_MS, delta=50)
self.assertEqual(int(values["livememory"]), 130560)
finally:
if process.poll() is None:
process.kill()
process.communicate()
class ClockResetCommandTest(unittest.TestCase):
def test_reset_keeps_paths_with_spaces_and_shell_syntax_as_single_arguments(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
folder = root / "session dir; touch injected $(touch substituted) 'quoted'"
folder.mkdir()
control = folder / "clock"
control.write_bytes(struct.pack("<q", 10_000_000_000) + b"tail")
(folder / "zram").write_text("1")
bystander = root / "session"
bystander.write_text("keep")
inode = control.stat().st_ino
subprocess.run(["bash", "-c", clock_reset_command(control)], cwd=root, check=True, timeout=5)
self.assertEqual(control.stat().st_ino, inode)
self.assertEqual(control.read_bytes(), struct.pack("<q", 0) + b"tail")
self.assertFalse((folder / "zram").exists())
self.assertEqual(bystander.read_text(), "keep")
self.assertEqual(sorted(path.name for path in root.iterdir()), sorted([folder.name, bystander.name]))
def test_reset_does_not_rewrite_placeholders_inside_substituted_paths(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
folder = root / "tmp/.bl-zram/$(touch injected)"
folder.mkdir(parents=True)
control = folder / "clock"
control.write_bytes(struct.pack("<q", 10_000_000_000))
(folder / "zram").write_text("1")
inode = control.stat().st_ino
subprocess.run(["bash", "-c", clock_reset_command(control)], cwd=root, check=True, timeout=5)
self.assertEqual(control.stat().st_ino, inode)
self.assertEqual(control.read_bytes(), struct.pack("<q", 0))
self.assertFalse((folder / "zram").exists())
self.assertEqual([path.name for path in root.iterdir()], ["tmp"])
if __name__ == "__main__":
unittest.main()
+93
View File
@@ -0,0 +1,93 @@
import json
import os
from pathlib import Path
import subprocess
import tempfile
import time
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'agent/dd-lab-build'
class LabBuildOptionsTest(unittest.TestCase):
def run_script(self, *args):
with tempfile.TemporaryDirectory() as tmp:
inbox = Path(tmp) / 'agent'
inbox.mkdir()
env = {**os.environ, 'HOME': tmp, 'DD_AGENT': '1', 'DD_AGENT_INBOX': str(inbox)}
env.pop('DD_LAB_DETACHED', None)
result = subprocess.run(['bash', str(SCRIPT), *args], env=env,
capture_output=True, text=True, timeout=10)
return result, (inbox / 'lab-request').exists()
def test_help_prints_usage_without_starting_a_build(self):
result, requested = self.run_script('--help')
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('Usage: dd-lab-build', result.stdout)
self.assertFalse(requested)
def test_unknown_options_are_refused_without_starting_a_build(self):
result, requested = self.run_script('--bogus')
self.assertEqual(2, result.returncode)
self.assertIn('unknown option --bogus', result.stderr)
self.assertFalse(requested)
class LabBuildPackageTest(unittest.TestCase):
def test_package_override_survives_app_handoff_without_its_environment(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
inbox = root / 'agent'
inbox.mkdir()
cache = root / '.cache'
env = {**os.environ, 'HOME': tmp, 'DD_AGENT': '1',
'DD_AGENT_INBOX': str(inbox), 'DROIDDECK_PACKAGE': 'com.example.target'}
env.pop('DD_LAB_DETACHED', None)
child = subprocess.Popen(['bash', str(SCRIPT), '--prepare'], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
request = inbox / 'lab-request'
deadline = time.monotonic() + 10
while not request.exists() and child.poll() is None and time.monotonic() < deadline:
time.sleep(0.01)
self.assertTrue(request.exists())
payload = json.loads(request.read_text())
self.assertEqual(['--prepare', '--package=com.example.target'], payload['args'])
progress = cache / 'dd-lab-build.json'
progress.write_text('{"stage":"prepared"}')
stdout, stderr = child.communicate(timeout=10)
self.assertEqual(0, child.returncode, stdout + stderr)
finally:
if child.poll() is None:
child.kill()
child.communicate()
bin_dir = root / 'bin'
bin_dir.mkdir()
(bin_dir / 'adb').write_text('#!/bin/sh\nexit 0\n')
(bin_dir / 'python3').write_text(
'#!/bin/sh\nprintf "%s" "$DROIDDECK_PACKAGE" > "$HOME/selected-package"\nexit 1\n')
for tool in bin_dir.iterdir():
tool.chmod(0o755)
env.pop('DROIDDECK_PACKAGE')
env['DD_LAB_DETACHED'] = '1'
env['PATH'] = str(bin_dir) + os.pathsep + env['PATH']
result = subprocess.run(['bash', str(SCRIPT), *payload['args']], env=env,
capture_output=True, text=True, timeout=10, cwd=SCRIPT.parents[2])
self.assertNotEqual(0, result.returncode)
self.assertIn('could not read DroidDeck', result.stderr)
self.assertEqual('com.example.target', (root / 'selected-package').read_text())
def test_invalid_packages_are_rejected_before_handoff(self):
with tempfile.TemporaryDirectory() as tmp:
inbox = Path(tmp) / 'agent'
inbox.mkdir()
for package in ('bad;touch injected', '../other', '', 'com.example/other'):
with self.subTest(package=package):
env = {**os.environ, 'HOME': tmp, 'DD_AGENT': '1', 'DD_AGENT_INBOX': str(inbox)}
result = subprocess.run(['bash', str(SCRIPT), '--package=' + package], env=env,
capture_output=True, text=True, timeout=10)
self.assertNotEqual(0, result.returncode)
self.assertIn('invalid Android package', result.stderr)
self.assertFalse((inbox / 'lab-request').exists())
+245
View File
@@ -0,0 +1,245 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
FAKE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
static int answer(int fd) {
char link[32], path[4096];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
long n = syscall(SYS_readlinkat, AT_FDCWD, link, path, sizeof(path) - 1);
path[n > 0 ? n : 0] = '\0';
if (strstr(path, "/card/")) return ENOTSUP;
if (strstr(path, "/denied/")) return EACCES;
return ENODATA;
}
ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) {
(void)name; (void)value; (void)size;
errno = answer(fd);
return -1;
}
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) {
(void)name; (void)value; (void)size; (void)flags;
int error = answer(fd);
if (error == ENODATA) return 0;
errno = error;
return -1;
}
int fremovexattr(int fd, const char *name) {
(void)name;
errno = answer(fd);
return -1;
}
"""
PROGRAM = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/xattr.h>
#include <unistd.h>
static const char *error(void) {
return errno == ENOTSUP ? "unsupported" : errno == ENODATA ? "none" : errno == ERANGE ? "range" :
errno == EACCES ? "denied" : "other";
}
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
const char *op = argv[i];
if (!strcmp(op, "unlink") || !strcmp(op, "rmdir")) {
const char *path = argv[++i];
printf("%s\n", (op[0] == 'u' ? unlink(path) : rmdir(path)) == 0 ? "ok" : "failed");
continue;
}
if (!strcmp(op, "remove-path")) {
printf("%s\n", remove(argv[++i]) == 0 ? "ok" : "failed");
continue;
}
if (!strcmp(op, "rename")) {
const char *from = argv[++i], *to = argv[++i];
printf("%s\n", rename(from, to) == 0 ? "ok" : "failed");
continue;
}
int fd = open(argv[++i], O_RDONLY);
char value[64];
if (!strcmp(op, "set")) {
const char *text = argv[++i];
errno = 1234;
int result = fsetxattr(fd, "user.wine.sd", text, strlen(text), 0);
printf("%s\n", result == 0 ? errno == 1234 ? "ok" : "errno" : error());
} else if (!strcmp(op, "get")) {
ssize_t n = fgetxattr(fd, "user.wine.sd", value, sizeof(value));
if (n < 0) printf("%s\n", error());
else printf("=%.*s\n", (int)n, value);
} else if (!strcmp(op, "size")) {
ssize_t n = fgetxattr(fd, "user.wine.sd", NULL, 0);
if (n < 0) printf("%s\n", error());
else printf("%d\n", (int)n);
} else if (!strcmp(op, "short")) {
ssize_t n = fgetxattr(fd, "user.wine.sd", value, 2);
printf("%s\n", n < 0 ? error() : "read");
} else if (!strcmp(op, "remove")) {
errno = 1234;
int result = fremovexattr(fd, "user.wine.sd");
printf("%s\n", result == 0 ? errno == 1234 ? "ok" : "errno" : error());
} else if (!strcmp(op, "other")) {
ssize_t n = fgetxattr(fd, "user.other", value, sizeof(value));
printf("%s\n", n < 0 ? error() : "read");
}
close(fd);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class DescriptorPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.build_dir = tempfile.TemporaryDirectory()
build = Path(cls.build_dir.name)
(build / "fake.c").write_text(FAKE)
(build / "program.c").write_text(PROGRAM)
cls.preload = build / "libblsession.so"
cls.fake = build / "fake.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c")], check=True)
cls.wineserver = build / "wineserver"
subprocess.run(["cc", "-O2", "-o", str(cls.wineserver), str(build / "program.c")], check=True)
cls.other = build / "wine64-preloader"
shutil.copy(cls.wineserver, cls.other)
@classmethod
def tearDownClass(cls):
cls.build_dir.cleanup()
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.dir = Path(os.path.realpath(self.temp.name))
self.prefix = self.dir / "prefix"
self.prefix.mkdir()
self.store = self.prefix / ".droiddeck-descriptors"
for kind in ("card", "disk", "denied"):
(self.dir / kind / "game").mkdir(parents=True)
(self.dir / kind / "game" / "file").write_text("x")
def tearDown(self):
self.temp.cleanup()
def path(self, *parts):
return str(self.dir.joinpath(*parts))
def run_as(self, program, *args, prefix=True):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.preload, self.fake))
env.pop("WINEPREFIX", None)
if prefix:
env["WINEPREFIX"] = str(self.prefix)
result = subprocess.run([str(program), *args], env=env, capture_output=True, text=True, check=True)
return result.stdout.split()
def server(self, *args, **kwargs):
return self.run_as(self.wineserver, *args, **kwargs)
def test_a_descriptor_is_kept_where_the_volume_cannot_store_it(self):
file, folder = self.path("card", "game", "file"), self.path("card", "game")
self.assertEqual(["none", "ok", "ok"], self.server("get", file, "set", file, "one", "set", folder, "two"))
self.assertEqual(["=one", "3", "=two"], self.server("get", file, "size", file, "get", folder))
def test_a_descriptor_is_replaced_and_removed(self):
file = self.path("card", "game", "file")
self.assertEqual(["ok", "ok", "=longer"], self.server("set", file, "one", "set", file, "longer", "get", file))
self.assertEqual(["range", "ok", "none", "none"], self.server("short", file, "remove", file, "get", file, "remove", file))
def test_a_volume_that_stores_descriptors_is_left_alone(self):
file = self.path("disk", "game", "file")
self.assertEqual(["ok", "none", "none"], self.server("set", file, "one", "get", file, "remove", file))
self.assertFalse(self.store.exists())
def test_other_failures_keep_their_error(self):
file = self.path("denied", "game", "file")
self.assertEqual(["denied", "denied", "denied"], self.server("set", file, "one", "get", file, "remove", file))
self.assertFalse(self.store.exists())
def test_other_programs_and_other_attributes_are_unchanged(self):
file = self.path("card", "game", "file")
self.assertEqual(["unsupported", "unsupported", "unsupported"],
self.run_as(self.other, "set", file, "one", "get", file, "remove", file))
self.assertEqual(["ok", "unsupported"], self.server("set", file, "one", "other", file))
self.assertEqual(["unsupported"], self.run_as(self.other, "get", file))
def test_nothing_is_kept_without_a_prefix(self):
file = self.path("card", "game", "file")
self.assertEqual(["unsupported", "unsupported", "unsupported"],
self.server("set", file, "one", "get", file, "remove", file, prefix=False))
def test_a_deleted_file_loses_its_descriptor(self):
file, folder = self.path("card", "game", "file"), self.path("card", "game")
self.assertEqual(["ok", "ok", "ok"], self.server("set", file, "one", "set", folder, "two", "unlink", file))
Path(file).write_text("x")
self.assertEqual(["none", "ok", "ok"], self.server("get", file, "unlink", file, "rmdir", folder))
Path(folder).mkdir()
self.assertEqual(["none"], self.server("get", folder))
def test_a_removed_file_or_folder_loses_its_descriptor(self):
file, folder = self.path("card", "game", "file"), self.path("card", "game")
self.assertEqual(["ok", "ok", "ok", "ok"],
self.server("set", file, "one", "set", folder, "two", "remove-path", file, "remove-path", folder))
Path(folder).mkdir()
Path(file).write_text("x")
self.assertEqual(["none", "none"], self.server("get", folder, "get", file))
def test_a_file_deleted_through_a_link_loses_its_descriptor(self):
file = self.path("card", "game", "file")
os.symlink(self.path("card"), self.path("drive"))
self.assertEqual(["ok", "ok"], self.server("set", file, "one", "unlink", self.path("drive", "game", "file")))
Path(file).write_text("x")
self.assertEqual(["none"], self.server("get", file))
def test_a_descriptor_follows_a_rename(self):
file, moved = self.path("card", "game", "file"), self.path("card", "game", "moved")
self.assertEqual(["ok", "ok", "=one"], self.server("set", file, "one", "rename", file, moved, "get", moved))
Path(file).write_text("x")
self.assertEqual(["none", "ok", "none"], self.server("get", file, "rename", file, moved, "get", moved))
def test_descriptors_follow_a_renamed_folder(self):
file, folder, moved = self.path("card", "game", "file"), self.path("card", "game"), self.path("card", "moved")
self.assertEqual(["ok", "ok", "ok"], self.server("set", file, "one", "set", folder, "two", "rename", folder, moved))
self.assertEqual(["=two", "=one"], self.server("get", moved, "get", self.path("card", "moved", "file")))
Path(folder).mkdir()
(Path(folder) / "file").write_text("x")
self.assertEqual(["none", "none"], self.server("get", folder, "get", file))
def test_deletes_outside_the_store_cost_nothing_before_it_exists(self):
file = self.path("disk", "game", "file")
self.assertEqual(["ok"], self.server("unlink", file))
self.assertFalse(self.store.exists())
def test_a_name_too_long_to_keep_reports_no_support(self):
long_file = self.path("card", "game", "n" * 254)
Path(long_file).write_text("x")
self.assertEqual(["unsupported", "unsupported"], self.server("set", long_file, "one", "get", long_file))
if __name__ == "__main__":
unittest.main()
+38
View File
@@ -136,6 +136,30 @@ class CommandTest(Temp):
self.assertEqual(OPEN["command"](script, [], "x86 script")[0],
[OPEN["FEX"], "run", "--mode", "on", "--for", str(self.tmp), "--", "/bin/sh", script])
def test_a_store_games_exe_runs_through_its_launcher(self):
exe, launcher = str(self.tmp / "game.exe"), str(self.tmp / "launch.bat")
with mock.patch.dict(OPEN, {"store_launcher": lambda path: launcher if path == exe else None,
"exe_prefix": lambda path: ["--prefix", "4242", "--compatdata", "/c/4242"]}):
keep = ["--prefix", "4242", "--compatdata", "/c/4242"]
self.assertEqual(OPEN["command"](exe, [], "windows")[0], [OPEN["PROTON_RUN"]] + keep + [launcher])
self.assertEqual(OPEN["command"](exe, [], "windows", True)[0],
[OPEN["PROTON_RUN"], "--window"] + keep + [launcher])
self.assertEqual(OPEN["command"](exe, ["-x"], "windows")[0], [OPEN["PROTON_RUN"], exe, "-x"])
other = str(self.tmp / "other.exe")
self.assertEqual(OPEN["command"](other, [], "windows")[0], [OPEN["PROTON_RUN"], other])
def test_a_store_games_launcher_keeps_the_exes_prefix(self):
exe = self.tmp / "game.exe"
exe.write_text("x")
root = str(self.tmp / "steam")
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": root}), \
mock.patch.dict(OPEN, {"PROTON_RUN": str(BIN / "droiddeck-proton-run"),
"store_launcher": lambda path: str(self.tmp / "launch.bat")}):
command = OPEN["command"](str(exe), [], "windows")[0]
located = RUN["locate"](str(exe), root)
self.assertEqual(command[1:5], ["--prefix", located.appid, "--compatdata", located.compatdata])
self.assertEqual(str(RUN["own_id"](str(exe))), str(RUN["locate"](str(exe), root).appid))
def test_a_native_program_on_noexec_storage_runs_from_a_copy(self):
program = self.write("storage/tool", elf(183))
x86 = self.write("storage/game.x86_64", elf(62))
@@ -737,6 +761,20 @@ class ProtonRunTest(Temp):
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed))
self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists())
def test_a_launcher_run_keeps_the_resolved_compatdata_folder(self):
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
signed = self.root / "steamapps/compatdata/-1561598272"
signed.mkdir(parents=True)
other = self.tmp / "Library2/steamapps/compatdata/555"
other.mkdir(parents=True)
for compatdata, appid in ((signed, "2733369024"), (other, "555")):
with self.subTest(compatdata=str(compatdata)):
code, calls, dirs = self.run_main(["--prefix", appid, "--compatdata", str(compatdata), str(bat)])
self.assertIsNone(code)
self.assertEqual(calls[0][2]["STEAM_COMPAT_DATA_PATH"], str(compatdata))
code, calls, dirs = self.run_main(["--prefix", "555", str(bat)])
self.assertEqual(calls[0][2]["STEAM_COMPAT_DATA_PATH"], str(self.root / "steamapps/compatdata/555"))
def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self):
signed = self.root / "steamapps/compatdata/-1561598272"
signed.mkdir(parents=True)
+84
View File
@@ -0,0 +1,84 @@
import os
from pathlib import Path
import subprocess
import unittest
LINUXFS = Path(__file__).resolve().parents[1] / 'linuxfs'
DESKTOP = (LINUXFS / 'desktop/droiddeck-desktop').read_text()
SESSION = (LINUXFS / 'overlay/usr/local/bin/droiddeck-session').read_text()
BOTTOM_DESKTOP = (LINUXFS / 'overlay/usr/local/bin/droiddeck-bottom-desktop').read_text()
BOTTOM_SESSION = (
Path(__file__).resolve().parents[2]
/ 'app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt'
).read_text()
HELPER = '/usr/local/bin/droiddeck-pipewire'
class DesktopPipeWireTest(unittest.TestCase):
def run_lifecycle_block(self, start, end, bottom, start_status=0, probe_env=False):
block = DESKTOP[DESKTOP.index(start):DESKTOP.index(end, DESKTOP.index(start))]
block = block.replace(HELPER, 'pipewire')
script = '''
pipewire() {
if [ "$1" = env ]; then
printf 'export PW_ENV=set\\n'
else
printf 'call:%s\\n' "$1"
[ "$1" != start ] || return "$PW_START_STATUS"
fi
}
''' + block + ('echo "env:${PW_ENV:-unset}"\n' if probe_env else '')
environment = dict(os.environ, BL_BOTTOM_DESKTOP='1' if bottom else '0',
PW_START_STATUS=str(start_status))
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True,
text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
return result.stdout.splitlines()
def test_desktop_serves_pipewire_before_plasma_and_stops_it_after(self):
start = DESKTOP.index(HELPER + ' start')
env = DESKTOP.index(HELPER + ' env')
plasma = DESKTOP.index('dbus-run-session -- startplasma-wayland')
stop = DESKTOP.index(HELPER + ' stop')
self.assertLess(start, env)
self.assertLess(env, plasma)
self.assertLess(plasma, stop)
self.assertLess(stop, DESKTOP.index('droiddeck-steam-launch bigpicture'))
def test_steam_session_keeps_its_pipewire_startup(self):
self.assertEqual(1, SESSION.count(HELPER + ' start'))
self.assertIn('if [ "$mode" = steam ]; then\n if ' + HELPER + ' start', SESSION)
def test_bottom_desktop_starts_and_stops_its_pipewire_service(self):
self.assertIn('export BL_BOTTOM_DESKTOP=1', BOTTOM_DESKTOP)
self.assertLess(BOTTOM_DESKTOP.index('export BL_BOTTOM_DESKTOP=1'),
BOTTOM_DESKTOP.index('exec /usr/local/bin/droiddeck-desktop'))
self.assertIn('File(context.filesDir, ".wayland-rt-bottom")', BOTTOM_SESSION)
self.assertNotIn('if [ "${BL_BOTTOM_DESKTOP:-0}" != 1 ]; then', DESKTOP)
for bottom in (False, True):
self.assertEqual(['call:start'], self.run_lifecycle_block(
'if ' + HELPER + ' start',
'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom))
self.assertEqual(['call:stop'], self.run_lifecycle_block(
HELPER + ' stop',
'echo "== droiddeck-desktop: Plasma ended ($rc)"', bottom))
def test_successful_start_exports_the_client_environment(self):
for bottom in (False, True):
self.assertEqual(['call:start', 'env:set'], self.run_lifecycle_block(
'if ' + HELPER + ' start',
'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom, probe_env=True))
def test_failed_start_reports_it_and_leaves_the_environment_alone(self):
for bottom in (False, True):
self.assertEqual(
['call:start', '== pipewire: not running; screen capture has no picture', 'env:unset'],
self.run_lifecycle_block(
'if ' + HELPER + ' start',
'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom,
start_status=1, probe_env=True))
if __name__ == '__main__':
unittest.main()
+32 -2
View File
@@ -83,9 +83,25 @@ int inotify_add_watch(int fd, const char *path, uint32_t mask) {
errno = ENOSPC;
return -1;
}
if (getenv("NESTED") && (mask & IN_ONLYDIR)) {
static DIR *(*uncounted)(const char *);
if (!uncounted) uncounted = dlsym(RTLD_NEXT, "opendir");
mkdir(path, 0755);
DIR *d = uncounted("/proc/self/fd");
while (d && readdir(d)) {}
if (d) closedir(d);
}
return next(fd, path, mask);
}
int remove(const char *path) {
static int (*next)(const char *);
if (!next) next = dlsym(RTLD_NEXT, "remove");
if (!getenv("NESTED")) return next(path);
if (unlink(path) == 0) return 0;
return errno == EISDIR ? rmdir(path) : -1;
}
int statfs(const char *path, struct statfs *out) {
static int (*next)(const char *, struct statfs *);
if (!next) next = dlsym(RTLD_NEXT, "statfs");
@@ -337,9 +353,9 @@ class DirCachePreloadTest(unittest.TestCase):
environment.update(env or {})
return environment
def run_program(self, *args, program=None, env=None):
def run_program(self, *args, program=None, env=None, timeout=60):
result = subprocess.run([str(program or self.steam), *map(str, args)], env=self.environment(env),
capture_output=True, text=True, check=True, timeout=60)
capture_output=True, text=True, check=True, timeout=timeout)
return result.stdout.splitlines()
def run_paused(self, *args, between, env=None):
@@ -675,6 +691,20 @@ class DirCachePreloadTest(unittest.TestCase):
env={"BL_NO_DIR_CACHE": "1"})
self.assertEqual(["-1 2", "-1 2", "2"], out[1:])
def test_a_preload_below_calling_back_while_a_folder_is_watched_does_not_hang(self):
common = self.lib / "common/Game"
common.mkdir(parents=True)
(common / "game.exe").touch()
out = self.run_program("list", self.staging, "list", common, "list", common, "opens",
env={"NESTED": "1"}, timeout=20)
self.assertEqual(["a.bundle,b.bundle", "game.exe", "game.exe", "2"], out)
def test_a_preload_below_removing_through_unlink_does_not_hang(self):
s = self.staging
out = self.run_program("list", s, "remove", s / "a.bundle", "list", s, "raw", s, "opens",
env={"NESTED": "1"}, timeout=20)
self.assertEqual(["a.bundle,b.bundle", "b.bundle", "b.bundle", "1"], out)
def test_can_be_turned_off(self):
out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"BL_NO_DIR_CACHE": "1"})
self.assertEqual("2", out[-1])
+97
View File
@@ -0,0 +1,97 @@
import pathlib
import subprocess
import tempfile
import unittest
class DirectAudioWatchdogTest(unittest.TestCase):
def test_recovery_threshold_callback_race_and_forced_exit(self):
source = pathlib.Path('tools/directaudio/sink/module-directaudio-native-sink.c').read_text()
watchdog = source[source.index('static void watchdog('):source.index('static void close_output(')]
callback = source[source.index('static void record_callback('):
source.index('static aaudio_data_callback_result_t out_cb(')]
constants = '\n'.join(line for line in source.splitlines()
if line.startswith(('#define DA_FREEZE_GAP_NS ', '#define DA_CB_STALL_NS ',
'#define DA_HOST_RESTART_STALLS ')))
harness = r'''
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
typedef void AAudioStream;
struct userdata {
bool watchdog_on;
AAudioStream *aq;
uint64_t wd_last_tick_ns, last_cb_ns;
unsigned int cb_count, wd_last_cb;
uint64_t stall_state;
};
static uint64_t clock_ns = 10000000000ull;
static unsigned int reopens;
static bool callback_race;
static struct userdata *current;
static uint64_t now_ns(void) { return clock_ns; }
static void request_reopen(struct userdata *u, const char *why) { reopens++; }
#define pa_log(...) ((void)0)
CALLBACK
static bool exchange(uint64_t *value, uint64_t *expected, uint64_t next,
int weak, int success, int failure) {
if (callback_race) {
struct userdata *u = current;
record_callback(u);
__atomic_add_fetch(&u->cb_count, 1, __ATOMIC_SEQ_CST);
}
return __atomic_compare_exchange_n(value, expected, next, weak, success, failure);
}
#define __atomic_compare_exchange_n exchange
WATCHDOG
static void cleanup(void) { _exit(99); }
static void tick(struct userdata *u) {
clock_ns += 1000000000ull;
watchdog(u);
}
int main(int argc, char **argv) {
struct userdata state = {.watchdog_on = true, .aq = (void *)1};
struct userdata *u = &state;
current = u;
watchdog(u);
if (argc > 1 && strcmp(argv[1], "zero") == 0) {
callback_race = true;
tick(u);
assert(reopens == 0 && (uint32_t) u->stall_state == 0);
return 0;
}
tick(u);
assert(reopens == 1 && (uint32_t) u->stall_state == 1);
tick(u);
assert(reopens == 2 && (uint32_t) u->stall_state == 2);
if (argc > 1 && strcmp(argv[1], "exit") == 0) {
atexit(cleanup);
tick(u);
return 42;
}
callback_race = true;
tick(u);
assert(reopens == 2 && (uint32_t) u->stall_state == 0);
callback_race = false;
tick(u);
assert(reopens == 2 && (uint32_t) u->stall_state == 0);
tick(u);
assert(reopens == 3 && (uint32_t) u->stall_state == 1);
u->watchdog_on = false;
tick(u);
assert(reopens == 3 && (uint32_t) u->stall_state == 1);
return 0;
}
'''.replace('CALLBACK', callback).replace('WATCHDOG', watchdog)
with tempfile.TemporaryDirectory() as folder:
path = pathlib.Path(folder)
(path / 'watchdog.c').write_text(constants + '\n' + harness)
subprocess.run(['cc', '-std=c11', '-Werror', str(path / 'watchdog.c'),
'-o', str(path / 'watchdog')], check=True, capture_output=True)
subprocess.run([str(path / 'watchdog')], check=True, timeout=5)
subprocess.run([str(path / 'watchdog'), 'zero'], check=True, timeout=5)
result = subprocess.run([str(path / 'watchdog'), 'exit'], timeout=5)
self.assertEqual(1, result.returncode)
+171 -9
View File
@@ -175,17 +175,27 @@ class RuntimeExtractTest(EpicTestCase):
old = self.state / "app/0.1"
old.mkdir(parents=True)
def extract_app(image, dest):
os.makedirs(os.path.join(dest, "usr/bin"))
Path(dest, "AppRun").write_text("run")
Path(dest, "usr/bin/EpicGamesLauncher").write_text("bin")
layers = []
def extract_app(image, dest, desktop=()):
layers.append(list(desktop))
os.makedirs(os.path.join(dest, "usr/bin"))
os.makedirs(os.path.join(dest, "desktop/usr/lib/x86_64-linux-gnu"))
Path(dest, "usr/bin/EpicGamesLauncher").write_text("bin")
Path(dest, "desktop/usr/lib/x86_64-linux-gnu/libwebkit2gtk-4.1.so.0").write_text("webkit")
package = self.tmp / "libwebkit.deb"
package.write_bytes(b"x")
with mock.patch.dict(G, {"extract_app": extract_app, "fex_tool": lambda request=False: {"bin": "/fex", "server": "/s"}}), \
mock.patch("sys.stdout", new_callable=io.StringIO) as out:
image = self.tmp / "image"
image.write_bytes(b"x")
with self.assertRaises(G["Failure"]):
G["install"]({"app": str(image), "app-version": "0.95.2+g1", "runtime": str(tarball),
"runtime-version": "4.0.1", "gles": str(deb), "desktop": [str(self.tmp / "missing.deb")]})
code = G["install"]({"app": str(image), "app-version": "0.95.2+g1", "runtime": str(tarball),
"runtime-version": "4.0.1", "gles": str(deb)})
"runtime-version": "4.0.1", "gles": str(deb), "desktop": [str(package)]})
self.assertEqual([[str(package)]], layers)
self.assertEqual(0, code)
report = json.loads(out.getvalue())
self.assertTrue(report["installed"])
@@ -197,6 +207,147 @@ class RuntimeExtractTest(EpicTestCase):
self.assertTrue((self.state / "app/0.95.2+g1/.droiddeck-ready").is_file())
def deb(path, entries, compression="gz"):
data = io.BytesIO()
with tarfile.open(fileobj=data, mode="w:" + compression) as archive:
for entry in entries:
tar_add(archive, *entry[:1], **entry[1])
path.write_bytes(ar([("debian-binary", b"2.0\n"), ("control.tar.xz", b"c"), ("data.tar." + compression, data.getvalue())]))
return path
class LauncherDebTest(EpicTestCase):
def launcher(self, extra=()):
return deb(self.tmp / "EpicGamesLauncher-x86_64.deb", [
("./usr", {"kind": "dir"}),
("./usr/bin/EpicGamesLauncher", {"data": b"egl", "mode": 0o755}),
("./usr/lib/epic-games-launcher/libEOSSDK-Linux-Shipping.so", {"data": b"eos"}),
("./usr/share/icons/hicolor/256x256@2/apps/EpicGamesLauncher.png", {"data": b"png"}),
("./usr/share/applications/epic-games-launcher.desktop", {"data": b"[Desktop Entry]\n"}),
("./usr/bin/egl", {"link": "/usr/bin/EpicGamesLauncher"}),
("../escape", {"data": b"x"}),
*extra,
])
def webkit(self):
return deb(self.tmp / "libwebkit2gtk-4.1-0_amd64.deb", [
("./usr/lib/x86_64-linux-gnu/libwebkit2gtk-4.1.so.0.19.1", {"data": b"webkit"}),
("./usr/lib/x86_64-linux-gnu/libwebkit2gtk-4.1.so.0", {"link": "libwebkit2gtk-4.1.so.0.19.1"}),
("./usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/WebKitNetworkProcess", {"data": b"net", "mode": 0o755}),
("./usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/injected-bundle/libwebkit2gtkinjectedbundle.so", {"data": b"bundle"}),
("./usr/share/glib-2.0/schemas/org.gnome.GWeather4.gschema.xml", {"data": b"schema"}),
("./usr/share/doc/libwebkit2gtk-4.1-0/copyright", {"data": b"c"}),
("./usr/share/locale/fr/LC_MESSAGES/WebKitGTK-4.1.mo", {"data": b"fr"}),
], "xz")
def test_the_launcher_and_its_desktop_layer_come_out_of_debs(self):
dest = self.state / "app/0.113.0+g1"
G["extract_app"](str(self.launcher()), str(dest), [str(self.webkit())])
self.assertEqual(b"egl", (dest / "usr/bin/EpicGamesLauncher").read_bytes())
self.assertTrue(os.access(dest / "usr/bin/EpicGamesLauncher", os.X_OK))
self.assertEqual(b"eos", (dest / "usr/lib/epic-games-launcher/libEOSSDK-Linux-Shipping.so").read_bytes())
self.assertEqual("EpicGamesLauncher", os.readlink(dest / "usr/bin/egl"))
self.assertEqual(b"png", (dest / "epic-games-launcher.png").read_bytes())
libs = dest / "desktop/usr/lib/x86_64-linux-gnu"
self.assertEqual(b"webkit", (libs / "libwebkit2gtk-4.1.so.0").read_bytes())
self.assertEqual(b"net", (libs / "webkit2gtk-4.1/WebKitNetworkProcess").read_bytes())
self.assertEqual(b"schema", (dest / "desktop/usr/share/glib-2.0/schemas/org.gnome.GWeather4.gschema.xml").read_bytes())
self.assertFalse((dest / "desktop/usr/share/doc").exists())
self.assertFalse((self.state / "app/escape").exists())
self.assertFalse((self.state / "app/0.113.0+g1.staging").exists())
self.assertTrue(G["app_complete"](str(dest)))
self.assertEqual(str(dest / "usr/bin/EpicGamesLauncher"), G["app_command"](str(dest)))
self.assertEqual(str(libs), G["desktop_libs"](str(dest)))
def test_archive_symlinks_cannot_redirect_the_desktop_layer_or_icon(self):
outside = self.tmp / "outside"
outside.mkdir()
dest = self.state / "app/0.113.0+g1"
escape = os.path.relpath(outside, Path(str(dest) + ".staging"))
launcher = self.launcher([("./desktop", {"link": escape}),
("./epic-games-launcher.png", {"link": escape + "/target"})])
with self.assertRaises(G["Failure"]) as caught:
G["extract_app"](str(launcher), str(dest), [str(self.webkit())])
self.assertEqual("app-extract", str(caught.exception))
self.assertFalse((outside / "usr").exists())
self.assertFalse((outside / "target").exists())
icon_dest = self.state / "app/0.113.0+g2"
icon_escape = os.path.relpath(outside / "target", Path(str(icon_dest) + ".staging"))
G["extract_app"](str(self.launcher([("./epic-games-launcher.png", {"link": icon_escape})])),
str(icon_dest), [str(self.webkit())])
self.assertEqual(b"png", (icon_dest / "epic-games-launcher.png").read_bytes())
self.assertFalse((outside / "target").exists())
def test_a_launcher_without_its_desktop_layer_is_refused(self):
dest = self.state / "app/0.113.0+g1"
with self.assertRaises(G["Failure"]) as caught:
G["extract_app"](str(self.launcher()), str(dest))
self.assertEqual("app-extract", str(caught.exception))
self.assertFalse(dest.exists())
self.assertFalse(Path(str(dest) + ".staging").exists())
def test_anything_but_a_deb_is_refused_and_leaves_nothing_behind(self):
image = self.tmp / "EpicGamesLauncher-x86_64.AppImage"
image.write_bytes(b"\x7fELF\x02\x01\x01\x00AI\x02" + bytes(64))
dest = self.state / "app/0.95.2+g1"
with self.assertRaises(G["Failure"]) as caught:
G["extract_app"](str(image), str(dest), [str(self.webkit())])
self.assertEqual("app-format", str(caught.exception))
plain = self.tmp / "plain.deb"
plain.write_bytes(ar([("data.tar.gz", b"x")]))
with self.assertRaises(G["Failure"]) as caught:
G["extract_app"](str(self.launcher()), str(dest), [str(plain)])
self.assertEqual("desktop-format", str(caught.exception))
self.assertFalse(dest.exists())
self.assertFalse(Path(str(dest) + ".staging").exists())
def test_an_installed_appimage_launcher_still_runs_through_apprun(self):
app = self.state / "app/0.95.2+g1"
(app / "usr/bin").mkdir(parents=True)
(app / "AppRun").write_text("run")
(app / "usr/bin/EpicGamesLauncher").write_text("bin")
self.assertTrue(G["app_complete"](str(app)))
self.assertEqual(str(app / "AppRun"), G["app_command"](str(app)))
self.assertIsNone(G["desktop_libs"](str(app)))
(app / "usr/bin/EpicGamesLauncher").unlink()
self.assertFalse(G["app_complete"](str(app)))
def test_the_webkit_helpers_are_linked_into_the_runtime(self):
dest = self.state / "app/0.113.0+g1"
G["extract_app"](str(self.launcher()), str(dest), [str(self.webkit())])
files = self.state / "runtime/4.0.1/files"
(files / "lib/x86_64-linux-gnu").mkdir(parents=True)
link = files / "lib/x86_64-linux-gnu/webkit2gtk-4.1"
G["link_webkit"](str(files), G["desktop_libs"](str(dest)))
self.assertFalse(os.path.isabs(os.readlink(link)))
self.assertEqual(b"net", (link / "WebKitNetworkProcess").read_bytes())
G["link_webkit"](str(files), G["desktop_libs"](str(dest)))
self.assertEqual(b"net", (link / "WebKitNetworkProcess").read_bytes())
G["link_webkit"](str(files), None)
self.assertFalse(os.path.lexists(link))
link.mkdir()
(link / "own").write_text("x")
G["link_webkit"](str(files), G["desktop_libs"](str(dest)))
self.assertTrue((link / "own").is_file())
self.assertTrue((dest / "desktop/usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/WebKitNetworkProcess").is_file())
def test_only_the_deb_launcher_gets_the_desktop_libraries(self):
with mock.patch.dict(G, {"fex_environment": lambda fex, files, base: {}}):
plain = G["client_environment"]({"LD_LIBRARY_PATH": "/host"}, None, None, ":0", "bus", "broker")
layered = G["client_environment"]({}, None, None, ":0", "bus", "broker", libs="/app/desktop/usr/lib/x86_64-linux-gnu")
self.assertNotIn("LD_LIBRARY_PATH", plain)
self.assertEqual("/app/desktop/usr/lib/x86_64-linux-gnu", layered["LD_LIBRARY_PATH"])
self.assertEqual("/app/desktop/usr/share:/usr/local/share:/usr/share", layered["XDG_DATA_DIRS"])
self.assertEqual("/app/desktop/usr/share/glib-2.0/schemas", layered["GSETTINGS_SCHEMA_DIR"])
def test_every_desktop_package_reaches_the_install(self):
options, rest = G["parse_options"](["--app", "a.deb", "--desktop", "one.deb", "--desktop", "two.deb", "x"], lists=("desktop",))
self.assertEqual({"app": "a.deb", "desktop": ["one.deb", "two.deb"]}, options)
self.assertEqual(["x"], rest)
self.assertEqual({"desktop": "two.deb"}, G["parse_options"](["--desktop", "one.deb", "--desktop", "two.deb"])[0])
class ArgumentsTest(EpicTestCase):
def test_client_arguments_win_and_paths_become_windows_paths(self):
ovt = self.tmp / "ovt"
@@ -736,17 +887,28 @@ class BrokerTest(EpicTestCase):
folder.mkdir()
(folder / ".droiddeck-store.json").write_text(json.dumps({"store": "epic", "id": "Fig", "args": ["-x"]}))
(folder / ".droiddeck-launch.bat").write_text('if exist "%~dp0.droiddeck-epic-args" goto client\r\n')
debug_dir = self.tmp / "session"
debug_dir.mkdir()
config = self.home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "gameDebugLogs": True}))
calls = []
def popen(command, env=None, cwd=None, start_new_session=False):
calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), start_new_session))
calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), env.get("BL_DEBUG_DIR"),
env.get("PROTON_LOG"), env.get("WINEDEBUG"), start_new_session))
return mock.Mock(wait=mock.Mock(return_value=7))
running = []
with mock.patch.object(subprocess, "Popen", popen):
code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]}, {"PATH": "/usr/bin"}, running)
with mock.patch.dict(os.environ, {"HOME": str(self.home), "BL_DEBUG_DIR": str(debug_dir),
"PROTON_LOG": "0", "WINEDEBUG": "-all"}), \
mock.patch.object(subprocess, "Popen", popen):
code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]},
{"PATH": "/usr/bin", "BL_DEBUG_DIR": str(debug_dir)}, running)
self.assertEqual(7, code)
self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", True), calls[0])
self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", str(debug_dir), "1",
mock.ANY, True), calls[0])
self.assertIn("+seh", calls[0][4])
self.assertEqual([], running)
self.assertEqual(b"-epicapp=Fig -x\r\n", (folder / ".droiddeck-epic-args").read_bytes())
+67
View File
@@ -5,6 +5,7 @@ import json
import os
import runpy
import shutil
import stat
import struct
import subprocess
import tempfile
@@ -450,6 +451,72 @@ class PrepareTest(FexTestCase):
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"])
def test_the_built_x86_runtime_holds_nothing_that_leaves_it(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
os.chmod(sniper / "files/share/ca", 0o750)
self.quiet(FEX["prepare"])
root = (self.home / ".local/share/droiddeck-fex/rootfs").resolve()
self.assertEqual(stat.S_IMODE(os.stat(root / "share/ca").st_mode), 0o750)
entries = 0
for directory, dirs, files in os.walk(root):
for name in dirs + files:
path = Path(directory) / name
entries += 1
if path.is_symlink():
self.assertFalse(os.path.isabs(os.readlink(path)), path)
self.assertTrue(path.resolve().is_relative_to(root), path)
self.assertGreater(entries, 10)
self.assertEqual((root / "bin/[").read_bytes(), b"blob")
self.assertEqual((root / "share/ca/real.crt").read_bytes(), b"cert")
self.assertFalse(os.path.lexists(root / "ab"))
def test_guest_writes_do_not_mutate_runtime_blob_files(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
self.quiet(FEX["prepare"])
root = self.home / ".local/share/droiddeck-fex/rootfs"
marker = root / ".droiddeck-fex"
stamp = marker.read_text()
marker.write_text("3\n" + stamp.partition("\n")[2])
source = sniper / "files/ab/cdef-1.bin"
guest = root / "bin/["
guest.unlink()
os.link(source, guest)
self.assertEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertNotEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
guest.write_bytes(b"guest mutation")
self.assertEqual(source.read_bytes(), b"blob")
self.assertEqual(guest.read_bytes(), b"guest mutation")
def test_a_rebuilt_x86_runtime_refreshes_the_steam_client_links_and_drops_read_only_trees(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
base = sniper / "files"
(base / str(self.home).lstrip("/") / ".steam").mkdir(parents=True)
os.symlink(self.steam / "linuxarm64", base / str(self.home).lstrip("/") / ".steam/sdk64")
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
os.chmod(base / "share/ca", 0o500)
self.addCleanup(os.chmod, base / "share/ca", 0o700)
self.quiet(FEX["prepare"])
rootfs = self.home / ".local/share/droiddeck-fex/rootfs"
os.chmod(rootfs / "share/ca", 0o000)
self.write(self.steam / "linux64/steamclient.so", elf(62))
self.write(self.steam / "linux32/steamclient.so", elf(3))
os.utime(self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390/usr-mtree.txt.gz", ns=(1, 1))
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
guest = rootfs / str(self.home).lstrip("/") / ".steam"
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(sorted(os.listdir(rootfs.parent)), ["config", "lock", "rootfs", "status.json"])
def test_a_runtime_that_is_not_newer_is_left_out(self):
self.fex_tool()
sniper = self.runtime()
+29 -1
View File
@@ -55,6 +55,19 @@ FAKE_ADB = textwrap.dedent('''\
print("Result: Bundle[{json=" + json.dumps(answers) + "}]")
elif args[:3] == ["shell", "dumpsys", "display"]:
print(config.get("dumpsys_display", ""))
elif args[:3] == ["shell", "dumpsys", "input"]:
print(config.get("dumpsys_input", ""))
elif args[:3] == ["shell", "uinput", "-"]:
entry["stdin"] = sys.stdin.read()
if "uinput_stdout" in config:
print(config["uinput_stdout"])
else:
for line in entry["stdin"].splitlines():
command = json.loads(line)
if command["command"] == "sync":
print(json.dumps({"reason": "sync", "id": command["id"], "syncToken": command["syncToken"]}))
elif args[:1] == ["shell"] and len(args) == 2 and "command -v uinput" in args[1]:
print(config.get("uinput_probe", ""))
elif args[:3] == ["shell", "dumpsys", "power"]:
print(" mWakefulness=Awake")
elif args[:3] == ["shell", "dumpsys", "SurfaceFlinger"] and "-dump" in args:
@@ -303,7 +316,7 @@ class DroiddeckctlTest(FakeAdbTest):
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
self.assertEqual(7, code)
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
self.assertIn("Setup > Diagnostics > Debugging tools", out["error"]["message"])
self.assertIn("Setup > Developer > Debugging tools", out["error"]["message"])
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
def test_override_checks_names_before_pushing_any_file(self):
@@ -332,6 +345,21 @@ class DroiddeckctlTest(FakeAdbTest):
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p", "-d", "222"], shot["args"])
def test_screenshot_with_two_screens_takes_the_main_display(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"))
self.assertEqual(0, code)
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p", "-d", "111"], shot["args"])
def test_screenshot_with_one_screen_names_no_display(self):
one = DUMPSYS_DISPLAY.split(" Display 4:")[0]
self.configure({}, dumpsys_display=one)
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"))
self.assertEqual(0, code)
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p"], shot["args"])
def test_displays(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("displays")
+255
View File
@@ -0,0 +1,255 @@
import json
import unittest
import unittest.mock
from test_droiddeckctl import FakeAdbTest, ctl
def samples(*argv):
return ctl.pen_samples(ctl.build_parser().parse_args(["input", "pen", *argv]))
def phases(gesture):
return [s["phase"] for s in gesture]
def dumpsys_input(rotation=0, size=(1140, 2616), active=1, frame=None):
other = ("Viewport INTERNAL: displayId=2, uniqueId=local:147, port=147, orientation=0, "
"logicalFrame=[0, 0, 2248, 2480], physicalFrame=[0, 0, 2248, 2480], deviceSize=[2248, 2480], isActive=[0]")
shown = (f"Viewport INTERNAL: displayId=0, uniqueId=local:148, port=148, orientation={rotation}, "
f"logicalFrame=[0, 0, {size[0]}, {size[1]}], physicalFrame=[{', '.join(map(str, frame or (0, 0, *size)))}], "
f"deviceSize=[{size[0]}, {size[1]}], isActive=[{active}]")
reader = (f"Input Reader State (Nums of device: 11):\n Device 6: touchpanel_pen\n {other}\n"
f" Configuration:\n Viewports:\n {other}\n {shown}\n OplusInputReader mMergeEnable = 0\n")
return reader + "\nINPUT MANAGER (dumpsys input)\n\n" + reader
def frames(commands):
found, frame = [], {}
for command in commands:
if command["command"] == "inject":
events = command["events"]
for code, value in zip(events[1::3], events[2::3]):
if code == "SYN_REPORT":
found.append(frame)
frame = {}
else:
frame[code] = value
return found
class PenSamplesTest(unittest.TestCase):
def test_a_tap_hovers_lands_lifts_and_leaves(self):
gesture = samples("tap", "0.5", "0.5", "--hold", "20")
self.assertEqual(["hover"] * 10 + ["down", "move", "up"] + ["hover"] * 10 + ["out"], phases(gesture))
times = [s["t"] for s in gesture]
self.assertEqual(sorted(times), times)
self.assertEqual([0, 8, 80, 100, 180, 180], [times[0], times[1], times[10], times[12], times[-2], times[-1]])
self.assertEqual({0.5}, {s["pressure"] for s in gesture[10:13]})
self.assertEqual({0}, {s["pressure"] for s in gesture[:10] + gesture[13:]})
self.assertEqual({(0.5, 0.5, None)}, {(s["x"], s["y"], s["button"]) for s in gesture})
def test_without_hover_the_pen_lands_and_leaves_at_once(self):
gesture = samples("tap", "0.5", "0.5", "--hover-ms", "0", "--hold", "0")
self.assertEqual([("down", 0), ("up", 0), ("out", 0)], [(s["phase"], s["t"]) for s in gesture])
def test_a_stroke_ramps_pressure_and_tilt(self):
gesture = samples("stroke", "0.25", "0.5", "0.75", "1", "--duration", "100", "--hover-ms", "20", "--rate", "100",
"--pressure", "0.25:0.75", "--tilt-x=-30:30", "--tilt-y", "10")
self.assertEqual(["hover", "hover", "down"] + ["move"] * 9 + ["up", "hover", "hover", "out"], phases(gesture))
contact = gesture[2:13]
self.assertEqual([(20, 0.25, 0.5, 0.25), (70, 0.5, 0.75, 0.5), (120, 0.75, 1, 0.75)],
[(s["t"], s["x"], s["y"], s["pressure"]) for s in (contact[0], contact[5], contact[-1])])
self.assertEqual((-30, 30), (gesture[0]["tilt_x"], gesture[-1]["tilt_x"]))
self.assertAlmostEqual(-30 + 60 * 20 / 140, contact[0]["tilt_x"])
self.assertEqual({10}, {s["tilt_y"] for s in gesture})
def test_hover_glides_to_the_target(self):
gesture = samples("hover", "0.25", "0.25", "--to", "0.75", "0.5", "--duration", "300", "--distance", "5")
self.assertEqual(["hover"] * 37 + ["out"], phases(gesture))
self.assertEqual([(0.25, 0.25), (0.75, 0.5), (0.75, 0.5)],
[(s["x"], s["y"]) for s in (gesture[0], gesture[-2], gesture[-1])])
self.assertEqual((300, {5}), (gesture[-1]["t"], {s["distance"] for s in gesture}))
def test_a_side_button_is_held_while_hovering(self):
gesture = samples("button", "secondary", "0.5", "0.5", "--hold", "40")
self.assertEqual([80, 88, 96, 104, 112], [s["t"] for s in gesture if s["button"] == "secondary"])
self.assertEqual(["hover"] * (len(gesture) - 1) + ["out"], phases(gesture))
self.assertEqual((200, None), (gesture[-1]["t"], gesture[-2]["button"]))
class PenUinputTest(FakeAdbTest):
def setUp(self):
super().setUp()
self.configure({}, dumpsys_input=dumpsys_input())
def pen(self, *argv):
return self.run_ctl("input", "pen", *argv)
def script(self):
[call] = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]]
return [json.loads(line) for line in call["stdin"].splitlines()]
def test_a_stroke_draws_with_a_virtual_direct_pen(self):
code, out = self.pen("stroke", "0.25", "0.5", "0.75", "0.5", "--duration", "100", "--rate", "100",
"--hover-ms", "20", "--pressure", "0.2:1")
self.assertEqual(0, code)
self.assertEqual({"ok": True, "command": "input", "type": "pen", "samples": 16, "deviceSerial": "fake-1",
"viewport": {"display": 0, "rotation": 0, "size": [1140, 2616]}},
{k: v for k, v in out.items() if k != "ms"})
self.assertFalse(self.calls("input"))
commands = self.script()
register = commands[0]
bits = {c["type"]: c["data"] for c in register["configuration"]}
self.assertEqual(("register", "virtual", ["EV_KEY", "EV_ABS"], ["INPUT_PROP_DIRECT"]),
(register["command"], register["bus"], bits["UI_SET_EVBIT"], bits["UI_SET_PROPBIT"]))
self.assertEqual({"BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"},
set(bits["UI_SET_KEYBIT"]))
ranges = {a["code"]: (a["info"]["minimum"], a["info"]["maximum"]) for a in register["abs_info"]}
self.assertEqual({"ABS_X": (0, 1140 * 16 - 1), "ABS_Y": (0, 2616 * 16 - 1), "ABS_PRESSURE": (0, 4095),
"ABS_DISTANCE": (0, 255), "ABS_TILT_X": (-90, 90), "ABS_TILT_Y": (-90, 90)}, ranges)
self.assertEqual(set(bits["UI_SET_ABSBIT"]), set(ranges))
self.assertEqual({"id": 1, "command": "delay", "duration": 1000}, commands[1])
self.assertNotIn("updateTimeBase", [c["command"] for c in commands])
self.assertEqual(140, sum(c["duration"] for c in commands[2:-2] if c["command"] == "delay"))
self.assertEqual([{"id": 1, "command": "delay", "duration": 300},
{"id": 1, "command": "sync", "syncToken": ctl.UINPUT_SYNC}], commands[-2:])
drawn = frames(commands)
self.assertEqual({"BTN_TOOL_PEN": 1, "ABS_X": 4560, "ABS_Y": 20928, "ABS_PRESSURE": 0, "ABS_DISTANCE": 0,
"ABS_TILT_X": 0, "ABS_TILT_Y": 0}, drawn[0])
self.assertEqual([{"ABS_X": 4561}, {"BTN_TOUCH": 1, "ABS_X": 4560, "ABS_PRESSURE": 819}], drawn[1:3])
self.assertEqual([{"ABS_X": 13680, "ABS_PRESSURE": 4095}, {"BTN_TOUCH": 0, "ABS_PRESSURE": 0}, {"ABS_X": 13681},
{"ABS_X": 13680}, {"BTN_TOOL_PEN": 0}], drawn[-5:])
pressures = [f["ABS_PRESSURE"] for f in drawn[2:-4]]
self.assertEqual(sorted(pressures), pressures)
def test_positions_and_tilt_follow_the_rotation(self):
cases = {0: ([1000, 2000], 4000, 24000, 30, -10), 1: ([2000, 1000], 3999, 8000, 10, 30),
2: ([1000, 2000], 11999, 7999, -30, 10), 3: ([2000, 1000], 12000, 23999, -10, -30)}
for rotation, (size, x, y, tilt_x, tilt_y) in cases.items():
with self.subTest(rotation=rotation):
self.configure({}, dumpsys_input=dumpsys_input(rotation, size))
self.log.unlink(missing_ok=True)
code, out = self.pen("tap", "0.25", "0.75", "--tilt-x", "30", "--tilt-y=-10")
self.assertEqual((0, rotation), (code, out["viewport"]["rotation"]))
commands = self.script()
self.assertEqual([15999, 31999], [a["info"]["maximum"] for a in commands[0]["abs_info"][:2]])
first = frames(commands)[0]
self.assertEqual((x, y, tilt_x, tilt_y),
tuple(first[key] for key in ("ABS_X", "ABS_Y", "ABS_TILT_X", "ABS_TILT_Y")))
def test_the_mapping_inverts_aosps_input_coordinates_example(self):
self.assertEqual((0, 2, 0, 0), ctl.uinput_point(2 / 4, 2 / 3, 0, 0, 1, 3, 4, [0, 0, 4, 3]))
self.assertEqual((2, 3, 0, 0), ctl.uinput_point(1, 1, 0, 0, 0, 3, 4, [0, 0, 3, 4]))
self.assertEqual((0, 0, 0, 0), ctl.uinput_point(1, 1, 0, 0, 2, 3, 4, [0, 0, 3, 4]))
def test_positions_map_onto_the_physical_frame(self):
cases = {0: ((1000, 2000), (100, 250, 900, 1750), ("1", "0.05"), (14399, 5200)),
1: ((2000, 1000), (250, 100, 1750, 900), ("0.05", "1"), (1600, 5200))}
for rotation, (size, frame, position, first) in cases.items():
with self.subTest(rotation=rotation):
self.configure({}, dumpsys_input=dumpsys_input(rotation, size, frame=frame))
self.log.unlink(missing_ok=True)
self.assertEqual(0, self.pen("tap", *position)[0])
drawn = frames(self.script())
self.assertEqual(first, (drawn[0]["ABS_X"], drawn[0]["ABS_Y"]))
self.assertTrue(all(1600 <= f.get("ABS_X", 1600) < 14400 for f in drawn))
def test_eraser_and_buttons_use_the_stylus_keys(self):
for button, side in (("primary", "BTN_STYLUS"), ("secondary", "BTN_STYLUS2")):
with self.subTest(button=button):
self.log.unlink(missing_ok=True)
code, _ = self.pen("button", button, "0.5", "0.5", "--hold", "40", "--tool", "eraser", "--distance", "12")
self.assertEqual(0, code)
drawn = frames(self.script())
keys = [(key, value) for frame in drawn for key, value in frame.items() if key.startswith("BTN_")]
self.assertEqual([("BTN_TOOL_RUBBER", 1), (side, 1), (side, 0), ("BTN_TOOL_RUBBER", 0)], keys)
self.assertEqual(12, drawn[0]["ABS_DISTANCE"])
def test_a_still_pen_keeps_reporting_at_the_rate(self):
code, out = self.pen("hover", "1", "0.5", "--duration", "100", "--rate", "50")
self.assertEqual(0, code)
commands = self.script()
drawn = frames(commands)
self.assertEqual(out["samples"], len(drawn))
self.assertEqual([18239, 18238, 18239, 18238, 18239, 18238], [f["ABS_X"] for f in drawn[:-1]])
self.assertEqual([20, 20, 20, 20, 20, 300], [c["duration"] for c in commands[2:] if c["command"] == "delay"])
def test_a_contact_without_pressure_still_touches(self):
code, _ = self.pen("tap", "0.5", "0.5", "--pressure", "0", "--hover-ms", "0", "--hold", "0", "--distance", "5")
self.assertEqual(0, code)
drawn = frames(self.script())
self.assertEqual((1, 1, 1, 0),
tuple(drawn[0][key] for key in ("BTN_TOOL_PEN", "BTN_TOUCH", "ABS_PRESSURE", "ABS_DISTANCE")))
self.assertEqual([{"BTN_TOUCH": 0, "ABS_PRESSURE": 0, "ABS_DISTANCE": 5}, {"BTN_TOOL_PEN": 0}], drawn[1:])
def test_bad_values_are_refused(self):
cases = [
(("tap", "1.5", "0.5"), "Positions are fractions of the screen"),
(("hover", "0.5", "0.5", "--to", "nan", "0.5"), "Positions are fractions of the screen"),
(("stroke", "0", "0", "1", "1", "--pressure", "0.5:1.5"), "--pressure must be 0..1"),
(("tap", "0.5", "0.5", "--tilt-x=-91"), "--tilt-x and --tilt-y must be -90..90"),
(("tap", "0.5", "0.5", "--tilt-y", "120"), "--tilt-x and --tilt-y must be -90..90"),
(("hover", "0.5", "0.5", "--distance", "256"), "--distance must be 0..255"),
(("tap", "0.5", "0.5", "--rate", "1e9"), "--rate must be 1..1000 Hz"),
(("button", "primary", "0.5", "0.5", "--hold", "-5"), "--hold must not be negative"),
(("tap", "0.5", "0.5", "--hover-ms", "-1"), "--hover-ms must not be negative"),
(("stroke", "0", "0", "1", "1", "--duration", "40000"), "lasts 40160 ms, more than 30000"),
(("hover", "0.5", "0.5", "--duration", "1000000000"), "more than 30000"),
]
with unittest.mock.patch.object(ctl, "pen_times", side_effect=AssertionError):
for argv, message in cases:
with self.subTest(message=message):
code, out = self.pen(*argv)
self.assertEqual((2, "INVALID_INPUT"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse(self.calls())
self.assertEqual(30_000, samples("tap", "1", "1", "--hover-ms", "14970")[-1]["t"])
def test_a_shell_without_uinput_is_unavailable(self):
for probe, message in (("no-uinput", "no `uinput` command"), ("no-dev-uinput", "cannot write /dev/uinput")):
with self.subTest(probe=probe):
self.configure({}, dumpsys_input=dumpsys_input(), uinput_probe=probe)
code, out = self.pen("tap", "0.5", "0.5")
self.assertEqual((3, "UINPUT_UNAVAILABLE"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
def test_a_missing_or_dark_display_is_refused(self):
for dump, message in (("Input Reader State (Nums of device: 0):\n", "no internal display viewport"),
(dumpsys_input(active=0), "Display 0 is off")):
with self.subTest(message=message):
self.configure({}, dumpsys_input=dump)
code, out = self.pen("tap", "0.5", "0.5")
self.assertEqual((3, "NO_VIEWPORT"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
def test_uinput_that_stops_early_fails(self):
self.configure({}, dumpsys_input=dumpsys_input(), uinput_stdout="")
code, out = self.pen("tap", "0.5", "0.5")
self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"]))
self.assertIn("adb logcat -s UINPUT", out["error"]["message"])
def test_the_viewport_android_maps_touchscreens_to(self):
self.assertEqual({"display": 0, "rotation": 0, "size": [1140, 2616], "frame": [0, 0, 1140, 2616], "active": True},
ctl.input_viewport(dumpsys_input()))
device = " Device 7: touchpanel\n Viewport INTERNAL: displayId=0, orientation=0, deviceSize=[1140, 2616]\n"
self.assertEqual(1, ctl.input_viewport(device + dumpsys_input(1, (2480, 2248)))["rotation"])
newest = (" Viewports:\n Viewport INTERNAL: displayId=3, uniqueId=local:1, port=<none>, orientation=3, "
"densityDpi=420 xDpi=409.432007, yDpi=411.891998, logicalFrame=[0, 0, 2400, 1080], "
"physicalFrame=[0, 0, 2400, 1080], deviceSize=[2400, 1080], isActive=[1]\n"
" Viewport INTERNAL: displayId=5, uniqueId=local:3, port=2, orientation=0, "
"deviceSize=[1080, 2400], isActive=[1]\n"
" Viewport EXTERNAL: displayId=0, uniqueId=local:2, port=1, orientation=0, "
"deviceSize=[1920, 1080], isActive=[1]\n")
self.assertEqual({"display": 3, "rotation": 3, "size": [2400, 1080], "frame": [0, 0, 2400, 1080], "active": True},
ctl.input_viewport(newest))
older = ("Viewport INTERNAL: displayId=0, orientation=2, logicalFrame=[0, 0, 720, 1280], "
"physicalFrame=[-3, 0, 717, 1280], deviceSize=[720, 1280]")
self.assertEqual({"display": 0, "rotation": 2, "size": [720, 1280], "frame": [-3, 0, 717, 1280], "active": True},
ctl.input_viewport(older))
if __name__ == "__main__":
unittest.main()
+28 -18
View File
@@ -1069,26 +1069,36 @@ class LauncherTest(SyncTestCase):
dist = self.dist_of(pack["id"], tool)
game_env = runpy.run_path(str(BIN / "droiddeck-game-env"))
command = [str(tool / "proton"), "waitforexitandrun", "game.exe"]
env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1")
calls = []
cases = (
({}, {"WINEDLLOVERRIDES": "tabtip.exe=d"}),
({"WINEDLLOVERRIDES": "dxgi=n"}, {"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=d"}),
({"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=b"}, {"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=b"}),
({"SteamDeck": "1"}, {"SteamDeck": "1"}),
)
for inherited, expected in cases:
with self.subTest(inherited=inherited):
env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1", **inherited)
calls = []
def execvpe(path, args, environment):
calls.append((path, list(args), dict(environment)))
if len(calls) == 1:
raise PermissionError("denied")
raise SystemExit(0)
def execvpe(path, args, environment):
calls.append((path, list(args), dict(environment)))
if len(calls) == 1:
raise PermissionError("denied")
raise SystemExit(0)
with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(sys, "argv", ["droiddeck-game-env"] + command), \
mock.patch("os.execvpe", execvpe), contextlib.redirect_stderr(io.StringIO()) as said:
with self.assertRaises(SystemExit):
game_env["main"]()
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
(str(tool / "proton"), command)])
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1"))
self.assertIn("could not start (", said.getvalue())
with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(sys, "argv", ["droiddeck-game-env"] + command), \
mock.patch("os.execvpe", execvpe), contextlib.redirect_stderr(io.StringIO()) as said:
with self.assertRaises(SystemExit):
game_env["main"]()
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
(str(tool / "proton"), command)])
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1", **expected))
self.assertEqual(calls[0][2].get("WINEDLLOVERRIDES"), expected.get("WINEDLLOVERRIDES"))
self.assertEqual(calls[0][2].get("SteamDeck"), expected.get("SteamDeck"))
self.assertIn("could not start (", said.getvalue())
def test_generated_launchers_run_the_dist_proton(self):
root = self.store()
+189
View File
@@ -1,3 +1,5 @@
import fcntl
import mmap
import os
from pathlib import Path
import shutil
@@ -5,6 +7,8 @@ import struct
import subprocess
import sys
import tempfile
import threading
import time
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
@@ -14,6 +18,14 @@ HEADER = 64
EVENT = 24
CAPACITY = 4096
DESCRIPTION = 1824
RING_SIZE = HEADER + CAPACITY * EVENT
DECK_IMU = 64
TRITON_BLOCK = 256
TRITON_MAGIC = 0x4E525454
TOUCH_MAGIC = 0x31484354
TOUCH_RING_SIZE = 256
PAD_TYPE_DECK = 0
PAD_TYPE_STEAM = 1
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
@@ -215,6 +227,72 @@ int main(int argc, char **argv)
return 0;
}
"""
HIDRAW_PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <linux/hidraw.h>
#include <poll.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd = open(argv[1], O_RDONLY | O_NONBLOCK);
if (fd < 0) {
puts(errno == ENOENT ? "refused" : "failed");
return 0;
}
struct hidraw_devinfo info;
if (ioctl(fd, HIDIOCGRAWINFO, &info) < 0)
return 1;
struct pollfd ready = {fd, POLLIN, 0};
unsigned char report[64];
if (poll(&ready, 1, 2000) != 1 || read(fd, report, sizeof(report)) <= 0)
return 2;
printf("%04hx:%04hx report %02x\n", info.vendor, info.product, report[0]);
return 0;
}
"""
FEATURE_PROBE = r"""
#include <fcntl.h>
#include <linux/hidraw.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main(int argc, char **argv)
{
unsigned char id = (unsigned char)strtoul(argv[1], NULL, 0);
int fd = open("/dev/hidraw18", O_RDWR);
if (fd < 0)
return 1;
int count = argc > 2 ? atoi(argv[2]) : 200, wrong = 0;
for (int i = 0; i < count; i++) {
unsigned char report[64] = {id};
if (ioctl(fd, HIDIOCGFEATURE(sizeof(report)), report) < 0 || report[0] != id || report[1] != id)
wrong++;
}
printf("%d wrong\n", wrong);
return 0;
}
"""
IMU_MODE_PROBE = r"""
#include <fcntl.h>
#include <linux/hidraw.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main(int argc, char **argv)
{
unsigned mode = (unsigned)strtoul(argv[1], NULL, 0);
int fd = open("/dev/hidraw16", O_RDWR);
if (fd < 0)
return 1;
unsigned char report[65] = {0x00, 0x87, 3, 48, mode & 0xff, mode >> 8};
return ioctl(fd, HIDIOCSFEATURE(sizeof(report)), report) < 0;
}
"""
OVERLAY_READ = r"""
#include <sys/uio.h>
#include <unistd.h>
@@ -348,6 +426,117 @@ class FakeinputRingTest(unittest.TestCase):
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "JSIOCGNAME -1 EINVAL\n28de:11ff Microsoft X-Box 360 pad 0\n")
def pad_ring(self, pad_type, triton_connected=False):
hooks, ring = self.ring(virtual=False)
data = bytearray(ring.read_bytes()) + bytearray(DECK_IMU + TRITON_BLOCK)
struct.pack_into("<I", data, RING_SIZE + 44, 0x80000000 | pad_type)
struct.pack_into("<II", data, RING_SIZE + DECK_IMU, TRITON_MAGIC, 1 if triton_connected else 0)
ring.write_bytes(bytes(data))
env = dict(os.environ, FAKE_EVDEV_DIR=str(hooks), FAKE_EVDEV_DECK="1", FAKE_EVDEV_TRITON="1",
FAKE_EVDEV_MEMFD_PATHS="0=" + str(ring))
return ring, env
def as_process(self, binary, name):
named = self.tmp / name
shutil.copy(binary, named)
return str(named)
def assert_opened_by_steam_and_remote_play_only(self, device, expected, env):
library, probe = self.build("-m64", HIDRAW_PROBE, "hidraw-probe")
env = dict(env, LD_PRELOAD=str(library))
for name, want in (("steam", expected), ("streaming_client", expected), ("game", "refused\n")):
with self.subTest(name=name):
run = subprocess.run([self.as_process(probe, name), device], capture_output=True, text=True,
timeout=10, env=env)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, want)
def test_the_deck_pad_opens_in_steam_and_its_remote_play_client_only(self):
_, env = self.pad_ring(PAD_TYPE_DECK)
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw16", "28de:1205 report 01\n", env)
def test_the_steam_controller_pad_opens_in_steam_and_its_remote_play_client_only(self):
_, env = self.pad_ring(PAD_TYPE_STEAM)
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw19", "28de:1302 report 42\n", env)
def test_the_touch_controller_opens_in_steam_and_its_remote_play_client_only(self):
_, env = self.pad_ring(PAD_TYPE_DECK)
touch = self.tmp / "touchctl"
data = bytearray(TOUCH_RING_SIZE)
struct.pack_into("<I", data, 0, TOUCH_MAGIC)
struct.pack_into("<I", data, 56, 1)
touch.write_bytes(bytes(data))
env["FAKE_TOUCHCTL_RING"] = str(touch)
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw17", "0000:11fb report 00\n", env)
def ask_paired_controller(self, probes, locks_unavailable=False, held=False, count=200):
library, probe = self.build("-m64", FEATURE_PROBE, "feature-probe")
ring, env = self.pad_ring(PAD_TYPE_DECK, triton_connected=True)
env["LD_PRELOAD"] = str(library)
lock = Path(env["FAKE_EVDEV_DIR"]) / ".triton-feature.lock"
if locks_unavailable:
lock.mkdir()
holder = open(lock, "w") if held else None
if holder:
self.addCleanup(holder.close)
fcntl.flock(holder, fcntl.LOCK_EX)
block = RING_SIZE + DECK_IMU
stop = threading.Event()
def controller():
with open(ring, "r+b") as f, mmap.mmap(f.fileno(), 0) as shared:
served = 0
while not stop.is_set():
request = struct.unpack_from("<Q", shared, block + 168)[0]
if request == served:
time.sleep(0.0001)
continue
report_id = struct.unpack_from("<I", shared, block + 184)[0]
struct.pack_into("<i", shared, block + 188, 2)
struct.pack_into("<BB", shared, block + 192, report_id, report_id)
struct.pack_into("<Q", shared, block + 176, request)
served = request
thread = threading.Thread(target=controller)
thread.start()
try:
runs = [subprocess.Popen([self.as_process(probe, name), report_id, str(count)], stdout=subprocess.PIPE,
text=True, env=env)
for name, report_id in probes]
outputs = [run.communicate(timeout=60)[0] for run in runs]
finally:
stop.set()
thread.join()
self.assertEqual([run.returncode for run in runs], [0] * len(probes))
return outputs
def test_steam_and_its_remote_play_client_take_turns_with_the_paired_controllers_features(self):
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")))
self.assertEqual(outputs, ["0 wrong\n", "0 wrong\n"])
def test_without_the_lock_only_steam_asks_the_paired_controller(self):
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")), locks_unavailable=True)
self.assertEqual(outputs, ["0 wrong\n", "200 wrong\n"])
def test_a_stopped_lock_holder_does_not_stall_steam_or_its_remote_play_client(self):
started = time.monotonic()
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")), held=True, count=3)
self.assertEqual(outputs, ["3 wrong\n", "3 wrong\n"])
self.assertLess(time.monotonic() - started, 20)
def test_steam_turning_motion_off_leaves_it_on_for_its_remote_play_client(self):
library, probe = self.build("-m64", IMU_MODE_PROBE, "imu-mode-probe")
ring, env = self.pad_ring(PAD_TYPE_DECK)
env["LD_PRELOAD"] = str(library)
pids = {}
for name, mode in (("steam", "0x18"), ("streaming_client", "0x18"), ("steam", "0x00")):
run = subprocess.Popen([self.as_process(probe, name), mode], env=env)
self.assertEqual(run.wait(timeout=10), 0)
pids[name] = run.pid
data = ring.read_bytes()
self.assertEqual(struct.unpack_from("<I", data, RING_SIZE + 4)[0], 0x80000000)
self.assertEqual(struct.unpack_from("<II", data, RING_SIZE + 52), (0x80000018, pids["streaming_client"]))
if __name__ == "__main__":
unittest.main()
+145
View File
@@ -0,0 +1,145 @@
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
RING_MAGIC = 0x46494252
DESCRIPTION_MAGIC = 0x46495544
HEADER = 64
EVENT = 24
CAPACITY = 4096
DESCRIPTION = 1824
GAME = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <unistd.h>
static int rumble(int fd, unsigned short strong) {
struct ff_effect effect;
memset(&effect, 0, sizeof(effect));
effect.id = -1;
effect.type = FF_RUMBLE;
effect.u.rumble.strong_magnitude = strong;
effect.u.rumble.weak_magnitude = 20000;
if (ioctl(fd, EVIOCSFF, &effect) < 0) return -1;
struct input_event play;
memset(&play, 0, sizeof(play));
play.type = EV_FF;
play.code = effect.id;
play.value = 1;
if (write(fd, &play, sizeof(play)) != sizeof(play)) return -1;
return effect.id;
}
int main(int argc, char **argv) {
int fd = open("/dev/input/event16", O_RDWR | O_NONBLOCK);
if (fd < 0) return 1;
if (argv[1][0] == 'p') {
int other = open("/dev/input/event16", O_RDWR | O_NONBLOCK);
if (other < 0 || rumble(fd, 40000) < 0 || rumble(other, 30000) < 0) return 2;
close(fd);
return 0;
}
if (argv[1][0] == 'k') {
pid_t child = fork();
if (child == 0) {
if (rumble(fd, 40000) < 0) _exit(2);
close(fd);
_exit(0);
}
int status = 0;
waitpid(child, &status, 0);
return WEXITSTATUS(status);
}
struct ff_effect effect;
effect.id = rumble(fd, 40000);
if (effect.id < 0) return 2;
if (argv[1][0] == 'e') ioctl(fd, EVIOCRMFF, effect.id);
else if (argv[1][0] == 'c') close(fd);
else if (argv[1][0] == 'f') {
pid_t child = fork();
if (child == 0) {
close(fd);
_exit(0);
}
waitpid(child, NULL, 0);
}
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("g++") and shutil.which("gcc"), "needs Linux, gcc and g++")
class FakeinputRumbleStopTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
cls.addClassCleanup(shutil.rmtree, cls.tmp, True)
cls.library = cls.tmp / "libfakeinput.so"
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17",
"-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(cls.library),
str(SOURCE), "-ldl"], check=True)
cls.game = cls.tmp / "game"
(cls.tmp / "game.c").write_text(GAME)
subprocess.run(["gcc", "-o", str(cls.game), str(cls.tmp / "game.c")], check=True)
cls.hooks = cls.tmp / "hooks"
cls.hooks.mkdir()
(cls.hooks / "event16").touch()
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 0, 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")
(cls.hooks / ".uinput-event16").write_bytes(bytes(ring))
def packets(self, ending):
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(server.close)
try:
server.bind("\0droiddeck-rumble")
except OSError:
self.skipTest("the rumble socket name is taken on this machine")
server.listen(16)
server.settimeout(0.5)
env = dict(os.environ, LD_PRELOAD=str(self.library), FAKE_EVDEV_DIR=str(self.hooks), FAKE_EVDEV_VIBRATION="1")
run = subprocess.run([str(self.game), ending], env=env, capture_output=True, timeout=10)
self.assertEqual(run.returncode, 0, run.stderr)
got = []
while True:
try:
client, _ = server.accept()
except socket.timeout:
return got
with client:
got.append(struct.unpack("<4H", client.recv(8))[:3])
def test_closing_the_controller_stops_its_held_rumble(self):
self.assertEqual(self.packets("close")[-1], (0, 0, 0))
def test_erasing_the_playing_effect_stops_it(self):
self.assertEqual(self.packets("erase")[-1], (0, 0, 0))
def test_a_forked_child_closing_its_copy_leaves_the_parents_rumble(self):
self.assertEqual(self.packets("fork")[-1], (40000, 20000, 0xffff))
def test_a_child_that_plays_on_an_inherited_controller_stops_it_on_close(self):
self.assertEqual(self.packets("kid")[-1], (0, 0, 0))
def test_closing_an_older_handle_leaves_the_newer_rumble_on_the_slot(self):
self.assertEqual(self.packets("pair")[-1], (30000, 20000, 0xffff))
def test_a_held_effect_still_plays_until_then(self):
self.assertIn((40000, 20000, 0xffff), self.packets("keep"))
if __name__ == "__main__":
unittest.main()
+314
View File
@@ -0,0 +1,314 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
USERNS = shutil.which("unshare") is not None and subprocess.run(["unshare", "-Urm", "true"], capture_output=True).returncode == 0
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
PROGRAM = r"""
#include "FASTPATH"
#include <sys/mount.h>
static const char *race_from, *race_to;
static dev_t race_dev;
static ino_t race_ino;
static long trapped_nr = -1, unsupported_nr = -1;
static long host_sys(long nr, long a, long b, long c, long d, long e, long f) {
if (nr == trapped_nr || (nr == unsupported_nr && a != -1)) return -ENOSYS;
long r = syscall(nr, a, b, c, d, e, f);
struct stat fs;
if (r >= 0 && nr == SYS_fcntl && b == F_DUPFD_CLOEXEC && c == DIR_FD_FLOOR && race_from
&& syscall(SYS_fstat, a, &fs) == 0 && fs.st_dev == race_dev && fs.st_ino == race_ino) {
syscall(SYS_renameat, AT_FDCWD, race_from, AT_FDCWD, race_to);
race_from = NULL;
}
return r < 0 ? -errno : r;
}
static void show(long r) {
if (r == FP_SLOW) puts("SLOW");
else if (r < 0) printf("E%ld\n", -r);
else puts("ok");
}
static int high_fds(void) {
int n = 0;
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + 4 * DIRS; fd++)
if (fcntl(fd, F_GETFD) >= 0) n++;
return n;
}
int main(int argc, char **argv) {
static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512];
static int taken[DIRS];
int ntaken = 0;
fp_sys = host_sys;
snprintf(root, sizeof root, "%s", argv[1]);
rootlen = strlen(root);
int i = 2;
for (; i + 1 < argc && strcmp(argv[i], "--"); i += 2) {
struct bind *bd = &binds[nbinds];
bd->host = hosts[nbinds];
bd->guest = guests[nbinds];
snprintf(bd->host, PATH_MAX, "%s", argv[i]);
snprintf(bd->guest, sizeof guests[0], "%s", argv[i + 1]);
bd->hlen = strlen(bd->host);
bd->glen = strlen(bd->guest);
nbinds++;
}
pthread_once(&init_once, fp_init);
fp_on = 1;
for (i++; i < argc; i++) {
const char *op = argv[i];
if (!strcmp(op, "fuse")) {
for (int b = 0; b < nbinds; b++) binds[b].fuse = 1;
} else if (!strcmp(op, "touch")) {
long fd = fp_open(AT_FDCWD, argv[++i], O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
if (fd >= 0) close((int)fd);
show(fd);
} else if (!strcmp(op, "stat")) {
struct stat st;
show(fp_stat(AT_FDCWD, argv[++i], AT_SYMLINK_NOFOLLOW, &st));
} else if (!strcmp(op, "symlink")) {
long r = fp_symlink("target", AT_FDCWD, argv[++i]);
if (refused()) puts("REFUSED");
else show(r);
} else if (!strcmp(op, "trap-symlink")) {
trapped_nr = SYS_symlinkat;
} else if (!strcmp(op, "no-symlinks")) {
unsupported_nr = SYS_symlinkat;
} else if (!strcmp(op, "on")) {
printf("%d\n", fp_ready());
} else if (!strcmp(op, "no-folders")) {
unsupported_nr = SYS_mkdirat;
} else if (!strcmp(op, "busy-cache")) {
pthread_mutex_lock(&dir_lock);
} else if (!strcmp(op, "mkdir")) {
long r = fp_mkdir(AT_FDCWD, argv[++i], 0755);
if (refused()) puts("REFUSED");
else show(r);
} else if (!strcmp(op, "mv")) {
show(fp_rename(AT_FDCWD, argv[i + 1], AT_FDCWD, argv[i + 2], 0));
i += 2;
} else if (!strcmp(op, "rm")) {
show(fp_unlink(AT_FDCWD, argv[++i], 0));
} else if (!strcmp(op, "host-mv")) {
show(host_sys(SYS_renameat, AT_FDCWD, (long)argv[i + 1], AT_FDCWD, (long)argv[i + 2], 0, 0));
i += 2;
} else if (!strcmp(op, "race-mv")) {
struct stat rs;
race_from = argv[i + 1];
race_to = argv[i + 2];
i += 2;
show(host_sys(SYS_newfstatat, AT_FDCWD, (long)race_from, (long)&rs, 0, 0, 0));
race_dev = rs.st_dev;
race_ino = rs.st_ino;
} else if (!strcmp(op, "host-rmdir")) {
show(host_sys(SYS_unlinkat, AT_FDCWD, (long)argv[++i], AT_REMOVEDIR, 0, 0, 0));
} else if (!strcmp(op, "host-mkdir")) {
show(host_sys(SYS_mkdirat, AT_FDCWD, (long)argv[++i], 0755, 0, 0, 0));
} else if (!strcmp(op, "clobber")) {
long null = host_sys(SYS_openat, AT_FDCWD, (long)"/dev/null", O_RDONLY, 0, 0, 0);
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) host_sys(SYS_dup3, null, fd, 0, 0, 0, 0);
host_sys(SYS_close, null, 0, 0, 0, 0, 0);
puts("ok");
} else if (!strcmp(op, "first-fd")) {
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%d", DIR_FD_FLOOR);
long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0);
out[n > 0 ? n : 0] = 0;
puts(out);
} else if (!strcmp(op, "fds")) {
printf("%d\n", high_fds());
} else if (!strcmp(op, "ttl")) {
ttl_ns = atoll(argv[++i]) * 1000000LL;
} else if (!strcmp(op, "sleep")) {
usleep(atoi(argv[++i]) * 1000);
} else if (!strcmp(op, "chmod")) {
show(fp_chmod(AT_FDCWD, argv[i + 1], strtol(argv[i + 2], NULL, 8), 0));
i += 2;
} else if (!strcmp(op, "host-mount")) {
show(mount("tmpfs", argv[++i], "tmpfs", 0, NULL) == 0 ? 0 : -errno);
} else if (!strcmp(op, "take-over")) {
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) {
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%d", fd);
long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0);
if (n <= 0) continue;
out[n] = 0;
long mine = host_sys(SYS_openat, AT_FDCWD, (long)out, O_RDONLY | O_DIRECTORY, 0, 0, 0);
host_sys(SYS_dup3, mine, fd, 0, 0, 0, 0);
host_sys(SYS_close, mine, 0, 0, 0, 0, 0);
taken[ntaken++] = fd;
}
puts("ok");
} else if (!strcmp(op, "taken")) {
int open_fds = 0;
for (int t = 0; t < ntaken; t++)
if (lseek(taken[t], 0, SEEK_CUR) == 0) open_fds++;
printf("%d/%d\n", open_fds, ntaken);
}
}
return 0;
}
"""
class FastPathFuseDirsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if shutil.which("gcc") is None:
raise unittest.SkipTest("gcc is not available")
cls.build = tempfile.TemporaryDirectory()
source = Path(cls.build.name) / "fuse_dirs.c"
source.write_text(PROGRAM.replace("FASTPATH", str(FASTPATH)))
cls.program = Path(cls.build.name) / "fuse_dirs"
subprocess.run(["gcc", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-format-truncation", "-pthread", "-o", str(cls.program), str(source), "-ldl"], check=True)
@classmethod
def tearDownClass(cls):
cls.build.cleanup()
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
base = Path(self.temp.name)
self.root = base / "root"
(self.root / "mnt").mkdir(parents=True)
self.card = base / "card"
(self.card / "Games/steamapps/common/Game/Data").mkdir(parents=True)
def ask(self, *ops, wrap=()):
argv = [*wrap, str(self.program), str(self.root), str(self.card), "/mnt/card", "--", *ops]
return subprocess.run(argv, capture_output=True, text=True, timeout=20, check=True).stdout.split()
def test_files_deep_in_a_fuse_library_are_created_renamed_and_removed(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "touch", f"{data}/a.tmp", "mv", f"{data}/a.tmp", f"{data}/a.idx",
"stat", f"{data}/a.idx", "stat", f"{data}/a.tmp", "rm", f"{data}/a.idx",
"stat", f"{data}/a.idx", "fds")
self.assertEqual(["ok", "ok", "ok", "E2", "ok", "E2"], out[:-1])
self.assertGreater(int(out[-1]), 0)
self.assertEqual([], list((self.card / "Games/steamapps/common/Game/Data").iterdir()))
def test_a_folder_renamed_behind_the_cache_is_not_reused(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"host-mv", str(game), str(game.parent / "Moved"),
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"stat", "/mnt/card/Games/steamapps/common/Moved/Data/keep")
self.assertEqual(["ok", "ok", "E2", "ok"], out)
def test_a_folder_renamed_while_it_is_opened_is_not_used_under_its_old_name(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
out = self.ask("fuse", "race-mv", str(game / "Data"), str(game / "Moved"),
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new", "fds")
self.assertEqual(["ok", "E2", "E2"], out[:3])
self.assertEqual(["keep"], [p.name for p in (game / "Moved").iterdir()])
self.assertLessEqual(int(out[-1]), 64)
def test_a_folder_deleted_and_made_again_is_looked_up_fresh(self):
data = self.card / "Games/steamapps/common/Game/Data"
out = self.ask("fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/old",
"rm", "/mnt/card/Games/steamapps/common/Game/Data/old",
"host-rmdir", str(data), "host-mkdir", str(data),
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
self.assertEqual(["ok"] * 5, out)
self.assertEqual(["new"], [p.name for p in data.iterdir()])
def test_folders_deleted_and_made_again_many_times_keep_descriptors_bounded(self):
data = self.card / "Games/steamapps/common/Game/Data"
ops = ["fuse"]
for _ in range(200):
ops += ["touch", "/mnt/card/Games/steamapps/common/Game/Data/x",
"rm", "/mnt/card/Games/steamapps/common/Game/Data/x",
"host-rmdir", str(data), "host-mkdir", str(data)]
out = self.ask(*ops, "fds")
self.assertEqual(["ok"] * 800, out[:-1])
self.assertLessEqual(int(out[-1]), 64)
def test_descriptors_the_program_takes_over_are_left_alone(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "touch", f"{data}/a", "clobber", "touch", f"{data}/b",
"stat", f"{data}/a", "first-fd")
self.assertEqual(["ok", "ok", "ok", "ok", "/dev/null"], out)
self.assertEqual({"a", "b"}, {p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()})
def test_a_folder_the_program_opened_itself_stays_open_when_the_cache_moves_on(self):
data = self.card / "Games/steamapps/common/Game/Data"
ops = ["fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/a", "take-over"]
for n in range(200):
(data / f"d{n}").mkdir()
ops += ["touch", f"/mnt/card/Games/steamapps/common/Game/Data/d{n}/x"]
out = self.ask(*ops, "taken")
self.assertEqual(["ok"] * 202, out[:-1])
opened, total = map(int, out[-1].split("/"))
self.assertGreater(total, 0)
self.assertEqual(total, opened)
self.assertEqual(200, len(list(data.glob("d*/x"))))
@unittest.skipIf(os.geteuid() == 0, "root passes folder permissions")
def test_a_parent_folder_closed_by_the_program_stops_cached_access_at_once(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
self.addCleanup(os.chmod, game, 0o755)
out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"chmod", "/mnt/card/Games/steamapps/common/Game", "000",
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
self.assertEqual(["ok", "ok"], out[:2])
self.assertNotIn("ok", out[2:])
os.chmod(game, 0o755)
self.assertEqual(["keep"], [p.name for p in (game / "Data").iterdir()])
@unittest.skipUnless(USERNS, "mount namespaces are not available")
def test_a_mount_placed_over_a_cached_folder_receives_later_writes(self):
data = self.card / "Games/steamapps/common/Game/Data"
out = self.ask("fuse", "ttl", "1", "touch", "/mnt/card/Games/steamapps/common/Game/Data/under",
"host-mount", str(data), "sleep", "20",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/over",
"stat", "/mnt/card/Games/steamapps/common/Game/Data/under", wrap=("unshare", "-Urm"))
self.assertEqual(["ok", "ok", "ok", "E2"], out)
self.assertEqual(["under"], [p.name for p in data.iterdir()])
def test_a_call_the_filesystem_does_not_implement_leaves_the_fast_path_on(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "no-symlinks", "touch", f"{data}/a", "symlink", f"{data}/link", "on",
"stat", f"{data}/a", "symlink", f"{data}/link", "on", "touch", f"{data}/b")
self.assertEqual(["ok", "REFUSED", "1", "ok", "REFUSED", "1", "ok"], out)
self.assertEqual(["a", "b"], sorted(p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()))
def test_repeated_unsupported_calls_close_the_folders_they_opened(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
ops = [op for n in range(40) for op in ("mkdir", f"{data}/new{n}")]
out = self.ask("fuse", "no-folders", "busy-cache", *ops, "on", "fds")
self.assertEqual(["REFUSED"] * 40 + ["1", "0"], out)
def test_a_trapped_call_still_stops_the_fast_path_for_the_process(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "trap-symlink", "symlink", f"{data}/link", "on")
self.assertEqual(["REFUSED", "0"], out)
def test_a_symlink_is_made_where_the_filesystem_allows_it(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "symlink", f"{data}/link", "on")
self.assertEqual(["ok", "1"], out)
self.assertEqual("target", os.readlink(self.card / "Games/steamapps/common/Game/Data/link"))
def test_other_filesystems_keep_absolute_paths_and_open_no_folders(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("touch", f"{data}/a", "mv", f"{data}/a", f"{data}/b", "rm", f"{data}/b", "fds")
self.assertEqual(["ok", "ok", "ok", "0"], out)
if __name__ == "__main__":
unittest.main()
+380 -8
View File
@@ -33,6 +33,94 @@ class SupergiantDotnetReporterTest(unittest.TestCase):
self.assertIsNone(MODULE["supergiant_dotnet_reporter"](game))
class DeathStrandingAllocatorTest(unittest.TestCase):
def make_exe(self, name="ds.exe", size=None, window=None, tail=None):
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder, True)
path = os.path.join(folder, name)
with open(path, "wb") as game:
game.truncate(MODULE["DS_SIZE"] if size is None else size)
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
game.write(b"<" + (MODULE["DS_WINDOW"] if window is None else window) + (MODULE["DS_ORIGINAL"] if tail is None else tail) + b">")
return path
def read_tail(self, path):
with open(path, "rb") as game:
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
return game.read(len(MODULE["DS_WINDOW"]) + len(MODULE["DS_ORIGINAL"]) + 2)
def run_fix(self, path, app_id="1850570"):
errors = io.StringIO()
with mock.patch("sys.stderr", errors):
return MODULE["death_stranding_allocator"](app_id, path), errors.getvalue()
def test_window_and_patch_have_the_measured_shape(self):
self.assertEqual(41, len(MODULE["DS_WINDOW"]))
self.assertEqual(6, len(MODULE["DS_ORIGINAL"]))
self.assertEqual(6, len(MODULE["DS_FIXED"]))
self.assertEqual(0x38FE1B9, MODULE["DS_WINDOW_OFFSET"] + len(MODULE["DS_WINDOW"]))
def test_replaces_only_the_jump_in_the_original_build(self):
path = self.make_exe()
patched, message = self.run_fix(path)
self.assertTrue(patched)
self.assertIn("Death Stranding", message)
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
self.assertEqual(MODULE["DS_SIZE"], os.path.getsize(path))
def test_an_already_patched_game_is_left_alone(self):
path = self.make_exe(tail=MODULE["DS_FIXED"])
before = os.stat(path).st_mtime_ns
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, os.stat(path).st_mtime_ns)
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
def test_a_second_run_changes_nothing(self):
path = self.make_exe()
self.assertTrue(self.run_fix(path)[0])
after_first = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(after_first, self.read_tail(path))
def test_other_builds_of_the_game_are_not_touched(self):
for size, window in ((MODULE["DS_SIZE"] + 1, None), (None, bytes(len(MODULE["DS_WINDOW"])))):
path = self.make_exe(size=size, window=window)
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_an_unknown_instruction_at_the_patch_site_is_not_touched(self):
path = self.make_exe(tail=bytes.fromhex("0f85a6000000"))
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_other_executables_are_ignored(self):
path = self.make_exe(name="game.exe")
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_other_games_are_not_touched_even_with_a_matching_file(self):
for app_id in ("440", "", None):
path = self.make_exe()
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path, app_id))
self.assertEqual(before, self.read_tail(path))
def test_both_death_stranding_app_ids_are_patched(self):
for app_id in ("1850570", "1190460"):
self.assertTrue(self.run_fix(self.make_exe(), app_id)[0])
def test_the_file_name_check_ignores_case(self):
self.assertTrue(self.run_fix(self.make_exe(name="DS.EXE"))[0])
def test_a_missing_game_file_is_reported_without_raising(self):
patched, message = self.run_fix(os.path.join(tempfile.gettempdir(), "droiddeck-no-such-folder", "ds.exe"))
self.assertFalse(patched)
self.assertIn("not applied", message)
def mapping_of(text):
tokens = COMPAT["tokenize"](text)
return COMPAT["read_mapping"](tokens, COMPAT["mapping_block"](tokens))
@@ -723,6 +811,7 @@ class GameEnvironmentTest(unittest.TestCase):
"install_scripts_done": lambda scripts, env: False,
"scripts_digest": lambda scripts: None,
"win_components": lambda *args: seen_components.append(args[3]) or "",
"restore_compatible_system_dlls": lambda *args: [],
"repair_foreign_system_dlls": lambda *args: seen_repair.append(args[2]) or [],
"gl_vsync": lambda env: False,
"game_images": lambda env: None,
@@ -756,6 +845,61 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_repair])
self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_start])
def test_keyboard_helper_is_off_unless_steam_keyboard_or_the_user_wants_it(self):
cases = (
({}, "tabtip.exe=d"),
({"WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "tabtipx=d"}, "tabtipx=d;tabtip.exe=d"),
({"SteamDeck": "0"}, "tabtip.exe=d"),
({"SteamDeck": "1"}, None),
({"SteamDeck": "1", "WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n"),
({"WINEDLLOVERRIDES": "tabtip.exe=b"}, "tabtip.exe=b"),
({"WINEDLLOVERRIDES": "dxgi=n; TabTip.EXE=n,b"}, "dxgi=n; TabTip.EXE=n,b"),
({"WINEDLLOVERRIDES": "dxgi=n; TabTip=n,b"}, "dxgi=n; TabTip=n,b;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "d3d11 tabtip.exe"}, "d3d11 tabtip.exe;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "tabtip.exe;dxgi=n"}, "tabtip.exe;dxgi=n;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "d3d11,tabtip.exe=b"}, "d3d11,tabtip.exe=b"),
({"WINEDLLOVERRIDES": "d3d11 tabtip.exe=b"}, "d3d11 tabtip.exe=b"),
({"WINEDLLOVERRIDES": "d3d11\ttabtip.exe=b"}, "d3d11\ttabtip.exe=b"),
({"WINEDLLOVERRIDES": "d3d11\ttabtip=b"}, "d3d11\ttabtip=b;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "d3d11 dxgi=n"}, "d3d11 dxgi=n;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "*tabtip.exe=b"}, "*tabtip.exe=b"),
({"WINEDLLOVERRIDES": "TabTip.exe.DLL=b"}, "TabTip.exe.DLL=b"),
({"WINEDLLOVERRIDES": "d3d11,*tabtip.exe.dll=n"}, "d3d11,*tabtip.exe.dll=n"),
({"WINEDLLOVERRIDES": "*tabtip=b"}, "*tabtip=b;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "tabtip.dll=b"}, "tabtip.dll=b;tabtip.exe=d"),
)
for before, overrides in cases:
with self.subTest(env=before):
env = dict(before)
note = MODULE["keyboard_helper_off"](env)
self.assertEqual(env.get("WINEDLLOVERRIDES"), overrides)
self.assertEqual(note is not None, overrides != before.get("WINEDLLOVERRIDES"))
def test_game_launch_turns_the_keyboard_helper_off_and_keeps_user_choices(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
probe = home / "probe"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('WINEDLLOVERRIDES', 'unset'))\n")
probe.chmod(0o755)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
cases = (
("waitforexitandrun", {}, "tabtip.exe=d"),
("waitforexitandrun", {"WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n;tabtip.exe=d"),
("waitforexitandrun", {"SteamDeck": "1"}, "unset"),
("waitforexitandrun", {"WINEDLLOVERRIDES": "tabtip.exe=b"}, "tabtip.exe=b"),
("run", {}, "unset"),
)
for verb, profile, expected in cases:
with self.subTest(verb=verb, profile=profile):
config.write_text(json.dumps({"version": 1, "games": {"42": profile}}))
env = {k: v for k, v in os.environ.items() if k not in ("SteamDeck", "WINEDLLOVERRIDES")}
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), verb],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip().splitlines()[-1], expected)
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
from unittest.mock import patch
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
@@ -950,6 +1094,22 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
def test_games_run_with_gl_error_checks_unless_the_user_turns_them_off(self):
gpu = MODULE["game_gpu"]
session = {"MESA_NO_ERROR": "1", "DROIDDECK_GAME_MESA_NO_ERROR": "", "KEEP": "1"}
self.assertEqual(gpu(session), {"KEEP": "1"})
self.assertEqual(gpu(session, True), {"MESA_NO_ERROR": "1", "KEEP": "1"})
self.assertEqual(gpu({"MESA_NO_ERROR": "1"}), {"MESA_NO_ERROR": "1"})
self.assertEqual(gpu({"MESA_NO_ERROR": "1", "DROIDDECK_GAME_MESA_NO_ERROR": "1"}), {"MESA_NO_ERROR": "1"})
both = gpu({"MESA_NO_ERROR": "1", "DROIDDECK_GAME_MESA_NO_ERROR": "", "TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "nolrz"})
self.assertEqual(both, {"TU_DEBUG": "nolrz"})
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "MESA_NO_ERROR": "1"}),
{"MESA_NO_ERROR": "1"})
config = {"version": 1, "games": {"42": {"MESA_NO_ERROR": "1"}}}
env = gpu(session)
self.assertEqual(MODULE["apply_config"](env, config, "42")["MESA_NO_ERROR"], "1")
self.assertNotIn("MESA_NO_ERROR", MODULE["apply_config"](env, config, "43"))
def test_a_chromium_app_keeps_the_sessions_turnip_debug(self):
gpu = MODULE["game_gpu"]
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "KEEP": "1"}, True),
@@ -992,9 +1152,11 @@ class GameEnvironmentTest(unittest.TestCase):
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
cap = MODULE["vram_cap"]
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096; dxgi.maxSharedMemory = 4096")
self.assertEqual(cap({"BL_VRAM_MB": "8192"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 8192; dxgi.maxSharedMemory = 8192")
self.assertEqual(cap({"BL_VRAM_MB": "4095"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4095; dxgi.maxSharedMemory = 4095; d3d9.maxAvailableMemory = 4095")
self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
"dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60")
"dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048; dxvk.maxFrameRate = 60")
for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}):
self.assertNotIn("DXVK_CONFIG", cap(off))
self.assertNotIn("DROIDDECK_VRAM_CAP", cap(off))
@@ -1154,6 +1316,8 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d")
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
self.assertEqual(MODULE["engine_fixes"](str(game / "Game.exe"), ["--rendering-driver", "opengl3"])[1], [])
(game / "data_game_windows_x86_64/Sentry.Godot.dll").touch()
self.assertNotIn("WINEDLLOVERRIDES", MODULE["engine_fixes"](str(game / "Game.exe"), [])[0])
script = Path(tmp) / "GDScript Game"
script.mkdir()
for name in ("Game.exe", "Game.pck", "libsentry.windows.release.x86_64.dll"):
@@ -1520,6 +1684,19 @@ class GameEnvironmentTest(unittest.TestCase):
config = {"version": 1, "shared": {}, "games": {"42": values}}
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), values, name)
def test_ff7_rebirth_runs_at_feature_level_12_2_unless_the_game_overrides_it(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "FINAL FANTASY VII REBIRTH"
game = root / "End/Binaries/Win64/ff7rebirth_.exe"
game.parent.mkdir(parents=True)
for exe in (root / "ff7rebirth.exe", game):
exe.touch()
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, exe.name)
self.assertTrue(notes)
config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}}
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"})
def test_unity_players_keep_tso_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
def game(*names):
@@ -1561,6 +1738,35 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(result["FEX_TSOENABLED"], "0")
self.assertEqual(result["WINEDLLOVERRIDES"], "dxgi=n;libsentry=d")
def test_game_dll_overrides_follow_droiddecks_own(self):
fixes = {"WINEDLLOVERRIDES": "msvcp100=n,b"}
config = {"version": 1, "shared": {}, "games": {"42": {"WINEDLLOVERRIDES": "windowscodecs,windowscodecsext=n"}}}
result = MODULE["apply_config"]({}, config, "42", fixes)
self.assertEqual(result["WINEDLLOVERRIDES"], "msvcp100=n,b;windowscodecs,windowscodecsext=n")
def test_game_dll_overrides_edge_cases(self):
fixes = {"WINEDLLOVERRIDES": "msvcp100=n,b"}
env = {"WINEDLLOVERRIDES": "dxgi=n"}
for game, shared, expected in (
({"WINEDLLOVERRIDES": "msvcp100=b"}, {}, "msvcp100=n,b;msvcp100=b"),
({"WINEDLLOVERRIDES": ""}, {}, "msvcp100=n,b"),
({"WINEDLLOVERRIDES": None}, {}, None),
({"WINEDLLOVERRIDES": "d3d9=n"}, {"WINEDLLOVERRIDES": "xinput1_3=n"}, "msvcp100=n,b;d3d9=n"),
({}, {}, "dxgi=n;msvcp100=n,b"),
({"WINEDLLOVERRIDES": "x" * 8179}, {}, "msvcp100=n,b;" + "x" * 8179),
):
with self.subTest(game=game, shared=shared):
config = {"version": 1, "shared": shared, "games": {"42": game, "43": {"WINEDLLOVERRIDES": "d3d11=n"}}}
result = MODULE["apply_config"](env, config, "42", fixes)
self.assertEqual(result.get("WINEDLLOVERRIDES"), expected)
self.assertEqual(MODULE["apply_config"](env, config, "43")["WINEDLLOVERRIDES"], "d3d11=n")
stderr = io.StringIO()
config = {"version": 1, "shared": {}, "games": {"42": {"WINEDLLOVERRIDES": "x" * 8192}}}
with mock.patch("sys.stderr", stderr):
result = MODULE["apply_config"](env, config, "42", fixes)
self.assertEqual(result["WINEDLLOVERRIDES"], "x" * 8192)
self.assertIn("too long", stderr.getvalue())
def test_invalid_configuration_is_atomic(self):
env = {"ORIGINAL": "unchanged"}
for entries in ({"A": "ok", "BAD=KEY": "x"}, {"A": "bad\0value"}, {"A": 1}):
@@ -2687,6 +2893,39 @@ def arm64ec_pe_image():
return bytes(image)
def program_image(machine, imports):
image = bytearray(0x400)
image[:2] = b"MZ"
image[60:64] = (64).to_bytes(4, "little")
image[64:68] = b"PE\0\0"
coff = 68
image[coff:coff + 2] = machine.to_bytes(2, "little")
image[coff + 2:coff + 4] = (1).to_bytes(2, "little")
image[coff + 16:coff + 18] = (240).to_bytes(2, "little")
optional = coff + 20
image[optional:optional + 2] = (0x20B).to_bytes(2, "little")
image[optional + 108:optional + 112] = (16).to_bytes(4, "little")
image[optional + 120:optional + 124] = (0x1000).to_bytes(4, "little")
image[optional + 124:optional + 128] = (20 * (len(imports) + 1)).to_bytes(4, "little")
section = optional + 240
image[section + 8:section + 12] = (0x200).to_bytes(4, "little")
image[section + 12:section + 16] = (0x1000).to_bytes(4, "little")
image[section + 16:section + 20] = (0x200).to_bytes(4, "little")
image[section + 20:section + 24] = (0x200).to_bytes(4, "little")
name = 20 * (len(imports) + 1)
for index, dll in enumerate(imports):
image[0x200 + index * 20 + 12:0x200 + index * 20 + 16] = (0x1000 + name).to_bytes(4, "little")
image[0x200 + name:0x200 + name + len(dll)] = dll.encode()
name += len(dll) + 1
return bytes(image)
def bytes_path(folder, data):
path = folder / "image.exe"
path.write_bytes(data)
return path
class ForeignSystemDllTest(unittest.TestCase):
def prefix(self, tmp, arm=True):
proton = Path(tmp) / "Proton"
@@ -2698,7 +2937,8 @@ class ForeignSystemDllTest(unittest.TestCase):
for libdir, machine in (("aarch64-windows", 0xAA64), ("i386-windows", 0x14C)):
(dist / libdir).mkdir(parents=True)
for name in ("ucrtbase.dll", "rpcrt4.dll"):
(dist / libdir / name).write_bytes(pe_image(machine))
(dist / libdir / name).write_bytes(program_image(machine, []))
(dist / "aarch64-windows/wineboot.exe").write_bytes(program_image(0xAA64, ["UCRTBASE.dll", "rpcrt4.dll"]))
windows = Path(tmp) / "compat/pfx/drive_c/windows"
for folder in ("system32", "syswow64"):
(windows / folder).mkdir(parents=True)
@@ -2738,16 +2978,148 @@ class ForeignSystemDllTest(unittest.TestCase):
self.assertFalse((system32 / "ucrtbase.dll").is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](system32 / "userlib.dll"))
def test_x64_visual_cpp_runtime_in_arm64_system32_is_kept(self):
def test_x64_dlls_proton_programs_do_not_import_are_kept_in_arm64_system32(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
for name in ("msvcp140.dll", "VCRUNTIME140.dll", "msvcp_win.dll"):
(builtins / name.lower()).write_bytes(pe_image(0xAA64))
(builtins / "explorer.exe").write_bytes(program_image(0xAA64, ["shell32.dll"]))
(builtins / "shell32.dll").write_bytes(program_image(0xAA64, ["msvcp_win.dll"]))
names = ("vulkan-1.dll", "msvcp140.dll", "VCRUNTIME140.dll", "concrt140.dll", "d3dcompiler_43.dll",
"winhttp.dll", "msvcp_win.dll")
for name in names:
(builtins / name.lower()).write_bytes(program_image(0xAA64, []))
(windows / "system32" / name).write_bytes(pe_image(0x8664))
self.assertEqual(["system32/msvcp_win.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertFalse((windows / "system32/msvcp140.dll").is_symlink())
self.assertFalse((windows / "system32/VCRUNTIME140.dll").is_symlink())
for name in names[:-1]:
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
def test_repaired_dll_proton_programs_do_not_import_gets_its_native_copy_back(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
for name in ("vulkan-1.dll", "ucrtbase.dll"):
(system32 / name).symlink_to(os.path.relpath(builtins / name, system32))
(system32 / (name + ".foreign-arch")).write_bytes(pe_image(0x8664))
(system32 / "vulkan-1.dll.foreign-arch.1").write_bytes(pe_image(0x8664) + b"newest")
restore = MODULE["restore_compatible_system_dlls"]
self.assertEqual(["system32/vulkan-1.dll (machine 0x8664)"], restore(str(compat), str(proton)))
self.assertFalse((system32 / "vulkan-1.dll").is_symlink())
self.assertTrue((system32 / "vulkan-1.dll").read_bytes().endswith(b"newest"))
self.assertFalse((system32 / "vulkan-1.dll.foreign-arch.1").exists())
self.assertTrue((system32 / "ucrtbase.dll").is_symlink())
self.assertEqual([], restore(str(compat), str(proton)))
self.assertEqual([], self.run_repair(compat, proton))
def test_prefix_backup_directory_is_listed_once_per_pass(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
system32 = windows / "system32"
for index in range(12):
name = "native_%02d.dll" % index
(builtins / name).write_bytes(pe_image(0xAA64))
(system32 / name).symlink_to(os.path.relpath(builtins / name, system32))
(system32 / (name + ".foreign-arch")).write_bytes(pe_image(0x8664))
(system32 / "ucrtbase.dll").write_bytes(pe_image(0x8664))
original_listdir = os.listdir
visited = []
def counted_listdir(folder):
if Path(folder) == system32:
visited.append(folder)
return original_listdir(folder)
with mock.patch("os.listdir", side_effect=counted_listdir):
restored = MODULE["restore_compatible_system_dlls"](str(compat), str(proton))
fixed = self.run_repair(compat, proton)
self.assertEqual(12, len(restored))
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], fixed)
# One system32 listing for restore and one for repair, regardless
# of the number of DLLs and backup files in the prefix.
self.assertEqual(2, len(visited))
def test_restore_takes_the_highest_backup_serial_across_gaps(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(builtins / "vulkan-1.dll", system32))
(system32 / "vulkan-1.dll.foreign-arch.2").write_bytes(pe_image(0x8664) + b"two")
(system32 / "vulkan-1.dll.foreign-arch.10").write_bytes(pe_image(0x8664) + b"ten")
self.assertEqual(["system32/vulkan-1.dll (machine 0x8664)"],
MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").read_bytes().endswith(b"ten"))
def test_unreadable_proton_program_keeps_the_conservative_rule(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "broken.exe").mkdir()
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
(system32 / "concrt140.dll").write_bytes(pe_image(0x8664))
(builtins / "concrt140.dll").write_bytes(pe_image(0xAA64))
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(builtins / "vulkan-1.dll", system32))
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0x8664))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
self.assertEqual(["system32/concrt140.dll (machine 0x8664)"], self.run_repair(compat, proton))
def test_new_backup_goes_above_the_highest_existing_serial(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
system32 = windows / "system32"
(system32 / "ucrtbase.dll").write_bytes(pe_image(0x8664) + b"newest")
(system32 / "ucrtbase.dll.foreign-arch").write_bytes(pe_image(0x8664))
(system32 / "ucrtbase.dll.foreign-arch.2").write_bytes(pe_image(0x8664))
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertTrue((system32 / "ucrtbase.dll.foreign-arch.3").read_bytes().endswith(b"newest"))
self.assertFalse((system32 / "ucrtbase.dll.foreign-arch.1").exists())
def test_truncated_import_table_keeps_the_conservative_rule(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "cut.exe").write_bytes(program_image(0xAA64, ["concrt140.dll"])[:0x20A])
self.assertIsNone(MODULE["PE"]["pe_imports"](builtins / "cut.exe"))
self.assertIsNone(MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), program_image(0xAA64, ["a.dll"])[:200])))
self.assertEqual(set(), MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), program_image(0xAA64, []))))
moved = bytearray(program_image(0xAA64, ["concrt140.dll"]))
moved[208:212] = (0x3000).to_bytes(4, "little")
self.assertIsNone(MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), moved)))
(builtins / "concrt140.dll").write_bytes(pe_image(0xAA64))
(windows / "system32/concrt140.dll").write_bytes(pe_image(0x8664))
self.assertEqual(["system32/concrt140.dll (machine 0x8664)"], self.run_repair(compat, proton))
def test_restore_leaves_other_links_and_x64_proton_alone(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
other = Path(tmp) / "other-vulkan-1.dll"
other.write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
(system32 / "vulkan-1.dll").symlink_to(other)
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0x8664))
(system32 / "rpcrt4.dll").symlink_to(os.path.relpath(builtins / "rpcrt4.dll", system32))
(system32 / "rpcrt4.dll.foreign-arch").write_bytes(pe_image(0x14C))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
self.assertTrue((system32 / "rpcrt4.dll").is_symlink())
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp, arm=False)
dist = proton.parent / "files/lib/wine/x86_64-windows"
dist.mkdir(parents=True)
(dist / "vulkan-1.dll").write_bytes(pe_image(0x8664))
system32 = windows / "system32"
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(dist / "vulkan-1.dll", system32))
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0xAA64))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
def test_final_arm64ec_image_is_not_repaired_as_a_foreign_x64_dll(self):
with tempfile.TemporaryDirectory() as tmp:
+10 -1
View File
@@ -9,7 +9,7 @@ from pathlib import Path
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "MESA_LOADER_DRIVER_OVERRIDE", "GALLIUM_DRIVER",
"LIBGL_KOPPER_DRI2", "VK_ICD_FILENAMES", "VK_DRIVER_FILES")
"LIBGL_KOPPER_DRI2", "VK_ICD_FILENAMES", "VK_DRIVER_FILES", "MESA_NO_ERROR", "DROIDDECK_GAME_MESA_NO_ERROR")
SESSION = {"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""}
GPU_SESSION = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink",
"LIBGL_KOPPER_DRI2": "true", "VK_ICD_FILENAMES": "/runtime/turnip.json",
@@ -68,6 +68,15 @@ class GameGpuLaunchersTest(unittest.TestCase):
self.chromium()
self.assertEqual("sysmem", self.wrapper("--for", str(self.app / "files"))["TU_DEBUG"])
def test_programs_get_gl_error_checks_back_while_chromium_keeps_the_client_setting(self):
session = dict(GPU_SESSION, MESA_NO_ERROR="1", DROIDDECK_GAME_MESA_NO_ERROR="")
values = self.wrapper(session=session)
self.assertEqual(("unset", "unset"), (values["MESA_NO_ERROR"], values["DROIDDECK_GAME_MESA_NO_ERROR"]))
self.assertEqual(GPU_SESSION, {key: values[key] for key in GPU_SESSION})
self.assertEqual("1", self.wrapper("--chromium", session=session)["MESA_NO_ERROR"])
self.assertEqual("unset", self.flatpak(session)["MESA_NO_ERROR"])
self.assertEqual("1", self.wrapper(session={"MESA_NO_ERROR": "1"})["MESA_NO_ERROR"])
def test_without_the_game_setting_the_wrapper_changes_nothing(self):
self.assertEqual("sysmem", self.wrapper(session={"TU_DEBUG": "sysmem"})["TU_DEBUG"])
self.assertEqual("unset", self.wrapper(session={})["TU_DEBUG"])
+53
View File
@@ -0,0 +1,53 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
class GameResolutionTest(unittest.TestCase):
def launch(self, mode, **overrides):
source = SESSION.read_text()
start = source.index(' width=${BL_WIDTH:-1280}')
end = source.index('\nfi\n\nbl_displays()', start)
block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub')
with tempfile.TemporaryDirectory() as directory:
env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH='60', BL_MANGOAPP='0',
BL_WIDTH='2560', BL_HEIGHT='1600')
for name in ('BL_GAME_WIDTH', 'BL_GAME_HEIGHT', 'BL_FOLLOW_OUTPUT', 'BL_GAMESCOPE_STRETCH_16X9'):
env.pop(name, None)
env.update(overrides)
fake = Path(directory) / 'gamescope'
fake.write_text('#!/bin/bash\nprintf "ARG:%s\\n" "$@"\n')
fake.chmod(0o755)
env['PATH'] = directory + os.pathsep + env['PATH']
script = f'''
set -u
mode={mode}
pipewire_stub() {{ return 1; }}
run_gamescope() {{ printf 'ARG:%s\n' "$@"; }}
''' + block
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
return [line.removeprefix('ARG:') for line in result.stdout.splitlines() if line.startswith('ARG:')]
def test_a_game_started_without_steam_runs_at_its_resolution_with_proportions_kept(self):
args = self.launch('run', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720')
self.assertEqual(['2560', '1600'], [args[args.index('-W') + 1], args[args.index('-H') + 1]])
self.assertEqual(['1280', '720'], [args[args.index('-w') + 1], args[args.index('-h') + 1]])
self.assertNotIn('-S', args)
def test_without_a_game_resolution_the_game_matches_the_output(self):
args = self.launch('run')
self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]])
def test_steam_ignores_the_game_resolution(self):
args = self.launch('steam', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720')
self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]])
if __name__ == '__main__':
unittest.main()
+48
View File
@@ -1,6 +1,7 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
@@ -100,3 +101,50 @@ class DesktopGamescopeBackendTest(unittest.TestCase):
self.assertEqual(64, result.returncode)
self.assertIn("unsupported gamescope backend: drm", result.stderr)
self.assertIsNone(capture)
class DesktopGamescopeReaperTest(unittest.TestCase):
def launch(self, reaper_on_path):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
bin_dir = root / "bin"
games = root / "games"
bin_dir.mkdir()
games.mkdir()
capture = root / "path.txt"
gamescope = bin_dir / "gamescope"
gamescope.write_text(
"#!/bin/sh\n"
"printf '%s\\n' \"$PATH\" > \"$GAMESCOPE_CAPTURE\"\n"
"command -v gamescopereaper >> \"$GAMESCOPE_CAPTURE\" || exit 3\n"
)
gamescope.chmod(0o755)
reaper = (bin_dir if reaper_on_path else games) / "gamescopereaper"
reaper.write_text("#!/bin/sh\n")
reaper.chmod(0o755)
date = bin_dir / "date"
date.write_text(f"#!/bin/sh\nexec {shutil.which('date')} \"$@\"\n")
date.chmod(0o755)
script = root / "droiddeck-gpu"
source = DESKTOP_GPU.read_text()
self.assertIn("for dir in /usr/games ", source)
script.write_text(source.replace("for dir in /usr/games ", f"for dir in {games} ", 1))
start_path = str(bin_dir)
env = {"PATH": start_path, "HOME": directory, "GAMESCOPE_CAPTURE": str(capture),
"WAYLAND_DISPLAY": "desktop-0", "BL_DESKTOP_GPU_WINDOW": "0"}
result = subprocess.run(["/bin/bash", str(script), "demo"], env=env, text=True,
capture_output=True, timeout=5)
lines = capture.read_text().splitlines() if capture.exists() else []
return result, start_path, lines, str(reaper)
def test_reaper_outside_path_is_added_for_gamescope(self):
result, start_path, lines, reaper = self.launch(reaper_on_path=False)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual(start_path + os.pathsep + str(Path(reaper).parent), lines[0])
self.assertEqual(reaper, lines[1])
def test_path_with_reaper_is_left_as_it_is(self):
result, start_path, lines, reaper = self.launch(reaper_on_path=True)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual(start_path, lines[0])
self.assertEqual(reaper, lines[1])
+112
View File
@@ -0,0 +1,112 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0134-touch-click-press-once.patch"
def added_source():
return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
def block(text, start):
begin = text.index(start)
return text[begin:text.index("\n}", begin) + 3]
PREAMBLE = r'''
#include <cassert>
#include <cstdint>
#define WLSERVER_BUTTON_COUNT 7
enum { HOVER = 0, LEFT = 1, RIGHT = 2, PASSTHROUGH = 4 };
static const uint32_t BTN_L = 0x110, BTN_R = 0x111;
'''
MAIN = r'''
struct Seat {
int pressed[2] = {0, 0};
int sent[2] = {0, 0};
int slot(uint32_t b) { return b == BTN_L ? 0 : 1; }
void press(uint32_t b) { if (pressed[slot(b)]++ == 0) sent[slot(b)]++; }
void release(uint32_t b) { if (pressed[slot(b)] > 0 && --pressed[slot(b)] == 0) sent[slot(b)]--; }
};
static uint32_t button_of(int mode) { return mode == LEFT ? BTN_L : mode == RIGHT ? BTN_R : 0; }
struct Server {
bool held[WLSERVER_BUTTON_COUNT] = {};
Seat seat;
void down(int mode) {
uint32_t b = button_of(mode);
if (touch_click_press(held, mode, b)) seat.press(b);
}
void up() {
for (int i = 0; i < WLSERVER_BUTTON_COUNT; i++) {
if (held[i] && button_of(i)) seat.release(button_of(i));
held[i] = false;
}
}
};
int main() {
Server tap;
tap.down(LEFT);
assert(tap.seat.sent[0] == 1);
tap.up();
assert(tap.seat.sent[0] == 0 && tap.seat.pressed[0] == 0);
Server overlap;
overlap.down(LEFT);
overlap.down(LEFT);
overlap.up();
overlap.up();
assert(overlap.seat.pressed[0] == 0 && overlap.seat.sent[0] == 0);
overlap.down(LEFT);
assert(overlap.seat.sent[0] == 1);
overlap.up();
assert(overlap.seat.sent[0] == 0);
Server three;
for (int i = 0; i < 3; i++) three.down(LEFT);
for (int i = 0; i < 3; i++) three.up();
assert(three.seat.pressed[0] == 0);
Server modes;
modes.down(LEFT);
modes.down(RIGHT);
modes.up();
modes.up();
assert(modes.seat.pressed[0] == 0 && modes.seat.pressed[1] == 0);
Server hover;
hover.down(HOVER);
hover.down(PASSTHROUGH);
assert(hover.seat.pressed[0] == 0 && hover.seat.pressed[1] == 0);
bool held[WLSERVER_BUTTON_COUNT] = {};
assert(!touch_click_press(held, -1, BTN_L));
assert(!touch_click_press(held, WLSERVER_BUTTON_COUNT, BTN_L));
return 0;
}
'''
class GamescopeTouchClickTest(unittest.TestCase):
def test_overlapping_touches_release_the_emulated_button(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
source = PREAMBLE + block(added_source(), "static bool touch_click_press") + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "touch_click.cpp"
exe = Path(tmp) / "touch_click"
src.write_text(source)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
if __name__ == "__main__":
unittest.main()
+160
View File
@@ -0,0 +1,160 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
GIB = 1 << 30
PROGRAM = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static void report(const char *call, int fd, int result) {
struct stat st;
if (fstat(fd, &st) != 0) { printf("%s fstat-failed\n", call); return; }
printf("%s %d %lld\n", call, result, (long long)st.st_size);
}
int main(int argc, char **argv) {
const char *dir = argv[1];
long long far = atoll(argv[2]);
char path[4096];
snprintf(path, sizeof(path), "%s/machine-id", dir);
int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fd < 0 || write(fd, "0123456789abcdef0123456789abcdef\n", 33) != 33) return 2;
report("fstat", fd, 0);
report("ftruncate", fd, ftruncate(fd, far));
report("pwrite", fd, pwrite(fd, "x", 1, far) == 1 ? 0 : errno);
close(fd);
snprintf(path, sizeof(path), "%s/reserved", dir);
fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644);
int result = posix_fallocate(fd, 0, 4096);
report("posix_fallocate", fd, result == EOPNOTSUPP ? 0 : result);
result = fallocate(fd, 0, 0, 8192);
report("fallocate", fd, result == 0 || errno == EOPNOTSUPP ? 0 : errno);
int other = open(path, O_RDWR);
struct flock lock = {.l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = far, .l_len = 1};
result = fcntl(fd, F_OFD_SETLK, &lock);
struct flock query = {.l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = far, .l_len = 1};
int queried = fcntl(other, F_OFD_GETLK, &query);
printf("lock %d %d %d %lld\n", result, queried, query.l_type == F_WRLCK, (long long)query.l_start);
close(other);
close(fd);
return 0;
}
"""
LOCKS = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
int fd = open(argv[1], O_RDWR | O_CREAT, 0644);
struct flock lock = {.l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 1};
int set = fcntl(fd, F_SETLK, &lock);
struct flock query = {.l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 1};
int get = fcntl(fd, F_GETLK, &query);
printf("%d %d %s\n", set, get, query.l_type == F_UNLCK ? "unlocked" : "locked");
return 0;
}
"""
NO_LOCKS = r"""
#include <errno.h>
int fcntl(int fd, int cmd, void *arg) { (void)fd; (void)cmd; (void)arg; errno = ENOSYS; return -1; }
int fcntl64(int fd, int cmd, void *arg) { (void)fd; (void)cmd; (void)arg; errno = ENOSYS; return -1; }
"""
def compiles(bits, workdir):
source = Path(workdir) / ("probe%s.c" % bits)
source.write_text("int main(void) { return 0; }\n")
out = Path(workdir) / ("probe%s" % bits)
if subprocess.run(["cc", bits, "-o", str(out), str(source)], capture_output=True).returncode != 0:
return False
return subprocess.run([str(out)], capture_output=True).returncode == 0
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class LargeFilePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
(cls.dir / "program.c").write_text(PROGRAM)
(cls.dir / "locks.c").write_text(LOCKS)
(cls.dir / "nolocks.c").write_text(NO_LOCKS)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def build(self, bits):
if not compiles(bits, self.dir):
self.skipTest("no %s toolchain" % bits)
out = self.dir / bits.lstrip("-")
out.mkdir(exist_ok=True)
lib, program = out / "libblsession.so", out / "program"
if not lib.exists():
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
subprocess.run(["cc", bits, "-shared", "-fPIC", "-O2", "-pthread", "-o", str(lib)] + sources + ["-ldl"], check=True)
subprocess.run(["cc", bits, "-O2", "-D_FILE_OFFSET_BITS=64", "-o", str(program), str(self.dir / "program.c")], check=True)
subprocess.run(["cc", bits, "-O2", "-D_FILE_OFFSET_BITS=64", "-o", str(out / "locks"), str(self.dir / "locks.c")], check=True)
subprocess.run(["cc", bits, "-shared", "-fPIC", "-O2", "-o", str(out / "nolocks.so"), str(self.dir / "nolocks.c")], check=True)
return lib, program
def run_program(self, bits, preload):
lib, program = self.build(bits)
work = Path(tempfile.mkdtemp(dir=self.dir))
env = {k: v for k, v in os.environ.items() if not k.startswith("BL_")}
env.pop("LD_PRELOAD", None)
if preload:
env["LD_PRELOAD"] = str(lib)
result = subprocess.run([str(program), str(work), str(5 * GIB)], env=env, capture_output=True, text=True, timeout=60, check=True)
return result.stdout.splitlines()
def expected(self):
return [
"fstat 0 33",
"ftruncate 0 %d" % (5 * GIB),
"pwrite 0 %d" % (5 * GIB + 1),
"posix_fallocate 0 4096",
"fallocate 0 8192",
"lock 0 0 1 %d" % (5 * GIB),
]
def test_32_bit_large_file_calls_see_the_real_size_and_offsets(self):
self.assertEqual(self.expected(), self.run_program("-m32", preload=True))
def test_32_bit_programs_behave_as_without_the_preload(self):
self.assertEqual(self.run_program("-m32", preload=False), self.run_program("-m32", preload=True))
def locks_without_filesystem_support(self, bits):
lib, program = self.build(bits)
env = {k: v for k, v in os.environ.items() if not k.startswith("BL_")}
env["LD_PRELOAD"] = "%s:%s" % (lib, program.parent / "nolocks.so")
work = Path(tempfile.mkdtemp(dir=self.dir))
result = subprocess.run([str(program.parent / "locks"), str(work / "file")], env=env, capture_output=True, text=True, timeout=60, check=True)
return result.stdout.strip()
def test_locks_on_filesystems_without_lock_support_still_succeed(self):
self.assertEqual("0 0 unlocked", self.locks_without_filesystem_support("-m64"))
self.assertEqual("0 0 unlocked", self.locks_without_filesystem_support("-m32"))
def test_64_bit_programs_are_unchanged(self):
self.assertEqual(self.expected(), self.run_program("-m64", preload=True))
self.assertEqual(self.run_program("-m64", preload=False), self.run_program("-m64", preload=True))
if __name__ == "__main__":
unittest.main()
+56
View File
@@ -0,0 +1,56 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
LAYER = ROOT / "tools/venus/layer"
DEPS = ROOT / "build/layer-deps"
def include(variable, default):
return Path(os.environ.get(variable, str(default)))
class MaliCompatLayerTest(unittest.TestCase):
def test_dual_source_blending_against_a_mock_loader_and_driver(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the Mali compatibility layer test")
vulkan = include("MALI_COMPAT_VULKAN_INCLUDE", DEPS / "vulkan/include")
spirv = include("MALI_COMPAT_SPIRV_INCLUDE", DEPS / "spirv/include")
bcdec = include("MALI_COMPAT_BCDEC_INCLUDE", DEPS / "bcdec")
missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h",
bcdec / "bcdec.h") if not path.is_file()]
if missing:
message = "Vulkan 1.4, SPIR-V and bcdec headers are required: " + ", ".join(missing)
if os.environ.get("CI"):
self.fail(message)
self.skipTest(message)
with tempfile.TemporaryDirectory(prefix="droiddeck-mali-compat-") as tmp:
program = Path(tmp) / "mali-compat-layer"
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
"-UNDEBUG", "-pthread", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv),
"-I", str(bcdec), str(Path(__file__).with_name("mali_compat_layer_test.c")),
*sorted(str(source) for source in LAYER.glob("*.c")), "-o", str(program)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program), tmp], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
self.assertIn("mali compat layer ok", ran.stdout)
self.assertIn("emulating dualSrcBlend for mock", ran.stderr)
validator = shutil.which("spirv-val")
if not validator:
return
for name, environment in (("dual-1.0.spv", "vulkan1.0"), ("plain-1.0.spv", "vulkan1.0"),
("stripped-1.0.spv", "vulkan1.0"), ("stripped-1.4.spv", "vulkan1.2")):
checked = subprocess.run([validator, "--target-env", environment, str(Path(tmp) / name)],
capture_output=True, text=True)
self.assertEqual(checked.returncode, 0, name + ": " + checked.stdout + checked.stderr)
if __name__ == "__main__":
unittest.main()
+228 -27
View File
@@ -2,7 +2,7 @@ from pathlib import Path
import tempfile
import unittest
from tools.tests.test_client_zram_focus import function_source, run_bash
from tools.tests.test_client_zram_focus import SCRIPT, function_source, run_bash
class MemoryPressureTest(unittest.TestCase):
@@ -20,8 +20,8 @@ class MemoryPressureTest(unittest.TestCase):
def run_policy(self, body):
functions = '\n'.join(function_source(name) for name in (
'bl_memory_read', 'bl_memory_tight', 'bl_client_can_pageout',
'bl_client_can_readback', 'bl_client_pressure'))
'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', 'bl_client_can_pageout',
'bl_client_can_readback', 'bl_client_pressure', 'bl_client_pressure_result', 'bl_zram_has_room'))
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
harness = '''
@@ -29,7 +29,7 @@ set -u
_bl_pids=(123) _bl_game=1 _bl_packed=-1 _bl_pressure_at=-1 _bl_pressure_backoff=30
rss=$((384 * 1024)) client_swap=$((512 * 1024)) reclaimed=$((128 * 1024))
step() { :; }
bl_zram_usage() { _bl_rss=$rss _bl_swap=$client_swap; }
bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$client_swap; }
bl_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _bl_pageout_complete=${pageout_complete:-1}; }
''' + functions + '\nbl_memory_read\n' + body
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
@@ -80,6 +80,13 @@ if bl_client_can_readback; then echo yes; else echo no; fi
self.assertEqual(['no'], self.run_policy('''
bl_client_pressure
if bl_client_can_pageout; then echo yes; else echo no; fi
'''))
def test_client_swap_budget_excludes_file_backed_memory(self):
self.memory(swap_free=1536)
self.assertEqual(['send:1:client'], self.run_policy('''
rss=$((2048 * 1024)) anon=$((256 * 1024))
bl_client_pressure
'''))
def test_without_swap_automatic_pageout_is_disabled(self):
@@ -152,20 +159,22 @@ class SessionPressureTest(unittest.TestCase):
def run_policy(self, body):
functions = '\n'.join(function_source(name) for name in (
'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', 'bl_low_ram',
'bl_session_pressure', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback'))
'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical',
'bl_client_can_pageout', 'bl_client_pressure', 'bl_client_pressure_result',
'bl_session_pressure', 'bl_zram_has_room', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback'))
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
harness = '''
set -u
_bl_game=1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() _bl_pids=(999)
_bl_pressure_at=-1 _bl_packed=-1
rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive=999 started=100 complete=1
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1
rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive="999 321 654" started=100 complete=1
step() { :; }
bl_game_focused() { [ "${focused:-1}" = 1 ]; }
bl_proc_start() { _bl_start=; case " $alive " in *" $1 "*) _bl_start=$started; return 0 ;; esac; return 1; }
nap() { echo "nap:$1"; }
bl_session_others() { _bl_session=(321 654); }
bl_zram_usage() { _bl_rss=$rss _bl_swap=$swap; }
bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$swap; }
bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); _bl_pageout_complete=$complete; }
''' + functions + '\nbl_memory_read\n' + body
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
@@ -174,37 +183,103 @@ bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed
return result.stdout.splitlines()
def test_low_headroom_compresses_the_game_session_at_most_every_30_seconds(self):
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
SECONDS=0; bl_session_pressure
SECONDS=10; bl_session_pressure
SECONDS=29; bl_session_pressure
SECONDS=30; bl_session_pressure
'''))
def test_twelve_gigabyte_devices_are_included_and_larger_ones_are_not(self):
for total, expected in ((11264, ['send:1:game']), (12288, ['send:1:game']), (15360, [])):
def test_pressure_policy_is_independent_of_ram_size(self):
for total, expected in ((11264, ['send:1:session']), (12288, ['send:1:session']), (16384, ['send:1:session'])):
with self.subTest(total=total):
self.memory(total=total)
self.assertEqual(expected, self.run_policy('bl_session_pressure'))
def test_large_device_with_real_headroom_does_not_reclaim(self):
self.memory(total=16384, available=5120, psi='12.34')
self.assertEqual([], self.run_policy('bl_session_pressure'))
def test_large_device_with_psi_and_moderate_headroom_reclaims(self):
self.memory(total=16384, available=3072, psi='1.23')
self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure'))
def test_no_game_does_not_compress_the_session(self):
self.assertEqual([], self.run_policy('_bl_game=0; bl_session_pressure'))
def test_disabled_idle_compression_does_not_compress_the_session(self):
self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
def test_disabled_idle_compression_signals_only_launcher_processes(self):
sender = (function_source('bl_zram_send') + '\n' + function_source('bl_zram_finish')).replace('/tmp/.bl-zram', str(self.root / 'control'))
self.assertEqual(['kill:-URG 999 998', 'mode:1'], self.run_policy('''
_bl_pids=(999 998)
kill() { echo "kill:$*"; }
bl_zram_wait() { _bl_pageout_complete=1; }
bl_zram_scan() { :; }
''' + sender + '''
BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure
echo "mode:$(cat ''' + str(self.root / 'control') + ''')"
'''))
def test_disabled_idle_compression_reclaims_only_the_launcher_before_focus(self):
self.memory(available=1700)
self.assertEqual(['send:1:client'], self.run_policy('''
BL_ZRAM_IDLE=0 focused=0
bl_client_pressure
bl_session_pressure
'''))
def test_disabled_idle_compression_respects_launcher_setting_and_threshold(self):
self.memory(available=1700)
self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0 BL_ZRAM_CLIENT=0; bl_client_pressure; bl_session_pressure'))
self.memory(available=1900)
self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
def test_game_reclaim_requires_focus(self):
self.assertEqual([], self.run_policy('focused=0; bl_session_pressure'))
def test_game_reclaim_runs_when_focus_is_unknown(self):
launch = self.root / 'launch'
(launch / 'agent').mkdir(parents=True)
body = function_source('bl_game_focused') + f'\nBL_LAUNCH_DIR={launch} _bl_apps=7\n'
self.assertEqual(['send:1:session'], self.run_policy(body + 'bl_session_pressure'))
(launch / 'agent' / 'focus.json').write_text('{"focusedApp": 9}')
self.assertEqual([], self.run_policy(body + 'bl_session_pressure'))
self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused'))
(launch / 'agent' / 'focus.json').unlink()
self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused'))
def test_launcher_pressure_remains_available_on_larger_devices(self):
self.memory(total=15360, available=1400)
self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
def test_enough_available_memory_does_not_compress_even_with_stalls(self):
self.memory(available=3072, psi='5.00')
self.assertEqual([], self.run_policy('bl_session_pressure'))
def test_stalls_with_moderate_headroom_compress_before_the_hard_limit(self):
self.memory(available=2048, psi='1.50')
self.assertEqual(['send:1:game'], self.run_policy('bl_session_pressure'))
self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure'))
def test_moderate_headroom_without_stalls_waits(self):
self.memory(available=2048)
self.assertEqual([], self.run_policy('bl_session_pressure'))
def test_same_second_memory_read_preserves_the_pressure_baseline(self):
self.memory(available=2048)
meminfo = self.root / 'meminfo'
self.assertEqual(['1048576:524288:2097152'], self.run_policy(f'''
SECONDS=100
_bl_sample_at=100 _bl_sample_available=2097152 _bl_growth=0 _bl_fall=524288
sed -i 's/MemAvailable: 2097152 kB/MemAvailable: 1048576 kB/' {meminfo}
bl_memory_read
echo "$_bl_available:$_bl_fall:$_bl_sample_available"
'''))
def test_game_reading_back_most_of_a_pageout_skips_and_doubles_the_wait(self):
self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game', 'backoff:60',
'send:1:game', 'backoff:30'], self.run_policy('''
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:60',
'send:1:session', 'backoff:30'], self.run_policy('''
pushed=$((512 * 1024))
SECONDS=0; bl_session_pressure
swap=$((swap / 4))
@@ -226,7 +301,7 @@ echo "backoff:$_bl_tier_backoff"
def test_nearly_out_of_memory_ignores_the_backoff_but_keeps_30_seconds(self):
self.memory(available=512)
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
_bl_tier_backoff=300
SECONDS=0; bl_session_pressure
SECONDS=20; bl_session_pressure
@@ -235,7 +310,7 @@ SECONDS=30; bl_session_pressure
def test_nearly_out_of_memory_still_backs_off_when_the_game_reads_its_pageout_back(self):
self.memory(available=512)
self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game'], self.run_policy('''
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session'], self.run_policy('''
SECONDS=0; bl_session_pressure
swap=0
SECONDS=30; bl_session_pressure
@@ -247,7 +322,7 @@ SECONDS=90; bl_session_pressure
def test_nearly_out_of_memory_retries_a_skipped_pageout_after_30_seconds(self):
self.memory(available=512)
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
SECONDS=0; bl_session_pressure
swap=0
SECONDS=30; bl_session_pressure
@@ -263,6 +338,24 @@ SECONDS=360; bl_session_pressure
self.memory(swap_free=1536, swap_total=2048)
self.assertEqual([], self.run_policy('bl_session_pressure'))
def test_file_backed_resident_memory_does_not_consume_the_swap_budget(self):
self.memory(swap_free=3088, swap_total=6144)
self.assertEqual(['send:1:session'], self.run_policy('''
rss=$((4096 * 1024)) anon=$((1024 * 1024))
bl_session_pressure
'''))
def test_anonymous_memory_and_pending_client_still_need_the_full_swap_reserve(self):
self.memory(swap_free=3088, swap_total=6144)
self.assertEqual([], self.run_policy('''
rss=$((4096 * 1024)) anon=$((2048 * 1024))
bl_session_pressure
'''))
self.assertEqual([], self.run_policy('''
rss=$((4096 * 1024)) anon=$((1536 * 1024)) _bl_client_reserve=$((512 * 1024))
bl_session_pressure
'''))
def test_small_session_is_left_alone(self):
self.assertEqual([], self.run_policy('rss=$((128 * 1024)); bl_session_pressure'))
@@ -275,10 +368,10 @@ SECONDS=360; bl_session_pressure
self.assertEqual(['nap:5'], self.run_policy('bl_watch_nap'))
self.assertEqual(['nap:5'], self.run_policy('_bl_game=0; bl_watch_nap'))
def test_one_push_compresses_the_game_and_the_launcher_and_restarts_the_launcher_wait(self):
self.assertEqual(['send:1:game', 'pids:321 654 999', 'client:0:0'], self.run_policy('''
def test_session_push_preserves_client_timestamps(self):
self.assertEqual(['send:1:session', 'pids:321 654', 'client:-1:-1'], self.run_policy('''
SECONDS=0; bl_session_pressure
bl_zram_pick game; echo "pids:${_pids[*]}"
bl_zram_pick session; echo "pids:${_pids[*]}"
echo "client:$_bl_pressure_at:$_bl_packed"
'''))
@@ -286,19 +379,19 @@ echo "client:$_bl_pressure_at:$_bl_packed"
self.assertEqual(['pids:321 654', 'client:-1:-1'], self.run_policy('''
BL_ZRAM_CLIENT=0
SECONDS=0; bl_session_pressure
bl_zram_pick game; echo "pids:${_pids[*]}"
bl_zram_pick session; echo "pids:${_pids[*]}"
echo "client:$_bl_pressure_at:$_bl_packed"
''')[1:])
def test_low_ram_devices_compress_with_a_quarter_of_memory_left(self):
self.memory(available=1700)
self.assertEqual(['send:1:game'], self.run_policy('bl_session_pressure'))
self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure'))
self.memory(available=1900)
self.assertEqual([], self.run_policy('bl_session_pressure'))
def test_a_compressed_process_that_exits_is_not_counted_as_read_back(self):
self.assertEqual(['send:1:game', 'send:1:game', 'backoff:30'], self.run_policy('''
self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy('''
SECONDS=0; bl_session_pressure
alive=""; swap=0
SECONDS=30; bl_session_pressure
@@ -306,7 +399,7 @@ echo "backoff:$_bl_tier_backoff"
'''))
def test_a_process_that_starts_after_a_pageout_is_not_in_its_read_back(self):
self.assertEqual(['send:1:game', 'targets:999', 'send:1:game', 'backoff:30'], self.run_policy('''
self.assertEqual(['send:1:session', 'targets:321 654', 'send:1:session', 'backoff:30'], self.run_policy('''
SECONDS=0; bl_session_pressure
echo "targets:${_bl_tier_targets[*]}"
alive="999 1234"
@@ -315,7 +408,7 @@ echo "backoff:$_bl_tier_backoff"
'''))
def test_an_incomplete_pageout_does_not_restart_the_launcher_wait(self):
self.assertEqual(['send:1:game', 'client:-1:-1'], self.run_policy('''
self.assertEqual(['send:1:session', 'client:-1:-1'], self.run_policy('''
complete=0
SECONDS=0; bl_session_pressure
echo "client:$_bl_pressure_at:$_bl_packed"
@@ -323,7 +416,7 @@ echo "client:$_bl_pressure_at:$_bl_packed"
def test_a_reused_process_id_is_not_counted_as_read_back(self):
self.assertEqual(['send:1:game', 'send:1:game', 'backoff:30'], self.run_policy('''
self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy('''
SECONDS=0; bl_session_pressure
started=200; swap=0
SECONDS=30; bl_session_pressure
@@ -344,5 +437,113 @@ echo "backoff:$_bl_tier_backoff"
self.assertEqual(['gone'], result.stdout.split())
class ReclaimDispatchTest(unittest.TestCase):
def run_cycle(self, client=1, game=1, anonymous=384, complete=1, reclaimed=128, body=None, available=1024, fall=0, tick=0):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'meminfo').write_text(
f'MemTotal: 7340032 kB\nMemAvailable: {available * 1024} kB\n'
'SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n')
(root / 'pressure').write_text('some avg10=0.00 avg60=0.00 avg300=0.00 total=0\n')
names = ('bl_memory_read', 'bl_memory_tight', 'bl_memory_critical',
'bl_zram_has_room', 'bl_client_can_pageout', 'bl_client_pressure',
'bl_client_pressure_result', 'bl_client_pressure_finish',
'bl_session_pressure', 'bl_zram_send', 'bl_zram_finish', 'bl_zram_pick')
source = '\n'.join(function_source(name) for name in names)
source = source.replace('/proc/meminfo', str(root / 'meminfo'))
source = source.replace('/proc/pressure/memory', str(root / 'pressure'))
source = source.replace('/tmp/.bl-zram', str(root / 'ctl'))
monitor = SCRIPT.read_text()
start = monitor.index(' _bl_preserved_growth=$_bl_growth', monitor.index('while kill -0 $$'))
stop = monitor.index(' if [ "$_bl_game" = 1 ] && bl_game_focused', start)
cycle = monitor[start:stop] if body is None else body
script = f'''
set -u
BL_ZRAM_CLIENT={client} _bl_game={game} _bl_pids=(123) _bl_others=(321)
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1
_bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0
_bl_client_reserve=0 client_rss=393216 client_anon={anonymous * 1024}
step() {{ :; }}
bl_session_others() {{ _bl_session=(321); }}
bl_zram_scan() {{ _bl_pids=(456); }}
nap() {{ echo "nap:$*:at:$NOW"; }}
bl_zram_usage() {{
if [ "$1" = 123 ]; then
_bl_rss=$client_rss _bl_anon=$client_anon _bl_swap=0
else
_bl_rss=3145728 _bl_anon=1572864 _bl_swap=0
fi
}}
kill() {{ echo "signal:$*:at:$NOW"; NOW=$((NOW + {tick})); }}
bl_zram_wait() {{
echo "wait:$*:at:$NOW"
NOW=$((NOW + 12))
_bl_pageout_complete={complete}
[ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024}))
}}
bl_tier_note() {{ :; }}
bl_game_focused() {{ :; }}
''' + source + f'''
bl_memory_read
_bl_fall={fall * 1024}
''' + cycle + '''
echo "client:$_bl_pressure_backoff:${_bl_client_reserve:-0}:${_bl_client_pending:-0}"
'''
result = run_bash('NOW=0\n' + script.replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
return result.stdout.splitlines()
def test_both_requests_are_sent_before_either_wait(self):
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0',
'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'], self.run_cycle())
def test_disabled_client_is_never_signalled_or_waited_for(self):
self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'],
self.run_cycle(client=0))
def test_no_game_requests_nothing(self):
self.assertEqual(['client:30:0:0'], self.run_cycle(game=0))
def test_a_client_with_no_anonymous_pages_still_finishes_its_request(self):
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0',
'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'],
self.run_cycle(anonymous=0))
def test_falling_headroom_survives_a_tick_between_requests(self):
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:1',
'wait:321:at:2', 'wait:123:at:14', 'client:30:0:0'],
self.run_cycle(available=2304, fall=512, tick=1))
def test_deferred_ineffective_reclaim_still_doubles_the_backoff(self):
self.assertEqual('client:60:0:0', self.run_cycle(reclaimed=0)[-1])
def test_deferred_incomplete_reclaim_does_not_double_the_backoff(self):
self.assertEqual('client:30:0:0', self.run_cycle(reclaimed=0, complete=0)[-1])
def test_explicit_combined_send_keeps_its_synchronous_wait(self):
self.assertEqual(['signal:-URG 321 123:at:0', 'wait:321 123:at:0', 'client:30:0:0'],
self.run_cycle(body='bl_zram_send 1 cap game\n'))
self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'],
self.run_cycle(client=0, body='bl_zram_send 1 cap game\n'))
def test_readback_keeps_its_synchronous_delay(self):
self.assertEqual(['signal:-URG 123:at:0', 'nap:5:at:0', 'client:30:0:0'],
self.run_cycle(body='bl_zram_send 0 readback client\n'))
def test_usage_sums_anonymous_rss_and_falls_back_per_process(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for pid, contents in ((123, 'VmRSS: 2000 kB\nRssAnon: 300 kB\nVmSwap: 100 kB\n'),
(321, 'VmRSS: 4000 kB\nVmSwap: 200 kB\n'),
(654, 'VmRSS: 1000 kB\nRssAnon: 0 kB\n')):
(root / str(pid)).mkdir()
(root / str(pid) / 'status').write_text(contents)
source = function_source('bl_zram_usage').replace('/proc/', str(root) + '/')
result = run_bash(source + '\nbl_zram_usage 123 321 654 > /dev/null; echo "$_bl_rss:$_bl_anon:$_bl_swap"')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('7000:4300:300', result.stdout.strip())
if __name__ == '__main__':
unittest.main()
+224
View File
@@ -0,0 +1,224 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
char cwd[4096];
for (int i = 1; i < argc; i++) {
struct stat st;
if (strncmp(argv[i], "cd:", 3) == 0) {
int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL;
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
continue;
}
if (strncmp(argv[i], "at:", 3) == 0) {
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
printf("%s\t%d\t%d\n", argv[i], fstatat(AT_FDCWD, argv[i] + 3, &st, 0) == 0, dfd >= 0);
if (dfd >= 0) close(dfd);
continue;
}
if (strncmp(argv[i], "ls:", 3) == 0) {
DIR *dir = opendir(argv[i] + 3);
char names[1024] = "";
struct dirent *de;
while (dir && (de = readdir(dir)) != NULL) {
if (de->d_name[0] == '.') continue;
if (names[0]) strncat(names, ",", sizeof(names) - strlen(names) - 1);
strncat(names, de->d_name, sizeof(names) - strlen(names) - 1);
}
if (dir) closedir(dir);
printf("%s\t%s\n", argv[i], dir ? names : "-");
continue;
}
int fd = open(argv[i], O_RDONLY);
char data[64] = "-";
if (fd >= 0) {
ssize_t n = read(fd, data, sizeof(data) - 1);
data[n > 0 ? n : 0] = 0;
close(fd);
}
printf("%s\t%d\t%s\n", argv[i], stat(argv[i], &st) == 0, data);
}
return 0;
}
"""
GAME = "/mnt/library/Some Game"
class NativeHookMountTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
cls.probe = tmp / "probe"
cls.root = tmp / "root"
cls.library = tmp / "storage/PC GAMES"
(cls.root / "etc").mkdir(parents=True)
(cls.root / "etc/hostname").write_text("rootfs")
(cls.root / "mnt/library/Some Game").mkdir(parents=True)
(cls.root / "mnt/library/Some Game/game.txt").write_text("mount point")
(cls.library / "Some Game").mkdir(parents=True)
(cls.library / "Some Game/game.txt").write_text("library")
for name, target in (("native", str(cls.root)), ("guest", "/")):
devices = cls.root / "pfx" / name / "dosdevices"
devices.mkdir(parents=True)
os.symlink(target, devices / "z:")
relinked = cls.root / "pfx/relinked"
(relinked / "dosdevices").mkdir(parents=True)
(relinked / "drive_c").mkdir()
(relinked / "drive_c/c.txt").write_text("drive c")
os.symlink(os.path.relpath(cls.root, relinked / "dosdevices"), relinked / "dosdevices/z:")
os.symlink("../drive_c", relinked / "dosdevices/c:")
copied = cls.root / "pfx/copied/dosdevices"
copied.mkdir(parents=True)
os.symlink("../" * 12 + "..", copied / "z:")
elsewhere = tmp / "elsewhere"
(elsewhere / "outside/pfx/dosdevices").mkdir(parents=True)
(elsewhere / "mnt/library/Some Game").mkdir(parents=True)
(elsewhere / "mnt/library/Some Game/game.txt").write_text("elsewhere")
os.symlink("../../..", elsewhere / "outside/pfx/dosdevices/z:")
os.symlink(str(elsewhere / "outside/pfx"), cls.root / "pfx/outside")
cls.private = tmp / "private"
private_pfx = cls.private / "123/pfx/dosdevices"
private_pfx.mkdir(parents=True)
os.symlink(os.path.relpath("/", "/mnt/private/123/pfx/dosdevices"), private_pfx / "z:")
private_copy = cls.private / "456/pfx/dosdevices"
private_copy.mkdir(parents=True)
os.symlink("../" * 12 + "..", private_copy / "z:")
cls.eqlen_src = tmp / "eqsrcdir"
cls.eqlen_dst = "/" + "d" * (len(str(cls.eqlen_src)) - 1)
eqlen_pfx = cls.eqlen_src / "123/pfx/dosdevices"
eqlen_pfx.mkdir(parents=True)
os.symlink(os.path.relpath("/", f"{cls.eqlen_dst}/123/pfx/dosdevices"), eqlen_pfx / "z:")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, *args):
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *args], env=env, capture_output=True, text=True, timeout=120,
cwd=self.tmp.name)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self):
path = f"/pfx/native/dosdevices/z:{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
def test_working_directory_through_a_drive_link_is_the_mount(self):
arg = f"cd:/pfx/native/dosdevices/z:{GAME}/"
self.assertEqual(self.run_probe(arg)[arg], [GAME])
def test_rootfs_path_under_a_mount_point_reaches_the_mount(self):
path = f"{self.root}{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
def test_guest_drive_link_is_unchanged(self):
path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
def test_rootfs_paths_outside_mounts_are_unchanged(self):
paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"]
result = self.run_probe(*paths)
for path in paths:
self.assertEqual(result[path], ["1", "rootfs"], path)
def test_wine_lookup_steps_reach_the_mount(self):
for pfx in ("/pfx/native", "/pfx/guest", "/pfx/relinked", f"{self.root}/pfx/native", f"{self.root}/pfx/guest",
f"{self.root}/pfx/relinked"):
drive = f"{pfx}/dosdevices/z:"
args = [f"at:{drive}{GAME}/", f"at:{drive}{GAME}", f"ls:{drive}/mnt/library", f"ls:{drive}{GAME}"]
result = self.run_probe(*args)
self.assertEqual(result[args[0]], ["1", "1"], pfx)
self.assertEqual(result[args[1]], ["1", "1"], pfx)
self.assertEqual(result[args[2]], ["Some Game"], pfx)
self.assertEqual(result[args[3]], ["game.txt"], pfx)
def test_relative_drive_link_reaches_the_mount(self):
path = f"/pfx/relinked/dosdevices/z:{GAME}/game.txt"
cd = f"cd:/pfx/relinked/dosdevices/z:{GAME}/"
result = self.run_probe(path, cd)
self.assertEqual(result[path], ["1", "library"])
self.assertEqual(result[cd], [GAME])
def test_relative_links_outside_mounts_are_unchanged(self):
paths = ["/pfx/relinked/dosdevices/z:/etc/hostname", "/pfx/relinked/dosdevices/c:/c.txt",
f"{self.root}/pfx/relinked/dosdevices/c:/c.txt"]
result = self.run_probe(*paths)
self.assertEqual(result[paths[0]], ["1", "rootfs"])
self.assertEqual(result[paths[1]], ["1", "drive c"])
self.assertEqual(result[paths[2]], ["1", "drive c"])
def test_suffix_after_a_relative_link_is_not_collapsed(self):
path = "/pfx/relinked/dosdevices/z:/mnt/library/missing/../Some Game/game.txt"
self.assertEqual(self.run_probe(path)[path], ["0", "-"])
def test_relative_drive_link_climbing_past_the_root_reaches_the_mount(self):
path = f"/pfx/copied/dosdevices/z:{GAME}/game.txt"
cd = f"cd:/pfx/copied/dosdevices/z:{GAME}/"
result = self.run_probe(path, cd)
self.assertEqual(result[path], ["1", "library"])
self.assertEqual(result[cd], [GAME])
def test_relative_link_climbing_past_the_root_stays_in_the_rootfs(self):
path = "/pfx/copied/dosdevices/z:/etc/hostname"
self.assertEqual(self.run_probe(path)[path], ["1", "rootfs"])
def test_relative_link_is_resolved_from_its_real_directory(self):
path = f"/pfx/outside/dosdevices/z:{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "elsewhere"])
def test_drive_link_in_a_bound_prefix_reaches_the_mount(self):
path = f"/mnt/private/123/pfx/dosdevices/z:{GAME}/game.txt"
cd = f"cd:/mnt/private/123/pfx/dosdevices/z:{GAME}/"
result = self.run_probe(path, cd)
self.assertEqual(result[path], ["1", "library"])
self.assertEqual(result[cd], [GAME])
def test_drive_link_copied_into_a_bound_prefix_reaches_the_mount(self):
path = f"/mnt/private/456/pfx/dosdevices/z:{GAME}/game.txt"
cd = f"cd:/mnt/private/456/pfx/dosdevices/z:{GAME}/"
result = self.run_probe(path, cd)
self.assertEqual(result[path], ["1", "library"])
self.assertEqual(result[cd], [GAME])
def test_drive_link_in_equal_length_bound_prefix_reaches_the_mount(self):
path = f"{self.eqlen_dst}/123/pfx/dosdevices/z:{GAME}/game.txt"
cd = f"cd:{self.eqlen_dst}/123/pfx/dosdevices/z:{GAME}/"
result = self.run_probe(path, cd)
self.assertEqual(result[path], ["1", "library"])
self.assertEqual(result[cd], [GAME])
if __name__ == "__main__":
unittest.main()
+190 -7
View File
@@ -1,5 +1,6 @@
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
@@ -25,6 +26,136 @@ int main(int argc, char **argv) {
}
"""
IMAGE = r"""
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
static void run(const char *name, void *code, size_t len, int prot) {
int error = mprotect(code, len, prot) ? errno : 0;
printf("%s %d %d\n", name, error, error ? -1 : ((int (*)(void))code)());
}
int main(int argc, char **argv) {
if (argc < 2) return 2;
size_t page = (size_t)sysconf(_SC_PAGESIZE);
int fd = open(argv[1], O_RDONLY);
run("private", mmap(NULL, page, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0), page, PROT_READ | PROT_EXEC);
run("hidden", mmap(NULL, page, PROT_NONE, MAP_PRIVATE, fd, 0), page, PROT_READ | PROT_EXEC);
char *mixed = mmap(NULL, 2 * page, PROT_READ, MAP_PRIVATE, fd, 0);
if (mixed == MAP_FAILED || mmap(mixed + page, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) != mixed + page)
return 3;
run("mixed", mixed, page + 1, PROT_READ | PROT_EXEC);
char *past = mmap(NULL, 3 * page, PROT_NONE, MAP_PRIVATE, fd, 0);
if (past == MAP_FAILED || mmap(past + page, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) != past + page ||
mmap(past + 2 * page, page, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, page) != past + 2 * page)
return 3;
int error = mprotect(past, 3 * page, PROT_READ | PROT_EXEC) ? errno : 0;
past[page] = 7;
printf("past %d %d\n", error, past[page]);
error = mprotect(mmap(NULL, page, PROT_READ, MAP_SHARED, fd, 0), page, PROT_READ | PROT_EXEC) ? errno : 0;
printf("shared %d\n", error);
return 0;
}
"""
FAILURES = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdlib.h>
static void *destination;
static int fixed_calls, remap_calls, protect_calls;
void arm(void *addr) { destination = addr; }
int counts(int which) { return which == 0 ? fixed_calls : which == 1 ? remap_calls : protect_calls; }
int mprotect(void *addr, size_t len, int prot) {
int (*next)(void *, size_t, int) = dlsym(RTLD_NEXT, "mprotect");
if (addr == destination && (prot & PROT_EXEC)) {
protect_calls++;
errno = EACCES;
return -1;
}
if (destination && (prot & PROT_EXEC) && getenv("FAIL_COPY")) {
errno = EACCES;
return -1;
}
return next(addr, len, prot);
}
void *mremap(void *addr, size_t old, size_t size, int flags, ...) {
remap_calls++;
errno = ENOMEM;
return MAP_FAILED;
}
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset) {
void *(*next)(void *, size_t, int, int, int, off_t) = dlsym(RTLD_NEXT, "mmap");
if (addr == destination && (flags & MAP_FIXED)) {
fixed_calls++;
if (fd >= 0 && !getenv("ALLOW_FIXED")) {
errno = ENOMEM;
return MAP_FAILED;
}
}
return next(addr, len, prot, flags, fd, offset);
}
"""
FAILURE_IMAGE = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
static void mapping(void *addr, char *out) {
FILE *maps = fopen("/proc/self/maps", "r");
char line[1024];
unsigned long lo, hi;
out[0] = 0;
while (fgets(line, sizeof line, maps))
if (sscanf(line, "%lx-%lx", &lo, &hi) == 2 && (uintptr_t)addr >= lo && (uintptr_t)addr < hi) {
strcpy(out, line);
break;
}
fclose(maps);
}
int main(int argc, char **argv) {
if (argc < 2) return 2;
int anonymous = argc > 2;
size_t page = sysconf(_SC_PAGESIZE);
int fd = open(argv[1], O_RDONLY);
char *addr = anonymous ? mmap(NULL, page * 2, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
: mmap(NULL, page * 2, PROT_NONE, MAP_PRIVATE, fd, 0);
if (addr == MAP_FAILED || (!anonymous && mmap(addr + page, page, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) != addr + page)) return 3;
addr[page] = 73;
char before[1024], after[1024], tail_before[1024], tail_after[1024];
mapping(addr, before);
mapping(addr + page, tail_before);
void (*arm)(void *) = dlsym(RTLD_DEFAULT, "arm");
int (*counts)(int) = dlsym(RTLD_DEFAULT, "counts");
if (!arm || !counts) return 4;
arm(addr);
int result = mprotect(addr, 2 * page, PROT_READ | PROT_EXEC);
int error = errno;
mapping(addr, after);
mapping(addr + page, tail_after);
printf("result %d %d preserved %d %d tail %d calls %d %d %d\n", result, error,
!strcmp(before, after), !strcmp(tail_before, tail_after), addr[page], counts(0), counts(1), counts(2));
if (!result) printf("execute %d\n", ((int (*)(void))addr)());
return 0;
}
"""
RETURN_42 = {"x86_64": bytes.fromhex("b82a000000c3"), "aarch64": bytes.fromhex("40058052c0035fd6")}
def noexec_folder():
for folder in ("/run/lock", "/dev/shm", "/run/user/%d" % os.getuid()):
@@ -36,7 +167,7 @@ def noexec_folder():
return None
@unittest.skipUnless(shutil.which("cc") and noexec_folder(), "needs cc and a writable noexec mount")
@unittest.skipUnless(shutil.which("cc"), "needs cc")
class NoexecPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
@@ -48,26 +179,78 @@ class NoexecPreloadTest(unittest.TestCase):
source.write_text(PROGRAM)
for name in ("FEX", "game"):
subprocess.run(["cc", "-O2", "-o", str(cls.tmp / name), str(source)], check=True)
image = cls.tmp / "image.c"
image.write_text(IMAGE)
subprocess.run(["cc", "-O2", "-o", str(cls.tmp / "wine"), str(image)], check=True)
failures = cls.tmp / "failures.c"
failures.write_text(FAILURES)
cls.failures = cls.tmp / "failures.so"
subprocess.run(["cc", "-Wall", "-Werror", "-shared", "-fPIC", "-o", str(cls.failures), str(failures), "-ldl"], check=True)
failure_image = cls.tmp / "failure_image.c"
failure_image.write_text(FAILURE_IMAGE)
subprocess.run(["cc", "-Wall", "-Werror", "-o", str(cls.tmp / "failure_image"), str(failure_image), "-ldl"], check=True)
cls.target = Path(tempfile.mkdtemp(dir=noexec_folder())) / "Game.x86_64"
cls.target.write_bytes(b"\x7fELF" + bytes(4092))
cls.code = cls.target.parent / "game.exe"
cls.code.write_bytes(RETURN_42.get(platform.machine(), b"").ljust(os.sysconf("SC_PAGE_SIZE"), b"\0"))
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
shutil.rmtree(cls.target.parent, ignore_errors=True)
def run_as(self, name, preload=True):
def run_as(self, name, preload=True, target=None, lines=3):
env = dict(os.environ, LD_PRELOAD=str(self.lib)) if preload else {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
result = subprocess.run([str(self.tmp / name), str(self.target)], env=env, capture_output=True, text=True, check=True)
return result.stdout.split("\n")[:3]
result = subprocess.run([str(self.tmp / name), str(target or self.target)], env=env, capture_output=True, text=True, check=True)
return result.stdout.split("\n")[:lines]
def test_failed_replacement_preserves_original_mappings_and_permissions(self):
env = dict(os.environ, LD_PRELOAD=f"{self.lib}:{self.failures}")
result = subprocess.run([str(self.tmp / "failure_image"), str(self.code)], env=env,
capture_output=True, text=True, check=True)
self.assertEqual(result.stdout.strip(), "result -1 13 preserved 1 1 tail 73 calls 1 0 1")
def test_failed_copy_protection_preserves_original_mappings(self):
env = dict(os.environ, LD_PRELOAD=f"{self.lib}:{self.failures}", FAIL_COPY="1")
result = subprocess.run([str(self.tmp / "failure_image"), str(self.code)], env=env,
capture_output=True, text=True, check=True)
self.assertEqual(result.stdout.strip(), "result -1 13 preserved 1 1 tail 73 calls 0 0 1")
def test_anonymous_memory_is_never_replaced(self):
env = dict(os.environ, LD_PRELOAD=f"{self.lib}:{self.failures}", ALLOW_FIXED="1")
result = subprocess.run([str(self.tmp / "failure_image"), str(self.code), "anonymous"], env=env,
capture_output=True, text=True, check=True)
self.assertEqual(result.stdout.strip(), "result -1 13 preserved 1 1 tail 73 calls 0 0 1")
@unittest.skipUnless(platform.machine() in RETURN_42, "needs a known host instruction set")
def test_replacement_installs_executable_pages_without_final_mprotect(self):
env = dict(os.environ, LD_PRELOAD=f"{self.lib}:{self.failures}", ALLOW_FIXED="1")
result = subprocess.run([str(self.tmp / "failure_image"), str(self.code)], env=env,
capture_output=True, text=True, check=True)
self.assertIn("preserved 0 0 tail 73 calls 1 0 1", result.stdout)
self.assertEqual(result.stdout.splitlines()[-1], "execute 42")
@unittest.skipUnless(noexec_folder(), "needs a writable noexec mount")
def test_fex_maps_a_program_on_noexec_storage(self):
self.assertEqual(self.run_as("FEX"), ["map 0", "protect 0", "read \x7f"])
@unittest.skipUnless(noexec_folder(), "needs a writable noexec mount")
def test_the_kernel_still_refuses_everyone_else(self):
for refused in (self.run_as("game"), self.run_as("FEX", preload=False)):
self.assertIn(refused[0], ("map 1", "map 13"))
self.assertEqual(refused[1:], ["protect 13", "read -"])
refused = self.run_as("FEX", preload=False)
self.assertIn(refused[0], ("map 1", "map 13"))
self.assertEqual(refused[1:], ["protect 13", "read -"])
self.assertIn(self.run_as("game")[0], ("map 1", "map 13"))
@unittest.skipUnless(platform.machine() in RETURN_42, "needs a known host instruction set")
@unittest.skipUnless(noexec_folder(), "needs a writable noexec mount")
def test_private_image_pages_become_executable_copies(self):
self.assertEqual(self.run_as("wine", target=self.code, lines=5), ["private 0 42", "hidden 0 42", "mixed 0 42", "past 13 7", "shared 13"])
@unittest.skipUnless(platform.machine() in RETURN_42, "needs a known host instruction set")
@unittest.skipUnless(noexec_folder(), "needs a writable noexec mount")
def test_image_pages_stay_refused_without_the_preload(self):
self.assertEqual(self.run_as("wine", preload=False, target=self.code, lines=5),
["private 13 -1", "hidden 13 -1", "mixed 13 -1", "past 13 7", "shared 13"])
if __name__ == "__main__":
Loaded 100 of 654 files, more files were not shown because too many files have changed in this diff. Show more