mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 22:05:59 +00:00
chore: merge main into feat/lse-emu
This commit is contained in:
commit
73104aff03
667 files changed
+75245
-4143
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -1270,6 +1342,10 @@ def main():
|
||||
if scripts and install_scripts_done(scripts, env):
|
||||
print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr)
|
||||
return 0
|
||||
if scripts and not env.get("DBUS_SESSION_BUS_ADDRESS"):
|
||||
# libdbus would autolaunch a session bus under the evaluator's reaper, which then waits for it
|
||||
# forever: Steam keeps seeing the app as running and cannot move or update it
|
||||
env["DBUS_SESSION_BUS_ADDRESS"] = "disabled:"
|
||||
try:
|
||||
digest = scripts_digest(scripts) if scripts else None
|
||||
except OSError:
|
||||
@@ -1283,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 ({}, [], [])
|
||||
@@ -1303,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
@@ -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=()
|
||||
|
||||
@@ -137,8 +137,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() {
|
||||
@@ -517,6 +516,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) ;;
|
||||
@@ -534,7 +539,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
|
||||
@@ -817,19 +822,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
|
||||
@@ -837,15 +853,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))
|
||||
@@ -857,25 +908,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
|
||||
@@ -885,12 +940,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
|
||||
@@ -898,15 +970,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
|
||||
@@ -922,21 +993,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=
|
||||
@@ -967,7 +1035,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
|
||||
@@ -1023,10 +1091,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
|
||||
@@ -1035,7 +1109,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
|
||||
@@ -1053,6 +1127,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
|
||||
@@ -1079,8 +1155,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
|
||||
@@ -1110,6 +1189,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"
|
||||
@@ -1123,7 +1206,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
|
||||
@@ -1137,7 +1220,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" \
|
||||
@@ -1401,6 +1484,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 &
|
||||
@@ -1463,6 +1548,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", ""))))
|
||||
|
||||
@@ -479,13 +479,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):
|
||||
@@ -546,6 +548,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)]
|
||||
@@ -585,7 +588,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
|
||||
@@ -606,7 +609,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,4 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -75,10 +76,105 @@ def pe_has_arm64ec_metadata(path):
|
||||
return False
|
||||
|
||||
|
||||
def machine_compatible(path, machines, machine=None):
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
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)
|
||||
@@ -255,6 +421,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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -81,7 +81,10 @@ __attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *p
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || bl_from_ntdll(caller))
|
||||
return -1;
|
||||
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
// through the next open(): the native userland's hook gives the app's ids as root's there
|
||||
static int (*next_open)(const char *, int, ...) = NULL;
|
||||
if (!next_open) next_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
|
||||
int in = next_open ? next_open(path, O_RDONLY | O_CLOEXEC) : (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (in < 0) goto done;
|
||||
for (;;) {
|
||||
ssize_t n = read(in, text + len, sizeof(text) - 1 - len);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user