Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

fix: prevent unsafe cleanup and recover partial launcher installs

mikey92f383f726f7c4
diff --git a/README.ko.md b/README.ko.md
index 4a20318e3ee..c4c19325e42 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -64,7 +64,7 @@ brew install BCD1210/soju/soju
soju install # 이후: soju battlenet / soju d2r / soju steam / soju epic / soju gog
```
-설치기는 프리빌드 엔진(~350MB)을 받고, 애플 무료 GPTK 다운로드(애플이 재배포 금지한 파일 1개)를 안내한 뒤, 원하는 런처를 묻습니다. Battle.net, Steam, Epic Games Launcher, GOG GALAXY 중 아무 조합이나 고르면 각각 공식 설치기로 별도 보틀에 설치하고, 런처마다 더블클릭용 앱을 `~/Applications`에 만들어 줍니다(`Battle.net.app`, `Steam (Windows).app`, `Epic Games Launcher.app`, `GOG GALAXY.app`). 비대화형: `SOJU_PLATFORMS=battlenet,epic,gog curl ... | bash`. 로그인하고 플레이하세요.
+설치기는 프리빌드 엔진(~350MB)을 받고, 애플 무료 GPTK 다운로드(애플이 재배포 금지한 파일 1개)를 안내한 뒤, 원하는 런처를 묻습니다. Battle.net, Steam, Epic Games Launcher, GOG GALAXY 중 아무 조합이나 고르면 각각 공식 설치기로 별도 보틀에 설치하고, 런처마다 더블클릭용 앱을 `~/Applications`에 만들어 줍니다(`Battle.net.app`, `Steam (Windows).app`, `Epic Games Launcher.app`, `GOG GALAXY.app`). 비대화형: `curl -fsSL https://soju.snack-wrap.com/install.sh | SOJU_PLATFORMS=battlenet,epic,gog bash`. 로그인하고 플레이하세요.
## 일상 명령
diff --git a/README.md b/README.md
index 00716ebee6e..5eb3ca59340 100644
--- a/README.md
+++ b/README.md
@@ -68,7 +68,7 @@ brew install BCD1210/soju/soju
soju install # then: soju battlenet / soju d2r / soju steam / soju epic / soju gog
```
-The installer downloads the prebuilt engine (~350 MB), walks you through Apple's free GPTK download (the one file Apple forbids redistributing), then asks which launchers you want, any combination of Battle.net, Steam, Epic Games Launcher and GOG GALAXY, installs each with its official installer into its own bottle, and drops a double-clickable app per launcher in `~/Applications` (`Battle.net.app`, `Steam (Windows).app`, `Epic Games Launcher.app`, `GOG GALAXY.app`). Non-interactive: `SOJU_PLATFORMS=battlenet,epic,gog curl ... | bash`. Log in and play.
+The installer downloads the prebuilt engine (~350 MB), walks you through Apple's free GPTK download (the one file Apple forbids redistributing), then asks which launchers you want, any combination of Battle.net, Steam, Epic Games Launcher and GOG GALAXY, installs each with its official installer into its own bottle, and drops a double-clickable app per launcher in `~/Applications` (`Battle.net.app`, `Steam (Windows).app`, `Epic Games Launcher.app`, `GOG GALAXY.app`). Non-interactive: `curl -fsSL https://soju.snack-wrap.com/install.sh | SOJU_PLATFORMS=battlenet,epic,gog bash`. Log in and play.
## Everyday commands
diff --git a/README.zh.md b/README.zh.md
index 61a3179fab6..500147a40f3 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -68,7 +68,7 @@ brew install BCD1210/soju/soju
soju install # 然后:soju battlenet / soju d2r / soju steam / soju epic / soju gog
```
-安装器会下载预编译引擎(约 350 MB),引导你下载 Apple 免费的 GPTK(唯一一个 Apple 禁止再分发的文件),然后询问你要装哪些登录器(任意组合:战网、Steam、Epic Games Launcher、GOG GALAXY),用各自的官方安装包装进各自独立的 bottle,并在 `~/Applications` 里为每个登录器生成可双击的 app(`Battle.net.app`、`Steam (Windows).app`、`Epic Games Launcher.app`、`GOG GALAXY.app`)。非交互模式:`SOJU_PLATFORMS=battlenet,epic,gog curl ... | bash`。登录,开玩。
+安装器会下载预编译引擎(约 350 MB),引导你下载 Apple 免费的 GPTK(唯一一个 Apple 禁止再分发的文件),然后询问你要装哪些登录器(任意组合:战网、Steam、Epic Games Launcher、GOG GALAXY),用各自的官方安装包装进各自独立的 bottle,并在 `~/Applications` 里为每个登录器生成可双击的 app(`Battle.net.app`、`Steam (Windows).app`、`Epic Games Launcher.app`、`GOG GALAXY.app`)。非交互模式:`curl -fsSL https://soju.snack-wrap.com/install.sh | SOJU_PLATFORMS=battlenet,epic,gog bash`。登录,开玩。
## 日常维护
diff --git a/install.sh b/install.sh
index 8a661bae23e..0a9aab5cdea 100644
--- a/install.sh
+++ b/install.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
# Soju one-line installer: Battle.net, Steam, Epic and GOG launchers on Apple Silicon, no CrossOver.
# curl -fsSL soju.snack-wrap.com/install.sh | bash
-# SOJU_PLATFORMS=battlenet,epic,gog curl ... | bash (non-interactive selection)
+# curl -fsSL https://soju.snack-wrap.com/install.sh | SOJU_PLATFORMS=battlenet,epic,gog bash (non-interactive selection)
#
# What it does:
# 1. Downloads the prebuilt GPL Wine engine (built from CodeWeavers' published sources)
@@ -202,6 +202,10 @@ for p in $PLATFORMS; do
bash "$SOJU_DIR/scripts/create-gog-bottle.sh"
fi ;;
esac
+ # The client EXE does not prove its helper build completed.
+ case "$p" in
+ epic|gog) bash "$SOJU_DIR/scripts/ensure-launcher-helper.sh" "$p" ;;
+ esac
done
# ---------- 4. App bundles ----------
diff --git a/scripts/create-epic-bottle.sh b/scripts/create-epic-bottle.sh
index 146458a93ec..3752f4b77d2 100755
--- a/scripts/create-epic-bottle.sh
+++ b/scripts/create-epic-bottle.sh
@@ -14,6 +14,13 @@ export WINEMSYNC=1 ROSETTA_ADVERTISE_AVX=1 WINE_SIMULATE_WRITECOPY=1
export CX_APPLEGPTK_LIBD3DSHARED_PATH="$ENGINE/lib/external/libd3dshared.dylib"
export DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib"
+# A previous run may have installed the client but failed to build its helper.
+if [ -f "$WINEPREFIX/drive_c/Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe" ]; then
+ bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ensure-launcher-helper.sh" epic
+ echo "==> Launcher already installed; tray-restore helper ready"
+ exit 0
+fi
+
[ -x "$ENGINE/bin/wine" ] || { echo "Engine not found, run install.sh (or build-engine.sh) first"; exit 1; }
[ -f "$CX_APPLEGPTK_LIBD3DSHARED_PATH" ] || { echo "libd3dshared not found, run get-gptk.sh first"; exit 1; }
@@ -36,13 +43,7 @@ echo "==> Running the installer (unattended, about half a minute)"
EXE="$WINEPREFIX/drive_c/Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe"
[ -f "$EXE" ] || { echo "Install failed, try: WINEDEBUG=+msi $W msiexec /i \"$MSI\""; exit 1; }
-SUPPORT="$HOME/.battlenet-macos/epic-support"; mkdir -p "$SUPPORT"
-if [ ! -f "$SUPPORT/soju-epic-restore.exe" ]; then
- echo "==> Building the tray-restore helper (mingw-w64)"
- command -v x86_64-w64-mingw32-gcc >/dev/null || brew install mingw-w64
- x86_64-w64-mingw32-gcc -O2 -Wall -mwindows -o "$SUPPORT/soju-epic-restore.exe" -lpsapi \
- "$(cd "$(dirname "$0")/.." && pwd)/tools/soju-epic-restore.c"
-fi
+bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ensure-launcher-helper.sh" epic
echo "==> Epic Games Launcher installed"
"$ENGINE/bin/wineserver" -k 2>/dev/null || true
echo "==> Done. Now run: scripts/play.sh epic (log in, then install games from the launcher)"
diff --git a/scripts/create-gog-bottle.sh b/scripts/create-gog-bottle.sh
index 7ed7851c044..93a5c46bb19 100755
--- a/scripts/create-gog-bottle.sh
+++ b/scripts/create-gog-bottle.sh
@@ -17,6 +17,13 @@ export WINEMSYNC=1 ROSETTA_ADVERTISE_AVX=1 WINE_SIMULATE_WRITECOPY=1
export CX_APPLEGPTK_LIBD3DSHARED_PATH="$ENGINE/lib/external/libd3dshared.dylib"
export DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib"
+# A previous run may have installed the client but failed to build its helper.
+if [ -f "$WINEPREFIX/drive_c/Program Files/GOG Galaxy/GalaxyClient.exe" ]; then
+ bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ensure-launcher-helper.sh" gog
+ echo "==> Launcher already installed; tray-restore helper ready"
+ exit 0
+fi
+
[ -x "$ENGINE/bin/wine" ] || { echo "Engine not found, run install.sh (or build-engine.sh) first"; exit 1; }
[ -f "$CX_APPLEGPTK_LIBD3DSHARED_PATH" ] || { echo "libd3dshared not found, run get-gptk.sh first"; exit 1; }
@@ -44,11 +51,5 @@ CLIENT="$WINEPREFIX/drive_c/Program Files/GOG Galaxy/GalaxyClient.exe"
"$ENGINE/bin/wineserver" -k 2>/dev/null || true
sleep 2
rm -f "$WINEPREFIX/drive_c/ProgramData/GOG.com/Galaxy/lock-files/"* 2>/dev/null || true
-SUPPORT="$HOME/.battlenet-macos/gog-support"; mkdir -p "$SUPPORT"
-if [ ! -f "$SUPPORT/soju-gog-restore.exe" ]; then
- echo "==> Building the tray-restore helper (mingw-w64)"
- command -v x86_64-w64-mingw32-gcc >/dev/null || brew install mingw-w64
- x86_64-w64-mingw32-gcc -O2 -Wall -mwindows -o "$SUPPORT/soju-gog-restore.exe" -lpsapi \
- "$(cd "$(dirname "$0")/.." && pwd)/tools/soju-gog-restore.c"
-fi
+bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ensure-launcher-helper.sh" gog
echo "==> GOG GALAXY installed. Launch with: scripts/play.sh gog"
diff --git a/scripts/ensure-launcher-helper.sh b/scripts/ensure-launcher-helper.sh
new file mode 100755
index 00000000000..a0e9c65a971
--- /dev/null
+++ b/scripts/ensure-launcher-helper.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Repair a tray-restore helper independently of the official launcher setup.
+# Optional support directory allows isolated builds and regression tests.
+set -euo pipefail
+MODE="${1:?usage: ensure-launcher-helper.sh epic|gog [support-directory]}"
+case "$MODE" in epic|gog) ;; *) echo "Unknown launcher: $MODE" >&2; exit 1;; esac
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+SUPPORT="${2:-$HOME/.battlenet-macos/$MODE-support}"
+DEST="$SUPPORT/soju-$MODE-restore.exe"
+[ ! -s "$DEST" ] || exit 0
+mkdir -p "$SUPPORT"
+echo "==> Building the $MODE tray-restore helper (mingw-w64)"
+command -v x86_64-w64-mingw32-gcc >/dev/null || brew install mingw-w64
+TMP=$(mktemp "$SUPPORT/.soju-$MODE-restore.XXXXXX")
+trap 'rm -f "$TMP"' EXIT
+x86_64-w64-mingw32-gcc -O2 -Wall -mwindows \
+ -o "$TMP" "$ROOT/tools/soju-$MODE-restore.c" -lpsapi
+[ -s "$TMP" ] || { echo "Compiler produced an empty helper" >&2; exit 1; }
+mv -f "$TMP" "$DEST"
diff --git a/scripts/soju-reaper.sh b/scripts/soju-reaper.sh
index 060f6b87f81..2708b2345b4 100755
--- a/scripts/soju-reaper.sh
+++ b/scripts/soju-reaper.sh
@@ -205,7 +205,7 @@ except Exception:
PY
}
-declare -a STRIKES # indexed by pid
+declare -a STRIKES SEEN_WINDOWS GAME_IDENTITIES # indexed by pid
IDLE_STRIKES=0
ORPHAN_STRIKES=0
@@ -246,15 +246,29 @@ while true; do
fi
IDLE_STRIKES=0
- # Zombie games: a game process of this bottle with no window at all for
- # ZOMBIE_STRIKES checks in a row.
+ # A cold start may load for minutes before creating its first window.
+ # Reap only after a previously observed window disappears. Start time
+ # prevents a reused PID from inheriting another game's window history.
[ -n "${GAME_PIDS// /}" ] || continue
WINS=" $(window_pids) " || continue
[ "$WINS" != " " ] || continue # query failed or no windows anywhere: skip the round
+ for pid in "${!GAME_IDENTITIES[@]}"; do
+ case " $GAME_PIDS " in *" $pid "*) ;; *)
+ unset "GAME_IDENTITIES[$pid]" "SEEN_WINDOWS[$pid]" "STRIKES[$pid]" ;;
+ esac
+ done
for pid in $GAME_PIDS; do
+ identity=$(ps -o lstart= -p "$pid" 2>/dev/null) || continue
+ [ -n "$identity" ] || continue
+ if [ "${GAME_IDENTITIES[$pid]:-}" != "$identity" ]; then
+ GAME_IDENTITIES[$pid]="$identity"
+ SEEN_WINDOWS[$pid]=0
+ STRIKES[$pid]=0
+ fi
if [[ "$WINS" == *" $pid "* ]]; then
+ SEEN_WINDOWS[$pid]=1
STRIKES[$pid]=0
- else
+ elif [ "${SEEN_WINDOWS[$pid]:-0}" = 1 ]; then
STRIKES[$pid]=$(( ${STRIKES[$pid]:-0} + 1 ))
if [ "${STRIKES[$pid]}" -ge "$ZOMBIE_STRIKES" ]; then
echo "soju-reaper: $(exe_of "$pid") ($pid) has had no window for $((ZOMBIE_STRIKES * INTERVAL)) s, killing it"
diff --git a/scripts/soju-sweep.sh b/scripts/soju-sweep.sh
index dde09af4229..d00687f73bf 100755
--- a/scripts/soju-sweep.sh
+++ b/scripts/soju-sweep.sh
@@ -1,58 +1,79 @@
#!/usr/bin/env bash
-# soju-sweep: remove orphaned Wine service processes.
-#
-# Every bottle start spawns a set of idle Windows "system" processes
-# (services.exe, winedevice.exe x2, plugplay.exe, rpcss.exe, explorer.exe
-# /desktop: ~100 MB together). When the bottle's wineserver is killed
-# (wineserver -k, a crashed launcher, an aborted test) the apps die, but these
-# sleeping services never talk to the server again and so never notice it is
-# gone; they linger for hours. This sweeps them.
-#
-# Only service processes are candidates, never launchers or games, and a
-# candidate is removed only if it is attached to no running wineserver: every
-# process of a live bottle holds a file open in its server's socket directory
-# (the server's working directory), so the ones without such a file belong to
-# a server that is gone. Safe to run while other bottles are up.
-#
-# Usage: soju-sweep.sh (called by play.sh *-kill, soju-reaper.sh, soju sweep)
-# SOJU_SWEEP_DRY=1 soju-sweep.sh only print what would be removed
+# Remove orphaned Wine services. SOJU_SWEEP_DRY=1 only reports candidates.
+# Never infer ownership from command-line arguments or a failed lsof query.
set -u
-# Also Wine's own prompts (the "Wine Mono Installer" dialog is control.exe
-# appwiz.cpl install_mono): orphaned, they sit in the Dock as "wine" for hours.
-RE='(explorer\.exe /desktop|services\.exe|winedevice\.exe|plugplay\.exe|rpcss\.exe|svchost\.exe|conhost\.exe|tabtip\.exe|control\.exe appwiz\.cpl|wineboot\.exe|winedbg\.exe|start\.exe /exec)'
-CAND=$(pgrep -f "$RE" 2>/dev/null || true)
-[ -n "$CAND" ] || exit 0
-SERVERS=$( { pgrep -x wineserver; pgrep -x wineserver64; } 2>/dev/null | tr '\n' ',' | sed 's/,$//')
-ATTACHED=""
+# macOS Wine rewrites comm to the Windows executable path. A log reader
+# with "services.exe.log" in its arguments has comm=/usr/bin/tail.
+service_exe() {
+ local exe name
+ exe=$(ps -o comm= -p "$1" 2>/dev/null) || return 1
+ [[ "$exe" =~ ^[A-Za-z]:[\\/] ]] || return 1
+ name=${exe##*\\}; name=${name##*/}
+ name=$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')
+ case "$name" in
+ services.exe|winedevice.exe|plugplay.exe|rpcss.exe|svchost.exe|explorer.exe|conhost.exe|tabtip.exe|control.exe|wineboot.exe|winedbg.exe|start.exe)
+ printf '%s\n' "$exe" ;;
+ *) return 1 ;;
+ esac
+}
+server_pids() {
+ { pgrep -x wineserver; pgrep -x wineserver64; } 2>/dev/null | sort -un
+}
+csv() { tr '\n' ',' | sed 's/,$//'; }
+
+declare -a IDENTITIES
+CAND=""
+for p in $(pgrep -if '\.exe' 2>/dev/null || true); do
+ service_exe "$p" >/dev/null || continue
+ identity=$(ps -o lstart= -p "$p" 2>/dev/null) || continue
+ [ -n "$identity" ] || continue
+ IDENTITIES[$p]="$identity"
+ CAND="$CAND $p"
+done
+[ -n "${CAND// /}" ] || exit 0
+
+SERVERS=$(server_pids)
+DIRS=""
if [ -n "$SERVERS" ]; then
- # One line per server directory, joined with "|" (macOS awk rejects a
- # newline inside -v, and would silently see no directories at all).
- DIRS=$(lsof -a -p "$SERVERS" -d cwd -Fn 2>/dev/null | sed -n 's/^n//p' | tr '\n' '|')
- # Fail closed: with servers up but no directories, or no open-file listing
- # for the candidates at all, attribution is unknown and every candidate
- # would look orphaned; killing the live bottles' services is the one
- # outcome this script must never produce.
- if [ -z "${DIRS//|/}" ]; then echo "soju-sweep: could not read the wineserver directories; not touching anything" >&2; exit 1; fi
- LISTING=$(lsof -a -p "$(echo "$CAND" | tr '\n' ',' | sed 's/,$//')" -Fpn 2>/dev/null)
- if ! printf '%s\n' "$LISTING" | grep -q '^p'; then echo "soju-sweep: could not list the candidates' open files; not touching anything" >&2; exit 1; fi
- ATTACHED=$(printf '%s\n' "$LISTING" | awk -v dirs="$DIRS" '
- BEGIN { n = split(dirs, d, "|") }
- /^p/ { pid = substr($0, 2) }
- /^n/ { for (i = 1; i <= n; i++) if (d[i] != "" && index($0, "n" d[i] "/") == 1) { seen[pid] = 1; break } }
- END { for (p in seen) print p }' | tr '\n' ' ')
+ CWD=$(lsof -a -p "$(printf '%s\n' "$SERVERS" | csv)" -d cwd -Fpn 2>/dev/null) || {
+ echo "soju-sweep: could not read all server directories; not touching anything" >&2; exit 1;
+ }
+ for p in $SERVERS; do
+ dir=$(printf '%s\n' "$CWD" | awk -v target="$p" '
+ /^p/ { pid=substr($0,2) }
+ /^n/ && pid==target { print substr($0,2); exit }')
+ [ -n "$dir" ] || { echo "soju-sweep: missing server directory; not touching anything" >&2; exit 1; }
+ DIRS="${DIRS}${dir}|"
+ done
fi
-PIDS=""
+LISTING=$(lsof -a -p "$(printf '%s\n' $CAND | csv)" -Fpn 2>/dev/null) || {
+ echo "soju-sweep: incomplete process listing; not touching anything" >&2; exit 1;
+}
+# Require positive Wine-prefix evidence; a missing PID record is unknown.
+ORPHANS=$(printf '%s\n' "$LISTING" | awk -v dirs="$DIRS" '
+ BEGIN { n=split(dirs,d,"|") }
+ /^p/ { pid=substr($0,2) }
+ /^n/ {
+ if ($0 ~ /\/drive_c\/windows(\/|$)/) wine[pid]=1
+ for (i=1;i<=n;i++)
+ if (d[i]!="" && index($0,"n" d[i] "/")==1) attached[pid]=1
+ }
+ END { for (p in wine) if (!attached[p]) print p }')
+
+# A server may have started while lsof ran. Reject that stale snapshot.
+[ "$(server_pids)" = "$SERVERS" ] || {
+ echo "soju-sweep: servers changed during inspection; retry later" >&2; exit 1;
+}
for p in $CAND; do
- case " $ATTACHED " in *" $p "*) ;; *) PIDS="$PIDS $p" ;; esac
+ case " $(printf '%s\n' "$ORPHANS" | tr '\n' ' ') " in *" $p "*) ;; *) continue;; esac
+ exe=$(service_exe "$p") || continue
+ [ "$(ps -o lstart= -p "$p" 2>/dev/null)" = "${IDENTITIES[$p]}" ] || continue
+ if [ "${SOJU_SWEEP_DRY:-0}" = 1 ]; then
+ echo "soju-sweep (dry run): would remove $p $exe"
+ else
+ echo "soju-sweep: removing orphaned Wine service $p $exe"
+ kill -9 "$p" 2>/dev/null || true
+ fi
done
-[ -n "${PIDS// /}" ] || exit 0
-if [ "${SOJU_SWEEP_DRY:-0}" = 1 ]; then
- echo "soju-sweep (dry run): would remove $(echo $PIDS | wc -w | tr -d ' ') orphaned Wine services:"
- for p in $PIDS; do echo " $p $(ps -o args= -p "$p" 2>/dev/null | cut -c1-80)"; done
- exit 0
-fi
-echo "soju-sweep: removing orphaned Wine services: $(echo $PIDS | wc -w | tr -d ' ') processes"
-# shellcheck disable=SC2086
-kill -9 $PIDS 2>/dev/null || true
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
index 94b24b4b253..ead9624b246 100755
--- a/scripts/uninstall.sh
+++ b/scripts/uninstall.sh
@@ -7,6 +7,7 @@ set -euo pipefail
BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"
ENGINE="${ENGINE:-$BASE/cx26-engine}"
TTY=/dev/tty
+REMOVED=0
YES=0; [ "${1:-}" = "--yes" ] && YES=1
ask(){
@@ -17,14 +18,13 @@ ask(){
echo "soju uninstall: this removes things soju created. Nothing is touched without a yes."
-# 1. Stop everything first (best effort).
-for b in bottle epic-bottle gog-bottle; do
- [ -d "$BASE/$b" ] && WINEPREFIX="$BASE/$b" DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib" \
- "$ENGINE/bin/wineserver" -k 2>/dev/null || true
-done
-WS="/Applications/Wine Stable.app/Contents/Resources/wine/bin/wineserver"
-[ -d "$BASE/steam-bottle" ] && [ -x "$WS" ] && WINEPREFIX="$BASE/steam-bottle" "$WS" -k 2>/dev/null || true
-sleep 1
+# Stop only after this bottle's removal (or engine removal) was accepted.
+stop_bottle() {
+ local b="$1" ws="$ENGINE/bin/wineserver"
+ [ "$b" != steam-bottle ] || ws="/Applications/Wine Stable.app/Contents/Resources/wine/bin/wineserver"
+ [ -d "$BASE/$b" ] || return 0
+ WINEPREFIX="$BASE/$b" DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib" "$ws" -k 2>/dev/null || true
+}
# 2. App bundles.
# Only bundles install.sh wrote for this install (their launcher script names
@@ -36,7 +36,7 @@ for a in "Battle.net" "Steam (Windows)" "Epic Games Launcher" "GOG GALAXY"; do
done
if [ "${#apps[@]}" -gt 0 ]; then
printf 'Apps: %s\n' "${apps[@]}"
- if ask "Remove these apps?"; then rm -rf "${apps[@]}"; echo " removed"; fi
+ if ask "Remove these apps?"; then rm -rf "${apps[@]}"; REMOVED=1; echo " removed"; fi
fi
# 3. Bottles (this is where installed games live; can be tens of GB).
@@ -44,14 +44,18 @@ for b in bottle steam-bottle epic-bottle gog-bottle; do
d="$BASE/$b"
[ -d "$d" ] || continue
sz=$(du -sh "$d" 2>/dev/null | cut -f1)
- if ask "Remove bottle $b ($sz, includes installed games)?"; then rm -rf "$d"; echo " removed"; fi
+ if ask "Remove bottle $b ($sz, includes installed games)?"; then
+ stop_bottle "$b"
+ rm -rf "$d"; REMOVED=1; echo " removed"
+ fi
done
# 4. Engine (+ the GPTK payload inside it).
if [ -d "$ENGINE" ]; then
sz=$(du -sh "$ENGINE" 2>/dev/null | cut -f1)
if ask "Remove the engine ($sz, includes the GPTK payload; re-downloadable with soju install)?"; then
- rm -rf "$ENGINE"; echo " removed"
+ for b in bottle epic-bottle gog-bottle; do stop_bottle "$b"; done
+ rm -rf "$ENGINE"; REMOVED=1; echo " removed"
fi
fi
@@ -61,18 +65,20 @@ extras=()
for d in build steam-support epic-support gog-support logs cx26-engine.old cx26-engine.new soju.old; do
[ -e "$BASE/$d" ] && extras+=("$BASE/$d")
done
+for d in "$BASE"/reaper-*.log "$BASE"/*.tar.xz "$BASE"/*.part; do
+ [ -f "$d" ] && extras+=("$d")
+done
if [ "${#extras[@]}" -gt 0 ]; then
sz=$(du -shc "${extras[@]}" 2>/dev/null | tail -1 | cut -f1)
printf 'Caches and support files (%s):\n' "$sz"; printf ' %s\n' "${extras[@]}"
- if ask "Remove these?"; then rm -rf "${extras[@]}"; echo " removed"; fi
+ if ask "Remove these?"; then rm -rf "${extras[@]}"; REMOVED=1; echo " removed"; fi
fi
-rm -f "$BASE"/reaper-*.log "$BASE"/*.tar.xz "$BASE"/*.part 2>/dev/null || true
# 6. The scripts copy made by the one-line installer.
if [ -d "$BASE/soju" ]; then
- if ask "Remove the scripts copy at $BASE/soju?"; then rm -rf "$BASE/soju"; echo " removed"; fi
+ if ask "Remove the scripts copy at $BASE/soju?"; then rm -rf "$BASE/soju"; REMOVED=1; echo " removed"; fi
fi
-rmdir "$BASE" 2>/dev/null && echo "Removed empty $BASE" || true
+[ "$REMOVED" = 0 ] || { rmdir "$BASE" 2>/dev/null && echo "Removed empty $BASE" || true; }
cat <<'EOT'
diff --git a/tests/test_regressions.py b/tests/test_regressions.py
new file mode 100644
index 00000000000..2733a200b55
--- /dev/null
+++ b/tests/test_regressions.py
@@ -0,0 +1,289 @@
+"""Run on macOS: python3 -m unittest discover -s tests -v.
+All process APIs are mocked; Wine and installed games are never launched/killed.
+"""
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+BASH = "/bin/bash"
+
+
+def run(code, env=None, args=()):
+ return subprocess.run(
+ [BASH, "-c", code, "probe", *args], text=True, capture_output=True,
+ timeout=15, start_new_session=True, env={**os.environ, **(env or {})})
+
+
+class ReaperTests(unittest.TestCase):
+ def probe(self, frames, identities=None):
+ with tempfile.TemporaryDirectory(prefix="soju-test-") as t:
+ # Insert mocked OS queries before the unchanged production loop.
+ script = (ROOT / "scripts/soju-reaper.sh").read_text()
+ boundary = script.index("declare -a STRIKES")
+ identities = identities or ["original"] * len(frames)
+ mocks = """
+server_alive(){ return 0; }
+bottle_pids(){ echo 42001; }
+classify(){ ALIVE_PIDS='42001'; GAME_PIDS='42001'; HELPER_PIDS=''; }
+exe_of(){ echo D2R.exe; }
+kill(){ echo "SIGNAL $*"; }
+"""
+ mocks += "FRAMES=(" + " ".join(shlex.quote(x) for x in frames) + ")\n"
+ mocks += "IDENTITY_FRAMES=(" + " ".join(shlex.quote(x) for x in identities) + ")\n"
+ mocks += """
+N=-1
+sleep(){ N=$((N+1)); [ "$N" -lt "${#FRAMES[@]}" ] || exit 0; }
+window_pids(){ [ "${FRAMES[$N]}" != error ] || return 1; echo "${FRAMES[$N]}"; }
+ps(){ echo "${IDENTITY_FRAMES[$N]}"; }
+"""
+ p = Path(t) / "reaper.sh"
+ p.write_text(script[:boundary] + mocks + script[boundary:])
+ result = subprocess.run(
+ [BASH, str(p), t, "/no-real-wineserver", "battlenet"],
+ capture_output=True, text=True, timeout=15)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stderr, "")
+ return result.stdout
+
+ def test_first_window_can_take_many_rounds(self):
+ self.assertNotIn("SIGNAL", self.probe(["42002"] * 12))
+
+ def test_exited_window_is_still_reaped(self):
+ out = self.probe(["42001", "42002", "42002", "42002"])
+ self.assertEqual(out.count("SIGNAL -9 42001"), 1)
+
+ def test_window_return_resets_strikes(self):
+ self.assertNotIn("SIGNAL", self.probe(
+ ["42001", "42002", "42002", "42001", "42002", "42002"]))
+
+ def test_reused_pid_has_no_previous_window_history(self):
+ self.assertNotIn("SIGNAL", self.probe(
+ ["42001", "42002", "42002", "42002", "42002"],
+ ["old", "new", "new", "new", "new"]))
+
+ def test_failed_window_query_does_not_count(self):
+ self.assertNotIn("SIGNAL", self.probe(
+ ["42001", "error", "error", "error", "42002", "42002"]))
+
+
+class SweepTests(unittest.TestCase):
+ def probe(self, candidates, comm, listing, servers="", cwd="", lsof_exit=0,
+ dry=False, changed=False):
+ env = {
+ "MOCK_CAND": candidates, "MOCK_COMM": comm, "MOCK_LISTING": listing,
+ "MOCK_SERVERS": servers, "MOCK_CWD": cwd,
+ "MOCK_LSOF_EXIT": str(lsof_exit), "SOJU_SWEEP_DRY": str(int(dry))}
+ pre = r"""
+pgrep(){
+ case "$1" in
+ -if|-f) printf '%s\n' "$MOCK_CAND";;
+ -x) [ "$2" = wineserver ] && printf '%s\n' "$MOCK_SERVERS";;
+ esac
+}
+ps(){
+ case "$2" in comm=) printf '%s\n' "$MOCK_COMM";; lstart=) echo original;; esac
+}
+lsof(){
+ case " $* " in
+ *" -d cwd "*) printf '%s\n' "$MOCK_CWD";;
+ *) printf '%s\n' "$MOCK_LISTING"; return "$MOCK_LSOF_EXIT";;
+ esac
+}
+kill(){ echo "SIGNAL $*"; }
+"""
+ if changed:
+ pre += 'server_pids(){ :; }\n' # Production definition is tested below via pgrep.
+ with tempfile.TemporaryDirectory(prefix="soju-test-") as t:
+ counter = Path(t) / "server-count"
+ env["MOCK_COUNTER"] = str(counter)
+ pre += r"""
+pgrep(){
+ case "$1" in
+ -if|-f) printf '%s\n' "$MOCK_CAND";;
+ -x)
+ [ "$2" = wineserver ] || return 1
+ if [ -e "$MOCK_COUNTER" ]; then echo 43000; else : > "$MOCK_COUNTER"; fi;;
+ esac
+}
+"""
+ result = run(pre + "\nsource " + shlex.quote(str(ROOT / "scripts/soju-sweep.sh")), env)
+ else:
+ result = run(pre + "\nsource " + shlex.quote(str(ROOT / "scripts/soju-sweep.sh")), env)
+ self.assertNotIn("unbound", result.stderr)
+ return result
+
+ def test_log_reader_is_not_a_service(self):
+ x = self.probe("42001", "/usr/bin/tail", "p42001\nn/tmp/services.exe.log")
+ self.assertNotIn("SIGNAL", x.stdout)
+ self.assertEqual(x.returncode, 0)
+
+ def test_real_orphan_is_removed(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows")
+ self.assertIn("SIGNAL -9 42001", x.stdout)
+
+ def test_live_service_is_preserved(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows\nn/private/tmp/server/tmpmap-1",
+ "43000", "p43000\nn/private/tmp/server")
+ self.assertNotIn("SIGNAL", x.stdout)
+
+ def test_missing_pid_is_unknown(self):
+ x = self.probe("42001\n42002", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows\nn/private/tmp/server/tmpmap-1",
+ "43000", "p43000\nn/private/tmp/server")
+ self.assertNotIn("SIGNAL", x.stdout)
+
+ def test_partial_lsof_error_is_unknown(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows", lsof_exit=1)
+ self.assertNotIn("SIGNAL", x.stdout)
+ self.assertNotEqual(x.returncode, 0)
+
+ def test_missing_server_cwd_is_unknown(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows",
+ "43000\n43001", "p43000\nn/private/tmp/server")
+ self.assertNotIn("SIGNAL", x.stdout)
+ self.assertNotEqual(x.returncode, 0)
+
+ def test_no_wine_prefix_evidence_is_preserved(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe", "p42001\nn/tmp/other")
+ self.assertNotIn("SIGNAL", x.stdout)
+
+ def test_dry_run_never_signals(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows", dry=True)
+ self.assertIn("would remove 42001", x.stdout)
+ self.assertNotIn("SIGNAL", x.stdout)
+
+ def test_new_server_invalidates_snapshot(self):
+ x = self.probe("42001", r"C:\windows\system32\services.exe",
+ "p42001\nn/tmp/bottle/drive_c/windows", changed=True)
+ self.assertNotIn("SIGNAL", x.stdout)
+ self.assertNotEqual(x.returncode, 0)
+
+
+class UninstallTests(unittest.TestCase):
+ def scenario(self, answers=None, yes=False, empty=False):
+ with tempfile.TemporaryDirectory(prefix="soju-test-") as t:
+ d = Path(t)
+ base = d / "base"
+ engine = base / "cx26-engine"
+ base.mkdir()
+ marker = d / "stopped"
+ if not empty:
+ (engine / "bin").mkdir(parents=True)
+ server = engine / "bin/wineserver"
+ server.write_text("#!/bin/bash\necho \"$*\" >> " + shlex.quote(str(marker)) + "\n")
+ server.chmod(0o755)
+ (base / "bottle").mkdir()
+ (base / "test.part").write_text("keep")
+ # Only replace the terminal path so each production ask() reads
+ # an explicit answer without acquiring the user's terminal.
+ src = (ROOT / "scripts/uninstall.sh").read_text()
+ if answers is not None:
+ answer_file = d / "answers"
+ answer_file.write_text(answers)
+ # Keep one descriptor open so consecutive read calls advance.
+ src = src.replace("TTY=/dev/tty",
+ "exec 9<" + shlex.quote(str(answer_file)) + "\nTTY=/dev/fd/9")
+ script = d / "uninstall.sh"
+ script.write_text(src)
+ x = subprocess.run([BASH, str(script), *(["--yes"] if yes else [])],
+ env={**os.environ, "SOJU_BASE": str(base), "ENGINE": str(engine)},
+ capture_output=True, text=True, timeout=15, start_new_session=True)
+ self.assertEqual(x.returncode, 0, x.stderr)
+ return {"stopped": marker.exists(), "bottle": (base / "bottle").exists(),
+ "engine": engine.exists(), "download": (base / "test.part").exists(),
+ "base": base.exists()}
+
+ def test_reject_all_has_no_effect(self):
+ x = self.scenario("n\nn\nn\n")
+ self.assertFalse(x["stopped"])
+ self.assertTrue(x["bottle"] and x["engine"] and x["download"])
+
+ def test_no_terminal_has_no_effect(self):
+ x = self.scenario()
+ self.assertFalse(x["stopped"])
+ self.assertTrue(x["bottle"] and x["engine"] and x["download"])
+
+ def test_empty_directory_preserved_without_consent(self):
+ self.assertTrue(self.scenario(empty=True)["base"])
+
+ def test_accept_bottle_only(self):
+ x = self.scenario("y\nn\nn\n")
+ self.assertTrue(x["stopped"])
+ self.assertFalse(x["bottle"])
+ self.assertTrue(x["engine"] and x["download"])
+
+ def test_yes_still_removes_everything(self):
+ x = self.scenario(yes=True)
+ self.assertTrue(x["stopped"])
+ self.assertFalse(x["base"])
+
+
+class HelperTests(unittest.TestCase):
+ def test_build_failure_retry_and_existing_helper(self):
+ with tempfile.TemporaryDirectory(prefix="soju-test-") as t:
+ d = Path(t); bin_dir = d / "bin"; bin_dir.mkdir()
+ compiler = bin_dir / "x86_64-w64-mingw32-gcc"
+ compiler.write_text("""#!/usr/bin/python3
+import sys, os
+from pathlib import Path
+out = Path(sys.argv[sys.argv.index('-o')+1])
+out.write_bytes(b'MZfixture')
+sys.exit(7 if os.environ.get('FAIL_BUILD') == '1' else 0)
+""")
+ compiler.chmod(0o755)
+ env = {**os.environ, "PATH": str(bin_dir)+":"+os.environ["PATH"]}
+ script = ROOT / "scripts/ensure-launcher-helper.sh"
+ for mode in ("epic", "gog"):
+ support = d / mode
+ dest = support / ("soju-"+mode+"-restore.exe")
+ cmd = [BASH, str(script), mode, str(support)]
+ x = subprocess.run(cmd, env={**env, "FAIL_BUILD": "1"}, capture_output=True)
+ self.assertNotEqual(x.returncode, 0)
+ self.assertFalse(dest.exists())
+ self.assertEqual(list(support.iterdir()), [])
+ x = subprocess.run(cmd, env=env, capture_output=True)
+ self.assertEqual(x.returncode, 0, x.stderr)
+ self.assertGreater(dest.stat().st_size, 0)
+ x = subprocess.run(cmd, env={**env, "FAIL_BUILD": "1"}, capture_output=True)
+ self.assertEqual(x.returncode, 0)
+ dest.write_bytes(b"")
+ x = subprocess.run(cmd, env=env, capture_output=True)
+ self.assertEqual(x.returncode, 0)
+ self.assertGreater(dest.stat().st_size, 0)
+
+ def test_installer_repairs_helpers_for_existing_clients(self):
+ src = (ROOT / "install.sh").read_text()
+ stage = src[src.index('ALL="battlenet steam epic gog"'):
+ src.index("# ---------- 4. App bundles")]
+ with tempfile.TemporaryDirectory(prefix="soju-test-") as t:
+ d = Path(t)
+ for path in (
+ "epic-bottle/drive_c/Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe",
+ "gog-bottle/drive_c/Program Files/GOG Galaxy/GalaxyClient.exe"):
+ p=d/path; p.parent.mkdir(parents=True); p.touch()
+ (d/"scripts").mkdir()
+ (d/"scripts/ensure-launcher-helper.sh").write_text('echo "REPAIR $1"\n')
+ pre = ('set -euo pipefail\nBASE='+shlex.quote(t)+
+ '\nBOTTLE="$BASE/bottle"\nENGINE="$BASE/engine"\nSOJU_DIR="$BASE"'
+ '\nSOJU_PLATFORMS=epic,gog\nsay(){ echo "$*"; }\n')
+ x = run(pre+stage)
+ self.assertEqual(x.returncode, 0, x.stderr)
+ self.assertIn("REPAIR epic", x.stdout)
+ self.assertIn("REPAIR gog", x.stdout)
+
+ def test_noninteractive_selection_reaches_bash(self):
+ x = run("printf x | SOJU_PLATFORMS=epic,gog /bin/bash -c 'echo \"$SOJU_PLATFORMS\"'")
+ self.assertEqual(x.stdout.strip(), "epic,gog")
+
+
+if __name__ == "__main__":
+ unittest.main()