mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 21:15:43 +00:00
Merge main into Wine timezone fix
This commit is contained in:
commit
3f3932d575
941 files changed
+106838
-7538
No files matched your search
+13
-4
@@ -44,8 +44,10 @@ from what tripped agents up on real devices.
|
||||
running makes Steam show "Game already running" and `launch` time out.
|
||||
- Session scripts are APK assets, copied into the rootfs at every session start over any local
|
||||
edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only:
|
||||
session scripts, native code and assets need a new APK, such as the pull request's CI test build
|
||||
(DroidDeck > Updates > Test builds).
|
||||
session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull
|
||||
request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the
|
||||
manifest, native code, Gradle files and a few startup classes, but builds session script and asset
|
||||
changes without them. To try the rest of a branch, build a copy without those changes.
|
||||
|
||||
## Changing DroidDeck
|
||||
|
||||
@@ -56,10 +58,17 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools
|
||||
- `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the
|
||||
build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in
|
||||
the background and keep checking, so the user can talk to you meanwhile. The restart ends your
|
||||
process, and the conversation continues on the new build.
|
||||
process; DroidDeck starts you again on the new build, in the same conversation, so tell the user
|
||||
what you will check then instead of asking them to message you.
|
||||
- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle
|
||||
compile first only adds time. It refuses changes since the installed build (`apkCommit` in
|
||||
`droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick
|
||||
its commits onto a branch from `apkCommit` and build that.
|
||||
- Python tests run from the repository root: `python3 -m unittest tools.tests.test_x`. Some fail on
|
||||
the device on `origin/main` too; run them on a worktree of `origin/main` before blaming a change.
|
||||
- Gradle unit tests rarely run on the device. Leave them to CI and say so rather than retrying.
|
||||
- Gradle runs on the device once the build tools are set up, but slowly: run the test classes that cover
|
||||
your change, and leave full suites and native builds to CI. `PreviewRenderTest` cannot run here
|
||||
(Robolectric's native graphics has no aarch64 Linux build).
|
||||
- If `git push` asks for credentials, run `gh auth setup-git` once.
|
||||
- Commits and pull requests you make are the user's own: no co-author line, AI credit or
|
||||
generated-by note.
|
||||
|
||||
@@ -28,6 +28,19 @@ float_code() {
|
||||
[ "$result" = ok ]
|
||||
}
|
||||
|
||||
# git pushes through gh's sign-in and commits as the signed-in account, with its no-reply address.
|
||||
configure_git() {
|
||||
gh auth setup-git || return 1
|
||||
[ -n "$(git config --global user.name)" ] && [ -n "$(git config --global user.email)" ] && return 0
|
||||
local user id login name
|
||||
user=$(gh api user -q '"\(.id) \(.login) \(.name // .login)"') || return 1
|
||||
read -r id login name <<<"$user"
|
||||
[ -n "$id" ] && [ -n "$login" ] || return 1
|
||||
[ -n "$(git config --global user.name)" ] || git config --global user.name "${name:-$login}"
|
||||
[ -n "$(git config --global user.email)" ] || git config --global user.email "$id+$login@users.noreply.github.com"
|
||||
}
|
||||
if [ "${1:-}" = --git ]; then configure_git; exit; fi
|
||||
|
||||
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
|
||||
gh_pid=$GH_PID
|
||||
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
|
||||
@@ -48,5 +61,9 @@ while IFS= read -r line <&"$ghout"; do
|
||||
done
|
||||
wait "$gh_pid"
|
||||
status=$?
|
||||
if [ $status = 0 ] && ! configure_git; then
|
||||
echo "Signed in, but git could not be set up: run dd-gh-login --git"
|
||||
status=1
|
||||
fi
|
||||
[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
|
||||
exit $status
|
||||
@@ -134,6 +134,54 @@ fi
|
||||
gradle=(./gradlew :app:processReleaseResources :app:mergeDexRelease --max-workers=2 -PskipRust=true -x buildVkBridgeServer
|
||||
-Pandroid.aapt2FromMavenOverride=$HOME/aapt2/aapt2 -Pkotlin.compiler.execution.strategy=daemon
|
||||
-Pkotlin.daemon.jvmargs=-Xmx${kotlin_heap}m -Dorg.gradle.jvmargs=-Xmx${gradle_heap}m --console=plain)
|
||||
# Release package aliases rewrite the manifest but keep the resource table under the linker package.
|
||||
resource_package=com.droiddeck.launcher
|
||||
resource_cache=$cache/dd-lab-resource-ids
|
||||
mkdir -p "$resource_cache"
|
||||
resource_key=$(printf '%s\n' "$pkg" "$base" "$apk" | sha256sum | cut -d ' ' -f1)
|
||||
stable_ids=$resource_cache/$resource_key.txt
|
||||
if [ ! -s "$stable_ids" ]; then
|
||||
progress checking 0 "reading the installed APK resource IDs"
|
||||
if ! (
|
||||
resource_work=$(mktemp -d "$resource_cache/.extract.XXXXXX") || exit 1
|
||||
trap 'rm -rf "$resource_work"' EXIT
|
||||
adb -s "$serial" pull "$apk" "$resource_work/base.apk" >/dev/null &&
|
||||
"$HOME/aapt2/aapt2" dump resources "$resource_work/base.apk" > "$resource_work/resources.txt" &&
|
||||
awk -v package="$resource_package" '
|
||||
$1 == "Package" { in_package = ($2 == "name=" package) }
|
||||
in_package && $1 == "resource" && $2 ~ /^0x[[:xdigit:]]+$/ {
|
||||
print package ":" $3 " = " $2
|
||||
count++
|
||||
}
|
||||
END { if (!count) exit 1 }
|
||||
' "$resource_work/resources.txt" > "$resource_work/ids.txt" &&
|
||||
mv "$resource_work/ids.txt" "$stable_ids"
|
||||
); then
|
||||
fail "could not read resource IDs from the installed APK"
|
||||
fi
|
||||
fi
|
||||
|
||||
resource_init=$resource_cache/link.gradle
|
||||
cat > "$resource_init.part.$$" <<'EOF'
|
||||
gradle.beforeProject { project ->
|
||||
if (project.path == ':app') {
|
||||
project.pluginManager.withPlugin('com.android.application') {
|
||||
project.androidComponents.finalizeDsl { android ->
|
||||
android.androidResources.additionalParameters.addAll([
|
||||
'--stable-ids', project.providers.gradleProperty('droiddeckLabStableIds').get()
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
if cmp -s "$resource_init.part.$$" "$resource_init"; then
|
||||
rm "$resource_init.part.$$"
|
||||
else
|
||||
mv "$resource_init.part.$$" "$resource_init"
|
||||
fi
|
||||
gradle+=(--init-script "$resource_init" "-PdroiddeckLabStableIds=$stable_ids")
|
||||
|
||||
progress planning
|
||||
plan_file=$cache/dd-lab-build-plan
|
||||
plan_key=$(
|
||||
|
||||
@@ -16,6 +16,9 @@ command -v claude >/dev/null || [ -x "$HOME/.local/bin/claude" ] ||
|
||||
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
for tool in dd-agent dd-lab-build dd-gh-login android-open; do install -m755 "$here/$tool" "$HOME/.local/bin/$tool"; done
|
||||
if gh auth status >/dev/null 2>&1 && ! "$here/dd-gh-login" --git; then
|
||||
echo "setup: git could not use the GitHub sign-in; run dd-gh-login --git" >&2
|
||||
fi
|
||||
# DroidDeck passes the live loopback adb port; a fixed one here would go stale whenever wireless debugging is toggled.
|
||||
sed -i 's|ADB_SERIAL=127.0.0.1:5555 |ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" |' "$HOME/.bashrc" 2>/dev/null || true
|
||||
grep -q 'droiddeck-agent-path' "$HOME/.bashrc" 2>/dev/null ||
|
||||
@@ -63,6 +66,29 @@ if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then
|
||||
mv "$sdk/cmdline-tools/cmdline-tools" "$sdk/cmdline-tools/latest"
|
||||
fi
|
||||
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64
|
||||
# Ubuntu's default JDK can be newer than the Gradle wrapper supports, so every shell and Gradle run
|
||||
# here uses 17, the SDK above and the qemu-wrapped aapt2, not only dd-lab-build's.
|
||||
sed -i '/^# droiddeck-agent-gradle$/,+1d' "$HOME/.bashrc" 2>/dev/null || true
|
||||
printf '# droiddeck-agent-gradle\nexport JAVA_HOME=%s ANDROID_HOME="$HOME/android-sdk"\n' "$JAVA_HOME" >> "$HOME/.bashrc"
|
||||
mkdir -p "$HOME/.gradle"
|
||||
touch "$HOME/.gradle/gradle.properties"
|
||||
# Gradle's own settings carry the SDK too, for shells that do not read ~/.bashrc.
|
||||
for setting in "org.gradle.java.home=$JAVA_HOME" "android.aapt2FromMavenOverride=$HOME/aapt2/aapt2" "systemProp.android.home=$sdk"; do
|
||||
sed -i "/^${setting%%=*}=/d" "$HOME/.gradle/gradle.properties"
|
||||
echo "$setting" >> "$HOME/.gradle/gradle.properties"
|
||||
done
|
||||
# The NDK's compilers are x86-64 only, so DroidDeck's native code is left to CI, as dd-lab-build does,
|
||||
# and Conscrypt ships no aarch64 Linux library for Robolectric to load.
|
||||
mkdir -p "$HOME/.gradle/init.d"
|
||||
cat > "$HOME/.gradle/init.d/droiddeck-device.gradle" <<'GRADLE'
|
||||
settingsEvaluated { settings ->
|
||||
if (settings.rootProject.name != 'DroidDeck') return
|
||||
gradle.startParameter.excludedTaskNames += ':app:buildVkBridgeServer'
|
||||
gradle.allprojects {
|
||||
tasks.withType(org.gradle.api.tasks.testing.Test).configureEach { systemProperty 'robolectric.conscryptMode', 'OFF' }
|
||||
}
|
||||
}
|
||||
GRADLE
|
||||
(set +o pipefail; yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null)
|
||||
"$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null
|
||||
|
||||
|
||||
@@ -35,10 +35,13 @@ GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
|
||||
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
|
||||
VULKAN_HEADERS_TAG=v1.4.341
|
||||
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
|
||||
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
|
||||
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
|
||||
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
|
||||
LAYER_VERSION=12.8
|
||||
# Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it
|
||||
# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). This build adds the
|
||||
# original Xbox fixes on top of v18 (special APC delivery, boot video aperture, 0 timer resolution: each off unless
|
||||
# droiddeck-game-env sets its variable; FileAllocationInfo, MFCreateWaveFormatEx NULL size).
|
||||
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261203-ogxbox/DroidDeck-proton-11.0-14.1-arm64ec.wcp
|
||||
LAYER_SHA256=a779747c880c64bacc0171cf26822f3398eaf32f0b214bca3448a95bf4127a90 # proton-wine ee646200 (run 47122517177)
|
||||
LAYER_VERSION=14.1
|
||||
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
|
||||
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
|
||||
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
|
||||
@@ -183,7 +186,7 @@ echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-taggi
|
||||
"$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \
|
||||
-ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" "$HERE/handoff.c" -ldl -o "$PACK/preload/libexecshim.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so"
|
||||
"$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag"
|
||||
"$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag"
|
||||
@@ -237,6 +240,11 @@ cp "$WORK/FEX/system32/"*.dll "$T/files/runtime/fex/aarch64-windows/"
|
||||
install -m 755 "$HERE/tool/proton" "$T/proton"
|
||||
install -m 755 "$HERE/tool/launch.sh" "$T/bionic/launch.sh"
|
||||
cp "$HERE/tool/desktop.reg" "$HERE/tool/Xdefaults" "$T/bionic/"
|
||||
# dd-directcontroller: the XInput DLLs launch.sh puts in the prefix of a game set to start without Steam, and the
|
||||
# host test of their ring reader
|
||||
"$HERE/dd-directcontroller/build.sh" host "$WORK/dd-directcontroller-host"
|
||||
"$WORK/dd-directcontroller-host/host_test"
|
||||
"$HERE/dd-directcontroller/build.sh" dlls "$T/bionic/dd-directcontroller"
|
||||
cp "$HERE/tool/toolmanifest.vdf" "$T/"
|
||||
# The name Steam registers the tool under ends in -Proton: Steam maps Windows save folders (WinAppDataLocal, WinMyDocuments
|
||||
# ...) into compatdata/<app>/pfx only for tools whose name contains "proton" (a case-insensitive search in
|
||||
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env bash
|
||||
# dd-directcontroller: build the XInput DLLs DroidDeck-Bionic puts in a prefix for games set to start without Steam
|
||||
# (launch.sh). Used by tools/bionic-runtime/build.sh.
|
||||
#
|
||||
# build.sh toolchain fetch the pinned llvm-mingw into $LLVM_MINGW (default ~/.cache/...)
|
||||
# build.sh dlls <outdir> <outdir>/{arm64x,i386}/<dll>.dll for every XInput DLL name, each export table
|
||||
# (both views of an ARM64X image), import list and machine type checked
|
||||
# build.sh host <outdir> <outdir>/host_test (native, cc): the ring snapshot reader against a writer
|
||||
#
|
||||
# The PE side uses bylaws/llvm-mingw (its arm64ec target does not predefine __x86_64__, unlike upstream's).
|
||||
# One C source (src/dd_directcontroller.c) is linked once per DLL name with that name's .def file (def/), so each
|
||||
# DLL has exactly the exports and ordinals of the Windows DLL it stands in for. i386 .def files get stdcall
|
||||
# decorations here and the link strips them (--kill-at).
|
||||
#
|
||||
# arm64x (system32 of the arm64ec layer): the source is compiled for ARM64EC and for native ARM64 and both
|
||||
# objects are linked into one ARM64X image (lld: -m arm64xpe, the .def for the EC view, -defarm64native for
|
||||
# the native view; each view gets its own CRT, the native one taken from the toolchain's own aarch64 link
|
||||
# line). An x64 game loads the EC view, a native ARM64 process (Wine's own control.exe, ...) the ARM64 view;
|
||||
# an ARM64EC-only image fails there with c000007b. i386 goes to syswow64 for 32-bit games.
|
||||
#
|
||||
# Every DLL carries a VERSIONINFO resource with the file version of the Wine builtin DLL it replaces, so a
|
||||
# program reading it sees the same number as before.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
LLVM_MINGW_VER=20250920
|
||||
case "$(uname -m)" in
|
||||
aarch64|arm64)
|
||||
LLVM_MINGW_HOST=aarch64; HOST_SUFFIX=-aarch64
|
||||
LLVM_MINGW_SHA256=bce5cc755c613515fd44e1ee9523123d854103abae147571adb645450036274d ;;
|
||||
*)
|
||||
LLVM_MINGW_HOST=x86_64; HOST_SUFFIX=
|
||||
LLVM_MINGW_SHA256=8dd8c34fc051a50c2fae86015f35057f8aae93fe1e19b34537ef1269a8b4c772 ;;
|
||||
esac
|
||||
LLVM_MINGW_TAR="llvm-mingw-${LLVM_MINGW_VER}-ucrt-ubuntu-22.04-${LLVM_MINGW_HOST}.tar.xz"
|
||||
LLVM_MINGW_URL="https://github.com/bylaws/llvm-mingw/releases/download/${LLVM_MINGW_VER}/${LLVM_MINGW_TAR}"
|
||||
LLVM_MINGW="${LLVM_MINGW:-$HOME/.cache/llvm-mingw-bylaws-${LLVM_MINGW_VER}${HOST_SUFFIX}}"
|
||||
|
||||
DLLS="xinput1_1 xinput1_2 xinput1_3 xinput1_4 xinput9_1_0 xinputuap"
|
||||
ARCHES="arm64x i386"
|
||||
MARKER="dd-directcontroller: "
|
||||
|
||||
say() { printf '== dd-directcontroller: %s\n' "$*"; }
|
||||
die() { printf '::error::dd-directcontroller: %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
toolchain() {
|
||||
if [ ! -x "$LLVM_MINGW/bin/arm64ec-w64-mingw32-clang" ]; then
|
||||
say "fetching $LLVM_MINGW_TAR"
|
||||
local tmp; tmp="$(mktemp -d)"
|
||||
curl -fsSL --retry 5 --retry-delay 5 -o "$tmp/t.tar.xz" "$LLVM_MINGW_URL"
|
||||
echo "$LLVM_MINGW_SHA256 $tmp/t.tar.xz" | sha256sum -c -
|
||||
mkdir -p "$LLVM_MINGW"
|
||||
tar -xJf "$tmp/t.tar.xz" -C "$LLVM_MINGW" --strip-components=1
|
||||
rm -rf "$tmp"
|
||||
fi
|
||||
export PATH="$LLVM_MINGW/bin:$PATH"
|
||||
for t in i686 arm64ec aarch64; do
|
||||
command -v "$t-w64-mingw32-clang" >/dev/null || die "llvm-mingw has no $t-w64-mingw32-clang"
|
||||
done
|
||||
for t in i686 aarch64; do
|
||||
command -v "$t-w64-mingw32-windres" >/dev/null || die "llvm-mingw has no $t-w64-mingw32-windres"
|
||||
done
|
||||
say "llvm-mingw $LLVM_MINGW_VER: $(arm64ec-w64-mingw32-clang --version | head -1)"
|
||||
}
|
||||
|
||||
windres_for() {
|
||||
case "$1" in
|
||||
i386) echo i686-w64-mingw32-windres ;;
|
||||
arm64x) echo aarch64-w64-mingw32-windres ;;
|
||||
*) die "unknown arch $1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# File version of the Wine builtin each DLL replaces (dlls/<name>/version.rc).
|
||||
DLL_VERSIONS='xinput1_1:9,12,589,0 xinput1_2:9,14,701,0 xinput1_3:9,15,779,0 xinput1_4:6,3,9600,16384 xinput9_1_0:9,10,455,0 xinputuap:10,0,19041,746'
|
||||
|
||||
version_res() { # version_res <arch> <dll> <tmpdir> -> path of a COFF object with the DLL's VERSIONINFO
|
||||
local ver="" kv rc="$3/$2.rc" obj="$3/$2-ver-$1.o"
|
||||
for kv in $DLL_VERSIONS; do [ "${kv%%:*}" = "$2" ] && ver="${kv#*:}"; done
|
||||
[ -n "$ver" ] || die "no version for $2 in DLL_VERSIONS"
|
||||
cat >"$rc" <<EOF
|
||||
1 VERSIONINFO
|
||||
FILEVERSION $ver
|
||||
PRODUCTVERSION $ver
|
||||
FILEFLAGSMASK 0x3f
|
||||
FILEFLAGS 0x0
|
||||
FILEOS 0x40004
|
||||
FILETYPE 0x2
|
||||
FILESUBTYPE 0x0
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904b0"
|
||||
BEGIN
|
||||
VALUE "CompanyName", "DroidDeck"
|
||||
VALUE "FileDescription", "dd-directcontroller controller API (DroidDeck)"
|
||||
VALUE "FileVersion", "${ver//,/.}"
|
||||
VALUE "InternalName", "$2"
|
||||
VALUE "LegalCopyright", "GPL-3.0"
|
||||
VALUE "OriginalFilename", "$2.dll"
|
||||
VALUE "ProductName", "DroidDeck"
|
||||
VALUE "ProductVersion", "${ver//,/.}"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1200
|
||||
END
|
||||
END
|
||||
EOF
|
||||
"$(windres_for "$1")" "$rc" -O coff -o "$obj"
|
||||
echo "$obj"
|
||||
}
|
||||
|
||||
# stdcall argument bytes of every export (i386 decoration).
|
||||
I386_DECOR='DllMain:12 XInputGetState:8 XInputSetState:8 XInputGetStateEx:8 XInputGetCapabilities:12 XInputGetDSoundAudioDeviceGuids:12 XInputGetBatteryInformation:12 XInputGetKeystroke:12 XInputWaitForGuideButton:12 XInputEnable:4 XInputCancelGuideButtonWait:4 XInputPowerOffController:4 XInputGetAudioDeviceIds:20 XInputGetCapabilitiesEx:16'
|
||||
|
||||
def_for() { # def_for <arch> <dll> <tmpdir> -> path of the .def to link with
|
||||
local src="$HERE/def/$2.def"
|
||||
if [ "$1" != i386 ]; then echo "$src"; return; fi
|
||||
awk -v table="$I386_DECOR" 'BEGIN { n = split(table, a, " "); for (i = 1; i <= n; i++) { split(a[i], kv, ":"); m[kv[1]] = kv[2] } }
|
||||
($1 in m) { sub($1, $1 "@" m[$1]) } { print }' "$src" > "$3/$2.def"
|
||||
echo "$3/$2.def"
|
||||
}
|
||||
|
||||
# expected "<ordinal> <name|->" lines of a .def (NONAME exports have no name)
|
||||
def_exports() {
|
||||
awk 'f && NF { ord = ""; for (i = 2; i <= NF; i++) if ($i ~ /^@[0-9]+$/) ord = substr($i, 2);
|
||||
name = $1; for (i = 2; i <= NF; i++) if ($i == "NONAME") name = "-";
|
||||
print (ord == "" ? "?" : ord), name }
|
||||
/^EXPORTS/ { f = 1 }' "$1" | sort
|
||||
}
|
||||
|
||||
# actual "<ordinal> <name|->" lines of a DLL (unused ordinals between the numbered ones have RVA 0 and are
|
||||
# skipped). dll_exports <file> [main|hybrid]: llvm-readobj prints an ARM64X image's native view first, then
|
||||
# its EC view inside "HybridObject {".
|
||||
dll_exports() {
|
||||
llvm-readobj --coff-exports "$1" | awk -v view="${2:-main}" '
|
||||
/HybridObject \{/ { h = 1; next }
|
||||
(view == "main" && h) || (view == "hybrid" && !h) { next }
|
||||
/^ *Export \{/ { o = ""; n = "-"; r = "" }
|
||||
/^ *Ordinal:/ { o = $2 }
|
||||
/^ *Name:/ { if (NF >= 2) n = $2 }
|
||||
/^ *RVA:/ { r = $2 }
|
||||
/^ *\}/ { if (o != "" && r != "" && r != "0x0") print o, n; o = "" }' | sort
|
||||
}
|
||||
|
||||
compare_exports() { # compare_exports <label> <file> <def> <view>
|
||||
local want got
|
||||
want="$(def_exports "$HERE/def/$3.def")"
|
||||
got="$(dll_exports "$2" "$4")"
|
||||
if [ "$want" != "$got" ]; then
|
||||
printf 'want:\n%s\ngot:\n%s\n' "$want" "$got"
|
||||
die "$1 exports differ from def/$3.def"
|
||||
fi
|
||||
}
|
||||
|
||||
check_dll() { # check_dll <arch> <dll name> <file>
|
||||
local arch="$1" name="$2" f="$3" fmts fmt hyb machine lc imports bad res
|
||||
fmts="$(llvm-readobj --file-headers "$f" | sed -n 's/^ *Format: //p')"
|
||||
fmt="$(sed -n 1p <<<"$fmts")"
|
||||
hyb="$(sed -n 2p <<<"$fmts")"
|
||||
case "$arch" in
|
||||
i386) [ "$fmt" = "COFF-i386" ] && [ -z "$hyb" ] || die "$f is $fmt${hyb:+ + $hyb}, want COFF-i386" ;;
|
||||
arm64x)
|
||||
# Native view: an ARM64 PE (what an ARM64 process maps). EC view: ARM64EC (what an x64 process sees
|
||||
# through the ARM64X dynamic relocations). Both need the CHPE metadata.
|
||||
machine="$(python3 -c 'import struct,sys; d=open(sys.argv[1],"rb").read(4096); o=struct.unpack_from("<I",d,0x3c)[0]; print(hex(struct.unpack_from("<H",d,o+4)[0]) if d[o:o+4]==b"PE\0\0" else "?")' "$f")"
|
||||
[ "$machine" = 0xaa64 ] || die "$f PE header machine is $machine, want 0xaa64 (ARM64)"
|
||||
[ "$hyb" = "COFF-ARM64EC" ] || die "$f has no ARM64EC hybrid view (formats: $(echo $fmts))"
|
||||
lc="$(llvm-readobj --coff-load-config "$f")"
|
||||
grep -q 'CHPEMetadata' <<<"$lc" || die "$f has no CHPE metadata"
|
||||
grep -q 'Arm64X' <<<"$lc" || die "$f has no ARM64X dynamic relocations"
|
||||
# One TLS directory serves both views and would list native ARM64 callbacks (see src/notls.c).
|
||||
llvm-readobj --file-headers "$f" | grep -q 'TLSTableRVA: 0x[1-9a-fA-F]' && die "$f has a TLS directory"
|
||||
fmt="$fmt/$hyb/$machine"
|
||||
;;
|
||||
esac
|
||||
compare_exports "$arch/$name.dll" "$f" "$name" main
|
||||
[ "$arch" != arm64x ] || compare_exports "$arch/$name.dll (EC view)" "$f" "$name" hybrid
|
||||
imports="$(llvm-readobj --coff-imports "$f" | sed -n 's/^ *Name: //p' | tr 'A-Z' 'a-z' | sort -u)"
|
||||
bad="$(grep -vxE 'kernel32\.dll|ucrtbase\.dll|msvcrt\.dll|api-ms-win-crt-[a-z0-9-]+\.dll' <<<"$imports" || true)"
|
||||
[ -z "$bad" ] || die "$arch/$name.dll imports $(echo $bad) (only kernel32 and the C runtime are allowed)"
|
||||
grep -aqF "$MARKER" "$f" || die "$arch/$name.dll lacks its '$MARKER' marker (launch.sh and the rumble path look for it)"
|
||||
res="$(llvm-readobj --coff-resources "$f")"
|
||||
grep -q 'Type: VERSIONINFO (ID 16)' <<<"$res" || die "$arch/$name.dll has no VERSIONINFO resource"
|
||||
printf ' %-7s %-15s %6d bytes %-24s imports: %s\n' "$arch" "$name.dll" "$(stat -c %s "$f")" "$fmt" "$(echo $imports)"
|
||||
}
|
||||
|
||||
# The objects and archives the toolchain links into an aarch64 DLL (CRT start-up, mingw/ucrt/kernel32 import
|
||||
# libraries, compiler-rt), as absolute paths: the native view of an ARM64X image needs its own.
|
||||
native_link_inputs() { # native_link_inputs <tmpdir>
|
||||
printf 'int x;\n' > "$1/empty.c"
|
||||
aarch64-w64-mingw32-clang -shared -o "$1/empty.dll" "$1/empty.c" -### 2>&1 | python3 -c '
|
||||
import os, shlex, sys
|
||||
line = [l for l in sys.stdin.read().splitlines() if "ld.lld" in l or "lld-link" in l]
|
||||
if not line:
|
||||
sys.exit("no link line in the -### output")
|
||||
toks = shlex.split(line[-1])
|
||||
dirs = [t[2:] for t in toks if t.startswith("-L")]
|
||||
out = []
|
||||
for t in toks[1:]:
|
||||
if t.startswith("-l"):
|
||||
name = t[2:]
|
||||
hit = next((os.path.join(d, c) for d in dirs for c in ("lib%s.a" % name, "lib%s.dll.a" % name, "%s.lib" % name)
|
||||
if os.path.isfile(os.path.join(d, c))), None)
|
||||
if not hit:
|
||||
sys.exit("cannot resolve -l%s in %s" % (name, dirs))
|
||||
out.append(hit)
|
||||
elif t.endswith((".o", ".a", ".obj", ".lib")) and os.path.isabs(t) and os.path.isfile(t):
|
||||
out.append(t)
|
||||
seen = set()
|
||||
print("\n".join(p for p in out if not (p in seen or seen.add(p))))
|
||||
'
|
||||
}
|
||||
|
||||
# notls-*.o (src/notls.c) come before the CRT so the image gets no TLS directory.
|
||||
link_arm64x() { # link_arm64x <out> <def> <ec obj> <native obj> <native inputs file> <ec notls obj> <native notls obj> <version res obj>
|
||||
local nat=()
|
||||
mapfile -t nat <"$5"
|
||||
arm64ec-w64-mingw32-clang -shared -s -Wl,--no-insert-timestamp -Wl,-marm64xpe "-Wl,--Xlink=-defarm64native:$2" \
|
||||
-o "$1" "$3" "$6" "$4" "$7" "$8" "$2" "${nat[@]}" -lkernel32
|
||||
}
|
||||
|
||||
CFLAGS_COMMON="-std=gnu11 -O2 -Wall -Wextra -Werror -fno-strict-aliasing -I$HERE/src"
|
||||
|
||||
dlls() {
|
||||
local out="${1:?usage: build.sh dlls <outdir>}" tmp arch name def
|
||||
toolchain
|
||||
mkdir -p "$out"; out="$(cd "$out" && pwd)"
|
||||
tmp="$(mktemp -d)"
|
||||
for arch in $ARCHES; do
|
||||
mkdir -p "$out/$arch"
|
||||
if [ "$arch" = arm64x ]; then
|
||||
arm64ec-w64-mingw32-clang $CFLAGS_COMMON -DDDC_HYBRID=1 -c "$HERE/src/dd_directcontroller.c" -o "$tmp/ddc-arm64ec.o"
|
||||
aarch64-w64-mingw32-clang $CFLAGS_COMMON -DDDC_HYBRID=1 -c "$HERE/src/dd_directcontroller.c" -o "$tmp/ddc-aarch64.o"
|
||||
arm64ec-w64-mingw32-clang $CFLAGS_COMMON -c "$HERE/src/notls.c" -o "$tmp/notls-arm64ec.o"
|
||||
aarch64-w64-mingw32-clang $CFLAGS_COMMON -c "$HERE/src/notls.c" -o "$tmp/notls-aarch64.o"
|
||||
native_link_inputs "$tmp" >"$tmp/native-inputs"
|
||||
for name in $DLLS; do
|
||||
link_arm64x "$out/$arch/$name.dll" "$HERE/def/$name.def" "$tmp/ddc-arm64ec.o" "$tmp/ddc-aarch64.o" "$tmp/native-inputs" \
|
||||
"$tmp/notls-arm64ec.o" "$tmp/notls-aarch64.o" "$(version_res "$arch" "$name" "$tmp")"
|
||||
check_dll "$arch" "$name" "$out/$arch/$name.dll"
|
||||
done
|
||||
continue
|
||||
fi
|
||||
# i386: SSE2 so a full fence is mfence
|
||||
i686-w64-mingw32-clang $CFLAGS_COMMON -msse2 -mfpmath=sse -c "$HERE/src/dd_directcontroller.c" -o "$tmp/ddc-i386.o"
|
||||
for name in $DLLS; do
|
||||
def="$(def_for "$arch" "$name" "$tmp")"
|
||||
i686-w64-mingw32-clang -shared -s -Wl,--no-insert-timestamp -Wl,--kill-at -o "$out/$arch/$name.dll" "$tmp/ddc-i386.o" \
|
||||
"$(version_res "$arch" "$name" "$tmp")" "$def" -lkernel32
|
||||
check_dll "$arch" "$name" "$out/$arch/$name.dll"
|
||||
done
|
||||
done
|
||||
rm -rf "$tmp"
|
||||
say "$(ls "$out"/*/*.dll | wc -l) DLLs in $out"
|
||||
}
|
||||
|
||||
host() {
|
||||
local out="${1:?usage: build.sh host <outdir>}"
|
||||
mkdir -p "$out"
|
||||
"${CC:-cc}" -std=gnu11 -O2 -Wall -Wextra -Werror -pthread -I"$HERE/src" -o "$out/host_test" "$HERE/test/host_test.c"
|
||||
say "host_test built for $(uname -m)"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
toolchain) toolchain ;;
|
||||
dlls) dlls "${2:-}" ;;
|
||||
host) host "${2:-}" ;;
|
||||
*) die "usage: $0 toolchain | dlls <outdir> | host <outdir>" ;;
|
||||
esac
|
||||
@@ -0,0 +1,11 @@
|
||||
LIBRARY xinput1_1.dll
|
||||
EXPORTS
|
||||
XInputEnable @1
|
||||
XInputGetCapabilities @2
|
||||
XInputGetDSoundAudioDeviceGuids @3
|
||||
XInputSetState @4
|
||||
XInputGetState @5
|
||||
XInputGetStateEx @100
|
||||
XInputWaitForGuideButton @101
|
||||
XInputCancelGuideButtonWait @102
|
||||
XInputPowerOffController @103
|
||||
@@ -0,0 +1,11 @@
|
||||
LIBRARY xinput1_2.dll
|
||||
EXPORTS
|
||||
XInputEnable @1
|
||||
XInputGetCapabilities @2
|
||||
XInputGetDSoundAudioDeviceGuids @3
|
||||
XInputSetState @4
|
||||
XInputGetState @5
|
||||
XInputGetStateEx @100
|
||||
XInputWaitForGuideButton @101
|
||||
XInputCancelGuideButtonWait @102
|
||||
XInputPowerOffController @103
|
||||
@@ -0,0 +1,14 @@
|
||||
LIBRARY xinput1_3.dll
|
||||
EXPORTS
|
||||
DllMain @1
|
||||
XInputGetState @2
|
||||
XInputSetState @3
|
||||
XInputGetCapabilities @4
|
||||
XInputEnable @5
|
||||
XInputGetDSoundAudioDeviceGuids @6
|
||||
XInputGetBatteryInformation @7
|
||||
XInputGetKeystroke @8
|
||||
XInputGetStateEx @100
|
||||
XInputWaitForGuideButton @101
|
||||
XInputCancelGuideButtonWait @102
|
||||
XInputPowerOffController @103
|
||||
@@ -0,0 +1,15 @@
|
||||
LIBRARY xinput1_4.dll
|
||||
EXPORTS
|
||||
DllMain @1
|
||||
XInputGetState @2
|
||||
XInputSetState @3
|
||||
XInputGetCapabilities @4
|
||||
XInputEnable @5
|
||||
XInputGetBatteryInformation @7
|
||||
XInputGetKeystroke @8
|
||||
XInputGetAudioDeviceIds @10
|
||||
XInputGetStateEx @100
|
||||
XInputWaitForGuideButton @101
|
||||
XInputCancelGuideButtonWait @102
|
||||
XInputPowerOffController @103
|
||||
XInputGetCapabilitiesEx @108
|
||||
@@ -0,0 +1,10 @@
|
||||
LIBRARY xinput9_1_0.dll
|
||||
EXPORTS
|
||||
XInputGetCapabilities @1
|
||||
XInputGetDSoundAudioDeviceGuids @2
|
||||
XInputSetState @3
|
||||
XInputGetState @4
|
||||
XInputGetStateEx @100
|
||||
XInputWaitForGuideButton @101
|
||||
XInputCancelGuideButtonWait @102
|
||||
XInputPowerOffController @103
|
||||
@@ -0,0 +1,14 @@
|
||||
LIBRARY xinputuap.dll
|
||||
EXPORTS
|
||||
DllMain @1
|
||||
XInputEnable @2
|
||||
XInputGetAudioDeviceIds @3
|
||||
XInputGetBatteryInformation @4
|
||||
XInputGetCapabilities @5
|
||||
XInputGetKeystroke @6
|
||||
XInputGetState @7
|
||||
XInputSetState @8
|
||||
XInputGetStateEx @100
|
||||
XInputWaitForGuideButton @101
|
||||
XInputCancelGuideButtonWait @102
|
||||
XInputPowerOffController @103
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* dd-directcontroller: the read side of DroidDeck's controller ring file (one per pad slot), shared by the
|
||||
* XInput DLL and its host test.
|
||||
*
|
||||
* The app (input/FakeInputWriter.java) writes each slot's ring file; fakeinput_steam.cpp reads its events
|
||||
* for Wine's evdev path. The 64-byte header (FakeInputRingHeader, ABI-stable) also carries a snapshot of
|
||||
* the whole pad that the writer updates on every publish, under a sequence counter:
|
||||
*
|
||||
* 0 u32 magic 0x46494252 16 u64 write_seq 40 u32 snapshot buttons (bit = BUTTON_MAP index)
|
||||
* 4 u32 version 2 24 u64 generation 44 i16 snapshot axes[8]
|
||||
* 8 u32 event size 24 32 u64 snapshot_seq 60 u32 resync_seq
|
||||
* 12 u32 capacity 4096
|
||||
*
|
||||
* Snapshot protocol (FakeInputWriter.writeSnapshotLocked): seq + 1 (odd), store fence, buttons and axes,
|
||||
* store fence, seq + 2 (even). A reader takes the state when it saw the same even seq before and after.
|
||||
* Only 32-bit loads are used: on i386 a 64-bit atomic load is a cmpxchg8b, which writes and so faults on a
|
||||
* read-only view; the low halves of seq and generation are enough to see a change.
|
||||
*
|
||||
* Axes: [0] left X, [1] left Y, [2] right X, [3] right Y (evdev sense, -32767..32767, Y positive = down),
|
||||
* [4] right trigger, [5] left trigger (0..255), [6] hat X, [7] hat Y (-1, 0, 1; Y -1 = up).
|
||||
*/
|
||||
#ifndef DD_DIRECTCONTROLLER_RING_H
|
||||
#define DD_DIRECTCONTROLLER_RING_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define DDC_RING_MAGIC 0x46494252u
|
||||
#define DDC_RING_VERSION 2u
|
||||
#define DDC_RING_EVENT_SIZE 24u
|
||||
#define DDC_RING_CAPACITY 4096u
|
||||
#define DDC_RING_HEADER_SIZE 64u
|
||||
|
||||
#define DDC_OFF_MAGIC 0u
|
||||
#define DDC_OFF_VERSION 4u
|
||||
#define DDC_OFF_EVENT_SIZE 8u
|
||||
#define DDC_OFF_CAPACITY 12u
|
||||
#define DDC_OFF_GENERATION 24u /* low half */
|
||||
#define DDC_OFF_SNAP_SEQ 32u /* low half */
|
||||
#define DDC_OFF_SNAP_BUTTONS 40u
|
||||
#define DDC_OFF_SNAP_AXES 44u
|
||||
|
||||
/* Snapshot button bits: FakeInputWriter.BUTTON_MAP index (QAM = DroidDeck's quick-access button). */
|
||||
enum {
|
||||
DDC_B_A, DDC_B_B, DDC_B_X, DDC_B_Y, DDC_B_TL, DDC_B_TR, DDC_B_SELECT, DDC_B_START,
|
||||
DDC_B_THUMBL, DDC_B_THUMBR, DDC_B_MODE, DDC_B_QAM,
|
||||
};
|
||||
|
||||
enum { DDC_A_LX, DDC_A_LY, DDC_A_RX, DDC_A_RY, DDC_A_RT, DDC_A_LT, DDC_A_HATX, DDC_A_HATY };
|
||||
|
||||
/* XInput button bits */
|
||||
#define DDC_XI_DPAD_UP 0x0001u
|
||||
#define DDC_XI_DPAD_DOWN 0x0002u
|
||||
#define DDC_XI_DPAD_LEFT 0x0004u
|
||||
#define DDC_XI_DPAD_RIGHT 0x0008u
|
||||
#define DDC_XI_START 0x0010u
|
||||
#define DDC_XI_BACK 0x0020u
|
||||
#define DDC_XI_LEFT_THUMB 0x0040u
|
||||
#define DDC_XI_RIGHT_THUMB 0x0080u
|
||||
#define DDC_XI_LEFT_SHOULDER 0x0100u
|
||||
#define DDC_XI_RIGHT_SHOULDER 0x0200u
|
||||
#define DDC_XI_GUIDE 0x0400u
|
||||
#define DDC_XI_A 0x1000u
|
||||
#define DDC_XI_B 0x2000u
|
||||
#define DDC_XI_X 0x4000u
|
||||
#define DDC_XI_Y 0x8000u
|
||||
|
||||
typedef struct {
|
||||
uint32_t seq; /* low half of snapshot_seq (even) */
|
||||
uint32_t generation; /* low half */
|
||||
uint32_t buttons;
|
||||
int16_t axes[8];
|
||||
} ddc_snap;
|
||||
|
||||
typedef struct {
|
||||
uint16_t buttons;
|
||||
uint8_t lt, rt;
|
||||
int16_t lx, ly, rx, ry;
|
||||
} ddc_pad;
|
||||
|
||||
static inline uint32_t ddc_ld32(const uint8_t *v, uint32_t off, int order) {
|
||||
return __atomic_load_n((const uint32_t *)(const void *)(v + off), order);
|
||||
}
|
||||
|
||||
/* 1 if the view starts with a version-2 ring header of the size this file reads. */
|
||||
static inline int ddc_valid(const uint8_t *v) {
|
||||
return ddc_ld32(v, DDC_OFF_MAGIC, __ATOMIC_RELAXED) == DDC_RING_MAGIC &&
|
||||
ddc_ld32(v, DDC_OFF_VERSION, __ATOMIC_RELAXED) == DDC_RING_VERSION &&
|
||||
ddc_ld32(v, DDC_OFF_EVENT_SIZE, __ATOMIC_RELAXED) == DDC_RING_EVENT_SIZE &&
|
||||
ddc_ld32(v, DDC_OFF_CAPACITY, __ATOMIC_RELAXED) == DDC_RING_CAPACITY;
|
||||
}
|
||||
|
||||
/* A consistent copy of the snapshot, in at most `attempts` tries; 0 if the writer kept lapping it. */
|
||||
static inline int ddc_snapshot(const uint8_t *v, ddc_snap *out, unsigned attempts) {
|
||||
for (unsigned i = 0; i < attempts; i++) {
|
||||
uint32_t s1 = ddc_ld32(v, DDC_OFF_SNAP_SEQ, __ATOMIC_ACQUIRE);
|
||||
if (s1 & 1u) continue;
|
||||
uint32_t gen = ddc_ld32(v, DDC_OFF_GENERATION, __ATOMIC_RELAXED);
|
||||
uint32_t buttons = ddc_ld32(v, DDC_OFF_SNAP_BUTTONS, __ATOMIC_RELAXED);
|
||||
uint32_t w[4];
|
||||
for (unsigned k = 0; k < 4; k++) w[k] = ddc_ld32(v, DDC_OFF_SNAP_AXES + 4u * k, __ATOMIC_RELAXED);
|
||||
__atomic_thread_fence(__ATOMIC_ACQUIRE);
|
||||
if (ddc_ld32(v, DDC_OFF_SNAP_SEQ, __ATOMIC_RELAXED) != s1) continue;
|
||||
out->seq = s1;
|
||||
out->generation = gen;
|
||||
out->buttons = buttons;
|
||||
for (unsigned k = 0; k < 4; k++) { /* little endian: axis 2k in the low half */
|
||||
out->axes[2 * k] = (int16_t)(uint16_t)(w[k] & 0xffffu);
|
||||
out->axes[2 * k + 1] = (int16_t)(uint16_t)(w[k] >> 16);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static inline int16_t ddc_flip(int16_t v) { /* evdev Y (down = +) to XInput Y (up = +) */
|
||||
return v == INT16_MIN ? INT16_MAX : (int16_t)-v;
|
||||
}
|
||||
|
||||
static inline uint8_t ddc_trigger(int16_t v) {
|
||||
return v <= 0 ? 0 : v >= 255 ? 255 : (uint8_t)v;
|
||||
}
|
||||
|
||||
/* The snapshot as an XInput pad; Guide only when `guide` (XInputGetStateEx). */
|
||||
static inline void ddc_map(const ddc_snap *s, int guide, ddc_pad *p) {
|
||||
static const uint16_t bit[11] = {
|
||||
DDC_XI_A, DDC_XI_B, DDC_XI_X, DDC_XI_Y, DDC_XI_LEFT_SHOULDER, DDC_XI_RIGHT_SHOULDER,
|
||||
DDC_XI_BACK, DDC_XI_START, DDC_XI_LEFT_THUMB, DDC_XI_RIGHT_THUMB, DDC_XI_GUIDE,
|
||||
};
|
||||
uint16_t b = 0;
|
||||
for (unsigned i = 0; i < 11; i++)
|
||||
if (s->buttons & (1u << i)) b |= bit[i];
|
||||
if (!guide) b &= (uint16_t)~DDC_XI_GUIDE;
|
||||
if (s->axes[DDC_A_HATX] < 0) b |= DDC_XI_DPAD_LEFT;
|
||||
if (s->axes[DDC_A_HATX] > 0) b |= DDC_XI_DPAD_RIGHT;
|
||||
if (s->axes[DDC_A_HATY] < 0) b |= DDC_XI_DPAD_UP;
|
||||
if (s->axes[DDC_A_HATY] > 0) b |= DDC_XI_DPAD_DOWN;
|
||||
p->buttons = b;
|
||||
p->lx = s->axes[DDC_A_LX];
|
||||
p->ly = ddc_flip(s->axes[DDC_A_LY]);
|
||||
p->rx = s->axes[DDC_A_RX];
|
||||
p->ry = ddc_flip(s->axes[DDC_A_RY]);
|
||||
p->lt = ddc_trigger(s->axes[DDC_A_LT]);
|
||||
p->rt = ddc_trigger(s->axes[DDC_A_RT]);
|
||||
}
|
||||
|
||||
/* FAKE_EVDEV_MEMFD_PATHS: "<slot>=<unix path>;..." -> take(ctx, slot, path, len) for slots 0..max-1. */
|
||||
#define DDC_DEFINE_PARSE_PATHS(fname, CH) \
|
||||
static void fname(const CH *s, void (*take)(void *, uint32_t, const CH *, size_t), void *ctx, \
|
||||
uint32_t max) { \
|
||||
while (s && *s) { \
|
||||
const CH *e = s; \
|
||||
while (*e && *e != ';') e++; \
|
||||
const CH *q = s; \
|
||||
uint32_t slot = 0; \
|
||||
int digits = 0; \
|
||||
while (q < e && *q >= '0' && *q <= '9' && digits < 3) slot = slot * 10u + (uint32_t)(*q++ - '0'), digits++; \
|
||||
if (digits && q < e && *q == '=' && q + 1 < e && slot < max) take(ctx, slot, q + 1, (size_t)(e - q - 1)); \
|
||||
s = *e ? e + 1 : e; \
|
||||
} \
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Linked into both views of the ARM64X image only (build.sh link_arm64x), ahead of the mingw CRT.
|
||||
*
|
||||
* The CRT's DLL start-up (dllcrt2.o) references __dyn_tls_init_callback, which pulls tlssup.o and
|
||||
* with it _tls_used, the TLS directory. An ARM64X image has one TLS directory for both views (the
|
||||
* linker takes the native view's and emits no ARM64X relocation for it), so its callbacks are the
|
||||
* native ARM64 ones. In an x64 process (the EC view) Wine treats non-EC code as x64 and the emulator
|
||||
* runs those ARM64 bytes as x86 on every thread start: a stray write to the image header (base+0x42)
|
||||
* that the loader catches, but a game's own first-chance exception handler sees first (Cyberpunk
|
||||
* 2077's crash reporter exits on it).
|
||||
*
|
||||
* Defining the symbol here keeps tlssup.o out, so the image has no TLS directory. The CRT checks the
|
||||
* pointer for NULL before calling it; this DLL has no thread-local variables.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
const PIMAGE_TLS_CALLBACK __dyn_tls_init_callback = NULL;
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* dd-directcontroller host test: the ring snapshot reader (dd_directcontroller_ring.h) against a writer that follows
|
||||
* FakeInputWriter.writeSnapshotLocked, on a shared file mapping (the app and the guest map the same file),
|
||||
* plus the XInput mapping and the FAKE_EVDEV_MEMFD_PATHS parser.
|
||||
*/
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "dd_directcontroller_ring.h"
|
||||
|
||||
static int failures;
|
||||
#define CHECK(c, ...) do { if (!(c)) { failures++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
static uint8_t *wmap;
|
||||
static volatile int stop;
|
||||
|
||||
static void put32(uint32_t off, uint32_t v) { __atomic_store_n((uint32_t *)(void *)(wmap + off), v, __ATOMIC_RELAXED); }
|
||||
static void put64(uint32_t off, uint64_t v) { __atomic_store_n((uint64_t *)(void *)(wmap + off), v, __ATOMIC_RELAXED); }
|
||||
|
||||
static void header(void) {
|
||||
put32(DDC_OFF_MAGIC, DDC_RING_MAGIC);
|
||||
put32(DDC_OFF_VERSION, DDC_RING_VERSION);
|
||||
put32(DDC_OFF_EVENT_SIZE, DDC_RING_EVENT_SIZE);
|
||||
put32(DDC_OFF_CAPACITY, DDC_RING_CAPACITY);
|
||||
}
|
||||
|
||||
/* FakeInputWriter.writeSnapshotLocked: seq + 1, fence, fields, fence, seq + 2 */
|
||||
static void publish(uint64_t *seq, uint32_t buttons, const int16_t axes[8]) {
|
||||
put64(DDC_OFF_SNAP_SEQ, *seq + 1);
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
put32(DDC_OFF_SNAP_BUTTONS, buttons);
|
||||
for (int k = 0; k < 8; k++)
|
||||
__atomic_store_n((int16_t *)(void *)(wmap + DDC_OFF_SNAP_AXES + 2 * k), axes[k], __ATOMIC_RELAXED);
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
put64(DDC_OFF_SNAP_SEQ, *seq + 2);
|
||||
*seq += 2;
|
||||
}
|
||||
|
||||
/* Every field carries the same counter, so a torn read shows up as fields that differ. */
|
||||
static uint64_t writer_seq;
|
||||
|
||||
static void *writer(void *arg) {
|
||||
(void)arg;
|
||||
uint64_t seq = writer_seq; /* the sequence continues: a reused value would let a stale read pass (ABA) */
|
||||
uint32_t n = 1;
|
||||
while (!stop) {
|
||||
int16_t v = (int16_t)(n & 0x3fff);
|
||||
int16_t axes[8] = {v, v, v, v, v, v, v, v};
|
||||
publish(&seq, (uint32_t)v, axes);
|
||||
n++;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void take(void *ctx, uint32_t slot, const char *p, size_t len) {
|
||||
char *out = ctx;
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof buf, "%u:%.*s|", slot, (int)len, p);
|
||||
strcat(out, buf);
|
||||
}
|
||||
DDC_DEFINE_PARSE_PATHS(parse_paths, char)
|
||||
|
||||
int main(void) {
|
||||
char path[] = "/tmp/ddc-ring-XXXXXX";
|
||||
int fd = mkstemp(path);
|
||||
CHECK(fd >= 0, "mkstemp");
|
||||
size_t size = DDC_RING_HEADER_SIZE + DDC_RING_CAPACITY * DDC_RING_EVENT_SIZE;
|
||||
CHECK(ftruncate(fd, (off_t)size) == 0, "ftruncate");
|
||||
wmap = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
const uint8_t *rmap = mmap(NULL, DDC_RING_HEADER_SIZE, PROT_READ, MAP_SHARED, fd, 0);
|
||||
CHECK(wmap != MAP_FAILED && rmap != MAP_FAILED, "mmap");
|
||||
unlink(path);
|
||||
|
||||
CHECK(!ddc_valid(rmap), "an empty file is not a ring");
|
||||
header();
|
||||
CHECK(ddc_valid(rmap), "a version-2 header is a ring");
|
||||
put32(DDC_OFF_VERSION, 1);
|
||||
CHECK(!ddc_valid(rmap), "version 1 is refused");
|
||||
put32(DDC_OFF_VERSION, DDC_RING_VERSION);
|
||||
|
||||
/* mapping */
|
||||
uint64_t seq = 0;
|
||||
int16_t axes[8] = {1000, 2000, -3000, -32767, 255, 128, -1, 1};
|
||||
uint32_t buttons = (1u << DDC_B_A) | (1u << DDC_B_TR) | (1u << DDC_B_START) | (1u << DDC_B_MODE) | (1u << DDC_B_QAM);
|
||||
publish(&seq, buttons, axes);
|
||||
ddc_snap s;
|
||||
CHECK(ddc_snapshot(rmap, &s, 64), "snapshot of a settled ring");
|
||||
CHECK(s.seq == 2, "seq %u", s.seq);
|
||||
ddc_pad p;
|
||||
ddc_map(&s, 0, &p);
|
||||
CHECK(p.buttons == (DDC_XI_A | DDC_XI_RIGHT_SHOULDER | DDC_XI_START | DDC_XI_DPAD_LEFT | DDC_XI_DPAD_DOWN),
|
||||
"buttons 0x%04x (no Guide, no QAM, hat left + down)", p.buttons);
|
||||
CHECK(p.lx == 1000 && p.ly == -2000 && p.rx == -3000 && p.ry == 32767, "sticks %d %d %d %d (Y flipped)", p.lx, p.ly,
|
||||
p.rx, p.ry);
|
||||
CHECK(p.rt == 255 && p.lt == 128, "triggers lt %u rt %u", p.lt, p.rt);
|
||||
ddc_map(&s, 1, &p);
|
||||
CHECK(p.buttons & DDC_XI_GUIDE, "Guide in GetStateEx");
|
||||
int16_t edge[8] = {INT16_MIN, INT16_MIN, 0, 0, -5, 300, 0, -1};
|
||||
publish(&seq, 0, edge);
|
||||
CHECK(ddc_snapshot(rmap, &s, 64), "snapshot");
|
||||
ddc_map(&s, 0, &p);
|
||||
CHECK(p.ly == INT16_MAX && p.lt == 255 && p.rt == 0 && p.buttons == DDC_XI_DPAD_UP, "edges: ly %d lt %u rt %u b 0x%x",
|
||||
p.ly, p.lt, p.rt, p.buttons);
|
||||
|
||||
/* an odd seq (a write in progress) is never taken */
|
||||
put64(DDC_OFF_SNAP_SEQ, seq + 1);
|
||||
CHECK(!ddc_snapshot(rmap, &s, 64), "a snapshot mid-write is refused");
|
||||
put64(DDC_OFF_SNAP_SEQ, seq);
|
||||
|
||||
/* no torn reads against a running writer; the state before its first publish is consistent too */
|
||||
int16_t zero[8] = {0};
|
||||
publish(&seq, 0, zero);
|
||||
writer_seq = seq;
|
||||
pthread_t t;
|
||||
pthread_create(&t, NULL, writer, NULL);
|
||||
unsigned ok = 0, lapped = 0, torn = 0;
|
||||
for (unsigned i = 0; i < 2000000u; i++) {
|
||||
if (!ddc_snapshot(rmap, &s, 64)) { lapped++; continue; }
|
||||
ok++;
|
||||
for (int k = 1; k < 8; k++)
|
||||
if (s.axes[k] != s.axes[0]) { torn++; break; }
|
||||
if ((int16_t)s.buttons != s.axes[0]) torn++;
|
||||
}
|
||||
stop = 1;
|
||||
pthread_join(t, NULL);
|
||||
CHECK(torn == 0, "%u torn snapshots", torn);
|
||||
CHECK(ok > 0, "no snapshot taken");
|
||||
printf("concurrent: %u snapshots, %u lapped, %u torn\n", ok, lapped, torn);
|
||||
|
||||
/* FAKE_EVDEV_MEMFD_PATHS */
|
||||
char got[256] = "";
|
||||
parse_paths("0=/a/r0;1=/a/r1;4=/a/mouse;x=bad;2=;3=/a/r3", take, got, 4);
|
||||
CHECK(!strcmp(got, "0:/a/r0|1:/a/r1|3:/a/r3|"), "parsed '%s' (slot 4 = mouse and malformed entries skipped)", got);
|
||||
|
||||
printf(failures ? "host_test: %d failure(s)\n" : "host_test: OK\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -25,6 +25,9 @@ typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t;
|
||||
|
||||
#define LINKER "/system/bin/linker64"
|
||||
|
||||
// handoff.c: returns unless the exec was handed to one of the app's worker processes
|
||||
void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]);
|
||||
|
||||
enum kind { PASS, VIA_LINKER, VIA_INTERP };
|
||||
|
||||
// What starting `path` needs; for scripts, the interpreter and its optional argument.
|
||||
@@ -205,6 +208,8 @@ int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||
char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes)
|
||||
const char *file = path;
|
||||
char **args = rewrite(path, argv, &file, storage);
|
||||
// the app may run it in a worker instead (handoff.c): matched by the program, sent as the start below
|
||||
ddh_bionic_exec(file, args ? args : argv, envp, path, argv);
|
||||
int ret = real(file, args ? args : argv, envp);
|
||||
int saved = errno;
|
||||
free(args);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# GStreamer plugins packed for winegstreamer (game video/audio), from the imagefs's lib/gstreamer-1.0 by name
|
||||
# (libgst<name>.so): Proton's usual set as far as this imagefs has it (no vpx; videoconvert+videoscale are videoconvertscale).
|
||||
coreelements
|
||||
debug
|
||||
app
|
||||
audioconvert
|
||||
audiorate
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
// handoff: part of libexecshim.so, preloaded into the bionic Wine processes. The native hook's exec
|
||||
// handoff (tools/nativeguest/hook/handoff.c, docs/phantom-processes.md) built for bionic: a program a
|
||||
// Wine process forks and execs runs as the main process of one of the app's worker processes instead of
|
||||
// as a child Android counts against its limit. The glibc session's hook cannot reach these processes
|
||||
// (they run on Android's libc), so without this every Wine process of a bionic game was counted.
|
||||
//
|
||||
// What the native hook does around the handoff and this file does too: fork() records the child for
|
||||
// its parent's table, close(), close_range(), dup2() and dup3() leave the table and the worker's binder
|
||||
// fds alone (hook/kept.c), and execve() offers the exec to the app before it runs (execshim.c calls
|
||||
// ddh_bionic_exec() with the start it is about to make: "/system/bin/linker64 PROGRAM ARGS" for a
|
||||
// program in the app's data, matched against DD_HANDOFF by PROGRAM). wait*(), kill() and _exit() are
|
||||
// the handoff's own (hook/handoff.c). Nothing here acts without DD_SPAWN and DD_HANDOFF in the
|
||||
// environment (tools/bionic-runtime/tool/launch.sh keeps them).
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
// bionic has no thread cancellation: nothing can cancel the table's setup
|
||||
#ifndef PTHREAD_CANCEL_ENABLE
|
||||
#define PTHREAD_CANCEL_ENABLE 0
|
||||
#define PTHREAD_CANCEL_DISABLE 1
|
||||
static int pthread_setcancelstate(int state, int *old) {
|
||||
(void)state;
|
||||
if (old) *old = PTHREAD_CANCEL_ENABLE;
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
#ifndef CLOSE_RANGE_UNSHARE
|
||||
#define CLOSE_RANGE_UNSHARE (1U << 1)
|
||||
#endif
|
||||
#ifndef CLOSE_RANGE_CLOEXEC
|
||||
#define CLOSE_RANGE_CLOEXEC (1U << 2)
|
||||
#endif
|
||||
#ifndef __NR_close_range
|
||||
#define __NR_close_range 436
|
||||
#endif
|
||||
|
||||
#include <sys/sysmacros.h>
|
||||
static void pthread_testcancel(void) {}
|
||||
int close_range(unsigned int first, unsigned int last, int flags);
|
||||
|
||||
// bionic has no on_exit(): the handoff reports a program's exit status from it (exit() runs it).
|
||||
// atexit() handlers get no status, so exit() below notes it first; a return from main() reaches
|
||||
// exit() inside libc and reports 0.
|
||||
static void (*g_on_exit_fn)(int, void *);
|
||||
static void *g_on_exit_arg;
|
||||
static int g_exit_status;
|
||||
static void run_on_exit(void) {
|
||||
if (g_on_exit_fn) g_on_exit_fn(g_exit_status, g_on_exit_arg);
|
||||
}
|
||||
static int on_exit(void (*fn)(int, void *), void *arg) {
|
||||
g_on_exit_fn = fn;
|
||||
g_on_exit_arg = arg;
|
||||
return atexit(run_on_exit);
|
||||
}
|
||||
|
||||
// The native hook's names for the plain system call and for a guest path: here there is no guest root.
|
||||
static long call_orig_syscall(long nr, unsigned long a, unsigned long b, unsigned long c, unsigned long d,
|
||||
unsigned long e, unsigned long f) {
|
||||
return syscall(nr, a, b, c, d, e, f);
|
||||
}
|
||||
static const char *rewrite_path(const char *path, char *out, size_t size) {
|
||||
(void)out;
|
||||
(void)size;
|
||||
return path;
|
||||
}
|
||||
|
||||
// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their
|
||||
// first parent for the session's subreapers, and reap nothing themselves.
|
||||
static void ddnatv_manage_sigchld(void) {}
|
||||
static void ddh_reap_unclaimed(void) __attribute__((unused));
|
||||
|
||||
#include "../nativeguest/hook/kept.c"
|
||||
#include "../nativeguest/hook/handoff.c"
|
||||
|
||||
void exit(int status) {
|
||||
g_exit_status = status;
|
||||
void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, "exit");
|
||||
if (real) real(status);
|
||||
syscall(SYS_exit_group, status);
|
||||
__builtin_unreachable();
|
||||
}
|
||||
|
||||
static int ddh_is_linker(const char *path) {
|
||||
const char *base = path ? strrchr(path, '/') : NULL;
|
||||
return base && strcmp(base + 1, "linker64") == 0;
|
||||
}
|
||||
|
||||
static int ddh_regular(const char *path, int mode) {
|
||||
struct stat st;
|
||||
return path && stat(path, &st) == 0 && S_ISREG(st.st_mode) && access(path, mode) == 0;
|
||||
}
|
||||
|
||||
// Android refuses execve() of a file in the app's data unless SELinux is permissive (execshim.c makes the
|
||||
// dynamic ones linker64 starts). An unreadable setting counts as enforcing.
|
||||
static int ddh_selinux_permissive(void) {
|
||||
char c = 0;
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC, 0);
|
||||
if (fd < 0) return 0;
|
||||
long n = syscall(SYS_read, fd, &c, 1);
|
||||
syscall(SYS_close, fd);
|
||||
return n == 1 && c == '0';
|
||||
}
|
||||
|
||||
// A handed-off start that fails fails in the worker, where the caller cannot see it and try its next
|
||||
// candidate (Wine tries its preloader, then its loader), so only a start that would succeed here goes.
|
||||
static int ddh_bionic_startable(const char *file, char *const args[]) {
|
||||
char real[PATH_MAX];
|
||||
// env takes an argument with '=' for a variable, and looks a name without '/' up in PATH
|
||||
if (!file || strchr(file, '=') || !strchr(file, '/')) return 0;
|
||||
if (!ddh_regular(file, X_OK) || !realpath(file, real)) return 0;
|
||||
if (ddh_is_linker(real))
|
||||
return args && args[0] && args[1] && args[1][0] != '-' && ddh_regular(args[1], R_OK) && ddh_startable(args[1]);
|
||||
if (strncmp(real, "/data/", 6) == 0 && !ddh_selinux_permissive()) return 0;
|
||||
// env starts FILE with FILE as argv[0]
|
||||
return args && args[0] && strcmp(args[0], file) == 0 && ddh_startable(file);
|
||||
}
|
||||
|
||||
void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]) {
|
||||
if (ddh_env(envp, "DD_HANDOFF_DEBUG")) {
|
||||
char why[200];
|
||||
struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE);
|
||||
snprintf(why, sizeof(why), "bionic exec (spawn %d list %d table %d owner %d up %d ppid %d) of", ddh_env(envp, "DD_SPAWN") != NULL,
|
||||
ddh_env(envp, "DD_HANDOFF") != NULL, own != NULL, own ? (int)g_ddh_owner : 0, g_ddh_up != NULL, (int)getppid());
|
||||
ddh_debug(envp, why, path ? path : "(null)");
|
||||
}
|
||||
if (!ddh_env(envp, "DD_SPAWN") || !ddh_env(envp, "DD_HANDOFF")) return;
|
||||
if (!ddh_bionic_startable(file, args)) {
|
||||
ddh_debug(envp, "bionic exec stays here (not startable as a handoff):", path ? path : "(null)");
|
||||
return;
|
||||
}
|
||||
// Wine's own starts through the system linker ("/system/bin/linker64 PROGRAM ARGS") are listed by PROGRAM
|
||||
const char *match = path;
|
||||
char *const *match_argv = argv;
|
||||
if (ddh_is_linker(path) && argv && argv[0] && argv[1]) {
|
||||
match = argv[1];
|
||||
match_argv = argv + 1;
|
||||
}
|
||||
// The app starts a handed-off program from the glibc root's shell (GuestWorkers), which cannot load this
|
||||
// runtime's LD_PRELOAD and LD_LIBRARY_PATH (bionic libraries). The request carries them as arguments of
|
||||
// Android's env instead, which the shell execs and which puts them back for the program: the worker's main
|
||||
// process ends up as the program all the same. Stack only (this may run in a vfork child).
|
||||
int nargs = 0, nenv = 0;
|
||||
while (args[nargs]) nargs++;
|
||||
while (envp && envp[nenv]) nenv++;
|
||||
// env, up to two loader variables, FILE, args[1..], NULL (nargs >= 1: ddh_bionic_startable)
|
||||
char *wrapped[nargs + 4];
|
||||
char *trimmed[nenv + 1];
|
||||
int w = 0, t = 0;
|
||||
wrapped[w++] = (char *)"/system/bin/env";
|
||||
for (int i = 0; i < nenv; i++) {
|
||||
if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0 || strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) {
|
||||
if (w < 3) wrapped[w++] = envp[i];
|
||||
} else {
|
||||
trimmed[t++] = envp[i];
|
||||
}
|
||||
}
|
||||
trimmed[t] = NULL;
|
||||
// env runs the program by the path its first argument gives: the start's file, then the rest of its argv
|
||||
wrapped[w++] = (char *)file;
|
||||
for (int i = 1; i < nargs; i++) wrapped[w++] = args[i];
|
||||
wrapped[w] = NULL;
|
||||
ddh_try_as("/system/bin/env", wrapped, trimmed, match, match_argv);
|
||||
ddh_debug(envp, "bionic exec stays here:", path ? path : "(null)");
|
||||
}
|
||||
|
||||
// bionic's exec functions call the execve system call stub inside libc, past execshim.c's execve(): Wine
|
||||
// starts its programs with execv() (its preloader) and execvp(), so these go through execve() here.
|
||||
extern char **environ;
|
||||
|
||||
int execv(const char *path, char *const argv[]) { return execve(path, argv, environ); }
|
||||
|
||||
// bionic's execvpe(), through execve() here: an unset PATH is libc's default (Android 14's; an empty one, and an empty
|
||||
// entry, are the current directory), and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh.
|
||||
#define DDH_DEFPATH "/product/bin:/apex/com.android.runtime/bin:/apex/com.android.art/bin:/system_ext/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin"
|
||||
|
||||
static int exec_as_script(const char *file, char *const argv[], char *const envp[]) {
|
||||
int n = 0;
|
||||
while (argv && argv[n]) n++;
|
||||
char *script[(n > 0 ? n : 1) + 2];
|
||||
int s = 0;
|
||||
script[s++] = (char *)"sh";
|
||||
script[s++] = (char *)file;
|
||||
for (int i = 1; i < n; i++) script[s++] = argv[i];
|
||||
script[s] = NULL;
|
||||
return execve("/system/bin/sh", script, envp);
|
||||
}
|
||||
|
||||
int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
||||
if (!file || !*file) {
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
}
|
||||
if (strchr(file, '/')) {
|
||||
execve(file, argv, envp);
|
||||
return errno == ENOEXEC ? exec_as_script(file, argv, envp) : -1;
|
||||
}
|
||||
const char *dirs = getenv("PATH");
|
||||
if (!dirs) dirs = DDH_DEFPATH;
|
||||
int saw_eacces = 0;
|
||||
size_t flen = strlen(file);
|
||||
for (const char *p = dirs;;) {
|
||||
const char *end = strchr(p, ':');
|
||||
size_t len = end ? (size_t)(end - p) : strlen(p);
|
||||
const char *dir = len ? p : ".";
|
||||
if (!len) len = 1;
|
||||
char full[PATH_MAX];
|
||||
if (len + flen + 2 > sizeof(full)) {
|
||||
errno = ENAMETOOLONG;
|
||||
} else {
|
||||
memcpy(full, dir, len);
|
||||
full[len] = '/';
|
||||
memcpy(full + len + 1, file, flen + 1);
|
||||
execve(full, argv, envp);
|
||||
}
|
||||
switch (errno) {
|
||||
case EISDIR:
|
||||
case ELOOP:
|
||||
case ENAMETOOLONG:
|
||||
case ENOENT:
|
||||
case ENOTDIR:
|
||||
break;
|
||||
case ENOEXEC:
|
||||
return exec_as_script(full, argv, envp);
|
||||
case EACCES:
|
||||
saw_eacces = 1;
|
||||
break;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
if (!end) break;
|
||||
p = end + 1;
|
||||
}
|
||||
if (saw_eacces) errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); }
|
||||
|
||||
// execl(), execlp(), execle(): the list as an argv on the stack
|
||||
#define EXECL_ARGV(first, ap, n) \
|
||||
do { \
|
||||
va_list count_ap; \
|
||||
va_copy(count_ap, ap); \
|
||||
n = first ? 1 : 0; \
|
||||
if (first) \
|
||||
while (va_arg(count_ap, const char *)) n++; \
|
||||
va_end(count_ap); \
|
||||
} while (0)
|
||||
|
||||
int execl(const char *path, const char *arg0, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, arg0);
|
||||
int n;
|
||||
EXECL_ARGV(arg0, ap, n);
|
||||
char *argv[n + 1];
|
||||
argv[0] = (char *)arg0;
|
||||
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
|
||||
argv[n] = NULL;
|
||||
va_end(ap);
|
||||
return execve(path, argv, environ);
|
||||
}
|
||||
|
||||
int execlp(const char *file, const char *arg0, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, arg0);
|
||||
int n;
|
||||
EXECL_ARGV(arg0, ap, n);
|
||||
char *argv[n + 1];
|
||||
argv[0] = (char *)arg0;
|
||||
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
|
||||
argv[n] = NULL;
|
||||
va_end(ap);
|
||||
return execvp(file, argv);
|
||||
}
|
||||
|
||||
int execle(const char *path, const char *arg0, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, arg0);
|
||||
int n;
|
||||
EXECL_ARGV(arg0, ap, n);
|
||||
char *argv[n + 1];
|
||||
argv[0] = (char *)arg0;
|
||||
for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *);
|
||||
argv[n] = NULL;
|
||||
if (arg0) (void)va_arg(ap, char *); // the list's NULL
|
||||
char *const *envp = va_arg(ap, char *const *);
|
||||
va_end(ap);
|
||||
return execve(path, argv, envp);
|
||||
}
|
||||
|
||||
pid_t fork(void) {
|
||||
static pid_t (*orig_fork)(void) = NULL;
|
||||
if (!orig_fork) orig_fork = (pid_t (*)(void))dlsym(RTLD_NEXT, "fork");
|
||||
if (!orig_fork) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
ddh_prepare();
|
||||
pid_t forker = (pid_t)syscall(SYS_gettid);
|
||||
pid_t forking = (pid_t)syscall(SYS_getpid);
|
||||
pid_t pid = orig_fork();
|
||||
if (pid == 0) {
|
||||
kept_forked();
|
||||
kept_close_forked();
|
||||
ddh_drop_worker_binder();
|
||||
ddh_forked(forker);
|
||||
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
|
||||
} else if (pid > 0) {
|
||||
ddh_child_created(pid, 1);
|
||||
}
|
||||
return pid;
|
||||
}
|
||||
|
||||
int close(int fd) {
|
||||
static int (*orig_close)(int) = NULL;
|
||||
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
|
||||
uint64_t ticket = kept_close_begin();
|
||||
if (kept_any() > 0 && is_kept_fd(fd)) {
|
||||
kept_close_end(ticket);
|
||||
return 0;
|
||||
}
|
||||
int r = orig_close ? orig_close(fd) : (errno = ENOSYS, -1);
|
||||
int saved = errno;
|
||||
kept_close_end(ticket);
|
||||
errno = saved;
|
||||
return r;
|
||||
}
|
||||
|
||||
static int dup_moved(int (*dup_fn)(int, int, int), int oldfd, int newfd, int flags) {
|
||||
int pidfd_from = -1, locked = 0;
|
||||
if (oldfd != newfd) {
|
||||
locked = ddh_parent_pidfd_lock(newfd);
|
||||
pidfd_from = ddh_parent_pidfd_moves(newfd);
|
||||
}
|
||||
int ret = dup_fn(oldfd, newfd, flags);
|
||||
ddh_parent_pidfd_settle(pidfd_from, ret >= 0);
|
||||
int saved = errno;
|
||||
ddh_parent_pidfd_unlock(locked);
|
||||
errno = saved;
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int (*g_orig_dup2)(int, int);
|
||||
static int (*g_orig_dup3)(int, int, int);
|
||||
static int call_dup2(int oldfd, int newfd, int flags) {
|
||||
(void)flags;
|
||||
return g_orig_dup2 ? g_orig_dup2(oldfd, newfd) : (errno = ENOSYS, -1);
|
||||
}
|
||||
static int call_dup3(int oldfd, int newfd, int flags) {
|
||||
return g_orig_dup3 ? g_orig_dup3(oldfd, newfd, flags) : (errno = ENOSYS, -1);
|
||||
}
|
||||
|
||||
int dup2(int oldfd, int newfd) {
|
||||
if (!g_orig_dup2) g_orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
|
||||
return dup_moved(call_dup2, oldfd, newfd, 0);
|
||||
}
|
||||
|
||||
int dup3(int oldfd, int newfd, int flags) {
|
||||
if (!g_orig_dup3) g_orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
|
||||
return dup_moved(call_dup3, oldfd, newfd, flags);
|
||||
}
|
||||
|
||||
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
|
||||
return (int)syscall(__NR_close_range, first, last, *(int *)flags);
|
||||
}
|
||||
|
||||
static int close_range_unshare(void) {
|
||||
return (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE);
|
||||
}
|
||||
|
||||
int close_range(unsigned int first, unsigned int last, int flags) {
|
||||
// what the kernel refuses, refused before the range is split or the table unshared
|
||||
if (first > last || (flags & ~(int)(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
uint64_t ticket = kept_close_begin();
|
||||
int r = 0;
|
||||
// The table is unshared first, once, and this thread goes on with its own copy of the kept list
|
||||
// (kept_split())
|
||||
if (flags & CLOSE_RANGE_UNSHARE) {
|
||||
r = kept_split(close_range_unshare);
|
||||
flags &= ~(int)CLOSE_RANGE_UNSHARE;
|
||||
}
|
||||
if (r == 0) {
|
||||
int snapshot[DDNATV_MAX_KEPT_FDS];
|
||||
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
|
||||
int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
|
||||
r = count == 0 ? close_range_part(first, last, &flags)
|
||||
: for_each_range_without(first, last, kept, count, close_range_part, &flags);
|
||||
}
|
||||
int saved = errno;
|
||||
kept_close_end(ticket);
|
||||
errno = saved;
|
||||
return r;
|
||||
}
|
||||
|
||||
// The native hook's own uses of these (exec.c) have no counterpart here
|
||||
__attribute__((unused)) static void *const glibc_only[] = {(void *)ddh_try, (void *)ddh_spawn_wanted};
|
||||
@@ -29,6 +29,11 @@ echo "$(date +%H:%M:%S) $verb $EXE ($VERSION, uid $(id -u), DISPLAY ${DISPLAY:-u
|
||||
# Keep Steam's game identity, DroidDeck's input/display/driver/sync settings and its game environment (the names
|
||||
# ../proton lists in DROIDDECK_BIONIC_KEEP); drop the rest of the glibc guest's environment.
|
||||
KEEP=" ${DROIDDECK_BIONIC_KEEP:-} "
|
||||
# The built-in DirectAudio driver reads DroidDeck's AUDIO_DIRECT_* settings (the microphone switch among them) under
|
||||
# the BANNER_ names droiddeck-proton gives them for Proton.
|
||||
for v in $(env | sed -n 's/^\(AUDIO_DIRECT_[A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
eval "export BANNER_$v=\"\$$v\""
|
||||
done
|
||||
for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
case "$KEEP" in *" $v "*) continue ;; esac
|
||||
case "$v" in
|
||||
@@ -36,7 +41,7 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
ANDROID_*|BOOTCLASSPATH|DEX2OATBOOTCLASSPATH|SYSTEMSERVERCLASSPATH|EXTERNAL_STORAGE|ASEC_MOUNTPOINT) ;;
|
||||
FAKE_*|SDL_*|DD_WIDTH|DD_HEIGHT|DD_VK_DRIVER|WINEDLLOVERRIDES) ;;
|
||||
DISPLAY|GAMESCOPE_WAYLAND_DISPLAY|FEX_*) ;;
|
||||
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS) ;;
|
||||
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS|DROIDDECK_NO_STEAM|BANNER_AUDIO_DIRECT_*) ;;
|
||||
mesa_glthread|vblank_mode|ZINK_*|GALLIUM_HUD|GALLIUM_THREAD) ;;
|
||||
DD_SYNC|DD_FSYNC_FIRST|DD_SYNC_FALLBACK|PROTON_NO_ESYNC|PROTON_NO_FSYNC|PROTON_NO_NTSYNC|WINEESYNC) ;;
|
||||
PROTON_USE_D7VK) ;;
|
||||
@@ -47,6 +52,13 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
|
||||
DROIDDECK_GUEST_ROOT) ;;
|
||||
VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;;
|
||||
# droiddeck-game-env's original Xbox switches for this layer's Wine and the Xbox VKD3D-Proton build
|
||||
WINE_SPECIAL_APC_INTERRUPT|WINE_MF_DISPLAY_APERTURE|WINE_PRECISE_SLEEP) ;;
|
||||
VKD3D_INTEROP_PRESENT|VKD3D_PACKED_422|VKD3D_PACKED_422_SWIZZLE) ;;
|
||||
# The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the
|
||||
# glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs
|
||||
# in one): the first Wine process's hook knows the worker's binder fds are not its own.
|
||||
DD_SPAWN|DD_SPAWN_SESSION|DD_HANDOFF|DD_HANDOFF_DEBUG|DD_HANDOFF_PRESSURE|DDH_*|DDNATV_ROOT) ;;
|
||||
*) unset "$v" 2>/dev/null ;;
|
||||
esac
|
||||
done
|
||||
@@ -81,7 +93,8 @@ RTD=$APP/.wayland-rt
|
||||
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
|
||||
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
|
||||
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
|
||||
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
|
||||
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=0
|
||||
echo "WSI forced XWayland bypass disabled (GAMESCOPE_WSI_FORCE_BYPASS=$GAMESCOPE_WSI_FORCE_BYPASS)"
|
||||
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
|
||||
|
||||
# Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor),
|
||||
@@ -104,6 +117,9 @@ export NTSYNC_SHM=$COMPAT/ntsync-shm
|
||||
# DroidDeck's Force SSBS (its glibc libssbs.so preload) is bionic Wine's own WINE_FORCE_SSBS
|
||||
on "${DROIDDECK_FORCE_SSBS:-}" && export WINE_FORCE_SSBS=1
|
||||
export HODLL=libwow64fex.dll WINEDEBUG=err+all,fixme-all
|
||||
# The network adapter list (GetAdaptersAddresses) from the layer's getifaddrs code: its default if_nameindex code never
|
||||
# answered here, and the Paradox Launcher (Europa Universalis IV) waited on it forever.
|
||||
export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}
|
||||
export XENVIRONMENT=$TOOL/bionic/Xdefaults
|
||||
# The adapter's Wayland swapchain gets its buffers back from gamescope later than DroidDeck-Proton's Turnip does;
|
||||
# with gamescope's default three images the game waits for one about a fifth of the time at high frame rates.
|
||||
@@ -122,6 +138,13 @@ echo "sync ntsync=$WINENTSYNC esync=$WINEESYNC ssbs=${WINE_FORCE_SSBS:-0} tu_deb
|
||||
export WINESTEAMCLIENTPATH64=$ROOTFS/root/.local/share/Steam/androidarm64/libsteamclient.so
|
||||
# The layer sends a game's steamclient(64).dll to lsteamclient (and so to DroidDeck's Steam through the library
|
||||
# above) only with WINE_LSTEAMCLIENT set; without it Valve's Windows steamclient runs alone and SteamAPI_Init fails.
|
||||
# A game set to start without Steam has no Steam client behind lsteamclient, and a steamclient64.dll it brings itself
|
||||
# (a Steam emulator such as gbe_fork's ColdClient loader) would be replaced by it, so the game quit after its splash
|
||||
# screen. Such a game keeps its own; a WINE_LSTEAMCLIENT the player set wins.
|
||||
if [ -z "${WINE_LSTEAMCLIENT:-}" ] && on "${DROIDDECK_NO_STEAM:-}"; then
|
||||
echo "lsteamclient off: started without Steam"
|
||||
export WINE_LSTEAMCLIENT=0
|
||||
fi
|
||||
export WINE_LSTEAMCLIENT=${WINE_LSTEAMCLIENT:-1}
|
||||
# Steam Input data (Valve's Steam Deck layouts with game actions) lives in DroidDeck's /dev/shm; libsteamshm.so
|
||||
# points the Android library's shared memory there (it keeps its own in-process otherwise) and gives it the
|
||||
@@ -250,7 +273,7 @@ prepare_prefix() {
|
||||
prefix_busy() { # a process of this prefix is running
|
||||
for p in /proc/[0-9]*; do
|
||||
[ "${p#/proc/}" = "$$" ] && continue
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
|
||||
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
@@ -265,7 +288,7 @@ programs_left() { # a program of this prefix is still running, apart from Wine's
|
||||
""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe|\
|
||||
winemenubuilder|wineboot.exe|tabtip.exe) continue ;;
|
||||
esac
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
|
||||
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
@@ -274,7 +297,7 @@ stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game
|
||||
wineserver_ -k 2>/dev/null
|
||||
sleep 1
|
||||
for p in /proc/[0-9]*; do
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue
|
||||
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue
|
||||
[ "${p#/proc/}" = "$$" ] && continue
|
||||
echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)"
|
||||
kill -9 "${p#/proc/}" 2>/dev/null
|
||||
@@ -301,6 +324,21 @@ if [ "$verb" != runinprefix ] && prefix_busy; then
|
||||
fi
|
||||
prefix_busy || rm -f "$NTSYNC_SHM".v*
|
||||
|
||||
# Steam's running client, as a game's steam_api checks it: Proton names its steam.exe (the prefix's first program,
|
||||
# alive while the game runs), which this tool does not start. Here the first program is the one Steam started, so a
|
||||
# launcher that starts the game and quits (EU4's dowser.exe) left a game that reported "Steam not detected". The
|
||||
# PID is the one this tool's own prefixes carry.
|
||||
steam_pid() {
|
||||
R=$COMPAT/pfx/user.reg
|
||||
[ -f "$R" ] || return 0
|
||||
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
|
||||
on && /^"PID"=dword:/ && $0 != "\"PID\"=dword:0000fffe" { found = 1 } END { exit !found }' "$R" || return 0
|
||||
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
|
||||
on && /^"PID"=dword:/ { print "\"PID\"=dword:0000fffe"; next } { print }' "$R" > "$R.dd-new.$$" && mv -f "$R.dd-new.$$" "$R" &&
|
||||
echo "$(date +%H:%M:%S) Steam's process ID in the registry set to this tool's"
|
||||
}
|
||||
prefix_busy || steam_pid
|
||||
|
||||
# Links into a tool that is gone (an older DroidDeck-Bionic, a deleted DroidDeck-Proton) or to a file it no longer has.
|
||||
# Wine's update cannot write over them, so drivers (network, controller) and other files stay missing. Drop them and
|
||||
# clear both stamps: prepare_prefix relinks this tool's files and Wine's update puts its own back.
|
||||
@@ -388,6 +426,59 @@ elif [ -L "$S/ddraw_.dll" ] || [ -e "$S/ddraw_.dll" ]; then
|
||||
ln -s "$F/lib/wine/i386-windows/ddraw.dll" "$S/ddraw.dll"
|
||||
echo "$(date +%H:%M:%S) D7VK off: Wine's ddraw again"
|
||||
fi
|
||||
|
||||
# dd-directcontroller: a game set to start without Steam reads the controller through dd-directcontroller's XInput DLLs
|
||||
# (bionic/dd-directcontroller), which answer from the pad state DroidDeck keeps in each ring file instead of the queue
|
||||
# of HID reports Wine's xinput reads (a game that reads slower than the pad reports kept moving after the stick
|
||||
# was let go). They go into the prefix as copies, never through the links to this tool's builtins, with Wine's
|
||||
# xinput1_4 beside them as dd-directcontroller-wine-xinput.dll for rumble and pass-through. The mode file next to the
|
||||
# controller folder (DD_DIRECTCONTROLLER_CONTROL, '1' direct / '0' pass-through to Wine's xinput) is read by the DLLs
|
||||
# while the game runs, so DroidDeck can switch it live; it starts as DD_DIRECTCONTROLLER says (0 = pass-through). A game
|
||||
# no longer set to start without Steam gets Wine's links back.
|
||||
DDC=$TOOL/bionic/dd-directcontroller
|
||||
ddc_names="xinput1_1 xinput1_2 xinput1_3 xinput1_4 xinput9_1_0 xinputuap"
|
||||
ddc_put() { # src dst: dst becomes a copy of src; a link there is removed first, so the file it names stays as it was
|
||||
[ ! -L "$2" ] && cmp -s "$1" "$2" && return 0
|
||||
rm -f "$2" && cp "$1" "$2"
|
||||
}
|
||||
ddc_ours() { [ -f "$1" ] && [ ! -L "$1" ] && grep -qF "dd-directcontroller: " "$1"; }
|
||||
DDCW=$COMPAT/pfx/drive_c/windows
|
||||
if on "${DROIDDECK_NO_STEAM:-}" && [ -d "$DDC/arm64x" ] && [ -d "$DDC/i386" ]; then
|
||||
for a in arm64x:system32:aarch64-windows i386:syswow64:i386-windows; do
|
||||
src=$DDC/${a%%:*}; rest=${a#*:}; dir=$DDCW/${rest%%:*}; wine=$F/lib/wine/${rest#*:}
|
||||
[ -d "$dir" ] || continue
|
||||
for n in $ddc_names; do
|
||||
t=$dir/$n.dll
|
||||
# a native DLL that is neither Wine's nor ours (a game's own or a tool's) stays, as link_dir keeps it
|
||||
if [ -f "$t" ] && [ ! -L "$t" ] && ! is_builtin "$t" && ! ddc_ours "$t"; then
|
||||
echo "$(date +%H:%M:%S) dd-directcontroller: kept ${dir##*/}/$n.dll (not Wine's)"
|
||||
continue
|
||||
fi
|
||||
ddc_put "$src/$n.dll" "$t"
|
||||
done
|
||||
ddc_put "$wine/xinput1_4.dll" "$dir/dd-directcontroller-wine-xinput.dll"
|
||||
done
|
||||
export WINEDLLOVERRIDES="$WINEDLLOVERRIDES;xinput1_1,xinput1_2,xinput1_3,xinput1_4,xinput9_1_0,xinputuap=n,b"
|
||||
ddc_mode=1 ddc_name=direct
|
||||
[ "${DD_DIRECTCONTROLLER:-1}" = 0 ] && ddc_mode=0 ddc_name=pass-through
|
||||
if [ -n "${FAKE_EVDEV_DIR:-}" ] && echo "$ddc_mode" > "${FAKE_EVDEV_DIR%/*}/dd-directcontroller.mode"; then
|
||||
export DD_DIRECTCONTROLLER_CONTROL="${FAKE_EVDEV_DIR%/*}/dd-directcontroller.mode"
|
||||
else
|
||||
ddc_name="direct (no mode file)"
|
||||
fi
|
||||
echo "$(date +%H:%M:%S) dd-directcontroller on (starts $ddc_name)"
|
||||
else
|
||||
back=0
|
||||
for a in system32:aarch64-windows syswow64:i386-windows; do
|
||||
dir=$DDCW/${a%%:*}; wine=$F/lib/wine/${a#*:}
|
||||
for n in $ddc_names; do
|
||||
ddc_ours "$dir/$n.dll" || continue
|
||||
rm -f "$dir/$n.dll" && ln -s "$wine/$n.dll" "$dir/$n.dll" && back=$((back + 1))
|
||||
done
|
||||
rm -f "$dir/dd-directcontroller-wine-xinput.dll"
|
||||
done
|
||||
[ $back -gt 0 ] && echo "$(date +%H:%M:%S) dd-directcontroller off: Wine's xinput again"
|
||||
fi
|
||||
# A Windows path (an Xbox game on its own drive letter) starts in the folder Steam gave.
|
||||
case "$EXE" in [A-Za-z]:[\\/]*) ;; *) cd "$(dirname "$EXE")" || exit 1 ;; esac
|
||||
|
||||
@@ -403,7 +494,7 @@ comm=$(echo "$name" | cut -c1-15)
|
||||
game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name)
|
||||
for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do
|
||||
p=${p%/comm}
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}"
|
||||
tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}"
|
||||
done
|
||||
}
|
||||
# The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game
|
||||
|
||||
@@ -36,6 +36,21 @@ zpath() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Drive links of the prefix in compatdata folder $1 that name guest paths (DroidDeck-Proton's s: for the Steam library)
|
||||
# -> their Android paths, which this Wine follows. A game's mods on S: were missing otherwise. A session's start
|
||||
# gives them their guest paths back (NativeGuest.relinkPrefixDrives); z: is launch.sh's.
|
||||
android_drives() {
|
||||
local d t a
|
||||
for d in "$1"/pfx/dosdevices/[a-y]:; do
|
||||
[ -L "$d" ] || continue
|
||||
t=$(readlink "$d")
|
||||
case "$t" in /*) ;; *) continue ;; esac
|
||||
a=$(real "$t")
|
||||
[ "$a" = "$t" ] && continue
|
||||
ln -sfn "$a" "$d.dd-new.$$" && mv -fT "$d.dd-new.$$" "$d" && echo "drive ${d##*/} -> $a"
|
||||
done
|
||||
}
|
||||
|
||||
# Where a game launch's log goes in DroidDeck's session folder (Share logs takes that folder): the game's log folder
|
||||
# when Detailed graphics logs made one (droiddeck-game-env), else a folder of its own; nothing for other verbs
|
||||
session_logs() {
|
||||
@@ -109,6 +124,7 @@ print(" ".join(sorted(n for n in names if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*"
|
||||
PY
|
||||
)
|
||||
export DROIDDECK_BIONIC_KEEP
|
||||
[ -n "${STEAM_COMPAT_DATA_PATH:-}" ] && android_drives "$STEAM_COMPAT_DATA_PATH" >&2
|
||||
exec /system/bin/sh "$tool/bionic/launch.sh" "$verb" "$compat" "$exe" ${args[@]+"${args[@]}"} ;;
|
||||
getcompatpath)
|
||||
p=$(real "${1:-}")
|
||||
|
||||
@@ -50,7 +50,7 @@ if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in curl tar zstd shasum unzip python3 go; do
|
||||
for tool in curl tar zstd shasum unzip python3 go rpm2cpio cpio; do
|
||||
if ! command -v "${tool}" >/dev/null 2>&1; then
|
||||
echo "${tool} is required to build the CI-equivalent APK." >&2
|
||||
exit 1
|
||||
@@ -225,6 +225,7 @@ else
|
||||
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
|
||||
bash tools/linuxfs/lse-emu/build.sh "$d"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
@@ -540,6 +541,8 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
|
||||
fi
|
||||
python3 tools/powervr/fetch.py
|
||||
bash tools/packs/build.sh app/build/packs
|
||||
mkdir -p "${cache_dir}/ime"
|
||||
python3 "${repo_root}/tools/ime/prepare.py" --packages "${cache_dir}/ime" --download --output "${linuxfs_dir}"
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
|
||||
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
|
||||
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Exports the build metadata Gradle bakes into BuildConfig and prints the label for DROIDDECK_BUILD_LABEL.
|
||||
set -euo pipefail
|
||||
if [[ -n "$(git status --porcelain)" ]]; then
|
||||
tree_state=dirty
|
||||
else
|
||||
tree_state=clean
|
||||
fi
|
||||
echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV"
|
||||
if [[ -n "${PR_NUMBER:-}" ]]; then
|
||||
label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}"
|
||||
else
|
||||
label="${BUILD_REF} at ${BUILD_SHA:0:7}"
|
||||
fi
|
||||
echo "label=$label" >> "$GITHUB_OUTPUT"
|
||||
echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV"
|
||||
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
|
||||
echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV"
|
||||
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -10,13 +10,13 @@ if [ "${#missing[@]}" = 0 ]; then
|
||||
echo "Ubuntu build dependencies are already installed."
|
||||
exit 0
|
||||
fi
|
||||
options=()
|
||||
source_options=()
|
||||
# Runners without the deb822 Ubuntu sources file keep their own apt configuration.
|
||||
ubuntu_sources=${UBUNTU_SOURCES_FILE:-/etc/apt/sources.list.d/ubuntu.sources}
|
||||
if [ -f "$ubuntu_sources" ]; then
|
||||
options+=(-o "Dir::Etc::sourcelist=$ubuntu_sources" -o Dir::Etc::sourceparts=-)
|
||||
source_options=(-o "Dir::Etc::sourcelist=$ubuntu_sources" -o Dir::Etc::sourceparts=-)
|
||||
fi
|
||||
options+=(
|
||||
apt_options=(
|
||||
-o Acquire::Retries=1
|
||||
-o Acquire::http::Timeout=15
|
||||
-o Acquire::https::Timeout=15
|
||||
@@ -24,14 +24,23 @@ options+=(
|
||||
)
|
||||
install_packages() {
|
||||
echo "Updating Ubuntu package indexes."
|
||||
sudo timeout --kill-after=10s 60s apt-get "${options[@]}" -o APT::Update::Error-Mode=any update -q || return $?
|
||||
sudo timeout --kill-after=10s 60s apt-get "${source_options[@]}" "${apt_options[@]}" -o APT::Update::Error-Mode=any update -q || return $?
|
||||
echo "Installing: ${missing[*]}"
|
||||
sudo timeout --kill-after=10s 120s env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get "${options[@]}" install -y -q --no-install-recommends "${missing[@]}"
|
||||
sudo timeout --kill-after=10s 120s env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get "${source_options[@]}" "${apt_options[@]}" install -y -q --no-install-recommends "${missing[@]}"
|
||||
}
|
||||
if install_packages; then
|
||||
exit 0
|
||||
fi
|
||||
[ -f "$ubuntu_sources" ] || exit 1
|
||||
if [ -f "$ubuntu_sources" ]; then
|
||||
template=$(cat "$ubuntu_sources")
|
||||
else
|
||||
codename=$(. "${OS_RELEASE_FILE:-/etc/os-release}" && echo "${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}")
|
||||
[ -n "$codename" ] || exit 1
|
||||
template="Types: deb
|
||||
URIs: -
|
||||
Suites: $codename $codename-updates $codename-security
|
||||
Components: main restricted universe multiverse"
|
||||
fi
|
||||
sources=$(mktemp --suffix=.sources)
|
||||
trap 'rm -f "$sources"' EXIT
|
||||
# The last mirror of each list is outside Canonical's network, so it still answers when runners cannot reach Canonical.
|
||||
@@ -39,12 +48,12 @@ mirrors=(https://archive.ubuntu.com/ubuntu https://mirrors.edge.kernel.org/ubunt
|
||||
case "$(dpkg --print-architecture)" in
|
||||
arm64) mirrors=(https://ports.ubuntu.com/ubuntu-ports https://mirrors.ocf.berkeley.edu/ubuntu-ports) ;;
|
||||
esac
|
||||
source_options=(-o "Dir::Etc::sourcelist=$sources" -o Dir::Etc::sourceparts=-)
|
||||
status=1
|
||||
for mirror in "${mirrors[@]}"; do
|
||||
echo "::warning::Ubuntu mirror failed or timed out; retrying with $mirror."
|
||||
sed -E "s@^URIs:.*@URIs: $mirror@" "$ubuntu_sources" > "$sources"
|
||||
printf '%s\n' "$template" | sed -E "s@^URIs:.*@URIs: $mirror@" > "$sources"
|
||||
chmod 644 "$sources"
|
||||
options[1]="Dir::Etc::sourcelist=$sources"
|
||||
status=0
|
||||
install_packages || status=$?
|
||||
[ "$status" = 0 ] && exit 0
|
||||
|
||||
@@ -10,13 +10,18 @@ flowchart LR
|
||||
Source[Pin source tree] --> Components[Prepare verified components]
|
||||
Source --> Xbox[Xbox ARM64 backend]
|
||||
Source --> Tests[Python and native tests]
|
||||
Components --> APK[Compile APK and Android tests]
|
||||
Components --> APK[Compile APK]
|
||||
Xbox --> APK
|
||||
APK --> Gate[Compile and test APK gate]
|
||||
Tests --> Gate
|
||||
Gate --> Publish[Main only: signing and publishing]
|
||||
```
|
||||
|
||||
Kotlin unit tests run in the separate `Unit tests` workflow (`unit-tests.yml`), so a
|
||||
PR test build is published as soon as the APK compiles. Build validation folds both
|
||||
workflows into the `Build APK` commit status, and Release APKs requires both for the
|
||||
released commit.
|
||||
|
||||
All workers verify the same source tree. The component artifact records that tree,
|
||||
recipe identities and every output hash; the APK worker verifies the inventory
|
||||
before building. This handoff verifies consistency within the same CI run. It is
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"tools/msitools",
|
||||
"tools/pipewire",
|
||||
"tools/vr",
|
||||
"tools/ime",
|
||||
"tools/gpuload",
|
||||
"app/src/main/cpp/waylandcomp/generated",
|
||||
"app/src/main/cpp/waylandcomp/src/headpose_shm.h",
|
||||
@@ -24,6 +25,10 @@
|
||||
"outputs": [
|
||||
"app/src/main/assets/linuxfs/usr/local/bin/gamescope",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so",
|
||||
"app/src/main/assets/linuxfs/usr/local/share/droiddeck/ime-files.json",
|
||||
"app/src/main/assets/linuxfs/usr/local/share/droiddeck/ibus.profile",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ime/ibus-engine-pinyin",
|
||||
"app/src/main/assets/linuxfs/usr/share/pyzy/db/android.db",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
|
||||
],
|
||||
"ndk": true,
|
||||
@@ -32,7 +37,9 @@
|
||||
"libc6-dev-arm64-cross",
|
||||
"g++-aarch64-linux-gnu",
|
||||
"libvulkan1",
|
||||
"mesa-vulkan-drivers"
|
||||
"mesa-vulkan-drivers",
|
||||
"rpm2cpio",
|
||||
"cpio"
|
||||
]
|
||||
},
|
||||
"esync": {
|
||||
|
||||
@@ -12,6 +12,8 @@ done
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
[ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
mkdir -p app/build/ime-packages
|
||||
python3 tools/ime/prepare.py --packages app/build/ime-packages --download --output "$D"
|
||||
if [ -f tools/gamescope/release.env ]; then
|
||||
. tools/gamescope/release.env
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst"
|
||||
|
||||
@@ -23,8 +23,8 @@ import prepare # noqa: E402
|
||||
# CI records identities under its runner labels and pinned NDK, not this host's.
|
||||
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
|
||||
# The components job builds these outside the recipe registry.
|
||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c',
|
||||
'tools/quest']
|
||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu',
|
||||
'tools/venus/glprobe.c', 'tools/quest']
|
||||
|
||||
|
||||
def ci_environment(architecture, root):
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
#version 450
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// win-fg C2 — FLOW REGULARIZATION (TV-L1 smoothness prior), one iteration.
|
||||
//
|
||||
// CLEAN-ROOM STATEMENT
|
||||
// Written from first principles for win-fg. NO code from LSFG, Max's wnfg_XX
|
||||
// blobs, GameScope, or any NC-licensed source — equations only, from published
|
||||
// papers. win-fg is MIT.
|
||||
//
|
||||
// WHAT THIS DOES
|
||||
// C1 (of3_gm_prewarp) removes the CAMERA motion before the dense SAD search, so
|
||||
// the flow field this shader receives (flowLvl_[kFlowFinest], 1/4-res) is the
|
||||
// OBJECT-only residual. That residual still carries incoherent / spurious
|
||||
// per-block vectors on low-texture or ambiguous blocks. C2 applies a variational
|
||||
// smoothness prior that suppresses those spurious vectors while PRESERVING true
|
||||
// motion discontinuities at object edges (that is the whole point of using an L1
|
||||
// / Total-Variation prior instead of an L2 / Horn-Schunck one — L2 rounds the
|
||||
// silhouettes off, which is exactly the smear we are trying to remove).
|
||||
//
|
||||
// ENERGY (TV-L1 optical-flow denoising of a fixed observation f0):
|
||||
// min_u Σ g(x)·|∇u(x)| + λ·|u(x) − f0(x)|
|
||||
// where u is the regularized flow, f0 is the raw SAD flow (the fixed data term),
|
||||
// |∇u| is the Total-Variation (L1-of-gradient) regularizer, and g(x)∈(0,1] is an
|
||||
// edge-aware weight from the luma gradient (small across an object silhouette so
|
||||
// the prior does NOT smooth flow across it). References:
|
||||
// * Zach, Pock & Bischof 2007, "A Duality Based Approach for Realtime TV-L1
|
||||
// Optical Flow" (DAGM) — the TV-L1 energy + the L1 data soft-threshold step.
|
||||
// * Chambolle & Pock 2011, "A First-Order Primal-Dual Algorithm ..." (JMIV) —
|
||||
// primal-dual TV framework.
|
||||
// * Rudin, Osher & Fatemi 1992 — Total Variation regularization (ROF).
|
||||
// * Vogel & Oman 1996; Chan, Golub & Mulet 1999 — the lagged-diffusivity /
|
||||
// semi-implicit solver actually used here (see SCHEME note).
|
||||
// * Perona & Malik 1990; Weickert 1998; Nagel & Enkelmann 1986 — the
|
||||
// edge-aware (image-gradient) weighting of the smoothness term.
|
||||
// * Horn & Schunck 1981 — the L2 baseline this L1 variant deliberately replaces.
|
||||
//
|
||||
// SCHEME (why not textbook Chambolle-Pock primal-dual):
|
||||
// The canonical TV-L1 solver keeps a persistent dual field p (2 components per
|
||||
// flow channel = 8 floats/px) and alternates a dual-ascent + primal-descent with
|
||||
// step sizes (σ,τ) that must satisfy στL²≤1 or it DIVERGES. That is exactly the
|
||||
// kind of tuning-sensitive instability we do not want on Turnip, and it breaks
|
||||
// the one-shader / ping-pong-two-flow-images contract (it needs extra dual
|
||||
// images). Instead we solve the SAME energy with a lagged-diffusivity
|
||||
// semi-implicit (Jacobi) step: the TV term is linearized as a divergence of the
|
||||
// edge-weighted, TV-normalized gradient (dual re-derived in closed form each
|
||||
// iteration as p = g·∇u/|∇u|_ε, which is exactly the optimal TV dual and has
|
||||
// |p|≤1 by construction), then a Jacobi update that is UNCONDITIONALLY STABLE for
|
||||
// any dt>0 (the primal is a convex combination of the centre and its neighbours,
|
||||
// so it can never blow up or NaN), followed by the exact L1 data-term
|
||||
// soft-threshold. State carried between iterations is only u itself → ping-pong
|
||||
// two rgba16f flow images, N iterations. Identity behaviour: with 0 iterations
|
||||
// the field is untouched (byte-identical to pre-C2).
|
||||
//
|
||||
// COMPOSES WITH:
|
||||
// * quality-tier2's 5-tap median: that median stays in of3_expand(_m4) and runs
|
||||
// AFTER C2, as a final speckle scrub on the already-coherent field (harmless —
|
||||
// L1 is already outlier-robust). C2 does not touch expand.
|
||||
// * C1 global-motion add-back: C2 cleans the residual IN PLACE at
|
||||
// flowLvl_[kFlowFinest]; of3_expand then medians + confidence-gates + adds the
|
||||
// global affine back exactly as before, now on the cleaned residual. The
|
||||
// end-to-end composed flow stays correct; identity affine ⇒ pre-C1 path.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
|
||||
layout(binding = 0) uniform U {
|
||||
// x = dt : semi-implicit smoothing step (larger ⇒ more smoothing)
|
||||
// y = lambda : L1 data-fidelity weight (larger ⇒ trust the SAD flow more)
|
||||
// z = edgeAlpha : luma-gradient edge sensitivity for g (larger ⇒ sharper stop)
|
||||
// w = epsTV : Charbonnier epsilon for the TV diffusivity (px; larger ⇒ softer)
|
||||
vec4 params;
|
||||
};
|
||||
|
||||
layout(binding = 32) uniform sampler2D uFlowIn; // current iterate u (.xy fwd, .zw bwd), full-res px
|
||||
layout(binding = 33) uniform sampler2D uFlowObs; // fixed observation f0 (the raw SAD flow)
|
||||
layout(binding = 34) uniform sampler2D uLuma; // prev luma at this flow level (R32F, Rec.709 [0,1])
|
||||
layout(binding = 48, rgba16f) uniform writeonly image2D uFlowOut;
|
||||
|
||||
vec4 fetchU(ivec2 p, ivec2 dim) {
|
||||
return texelFetch(uFlowIn, clamp(p, ivec2(0), dim - 1), 0);
|
||||
}
|
||||
float fetchL(ivec2 p, ivec2 dim) {
|
||||
return texelFetch(uLuma, clamp(p, ivec2(0), dim - 1), 0).r;
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 gid = ivec2(gl_GlobalInvocationID.xy);
|
||||
ivec2 dim = textureSize(uFlowIn, 0);
|
||||
if (gid.x >= dim.x || gid.y >= dim.y) return;
|
||||
|
||||
float dt = params.x;
|
||||
float lambda = params.y;
|
||||
float edgeAlpha = params.z;
|
||||
float epsTV = params.w;
|
||||
|
||||
// 4-connected neighbourhood of the current iterate (all 4 flow channels).
|
||||
vec4 uC = texelFetch(uFlowIn, gid, 0);
|
||||
vec4 uL = fetchU(gid + ivec2(-1, 0), dim);
|
||||
vec4 uR = fetchU(gid + ivec2( 1, 0), dim);
|
||||
vec4 uU = fetchU(gid + ivec2( 0, -1), dim);
|
||||
vec4 uD = fetchU(gid + ivec2( 0, 1), dim);
|
||||
|
||||
// ── Edge-aware weight g from the luma gradient (Perona-Malik / Weickert) ────
|
||||
// Luma level res == flow level res (both at kFlowFinest), so index 1:1.
|
||||
float lL = fetchL(gid + ivec2(-1, 0), dim);
|
||||
float lR = fetchL(gid + ivec2( 1, 0), dim);
|
||||
float lU = fetchL(gid + ivec2( 0,-1), dim);
|
||||
float lD = fetchL(gid + ivec2( 0, 1), dim);
|
||||
float gmag = 0.5 * length(vec2(lR - lL, lD - lU)); // |∇I|, central diff
|
||||
float g = clamp(exp(-edgeAlpha * gmag), 0.05, 1.0); // small across silhouettes
|
||||
|
||||
// ── TV diffusivity per face: w = g / sqrt(|Δu|² + ε²) ───────────────────────
|
||||
// |Δu| is the full 4-vector flow difference (vectorial-TV coupling: fwd & bwd
|
||||
// share the same motion discontinuities). Large across a flow edge ⇒ small w ⇒
|
||||
// the edge is preserved; ~0 in flat regions ⇒ large w ⇒ strong smoothing.
|
||||
vec4 dL = uL - uC, dR = uR - uC, dU = uU - uC, dD = uD - uC;
|
||||
float e2 = epsTV * epsTV;
|
||||
float qL = inversesqrt(dot(dL, dL) + e2);
|
||||
float qR = inversesqrt(dot(dR, dR) + e2);
|
||||
float qU = inversesqrt(dot(dU, dU) + e2);
|
||||
float qD = inversesqrt(dot(dD, dD) + e2);
|
||||
|
||||
float sumW = g * (qL + qR + qU + qD);
|
||||
vec4 sumWU = g * (qL * uL + qR * uR + qU * uU + qD * uD);
|
||||
|
||||
// Semi-implicit (Jacobi) TV step: a convex combination of uC and the
|
||||
// edge/TV-weighted neighbour mean ⇒ unconditionally stable, always finite.
|
||||
vec4 uDiff = (uC + dt * sumWU) / (1.0 + dt * sumW);
|
||||
|
||||
// ── L1 data term (exact TV-L1 soft-threshold toward the fixed observation) ──
|
||||
// r>θ ⇒ u=uDiff−θ , r<−θ ⇒ u=uDiff+θ , |r|≤θ ⇒ u=f0 , with θ = dt·λ.
|
||||
// The branchless form u = uDiff − clamp(r,−θ,θ) is identical per component.
|
||||
vec4 f0 = texelFetch(uFlowObs, gid, 0);
|
||||
float theta = dt * lambda;
|
||||
vec4 r = uDiff - f0;
|
||||
vec4 uNew = uDiff - clamp(r, vec4(-theta), vec4(theta));
|
||||
|
||||
imageStore(uFlowOut, gid, uNew);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ both build jobs verify the Arch Linux ARM signature and pinned SHA-256 as for ev
|
||||
The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest
|
||||
comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch,
|
||||
executable, library and build package hashes. Corresponding source is
|
||||
https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz plus the patch in this repository.
|
||||
https://download.kde.org/stable/plasma/6.8.3/kwin-6.8.3.tar.xz plus the patch in this repository.
|
||||
|
||||
The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips
|
||||
its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes.
|
||||
|
||||
@@ -6,7 +6,7 @@ here=$(cd "$(dirname "$0")" && pwd)
|
||||
source "$here/kwin.env"
|
||||
source "$here/mesa.env"
|
||||
version=$DESKTOP_KWIN_VERSION
|
||||
source_sha=ea5e68d957c7d70abed97222a592d4445fda29129e20942658badd224ee138b4
|
||||
source_sha=fd5cb783f220ea4526a9afee2f72b582c3e87ef7f91b19bc5c7a6662ffe7fbdc
|
||||
mirror=https://fl.us.mirror.archlinuxarm.org/aarch64
|
||||
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
|
||||
work=$(mktemp -d)
|
||||
|
||||
@@ -1 +1 @@
|
||||
DESKTOP_KWIN_VERSION=6.8.2
|
||||
DESKTOP_KWIN_VERSION=6.8.3
|
||||
@@ -1,9 +0,0 @@
|
||||
[Desktop Entry]
|
||||
Name=Return to Gaming Mode
|
||||
Comment=Log out of the desktop and go back to Steam
|
||||
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
|
||||
Icon=steamdeck-gaming-return
|
||||
Terminal=false
|
||||
Type=Application
|
||||
StartupNotify=false
|
||||
NoDisplay=true
|
||||
@@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay)
|
||||
- steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme),
|
||||
GPL-3.0.
|
||||
|
||||
- kwin_wayland: KWin 6.8.2, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz and
|
||||
- kwin_wayland: KWin 6.8.3, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.3/kwin-6.8.3.tar.xz and
|
||||
https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches
|
||||
(the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package).
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ if [[ -z "${docker_platform}" ]]; then
|
||||
fi
|
||||
case "${docker_platform}" in linux/arm64|linux/arm64/*) docker_platform=linux/arm64 ;; esac
|
||||
if [[ -z "${DROIDDECK_BUILD_IMAGE:-}" ]]; then
|
||||
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v4
|
||||
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v5
|
||||
[[ "${docker_platform}" == linux/arm64 ]] && DROIDDECK_BUILD_IMAGE+=-arm64
|
||||
fi
|
||||
export DROIDDECK_DOCKER_PLATFORM=${docker_platform} DROIDDECK_BUILD_IMAGE
|
||||
+86
-19
@@ -108,7 +108,8 @@ def receiver_call(adb: str, serial: str, method: str, arg: str | None, request:
|
||||
raise ControlError(f"{PACKAGE} is not running and this shell has no `content` command to start it; open DroidDeck once", "APP_NOT_RUNNING")
|
||||
call_id = uuid.uuid4().hex[:16]
|
||||
remote = f"/sdcard/Android/data/{PACKAGE}/files/agent-calls/{call_id}.json"
|
||||
command = ["shell", "am", "broadcast", "-a", f"{PACKAGE}.AGENT_CALL", "-p", PACKAGE,
|
||||
# By component: release variants rename the package but not the receiver's intent action.
|
||||
command = ["shell", "am", "broadcast", "-n", f"{PACKAGE}/com.droiddeck.launcher.agent.AgentCallReceiver",
|
||||
"--es", "method", method, "--es", "id", call_id]
|
||||
if arg is not None:
|
||||
command += ["--es", "arg", shlex.quote(arg)]
|
||||
@@ -599,7 +600,7 @@ def unpack_logs(archive: Path, destination: Path, session_id: str) -> None:
|
||||
def require_commands(adb: str, serial: str) -> dict:
|
||||
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
|
||||
if access.get("commands") is not True:
|
||||
raise ControlError("Debugging tools are off: turn on Setup > Developer > Debugging tools on the device",
|
||||
raise ControlError("droiddeckctl is off: turn on Setup > Developer > droiddeckctl on the device",
|
||||
"AGENT_COMMANDS_DISABLED")
|
||||
return access
|
||||
|
||||
@@ -750,13 +751,16 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict
|
||||
return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}}
|
||||
|
||||
commands = [
|
||||
{"id": 1, "command": "register", "name": "DroidDeck agent pen", "bus": "virtual", "configuration": [
|
||||
# The bus comes after the codes: a `uinput` without the virtual bus fails on it with no "Error reading in
|
||||
# object", while symbolic codes read first produce that message and send the script round again as numbers.
|
||||
{"id": 1, "command": "register", "name": "DroidDeck agent pen", "configuration": [
|
||||
{"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]},
|
||||
{"type": "UI_SET_KEYBIT", "data": ["BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"]},
|
||||
{"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_PRESSURE", "ABS_DISTANCE", "ABS_TILT_X", "ABS_TILT_Y"]},
|
||||
{"type": "UI_SET_PROPBIT", "data": ["INPUT_PROP_DIRECT"]},
|
||||
], "abs_info": [axis("ABS_X", 0, width - 1), axis("ABS_Y", 0, height - 1), axis("ABS_PRESSURE", 0, UINPUT_PRESSURE),
|
||||
axis("ABS_DISTANCE", 0, UINPUT_DISTANCE), axis("ABS_TILT_X", -90, 90), axis("ABS_TILT_Y", -90, 90)]},
|
||||
axis("ABS_DISTANCE", 0, UINPUT_DISTANCE), axis("ABS_TILT_X", -90, 90), axis("ABS_TILT_Y", -90, 90)],
|
||||
"bus": "virtual"},
|
||||
{"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS},
|
||||
]
|
||||
sent = {tool_key: 0, "BTN_TOUCH": 0, "BTN_STYLUS": 0, "BTN_STYLUS2": 0}
|
||||
@@ -792,27 +796,91 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict
|
||||
{"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}]
|
||||
|
||||
|
||||
def uinput_check(adb: str, serial: str) -> None:
|
||||
def uinput_check(adb: str, serial: str) -> int:
|
||||
"""Checks the device can inject through `uinput` and returns its SDK level."""
|
||||
probe = run_adb(adb, serial, "shell",
|
||||
"command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput")
|
||||
"command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput; "
|
||||
"echo sdk=$(getprop ro.build.version.sdk)")
|
||||
if probe.returncode != 0:
|
||||
raise ControlError((probe.stdout + probe.stderr).decode(errors="replace").strip() or "adb shell failed", "ADB_FAILED")
|
||||
missing = probe.stdout.decode(errors="replace").split()
|
||||
if "no-uinput" in missing:
|
||||
words = probe.stdout.decode(errors="replace").split()
|
||||
if "no-uinput" in words:
|
||||
raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE")
|
||||
if "no-dev-uinput" in missing:
|
||||
if "no-dev-uinput" in words:
|
||||
raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE")
|
||||
sdk = next((w[4:] for w in words if w.startswith("sdk=")), "")
|
||||
return int(sdk) if sdk.isdigit() else UINPUT_NAMED_SDK
|
||||
|
||||
|
||||
# Android 14 QPR2 taught `uinput` symbolic event names, the `sync` command and the virtual bus. Earlier versions stop at
|
||||
# the register line with "Error reading in object" before any device exists, so their scripts carry Linux's numeric
|
||||
# codes, register on the USB bus and end without `sync`. SDK 34 covers both sides of QPR2, so it is tried named first.
|
||||
UINPUT_NAMED_SDK = 34
|
||||
UINPUT_REJECTED = "Error reading in object"
|
||||
UINPUT_CODES = {
|
||||
"EV_SYN": 0, "EV_KEY": 1, "EV_ABS": 3, "SYN_REPORT": 0, "INPUT_PROP_DIRECT": 1,
|
||||
"BTN_SOUTH": 304, "BTN_EAST": 305, "BTN_NORTH": 307, "BTN_WEST": 308, "BTN_TL": 310, "BTN_TR": 311,
|
||||
"BTN_SELECT": 314, "BTN_START": 315, "BTN_MODE": 316, "BTN_THUMBL": 317, "BTN_THUMBR": 318,
|
||||
"BTN_TOOL_PEN": 320, "BTN_TOOL_RUBBER": 321, "BTN_TOUCH": 330, "BTN_STYLUS": 331, "BTN_STYLUS2": 332,
|
||||
"ABS_X": 0, "ABS_Y": 1, "ABS_RX": 3, "ABS_RY": 4, "ABS_HAT0X": 16, "ABS_HAT0Y": 17,
|
||||
"ABS_PRESSURE": 24, "ABS_DISTANCE": 25, "ABS_TILT_X": 26, "ABS_TILT_Y": 27,
|
||||
}
|
||||
UINPUT_CONFIG_CODES = {"UI_SET_EVBIT": 100, "UI_SET_KEYBIT": 101, "UI_SET_ABSBIT": 103, "UI_SET_PROPBIT": 110}
|
||||
|
||||
|
||||
def uinput_script(commands: list[dict], legacy: bool) -> str:
|
||||
"""The `uinput -` input: as written, or for [legacy] `uinput` numeric, on the USB bus and without `sync`."""
|
||||
if legacy:
|
||||
def code(value):
|
||||
return UINPUT_CODES[value] if isinstance(value, str) else value
|
||||
|
||||
numeric = []
|
||||
for command in commands:
|
||||
if command["command"] == "sync":
|
||||
continue
|
||||
command = dict(command)
|
||||
if command["command"] == "register":
|
||||
if command.get("bus") == "virtual":
|
||||
command["bus"] = "usb"
|
||||
command["configuration"] = [{"type": UINPUT_CONFIG_CODES[c["type"]], "data": [code(d) for d in c["data"]]}
|
||||
for c in command["configuration"]]
|
||||
command["abs_info"] = [dict(a, code=code(a["code"])) for a in command.get("abs_info", [])]
|
||||
elif command["command"] == "inject":
|
||||
command["events"] = [code(e) for e in command["events"]]
|
||||
numeric.append(command)
|
||||
commands = numeric
|
||||
return "".join(json.dumps(command) + "\n" for command in commands)
|
||||
|
||||
|
||||
def uinput_finished(result: subprocess.CompletedProcess, token: str, legacy: bool) -> bool:
|
||||
"""Whether `uinput` ran the whole script: by its sync token, or for [legacy] `uinput` by a clean exit."""
|
||||
out = result.stdout.decode(errors="replace")
|
||||
if not legacy:
|
||||
return token in out
|
||||
text = out + (result.stderr or b"").decode(errors="replace")
|
||||
return result.returncode == 0 and "Error" not in text and "Exception" not in text
|
||||
|
||||
|
||||
def uinput_run(adb: str, serial: str, sdk: int, commands: list[dict], token: str,
|
||||
timeout: float) -> tuple[subprocess.CompletedProcess, bool]:
|
||||
"""Runs [commands] through `uinput -` in the form the device reads; returns the result and whether it finished."""
|
||||
legacy = sdk < UINPUT_NAMED_SDK
|
||||
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=uinput_script(commands, legacy).encode(), timeout=timeout)
|
||||
out = result.stdout.decode(errors="replace")
|
||||
if not legacy and UINPUT_REJECTED in out and token not in out:
|
||||
legacy = True
|
||||
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=uinput_script(commands, legacy).encode(), timeout=timeout)
|
||||
return result, uinput_finished(result, token, legacy)
|
||||
|
||||
|
||||
def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
|
||||
uinput_check(adb, serial)
|
||||
sdk = uinput_check(adb, serial)
|
||||
viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace"))
|
||||
script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport))
|
||||
started = time.monotonic()
|
||||
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(),
|
||||
timeout=(UINPUT_REGISTER_MS + samples[-1]["t"] + UINPUT_TAIL_MS) / 1000 + 30)
|
||||
result, finished = uinput_run(adb, serial, sdk, uinput_commands(samples, tool, viewport), UINPUT_SYNC,
|
||||
(UINPUT_REGISTER_MS + samples[-1]["t"] + UINPUT_TAIL_MS) / 1000 + 30)
|
||||
elapsed = round((time.monotonic() - started) * 1000)
|
||||
if UINPUT_SYNC not in result.stdout.decode(errors="replace"):
|
||||
if not finished:
|
||||
detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:]
|
||||
raise ControlError(f"uinput stopped before the end of the gesture (exit {result.returncode})"
|
||||
+ (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why",
|
||||
@@ -869,13 +937,12 @@ def gamepad_commands(buttons: list[str], hold: int, gap: int) -> list[dict]:
|
||||
|
||||
def gamepad_uinput(adb: str, serial: str, buttons: list[str], hold: int, gap: int) -> dict:
|
||||
commands = gamepad_commands(buttons, hold, gap)
|
||||
uinput_check(adb, serial)
|
||||
script = "".join(json.dumps(command) + "\n" for command in commands)
|
||||
sdk = uinput_check(adb, serial)
|
||||
started = time.monotonic()
|
||||
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(),
|
||||
timeout=(UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30)
|
||||
result, finished = uinput_run(adb, serial, sdk, commands, GAMEPAD_SYNC,
|
||||
(UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30)
|
||||
elapsed = round((time.monotonic() - started) * 1000)
|
||||
if GAMEPAD_SYNC not in result.stdout.decode(errors="replace"):
|
||||
if not finished:
|
||||
detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:]
|
||||
raise ControlError(f"uinput stopped before the last button (exit {result.returncode})"
|
||||
+ (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why",
|
||||
|
||||
@@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \
|
||||
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
|
||||
ninja -C fex-build
|
||||
DESTDIR="$WORK/out" ninja -C fex-build install
|
||||
mkdir -p out/usr/local/share/fex-emu
|
||||
for p in tools/fex/patches/*.patch; do
|
||||
p=$(basename "$p" .patch)
|
||||
echo "${p#*-}"
|
||||
done > out/usr/local/share/fex-emu/.droiddeck-patches
|
||||
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
|
||||
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
|
||||
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
Fixed-upstream: FEX-2612
|
||||
diff --git a/CMakeLists.txt b/CMakeLists.txt
|
||||
index 8976588..3ae54f4 100644
|
||||
--- a/CMakeLists.txt
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index b4c7b24..643185d 100644
|
||||
index 345f4d834..085ff00a2 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
|
||||
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
index 02bb6bf..2e72492 100644
|
||||
index 02bb6bfef..2e724929f 100644
|
||||
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
@@ -49,6 +49,11 @@ struct X86ContextBackup {
|
||||
@@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644
|
||||
|
||||
// Arm64 doesn't have a red zone
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index 643185d..53179c4 100644
|
||||
index 085ff00a2..5c79d1092 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ index 643185d..53179c4 100644
|
||||
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
|
||||
// We can end up getting a signal at any point in our host state
|
||||
// Jump to a handler that saves all state so we can safely return
|
||||
@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
}
|
||||
|
||||
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
|
||||
@@ -82,7 +82,7 @@ index 643185d..53179c4 100644
|
||||
}
|
||||
|
||||
uintptr_t NewSP = OldSP;
|
||||
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
|
||||
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
@@ -90,7 +90,7 @@ index 643185d..53179c4 100644
|
||||
|
||||
// Ref count our faults
|
||||
// We use this to track if it is safe to clear cache
|
||||
@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
|
||||
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
|
||||
uint64_t NewGuestSP = OldGuestSP;
|
||||
@@ -99,7 +99,7 @@ index 643185d..53179c4 100644
|
||||
|
||||
// altstack is only used if the signal handler was setup with SA_ONSTACK
|
||||
if (GuestAction->sa_flags & SA_ONSTACK) {
|
||||
@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
|
||||
uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp);
|
||||
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
|
||||
@@ -108,7 +108,7 @@ index 643185d..53179c4 100644
|
||||
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
|
||||
// We are already in the alt stack, the rest of the code will handle adjusting this
|
||||
} else {
|
||||
@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ index 643185d..53179c4 100644
|
||||
// siginfo_t
|
||||
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
|
||||
|
||||
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
|
||||
@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
|
||||
|
||||
// Our ref counting doesn't matter anymore
|
||||
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
|
||||
@@ -159,7 +159,7 @@ index 643185d..53179c4 100644
|
||||
// Set the new PC
|
||||
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index dfcd4b0..e4a86a9 100644
|
||||
index 0f45cf68d..408cddf71 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
index 1946dc946..9f04358c5 100644
|
||||
--- a/FEXCore/Source/Interface/Core/Core.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
@@ -383,7 +383,11 @@
|
||||
@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() {
|
||||
}
|
||||
|
||||
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
|
||||
@@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C
|
||||
|
||||
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
index ae3ed51e4..c5e656d2c 100644
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
@@ -305,6 +305,9 @@
|
||||
@@ -306,6 +306,9 @@ DEF_OP(Thunk) {
|
||||
|
||||
PushDynamicRegs(TMP1);
|
||||
|
||||
@@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
|
||||
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
|
||||
|
||||
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
|
||||
@@ -320,6 +323,8 @@
|
||||
@@ -321,6 +324,8 @@ DEF_OP(Thunk) {
|
||||
FillStaticRegs({
|
||||
.NZCV = false,
|
||||
});
|
||||
@@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
|
||||
|
||||
DEF_OP(ValidateCode) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index 5c79d1092..e8e04b056 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -107,6 +107,10 @@
|
||||
@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
#ifdef ARCHITECTURE_arm64
|
||||
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
|
||||
|
||||
@@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
|
||||
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
|
||||
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
|
||||
if (IgnoreMask & (1U << SRAIdxMap)) {
|
||||
@@ -301,12 +305,10 @@
|
||||
@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
if (Context->UContextLocation) {
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
|
||||
@@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
|
||||
|
||||
if (Is64BitMode) {
|
||||
RestoreFrame_x64(Thread, Context, Frame, ucontext);
|
||||
@@ -361,6 +363,9 @@
|
||||
@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
|
||||
Thread->CurrentFrame->InSyscallInfo = 0;
|
||||
} else {
|
||||
@@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
|
||||
// This is likely to cause issues but in some cases it isn't fatal
|
||||
// This can also happen if we have put a signal on hold, then we just reenabled the signal
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
index fa6260954..e5d92e7c5 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
@@ -131,7 +131,7 @@
|
||||
@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
|
||||
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
|
||||
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
@@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -211,7 +211,7 @@
|
||||
@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
|
||||
// If the guest modified the RIP then we need to take special precautions here
|
||||
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
@@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -290,7 +290,7 @@
|
||||
@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
|
||||
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
|
||||
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
index 9e6820bf6..43898e700 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
@@ -263,6 +263,8 @@
|
||||
@@ -266,6 +266,8 @@ private:
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
||||
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
||||
@@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc
|
||||
///< Setup the signal frame for x64.
|
||||
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
index e5d92e7c5..38dc524f1 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
@@ -122,6 +122,32 @@
|
||||
@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
|
||||
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
|
||||
@@ -202,6 +228,27 @@
|
||||
@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
|
||||
}
|
||||
@@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +327,17 @@
|
||||
@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
||||
}
|
||||
@@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,6 +417,17 @@
|
||||
@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
|
||||
index 2881ad9..abc84f3 100644
|
||||
index dd2c18303..e7e88f8f2 100644
|
||||
--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
|
||||
+++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
|
||||
@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) {
|
||||
@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) {
|
||||
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName);
|
||||
} else {
|
||||
// Anonymous program.
|
||||
@@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644
|
||||
}
|
||||
} else {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
index a7a432b..4a77d87 100644
|
||||
index a7a432bbd..4a77d8716 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
index cebf1f5..b1a72d2 100644
|
||||
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
@@ -32,6 +32,7 @@
|
||||
#include <sys/personality.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/random.h>
|
||||
+#include <sys/resource.h>
|
||||
|
||||
#define PAGE_START(x) ((x) & ~(uintptr_t)(4095))
|
||||
#define PAGE_OFFSET(x) ((x) & 4095)
|
||||
@@ -505,7 +506,12 @@ public:
|
||||
auto PageSize = sysconf(_SC_PAGESIZE);
|
||||
PageSize = PageSize > 0 ? PageSize : FEXCore::Utils::FEX_PAGE_SIZE;
|
||||
|
||||
+ const auto [HostStackLow, HostStackHigh] = HostStackReservation(PageSize);
|
||||
+
|
||||
do {
|
||||
+ if (StackHint < HostStackHigh && StackHint + FULL_STACK_SIZE > HostStackLow && HostStackLow > FULL_STACK_SIZE) {
|
||||
+ StackHint = (HostStackLow - FULL_STACK_SIZE) & ~static_cast<uint64_t>(PageSize - 1);
|
||||
+ }
|
||||
// Allocate the base of the full 128MB stack range.
|
||||
StackPointerBase = Handler->GuestMmap(Thread, reinterpret_cast<void*>(StackHint), FULL_STACK_SIZE, PROT_NONE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_GROWSDOWN | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0);
|
||||
@@ -793,6 +799,19 @@ public:
|
||||
*AuxTabSize = sizeof(AuxType) * AuxVariables.size();
|
||||
}
|
||||
|
||||
+ static std::pair<uint64_t, uint64_t> HostStackReservation(uint64_t PageSize) {
|
||||
+ struct prctl_mm_map map {};
|
||||
+ uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast<uint64_t>(__builtin_frame_address(0));
|
||||
+ Top = (Top + PageSize - 1) & ~(PageSize - 1);
|
||||
+
|
||||
+ constexpr uint64_t MinGap = 128ULL * 1024 * 1024;
|
||||
+ const uint64_t MaxGap = std::max(Top / 6 * 5, MinGap);
|
||||
+ struct rlimit Limit {};
|
||||
+ uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast<uint64_t>(Limit.rlim_cur) : MinGap;
|
||||
+ Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize;
|
||||
+ return {Top > Gap ? Top - Gap : 0, Top};
|
||||
+ }
|
||||
+
|
||||
// Get the current memory map from /proc/self/stat
|
||||
static bool GetCurrentMap(struct prctl_mm_map& map) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Subject: [PATCH] List only guest mappings in /proc/<pid>/maps on hosts below 47 address bits
|
||||
|
||||
Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index eb12945e4..65b0521c9 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -17,7 +17,11 @@ $end_info$
|
||||
#include <FEXCore/Config/Config.h>
|
||||
#include <FEXCore/Core/Context.h>
|
||||
#include <FEXCore/Core/CPUID.h>
|
||||
+#include <FEXCore/Utils/Allocator.h>
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
+#include <FEXCore/Utils/SignalScopeGuards.h>
|
||||
+#include <FEXCore/fextl/unordered_map.h>
|
||||
+#include <FEXCore/fextl/vector.h>
|
||||
#include <FEXCore/fextl/fmt.h>
|
||||
#include <FEXCore/fextl/string.h>
|
||||
#include <FEXCore/fextl/sstream.h>
|
||||
@@ -25,9 +29,13 @@ $end_info$
|
||||
|
||||
#include <git_version.h>
|
||||
|
||||
+#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
+#include <elf.h>
|
||||
+#include <mutex>
|
||||
+#include <shared_mutex>
|
||||
#include <fcntl.h>
|
||||
#include <filesystem>
|
||||
#include <ostream>
|
||||
@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
|
||||
|
||||
EmulatedFDManager::~EmulatedFDManager() {}
|
||||
|
||||
+static bool IsSelfProcPath(const char* Path) {
|
||||
+ const char* P = Path + 6;
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return strtol(P, nullptr, 10) == ::getpid();
|
||||
+}
|
||||
+
|
||||
+static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::string, bool>& Seen) {
|
||||
+ auto Known = Seen.find(Path);
|
||||
+ if (Known != Seen.end()) {
|
||||
+ return Known->second;
|
||||
+ }
|
||||
+ bool Host = false;
|
||||
+ int FD = ::open(Path, O_RDONLY | O_CLOEXEC);
|
||||
+ if (FD >= 0) {
|
||||
+ Elf64_Ehdr Header {};
|
||||
+ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast<ssize_t>(offsetof(Elf64_Ehdr, e_version)) &&
|
||||
+ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) {
|
||||
+#if defined(__aarch64__)
|
||||
+ Host = Header.e_machine == EM_AARCH64;
|
||||
+#else
|
||||
+ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386;
|
||||
+#endif
|
||||
+ }
|
||||
+ ::close(FD);
|
||||
+ }
|
||||
+ Seen.emplace(Path, Host);
|
||||
+ return Host;
|
||||
+}
|
||||
+
|
||||
static bool IsProcMapsPath(const char* Path) {
|
||||
if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
return false;
|
||||
@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
|
||||
::close(HostFD);
|
||||
|
||||
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
|
||||
+ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
|
||||
+ const bool Self = IsSelfProcPath(pathname);
|
||||
+ fextl::vector<std::pair<uint64_t, uint64_t>> GuestRanges;
|
||||
+ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) {
|
||||
+ auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(FEX::HLE::_SyscallHandler->VMATracking.Mutex);
|
||||
+ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size());
|
||||
+ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) {
|
||||
+ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) {
|
||||
+ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length);
|
||||
+ } else {
|
||||
+ GuestRanges.emplace_back(Base, Base + VMA.Length);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) {
|
||||
+ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start,
|
||||
+ [](uint64_t Value, const std::pair<uint64_t, uint64_t>& Range) { return Value < Range.first; });
|
||||
+ if (It != GuestRanges.begin() && std::prev(It)->second > Start) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return It != GuestRanges.end() && It->first < End;
|
||||
+ };
|
||||
+ fextl::unordered_map<fextl::string, bool> ModuleArch;
|
||||
fextl::string Out;
|
||||
Out.reserve(In.size());
|
||||
size_t Pos = 0;
|
||||
while (Pos < In.size()) {
|
||||
size_t Eol = In.find('\n', Pos);
|
||||
const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1;
|
||||
- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16);
|
||||
- if (Start < X86_64TaskSizeMax) {
|
||||
+ char* Cursor {};
|
||||
+ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16);
|
||||
+ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start;
|
||||
+ bool Keep = Start < X86_64TaskSizeMax;
|
||||
+ if (Keep && HostSharesGuestRange) {
|
||||
+ if (Self) {
|
||||
+ Keep = IsGuestRange(Start, Stop);
|
||||
+ } else {
|
||||
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
|
||||
+ size_t Name = In.find_first_of("/[", Pos);
|
||||
+ if (Name != fextl::string::npos && Name < LineEnd) {
|
||||
+ fextl::string Path(In, Name, LineEnd - Name);
|
||||
+ if (Path.starts_with("[anon:FEX")) {
|
||||
+ Keep = false;
|
||||
+ } else if (Path[0] == '/') {
|
||||
+ Keep = !IsHostArchModule(Path.c_str(), ModuleArch);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ if (Keep) {
|
||||
Out.append(In, Pos, End - Pos);
|
||||
}
|
||||
Pos = End;
|
||||
@@ -0,0 +1,53 @@
|
||||
From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:21:23 -0500
|
||||
Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
.../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++-
|
||||
.../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++
|
||||
2 files changed, 15 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index 65b0521c9..ce36b988b 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
Buf[Len] = '\0';
|
||||
|
||||
uint32_t SeccompMode = SECCOMP_MODE_DISABLED;
|
||||
- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) {
|
||||
+ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr;
|
||||
+ if (!Thread) {
|
||||
+ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject();
|
||||
+ }
|
||||
+ if (Thread) {
|
||||
SeccompMode = Thread->SeccompMode;
|
||||
}
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index 0a46703ca..9c5f9f1c2 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -290,6 +290,16 @@ public:
|
||||
return &Threads;
|
||||
}
|
||||
|
||||
+ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) {
|
||||
+ std::lock_guard lk(ThreadCreationMutex);
|
||||
+ for (auto* Thread : Threads) {
|
||||
+ if (Thread->ThreadInfo.TID == TID) {
|
||||
+ return Thread;
|
||||
+ }
|
||||
+ }
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+
|
||||
private:
|
||||
struct InvalidationStats {
|
||||
explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread)
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:25:20 -0500
|
||||
Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system
|
||||
call
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++
|
||||
.../EmulatedFiles/EmulatedFiles.cpp | 3 +-
|
||||
.../LinuxSyscalls/PtraceEmu.cpp | 3 +-
|
||||
3 files changed, 34 insertions(+), 2 deletions(-)
|
||||
|
||||
diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
index dae3d3bcc..c0f3eb3ed 100644
|
||||
--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
+++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
|
||||
#include <cstdint>
|
||||
+#include <errno.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
@@ -123,4 +124,33 @@ inline int32_t gettid() {
|
||||
|
||||
#endif
|
||||
|
||||
+#ifndef _WIN32
|
||||
+inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) {
|
||||
+#if defined(__aarch64__)
|
||||
+ register long x0 asm("x0") = dirfd;
|
||||
+ register long x1 asm("x1") = reinterpret_cast<long>(pathname);
|
||||
+ register long x2 asm("x2") = flags;
|
||||
+ register long x3 asm("x3") = 0;
|
||||
+ register long x8 asm("x8") = SYS_openat;
|
||||
+ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory");
|
||||
+ if (x0 < 0) {
|
||||
+ errno = static_cast<int>(-x0);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ return static_cast<int32_t>(x0);
|
||||
+#elif defined(__x86_64__)
|
||||
+ long ret;
|
||||
+ register long r10 asm("r10") = 0;
|
||||
+ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory");
|
||||
+ if (ret < 0) {
|
||||
+ errno = static_cast<int>(-ret);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ return static_cast<int32_t>(ret);
|
||||
+#else
|
||||
+ return static_cast<int32_t>(::syscall(SYS_openat, dirfd, pathname, flags));
|
||||
+#endif
|
||||
+}
|
||||
+#endif
|
||||
+
|
||||
} // namespace FHU::Syscalls
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index ce36b988b..19bfc814f 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -14,6 +14,7 @@ $end_info$
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
#include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
|
||||
|
||||
+#include <FEXHeaderUtils/Syscalls.h>
|
||||
#include <FEXCore/Config/Config.h>
|
||||
#include <FEXCore/Core/Context.h>
|
||||
#include <FEXCore/Core/CPUID.h>
|
||||
@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
char Buf[8192];
|
||||
ssize_t Len = 0;
|
||||
{
|
||||
- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
+ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
if (HostFD >= 0) {
|
||||
Len = ::read(HostFD, Buf, sizeof(Buf) - 1);
|
||||
::close(HostFD);
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
index ca4c86063..49ece24a3 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "LinuxSyscalls/PtraceEmu.h"
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
|
||||
+#include <FEXHeaderUtils/Syscalls.h>
|
||||
#include <FEXCore/Core/CoreState.h>
|
||||
#include <FEXCore/Core/X86Enums.h>
|
||||
|
||||
@@ -133,7 +134,7 @@ namespace {
|
||||
}
|
||||
|
||||
bool HasHostTracer() {
|
||||
- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
+ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
return true;
|
||||
}
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:41:52 -0500
|
||||
Subject: [PATCH] Hand the tracee's ptrace state across exec
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
.../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++-
|
||||
1 file changed, 53 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
index 49ece24a3..62acdb0da 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
@@ -266,6 +266,38 @@ namespace {
|
||||
::close(fd);
|
||||
}
|
||||
|
||||
+ bool AdoptionTried = false;
|
||||
+
|
||||
+ void AdoptSharedPage() {
|
||||
+ if (AdoptionTried || Current != &StaticState || !IsMainThread()) {
|
||||
+ return;
|
||||
+ }
|
||||
+ AdoptionTried = true;
|
||||
+ const int fd = OpenSidecar("state", ::getpid(), O_RDWR);
|
||||
+ if (fd < 0) {
|
||||
+ return;
|
||||
+ }
|
||||
+ if (!HasHostTracer()) {
|
||||
+ ::close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
+ ::close(fd);
|
||||
+ if (Page == MAP_FAILED) {
|
||||
+ return;
|
||||
+ }
|
||||
+ auto* S = static_cast<SharedState*>(Page);
|
||||
+ if (S->Magic != SharedState::MagicValue) {
|
||||
+ ::munmap(Page, 4096);
|
||||
+ return;
|
||||
+ }
|
||||
+ S->Pending = 0;
|
||||
+ S->DirtyMask = 0;
|
||||
+ S->SignalNumber = 0;
|
||||
+ S->FlushLen = 0;
|
||||
+ Current = S;
|
||||
+ }
|
||||
+
|
||||
struct Remote {
|
||||
uint8_t* Mapped = nullptr;
|
||||
uintptr_t StaticAddr = 0;
|
||||
@@ -332,6 +364,22 @@ namespace {
|
||||
return &Remotes.emplace(Pid, std::move(R)).first->second;
|
||||
}
|
||||
|
||||
+ bool KeepAcrossExec(pid_t Pid) {
|
||||
+ {
|
||||
+ std::lock_guard lk(RemotesLock);
|
||||
+ auto It = Remotes.find(Pid);
|
||||
+ if (It != Remotes.end()) {
|
||||
+ return It->second.Mapped != nullptr;
|
||||
+ }
|
||||
+ }
|
||||
+ const int fd = OpenSidecar("state", Pid, O_RDONLY);
|
||||
+ if (fd < 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ ::close(fd);
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
void Forget(pid_t Pid, bool Exited) {
|
||||
std::lock_guard lk(RemotesLock);
|
||||
auto It = Remotes.find(Pid);
|
||||
@@ -470,10 +518,12 @@ namespace {
|
||||
|
||||
|
||||
bool IsAttached() {
|
||||
+ AdoptSharedPage();
|
||||
return Current->Attached != 0;
|
||||
}
|
||||
|
||||
bool WantsSyscallStops() {
|
||||
+ AdoptSharedPage();
|
||||
return Current->SyscallStops && IsMainThread();
|
||||
}
|
||||
|
||||
@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) {
|
||||
|
||||
if ((St >> 16) == X86_PTRACE_EVENT_EXEC) {
|
||||
CaptureExecPath(Pid);
|
||||
- Forget(Pid, false);
|
||||
+ if (!KeepAcrossExec(Pid)) {
|
||||
+ Forget(Pid, false);
|
||||
+ }
|
||||
}
|
||||
|
||||
if (WSTOPSIG(St) == SIGSTOP) {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:58:13 -0500
|
||||
Subject: [PATCH] Serve emulated proc files by the requested path when the host
|
||||
returns a memfd
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
---
|
||||
.../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++----
|
||||
.../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +-
|
||||
2 files changed, 8 insertions(+), 5 deletions(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
index 62b6a2d27..b76e96e58 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint
|
||||
return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode);
|
||||
}
|
||||
|
||||
-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
|
||||
+bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) {
|
||||
char Tmp[PATH_MAX + 1];
|
||||
|
||||
if (fd < 0) {
|
||||
@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
|
||||
|
||||
// And try to open via EmuFD
|
||||
auto EmuFd = EmuFD.Open(Tmp, flags, mode);
|
||||
+ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) {
|
||||
+ EmuFd = EmuFD.Open(RequestedPath, flags, mode);
|
||||
+ }
|
||||
if (EmuFd == -1) {
|
||||
return false;
|
||||
}
|
||||
@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
|
||||
fd = ::open(SelfPath, flags, mode);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, flags, mode);
|
||||
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
|
||||
} else {
|
||||
fd = ::open(SelfPath, flags, mode);
|
||||
}
|
||||
@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
|
||||
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, flags, mode);
|
||||
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
|
||||
} else {
|
||||
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
|
||||
}
|
||||
@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, how->flags, how->mode);
|
||||
+ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath);
|
||||
} else {
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
|
||||
}
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
index b11f096f7..a86539972 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
@@ -102,7 +102,7 @@ public:
|
||||
fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const;
|
||||
fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const;
|
||||
|
||||
- bool ReplaceEmuFd(int fd, int flags, uint32_t mode);
|
||||
+ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath);
|
||||
|
||||
#if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED
|
||||
void TrackFEXFD(int FD) noexcept {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,58 @@
|
||||
From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Thu, 3 Dec 2026 03:26:13 -0500
|
||||
Subject: [PATCH] Show the guest command line when the argument area cannot be
|
||||
remapped
|
||||
|
||||
Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP,
|
||||
so /proc/pid/cmdline kept showing the FEX invocation instead of the
|
||||
guest program and the argv rewrites it makes. For 64-bit guests whose
|
||||
arguments fit, the guest argument strings now live in the original
|
||||
argument area and argv points there, which needs no privilege.
|
||||
---
|
||||
Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++-
|
||||
1 file changed, 22 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
index b1a72d227..6d2157365 100644
|
||||
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
@@ -874,13 +874,34 @@ public:
|
||||
|
||||
int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L);
|
||||
if (r != 0) {
|
||||
- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno);
|
||||
+ int Error = errno;
|
||||
+ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) {
|
||||
+ return;
|
||||
+ }
|
||||
+ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error);
|
||||
}
|
||||
} else {
|
||||
LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)");
|
||||
}
|
||||
}
|
||||
|
||||
+ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) {
|
||||
+ struct prctl_mm_map map {};
|
||||
+ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ auto HostArgs = reinterpret_cast<uint8_t*>(map.arg_start);
|
||||
+ memmove(HostArgs, reinterpret_cast<const void*>(GuestArgStart), ArgSize);
|
||||
+ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize);
|
||||
+
|
||||
+ auto ArgumentPointers = reinterpret_cast<uint64_t*>(StackPointer + sizeof(uint64_t));
|
||||
+ for (size_t i = 0; i < ApplicationArgs.size(); ++i) {
|
||||
+ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start;
|
||||
+ }
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
// Setups the stack initial data (argv, envp, auxv)
|
||||
void SetupStack() {
|
||||
StackPointer += StackSize();
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Thu, 3 Dec 2026 08:03:20 -0500
|
||||
Subject: [PATCH] Describe the container's procfs in emulated mount tables
|
||||
|
||||
Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the
|
||||
processes of other users. Every process of the container runs as the app's
|
||||
user, so the container sees all of its own processes, as it would through a
|
||||
procfs of its own in a PID namespace. The emulated /proc/<pid>/mounts and
|
||||
mountinfo now list the proc mount without the host instance's access options
|
||||
(hidepid, gid, subset). Every other mount is passed through unchanged.
|
||||
---
|
||||
.../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++-----
|
||||
.../EmulatedFiles/EmulatedFiles.h | 1 +
|
||||
2 files changed, 170 insertions(+), 61 deletions(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index 19bfc814f..85f1b3e15 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -37,6 +37,7 @@ $end_info$
|
||||
#include <elf.h>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
+#include <string_view>
|
||||
#include <fcntl.h>
|
||||
#include <filesystem>
|
||||
#include <ostream>
|
||||
@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::strin
|
||||
return Host;
|
||||
}
|
||||
|
||||
+static bool ReadHostFile(const char* Path, fextl::string& Out) {
|
||||
+ int HostFD = ::open(Path, O_RDONLY | O_CLOEXEC);
|
||||
+ if (HostFD < 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ char Buf[65536];
|
||||
+ for (;;) {
|
||||
+ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
|
||||
+ if (Len > 0) {
|
||||
+ Out.append(Buf, Len);
|
||||
+ } else if (Len == 0) {
|
||||
+ break;
|
||||
+ } else if (errno != EINTR) {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno);
|
||||
+ ::close(HostFD);
|
||||
+ return false;
|
||||
+ }
|
||||
+ }
|
||||
+ ::close(HostFD);
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
+static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) {
|
||||
+ int NewFD = GenTmpFD(pathname, flags);
|
||||
+ if (NewFD < 0) {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ for (size_t Done = 0; Done < Data.size();) {
|
||||
+ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done);
|
||||
+ if (Wrote > 0) {
|
||||
+ Done += Wrote;
|
||||
+ } else if (Wrote < 0 && errno == EINTR) {
|
||||
+ continue;
|
||||
+ } else {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno);
|
||||
+ ::close(NewFD);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ }
|
||||
+ if (::lseek(NewFD, 0, SEEK_SET) != 0) {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno);
|
||||
+ ::close(NewFD);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ SealTmpFD(NewFD);
|
||||
+ return NewFD;
|
||||
+}
|
||||
+
|
||||
+static const char* ProcFileOfPid(const char* Path) {
|
||||
+ if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ const char* P = Path + 6;
|
||||
+ if (strncmp(P, "self/", 5) == 0) {
|
||||
+ return P + 5;
|
||||
+ }
|
||||
+ if (strncmp(P, "thread-self/", 12) == 0) {
|
||||
+ return P + 12;
|
||||
+ }
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return P;
|
||||
+ }
|
||||
+ while (isdigit(*P)) {
|
||||
+ ++P;
|
||||
+ }
|
||||
+ if (*P++ != '/') {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ if (strncmp(P, "task/", 5) == 0) {
|
||||
+ P += 5;
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ while (isdigit(*P)) {
|
||||
+ ++P;
|
||||
+ }
|
||||
+ if (*P++ != '/') {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ }
|
||||
+ return P;
|
||||
+}
|
||||
+
|
||||
+static bool IsProcMountTablePath(const char* Path) {
|
||||
+ const char* File = ProcFileOfPid(Path);
|
||||
+ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0);
|
||||
+}
|
||||
+
|
||||
+static fextl::string ContainerProcOptions(std::string_view Options) {
|
||||
+ fextl::string Out;
|
||||
+ size_t Pos = 0;
|
||||
+ while (Pos <= Options.size()) {
|
||||
+ size_t Comma = Options.find(',', Pos);
|
||||
+ if (Comma == std::string_view::npos) {
|
||||
+ Comma = Options.size();
|
||||
+ }
|
||||
+ const std::string_view Option = Options.substr(Pos, Comma - Pos);
|
||||
+ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) {
|
||||
+ if (!Out.empty()) {
|
||||
+ Out += ',';
|
||||
+ }
|
||||
+ Out.append(Option);
|
||||
+ }
|
||||
+ Pos = Comma + 1;
|
||||
+ }
|
||||
+ return Out;
|
||||
+}
|
||||
+
|
||||
+static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {
|
||||
+ fextl::vector<std::string_view> Fields;
|
||||
+ size_t Pos = 0;
|
||||
+ while (Pos < Line.size()) {
|
||||
+ size_t Space = Line.find(' ', Pos);
|
||||
+ if (Space == std::string_view::npos) {
|
||||
+ Space = Line.size();
|
||||
+ }
|
||||
+ Fields.push_back(Line.substr(Pos, Space - Pos));
|
||||
+ Pos = Space + 1;
|
||||
+ }
|
||||
+ size_t Type = 2;
|
||||
+ if (MountInfo) {
|
||||
+ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-"));
|
||||
+ Type = static_cast<size_t>(Dash - Fields.begin()) + 1;
|
||||
+ }
|
||||
+ const size_t Options = MountInfo ? Type + 2 : Type + 1;
|
||||
+ if (Options >= Fields.size() || Fields[Type] != "proc") {
|
||||
+ return fextl::string(Line);
|
||||
+ }
|
||||
+ fextl::string Out;
|
||||
+ for (size_t i = 0; i < Fields.size(); ++i) {
|
||||
+ if (i) {
|
||||
+ Out += ' ';
|
||||
+ }
|
||||
+ if (i == Options) {
|
||||
+ Out += ContainerProcOptions(Fields[i]);
|
||||
+ } else {
|
||||
+ Out.append(Fields[i]);
|
||||
+ }
|
||||
+ }
|
||||
+ return Out;
|
||||
+}
|
||||
+
|
||||
static bool IsProcMapsPath(const char* Path) {
|
||||
if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
return false;
|
||||
@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
|
||||
if (pathname && IsProcMapsPath(pathname)) {
|
||||
return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode);
|
||||
}
|
||||
+ if (pathname && IsProcMountTablePath(pathname)) {
|
||||
+ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);
|
||||
+ }
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
|
||||
}
|
||||
|
||||
int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
- int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC);
|
||||
- if (HostFD < 0) {
|
||||
- return -1;
|
||||
- }
|
||||
fextl::string In;
|
||||
- char Buf[65536];
|
||||
- for (;;) {
|
||||
- const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
|
||||
- if (Len > 0) {
|
||||
- In.append(Buf, Len);
|
||||
- } else if (Len == 0) {
|
||||
- break;
|
||||
- } else if (errno != EINTR) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno);
|
||||
- ::close(HostFD);
|
||||
- return -1;
|
||||
- }
|
||||
+ if (!ReadHostFile(pathname, In)) {
|
||||
+ return -1;
|
||||
}
|
||||
- ::close(HostFD);
|
||||
|
||||
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
|
||||
const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
|
||||
@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
|
||||
Pos = End;
|
||||
}
|
||||
|
||||
- int NewFD = GenTmpFD(pathname, flags);
|
||||
- if (NewFD < 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
|
||||
+ return SealedFileOf(pathname, flags, Out);
|
||||
+}
|
||||
+
|
||||
+int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
+ fextl::string In;
|
||||
+ if (!ReadHostFile(pathname, In)) {
|
||||
return -1;
|
||||
}
|
||||
- for (size_t Done = 0; Done < Out.size();) {
|
||||
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
|
||||
- if (Wrote > 0) {
|
||||
- Done += Wrote;
|
||||
- } else if (Wrote < 0 && errno == EINTR) {
|
||||
- continue;
|
||||
- } else {
|
||||
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
+ const char* File = ProcFileOfPid(pathname);
|
||||
+ const bool MountInfo = File && strcmp(File, "mountinfo") == 0;
|
||||
+ fextl::string Out;
|
||||
+ Out.reserve(In.size());
|
||||
+ size_t Pos = 0;
|
||||
+ while (Pos < In.size()) {
|
||||
+ size_t Eol = In.find('\n', Pos);
|
||||
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
|
||||
+ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
|
||||
+ if (Eol != fextl::string::npos) {
|
||||
+ Out += '\n';
|
||||
}
|
||||
+ Pos = LineEnd + 1;
|
||||
}
|
||||
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
- }
|
||||
- SealTmpFD(NewFD);
|
||||
- return NewFD;
|
||||
+ return SealedFileOf(pathname, flags, Out);
|
||||
}
|
||||
|
||||
int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
Cursor = Eol + 1;
|
||||
}
|
||||
|
||||
- int NewFD = GenTmpFD(pathname, flags);
|
||||
- if (NewFD < 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
|
||||
- return -1;
|
||||
- }
|
||||
- for (size_t Done = 0; Done < Out.size();) {
|
||||
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
|
||||
- if (Wrote > 0) {
|
||||
- Done += Wrote;
|
||||
- } else if (Wrote < 0 && errno == EINTR) {
|
||||
- continue;
|
||||
- } else {
|
||||
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
- }
|
||||
- }
|
||||
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
- }
|
||||
- SealTmpFD(NewFD);
|
||||
- return NewFD;
|
||||
+ return SealedFileOf(pathname, flags, Out);
|
||||
}
|
||||
|
||||
int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
|
||||
index b98ef4bda..b1ec241a7 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
|
||||
@@ -35,6 +35,7 @@ private:
|
||||
|
||||
static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
+ static int32_t ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
const uint32_t ThreadsConfig;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define HIGH ((uintptr_t)0x7e0000000000ULL)
|
||||
#define ALIAS ((uintptr_t)0x7e0000100000ULL)
|
||||
#define THREADS 4
|
||||
#define ITERS 200000
|
||||
|
||||
static volatile uint64_t *counter;
|
||||
static volatile uint64_t *cas;
|
||||
static int fails;
|
||||
|
||||
static void check(const char *name, int ok) {
|
||||
printf("%s %s\n", ok ? "PASS" : "FAIL", name);
|
||||
if (!ok) fails++;
|
||||
}
|
||||
|
||||
static void *worker(void *arg) {
|
||||
(void)arg;
|
||||
for (int i = 0; i < ITERS; i++) {
|
||||
__atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST);
|
||||
uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED);
|
||||
while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
alarm(60);
|
||||
uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
|
||||
if (high == MAP_FAILED) {
|
||||
printf("NOTCLAIMED errno=%d\n", errno);
|
||||
return 0;
|
||||
}
|
||||
check("fixed-high-map", high == (uint8_t *)HIGH);
|
||||
memset(high, 0x5a, 65536);
|
||||
check("load-store", high[100] == 0x5a && high[65535] == 0x5a);
|
||||
|
||||
counter = (uint64_t *)(high + 64);
|
||||
cas = (uint64_t *)(high + 128);
|
||||
*counter = 0;
|
||||
*cas = 0;
|
||||
pthread_t t[THREADS];
|
||||
for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL);
|
||||
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
|
||||
check("atomic-add", *counter == (uint64_t)THREADS * ITERS);
|
||||
check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS);
|
||||
|
||||
int p[2];
|
||||
check("pipe", pipe(p) == 0);
|
||||
memcpy(high + 4096, "hello ", 6);
|
||||
memcpy(high + 8192, "world", 5);
|
||||
struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}};
|
||||
ssize_t w = writev(p[1], out, 2);
|
||||
memset(high + 12288, 0, 64);
|
||||
struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}};
|
||||
ssize_t r = w == 11 ? readv(p[0], in, 2) : -1;
|
||||
check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0);
|
||||
|
||||
int wrote = write(p[1], "abcdef", 6) == 6;
|
||||
check("write", wrote);
|
||||
check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0);
|
||||
|
||||
high[30000] = 7;
|
||||
check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0);
|
||||
|
||||
int fd = memfd_create("code", 0);
|
||||
check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0);
|
||||
static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3};
|
||||
check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code);
|
||||
uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
|
||||
uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
|
||||
check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS);
|
||||
int (*fn)(void) = (int (*)(void))low;
|
||||
int before = fn();
|
||||
alias[1] = 2;
|
||||
__atomic_thread_fence(__ATOMIC_SEQ_CST);
|
||||
int after = fn();
|
||||
printf("alias before=%d after=%d\n", before, after);
|
||||
check("smc-through-high-alias", before == 1 && after == 2);
|
||||
|
||||
printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS");
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -21,9 +21,10 @@ library list, before anything is published.
|
||||
trip to Xwayland on the paint thread; with no image, wlserver's position is used as upstream does.
|
||||
- `0101-nested-wayland-cursor-routing.patch` - this app: `gamescope_cursor_composite=2` lets the
|
||||
nested Wayland session paint its cursor in the output using the real X pointer position; client
|
||||
cursor surfaces are cleared to prevent a duplicate at the host pointer, while Gamescope's original
|
||||
default host-cursor fallback is preserved when its no-keyboard-focus policy selects it. Empty
|
||||
client cursor images and Gamescope's hidden flag still suppress the painted cursor.
|
||||
cursor surfaces are cleared to prevent a duplicate at the host pointer, and so is Gamescope's
|
||||
default host-cursor fallback, which would otherwise show a second arrow until Gamescope gets
|
||||
keyboard focus. Empty client cursor images and Gamescope's hidden flag still suppress the
|
||||
painted cursor.
|
||||
- `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's
|
||||
pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds
|
||||
`wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` /
|
||||
@@ -444,3 +445,76 @@ starts there as before, but no motion is sent for it. The fake pointer position
|
||||
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
|
||||
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
|
||||
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
|
||||
|
||||
## 0143 wlserver: only the first finger drives the emulated mouse
|
||||
|
||||
In the Hover, Left, Right, Middle and Trackpad touch click modes every finger warped the X pointer and any finger lifting
|
||||
released the click. With a second finger down the pointer jumped between both fingers on every frame while the button
|
||||
stayed held, so a dragged item followed whichever finger moved last, and lifting the second finger dropped it under the
|
||||
first. The first finger of a gesture now owns the emulated mouse: only it moves the pointer and only its lift releases the
|
||||
click. Fingers that land while it is down are ignored, and so are the others once it lifts, until every finger is up.
|
||||
Touches the click modes never claimed (Passthrough, Disabled, no focused surface) still release a held click when they
|
||||
lift, and the nested pointer (`bAlwaysWarpCursor`) moves the pointer as before. `tools/tests/test_gamescope_touch_click_owner.py`
|
||||
compiles the rule from this patch.
|
||||
|
||||
## 0144 steamcompmgr: motion into the screen edge does not decide the pointer hold
|
||||
|
||||
0133 compares the motion gamescope sends with how the X pointer moves. At the edge of the X screen the pointer cannot move
|
||||
further, so a drawn-cursor game whose pointer sat at an edge while touch or mouse motion pushed outward counted as
|
||||
holding the pointer: the hold stayed on, every such frame restarted the 30 frames needed to release it, and touch drags
|
||||
kept turning into relative motion with no button held. The sent motion is now clamped to what the pointer can reach
|
||||
inside the X screen before it is compared, so motion into an edge counts as no motion. A recentring game is detected as
|
||||
before, since its pointer stays away from the edges. `tools/tests/test_gamescope_pointer_hold_edge.py` compiles the rule
|
||||
from this patch with the 0133 rule.
|
||||
|
||||
## 0145 steamcompmgr: touch-down warps do not decide the pointer hold
|
||||
|
||||
In click mode every touch-down warps the X pointer to the finger. 0133 read that jump as the pointer not following the
|
||||
sent motion, so each new stroke on a drawn-cursor game restarted the 30 following frames needed to release the hold.
|
||||
Short strokes never released it, and taps kept landing at the relative pointer instead of under the finger. wlserver now
|
||||
counts its touch-down warps, and a frame that contains one is left out of the hold decision. Touch drags, mouse motion
|
||||
and mouse warps still count, so a drag on a game that follows the pointer releases the hold and a recentring game is
|
||||
still held. `tools/tests/test_gamescope_pointer_hold_touch_down.py` compiles the rule with the 0133 rule.
|
||||
|
||||
## 0146 rendervulkan: composite only into output images the display has finished scanning out
|
||||
|
||||
The host compositor now releases a zero-copy display buffer as soon as the display latches the next one, and attaches
|
||||
the display's release fence to the buffer's dma-buf instead of waiting for it on the CPU. That wait had held every
|
||||
release back by about one refresh, so a chain of three buffers ran at two thirds of the refresh rate. KGSL Turnip does
|
||||
not wait on fences attached to a dma-buf, so the composite now checks each output image's dma-buf with `poll(POLLOUT)`.
|
||||
It picks the next image that is neither held by the host nor still being scanned out. Only when every free image is
|
||||
still on the display does it wait for one, up to 100 ms. On kernels that cannot attach the fence, the host keeps
|
||||
waiting itself and nothing changes. `tools/gamescope/tests/nested-swapchain.cpp` covers the choice and the busy check.
|
||||
|
||||
## 0147 Wayland backend: a forwarded client buffer goes back to its client only after scanout
|
||||
|
||||
When no composite is needed, gamescope hands a client's own buffer to the host compositor as a plane. The host now
|
||||
releases a buffer as soon as the display latches the next one and leaves its release fence on the buffer's dma-buf.
|
||||
gamescope returned the buffer to the client on that release, and a client whose Vulkan driver does not wait on
|
||||
fences attached to a dma-buf then drew into it while the display was still scanning it out, which showed as black
|
||||
tiles in compressed buffers. A forwarded client buffer now stays held until `poll(POLLOUT)` on its dma-buf reports
|
||||
that the display has finished with it, on a waiter thread so nothing else blocks. A release that arrives after the
|
||||
buffer was shown again is dropped, so the later release decides. A pending wait holds its own reference on the
|
||||
buffer, since that later release can drop the host's reference before the wait ends. Composite output images keep the 0146 path, and a
|
||||
host that waits for the fence itself releases buffers that are already idle, so nothing changes there.
|
||||
|
||||
## 0148 Wayland backend: composite every frame when the host releases buffers before scanout
|
||||
|
||||
With 0147 a forwarded client buffer stays held until the display has finished scanning it out, about one refresh after
|
||||
the host releases it. Steam's web helper cycles three buffers of its own, so forwarding them held the Steam UI at 80 fps
|
||||
on a 120 Hz screen (frames alternately one and two refreshes apart). The first time a forwarded buffer comes back while
|
||||
it is still being scanned out, the backend now composites every frame into its own output images. Those are reused at
|
||||
latch under 0146, and the client's buffers return as soon as the composite has read them: the Steam UI then runs at
|
||||
the full 120 fps. Hosts that release a buffer only after scanout never take this path and keep forwarding.
|
||||
|
||||
## 0998 Wayland backend: verified producer acquire fences for forwarded frames
|
||||
|
||||
When the app opts in and the parent Wayland registry actually advertises
|
||||
`droiddeck_frame_acquire_v1`, Gamescope offers a separate v1 acquire global
|
||||
to nested clients. A validated native sync_file stays with one matching
|
||||
surface attachment and commit generation. Pending fences go through the
|
||||
existing readiness waiter; a failed fence never marks a frame ready.
|
||||
Only a forwarded, unchanged source buffer can carry its completed fence to
|
||||
the parent. Composited output, unsupported clients, older hosts, and X11
|
||||
continue through their existing paths. The host and producer do not need
|
||||
to upgrade simultaneously to retain the existing copy fallback.
|
||||
@@ -46,6 +46,9 @@ cd "$WORK"
|
||||
g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \
|
||||
tools/gamescope/tests/nested-swapchain.cpp -o pkg/test-nested-swapchain
|
||||
pkg/test-nested-swapchain
|
||||
g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \
|
||||
tools/gamescope/tests/producer-acquire.cpp -o pkg/test-producer-acquire
|
||||
env -u GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE pkg/test-producer-acquire
|
||||
rm -rf out && mkdir -p out/usr/local/bin
|
||||
PKG=$(ls pkg/arch/gamescope-*.pkg.tar.* | grep -v -- '-debug-' | head -1)
|
||||
tar -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope
|
||||
@@ -60,6 +63,11 @@ echo "NEEDED: $NEEDED"
|
||||
MISSING=""
|
||||
for lib in $NEEDED; do grep -qx "$lib" tools/gamescope/runtime-sonames.txt || MISSING="$MISSING $lib"; done
|
||||
if [ -n "$MISSING" ]; then echo "ERROR: not in the runtime:$MISSING"; exit 3; fi
|
||||
# The signed APK can distinguish the negotiated release from earlier Gamescope
|
||||
# assets; leave the feature unavailable rather than relying on a filename.
|
||||
LC_ALL=C grep -aFq 'GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE' out/usr/local/bin/gamescope
|
||||
mkdir -p out/usr/local/share/droiddeck
|
||||
printf 'droiddeck-producer-acquire-v1\n' > out/usr/local/share/droiddeck/gamescope-producer-acquire-v1
|
||||
(cd out && tar --use-compress-program='zstd -19' -cf ../gamescope.tzst usr)
|
||||
sha256sum gamescope.tzst | tee gamescope.tzst.sha256
|
||||
ls -l gamescope.tzst out/usr/local/bin/gamescope
|
||||
@@ -74,7 +74,7 @@ index 0000000..d7c21da
|
||||
+
|
||||
+ constexpr bool CursorShouldBeForwardedToHost( int cursorCompositeMode, bool useHostCursorFallback )
|
||||
+ {
|
||||
+ return cursorCompositeMode != 2 || useHostCursorFallback;
|
||||
+ return cursorCompositeMode != 2;
|
||||
+ }
|
||||
+
|
||||
+ constexpr bool CursorImageShouldBePainted( bool imageEmpty, bool cursorHidden )
|
||||
@@ -176,10 +176,10 @@ index 0000000..9c622db
|
||||
+ REQUIRE( CursorShouldBeComposited( 2, false, false, true, false ) );
|
||||
+}
|
||||
+
|
||||
+TEST_CASE("manual composition retains only the no-focus default cursor fallback", "[cursor_routing]")
|
||||
+TEST_CASE("manual composition never forwards a cursor to the host", "[cursor_routing]")
|
||||
+{
|
||||
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, false ) );
|
||||
+ REQUIRE( CursorShouldBeForwardedToHost( 2, true ) );
|
||||
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, true ) );
|
||||
+ REQUIRE( CursorShouldBeForwardedToHost( 1, false ) );
|
||||
+ REQUIRE( CursorShouldBeForwardedToHost( 0, false ) );
|
||||
+}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index 9740875..cb72051 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3283,6 +3283,38 @@ static void apply_touchscreen_orientation(GamescopePanelOrientation orientation,
|
||||
*y = ty;
|
||||
}
|
||||
|
||||
+struct TouchClickState
|
||||
+{
|
||||
+ std::set<int> ids;
|
||||
+ int nOwner = -1;
|
||||
+};
|
||||
+
|
||||
+static TouchClickState s_TouchClick;
|
||||
+
|
||||
+static bool touch_click_claim( TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ if ( state.ids.empty() )
|
||||
+ state.nOwner = nTouchId;
|
||||
+ state.ids.insert( nTouchId );
|
||||
+ return state.nOwner == nTouchId;
|
||||
+}
|
||||
+
|
||||
+static bool touch_click_drives( const TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ return state.nOwner == nTouchId;
|
||||
+}
|
||||
+
|
||||
+static bool touch_click_lift( TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ const bool bTracked = state.ids.erase( nTouchId ) > 0;
|
||||
+ if ( state.nOwner == nTouchId )
|
||||
+ {
|
||||
+ state.nOwner = -1;
|
||||
+ return true;
|
||||
+ }
|
||||
+ return !bTracked && state.nOwner < 0;
|
||||
+}
|
||||
+
|
||||
void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool bAlwaysWarpCursor, gamescope::IBackendConnector* connector )
|
||||
{
|
||||
assert( wlserver_is_lock_held() );
|
||||
@@ -3333,9 +3365,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
|
||||
}
|
||||
else if ( eMode == gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
- wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
|
||||
+ if ( touch_click_drives( s_TouchClick, touch_id ) )
|
||||
+ wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
|
||||
}
|
||||
- else
|
||||
+ else if ( bAlwaysWarpCursor || touch_click_drives( s_TouchClick, touch_id ) )
|
||||
{
|
||||
g_bPendingTouchMovement = true;
|
||||
|
||||
@@ -3389,7 +3422,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
|
||||
{
|
||||
return;
|
||||
}
|
||||
- else
|
||||
+ else if ( touch_click_claim( s_TouchClick, touch_id ) )
|
||||
{
|
||||
g_bPendingTouchMovement = true;
|
||||
|
||||
@@ -3417,7 +3450,8 @@ void wlserver_touchup( int touch_id, uint32_t time )
|
||||
|
||||
// Release whatever the touch pressed even if its surface is gone, or the seat keeps the button down.
|
||||
bool bReleasedAny = false;
|
||||
- for ( int i = 0; i < WLSERVER_BUTTON_COUNT; i++ )
|
||||
+ const bool bClickTouch = touch_click_lift( s_TouchClick, touch_id );
|
||||
+ for ( int i = 0; bClickTouch && i < WLSERVER_BUTTON_COUNT; i++ )
|
||||
{
|
||||
if ( wlserver.button_held[ i ] == true )
|
||||
{
|
||||
@@ -0,0 +1,28 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index e98d320..85af598 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -3245,6 +3245,11 @@ static bool pointer_hold_step( PointerHold &state, bool bConstrained, double flS
|
||||
return state.bHeld;
|
||||
}
|
||||
|
||||
+static double pointer_reach( int nFrom, double flDelta, int nSize )
|
||||
+{
|
||||
+ return std::clamp( nFrom + flDelta, 0.0, double( std::max( nSize - 1, 0 ) ) ) - nFrom;
|
||||
+}
|
||||
+
|
||||
static bool s_bPointerHeld = false;
|
||||
|
||||
static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool bHinted )
|
||||
@@ -3311,7 +3316,10 @@ static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool
|
||||
|
||||
if ( s_bTracking )
|
||||
{
|
||||
- s_bPointerHeld = pointer_hold_step( s_Hold, true, flDX, flDY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
+ const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
|
||||
+ const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
|
||||
+ const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
|
||||
+ s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -0,0 +1,73 @@
|
||||
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
|
||||
--- a/src/wlserver.hpp
|
||||
+++ b/src/wlserver.hpp
|
||||
@@ -173,6 +173,7 @@
|
||||
double flFollowDY = 0.0;
|
||||
double flSentDX = 0.0;
|
||||
double flSentDY = 0.0;
|
||||
+ uint64_t ulTouchDownWarps = 0;
|
||||
|
||||
bool button_held[ WLSERVER_BUTTON_COUNT ];
|
||||
std::set <uint32_t> touch_down_ids;
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3429,6 +3429,7 @@
|
||||
if ( eMode != gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
wlserver_mousewarp( tx, ty, time, false, true );
|
||||
+ wlserver.ulTouchDownWarps++;
|
||||
}
|
||||
|
||||
uint32_t button = TouchClickModeToLinuxButton( eMode );
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -3263,6 +3263,7 @@
|
||||
static bool s_bHinted = false;
|
||||
static const steamcompmgr_win_t *s_pWindow = nullptr;
|
||||
static const struct wlr_pointer_constraint_v1 *s_pConstraint = nullptr;
|
||||
+ static uint64_t s_ulTouchDownWarps = 0;
|
||||
|
||||
wlserver_lock();
|
||||
const double flX = wlserver.mouse_surface_cursorx;
|
||||
@@ -3272,8 +3273,12 @@
|
||||
const struct wlr_pointer_constraint_v1 *pConstraint = wlserver.GetCursorConstraint();
|
||||
wlserver.flSentDX = 0.0;
|
||||
wlserver.flSentDY = 0.0;
|
||||
+ const uint64_t ulTouchDownWarps = wlserver.ulTouchDownWarps;
|
||||
wlserver_unlock();
|
||||
|
||||
+ const bool bTouchDown = ulTouchDownWarps != s_ulTouchDownWarps;
|
||||
+ s_ulTouchDownWarps = ulTouchDownWarps;
|
||||
+
|
||||
if ( !bConstrained || !pFocus->cursor )
|
||||
{
|
||||
s_bTracking = false;
|
||||
@@ -3314,19 +3319,19 @@
|
||||
int nRootY = 0;
|
||||
pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
|
||||
|
||||
- if ( s_bTracking )
|
||||
+ if ( !s_bTracking )
|
||||
+ {
|
||||
+ s_Hold = PointerHold{};
|
||||
+ s_Hold.bHeld = bHinted;
|
||||
+ s_bPointerHeld = bHinted;
|
||||
+ }
|
||||
+ else if ( !bTouchDown )
|
||||
{
|
||||
const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
|
||||
const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
|
||||
const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
|
||||
s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
}
|
||||
- else
|
||||
- {
|
||||
- s_Hold = PointerHold{};
|
||||
- s_Hold.bHeld = bHinted;
|
||||
- s_bPointerHeld = bHinted;
|
||||
- }
|
||||
|
||||
s_bTracking = true;
|
||||
s_flSeatX = flX;
|
||||
@@ -0,0 +1,106 @@
|
||||
diff --git a/src/output_image_pick.hpp b/src/output_image_pick.hpp
|
||||
new file mode 100644
|
||||
index 0000000..193d9de
|
||||
--- /dev/null
|
||||
+++ b/src/output_image_pick.hpp
|
||||
@@ -0,0 +1,50 @@
|
||||
+#pragma once
|
||||
+#include <cstdint>
|
||||
+#include <poll.h>
|
||||
+
|
||||
+namespace gamescope
|
||||
+{
|
||||
+struct OutputImagePick
|
||||
+{
|
||||
+ uint32_t image;
|
||||
+ bool scanoutPending;
|
||||
+};
|
||||
+
|
||||
+template <typename Held, typename Busy>
|
||||
+inline OutputImagePick PickOutputImage( uint32_t count, uint32_t first, uint32_t last, uint32_t deferred,
|
||||
+ Held &&held, Busy &&busy )
|
||||
+{
|
||||
+ for ( int pass = 0; pass < 2; pass++ )
|
||||
+ {
|
||||
+ for ( uint32_t i = 0; i < count; i++ )
|
||||
+ {
|
||||
+ const uint32_t image = ( first + i ) % count;
|
||||
+ if ( count > 3 && ( image == last || image == deferred ) )
|
||||
+ continue;
|
||||
+ if ( held( image ) )
|
||||
+ continue;
|
||||
+ const bool pending = busy( image );
|
||||
+ if ( pass == 0 && pending )
|
||||
+ continue;
|
||||
+ return { image, pending };
|
||||
+ }
|
||||
+ }
|
||||
+ return { first, busy( first ) };
|
||||
+}
|
||||
+
|
||||
+inline bool DmabufScanoutPending( int fd )
|
||||
+{
|
||||
+ if ( fd < 0 )
|
||||
+ return false;
|
||||
+ pollfd p = { .fd = fd, .events = POLLOUT, .revents = 0 };
|
||||
+ return poll( &p, 1, 0 ) == 0;
|
||||
+}
|
||||
+
|
||||
+inline void WaitDmabufScanout( int fd, int timeoutMs )
|
||||
+{
|
||||
+ if ( fd < 0 )
|
||||
+ return;
|
||||
+ pollfd p = { .fd = fd, .events = POLLOUT, .revents = 0 };
|
||||
+ poll( &p, 1, timeoutMs );
|
||||
+}
|
||||
+}
|
||||
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
|
||||
index 1d3a80c..3668a10 100644
|
||||
--- a/src/rendervulkan.cpp
|
||||
+++ b/src/rendervulkan.cpp
|
||||
@@ -37,6 +37,7 @@
|
||||
#include "steamcompmgr.hpp"
|
||||
#include "log.hpp"
|
||||
#include "Utils/Process.h"
|
||||
+#include "output_image_pick.hpp"
|
||||
|
||||
#include "cs_composite_blit.h"
|
||||
#include "cs_composite_blur.h"
|
||||
@@ -4297,18 +4298,29 @@ static bool vulkan_output_image_held( uint32_t nImage )
|
||||
return false;
|
||||
}
|
||||
|
||||
+static bool vulkan_output_image_scanout_pending( uint32_t nImage )
|
||||
+{
|
||||
+ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } )
|
||||
+ {
|
||||
+ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && gamescope::DmabufScanoutPending( pImage->dmabuf().fd[0] ) )
|
||||
+ return true;
|
||||
+ }
|
||||
+ return false;
|
||||
+}
|
||||
+
|
||||
static uint32_t vulkan_free_output_image( uint32_t nFirst )
|
||||
{
|
||||
- const uint32_t uCount = g_output.outputImages.size();
|
||||
- for ( uint32_t i = 0; i < uCount; i++ )
|
||||
+ const gamescope::OutputImagePick pick = gamescope::PickOutputImage( g_output.outputImages.size(), nFirst,
|
||||
+ g_output.nLastOutImage, g_output.nDeferredOutImage, vulkan_output_image_held, vulkan_output_image_scanout_pending );
|
||||
+ if ( pick.scanoutPending )
|
||||
{
|
||||
- const uint32_t nImage = ( nFirst + i ) % uCount;
|
||||
- if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) )
|
||||
- continue;
|
||||
- if ( !vulkan_output_image_held( nImage ) )
|
||||
- return nImage;
|
||||
+ for ( const auto &pImage : { g_output.outputImages[ pick.image ], g_output.outputImagesPartialOverlay[ pick.image ] } )
|
||||
+ {
|
||||
+ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr )
|
||||
+ gamescope::WaitDmabufScanout( pImage->dmabuf().fd[0], 100 );
|
||||
+ }
|
||||
}
|
||||
- return nFirst;
|
||||
+ return pick.image;
|
||||
}
|
||||
|
||||
std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc<CVulkanTexture> pPipewireTexture, bool partial, gamescope::Rc<CVulkanTexture> pOutputOverride, bool increment, std::unique_ptr<CVulkanCmdBuffer> pInCommandBuffer )
|
||||
@@ -0,0 +1,355 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index 12f0f50..d9db2e6 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -3,24 +3,28 @@
|
||||
#include "wlserver.hpp"
|
||||
#include "vblankmanager.hpp"
|
||||
#include "steamcompmgr.hpp"
|
||||
#include "edid.h"
|
||||
#include "Utils/Defer.h"
|
||||
#include "Utils/Algorithm.h"
|
||||
#include "convar.h"
|
||||
#include "refresh_rate.h"
|
||||
#include "waitable.h"
|
||||
#include "Utils/TempFiles.h"
|
||||
#include "Utils/CursorRouting.h"
|
||||
#include "Utils/WaylandScaling.h"
|
||||
+#include "output_image_pick.hpp"
|
||||
+
|
||||
+#include <fcntl.h>
|
||||
+#include <mutex>
|
||||
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <csignal>
|
||||
#include <sys/mman.h>
|
||||
#include <poll.h>
|
||||
#include <linux/input-event-codes.h>
|
||||
#include <xkbcommon/xkbcommon.h>
|
||||
#include <libdecor.h>
|
||||
|
||||
#include "wlr_begin.hpp"
|
||||
@@ -485,44 +489,86 @@ namespace gamescope
|
||||
|
||||
// One backing plane plus every layer steamcompmgr can hand us.
|
||||
CWaylandPlane m_Planes[k_nMaxLayers + 1];
|
||||
bool m_bVisible = true;
|
||||
std::atomic<bool> m_bDesiredFullscreenState = { false };
|
||||
|
||||
bool m_bHostCompositorIsCurrentlyVRR = false;
|
||||
};
|
||||
|
||||
class CWaylandFb final : public CBaseBackendFb
|
||||
{
|
||||
public:
|
||||
- CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer );
|
||||
+ CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd = -1 );
|
||||
~CWaylandFb();
|
||||
|
||||
void OnCompositorAcquire();
|
||||
void OnCompositorRelease();
|
||||
+ void OnScanoutDone( uint64_t ulAcquireSerial );
|
||||
|
||||
wl_buffer *GetHostBuffer() const { return m_pHostBuffer; }
|
||||
wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; }
|
||||
|
||||
bool HeldByHost() const override { return m_bCompositorAcquired; }
|
||||
|
||||
void Wayland_Buffer_Release( wl_buffer *pBuffer );
|
||||
static const wl_buffer_listener s_BufferListener;
|
||||
|
||||
private:
|
||||
CWaylandBackend *m_pBackend = nullptr;
|
||||
wl_buffer *m_pHostBuffer = nullptr;
|
||||
wlr_buffer *m_pClientBuffer = nullptr;
|
||||
+ int m_nDmabufFd = -1;
|
||||
+ std::mutex m_AcquireMutex;
|
||||
+ uint64_t m_ulAcquireSerial = 0;
|
||||
bool m_bCompositorAcquired = false;
|
||||
};
|
||||
+
|
||||
+ class CWaylandScanoutRelease final : public IWaitable
|
||||
+ {
|
||||
+ public:
|
||||
+ CWaylandScanoutRelease( CWaylandFb *pFb, int nFd, uint64_t ulAcquireSerial )
|
||||
+ : m_pFb{ pFb }
|
||||
+ , m_nFd{ nFd }
|
||||
+ , m_ulAcquireSerial{ ulAcquireSerial }
|
||||
+ {
|
||||
+ // A later acquire and release can drop the compositor's reference before this wait ends.
|
||||
+ m_pFb->IncRef();
|
||||
+ }
|
||||
+
|
||||
+ ~CWaylandScanoutRelease() { m_pFb->DecRef(); }
|
||||
+
|
||||
+ int GetFD() override { return m_nFd; }
|
||||
+ void OnPollOut() override { Finish(); }
|
||||
+ void OnPollHangUp() override { Finish(); }
|
||||
+
|
||||
+ static CAsyncWaiter<> &Waiter()
|
||||
+ {
|
||||
+ static CAsyncWaiter<> s_Waiter{ "gamescope-scanout" };
|
||||
+ return s_Waiter;
|
||||
+ }
|
||||
+
|
||||
+ private:
|
||||
+ void Finish()
|
||||
+ {
|
||||
+ Waiter().RemoveWaitable( this );
|
||||
+ m_pFb->OnScanoutDone( m_ulAcquireSerial );
|
||||
+ close( m_nFd );
|
||||
+ delete this;
|
||||
+ }
|
||||
+
|
||||
+ CWaylandFb *m_pFb;
|
||||
+ int m_nFd;
|
||||
+ uint64_t m_ulAcquireSerial;
|
||||
+ };
|
||||
const wl_buffer_listener CWaylandFb::s_BufferListener =
|
||||
{
|
||||
.release = WAYLAND_USERDATA_TO_THIS( CWaylandFb, Wayland_Buffer_Release ),
|
||||
};
|
||||
|
||||
class CWaylandInputThread
|
||||
{
|
||||
public:
|
||||
CWaylandInputThread();
|
||||
~CWaylandInputThread();
|
||||
|
||||
bool Init( CWaylandBackend *pBackend );
|
||||
@@ -969,73 +1015,108 @@ namespace gamescope
|
||||
.action = WAYLAND_NULL(),
|
||||
};
|
||||
const zwp_primary_selection_source_v1_listener CWaylandBackend::s_PrimarySelectionSourceListener =
|
||||
{
|
||||
.send = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Send ),
|
||||
.cancelled = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Cancelled ),
|
||||
};
|
||||
|
||||
//////////////////
|
||||
// CWaylandFb
|
||||
//////////////////
|
||||
|
||||
- CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer )
|
||||
+ CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd )
|
||||
: CBaseBackendFb()
|
||||
, m_pBackend { pBackend }
|
||||
, m_pHostBuffer { pHostBuffer }
|
||||
+ , m_nDmabufFd { nDmabufFd }
|
||||
{
|
||||
wl_buffer_add_listener( pHostBuffer, &s_BufferListener, this );
|
||||
}
|
||||
|
||||
CWaylandFb::~CWaylandFb()
|
||||
{
|
||||
// I own the pHostBuffer.
|
||||
wl_buffer_destroy( m_pHostBuffer );
|
||||
m_pHostBuffer = nullptr;
|
||||
+ if ( m_nDmabufFd >= 0 )
|
||||
+ close( m_nDmabufFd );
|
||||
}
|
||||
|
||||
void CWaylandFb::OnCompositorAcquire()
|
||||
{
|
||||
- // If the compositor has acquired us, track that
|
||||
- // and increment the ref count.
|
||||
- if ( !m_bCompositorAcquired )
|
||||
+ bool bTakeRef = false;
|
||||
{
|
||||
+ std::scoped_lock lock( m_AcquireMutex );
|
||||
+ m_ulAcquireSerial++;
|
||||
+ bTakeRef = !m_bCompositorAcquired;
|
||||
m_bCompositorAcquired = true;
|
||||
- IncRef();
|
||||
}
|
||||
+
|
||||
+ if ( bTakeRef )
|
||||
+ IncRef();
|
||||
}
|
||||
|
||||
void CWaylandFb::OnCompositorRelease()
|
||||
{
|
||||
- // Compositor has released us, decrement rc.
|
||||
- //assert( m_bCompositorAcquired );
|
||||
+ uint64_t ulSerial;
|
||||
+ {
|
||||
+ std::scoped_lock lock( m_AcquireMutex );
|
||||
+ ulSerial = m_ulAcquireSerial;
|
||||
+ }
|
||||
+ OnScanoutDone( ulSerial );
|
||||
+ }
|
||||
|
||||
- if ( m_bCompositorAcquired )
|
||||
+ void CWaylandFb::OnScanoutDone( uint64_t ulAcquireSerial )
|
||||
+ {
|
||||
+ bool bDropRef = false;
|
||||
{
|
||||
+ std::scoped_lock lock( m_AcquireMutex );
|
||||
+ if ( ulAcquireSerial != m_ulAcquireSerial )
|
||||
+ return;
|
||||
+ bDropRef = m_bCompositorAcquired;
|
||||
m_bCompositorAcquired = false;
|
||||
- DecRef();
|
||||
}
|
||||
+
|
||||
+ if ( bDropRef )
|
||||
+ DecRef();
|
||||
else
|
||||
- {
|
||||
xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." );
|
||||
- }
|
||||
}
|
||||
|
||||
void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer )
|
||||
{
|
||||
assert( m_pHostBuffer );
|
||||
assert( m_pHostBuffer == pBuffer );
|
||||
|
||||
xdg_log.debugf( "buffer_release: %p", pBuffer );
|
||||
|
||||
+ if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) )
|
||||
+ {
|
||||
+ int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 );
|
||||
+ if ( nFd >= 0 )
|
||||
+ {
|
||||
+ uint64_t ulSerial;
|
||||
+ {
|
||||
+ std::scoped_lock lock( m_AcquireMutex );
|
||||
+ ulSerial = m_ulAcquireSerial;
|
||||
+ }
|
||||
+ auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial );
|
||||
+ if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) )
|
||||
+ return;
|
||||
+ delete pWait;
|
||||
+ close( nFd );
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
OnCompositorRelease();
|
||||
}
|
||||
|
||||
//////////////////
|
||||
// CWaylandConnector
|
||||
//////////////////
|
||||
|
||||
CWaylandConnector::CWaylandConnector( CWaylandBackend *pBackend, uint64_t ulVirtualConnectorKey )
|
||||
: CBaseBackendConnector{ ulVirtualConnectorKey }
|
||||
, m_pBackend( pBackend )
|
||||
, m_Planes{ this, this, this, this, this, this, this, this, this }
|
||||
{
|
||||
@@ -2349,25 +2430,26 @@ namespace gamescope
|
||||
pDmaBuf->format,
|
||||
0u );
|
||||
|
||||
if ( !pImportedBuffer )
|
||||
{
|
||||
xdg_log.errorf( "Failed to import dmabuf" );
|
||||
zwp_linux_buffer_params_v1_destroy( pBufferParams );
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
zwp_linux_buffer_params_v1_destroy( pBufferParams );
|
||||
|
||||
- return new CWaylandFb{ this, pImportedBuffer };
|
||||
+ int nDmabufFd = pDmaBuf->n_planes > 0 ? fcntl( pDmaBuf->fd[0], F_DUPFD_CLOEXEC, 0 ) : -1;
|
||||
+ return new CWaylandFb{ this, pImportedBuffer, nDmabufFd };
|
||||
}
|
||||
|
||||
bool CWaylandBackend::UsesModifiers() const
|
||||
{
|
||||
if ( !cv_wayland_use_modifiers )
|
||||
return false;
|
||||
|
||||
return m_bCanUseModifiers;
|
||||
}
|
||||
std::span<const uint64_t> CWaylandBackend::GetSupportedModifiers( uint32_t uDrmFormat ) const
|
||||
{
|
||||
auto iter = m_FormatModifiers.find( uDrmFormat );
|
||||
diff --git a/src/backend.cpp b/src/backend.cpp
|
||||
index cc91853..ec59c8b 100644
|
||||
--- a/src/backend.cpp
|
||||
+++ b/src/backend.cpp
|
||||
@@ -109,41 +109,47 @@ namespace gamescope
|
||||
wlserver_unlock();
|
||||
}
|
||||
|
||||
// Potentially release now!
|
||||
DecRefPrivate();
|
||||
}
|
||||
|
||||
return uRefCount;
|
||||
}
|
||||
|
||||
void CBaseBackendFb::SetBuffer( wlr_buffer *pClientBuffer )
|
||||
{
|
||||
+ if ( pClientBuffer )
|
||||
+ m_bShowsClientBuffer = true;
|
||||
+
|
||||
if ( m_pClientBuffer == pClientBuffer )
|
||||
return;
|
||||
|
||||
assert( m_pClientBuffer == nullptr );
|
||||
m_pClientBuffer = pClientBuffer;
|
||||
if ( GetRefCount() )
|
||||
{
|
||||
wlserver_lock();
|
||||
wlr_buffer_lock( m_pClientBuffer );
|
||||
wlserver_unlock( false );
|
||||
}
|
||||
|
||||
m_pReleasePoint = nullptr;
|
||||
}
|
||||
|
||||
void CBaseBackendFb::SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint )
|
||||
{
|
||||
+ if ( pReleasePoint )
|
||||
+ m_bShowsClientBuffer = true;
|
||||
+
|
||||
if ( m_pReleasePoint == pReleasePoint )
|
||||
return;
|
||||
|
||||
m_pReleasePoint = pReleasePoint;
|
||||
|
||||
if ( m_pClientBuffer && GetRefCount() )
|
||||
{
|
||||
wlserver_lock();
|
||||
wlr_buffer_unlock( m_pClientBuffer );
|
||||
wlserver_unlock();
|
||||
m_pClientBuffer = nullptr;
|
||||
}
|
||||
diff --git a/src/backend.h b/src/backend.h
|
||||
index 30b42ca..9a27711 100644
|
||||
--- a/src/backend.h
|
||||
+++ b/src/backend.h
|
||||
@@ -303,26 +303,29 @@ namespace gamescope
|
||||
public:
|
||||
CBaseBackendFb();
|
||||
virtual ~CBaseBackendFb();
|
||||
|
||||
uint32_t IncRef() override;
|
||||
uint32_t DecRef() override;
|
||||
|
||||
void SetBuffer( wlr_buffer *pClientBuffer ) override;
|
||||
void SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint ) override;
|
||||
|
||||
virtual IBackendFb *EnsureImported() override { return this; };
|
||||
|
||||
+ bool ShowsClientBuffer() const { return m_bShowsClientBuffer; }
|
||||
+
|
||||
private:
|
||||
wlr_buffer *m_pClientBuffer = nullptr;
|
||||
+ std::atomic<bool> m_bShowsClientBuffer = { false };
|
||||
std::shared_ptr<CReleaseTimelinePoint> m_pReleasePoint;
|
||||
};
|
||||
|
||||
class IBackend
|
||||
{
|
||||
public:
|
||||
virtual ~IBackend() {}
|
||||
|
||||
virtual bool Init() = 0;
|
||||
virtual bool PostInit() = 0;
|
||||
virtual std::span<const char *const> GetInstanceExtensions() const = 0;
|
||||
virtual std::span<const char *const> GetDeviceExtensions( VkPhysicalDevice pVkPhysicalDevice ) const = 0;
|
||||
@@ -0,0 +1,116 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index d9db2e6..5c4cd86 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -804,24 +804,31 @@ namespace gamescope
|
||||
{
|
||||
auto iter = m_pOutputs.find( pOutput );
|
||||
if ( iter == m_pOutputs.end() )
|
||||
return nullptr;
|
||||
|
||||
return &iter->second;
|
||||
}
|
||||
|
||||
wl_region *GetEmptyRegion() const { return m_pEmptyRegion; }
|
||||
wl_region *GetFullRegion() const { return m_pFullRegion; }
|
||||
CWaylandFb *GetBlackFb() const { return m_BlackFb.get(); }
|
||||
|
||||
+ bool HostReleasesBeforeScanout() const { return m_bHostReleasesBeforeScanout; }
|
||||
+ void OnHostReleasedBeforeScanout()
|
||||
+ {
|
||||
+ if ( !m_bHostReleasesBeforeScanout.exchange( true ) )
|
||||
+ xdg_log.infof( "Host releases buffers before scanout ends: compositing every frame into our own images" );
|
||||
+ }
|
||||
+
|
||||
void OnConnectorDestroyed( CWaylandConnector *pConnector )
|
||||
{
|
||||
m_pFocusConnector.compare_exchange_strong( pConnector, nullptr );
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void Wayland_Registry_Global( wl_registry *pRegistry, uint32_t uName, const char *pInterface, uint32_t uVersion );
|
||||
static const wl_registry_listener s_RegistryListener;
|
||||
|
||||
void Wayland_Modifier( zwp_linux_dmabuf_v1 *pDmabuf, uint32_t uFormat, uint32_t uModifierHi, uint32_t uModifierLo );
|
||||
|
||||
@@ -871,24 +878,25 @@ namespace gamescope
|
||||
|
||||
wl_display *m_pDisplay = nullptr;
|
||||
wl_shm *m_pShm = nullptr;
|
||||
wl_compositor *m_pCompositor = nullptr;
|
||||
wp_single_pixel_buffer_manager_v1 *m_pSinglePixelBufferManager = nullptr;
|
||||
wl_subcompositor *m_pSubcompositor = nullptr;
|
||||
zwp_linux_dmabuf_v1 *m_pLinuxDmabuf = nullptr;
|
||||
xdg_wm_base *m_pXdgWmBase = nullptr;
|
||||
wp_viewporter *m_pViewporter = nullptr;
|
||||
wl_region *m_pEmptyRegion = nullptr;
|
||||
wl_region *m_pFullRegion = nullptr;
|
||||
Rc<CWaylandFb> m_BlackFb;
|
||||
+ std::atomic<bool> m_bHostReleasesBeforeScanout = { false };
|
||||
OwningRc<CWaylandFb> m_pOwnedBlackFb;
|
||||
OwningRc<CVulkanTexture> m_pBlackTexture;
|
||||
wp_presentation *m_pPresentation = nullptr;
|
||||
droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
|
||||
std::array<uint32_t, 16> m_HostRefreshRates{};
|
||||
std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
|
||||
std::vector<uint32_t> m_PendingHostRefreshRates;
|
||||
int m_nSentHostRefresh = 0;
|
||||
int m_nSentHostFrameRate = 0;
|
||||
frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr;
|
||||
wp_color_manager_v1 *m_pWPColorManager = nullptr;
|
||||
wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{};
|
||||
@@ -1083,24 +1091,25 @@ namespace gamescope
|
||||
xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." );
|
||||
}
|
||||
|
||||
void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer )
|
||||
{
|
||||
assert( m_pHostBuffer );
|
||||
assert( m_pHostBuffer == pBuffer );
|
||||
|
||||
xdg_log.debugf( "buffer_release: %p", pBuffer );
|
||||
|
||||
if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) )
|
||||
{
|
||||
+ m_pBackend->OnHostReleasedBeforeScanout();
|
||||
int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 );
|
||||
if ( nFd >= 0 )
|
||||
{
|
||||
uint64_t ulSerial;
|
||||
{
|
||||
std::scoped_lock lock( m_AcquireMutex );
|
||||
ulSerial = m_ulAcquireSerial;
|
||||
}
|
||||
auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial );
|
||||
if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) )
|
||||
return;
|
||||
delete pWait;
|
||||
@@ -1194,24 +1203,27 @@ namespace gamescope
|
||||
plane.Present( nullptr );
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Dedupe some of this composite check code between us and drm.cpp
|
||||
bool bLayer0ScreenSize = close_enough(pFrameInfo->layers.get( 0 ).scale.x, 1.0f) && close_enough(pFrameInfo->layers.get( 0 ).scale.y, 1.0f);
|
||||
|
||||
GamescopeUpscaleFilter eLayer0Filter = pFrameInfo->layers.get( 0 ).filter;
|
||||
bool bNeedsCompositeFromFilter = ( eLayer0Filter == GamescopeUpscaleFilter::NEAREST ||
|
||||
eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize;
|
||||
|
||||
bNeedsFullComposite |= cv_composite_force;
|
||||
+ // A forwarded buffer would stay out of its client's hands until scanout ends, which caps a
|
||||
+ // three-image client at two thirds of the refresh rate. Our own output images are reused at latch.
|
||||
+ bNeedsFullComposite |= m_pBackend->HostReleasesBeforeScanout();
|
||||
bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes;
|
||||
bNeedsFullComposite |= pFrameInfo->useFSRLayer0;
|
||||
bNeedsFullComposite |= pFrameInfo->useNISLayer0;
|
||||
bNeedsFullComposite |= pFrameInfo->useSGSRLayer0;
|
||||
bNeedsFullComposite |= pFrameInfo->blurLayer0;
|
||||
bNeedsFullComposite |= bNeedsCompositeFromFilter;
|
||||
bNeedsFullComposite |= g_bColorSliderInUse;
|
||||
bNeedsFullComposite |= pFrameInfo->bFadingOut;
|
||||
bNeedsFullComposite |= !g_reshade_effect.empty();
|
||||
|
||||
if ( g_bOutputHDREnabled )
|
||||
bNeedsFullComposite |= g_bHDRItmEnable;
|
||||
@@ -0,0 +1,693 @@
|
||||
diff --git a/protocol/droiddeck-frame-acquire-v1.xml b/protocol/droiddeck-frame-acquire-v1.xml
|
||||
new file mode 100644
|
||||
index 0000000..f056b6e
|
||||
--- /dev/null
|
||||
+++ b/protocol/droiddeck-frame-acquire-v1.xml
|
||||
@@ -0,0 +1,43 @@
|
||||
+<?xml version="1.0" encoding="UTF-8"?>
|
||||
+<protocol name="droiddeck_frame_acquire_v1">
|
||||
+ <interface name="droiddeck_frame_acquire_v1" version="1">
|
||||
+ <description summary="DroidDeck producer write completion for a single Wayland attachment">
|
||||
+ Optional explicit acquire sideband independent of DRM syncobj and buffer
|
||||
+ allocation. Binding does not opt the client out of ordinary wl_buffer
|
||||
+ release or existing synchronization protocols. The server advertises it
|
||||
+ only when it implements all semantics for the selected display path.
|
||||
+ </description>
|
||||
+ <request name="destroy" type="destructor"/>
|
||||
+ <enum name="error">
|
||||
+ <entry name="invalid_attachment" value="0" summary="not the same client's pending DMA-BUF attachment"/>
|
||||
+ <entry name="duplicate_fence" value="1" summary="that attachment already has an acquire fence"/>
|
||||
+ <entry name="invalid_fence" value="2" summary="not a real successfully signaled Linux sync_file"/>
|
||||
+ </enum>
|
||||
+ <request name="set_acquire_fence">
|
||||
+ <description summary="set a one-shot kernel sync_file for the pending attachment">
|
||||
+ After wl_surface.attach of a non-null buffer, and before its next
|
||||
+ wl_surface.commit, send the producer's final writer fence for that
|
||||
+ exact attachment. This outer probe requires that fence to have already
|
||||
+ successfully signaled. The fence must be a real Linux sync_file, not a
|
||||
+ dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received
|
||||
+ descriptor once for that attachment; the caller closes its local FD
|
||||
+ after marshalling.
|
||||
+
|
||||
+ The receiver validates the matching pending surface and buffer and
|
||||
+ validates the descriptor. A duplicate, invalid, pending or mismatched
|
||||
+ request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same
|
||||
+ wl_buffer), detach, surface/resource loss or supersession makes the
|
||||
+ old proof inapplicable. Metadata-only commits may amend receiver-side
|
||||
+ still-pending state but cannot introduce or re-use a fence themselves.
|
||||
+ If no request was made, the receiver keeps its established safe path.
|
||||
+ If a valid fence has been accepted and later the layer is ineligible,
|
||||
+ the buffer must not be copied/read before that fence is satisfied or
|
||||
+ imported as the source dependency. Transport never implies readiness
|
||||
+ on missed deadlines and never changes release/retirement requirements.
|
||||
+ </description>
|
||||
+ <arg name="surface" type="object" interface="wl_surface"/>
|
||||
+ <arg name="buffer" type="object" interface="wl_buffer"/>
|
||||
+ <arg name="fence" type="fd" summary="producer's native acquire sync_file"/>
|
||||
+ </request>
|
||||
+ </interface>
|
||||
+</protocol>
|
||||
diff --git a/protocol/droiddeck-game-frame-acquire-v1.xml b/protocol/droiddeck-game-frame-acquire-v1.xml
|
||||
new file mode 100644
|
||||
index 0000000..1b8c2a5
|
||||
--- /dev/null
|
||||
+++ b/protocol/droiddeck-game-frame-acquire-v1.xml
|
||||
@@ -0,0 +1,17 @@
|
||||
+<?xml version="1.0" encoding="UTF-8"?>
|
||||
+<protocol name="droiddeck_game_frame_acquire_v1">
|
||||
+ <interface name="droiddeck_game_frame_acquire_v1" version="1">
|
||||
+ <description summary="guest producer acquire fence">
|
||||
+ Immediately after wl_surface.attach and before the associated nonempty
|
||||
+ commit, submit the successful or pending Linux sync_file representing the
|
||||
+ final writer of that exact attachment. The caller closes its descriptor
|
||||
+ after marshalling. This does not change wl_buffer release semantics.
|
||||
+ Without a genuine positive descriptor, omit the sideband.
|
||||
+ </description>
|
||||
+ <request name="set_acquire_fence">
|
||||
+ <arg name="surface" type="object" interface="wl_surface"/>
|
||||
+ <arg name="buffer" type="object" interface="wl_buffer"/>
|
||||
+ <arg name="fence" type="fd"/>
|
||||
+ </request>
|
||||
+ </interface>
|
||||
+</protocol>
|
||||
diff --git a/protocol/meson.build b/protocol/meson.build
|
||||
index 71fe31b..1e56fbf 100644
|
||||
--- a/protocol/meson.build
|
||||
+++ b/protocol/meson.build
|
||||
@@ -44,6 +44,8 @@ protocols = [
|
||||
'gamescope-action-binding.xml',
|
||||
|
||||
'droiddeck-refresh-v1.xml',
|
||||
+ 'droiddeck-game-frame-acquire-v1.xml',
|
||||
+ 'droiddeck-frame-acquire-v1.xml',
|
||||
|
||||
# wlroots protocols
|
||||
'wlr-layer-shell-unstable-v1.xml',
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index 45e32f3..e5cb845 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -43,6 +43,7 @@
|
||||
#include <fractional-scale-v1-client-protocol.h>
|
||||
#include <xdg-toplevel-icon-v1-client-protocol.h>
|
||||
#include <droiddeck-refresh-v1-client-protocol.h>
|
||||
+#include <droiddeck-frame-acquire-v1-client-protocol.h>
|
||||
#include "wlr_end.hpp"
|
||||
|
||||
#include "drm_include.h"
|
||||
@@ -143,6 +144,7 @@ namespace gamescope
|
||||
struct WaylandPlaneState
|
||||
{
|
||||
wl_buffer *pBuffer;
|
||||
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
|
||||
int32_t nDestX;
|
||||
int32_t nDestY;
|
||||
double flSrcX;
|
||||
@@ -755,6 +757,8 @@ namespace gamescope
|
||||
virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override;
|
||||
|
||||
std::span<const uint32_t> GetHostRefreshRates() const;
|
||||
+ droiddeck_frame_acquire_v1 *GetHostAcquire() const { return m_pHostAcquire; }
|
||||
+ bool SupportsDroidDeckProducerAcquire() const override { return m_pHostAcquire != nullptr; }
|
||||
void SyncHostRefreshTarget();
|
||||
virtual bool SupportsExplicitSync() const override;
|
||||
|
||||
@@ -893,6 +897,7 @@ namespace gamescope
|
||||
OwningRc<CVulkanTexture> m_pBlackTexture;
|
||||
wp_presentation *m_pPresentation = nullptr;
|
||||
droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
|
||||
+ droiddeck_frame_acquire_v1 *m_pHostAcquire = nullptr;
|
||||
std::array<uint32_t, 16> m_HostRefreshRates{};
|
||||
std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
|
||||
std::vector<uint32_t> m_PendingHostRefreshRates;
|
||||
@@ -1613,6 +1618,8 @@ namespace gamescope
|
||||
{
|
||||
std::unique_lock lock( m_PlaneStateLock );
|
||||
m_oCurrentPlaneState = oState;
|
||||
+ if (m_oCurrentPlaneState)
|
||||
+ m_oCurrentPlaneState->pProducerFence.reset();
|
||||
}
|
||||
|
||||
if ( oState )
|
||||
@@ -1760,6 +1767,12 @@ namespace gamescope
|
||||
// The x/y here does nothing? Why? What is it for...
|
||||
// Use the subsurface set_position thing instead.
|
||||
wl_surface_attach( m_pSurface, oState->pBuffer, 0, 0 );
|
||||
+ if ( auto *manager = m_pBackend->GetHostAcquire(); manager && oState->pProducerFence )
|
||||
+ {
|
||||
+ const int fd = oState->pProducerFence->SignaledFd();
|
||||
+ if (fd >= 0)
|
||||
+ droiddeck_frame_acquire_v1_set_acquire_fence(manager, m_pSurface, oState->pBuffer, fd);
|
||||
+ }
|
||||
wl_surface_damage( m_pSurface, 0, 0, INT32_MAX, INT32_MAX );
|
||||
wl_surface_set_opaque_region( m_pSurface, oState->bOpaque ? m_pBackend->GetFullRegion() : nullptr );
|
||||
wl_surface_set_buffer_scale( m_pSurface, 1 );
|
||||
@@ -1815,6 +1828,7 @@ namespace gamescope
|
||||
ClipPlane( WaylandPlaneState
|
||||
{
|
||||
.pBuffer = pBuffer,
|
||||
+ .pProducerFence = pLayer->pProducerFence,
|
||||
.nDestX = int32_t( -pLayer->offset.x ),
|
||||
.nDestY = int32_t( -pLayer->offset.y ),
|
||||
.flSrcX = 0.0,
|
||||
@@ -2812,6 +2826,12 @@ namespace gamescope
|
||||
wl_output_add_listener( pOutput , &s_OutputListener, this );
|
||||
m_pOutputs.emplace( std::make_pair<struct wl_output *, WaylandOutputInfo>( std::move( pOutput ), WaylandOutputInfo{} ) );
|
||||
}
|
||||
+ else if ( droiddeck::ProducerAcquireEnabled() &&
|
||||
+ uVersion >= 1 && !strcmp( pInterface, droiddeck_frame_acquire_v1_interface.name ) && !m_pHostAcquire )
|
||||
+ {
|
||||
+ m_pHostAcquire = static_cast<droiddeck_frame_acquire_v1 *>(
|
||||
+ wl_registry_bind( pRegistry, uName, &droiddeck_frame_acquire_v1_interface, 1u ) );
|
||||
+ }
|
||||
else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) )
|
||||
{
|
||||
m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u );
|
||||
diff --git a/src/WaylandServer/WaylandServerLegacy.h b/src/WaylandServer/WaylandServerLegacy.h
|
||||
index 63ee2ca..0164853 100644
|
||||
--- a/src/WaylandServer/WaylandServerLegacy.h
|
||||
+++ b/src/WaylandServer/WaylandServerLegacy.h
|
||||
@@ -3,9 +3,11 @@
|
||||
#include <wayland-server-core.h>
|
||||
#include "WaylandDecls.h"
|
||||
#include <memory>
|
||||
+#include <unordered_map>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include "vulkan_include.h"
|
||||
+#include "droiddeck_producer_fence.hpp"
|
||||
|
||||
|
||||
#include "wlr_begin.hpp"
|
||||
@@ -57,6 +59,10 @@ struct wlserver_wl_surface_info
|
||||
uint64_t desired_present_time = 0;
|
||||
|
||||
uint64_t last_refresh_cycle = 0;
|
||||
+ const void *producerPendingAttachment = nullptr;
|
||||
+ droiddeck::PendingProducerFence producerFence;
|
||||
+ std::unordered_map<uint32_t, droiddeck::PendingProducerFence> committedProducerFences;
|
||||
+ struct wl_listener producerFenceClientCommit;
|
||||
};
|
||||
|
||||
wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf);
|
||||
diff --git a/src/backend.h b/src/backend.h
|
||||
index 9a27711..9fe0c15 100644
|
||||
--- a/src/backend.h
|
||||
+++ b/src/backend.h
|
||||
@@ -377,6 +377,7 @@ namespace gamescope
|
||||
virtual bool IsSessionBased() const = 0;
|
||||
|
||||
virtual bool SupportsExplicitSync() const = 0;
|
||||
+ virtual bool SupportsDroidDeckProducerAcquire() const { return false; }
|
||||
|
||||
// Dumb helper we should remove to support multi display someday.
|
||||
gamescope::GamescopeScreenType GetScreenType()
|
||||
diff --git a/src/commit.cpp b/src/commit.cpp
|
||||
index fbfb550..cd35202 100644
|
||||
--- a/src/commit.cpp
|
||||
+++ b/src/commit.cpp
|
||||
@@ -55,7 +55,9 @@ void commit_t::OnPollIn()
|
||||
|
||||
{
|
||||
std::unique_lock lock( m_WaitableCommitStateMutex );
|
||||
- if ( !CloseFenceInternal() )
|
||||
+ const bool bFailedProducerFence = m_bProducerFence &&
|
||||
+ droiddeck::ProducerFenceStatus(m_nCommitFence) != 1;
|
||||
+ if ( !CloseFenceInternal() || bFailedProducerFence )
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -115,12 +117,13 @@ bool commit_t::CloseFenceInternal()
|
||||
return true;
|
||||
}
|
||||
|
||||
-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame )
|
||||
+void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame, bool bProducerFence )
|
||||
{
|
||||
std::unique_lock lock( m_WaitableCommitStateMutex );
|
||||
CloseFenceInternal();
|
||||
|
||||
m_nCommitFence = nFence;
|
||||
+ m_bProducerFence = bProducerFence;
|
||||
m_bMangoNudge = bMangoNudge;
|
||||
m_uMangoMsgType = uMangoMsgType;
|
||||
m_bDroidDeckHudFrame = bDroidDeckHudFrame;
|
||||
diff --git a/src/commit.h b/src/commit.h
|
||||
index ae767b6..99b32ae 100644
|
||||
--- a/src/commit.h
|
||||
+++ b/src/commit.h
|
||||
@@ -35,13 +35,14 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable,
|
||||
|
||||
// Returns true if we had a fence that was closed.
|
||||
bool CloseFenceInternal();
|
||||
- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame = false );
|
||||
+ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame = false, bool bProducerFence = false );
|
||||
|
||||
bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler );
|
||||
|
||||
struct wlr_buffer *buf = nullptr;
|
||||
gamescope::Rc<CVulkanTexture> vulkanTex;
|
||||
std::optional<UpscaledTexture_t> upscaledTexture;
|
||||
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
|
||||
|
||||
gamescope::Rc<CVulkanTexture> GetTexture( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler, GamescopeAppTextureColorspace &colorspace )
|
||||
{
|
||||
@@ -79,6 +80,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable,
|
||||
|
||||
std::mutex m_WaitableCommitStateMutex;
|
||||
int m_nCommitFence = -1;
|
||||
+ bool m_bProducerFence = false;
|
||||
bool m_bMangoNudge = false;
|
||||
// Typed mangoapp stream to nudge, 0 for none, never the legacy type.
|
||||
uint32_t m_uMangoMsgType = 0;
|
||||
diff --git a/src/droiddeck_producer_fence.hpp b/src/droiddeck_producer_fence.hpp
|
||||
new file mode 100644
|
||||
index 0000000..5e7dd9d
|
||||
--- /dev/null
|
||||
+++ b/src/droiddeck_producer_fence.hpp
|
||||
@@ -0,0 +1,67 @@
|
||||
+#pragma once
|
||||
+
|
||||
+#include <cstdint>
|
||||
+#include <cstdlib>
|
||||
+#include <cstring>
|
||||
+#include <fcntl.h>
|
||||
+#include <linux/sync_file.h>
|
||||
+#include <memory>
|
||||
+#include <sys/ioctl.h>
|
||||
+#include <unistd.h>
|
||||
+#include <utility>
|
||||
+
|
||||
+namespace droiddeck
|
||||
+{
|
||||
+ inline bool ProducerAcquireEnabled()
|
||||
+ {
|
||||
+ static const bool enabled = [] {
|
||||
+ const char *value = std::getenv("GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE");
|
||||
+ return value && std::strcmp(value, "1") == 0;
|
||||
+ }();
|
||||
+ return enabled;
|
||||
+ }
|
||||
+
|
||||
+ // Status 1 is success, 0 is pending, everything else is unsafe.
|
||||
+ inline int ProducerFenceStatus(int fd)
|
||||
+ {
|
||||
+ sync_file_info info{};
|
||||
+ if (fd < 0 || ioctl(fd, SYNC_IOC_FILE_INFO, &info) < 0 || !info.num_fences)
|
||||
+ return -1;
|
||||
+ return info.status;
|
||||
+ }
|
||||
+
|
||||
+ class ProducerFence
|
||||
+ {
|
||||
+ public:
|
||||
+ explicit ProducerFence(int fd) : m_fd(fd) {}
|
||||
+ ProducerFence(ProducerFence &&other) noexcept : m_fd(other.TakeFd()) {}
|
||||
+ ProducerFence(const ProducerFence &) = delete;
|
||||
+ ProducerFence &operator=(const ProducerFence &) = delete;
|
||||
+ ~ProducerFence() { if (m_fd >= 0) close(m_fd); }
|
||||
+
|
||||
+ int SyncStatus() const { return ProducerFenceStatus(m_fd); }
|
||||
+ int Dup() const { return m_fd < 0 ? -1 : fcntl(m_fd, F_DUPFD_CLOEXEC, 0); }
|
||||
+ int SignaledFd() const { return SyncStatus() == 1 ? m_fd : -1; }
|
||||
+ int Fd() const { return m_fd; }
|
||||
+ int TakeFd() { return std::exchange(m_fd, -1); }
|
||||
+
|
||||
+ private:
|
||||
+ int m_fd;
|
||||
+ };
|
||||
+
|
||||
+ // This slot belongs to one nested surface and is cleared by *every*
|
||||
+ // attach request, even if the client reuses the same wl_buffer object.
|
||||
+ struct PendingProducerFence
|
||||
+ {
|
||||
+ std::shared_ptr<ProducerFence> fence;
|
||||
+ uint32_t sequence = 0;
|
||||
+ const void *buffer = nullptr;
|
||||
+
|
||||
+ std::shared_ptr<ProducerFence> Consume(bool attached, uint32_t seq, const void *current)
|
||||
+ {
|
||||
+ auto owned = std::exchange(fence, {});
|
||||
+ const bool same = attached && seq == sequence && current && current == buffer;
|
||||
+ return same ? owned : nullptr;
|
||||
+ }
|
||||
+ };
|
||||
+}
|
||||
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
|
||||
index 8ae3b71..235cfc0 100644
|
||||
--- a/src/rendervulkan.hpp
|
||||
+++ b/src/rendervulkan.hpp
|
||||
@@ -281,6 +281,8 @@ enum AlphaBlendingMode_t
|
||||
//#define DRM_MODE_BLEND_COVERAGE 1
|
||||
//#define DRM_MODE_BLEND_PIXEL_NONE 2
|
||||
|
||||
+namespace droiddeck { class ProducerFence; }
|
||||
+
|
||||
struct FrameInfo_t
|
||||
{
|
||||
bool useFSRLayer0;
|
||||
@@ -309,6 +311,7 @@ struct FrameInfo_t
|
||||
struct Layer_t
|
||||
{
|
||||
gamescope::Rc<CVulkanTexture> tex;
|
||||
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
|
||||
int zpos;
|
||||
|
||||
vec2_t offset;
|
||||
@@ -378,6 +381,7 @@ struct FrameInfo_t
|
||||
if ( m_nCount >= k_nMaxLayers )
|
||||
return nullptr;
|
||||
|
||||
+ m_Layers[m_nCount].pProducerFence.reset();
|
||||
return &m_Layers[ m_nCount++ ];
|
||||
}
|
||||
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index c2e04ab..f5b744b 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -2559,6 +2559,7 @@ paint_cached_base_layer(const gamescope::Rc<commit_t>& commit, const BaseLayerIn
|
||||
|
||||
layer->tex = commit->GetTexture( base.eUpscaleFilter, base.eUpscaleScaler, layer->colorspace );
|
||||
layer->filter = base.filter;
|
||||
+ layer->pProducerFence = layer->tex == commit->vulkanTex ? commit->pProducerFence : nullptr;
|
||||
if ( layer->tex == commit->vulkanTex )
|
||||
{
|
||||
if ( base.uOutputWidth == currentOutputWidth && base.uOutputHeight == currentOutputHeight )
|
||||
@@ -2670,6 +2671,7 @@ paint_window_commit( const gamescope::Rc<commit_t> &lastCommit, steamcompmgr_win
|
||||
layer->filter = ( flags & PaintWindowFlag::NoFilter ) ? GamescopeUpscaleFilter::LINEAR : frameInfo->eUpscaleFilter;
|
||||
|
||||
layer->tex = lastCommit->GetTexture( layer->filter, frameInfo->eUpscaleScaler, layer->colorspace );
|
||||
+ layer->pProducerFence = layer->tex == lastCommit->vulkanTex ? lastCommit->pProducerFence : nullptr;
|
||||
|
||||
if ( flags & PaintWindowFlag::NoScale )
|
||||
{
|
||||
@@ -8915,7 +8917,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
|
||||
already_exists = true;
|
||||
}
|
||||
|
||||
- if ( already_exists && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() )
|
||||
+ if ( already_exists && !reslistentry.pProducerFence && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() )
|
||||
{
|
||||
wlserver_lock();
|
||||
wlr_buffer_unlock( buf );
|
||||
@@ -8957,6 +8959,8 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
|
||||
droiddeck::frame_trace::Event::ImportSucceededOther,
|
||||
bTraceCurrent );
|
||||
|
||||
+ newCommit->pProducerFence = std::move(reslistentry.pProducerFence);
|
||||
+ const bool bProducerFence = bool(newCommit->pProducerFence);
|
||||
int fence = -1;
|
||||
global_focus_t *pCurrentFocus = GetCurrentFocus();
|
||||
|
||||
@@ -9104,7 +9108,24 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
|
||||
pBackendFb->SetBuffer( buf );
|
||||
}
|
||||
|
||||
- if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent )
|
||||
+ if ( bProducerFence )
|
||||
+ {
|
||||
+ const int status = newCommit->pProducerFence->SyncStatus();
|
||||
+ if ( status != 0 && status != 1 )
|
||||
+ return; // A failed producer write may not be marked ready.
|
||||
+ bKnownReady = status == 1;
|
||||
+ if ( !bKnownReady )
|
||||
+ {
|
||||
+ fence = newCommit->pProducerFence->Dup();
|
||||
+ if ( fence < 0 )
|
||||
+ {
|
||||
+ // Still wait on original; this commit cannot forward proof.
|
||||
+ fence = newCommit->pProducerFence->TakeFd();
|
||||
+ newCommit->pProducerFence.reset();
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ else if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent )
|
||||
{
|
||||
fence = eventFd.first;
|
||||
bKnownReady = eventFd.second;
|
||||
@@ -9127,13 +9148,13 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
|
||||
|
||||
if ( cv_commit_ready_check )
|
||||
{
|
||||
- if ( !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) )
|
||||
+ if ( !bProducerFence && !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) )
|
||||
bKnownReady = true;
|
||||
note_commit_fence( bKnownReady );
|
||||
}
|
||||
gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 );
|
||||
{
|
||||
- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted() );
|
||||
+ newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted(), bProducerFence );
|
||||
if ( bKnownReady )
|
||||
{
|
||||
newCommit->Signal();
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index 84602c0..6a4f4da 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -57,6 +57,7 @@
|
||||
#include "gamescope-private-protocol.h"
|
||||
#include "gamescope-swapchain-protocol.h"
|
||||
#include "presentation-time-protocol.h"
|
||||
+#include "droiddeck-game-frame-acquire-v1-protocol.h"
|
||||
|
||||
#include "wlserver.hpp"
|
||||
#include "hdmi.h"
|
||||
@@ -136,7 +137,8 @@ std::vector<ResListEntry_t>& gamescope_xwayland_server_t::retrieve_commits()
|
||||
|
||||
gamescope::ConVar<bool> cv_drm_debug_syncobj_force_wait_on_commit( "drm_debug_syncobj_force_wait_on_commit", false, "Force a wait on DRM sync objects before committing buffers" );
|
||||
|
||||
-ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf )
|
||||
+ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf,
|
||||
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence )
|
||||
{
|
||||
auto wl_surf = get_wl_surface_info( surf );
|
||||
|
||||
@@ -168,7 +170,8 @@ ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf )
|
||||
wl_surf->present_id,
|
||||
wl_surf->desired_present_time,
|
||||
std::move( pAcquirePoint ),
|
||||
- std::move( pReleasePoint )
|
||||
+ std::move( pReleasePoint ),
|
||||
+ bExplicitSync ? nullptr : std::move( pProducerFence )
|
||||
};
|
||||
wl_surf->present_id = std::nullopt;
|
||||
wl_surf->desired_present_time = 0;
|
||||
@@ -216,6 +219,12 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
|
||||
? droiddeck::frame_trace::Event::SurfaceCommitBuffer
|
||||
: droiddeck::frame_trace::Event::SurfaceCommitNoBuffer );
|
||||
|
||||
+ // Capture state before the existing damage/attach flags are reset.
|
||||
+ const bool bAttached = wlr_surface->current.committed & WLR_SURFACE_STATE_BUFFER;
|
||||
+ auto &proofs = get_wl_surface_info(wlr_surface)->committedProducerFences;
|
||||
+ auto proof = proofs.extract(wlr_surface->current.seq);
|
||||
+ auto pProducerFence = proof.empty() ? nullptr : proof.mapped().Consume(
|
||||
+ bAttached, wlr_surface->current.seq, wlr_surface->current.buffer );
|
||||
wlr_surface->current.committed = 0;
|
||||
|
||||
wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface;
|
||||
@@ -249,7 +258,14 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
|
||||
|
||||
gpuvis_trace_printf( "xwayland_surface_commit wlr_surface %p", wlr_surface );
|
||||
|
||||
- ResListEntry_t entry = PrepareCommit( wlr_surface, buf );
|
||||
+ // A texture may still designate older storage after a rejected/no-op import.
|
||||
+ if ( pProducerFence )
|
||||
+ {
|
||||
+ struct wlr_dmabuf_attributes dmabuf{};
|
||||
+ if ( wlr_surface->current.buffer != buf || !wlr_buffer_get_dmabuf(buf, &dmabuf) )
|
||||
+ pProducerFence.reset();
|
||||
+ }
|
||||
+ ResListEntry_t entry = PrepareCommit( wlr_surface, buf, std::move(pProducerFence) );
|
||||
|
||||
if (wlserver_x11_surface_info)
|
||||
{
|
||||
@@ -612,6 +628,31 @@ wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf)
|
||||
return reinterpret_cast<wlserver_wl_surface_info *>(wlr_surf->data);
|
||||
}
|
||||
|
||||
+// This wlroots signal runs with its own pending.buffer lock, after the
|
||||
+// pending object has been resolved and before the commit is applied or cached.
|
||||
+static bool producer_fence_protocol_active();
|
||||
+
|
||||
+static void handle_producer_fence_client_commit(wl_listener *listener, void *)
|
||||
+{
|
||||
+ wlserver_wl_surface_info *info = wl_container_of(listener, info, producerFenceClientCommit);
|
||||
+ wlr_surface *surface = info->wlr;
|
||||
+ info->producerPendingAttachment = nullptr;
|
||||
+ auto proof = std::exchange(info->producerFence, {});
|
||||
+ if (!proof.fence || !surface->pending.buffer || proof.sequence != surface->pending.seq ||
|
||||
+ !(surface->pending.committed & WLR_SURFACE_STATE_BUFFER))
|
||||
+ return;
|
||||
+ struct wlr_dmabuf_attributes dmabuf{};
|
||||
+ if (!wlr_buffer_get_dmabuf(surface->pending.buffer, &dmabuf) ||
|
||||
+ info->committedProducerFences.size() >= 64 ||
|
||||
+ info->committedProducerFences.contains(proof.sequence))
|
||||
+ {
|
||||
+ wlr_surface_reject_pending(surface, surface->resource, 0, "invalid or excessive producer fence commits");
|
||||
+ return;
|
||||
+ }
|
||||
+ proof.buffer = surface->pending.buffer; // Borrowed from the state lock, no extra release path.
|
||||
+ info->committedProducerFences.emplace(proof.sequence, std::move(proof));
|
||||
+}
|
||||
+
|
||||
static void handle_wl_surface_commit( struct wl_listener *l, void *data )
|
||||
{
|
||||
wlserver_wl_surface_info *surf = wl_container_of( l, surf, commit );
|
||||
@@ -707,6 +748,7 @@ static void handle_wl_surface_destroy( struct wl_listener *l, void *data )
|
||||
}
|
||||
|
||||
wl_list_remove( &surf->commit.link );
|
||||
+ wl_list_remove(&surf->producerFenceClientCommit.link);
|
||||
wl_list_remove( &surf->destroy.link );
|
||||
|
||||
delete surf;
|
||||
@@ -725,6 +767,12 @@ static void wlserver_new_surface(struct wl_listener *l, void *data)
|
||||
|
||||
wl_surface_info->commit.notify = handle_wl_surface_commit;
|
||||
wl_signal_add( &wlr_surf->events.commit, &wl_surface_info->commit );
|
||||
+ wl_list_init(&wl_surface_info->producerFenceClientCommit.link);
|
||||
+ if (producer_fence_protocol_active())
|
||||
+ {
|
||||
+ wl_surface_info->producerFenceClientCommit.notify = handle_producer_fence_client_commit;
|
||||
+ wl_signal_add(&wlr_surf->events.client_commit, &wl_surface_info->producerFenceClientCommit);
|
||||
+ }
|
||||
|
||||
wlr_surf->data = wl_surface_info;
|
||||
|
||||
@@ -1811,6 +1859,79 @@ static bool filter_global(const struct wl_client *client, const struct wl_global
|
||||
return server && server->get_output() == output;
|
||||
}
|
||||
|
||||
+static wl_protocol_logger *s_pProducerFenceLogger;
|
||||
+static wl_global *s_pProducerFenceGlobal;
|
||||
+
|
||||
+static bool producer_fence_protocol_active()
|
||||
+{
|
||||
+ return s_pProducerFenceGlobal != nullptr;
|
||||
+}
|
||||
+
|
||||
+static void producer_fence_protocol_log( void *, wl_protocol_logger_type direction,
|
||||
+ const wl_protocol_logger_message *message )
|
||||
+{
|
||||
+ if ( direction != WL_PROTOCOL_LOGGER_REQUEST || std::strcmp(message->message->name, "attach") ||
|
||||
+ std::strcmp(wl_resource_get_class(message->resource), wl_surface_interface.name) ||
|
||||
+ message->arguments_count != 3 )
|
||||
+ return;
|
||||
+ auto *surf = wlr_surface_from_resource(message->resource);
|
||||
+ if ( auto *info = get_wl_surface_info(surf) )
|
||||
+ {
|
||||
+ info->producerFence = {};
|
||||
+ // Wayland's server demarshaller gives the wl_object at the start
|
||||
+ // of the wl_resource. Compare identity only, never dereference it.
|
||||
+ info->producerPendingAttachment = message->arguments[0].o;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+static void set_producer_fence( wl_client *client, wl_resource *manager, wl_resource *surface,
|
||||
+ wl_resource *buffer, int32_t fd )
|
||||
+{
|
||||
+ droiddeck::ProducerFence fence(fd);
|
||||
+ wlr_surface *surf = surface && wl_resource_get_client(surface) == client
|
||||
+ ? wlr_surface_from_resource(surface) : nullptr;
|
||||
+ auto *info = get_wl_surface_info(surf);
|
||||
+ if (!info || !buffer || wl_resource_get_client(buffer) != client ||
|
||||
+ !(surf->pending.committed & WLR_SURFACE_STATE_BUFFER) ||
|
||||
+ info->producerPendingAttachment != buffer || info->producerFence.fence)
|
||||
+ {
|
||||
+ wl_resource_post_error(manager, 0, "invalid or duplicate producer fence attachment");
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ const int status = fence.SyncStatus();
|
||||
+ if (status != 0 && status != 1)
|
||||
+ {
|
||||
+ wl_resource_post_error(manager, 0, "producer fence requires a real sync_file");
|
||||
+ return;
|
||||
+ }
|
||||
+ info->producerFence = { std::make_shared<droiddeck::ProducerFence>(std::move(fence)),
|
||||
+ surf->pending.seq };
|
||||
+}
|
||||
+
|
||||
+static const struct droiddeck_game_frame_acquire_v1_interface producer_fence_impl = {
|
||||
+ .set_acquire_fence = set_producer_fence,
|
||||
+};
|
||||
+
|
||||
+static void bind_producer_fence(wl_client *client, void *, uint32_t, uint32_t id)
|
||||
+{
|
||||
+ auto *resource = wl_resource_create(client, &droiddeck_game_frame_acquire_v1_interface, 1, id);
|
||||
+ if (!resource)
|
||||
+ {
|
||||
+ wl_client_post_no_memory(client);
|
||||
+ return;
|
||||
+ }
|
||||
+ wl_resource_set_implementation(resource, &producer_fence_impl, nullptr, nullptr);
|
||||
+}
|
||||
+
|
||||
+static void stop_producer_fence_protocol()
|
||||
+{
|
||||
+ if (s_pProducerFenceGlobal)
|
||||
+ wl_global_destroy(std::exchange(s_pProducerFenceGlobal, nullptr));
|
||||
+ if (s_pProducerFenceLogger)
|
||||
+ wl_protocol_logger_destroy(std::exchange(s_pProducerFenceLogger, nullptr));
|
||||
+}
|
||||
+
|
||||
bool wlsession_init( void ) {
|
||||
static bool s_bInitted = false;
|
||||
if ( s_bInitted )
|
||||
@@ -1824,6 +1945,7 @@ bool wlsession_init( void ) {
|
||||
|
||||
wl_display_set_global_filter(wlserver.display, filter_global, nullptr);
|
||||
|
||||
+
|
||||
const struct wlserver_output_info output_info = {
|
||||
.description = "Virtual gamescope output",
|
||||
};
|
||||
@@ -2200,6 +2322,18 @@ void wlserver_set_keyboard_layout( const char *pszLayout )
|
||||
bool wlserver_init( void ) {
|
||||
assert( wlserver.display != nullptr );
|
||||
|
||||
+ // The backend has round-tripped its parent registry before wlserver_init.
|
||||
+ // Older hosts, non-Wayland backends or an unarmed host keep the original
|
||||
+ // producer conventions: do not advertise this inner protocol at all.
|
||||
+ if (droiddeck::ProducerAcquireEnabled() && GetBackend()->SupportsDroidDeckProducerAcquire())
|
||||
+ {
|
||||
+ s_pProducerFenceLogger = wl_display_add_protocol_logger(wlserver.display, producer_fence_protocol_log, nullptr);
|
||||
+ if (s_pProducerFenceLogger)
|
||||
+ s_pProducerFenceGlobal = wl_global_create(wlserver.display, &droiddeck_game_frame_acquire_v1_interface, 1, nullptr, bind_producer_fence);
|
||||
+ if (!s_pProducerFenceGlobal)
|
||||
+ stop_producer_fence_protocol();
|
||||
+ }
|
||||
+
|
||||
wl_list_init(&pending_surfaces);
|
||||
|
||||
wlserver.wlr.multi_backend = wlr_multi_backend_create( wlserver.event_loop );
|
||||
@@ -2345,6 +2479,7 @@ bool wlserver_init( void ) {
|
||||
{
|
||||
wl_log.errorf("Failed to start backend");
|
||||
wlr_backend_destroy( wlserver.wlr.multi_backend );
|
||||
+ stop_producer_fence_protocol();
|
||||
wl_display_destroy(wlserver.display);
|
||||
return false;
|
||||
}
|
||||
@@ -2527,6 +2662,7 @@ void wlserver_run(void)
|
||||
wl_list_remove( &wlserver.session_active.link );
|
||||
#endif
|
||||
|
||||
+ stop_producer_fence_protocol();
|
||||
wl_display_destroy_clients(wlserver.display);
|
||||
wl_display_destroy(wlserver.display);
|
||||
wlserver.display = NULL;
|
||||
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
|
||||
index 63542ef..12141b6 100644
|
||||
--- a/src/wlserver.hpp
|
||||
+++ b/src/wlserver.hpp
|
||||
@@ -50,6 +50,7 @@ struct ResListEntry_t {
|
||||
uint64_t desired_present_time;
|
||||
std::shared_ptr<gamescope::CAcquireTimelinePoint> pAcquirePoint;
|
||||
std::shared_ptr<gamescope::CReleaseTimelinePoint> pReleasePoint;
|
||||
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
|
||||
};
|
||||
|
||||
struct wlserver_content_override;
|
||||
@@ -1,3 +1,3 @@
|
||||
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d
|
||||
GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-verified-acquire-v1
|
||||
GAMESCOPE_SHA256=0861b5f6f694842eead87e4fd68f7b3cf93c35f10e1dccffd5ea3fc75081b97d
|
||||
@@ -2,6 +2,9 @@
|
||||
#include "nested_surface_format.hpp"
|
||||
#include "dmabuf_import.hpp"
|
||||
#include "sdl_refresh.hpp"
|
||||
#include "output_image_pick.hpp"
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
|
||||
@@ -152,5 +155,43 @@ int main()
|
||||
assert(DmabufMemoryType(memory, 7, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX);
|
||||
assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == UINT32_MAX);
|
||||
|
||||
using gamescope::PickOutputImage;
|
||||
auto none = [](uint32_t) { return false; };
|
||||
auto pick = PickOutputImage(5, 2, 1, 0, none, none);
|
||||
assert(pick.image == 2 && !pick.scanoutPending);
|
||||
auto heldTwo = [](uint32_t i) { return i == 2; };
|
||||
pick = PickOutputImage(5, 2, 1, 0, heldTwo, none);
|
||||
assert(pick.image == 3 && !pick.scanoutPending);
|
||||
auto scanningTwo = [](uint32_t i) { return i == 2; };
|
||||
pick = PickOutputImage(5, 2, 1, 0, none, scanningTwo);
|
||||
assert(pick.image == 3 && !pick.scanoutPending);
|
||||
auto scanningAll = [](uint32_t) { return true; };
|
||||
pick = PickOutputImage(5, 2, 1, 0, heldTwo, scanningAll);
|
||||
assert(pick.image == 3 && pick.scanoutPending);
|
||||
auto heldAll = [](uint32_t) { return true; };
|
||||
auto scanningOne = [](uint32_t i) { return i == 1; };
|
||||
pick = PickOutputImage(5, 2, 1, 0, heldAll, none);
|
||||
assert(pick.image == 2 && !pick.scanoutPending);
|
||||
pick = PickOutputImage(5, 1, 0, 1, heldAll, scanningOne);
|
||||
assert(pick.image == 1 && pick.scanoutPending);
|
||||
pick = PickOutputImage(3, 1, 0, 2, none, none);
|
||||
assert(pick.image == 1 && !pick.scanoutPending);
|
||||
pick = PickOutputImage(3, 1, 0, 2, none, scanningOne);
|
||||
assert(pick.image == 2 && !pick.scanoutPending);
|
||||
|
||||
int fds[2];
|
||||
assert(pipe(fds) == 0);
|
||||
assert(!gamescope::DmabufScanoutPending(fds[1]));
|
||||
assert(!gamescope::DmabufScanoutPending(-1));
|
||||
fcntl(fds[1], F_SETFL, O_NONBLOCK);
|
||||
char block[4096] = {};
|
||||
while (write(fds[1], block, sizeof(block)) > 0) {}
|
||||
assert(gamescope::DmabufScanoutPending(fds[1]));
|
||||
gamescope::WaitDmabufScanout(fds[1], 1);
|
||||
while (read(fds[0], block, sizeof(block)) == sizeof(block) && gamescope::DmabufScanoutPending(fds[1])) {}
|
||||
assert(!gamescope::DmabufScanoutPending(fds[1]));
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
std::puts("Gamescope presentation and DMA-BUF import tests passed");
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#include "droiddeck_producer_fence.hpp"
|
||||
#include <cassert>
|
||||
#include <cerrno>
|
||||
#include <utility>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace droiddeck;
|
||||
assert(!ProducerAcquireEnabled()); // normal startup, no opt-in
|
||||
assert(ProducerFenceStatus(-1) < 0);
|
||||
|
||||
int ends[2];
|
||||
assert(pipe(ends) == 0);
|
||||
const int readEnd = ends[0];
|
||||
auto fd = std::make_shared<ProducerFence>(readEnd);
|
||||
assert(fd->SyncStatus() < 0); // ordinary pipe must never become a ready writer fence
|
||||
assert(fd->SignaledFd() < 0);
|
||||
int a, b;
|
||||
PendingProducerFence old{fd, 21, &a};
|
||||
assert(!old.Consume(true, 22, &a));
|
||||
assert(!old.fence);
|
||||
PendingProducerFence different{fd, 21, &a};
|
||||
assert(!different.Consume(true, 21, &b));
|
||||
PendingProducerFence empty{fd, 21, &a};
|
||||
assert(!empty.Consume(false, 21, &a));
|
||||
PendingProducerFence matching{std::move(fd), 21, &a};
|
||||
auto consumed = matching.Consume(true, 21, &a);
|
||||
assert(consumed && !matching.Consume(true, 21, &a)); // never clonable across commits
|
||||
int dup = consumed->Dup();
|
||||
assert(dup >= 0 && fcntl(dup, F_GETFD) == FD_CLOEXEC);
|
||||
consumed.reset();
|
||||
assert(fcntl(readEnd, F_GETFD) == -1 && errno == EBADF);
|
||||
assert(fcntl(dup, F_GETFD) == FD_CLOEXEC);
|
||||
close(dup);
|
||||
close(ends[1]);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"version": 1,
|
||||
"release": "Fedora 44 Everything aarch64",
|
||||
"mirror": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/",
|
||||
"packages": {
|
||||
"ibus-pinyin": {
|
||||
"filename": "ibus-pinyin-1.5.1-7.fc44.aarch64.rpm",
|
||||
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/i/ibus-pinyin-1.5.1-7.fc44.aarch64.rpm",
|
||||
"sha256": "fcae3a5f4263c005efa0751737bd653d4dca8ca53777362ad519f6bcbd99587c"
|
||||
},
|
||||
"pyzy": {
|
||||
"filename": "pyzy-0.1.0-37.fc44.aarch64.rpm",
|
||||
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-0.1.0-37.fc44.aarch64.rpm",
|
||||
"sha256": "aa41dfdaa052ac5432e2fd4c64ea706a7153b6e7b72f18bf1633006f7190b76f"
|
||||
},
|
||||
"pyzy-db-android": {
|
||||
"filename": "pyzy-db-android-0.1.0-37.fc44.noarch.rpm",
|
||||
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-db-android-0.1.0-37.fc44.noarch.rpm",
|
||||
"sha256": "bcaafe36fc93b892b1901607c887fd4efbc47eaa5b829bfe0347aa3137f41576"
|
||||
},
|
||||
"lua-libs": {
|
||||
"filename": "lua-libs-5.4.8-5.fc44.aarch64.rpm",
|
||||
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/l/lua-libs-5.4.8-5.fc44.aarch64.rpm",
|
||||
"sha256": "d719e35a8c2f771084f0b0d135a3ac68c51b032fc2199507685fe3ea32cee8fc"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare the pinned pinyin engine and its runtime dependencies."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import xml.etree.ElementTree as ElementTree
|
||||
|
||||
PACKAGES = Path(__file__).with_name('packages.json')
|
||||
LIBRARY_DIR = 'usr/local/lib/droiddeck-ime'
|
||||
ENGINE_NAME = 'ibus-engine-pinyin'
|
||||
ENGINE_MEMBERS = ('usr/libexec/' + ENGINE_NAME, 'usr/bin/' + ENGINE_NAME)
|
||||
COMPONENT = 'usr/share/ibus/component/pinyin.xml'
|
||||
PROFILE = 'usr/local/share/droiddeck/ibus.profile'
|
||||
MANIFEST = 'usr/local/share/droiddeck/ime-files.json'
|
||||
LICENSES = 'usr/local/share/licenses/droiddeck-ime'
|
||||
PROFILE_TEXT = 'user-db:user\nsystem-db:ibus\n'
|
||||
# The engine links these by soname, so the dereferenced copies keep the RPM member names.
|
||||
LIBRARIES = {'pyzy': ('usr/lib64/libpyzy-1.0.so.0',),
|
||||
'lua-libs': ('usr/lib64/liblua-5.4.so', 'usr/lib64/liblua-5.4.so.0')}
|
||||
DATA = {'ibus-pinyin': ('usr/share/ibus-pinyin/base.lua', 'usr/share/ibus-pinyin/phrases.txt',
|
||||
'usr/share/ibus-pinyin/db/english.db'),
|
||||
'pyzy': ('usr/share/pyzy/phrases.txt',),
|
||||
'pyzy-db-android': ('usr/share/pyzy/db/android.db',)}
|
||||
NOTICES = ('COPYING', 'LICENSE', 'COPYRIGHT', 'README', 'NOTICE')
|
||||
|
||||
|
||||
def digest(path):
|
||||
result = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
result.update(block)
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def specifications():
|
||||
return json.loads(PACKAGES.read_text())['packages']
|
||||
|
||||
|
||||
def fetch(directory, spec):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / spec['filename']
|
||||
pending = path.with_name(path.name + '.pending')
|
||||
with urllib.request.urlopen(spec['url'], timeout=60) as response, pending.open('wb') as stream:
|
||||
shutil.copyfileobj(response, stream)
|
||||
if digest(pending) != spec['sha256']:
|
||||
pending.unlink()
|
||||
raise ValueError('SHA256 mismatch for downloaded ' + spec['filename'])
|
||||
pending.replace(path)
|
||||
return path
|
||||
|
||||
|
||||
def verified(directory, download=False):
|
||||
sources = {}
|
||||
for name, spec in specifications().items():
|
||||
path = directory / spec['filename']
|
||||
if download and not (path.is_file() and digest(path) == spec['sha256']):
|
||||
path = fetch(directory, spec)
|
||||
if not path.is_file():
|
||||
raise ValueError('missing RPM ' + spec['filename'])
|
||||
if digest(path) != spec['sha256']:
|
||||
raise ValueError('SHA256 mismatch for ' + spec['filename'])
|
||||
sources[name] = path
|
||||
return sources
|
||||
|
||||
|
||||
def extract(name, rpm, destination):
|
||||
for tool in ('rpm2cpio', 'cpio'):
|
||||
if shutil.which(tool) is None:
|
||||
raise ValueError(tool + ' is required to unpack the RPM payload')
|
||||
destination.mkdir(parents=True)
|
||||
with tempfile.TemporaryFile(dir=destination.parent) as payload:
|
||||
subprocess.run(['rpm2cpio', str(rpm)], stdout=payload, check=True)
|
||||
payload.seek(0)
|
||||
listing = subprocess.run(['cpio', '-it', '--quiet'], stdin=payload,
|
||||
stdout=subprocess.PIPE, check=True)
|
||||
payload.seek(0)
|
||||
for line in listing.stdout.splitlines():
|
||||
path = PurePosixPath(line.decode('utf-8', 'surrogateescape'))
|
||||
if path.is_absolute() or '..' in path.parts:
|
||||
raise ValueError(f'{name}: RPM payload contains unsafe path {path}')
|
||||
subprocess.run(['cpio', '-idm', '--quiet'], stdin=payload,
|
||||
cwd=destination, check=True)
|
||||
|
||||
|
||||
def member(tree, name):
|
||||
path = (tree / name).resolve()
|
||||
if not path.is_relative_to(tree.resolve()) or not path.is_file():
|
||||
raise ValueError(f'{tree.name}: RPM payload is missing {name}')
|
||||
return path
|
||||
|
||||
|
||||
def install(source, target, output, files, executable=False):
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
target.chmod(0o755 if executable else 0o644)
|
||||
files.add(target.relative_to(output).as_posix())
|
||||
|
||||
|
||||
def engine(tree):
|
||||
for candidate in ENGINE_MEMBERS:
|
||||
if (tree / candidate).is_file():
|
||||
return candidate
|
||||
raise ValueError('ibus-pinyin RPM has no ' + ENGINE_NAME + ' executable')
|
||||
|
||||
|
||||
def component(tree):
|
||||
root = ElementTree.parse(member(tree, COMPONENT)).getroot()
|
||||
for element in list(root.iter()):
|
||||
for child in list(element):
|
||||
if child.tag == 'setup':
|
||||
element.remove(child)
|
||||
executable = root.find('exec')
|
||||
if executable is None:
|
||||
raise ValueError('pinyin.xml has no engine exec element')
|
||||
executable.text = f'/{LIBRARY_DIR}/{ENGINE_NAME} --ibus'
|
||||
engines = {node.findtext('name', '').strip() for node in root.iter('engine')}
|
||||
if not {'pinyin', 'bopomofo'} <= engines:
|
||||
raise ValueError('pinyin.xml no longer defines the pinyin and bopomofo engines')
|
||||
return root
|
||||
|
||||
|
||||
def icons(root, tree, output, files):
|
||||
names = set()
|
||||
for node in root.iter('icon'):
|
||||
text = (node.text or '').strip()
|
||||
if text:
|
||||
names.add(Path(text).stem if '/' in text else text)
|
||||
found = sorted(path for path in (tree / 'usr/share').rglob('*')
|
||||
if path.is_file() and path.suffix in ('.svg', '.png') and path.stem in names)
|
||||
if names and not found:
|
||||
raise ValueError('pinyin.xml icons are not in the ibus-pinyin RPM: ' + ', '.join(sorted(names)))
|
||||
for path in found:
|
||||
install(path, output / path.relative_to(tree), output, files)
|
||||
|
||||
|
||||
def notices(name, tree, output, files):
|
||||
copied = []
|
||||
for folder in ('usr/share/licenses/' + name, 'usr/share/doc/' + name):
|
||||
base = tree / folder
|
||||
if not base.is_dir():
|
||||
continue
|
||||
for path in sorted(base.rglob('*')):
|
||||
if path.is_file() and path.name.upper().startswith(NOTICES):
|
||||
target = output / LICENSES / name / path.relative_to(base)
|
||||
install(path, target, output, files)
|
||||
copied.append(target.relative_to(output / LICENSES).as_posix())
|
||||
return copied
|
||||
|
||||
|
||||
def prepare(directory, output, work=None, download=False):
|
||||
specs = specifications()
|
||||
sources = verified(directory, download)
|
||||
output = output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
created = work is None
|
||||
work = Path(tempfile.mkdtemp(prefix='.droiddeck-ime-', dir=output.parent)) if created else Path(work)
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
trees = {}
|
||||
for name, source in sources.items():
|
||||
trees[name] = work / name
|
||||
shutil.rmtree(trees[name], ignore_errors=True)
|
||||
extract(name, source, trees[name])
|
||||
files = set()
|
||||
pinyin = trees['ibus-pinyin']
|
||||
install(member(pinyin, engine(pinyin)), output / LIBRARY_DIR / ENGINE_NAME, output, files, executable=True)
|
||||
for name, candidates in LIBRARIES.items():
|
||||
installed = [candidate for candidate in candidates if (trees[name] / candidate).exists()]
|
||||
if not installed:
|
||||
raise ValueError(f'{name}: RPM has none of {list(candidates)}')
|
||||
for candidate in installed:
|
||||
install(member(trees[name], candidate), output / LIBRARY_DIR / Path(candidate).name, output, files)
|
||||
for name, members in DATA.items():
|
||||
for relative in members:
|
||||
install(member(trees[name], relative), output / relative, output, files)
|
||||
root = component(pinyin)
|
||||
icons(root, pinyin, output, files)
|
||||
target = output / COMPONENT
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
ElementTree.ElementTree(root).write(target, encoding='utf-8', xml_declaration=True)
|
||||
files.add(COMPONENT)
|
||||
profile = output / PROFILE
|
||||
profile.parent.mkdir(parents=True, exist_ok=True)
|
||||
profile.write_text(PROFILE_TEXT, newline='\n')
|
||||
files.add(PROFILE)
|
||||
packages = {}
|
||||
for name, spec in specs.items():
|
||||
license_files = notices(name, trees[name], output, files)
|
||||
packages[name] = {'filename': spec['filename'], 'url': spec['url'], 'sha256': spec['sha256'],
|
||||
'license_files': license_files}
|
||||
if not license_files:
|
||||
packages[name]['license_note'] = ('RPM bundles no separate license file; '
|
||||
'the payload is unmodified Fedora package content')
|
||||
manifest = {'version': 1, 'engine': 'pinyin', 'packages': packages,
|
||||
'files': {path: {'sha256': digest(output / path),
|
||||
'mode': f'{(output / path).stat().st_mode & 0o777:04o}'}
|
||||
for path in sorted(files)}}
|
||||
destination = output / MANIFEST
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(manifest, sort_keys=True, indent=2) + '\n', newline='\n')
|
||||
return destination, len(files)
|
||||
finally:
|
||||
if created:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--packages', type=Path, required=True, help='Directory with the exact pinned RPMs')
|
||||
parser.add_argument('--output', type=Path, required=True,
|
||||
help='Prepared linuxfs root, for example app/build/prepared-assets/linuxfs')
|
||||
parser.add_argument('--work', type=Path, help='Kept extraction cache instead of a temporary directory')
|
||||
parser.add_argument('--download', action='store_true',
|
||||
help='Fetch missing or mismatched RPMs into --packages and verify their SHA256')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
destination, count = prepare(args.packages, args.output, args.work, args.download)
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, ElementTree.ParseError) as error:
|
||||
parser.exit(1, f'error: {error}\n')
|
||||
print(f'Wrote {count} IME payload files; manifest {destination}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check pinyin configuration and text commits over IBus."""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
try:
|
||||
import gi
|
||||
|
||||
gi.require_version('IBus', '1.0')
|
||||
from gi.repository import GLib, IBus
|
||||
except (ImportError, ValueError) as error:
|
||||
raise SystemExit(f'error: PyGObject with the IBus 1.0 typelib is required: {error}')
|
||||
|
||||
CLIENT = 'droiddeck-ime-test'
|
||||
ENGINE = 'pinyin'
|
||||
SECTION = 'engine/Pinyin'
|
||||
BOOLEAN_KEYS = ('DoublePinyin', 'InitPinyin', 'GBK')
|
||||
KEYCODES = {'a': 38, 'h': 43, 'i': 31, 'n': 57, 'o': 32, 'space': 65, '1': 10}
|
||||
|
||||
|
||||
def pump(seconds, condition):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
GLib.MainContext.default().iteration(False)
|
||||
if condition():
|
||||
return True
|
||||
if time.monotonic() >= deadline:
|
||||
return False
|
||||
time.sleep(0.02)
|
||||
|
||||
|
||||
def press(context, name):
|
||||
keyval = IBus.keyval_from_name(name)
|
||||
keycode = KEYCODES[name]
|
||||
context.process_key_event(keyval, keycode, 0)
|
||||
context.process_key_event(keyval, keycode, IBus.ModifierType.RELEASE_MASK)
|
||||
|
||||
|
||||
def boolean(config, key):
|
||||
value = config.get_value(SECTION, key)
|
||||
if value is None or value.get_type_string() != 'b':
|
||||
return None
|
||||
return value.get_boolean()
|
||||
|
||||
|
||||
def unchanged(value, original):
|
||||
if original is None:
|
||||
return value is None
|
||||
return value is not None and value.print_(True) == original.print_(True)
|
||||
|
||||
|
||||
def configured(bus):
|
||||
config = bus.get_config()
|
||||
if config is None:
|
||||
raise SystemExit('error: the bus exposes no configuration service')
|
||||
saved = {key: config.get_value(SECTION, key) for key in BOOLEAN_KEYS}
|
||||
probed = 0
|
||||
try:
|
||||
for key in BOOLEAN_KEYS:
|
||||
original = saved[key]
|
||||
current = original is not None and original.get_type_string() == 'b' \
|
||||
and original.get_boolean()
|
||||
wanted = not current
|
||||
# The PyGObject override returns None on success, so verify writes by readback.
|
||||
config.set_value(SECTION, key, GLib.Variant.new_boolean(wanted))
|
||||
if not pump(3.0, lambda key=key, wanted=wanted: boolean(config, key) == wanted):
|
||||
raise SystemExit(f'error: {SECTION}/{key} did not read back as written')
|
||||
probed += 1
|
||||
finally:
|
||||
restore_failed = []
|
||||
for key in BOOLEAN_KEYS:
|
||||
original = saved[key]
|
||||
try:
|
||||
if original is None:
|
||||
config.unset(SECTION, key)
|
||||
else:
|
||||
config.set_value(SECTION, key, original)
|
||||
if not pump(3.0, lambda key=key, original=original:
|
||||
unchanged(config.get_value(SECTION, key), original)):
|
||||
restore_failed.append(key)
|
||||
except GLib.Error:
|
||||
restore_failed.append(key)
|
||||
if restore_failed:
|
||||
raise SystemExit('error: could not restore ' + SECTION + ' settings: '
|
||||
+ ', '.join(restore_failed))
|
||||
return probed
|
||||
|
||||
|
||||
def main():
|
||||
if not os.environ.get('IBUS_ADDRESS'):
|
||||
raise SystemExit('error: IBUS_ADDRESS is not set; the smoke test needs the private ibus-daemon')
|
||||
bus = IBus.Bus()
|
||||
if not bus.is_connected():
|
||||
raise SystemExit('error: cannot connect to the IBus bus from IBUS_ADDRESS')
|
||||
engines = {engine.get_name() for engine in bus.list_engines() or []}
|
||||
if ENGINE not in engines:
|
||||
raise SystemExit('error: pinyin is not registered: ' + ', '.join(sorted(engines)))
|
||||
print('IBus bus connected; pinyin engine registered')
|
||||
|
||||
keys = configured(bus)
|
||||
print(f'engine/Pinyin config write/readback ok ({keys} boolean settings)')
|
||||
|
||||
if not bus.set_global_engine(ENGINE):
|
||||
raise SystemExit('error: the bus rejected the pinyin global engine')
|
||||
context = bus.create_input_context(CLIENT)
|
||||
state = {'candidates': 0, 'commit': ''}
|
||||
|
||||
def lookup(_, table, visible):
|
||||
if table is not None:
|
||||
state['candidates'] = table.get_number_of_candidates()
|
||||
|
||||
def commit(_, text):
|
||||
state['commit'] = text.get_text() or state['commit']
|
||||
|
||||
context.connect('update-lookup-table', lookup)
|
||||
context.connect('commit-text', commit)
|
||||
context.set_capabilities(IBus.Capabilite.PREEDIT_TEXT | IBus.Capabilite.LOOKUP_TABLE
|
||||
| IBus.Capabilite.FOCUS)
|
||||
context.focus_in()
|
||||
pump(1.0, lambda: False)
|
||||
context.set_engine(ENGINE)
|
||||
pump(1.0, lambda: False)
|
||||
|
||||
for _ in range(3):
|
||||
for name in 'nihao':
|
||||
press(context, name)
|
||||
if pump(3.0, lambda: state['candidates'] > 0):
|
||||
break
|
||||
else:
|
||||
raise SystemExit('error: no pinyin candidates after typing the test syllable')
|
||||
print('lookup table ok')
|
||||
|
||||
def chinese():
|
||||
return any('\u4e00' <= character <= '\u9fff' for character in state['commit'])
|
||||
|
||||
for name in ('space', '1'):
|
||||
press(context, name)
|
||||
if pump(3.0, chinese):
|
||||
break
|
||||
if not chinese():
|
||||
raise SystemExit('error: pinyin committed no Chinese text for the test syllable')
|
||||
print('commit-text ok')
|
||||
context.focus_out()
|
||||
print('droiddeck IBus pinyin smoke test passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except GLib.Error as error:
|
||||
raise SystemExit(f'error: IBus call failed: {error.message}')
|
||||
@@ -31,5 +31,9 @@ for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDev
|
||||
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
|
||||
LSE=$(syms "$D/usr/local/lib/droiddeck-lse/liblse_emu.so")
|
||||
for sym in sigaction signal sigprocmask pthread_sigmask prctl syscall; do
|
||||
grep -qx "$sym" <<<"$LSE" || { echo "::error::liblse_emu.so does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/bin/droiddeck-session"
|
||||
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
||||
@@ -9,7 +9,8 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1
|
||||
export SHELL=/bin/bash
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export KWIN_USE_OVERLAYS=0
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
@@ -141,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
|
||||
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults --every 30 &
|
||||
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
|
||||
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
|
||||
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
|
||||
python3 /usr/local/bin/droiddeck-library-perms 2>&1 &
|
||||
mkdir -p /usr/local/share/applications
|
||||
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
@@ -174,6 +174,15 @@ fi
|
||||
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
|
||||
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
|
||||
fi
|
||||
# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them
|
||||
# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it
|
||||
# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the
|
||||
# global-menu proxy (the panel has no global menu).
|
||||
mkdir -p "$HOME/.config/autostart"
|
||||
for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do
|
||||
[ -e "$HOME/.config/autostart/$entry.desktop" ] ||
|
||||
printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop"
|
||||
done
|
||||
skel_done=$HOME/.local/share/droiddeck/skel-copied
|
||||
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
|
||||
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
|
||||
@@ -228,12 +237,21 @@ fi
|
||||
if ! /usr/local/bin/droiddeck-pipewire start; then
|
||||
echo "== pipewire: not running; screen capture has no picture"
|
||||
fi
|
||||
return_gaming=/run/droiddeck/return-gaming
|
||||
mkdir -p /run/droiddeck
|
||||
rm -f "$return_gaming"
|
||||
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
|
||||
dbus-run-session -- startplasma-wayland
|
||||
as_user=
|
||||
if [ "${DD_DESKTOP_USER:-}" = 1 ] && [ -n "${DDNATV_ROOT:-}" ]; then
|
||||
as_user=/usr/local/bin/droiddeck-user
|
||||
echo "== droiddeck-desktop: Plasma runs as an ordinary user"
|
||||
fi
|
||||
$as_user dbus-run-session -- startplasma-wayland
|
||||
rc=$?
|
||||
/usr/local/bin/droiddeck-pipewire stop
|
||||
echo "== droiddeck-desktop: Plasma ended ($rc)"
|
||||
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ]; then
|
||||
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ] && [ -e "$return_gaming" ]; then
|
||||
rm -f "$return_gaming"
|
||||
/usr/local/bin/droiddeck-steam-launch bigpicture
|
||||
sleep 30
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[Desktop Entry]
|
||||
Name=Return to Gaming Mode
|
||||
Comment=Log out of the desktop and go back to Steam
|
||||
Exec=sh -c ": > /run/droiddeck/return-gaming; dbus-send --session --print-reply --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout >/dev/null || rm -f /run/droiddeck/return-gaming"
|
||||
Icon=steamdeck-gaming-return
|
||||
Terminal=false
|
||||
Type=Application
|
||||
StartupNotify=false
|
||||
NoDisplay=true
|
||||
@@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false);
|
||||
pref("browser.aboutwelcome.enabled", false);
|
||||
pref("browser.startup.homepage", "about:blank");
|
||||
pref("layout.css.devPixelsPerPx", "1.25");
|
||||
// Android counts each of Firefox's processes against the app's limit of 32: one web content process
|
||||
// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and
|
||||
// about: pages in the processes that already exist.
|
||||
pref("fission.autostart", false);
|
||||
pref("dom.ipc.processCount", 2);
|
||||
pref("dom.ipc.processPrelaunch.enabled", false);
|
||||
pref("browser.tabs.remote.separatePrivilegedContentProcess", false);
|
||||
pref("extensions.webextensions.remote", false);
|
||||
@@ -0,0 +1,23 @@
|
||||
# LSE-Emu
|
||||
|
||||
`lse_emu.c` is a copy of [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) at commit
|
||||
`8bc9548ac6fd24a8d506b266b17ba8d0e71a9b01` (GPL-3.0-or-later) with two fixes, listed in
|
||||
`docs/arm-v8.0-steam-client.md` under "Fixes over upstream": NZCV kept across the min/max
|
||||
stubs, and a store-back on `CASP` mismatches so the returned pair is atomic. Carry them forward
|
||||
until upstream has them.
|
||||
|
||||
It is an `LD_PRELOAD` library that emulates the ARMv8.1 LSE atomic instructions (and `LDAPR`)
|
||||
on ARMv8.0 CPUs. A SIGILL handler performs each trapped instruction with an LL/SC loop. A GNU
|
||||
IFUNC resolver installs a minimal early handler on CPUs without LSE before dependency
|
||||
constructors, covering LSE instructions executed before the preload constructor. The early handler
|
||||
is removed after initialization unless `LSE_EMU=1` is set. With `LSE_EMU_PATCH=1` the first trap at a site
|
||||
writes an LL/SC stub nearby and replaces the instruction with a branch to it, so later runs do not trap.
|
||||
Patching is off by default. It is restricted to private file-backed executable mappings whose
|
||||
live file and offset still match the original mapping. Leave patching off for programs that
|
||||
can remap executable pages concurrently: checking the mapping cannot lock it against a remap.
|
||||
|
||||
The session stages it as `/usr/local/lib/droiddeck-lse/liblse_emu.so` and only lists it in
|
||||
`/etc/ld.so.preload` when `/proc/cpuinfo` has no `atomics` flag. See
|
||||
`docs/arm-v8.0-steam-client.md` for why.
|
||||
|
||||
To update, copy `lse_emu.c` from a newer upstream commit and change the commit above.
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
D=${1:?asset directory}
|
||||
CC=${CC:-aarch64-linux-gnu-gcc}
|
||||
STRIP=${STRIP:-aarch64-linux-gnu-strip}
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out="$D/usr/local/lib/droiddeck-lse/liblse_emu.so"
|
||||
mkdir -p "$(dirname "$out")"
|
||||
"$CC" -shared -fPIC -O2 -march=armv8-a -mno-outline-atomics -Wall -Wextra -Wno-unused-parameter \
|
||||
-Wl,-z,now,-z,max-page-size=65536 -o "$out" "$here/lse_emu.c" -ldl
|
||||
"$STRIP" --strip-unneeded "$out"
|
||||
disassembly=$("${OBJDUMP:-aarch64-linux-gnu-objdump}" -d "$out")
|
||||
if grep -qE $'\t((ld|st)(add|clr|eor|set|smax|smin|umax|umin)|swp|cas)[a-z]*\t' <<<"$disassembly"; then
|
||||
echo "::error::liblse_emu.so itself contains LSE instructions"; exit 1
|
||||
fi
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
import base64
|
||||
import ctypes
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
@@ -19,6 +20,7 @@ import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
VERSION = 1
|
||||
PR_SET_CHILD_SUBREAPER = 36
|
||||
OUTPUT_CAP = 256 * 1024
|
||||
REQUEST_CAP = 256 * 1024
|
||||
RESPONSE_CAP = 1024 * 1024
|
||||
@@ -282,8 +284,10 @@ def sandboxed_apps(proc=Path("/proc")):
|
||||
|
||||
def window_steam_app(win, flatpaks, proc=Path("/proc")):
|
||||
match = STEAM_APP_CLASS.match(win.get("class") or "")
|
||||
if match:
|
||||
return match.group(1) if os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64" else None
|
||||
if match and os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64":
|
||||
return match.group(1)
|
||||
# Gamescope finds the app of a window whose process runs under Steam's reaper. A game the
|
||||
# session runs in a worker process (GuestWorkers) is not under it, whatever its class.
|
||||
pid = win.get("pid")
|
||||
if pid:
|
||||
if under_reaper(pid, proc):
|
||||
@@ -569,11 +573,11 @@ def inspector_url(url):
|
||||
|
||||
|
||||
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
|
||||
command_line_api=False):
|
||||
command_line_api=False, connect_timeout=5):
|
||||
if inspector is not None:
|
||||
url, name = inspector_url(inspector), "inspector"
|
||||
else:
|
||||
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
|
||||
targets = [t for t in cdp_targets(agent_dir, timeout=connect_timeout) if t.get("webSocketDebuggerUrl")]
|
||||
want = target or "SharedJSContext"
|
||||
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
||||
if not match:
|
||||
@@ -837,6 +841,75 @@ class KeyboardWatcher(threading.Thread):
|
||||
self.report(params.get("payload") == "true")
|
||||
|
||||
|
||||
NATIVE_SUSPEND_JS = r"""/* Template arguments are inserted by Python after validation. */
|
||||
async (operation, token, value, order) => {
|
||||
const root = globalThis;
|
||||
const leases = root.__droiddeckNativeSleep ??= { current: null, order: 0n, canceled: false };
|
||||
const sequence = BigInt(order);
|
||||
if (sequence < leases.order) return operation === "wake" ? "miss" : "expired";
|
||||
if (sequence > leases.order) {
|
||||
// An older renderer evaluation can arrive after a newer one. Only
|
||||
// the newest Android request may own a still-in-flight preparation,
|
||||
// including when its own preparation cannot start before deadline.
|
||||
leases.order = sequence;
|
||||
leases.canceled = false;
|
||||
if (leases.current && !leases.current.result) {
|
||||
leases.current.owner = token;
|
||||
leases.current.wake = false;
|
||||
} else {
|
||||
leases.current = null;
|
||||
}
|
||||
}
|
||||
const busy = () => root.SuspendResumeStore?.m_bSuspending === true;
|
||||
const user = root.SteamClient?.User;
|
||||
async function recover(lease) {
|
||||
if (leases.current !== lease || lease.recovered || !lease.wake || busy()) return;
|
||||
if (typeof user?.ResumeSuspendedGames !== "function") return;
|
||||
lease.recovered = true;
|
||||
try { await user.ResumeSuspendedGames(false); } catch { /* no session kick or retry */ }
|
||||
}
|
||||
|
||||
if (operation === "wake") {
|
||||
leases.canceled = true;
|
||||
const lease = leases.current;
|
||||
if (lease?.owner !== token) return "miss";
|
||||
lease.wake = true;
|
||||
// If login1 already signaled sleep and preparation had settled before
|
||||
// wake, its normal resume notification owns recovery. A late success
|
||||
// must recover again only because that notification could precede it.
|
||||
if (lease.result === "prepared" && value !== "signaled") void recover(lease);
|
||||
return "ack";
|
||||
}
|
||||
|
||||
if (leases.canceled) return "expired";
|
||||
const active = leases.current;
|
||||
// A reused in-flight call still requires wake recovery, even when
|
||||
// this request is too late to issue its own call.
|
||||
if (active && !active.result) return "coalesced";
|
||||
if (Date.now() >= value) return "expired";
|
||||
if (typeof user?.PrepareForSystemSuspend !== "function") return "unavailable";
|
||||
if (busy()) return "steam-busy";
|
||||
if (active) return active.result;
|
||||
const lease = { owner: token, result: null, wake: false, recovered: false };
|
||||
leases.current = lease;
|
||||
try {
|
||||
const reply = await user.PrepareForSystemSuspend();
|
||||
lease.result = reply?.result === 1 ? "prepared" : "rejected";
|
||||
} catch {
|
||||
lease.result = "uncertain";
|
||||
}
|
||||
if (lease.result === "prepared" && lease.wake) void recover(lease);
|
||||
return lease.result;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def native_suspend_lease(agent_dir, command, token, value, order):
|
||||
expression = "(" + NATIVE_SUSPEND_JS + ")(" + ", ".join(map(json.dumps, (command, token, value, order))) + ")"
|
||||
return cdp_eval(agent_dir, expression, timeout=1.45 if command == "prepare" else 0.75,
|
||||
connect_timeout=0.35).get("value")
|
||||
|
||||
|
||||
def steam_idle_inhibit(agent_dir, inhibit):
|
||||
expression = """(async want => {
|
||||
const toggle = () => new Promise(done => {
|
||||
@@ -1238,7 +1311,17 @@ def answer(agent_dir, path):
|
||||
write_json(agent_dir / "resp" / (rid + ".json"), result)
|
||||
|
||||
|
||||
def stop_adopting_orphans():
|
||||
# libddsession makes every session process a child subreaper. The agent never reaps adopted orphans, so
|
||||
# SteamVR left zombies that its helper's stop counted as still running. The session shell above reaps them.
|
||||
try:
|
||||
ctypes.CDLL(None, use_errno=True).prctl(PR_SET_CHILD_SUBREAPER, 0, 0, 0, 0)
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
def serve(agent_dir, focus=True, poll=0.1):
|
||||
stop_adopting_orphans()
|
||||
(agent_dir / "req").mkdir(parents=True, exist_ok=True)
|
||||
(agent_dir / "resp").mkdir(parents=True, exist_ok=True)
|
||||
can_focus = focus and bool(os.environ.get("DISPLAY"))
|
||||
@@ -1304,6 +1387,23 @@ def main(argv):
|
||||
time.sleep(0.5)
|
||||
print({True: "yes", False: "no"}.get(value, "unknown"))
|
||||
return {True: 0, False: 5}.get(value, 1)
|
||||
if argv and argv[0] in ("--steam-prepare-native-suspend", "--steam-wake-native-suspend"):
|
||||
if (len(argv) != 4 or re.fullmatch(r"[0-9a-f]{32}", argv[1]) is None or
|
||||
re.fullmatch(r"[1-9][0-9]{0,19}", argv[3]) is None):
|
||||
return 2
|
||||
prepare = argv[0] == "--steam-prepare-native-suspend"
|
||||
if prepare and (not argv[2].isascii() or not argv[2].isdigit() or len(argv[2]) > 14):
|
||||
return 2
|
||||
if not prepare and argv[2] not in ("signaled", "unsignaled", "uncertain"):
|
||||
return 2
|
||||
kind = "prepare" if prepare else "wake"
|
||||
value = int(argv[2]) if prepare else argv[2]
|
||||
try:
|
||||
result = native_suspend_lease(Path(base) / "agent", kind, argv[1], value, argv[3])
|
||||
except (AgentError, OSError, ValueError):
|
||||
result = "uncertain"
|
||||
print(result or "uncertain")
|
||||
return 0 if result in ("prepared", "ack", "miss") else 1
|
||||
if argv and argv[0] == "--steam-asleep":
|
||||
expression = """(() => {
|
||||
const store = globalThis.SuspendResumeStore;
|
||||
|
||||
@@ -12,6 +12,7 @@ fi
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
if [ -s /etc/ld.so.preload ]; then
|
||||
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
|
||||
@@ -350,6 +350,17 @@ def keeps_open(root):
|
||||
return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1]
|
||||
|
||||
|
||||
def chosen_folder(root, current, library):
|
||||
current = current.strip()
|
||||
folder = windows_path(root, current) if current else None
|
||||
if not folder or rootfs_drive(root, current) or not os.path.isdir(folder):
|
||||
return False
|
||||
try:
|
||||
return volume_root(os.path.realpath(folder)) == volume_root(os.path.realpath(library))
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def write_config(root, library=None):
|
||||
path = os.path.join(drive_c(root), *CONFIG)
|
||||
key, value = LAUNCH_BEHAVIOR
|
||||
@@ -374,6 +385,7 @@ def write_config(root, library=None):
|
||||
client["HardwareAcceleration"] = "false"
|
||||
changes.append("acceleration")
|
||||
if library and isinstance(client.setdefault("Install", {}), dict) \
|
||||
and not chosen_folder(root, str(client["Install"].get("DefaultInstallPath", "")), library) \
|
||||
and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(root, library).rstrip("\\"):
|
||||
client["Install"]["DefaultInstallPath"] = install_path(root, library)
|
||||
changes.append("library")
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
#!/bin/bash
|
||||
[ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0
|
||||
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
|
||||
child=$!
|
||||
trap 'kill "$child" 2>/dev/null' EXIT
|
||||
[ -n "${DISPLAY:-}" ] || exit 0
|
||||
children=()
|
||||
if [ -n "${DD_ANDROID_CLIPBOARD:-}" ]; then
|
||||
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
|
||||
children+=("$!")
|
||||
fi
|
||||
if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-text-input ]; then
|
||||
/usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" &
|
||||
children+=("$!")
|
||||
fi
|
||||
[ "${#children[@]}" -gt 0 ] || exit 0
|
||||
trap 'kill "${children[@]}" 2>/dev/null' EXIT
|
||||
trap 'exit 0' TERM INT
|
||||
wait "$child"
|
||||
wait "${children[@]}"
|
||||
@@ -115,7 +115,7 @@ def link_libraries():
|
||||
common = os.path.join(library, "steamapps", "common")
|
||||
link = os.path.join(HOME, label)
|
||||
if os.path.isdir(common):
|
||||
if os.path.islink(link) and os.readlink(link) == common:
|
||||
if os.path.islink(link) and os.readlink(link) == common and os.path.isdir(os.path.join(link, ".")):
|
||||
continue
|
||||
if os.path.islink(link) or os.path.isfile(link):
|
||||
os.unlink(link)
|
||||
|
||||
@@ -10,7 +10,7 @@ free_name() {
|
||||
share() {
|
||||
local android=$HOME/Storage/$1 link=$HOME/$2 f
|
||||
[ -d "$android" ] && [ -w "$android" ] || return 0
|
||||
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
|
||||
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && [ -d "$link/." ] && return 0
|
||||
if [ -L "$link" ]; then
|
||||
rm -f "$link"
|
||||
elif [ -d "$link" ]; then
|
||||
|
||||
@@ -664,7 +664,7 @@ def data_dir(env):
|
||||
return DATA_DIR
|
||||
|
||||
|
||||
def guest_environment(fex, env):
|
||||
def guest_environment(fex, env, keep_compat=False):
|
||||
result = dict(env)
|
||||
data = data_dir(env)
|
||||
for directory in (CONFIG_DIR, data, CACHE_DIR):
|
||||
@@ -672,7 +672,7 @@ def guest_environment(fex, env):
|
||||
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
|
||||
result["FEX_APP_DATA_LOCATION"] = data + "/"
|
||||
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
|
||||
if result.get("STEAM_COMPAT_DATA_PATH"):
|
||||
if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat:
|
||||
short = data if data != DATA_DIR else "/tmp/fex"
|
||||
os.makedirs(short, exist_ok=True)
|
||||
result["STEAM_COMPAT_DATA_PATH"] = short
|
||||
@@ -682,6 +682,10 @@ def guest_environment(fex, env):
|
||||
if "aarch64" in result.get("GCONV_PATH", ""):
|
||||
result["GCONV_PATH"] = ""
|
||||
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
|
||||
if not result.get("COMPlus_INTERNAL_ThreadSuspendInjection"):
|
||||
if not result.get("DOTNET_INTERNAL_ThreadSuspendInjection"):
|
||||
result["DOTNET_INTERNAL_ThreadSuspendInjection"] = "0"
|
||||
result["COMPlus_INTERNAL_ThreadSuspendInjection"] = result["DOTNET_INTERNAL_ThreadSuspendInjection"]
|
||||
if fex["portable"]:
|
||||
result["FEX_PORTABLE"] = "1"
|
||||
else:
|
||||
@@ -746,9 +750,12 @@ def vulkan_thunk_loads(fex, folder):
|
||||
|
||||
|
||||
def required_runtime(program):
|
||||
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
|
||||
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
|
||||
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
|
||||
folder = os.path.dirname(program)
|
||||
for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"):
|
||||
match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "")
|
||||
if match and match.group(1) in RUNTIMES:
|
||||
return match.group(1)
|
||||
return SNIPER_APPID
|
||||
|
||||
|
||||
def resolve(program, env):
|
||||
@@ -757,7 +764,7 @@ def resolve(program, env):
|
||||
return shutil.which(program, path=env.get("PATH")) or program
|
||||
|
||||
|
||||
def launch(command, env, mode, decide=None):
|
||||
def launch(command, env, mode, decide=None, keep_compat=False):
|
||||
program = resolve(command[0], env)
|
||||
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
|
||||
if not use:
|
||||
@@ -765,7 +772,7 @@ def launch(command, env, mode, decide=None):
|
||||
fex = prepare(required_runtime(program))
|
||||
if fex is None:
|
||||
return 126
|
||||
guest = guest_environment(fex, env)
|
||||
guest = guest_environment(fex, env, keep_compat)
|
||||
x86_64 = elf_arch(program) != "i386"
|
||||
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
|
||||
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
|
||||
@@ -777,7 +784,7 @@ def launch(command, env, mode, decide=None):
|
||||
return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest)
|
||||
|
||||
|
||||
def game_environment(env, command):
|
||||
def game_environment(env, command, proton=None):
|
||||
try:
|
||||
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
|
||||
env = game_env["game_gpu"](env)
|
||||
@@ -796,7 +803,14 @@ def game_environment(env, command):
|
||||
config = json.load(source)
|
||||
except FileNotFoundError:
|
||||
config = {"version": 1}
|
||||
return game_env["apply_config"](env, config, str(app), fixes)
|
||||
env = game_env["apply_config"](env, config, str(app), fixes)
|
||||
if proton and len(proton) > 2 and proton[1] == "waitforexitandrun":
|
||||
logged = game_env["apply_game_debug_logs"](env, config)
|
||||
if logged is not env:
|
||||
say("game debug logs enabled for this launch")
|
||||
env = game_env["game_logs"](proton, logged, str(app))
|
||||
game_env["GAME_DEBUG"]["cap_proton_log"](env)
|
||||
return env
|
||||
except FileNotFoundError:
|
||||
return env
|
||||
except Exception as error:
|
||||
@@ -959,7 +973,7 @@ def parse_run(args):
|
||||
|
||||
def main(argv):
|
||||
if not argv:
|
||||
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
|
||||
say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status")
|
||||
return 2
|
||||
action, args = argv[0], list(argv[1:])
|
||||
if action == "steam":
|
||||
@@ -971,6 +985,10 @@ def main(argv):
|
||||
if not command:
|
||||
return 2
|
||||
return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto"))
|
||||
if action == "proton":
|
||||
if len(args) < 2:
|
||||
return 2
|
||||
return launch(args, game_environment(dict(os.environ), args[2:] or args, args), "on", keep_compat=True)
|
||||
if action == "run":
|
||||
try:
|
||||
mode, decide, command = parse_run(args)
|
||||
@@ -992,6 +1010,10 @@ def main(argv):
|
||||
return extract(args[0])
|
||||
if action == "prepare":
|
||||
return 0 if prepare() else 1
|
||||
if action == "update":
|
||||
with locked():
|
||||
update_own_fex()
|
||||
return 0
|
||||
if action == "status":
|
||||
with locked():
|
||||
status = describe(fex_install(), runtime_platform(), graphics_platform())
|
||||
|
||||
@@ -29,10 +29,14 @@ fex_install() {
|
||||
return 1
|
||||
fi
|
||||
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
|
||||
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
|
||||
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
|
||||
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
|
||||
done > "$tmp/stale"
|
||||
{
|
||||
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
|
||||
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
|
||||
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
|
||||
done
|
||||
f=usr/local/share/fex-emu/.droiddeck-patches
|
||||
if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi
|
||||
} > "$tmp/stale"
|
||||
mkdir "$tmp/old"
|
||||
while IFS= read -r f; do
|
||||
f=${f#./}
|
||||
|
||||
@@ -3,6 +3,7 @@ import contextlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -68,12 +69,57 @@ def apply_game_debug_logs(env, config=None, debug_dir=None):
|
||||
"PROTON_CRASH_REPORT_DIR": debug_dir,
|
||||
"DXVK_LOG_PATH": debug_dir,
|
||||
"DXVK_LOG_LEVEL": "debug",
|
||||
"VKD3D_DEBUG": "info",
|
||||
"VKD3D_DEBUG": "warn",
|
||||
"VKD3D_SHADER_DEBUG": "warn",
|
||||
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
# Proton appends its log through one inherited descriptor and never limits it; a game that loops on an
|
||||
# exception wrote 3 GB per run. Truncating keeps the first part and frees the rest, and Proton's
|
||||
# appends continue from the new end.
|
||||
PROTON_LOG_CAP = 64 * 1024 * 1024
|
||||
PROTON_LOG_CHECK_S = 1
|
||||
CAP_WATCH = r"""
|
||||
import os, stat, sys, time
|
||||
pid, limit, every, paths = int(sys.argv[1]), int(sys.argv[2]), float(sys.argv[3]), sys.argv[4:]
|
||||
while os.path.isdir("/proc/%d" % pid):
|
||||
for path in paths:
|
||||
try:
|
||||
info = os.lstat(path)
|
||||
if stat.S_ISREG(info.st_mode) and info.st_size > limit:
|
||||
os.truncate(path, limit)
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(every)
|
||||
"""
|
||||
|
||||
|
||||
def proton_log_paths(env):
|
||||
if env.get("PROTON_LOG", "0") in ("", "0"):
|
||||
return []
|
||||
folder = env.get("PROTON_LOG_DIR") or env.get("HOME") or os.environ.get("HOME") or "/root"
|
||||
paths = [os.path.join(folder, "steam-proton.log")]
|
||||
if env.get("SteamGameId"):
|
||||
paths.insert(0, os.path.join(folder, "steam-%s.log" % env["SteamGameId"]))
|
||||
return paths
|
||||
|
||||
|
||||
def cap_proton_log(env, pid=None, limit=PROTON_LOG_CAP, every=PROTON_LOG_CHECK_S, popen=subprocess.Popen):
|
||||
"""Keep Proton's log under `limit` bytes while process `pid` (this launcher, which becomes Proton) runs."""
|
||||
paths = proton_log_paths(env)
|
||||
if not paths:
|
||||
return None
|
||||
try:
|
||||
return popen([sys.executable, "-c", CAP_WATCH, str(pid or os.getpid()), str(limit), str(every)] + paths,
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: Proton log size limit unavailable (%s)" % error, file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def capped_log(path, limit, mirror=False):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
handle = open(path, "wb")
|
||||
|
||||
@@ -13,9 +13,10 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as ElementTree
|
||||
|
||||
GAME_PREFIX = "DROIDDECK_GAME_"
|
||||
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
|
||||
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE")
|
||||
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
|
||||
SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
|
||||
@@ -66,6 +67,93 @@ DOTNET_FEX = {
|
||||
"FEX_HALFBARRIERTSOENABLED": "1",
|
||||
"FEX_X87REDUCEDPRECISION": "0",
|
||||
}
|
||||
STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0")
|
||||
# Microsoft's original Xbox releases for PC run its emulator (Emu.exe). The switches turn on fixes in the builds of
|
||||
# DroidDeck-Bionic's Wine, FEX and VKD3D-Proton made for it, each off by default: Wine delivers the Windows 11 special
|
||||
# APCs the emulator interrupts its CPU threads with; FEX keeps the x87 state across those interrupts, checks for one in
|
||||
# a loop that branches back into its own block, and maps an image without a lock order that deadlocks; Wine gives the
|
||||
# boot video's types a display aperture and reports a 0 timer resolution (DXVK's vblank wait otherwise spins a core);
|
||||
# VKD3D-Proton presents frames DXVK drew through D3D11On12 and maps the packed 4:2:2 video formats. FEX keeps
|
||||
# DOTNET_FEX (the emulator's menu is .NET) without vector and memcpy TSO and with reduced x87 precision: on an
|
||||
# Adreno 750 the emulator's menus ran at ~58 fps instead of ~35.
|
||||
XBOX_BACK_COMPAT_IDENTITY = "xbox360backwardcompatibil"
|
||||
XBOX_BACK_COMPAT_ENV = dict(
|
||||
DOTNET_FEX,
|
||||
FEX_VECTORTSOENABLED="0",
|
||||
FEX_MEMCPYSETTSOENABLED="0",
|
||||
FEX_X87REDUCEDPRECISION="1",
|
||||
WINE_SPECIAL_APC_INTERRUPT="1",
|
||||
FEX_SYNCX87CONTEXT="1",
|
||||
FEX_LOOPSUSPENDCHECK="1",
|
||||
FEX_SAFEIMAGEMAP="1",
|
||||
WINE_MF_DISPLAY_APERTURE="1",
|
||||
WINE_PRECISE_SLEEP="1",
|
||||
VKD3D_INTEROP_PRESENT="1",
|
||||
VKD3D_PACKED_422="1",
|
||||
)
|
||||
PSPC_SDK_FILES = {"install_pspc_sdk_runtime.bat", "pspcsdkruntimeinstaller.msi", "pspcsdkruntimemanager.msi"}
|
||||
# Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders
|
||||
# from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30.
|
||||
INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj")
|
||||
INNO_RESOURCE_LIMIT = 4 << 20
|
||||
|
||||
|
||||
def is_inno_setup(path):
|
||||
try:
|
||||
with open(path, "rb") as exe:
|
||||
head = exe.read(4096)
|
||||
if head[:2] != b"MZ":
|
||||
return False
|
||||
if head[0x30:0x34] == b"Inno":
|
||||
return True
|
||||
pe = int.from_bytes(head[0x3C:0x40], "little")
|
||||
if head[pe:pe + 4] != b"PE\0\0" or int.from_bytes(head[pe + 4:pe + 6], "little") != 0x14C:
|
||||
return False
|
||||
count = int.from_bytes(head[pe + 6:pe + 8], "little")
|
||||
table = pe + 24 + int.from_bytes(head[pe + 20:pe + 22], "little")
|
||||
for entry in range(table, table + 40 * count, 40):
|
||||
if head[entry:entry + 8].rstrip(b"\0") == b".rsrc":
|
||||
exe.seek(int.from_bytes(head[entry + 20:entry + 24], "little"))
|
||||
size = int.from_bytes(head[entry + 16:entry + 20], "little")
|
||||
resources = exe.read(min(size, INNO_RESOURCE_LIMIT))
|
||||
return any(marker in resources for marker in INNO_LOADER_IDS)
|
||||
except OSError:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
STORE_LAUNCHER = ".droiddeck-launch.bat"
|
||||
STORE_SIDECAR = ".droiddeck-store.json"
|
||||
|
||||
|
||||
def store_game_exe(exe):
|
||||
if os.path.basename(exe).lower() != STORE_LAUNCHER:
|
||||
return exe
|
||||
folder = os.path.dirname(exe)
|
||||
try:
|
||||
with open(os.path.join(folder, STORE_SIDECAR), encoding="utf-8") as source:
|
||||
sidecar = json.load(source)
|
||||
except (OSError, ValueError):
|
||||
return exe
|
||||
target = sidecar.get("exe") if isinstance(sidecar, dict) else None
|
||||
if not isinstance(target, str) or not target.strip() or "\0" in target:
|
||||
return exe
|
||||
normalized = target.replace("\\", "/")
|
||||
if ":" in normalized or normalized.startswith("/") or ".." in normalized.split("/"):
|
||||
return exe
|
||||
relative = os.path.normpath(normalized)
|
||||
if os.path.isabs(relative) or relative in (".", "..") or relative.startswith(".." + os.sep):
|
||||
return exe
|
||||
candidate = os.path.join(folder, relative)
|
||||
if not os.path.isfile(candidate):
|
||||
return exe
|
||||
root = os.path.realpath(folder)
|
||||
try:
|
||||
if os.path.commonpath((root, os.path.realpath(candidate))) != root:
|
||||
return exe
|
||||
except ValueError:
|
||||
return exe
|
||||
return candidate
|
||||
|
||||
|
||||
def game_files(exe):
|
||||
@@ -86,14 +174,50 @@ def game_files(exe):
|
||||
return names
|
||||
|
||||
|
||||
def unreal_binary_files(exe):
|
||||
project = os.path.splitext(os.path.basename(exe))[0]
|
||||
try:
|
||||
with os.scandir(os.path.join(os.path.dirname(exe), project, "Binaries", "Win64")) as folder:
|
||||
return {entry.name.lower() for entry in folder}
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def xbox_identity(exe):
|
||||
"""The identity name in the MicrosoftGame.config of the Xbox package the executable is in, or ""."""
|
||||
folder = os.path.dirname(exe)
|
||||
for _ in range(4):
|
||||
# The Xbox store accepts the file name in any case (XboxManifest.read).
|
||||
name = "MicrosoftGame.config"
|
||||
if not os.path.isfile(os.path.join(folder, name)):
|
||||
try:
|
||||
name = next((entry for entry in sorted(os.listdir(folder)) if entry.lower() == "microsoftgame.config"), name)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
with open(os.path.join(folder, name), "rb") as source:
|
||||
root = ElementTree.fromstring(source.read(1 << 20))
|
||||
except (OSError, ElementTree.ParseError):
|
||||
root = None
|
||||
if root is not None:
|
||||
return next((node.get("Name", "") for node in root.iter() if node.tag.rsplit("}", 1)[-1] == "Identity"), "")
|
||||
parent = os.path.dirname(folder)
|
||||
if parent == folder:
|
||||
break
|
||||
folder = parent
|
||||
return ""
|
||||
|
||||
|
||||
class Game:
|
||||
|
||||
def __init__(self, exe, args, app_id=""):
|
||||
exe = store_game_exe(exe)
|
||||
self.exe = exe
|
||||
self.args = args
|
||||
self.app_id = app_id
|
||||
self.stem = os.path.splitext(os.path.basename(exe))[0].lower()
|
||||
self.files = game_files(exe)
|
||||
self.xbox_back_compat = os.path.isabs(exe) and xbox_identity(exe).lower().startswith(XBOX_BACK_COMPAT_IDENTITY)
|
||||
|
||||
def has_arg(self, name):
|
||||
return any(a == name or a.startswith(name + "=") for a in self.args)
|
||||
@@ -113,10 +237,16 @@ def is_godot(game):
|
||||
|
||||
@fix
|
||||
def dotnet_memory_ordering(game):
|
||||
if "coreclr.dll" in game.files:
|
||||
if "coreclr.dll" in game.files and not game.xbox_back_compat:
|
||||
return DOTNET_FEX, [], ".NET runtime: FEX with full TSO"
|
||||
|
||||
|
||||
@fix
|
||||
def xbox_back_compat(game):
|
||||
if game.xbox_back_compat:
|
||||
return XBOX_BACK_COMPAT_ENV, [], "Original Xbox game: emulator fixes on, FEX with load/store TSO and reduced x87 precision"
|
||||
|
||||
|
||||
@fix
|
||||
def unity_memory_ordering(game):
|
||||
if {"unityplayer.so", "gameassembly.so", "unityplayer.dll"} & game.files:
|
||||
@@ -185,12 +315,24 @@ def arkham_city_x87(game):
|
||||
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
|
||||
|
||||
|
||||
@fix
|
||||
def playstation_pc_sdk_x87(game):
|
||||
if PSPC_SDK_FILES & (game.files | unreal_binary_files(game.exe)):
|
||||
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "PlayStation PC SDK: FEX with full x87 precision"
|
||||
|
||||
|
||||
@fix
|
||||
def split_second_x87_fip(game):
|
||||
if game.app_id == "297860" or game.stem == "splitsecond":
|
||||
return {"FEX_JITFEATURES": "enablex87fip"}, [], "Split/Second: FEX x87 FIP emulation on (its SecuROM stops with error 8016 without it)"
|
||||
|
||||
|
||||
@fix
|
||||
def inno_setup_stability(game):
|
||||
if is_inno_setup(game.exe):
|
||||
return STABILITY_FEX, [], "Inno Setup installer: FEX Stability settings (under Performance + TSO the 32-bit setup stub corrupts its own paths)"
|
||||
|
||||
|
||||
@fix
|
||||
def doom_2016_swapchain_images(game):
|
||||
if "doomx64vk.exe" in game.files and game.stem in ("doomx64", "doomx64vk"):
|
||||
@@ -273,7 +415,7 @@ def with_system_settings(text, settings):
|
||||
|
||||
# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch.
|
||||
def dragon_quest_monsters_4_mesh_detail(exe, env):
|
||||
project = Path(exe).stem.split("-", 1)[0]
|
||||
project = Path(store_game_exe(exe)).stem.split("-", 1)[0]
|
||||
if not project.lower().startswith("dragonquestmonsters4"):
|
||||
return
|
||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||
@@ -398,7 +540,7 @@ def zomboid_rewrite(node):
|
||||
def project_zomboid_jvm(command):
|
||||
if len(command) <= 2:
|
||||
return
|
||||
exe = Path(command[2])
|
||||
exe = Path(store_game_exe(command[2]))
|
||||
if not exe.stem.lower().startswith("projectzomboid"):
|
||||
return
|
||||
settings = exe.with_suffix(".json")
|
||||
@@ -721,12 +863,15 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
|
||||
|
||||
def render_path_defaults(command, env):
|
||||
if len(command) < 3 or command[1] != "waitforexitandrun" or Path(command[2]).name.lower() != "spintires.exe":
|
||||
if len(command) < 3 or command[1] != "waitforexitandrun":
|
||||
return None
|
||||
exe = Path(store_game_exe(command[2]))
|
||||
if exe.name.lower() != "spintires.exe":
|
||||
return None
|
||||
own = env.get("DXVK_CONFIG", "")
|
||||
if re.search(r"(?:^|;)\s*dxvk\.tilerMode\s*=", own) or env.get("DXVK_CONFIG_FILE"):
|
||||
return None
|
||||
if Path("dxvk.conf").is_file() or Path(command[2]).with_name("dxvk.conf").is_file():
|
||||
if Path("dxvk.conf").is_file() or exe.with_name("dxvk.conf").is_file():
|
||||
return None
|
||||
driver = env.get("VK_DRIVER_FILES", env.get("VK_ICD_FILENAMES", ""))
|
||||
if Path(driver).parent.name != "DD-Turnip_v0.4.0":
|
||||
@@ -1290,7 +1435,7 @@ def dirt_ws2_wanted(command, env):
|
||||
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
if len(command) < 3 or not prefix or not os.path.isfile(DIRT_WS2):
|
||||
return None
|
||||
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(command[2]))[0].lower())
|
||||
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(store_game_exe(command[2])))[0].lower())
|
||||
if not game or not dirt_telemetry_on(prefix, game) or proton_has_dirt_fix(command[0]):
|
||||
return None
|
||||
return prefix if os.path.lexists(prefix_ws2(prefix)) else None
|
||||
@@ -1347,7 +1492,7 @@ def ego_core_plan(command, env):
|
||||
count = windows_core_count(env)
|
||||
if not count or len(command) < 3:
|
||||
return None
|
||||
folder = Path(command[2]).parent
|
||||
folder = Path(store_game_exe(command[2])).parent
|
||||
path = folder / EGO_RESTRICTIONS
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
@@ -1513,6 +1658,16 @@ def system_graphics_launch(command, env):
|
||||
return [str(wrapper), *command], result
|
||||
|
||||
|
||||
AUDIO_STREAMS_PROBE = (
|
||||
'folder=$1; launch=$2; shift 2; n=0; '
|
||||
'for t in "$@"; do '
|
||||
'while [ "$n" -lt "$t" ]; do kill -0 "$launch" 2>/dev/null || exit 0; sleep 1; n=$((n + 1)); done; '
|
||||
'kill -0 "$launch" 2>/dev/null || exit 0; '
|
||||
'{ echo "== $(date +%T)"; pactl list sink-inputs 2>&1 | head -80; } >> "$folder/audio-streams.txt"; '
|
||||
'done'
|
||||
)
|
||||
|
||||
|
||||
def game_logs(command, env, app_id, now=None):
|
||||
"""Detailed graphics logs for one game launch, in the session's log folder: Proton's own log,
|
||||
DXVK's and vkd3d-proton's, and the Vulkan driver's startup messages. The app turns this on
|
||||
@@ -1558,8 +1713,7 @@ def game_logs(command, env, app_id, now=None):
|
||||
pass
|
||||
# Whether the game's sound reaches PulseAudio: the streams 20 s and 60 s in, without waiting.
|
||||
try:
|
||||
subprocess.Popen(["sh", "-c", 'for t in 20 40; do sleep $t; { echo "== $(date +%T)"; '
|
||||
'pactl list sink-inputs 2>&1 | head -80; } >> "$1/audio-streams.txt"; done', "audio", str(folder)],
|
||||
subprocess.Popen(["sh", "-c", AUDIO_STREAMS_PROBE, "audio", str(folder), str(os.getpid()), "20", "60"],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
except OSError:
|
||||
@@ -1676,14 +1830,26 @@ def main():
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
else:
|
||||
# An installer started with the run verb gets the same Stability settings as one started with
|
||||
# waitforexitandrun; explicit game settings still win over them in apply_config.
|
||||
installer = {}
|
||||
if len(command) > 2 and command[1] == "run" and is_inno_setup(command[2]):
|
||||
installer = dict(STABILITY_FEX)
|
||||
print("droiddeck-game-env: Inno Setup installer: FEX Stability settings", file=sys.stderr)
|
||||
path = Path.home() / ".config/droiddeck/game-environment.json"
|
||||
try:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
config = json.load(source)
|
||||
env = apply_config(env, sync_config(config, app_id), app_id)
|
||||
synced = sync_config(config, app_id)
|
||||
if installer:
|
||||
# A FEX preset chosen for the game itself still wins, as on every other launch path.
|
||||
game = config.get("games", {}).get(app_id, {})
|
||||
synced["games"][app_id].update({k: v for k, v in game.items() if k in STABILITY_FEX})
|
||||
env = apply_config(env, synced, app_id, installer)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
env = dict(env, **installer)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
env = dict(env, **installer)
|
||||
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
if waiting:
|
||||
before_debug = env
|
||||
@@ -1748,6 +1914,8 @@ def main():
|
||||
except OSError as undo:
|
||||
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); Wine uses its own copy "
|
||||
"and the next launch puts the file back" % undo, file=sys.stderr)
|
||||
if len(command) > 1 and command[1] == "waitforexitandrun":
|
||||
GAME_DEBUG["cap_proton_log"](env)
|
||||
sync = load_sync()
|
||||
launch, launch_env = select_sync(command, env, sync)
|
||||
if launch[0] != command[0]:
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
# Appends stdin to a session log up to a byte cap, then reads and drops the rest, so that the session
|
||||
# writing into it never gets SIGPIPE. A program of its own, rather than a subshell of the session, so
|
||||
# that the native hook can start it outside the app's counted child processes.
|
||||
# usage: droiddeck-log-writer FILE CAP_BYTES
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
"$dd" of="$1" oflag=append conv=notrunc iflag=count_bytes count="$2" bs=65536 status=none
|
||||
exec cat >/dev/null
|
||||
@@ -7,6 +7,7 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import gi
|
||||
@@ -20,6 +21,10 @@ INTERFACE = NAME + ".Manager"
|
||||
UPOWER = "org.freedesktop.UPower"
|
||||
UPOWER_ROOT = "/org/freedesktop/UPower"
|
||||
NATIVE_PREPARE_MS = 1500
|
||||
STEAM_PREPARE_WAIT = 1.95
|
||||
STEAM_PREPARE_START_MS = 850
|
||||
STEAM_WAKE_WAIT = 1.25
|
||||
STEAM_WAKE_RETRY_DELAYS = (0, 0.2, 0.5)
|
||||
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
|
||||
ASLEEP_WAIT = 6
|
||||
INHIBIT_WAIT = 12
|
||||
@@ -55,6 +60,10 @@ class LoginManager:
|
||||
self.native_ready = self.directory / "steam-native-ready"
|
||||
self.pending = None
|
||||
self.pending_idle = False
|
||||
self.native_preparation = None
|
||||
self.native_signaled = False
|
||||
self.native_order = None
|
||||
self.native_wake_work = None
|
||||
self.waiting = set()
|
||||
self.timeout = None
|
||||
self.preparation = None
|
||||
@@ -90,6 +99,7 @@ class LoginManager:
|
||||
if self.pending:
|
||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||
return
|
||||
self.cancel_native_wake()
|
||||
self.pending = uuid.uuid4().hex
|
||||
self.pending_idle = False
|
||||
self.notify(True)
|
||||
@@ -133,19 +143,42 @@ class LoginManager:
|
||||
return
|
||||
self.pending = token
|
||||
self.pending_idle = words[1:] == ["idle"]
|
||||
# Idle requests never take ownership of Steam preparation. Preserve any
|
||||
# earlier wake delivery so an in-flight prepare cannot outlive its wake.
|
||||
if not self.pending_idle:
|
||||
self.cancel_native_wake()
|
||||
self.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
|
||||
self.hold(token, self.prepared, token, "hold")
|
||||
if self.pending_idle:
|
||||
return
|
||||
self.native_preparation = "pending"
|
||||
order = self.native_order = str(time.monotonic_ns())
|
||||
deadline = int(time.time() * 1000) + STEAM_PREPARE_START_MS
|
||||
|
||||
def prepare():
|
||||
_, out = agent("--steam-prepare-native-suspend", token, str(deadline), order, timeout=STEAM_PREPARE_WAIT)
|
||||
GLib.idle_add(self.steam_prepared, token, out.strip() or "uncertain")
|
||||
|
||||
threading.Thread(target=prepare, daemon=True).start()
|
||||
|
||||
def steam_prepared(self, token, outcome):
|
||||
self.check_state()
|
||||
if self.pending != token:
|
||||
return False
|
||||
self.native_preparation = outcome
|
||||
self.native_signaled = True
|
||||
print("== login1: Steam native preparation " + outcome, flush=True)
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.prepare_after_flush, token)
|
||||
return False
|
||||
|
||||
def prepare_after_flush(self, connection, result, token):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
except GLib.Error as error:
|
||||
print("== login1: cannot prepare native sleep: " + str(error), file=sys.stderr)
|
||||
self.resume()
|
||||
if self.pending == token:
|
||||
self.resume()
|
||||
return
|
||||
self.check_state()
|
||||
if self.pending == token:
|
||||
@@ -269,19 +302,49 @@ class LoginManager:
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.finish_recovery, None)
|
||||
return
|
||||
token = self.pending
|
||||
idle = self.pending_idle
|
||||
native = self.native_preparation
|
||||
signaled = self.native_signaled
|
||||
order = self.native_order
|
||||
self.native_order = None
|
||||
self.pending = None
|
||||
self.pending_idle = False
|
||||
self.native_preparation = None
|
||||
self.native_signaled = False
|
||||
if self.preparation is not None:
|
||||
GLib.source_remove(self.preparation)
|
||||
self.preparation = None
|
||||
if self.timeout is not None:
|
||||
GLib.source_remove(self.timeout)
|
||||
self.timeout = None
|
||||
if not idle:
|
||||
if not idle and (native is None or signaled):
|
||||
self.notify(False)
|
||||
if native in ("pending", "uncertain", "coalesced") or native == "prepared" and not signaled:
|
||||
phase = "uncertain" if signaled else "unsignaled"
|
||||
self.deliver_native_wake(token, phase, order)
|
||||
self.release_later()
|
||||
|
||||
def cancel_native_wake(self):
|
||||
if self.native_wake_work is not None:
|
||||
self.native_wake_work.set()
|
||||
self.native_wake_work = None
|
||||
|
||||
def deliver_native_wake(self, token, phase, order):
|
||||
work = self.native_wake_work = threading.Event()
|
||||
|
||||
def deliver():
|
||||
for delay in STEAM_WAKE_RETRY_DELAYS:
|
||||
if work.wait(delay):
|
||||
return
|
||||
code, outcome = agent("--steam-wake-native-suspend", token, phase, order, timeout=STEAM_WAKE_WAIT)
|
||||
if code == 0 and outcome.strip() in ("ack", "miss"):
|
||||
return
|
||||
if not work.is_set():
|
||||
print("== login1: Steam native wake recovery not acknowledged", file=sys.stderr, flush=True)
|
||||
|
||||
threading.Thread(target=deliver, daemon=True).start()
|
||||
|
||||
def finish_recovery(self, connection, result, _data):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
|
||||
@@ -51,6 +51,11 @@ SYSTEM_PROPERTIES = {
|
||||
"UILevel": "2", "INSTALLLEVEL": "1", "ProgramFilesFolder": None, "VersionMsi": "5.00",
|
||||
}
|
||||
|
||||
NATIVE_ARCHITECTURE = {"intel": "x86", "x64": "AMD64", "amd64": "AMD64", "arm64": "ARM64"}
|
||||
ARCHITECTURE_VALUE = ("system\\currentcontrolset\\control\\session manager\\environment", "processor_architecture")
|
||||
REG_LOCATOR_RAW = 2
|
||||
REG_ROOT_LOCAL_MACHINE = 2
|
||||
|
||||
COMPONENT_64BIT = 0x100
|
||||
FILE_NONCOMPRESSED = 0x2000
|
||||
SET_PROPERTY, SET_DIRECTORY, ERROR_ACTION = 51, 35, 19
|
||||
@@ -410,6 +415,18 @@ class Installer:
|
||||
return text
|
||||
|
||||
|
||||
def run_app_search(self):
|
||||
locators = {row["Signature_"]: row for row in self.pkg.table("RegLocator")}
|
||||
architecture = NATIVE_ARCHITECTURE.get(self.platform)
|
||||
for row in self.pkg.table("AppSearch"):
|
||||
locator = locators.get(row["Signature_"])
|
||||
if locator is None or architecture is None:
|
||||
continue
|
||||
if to_int(locator.get("Root")) != REG_ROOT_LOCAL_MACHINE or to_int(locator.get("Type")) & 0xF != REG_LOCATOR_RAW:
|
||||
continue
|
||||
if (locator.get("Key", "").rstrip("\\").casefold(), locator.get("Name", "").casefold()) == ARCHITECTURE_VALUE:
|
||||
self.props[row["Property"]] = architecture
|
||||
|
||||
def run_set_actions(self):
|
||||
actions = {row["Action"]: row for row in self.pkg.table("CustomAction")}
|
||||
sequence = {}
|
||||
@@ -704,6 +721,7 @@ class Installer:
|
||||
|
||||
def install(self):
|
||||
self.span.report(0.0, "reading %s" % (self.pkg.summary.get("subject") or Path(self.pkg.path).name))
|
||||
self.run_app_search()
|
||||
self.run_set_actions()
|
||||
self.select()
|
||||
with tempfile.TemporaryDirectory(dir=str(self.out.parent), prefix=".msi-") as work:
|
||||
@@ -865,13 +883,9 @@ def choose_packages(found, root):
|
||||
names = [entry.name.lower() for entry in top]
|
||||
if any("full" in name for name in names) and any("_core" in name or "_extended" in name for name in names):
|
||||
top = [entry for entry in top if not ("_core" in entry.name.lower() or "_extended" in entry.name.lower())]
|
||||
chosen = []
|
||||
for entry in top:
|
||||
template = Package(entry).summary.get("template", "").split(";")[0].strip().lower()
|
||||
if template in SKIP_PLATFORMS:
|
||||
continue
|
||||
chosen.append(entry)
|
||||
return chosen
|
||||
platforms = [(entry, Package(entry).summary.get("template", "").split(";")[0].strip().lower()) for entry in top]
|
||||
native = [entry for entry, template in platforms if template not in SKIP_PLATFORMS]
|
||||
return native or top
|
||||
|
||||
|
||||
def install_wrapper(path, out):
|
||||
@@ -901,6 +915,8 @@ def install_wrapper(path, out):
|
||||
for note in result["notes"]:
|
||||
if note not in total["notes"]:
|
||||
total["notes"].append(note)
|
||||
if not total["packages"]:
|
||||
raise MsiError("%s installs nothing here" % path.name)
|
||||
total["how"] = how
|
||||
return total
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import json
|
||||
import os
|
||||
LAUNCH_DIR_FILE = "/tmp/droiddeck-browser/launch-dir"
|
||||
STEAM = "/usr/local/bin/droiddeck-steam-shim"
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -17,6 +18,13 @@ def hand_over(url, launch_dir):
|
||||
os.rename(tmp, req / (rid + ".json"))
|
||||
|
||||
|
||||
def same_file(a, b):
|
||||
try:
|
||||
return os.path.samefile(a, b)
|
||||
except OSError:
|
||||
return os.path.realpath(a) == os.path.realpath(b)
|
||||
|
||||
|
||||
def where(url):
|
||||
from urllib.parse import urlsplit
|
||||
try:
|
||||
@@ -40,10 +48,11 @@ def main(argv):
|
||||
if url.startswith(("https://", "http://")) and launch_dir:
|
||||
hand_over(url, launch_dir)
|
||||
return 0
|
||||
here = os.path.dirname(os.path.realpath(sys.argv[0]))
|
||||
if url.startswith("steam://") and os.access(STEAM, os.X_OK):
|
||||
os.execv(STEAM, [STEAM, url])
|
||||
for d in os.environ.get("PATH", "").split(os.pathsep):
|
||||
candidate = os.path.join(d, "xdg-open")
|
||||
if os.access(candidate, os.X_OK) and os.path.realpath(candidate) != os.path.realpath(__file__) and os.path.abspath(d) != here:
|
||||
if os.access(candidate, os.X_OK) and not same_file(candidate, __file__):
|
||||
os.execv(candidate, [candidate] + argv)
|
||||
return 1
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/usr/bin/python3
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config"))
|
||||
@@ -1048,8 +1050,19 @@ def switch_emulators():
|
||||
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
|
||||
|
||||
|
||||
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
|
||||
try:
|
||||
step()
|
||||
except Exception as e:
|
||||
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")
|
||||
def run_all():
|
||||
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
|
||||
try:
|
||||
step()
|
||||
except Exception as e:
|
||||
print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True)
|
||||
|
||||
|
||||
# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process
|
||||
# for the whole desktop session rather than a shell loop starting a new one each time.
|
||||
sys.stdout.reconfigure(line_buffering=True)
|
||||
run_all()
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--every":
|
||||
while True:
|
||||
time.sleep(float(sys.argv[2]))
|
||||
run_all()
|
||||
@@ -100,6 +100,31 @@ def tools(root):
|
||||
return found
|
||||
|
||||
|
||||
def startable(root, available):
|
||||
c = compat()
|
||||
sources = dict(c["OWN_TOOLS"])
|
||||
return {name: tool for name, tool in available.items()
|
||||
if name not in sources or c["find_source"](root, sources[name], runnable=True)}
|
||||
|
||||
|
||||
def missing_proton(root):
|
||||
c = compat()
|
||||
for library in c["libraries"](root):
|
||||
text = read_text(os.path.join(library, "steamapps", "appmanifest_%s.acf" % c["PROTON_ARM64_APPID"]))
|
||||
if text is None:
|
||||
continue
|
||||
tokens = c["tokenize"](text)
|
||||
sizes = tuple(c["manifest_number"](tokens, key) // 2 ** 20 for key in ("BytesDownloaded", "BytesToDownload", "BytesToStage"))
|
||||
try:
|
||||
st = os.statvfs(library)
|
||||
free = "%d MB" % (st.f_bavail * st.f_frsize // 2 ** 20)
|
||||
except OSError:
|
||||
free = "unknown"
|
||||
return ("%s has not finished downloading in Steam (%d of %d MB downloaded, %d MB to unpack, %s free in %s); "
|
||||
"keep Steam open until it finishes" % ((c["SOURCES"][0],) + sizes + (free, library)))
|
||||
return "no Proton is installed yet; open Steam and keep it open until it has downloaded %s" % c["SOURCES"][0]
|
||||
|
||||
|
||||
def state_default():
|
||||
try:
|
||||
with open(STATE, encoding="utf-8") as f:
|
||||
@@ -130,6 +155,8 @@ def choose_tool(appid, current, available):
|
||||
for name in (default, c["TOOL"], c["TOOL_11"]):
|
||||
if name in available:
|
||||
return name, "the default ARM64 Proton"
|
||||
if newest:
|
||||
return newest, "the newest DroidDeck-Proton"
|
||||
return (sorted(available)[0], "the only one installed") if available else (None, None)
|
||||
|
||||
|
||||
@@ -515,10 +542,10 @@ def main(argv):
|
||||
target = fixed(program, root, prefix, compatdata)
|
||||
else:
|
||||
target = locate(program, root)
|
||||
available = tools(root)
|
||||
available = startable(root, tools(root))
|
||||
name, why = choose_tool(target.appid, mapping(root), available)
|
||||
if name is None:
|
||||
say("no Proton is installed yet; open Steam once and it is downloaded for you")
|
||||
say(missing_proton(root))
|
||||
return 69
|
||||
folder, command = available[name]
|
||||
os.makedirs(target.compatdata, exist_ok=True)
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/python3
|
||||
# Relays the app to Steam's DevTools port, which only answers clients inside the guest, while the bottom screen
|
||||
# shows Steam's quick access menu. Only requests carrying the secret printed at start reach DevTools, and only for
|
||||
# the target list and page sockets, so other local apps cannot use the relay to reach Steam.
|
||||
# droiddeck-qam-relay start <devtools port> prints the relay port and its secret
|
||||
# droiddeck-qam-relay stop [<relay port>] stops the relay, or only the one on that port
|
||||
|
||||
import contextlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
fcntl = None
|
||||
|
||||
FLAG = "/tmp/.dd-qam-relay"
|
||||
INTERVAL = 0.5
|
||||
MAX_SECONDS = 6 * 3600
|
||||
IDLE_SECONDS = 30
|
||||
HEAD_SECONDS = 3
|
||||
UNVERIFIED = threading.BoundedSemaphore(8)
|
||||
ALLOWED = re.compile(r"^/(json|json/list|devtools/page/[A-Za-z0-9-]+)$")
|
||||
|
||||
|
||||
class Activity:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.open = 0
|
||||
self.last = time.monotonic()
|
||||
|
||||
def change(self, delta):
|
||||
with self.lock:
|
||||
self.open += delta
|
||||
self.last = time.monotonic()
|
||||
|
||||
def idle(self):
|
||||
with self.lock:
|
||||
return self.open == 0 and time.monotonic() - self.last > IDLE_SECONDS
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def flag_lock():
|
||||
"""Serializes reading, removing and publishing the owner record, so a stop cannot remove a newer relay's record."""
|
||||
if fcntl is None:
|
||||
yield
|
||||
return
|
||||
fd = os.open(FLAG + ".lock", os.O_CREAT | os.O_RDWR, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
yield
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def owner():
|
||||
try:
|
||||
with open(FLAG) as f:
|
||||
return f.read().split()
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def pipe(src, dst):
|
||||
try:
|
||||
while True:
|
||||
data = src.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
dst.sendall(data)
|
||||
except OSError:
|
||||
pass
|
||||
for s in (src, dst):
|
||||
try:
|
||||
s.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def rewrite(head, token):
|
||||
"""Returns the request with the secret removed from its path, or None when it is not an allowed request."""
|
||||
line, sep, rest = head.partition(b"\r\n")
|
||||
parts = line.split(b" ")
|
||||
if not sep or len(parts) != 3 or parts[0] != b"GET" or not parts[2].startswith(b"HTTP/1."):
|
||||
return None
|
||||
prefix = b"/" + token.encode()
|
||||
path = parts[1]
|
||||
if not hmac.compare_digest(path[:len(prefix)], prefix) or not ALLOWED.match(path[len(prefix):].decode("ascii", "replace")):
|
||||
return None
|
||||
return b"GET " + path[len(prefix):] + b" " + parts[2] + sep + rest
|
||||
|
||||
|
||||
def handle(client, devtools_port, token, activity):
|
||||
activity.change(1)
|
||||
verifying = True
|
||||
try:
|
||||
deadline = time.monotonic() + HEAD_SECONDS
|
||||
head = b""
|
||||
while b"\r\n" not in head and len(head) < 4096:
|
||||
left = deadline - time.monotonic()
|
||||
if left <= 0:
|
||||
return
|
||||
client.settimeout(left)
|
||||
data = client.recv(4096)
|
||||
if not data:
|
||||
break
|
||||
head += data
|
||||
request = rewrite(head, token)
|
||||
UNVERIFIED.release()
|
||||
verifying = False
|
||||
if request is None:
|
||||
client.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
return
|
||||
client.settimeout(None)
|
||||
upstream = socket.create_connection(("127.0.0.1", devtools_port), 3)
|
||||
# The connect deadline must not end a quiet DevTools socket.
|
||||
upstream.settimeout(None)
|
||||
upstream.sendall(request)
|
||||
back = threading.Thread(target=pipe, args=(upstream, client), daemon=True)
|
||||
back.start()
|
||||
pipe(client, upstream)
|
||||
back.join()
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
if verifying:
|
||||
UNVERIFIED.release()
|
||||
client.close()
|
||||
activity.change(-1)
|
||||
|
||||
|
||||
def relay(server, devtools_port, token, activity):
|
||||
while True:
|
||||
try:
|
||||
client, _ = server.accept()
|
||||
except OSError:
|
||||
return
|
||||
# Connections that have not shown the secret yet are capped, so they cannot use up threads.
|
||||
if not UNVERIFIED.acquire(blocking=False):
|
||||
client.close()
|
||||
continue
|
||||
threading.Thread(target=handle, args=(client, devtools_port, token, activity), daemon=True).start()
|
||||
|
||||
|
||||
def serve(server, devtools_port, me, token):
|
||||
activity = Activity()
|
||||
threading.Thread(target=relay, args=(server, devtools_port, token, activity), daemon=True).start()
|
||||
started = time.monotonic()
|
||||
while owner()[:1] == [me] and time.monotonic() - started < MAX_SECONDS and not activity.idle():
|
||||
time.sleep(INTERVAL)
|
||||
server.close()
|
||||
|
||||
|
||||
def main():
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if command == "stop" and len(sys.argv) in (2, 3):
|
||||
with flag_lock():
|
||||
if len(sys.argv) == 3 and owner()[1:] != [sys.argv[2]]:
|
||||
return 0
|
||||
try:
|
||||
os.unlink(FLAG)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return 0
|
||||
if command != "start" or len(sys.argv) != 3:
|
||||
print("usage: droiddeck-qam-relay start <devtools port> | stop [<relay port>]", file=sys.stderr)
|
||||
return 2
|
||||
devtools_port = int(sys.argv[2])
|
||||
server = socket.socket()
|
||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
server.bind(("127.0.0.1", 0))
|
||||
server.listen(4)
|
||||
token = secrets.token_hex(16)
|
||||
print(server.getsockname()[1], token, flush=True)
|
||||
if os.fork():
|
||||
return 0
|
||||
os.setsid()
|
||||
me = str(os.getpid())
|
||||
with flag_lock(), open(FLAG, "w") as f:
|
||||
f.write("%s %d" % (me, server.getsockname()[1]))
|
||||
devnull = os.open(os.devnull, os.O_RDWR)
|
||||
for fd in (0, 1, 2):
|
||||
os.dup2(devnull, fd)
|
||||
serve(server, devtools_port, me, token)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable → Regular
+180
-25
@@ -11,9 +11,81 @@ if [ "${DD_RAISE_NOFILE:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ]; then
|
||||
unset dd_nofile_was
|
||||
fi
|
||||
export HOME=${HOME:-/root}
|
||||
if grep -qs '/liblse_emu\.so$' /etc/ld.so.preload; then
|
||||
if [ "${LSE_EMU+x}" != x ]; then export LSE_EMU=1; fi
|
||||
# Runtime instruction rewriting is opt-in; the SIGILL emulation path remains available.
|
||||
export LSE_EMU_PATCH=${LSE_EMU_PATCH:-0}
|
||||
[ -n "${DD_DEBUG_DIR:-}" ] && export LSE_EMU_LOG=${LSE_EMU_LOG:-$DD_DEBUG_DIR/lse_emu.log}
|
||||
fi
|
||||
mode=${1:-desktop}
|
||||
shift || true
|
||||
|
||||
# Steam and its helpers share one session bus per session; an existing desktop bus is inherited.
|
||||
if [ "$mode" = steam ] && [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
|
||||
exec dbus-run-session -- "$0" "$mode" "$@"
|
||||
fi
|
||||
|
||||
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
|
||||
# Starts a long-lived program in its own Android process, which Android does not count against
|
||||
# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
|
||||
# Its pid is in $dd_spawned either way, and the ones not started as jobs in $dd_daemons, which
|
||||
# the session stops as it ends.
|
||||
dd_daemons=
|
||||
dd_spawn() {
|
||||
dd_spawned=
|
||||
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ] && [ -x /usr/local/bin/droiddeck-spawn ]; then
|
||||
local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$ rc=0
|
||||
/usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@" || rc=$?
|
||||
dd_spawned=$(cat "$f" 2>/dev/null)
|
||||
rm -f "$f"
|
||||
if [ "$rc" = 0 ] && [ -n "$dd_spawned" ]; then
|
||||
dd_daemons="$dd_daemons $dd_spawned"
|
||||
return 0
|
||||
fi
|
||||
# started, but its pid is unknown: not a second time
|
||||
[ "$rc" = 3 ] && { dd_spawned=; return 0; }
|
||||
fi
|
||||
"$@" &
|
||||
dd_spawned=$!
|
||||
}
|
||||
dd_stop_daemons() {
|
||||
[ -n "$dd_daemons" ] && kill $dd_daemons 2>/dev/null
|
||||
dd_daemons=
|
||||
}
|
||||
dd_session_pid=$$
|
||||
# Runs function $1 (with its arguments) in the background in a new bash that first loads this shell's
|
||||
# variables, functions and options: a background subshell, but an exec'd program, which the native
|
||||
# hook can hand to its own process (DD_HANDOFF "bash+dd-job"). $! is its pid, as for ( ... ) &.
|
||||
dd_job() {
|
||||
local state
|
||||
if [ -n "${DD_HANDOFF:-}" ] && state=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/.dd-job.XXXXXX" 2>/dev/null); then
|
||||
{
|
||||
declare -p | grep -Ev '^declare -[a-zA-Z]*r|^declare -[-a-zA-Z]* (BASH[A-Z_]*|FUNCNAME|GROUPS|DIRSTACK|PIPESTATUS|COPROC|LINENO|_)='
|
||||
declare -f
|
||||
shopt -p
|
||||
set +o
|
||||
} > "$state" 2>/dev/null
|
||||
/bin/bash -c 'source "$1" 2>/dev/null; rm -f "$1"; shift; "$@"' dd-job "$state" "$@" &
|
||||
else
|
||||
"$@" &
|
||||
fi
|
||||
}
|
||||
# Long-lived programs the session's guests start run in their own processes too
|
||||
# (tools/nativeguest/hook/handoff.c). Not Steam, its web helper's browser process (gamescope finds a
|
||||
# window's app by walking its process's parents) or its utility processes (the client only accepts
|
||||
# its transport from its own children).
|
||||
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
|
||||
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker}
|
||||
# The programs these start for the user (an app from the panel, a file opened in Dolphin)
|
||||
export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin}
|
||||
# Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and
|
||||
# the programs that reap them even while they leave SIGCHLD alone (hook/signals.c)
|
||||
rm -f /run/droiddeck-parents.* 2>/dev/null
|
||||
export DD_PARENTS=/run/droiddeck-parents.$$
|
||||
export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real}
|
||||
else
|
||||
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED
|
||||
fi
|
||||
steam_setup_failed() {
|
||||
echo "== steam: the Steam client could not be set up (status $1)"
|
||||
[ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_STEAM_EXIT_FILE"
|
||||
@@ -24,12 +96,17 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
|
||||
if [ "$(stat -c %s "$DD_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
||||
mv -f "$DD_LOG" "$DD_LOG.1"
|
||||
fi
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
if [ -x /usr/local/bin/droiddeck-log-writer ]; then
|
||||
exec > >(exec /usr/local/bin/droiddeck-log-writer "$DD_LOG" "${DD_LOG_CAP:-268435456}") 2>&1
|
||||
else
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
fi
|
||||
echo "== droiddeck-session $(date) mode=$mode $*"
|
||||
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
||||
[ "${LSE_EMU:-}" = 1 ] && echo "== cpu: no LSE atomics (ARMv8.0); liblse_emu.so emulates them (log: ${LSE_EMU_LOG:-off})"
|
||||
fi
|
||||
|
||||
start_diagnostic_inventory() {
|
||||
@@ -224,15 +301,23 @@ if [ -n "${DD_VK_DRIVER:-}" ]; then
|
||||
unset dd_icd_lib
|
||||
fi
|
||||
dd_webhelper_layout() {
|
||||
local layout
|
||||
if [ -n "${DD_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then
|
||||
printf '%s\n' "$DD_VKBRIDGE_WEBHELPER_ARGS"
|
||||
elif [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then
|
||||
echo stock
|
||||
elif [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
|
||||
echo "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
|
||||
else
|
||||
echo "--use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE"
|
||||
return
|
||||
fi
|
||||
if [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then
|
||||
echo stock
|
||||
return
|
||||
fi
|
||||
# ANGLE switches must not replace the helper's stable single-process layout.
|
||||
layout="--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
|
||||
if [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
|
||||
layout="$layout --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
|
||||
else
|
||||
layout="$layout --use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE"
|
||||
fi
|
||||
printf '%s\n' "$layout"
|
||||
}
|
||||
dd_now_ms() {
|
||||
if [ -n "${EPOCHREALTIME:-}" ]; then
|
||||
@@ -561,6 +646,10 @@ if [ -z "${DD_INSIDE:-}" ]; then
|
||||
fi
|
||||
[ "$mode" = steam ] && args+=(--default-touch-mode 4)
|
||||
[ "${DD_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
|
||||
# An SDR game reaches Android as its own SDR buffer, but whenever gamescope composites (a Steam
|
||||
# toast, the volume slider) an HDR output encodes the frame in PQ, which the display tone-maps
|
||||
# darker and shifted in colour. The output turns HDR only while a window presents HDR.
|
||||
export gamescope_hdr_content_driven=1
|
||||
[ -n "${DD_GAMESCOPE_ARGS:-}" ] && read -r -a _dd_extra <<<"$DD_GAMESCOPE_ARGS" && args+=("${_dd_extra[@]}")
|
||||
if [ "$mode" = steam ] && [ "${DD_MANGOAPP:-1}" = 1 ] \
|
||||
&& [ "${DD_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then
|
||||
@@ -610,6 +699,11 @@ dd_stretch_game_screen() {
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
reap_orphans() {
|
||||
local round p stat pid left
|
||||
# Started by the app as an Android process of its own: its parent is zygote, whose other
|
||||
# children are the app's processes. The guest may not see zygote in /proc; a worker's own
|
||||
# program has DDH_WORKER_PID.
|
||||
[ "${DDH_WORKER_PID:-}" = "$$" ] && return 0
|
||||
case "$(tr -d '\0' < "/proc/$PPID/cmdline" 2>/dev/null)" in ''|zygote*) return 0 ;; esac
|
||||
for round in 1 2 3 4 5; do
|
||||
left=
|
||||
for p in /proc/[0-9]*; do
|
||||
@@ -628,7 +722,14 @@ reap_orphans() {
|
||||
}
|
||||
|
||||
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
|
||||
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
|
||||
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
|
||||
fi
|
||||
|
||||
ime_text_pid=
|
||||
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DISPLAY:-}" ] && [ -n "${DD_LAUNCH_DIR:-}" ] \
|
||||
&& [ -x /usr/local/bin/droiddeck-text-input ]; then
|
||||
/usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" &
|
||||
ime_text_pid=$!
|
||||
fi
|
||||
|
||||
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
|
||||
@@ -771,14 +872,14 @@ case $mode in
|
||||
fi
|
||||
if [ "${DD_ZRAM:-0}" = 1 ]; then
|
||||
step "zRAM compression: on"
|
||||
(
|
||||
_dd_job_zram() {
|
||||
dd_zram_scan() {
|
||||
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
|
||||
local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0
|
||||
for _d in /proc/[0-9]*; do
|
||||
[ "${_d##*/}" != "$BASHPID" ] || continue
|
||||
_args=()
|
||||
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
|
||||
mapfile -d '' -t _args 2>/dev/null < "$_d/cmdline" || true
|
||||
[ "${#_args[@]}" -gt 0 ] || continue
|
||||
_name=${_args[0]} _fex=0
|
||||
if [ "${#_args[@]}" -gt 1 ]; then
|
||||
@@ -1116,7 +1217,7 @@ case $mode in
|
||||
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
|
||||
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
|
||||
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
while kill -0 "$dd_session_pid" 2>/dev/null; do
|
||||
dd_memory_tick
|
||||
if [ "$_dd_available" -ge 0 ] &&
|
||||
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
|
||||
@@ -1125,7 +1226,8 @@ case $mode in
|
||||
nap 5
|
||||
fi
|
||||
done
|
||||
) &
|
||||
}
|
||||
dd_job _dd_job_zram
|
||||
fi
|
||||
if [ "${DD_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] \
|
||||
&& [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
|
||||
@@ -1141,6 +1243,7 @@ case $mode in
|
||||
droiddeck-steam-library "$steam_root" || true
|
||||
step "setting up the ARM64 Proton compatibility tool"
|
||||
steam-compatibility "$steam_root" || true
|
||||
steam-compatibility "$steam_root" --seed-arm64-tools || true
|
||||
if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then
|
||||
droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true
|
||||
fi
|
||||
@@ -1217,7 +1320,7 @@ case $mode in
|
||||
) &
|
||||
fi
|
||||
fi
|
||||
[ -z "${DD_DESKTOP:-}" ] && (
|
||||
_dd_job_properties() {
|
||||
stretch=0 restore=0
|
||||
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
|
||||
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
|
||||
@@ -1296,8 +1399,9 @@ case $mode in
|
||||
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
|
||||
;;
|
||||
esac
|
||||
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
) &
|
||||
done < <(exec xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
}
|
||||
[ -n "${DD_DESKTOP:-}" ] || dd_job _dd_job_properties
|
||||
steam_hold_launch() {
|
||||
local game=$1 shortcut= waited=0 status=0
|
||||
_dd_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
|
||||
@@ -1384,8 +1488,8 @@ case $mode in
|
||||
fi
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
write_system_bus_config
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
system_bus=$!
|
||||
dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile
|
||||
system_bus=$dd_spawned
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S /run/dbus/system_bus_socket ] && break
|
||||
sleep 0.1
|
||||
@@ -1393,8 +1497,8 @@ case $mode in
|
||||
if [ -S /run/dbus/system_bus_socket ]; then
|
||||
echo "== network: system bus up, NetworkManager stand-in running"
|
||||
rm -f "$DD_LAUNCH_DIR/steam-sleep-ready"
|
||||
droiddeck-login1 --with-netmanager &
|
||||
login_manager=$!
|
||||
dd_spawn droiddeck-login1 --with-netmanager
|
||||
login_manager=$dd_spawned
|
||||
for ((_i = 0; _i < 50; _i++)); do
|
||||
[ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break
|
||||
kill -0 "$login_manager" 2>/dev/null || break
|
||||
@@ -1418,7 +1522,7 @@ case $mode in
|
||||
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
|
||||
_dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
|
||||
rm -f "$_dd_bus"
|
||||
dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile &
|
||||
dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S "$_dd_bus" ] && break
|
||||
nap 0.1
|
||||
@@ -1456,13 +1560,14 @@ case $mode in
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
|
||||
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
|
||||
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then
|
||||
(
|
||||
_dd_job_decky() {
|
||||
decky_child=
|
||||
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
|
||||
export LIVE_RELOAD=0
|
||||
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 &
|
||||
@@ -1480,7 +1585,8 @@ case $mode in
|
||||
echo "== Decky: loader exited with status $decky_status; restart $((decky_exits + 1))/5 in ${decky_delay}s"
|
||||
sleep "$decky_delay"
|
||||
done
|
||||
) &
|
||||
}
|
||||
dd_job _dd_job_decky
|
||||
decky_supervisor=$!
|
||||
echo "== Decky: session supervisor started ($decky_arch)"
|
||||
else
|
||||
@@ -1681,7 +1787,7 @@ case $mode in
|
||||
rm -f "$DD_LAUNCH_DIR/steam-stop" "$DD_LAUNCH_DIR/steam-game" "$DD_LAUNCH_DIR/steam-game.tmp"
|
||||
requests=1
|
||||
fi
|
||||
(
|
||||
_dd_job_requests() {
|
||||
tick=0
|
||||
beat=0
|
||||
library_job=
|
||||
@@ -1859,7 +1965,8 @@ case $mode in
|
||||
fi
|
||||
fi
|
||||
done
|
||||
) &
|
||||
}
|
||||
dd_job _dd_job_requests
|
||||
stop_watcher=$!
|
||||
if [ "${DD_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then
|
||||
LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /'
|
||||
@@ -1892,6 +1999,46 @@ case $mode in
|
||||
fi
|
||||
fi
|
||||
rm -f "$HOME/.dd-restart-game" "$HOME/.dd-restarted-for"
|
||||
unset IBUS_ADDRESS
|
||||
ime_ibus_pid=
|
||||
ime_ibus_socket=
|
||||
stop_steam_ime() {
|
||||
if [ -n "$ime_ibus_pid" ]; then
|
||||
kill "$ime_ibus_pid" 2>/dev/null || true
|
||||
wait "$ime_ibus_pid" 2>/dev/null || true
|
||||
ime_ibus_pid=
|
||||
fi
|
||||
[ -S "$ime_ibus_socket" ] && rm -f "$ime_ibus_socket"
|
||||
ime_ibus_socket=
|
||||
unset IBUS_ADDRESS
|
||||
}
|
||||
if [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ] \
|
||||
&& [ -x /usr/bin/ibus-daemon ] && [ -x /usr/bin/ibus ]; then
|
||||
ime_ibus_socket="${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-ibus-$$.sock"
|
||||
export IBUS_ADDRESS="unix:path=$ime_ibus_socket"
|
||||
/usr/local/bin/droiddeck-steam-ime &
|
||||
ime_ibus_pid=$!
|
||||
ime_ready=0
|
||||
_ime_deadline=$((SECONDS + 5))
|
||||
while [ "$SECONDS" -lt "$_ime_deadline" ]; do
|
||||
if env -u LD_LIBRARY_PATH -u LD_PRELOAD -u GSETTINGS_SCHEMA_DIR -u DCONF_PROFILE \
|
||||
timeout 1 /usr/bin/ibus list-engine --name-only 2>/dev/null | grep -qx 'pinyin'; then
|
||||
ime_ready=1
|
||||
break
|
||||
fi
|
||||
kill -0 "$ime_ibus_pid" 2>/dev/null || break
|
||||
nap 0.1
|
||||
done
|
||||
unset _ime_deadline
|
||||
if [ "$ime_ready" = 1 ]; then
|
||||
echo "== ime: pinyin engine ready at $IBUS_ADDRESS"
|
||||
else
|
||||
echo "== ime: the pinyin engine did not start at $IBUS_ADDRESS; Steam starts without Chinese input"
|
||||
stop_steam_ime
|
||||
fi
|
||||
elif [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ]; then
|
||||
echo "== ime: the installed Linux runtime does not include IBus; Steam starts without pinyin"
|
||||
fi
|
||||
while :; do
|
||||
rm -f "$HOME/.dd-restart-once" "$HOME/.dd-restart-lost"
|
||||
if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then
|
||||
@@ -2007,12 +2154,19 @@ case $mode in
|
||||
kill "$games_watcher" 2>/dev/null || true
|
||||
wait "$games_watcher" 2>/dev/null || true
|
||||
fi
|
||||
stop_steam_ime
|
||||
if [ -n "${ime_text_pid:-}" ]; then
|
||||
kill "$ime_text_pid" 2>/dev/null || true
|
||||
wait "$ime_text_pid" 2>/dev/null || true
|
||||
ime_text_pid=
|
||||
fi
|
||||
if [ -n "${DD_DESKTOP:-}" ]; then
|
||||
if [ -n "${decky_supervisor:-}" ]; then
|
||||
kill "$decky_supervisor" 2>/dev/null || true
|
||||
wait "$decky_supervisor" 2>/dev/null || true
|
||||
echo "== Decky: session supervisor stopped"
|
||||
fi
|
||||
dd_stop_daemons
|
||||
_dd_jobs=$(jobs -p)
|
||||
[ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null
|
||||
echo "== steam: the client on the desktop has exited"
|
||||
@@ -2022,6 +2176,7 @@ case $mode in
|
||||
wait "$decky_supervisor" 2>/dev/null || true
|
||||
echo "== Decky: session supervisor stopped"
|
||||
fi
|
||||
dd_stop_daemons
|
||||
_dd_jobs=$(jobs -p)
|
||||
[ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null
|
||||
reap_orphans
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Starts a program as the main process of its own Android process, outside the session's cgroup.
|
||||
|
||||
usage: droiddeck-spawn [--wait] [--pid-file FILE] [--] PROGRAM [ARGS...]
|
||||
|
||||
Android counts the session's processes against its child-process limit; a program started this
|
||||
way is not counted (its own children are). It gets this process's environment, working directory
|
||||
and stdin/stdout/stderr, and is not a child of the caller: the pid printed on stdout (or written to
|
||||
FILE) is the one to signal. Without --wait this returns once the program has started; with --wait
|
||||
it waits for it and exits with its status. Where the app offers no spawner, the program is started as a normal child.
|
||||
"""
|
||||
import array
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
|
||||
# Exit status when the program started but its pid could not be reported: the caller must not
|
||||
# start it again.
|
||||
STARTED_UNREPORTED = 3
|
||||
|
||||
|
||||
def report(pid, pid_file):
|
||||
try:
|
||||
if pid_file:
|
||||
with open(pid_file, "w") as f:
|
||||
f.write("%s\n" % pid)
|
||||
else:
|
||||
print(pid, flush=True)
|
||||
return True
|
||||
except OSError as e:
|
||||
print("droiddeck-spawn: started pid %s but could not report it: %s" % (pid, e), file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def fallback(argv, wait, pid_file):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
os.execvp(argv[0], argv)
|
||||
except OSError as e:
|
||||
print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr)
|
||||
os._exit(127)
|
||||
reported = report(pid, pid_file)
|
||||
if wait:
|
||||
return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
|
||||
return 0 if reported else STARTED_UNREPORTED
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
wait = False
|
||||
pid_file = None
|
||||
while args and args[0].startswith("--"):
|
||||
flag = args.pop(0)
|
||||
if flag == "--":
|
||||
break
|
||||
if flag == "--wait":
|
||||
wait = True
|
||||
elif flag == "--pid-file" and args:
|
||||
pid_file = args.pop(0)
|
||||
else:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
if not args:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
name = os.environ.get("DD_SPAWN")
|
||||
if not name:
|
||||
return fallback(args, wait, pid_file)
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
s.connect("\0" + name)
|
||||
except OSError:
|
||||
return fallback(args, wait, pid_file)
|
||||
request = {"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}
|
||||
# the session it belongs to, as SessionService writes it (a positive decimal); anything else is
|
||||
# left out, and the app then runs nothing for it
|
||||
session = os.environ.get("DD_SPAWN_SESSION", "")
|
||||
if re.fullmatch(r"[1-9][0-9]{0,8}", session):
|
||||
request["session"] = int(session)
|
||||
payload = json.dumps(request).encode()
|
||||
s.sendmsg([struct.pack(">I", len(payload)), payload],
|
||||
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))])
|
||||
reply = s.makefile("r")
|
||||
first = reply.readline().split()
|
||||
if len(first) != 2 or first[0] != "pid":
|
||||
print("droiddeck-spawn: %s; starting %s as a child" % (" ".join(first[1:]) or "no answer", args[0]),
|
||||
file=sys.stderr)
|
||||
return fallback(args, wait, pid_file)
|
||||
reported = report(first[1], pid_file)
|
||||
if not wait:
|
||||
return 0 if reported else STARTED_UNREPORTED
|
||||
done = reply.readline().split()
|
||||
status = int(done[1]) if len(done) == 2 and done[0] == "exit" else 1
|
||||
return status if 0 <= status < 256 else 128 + (status & 0x7f)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
[ -n "${IBUS_ADDRESS:-}" ] || exit 0
|
||||
unset LD_PRELOAD LD_LIBRARY_PATH GSETTINGS_SCHEMA_DIR
|
||||
export LD_LIBRARY_PATH=/usr/local/lib/droiddeck-ime
|
||||
export DCONF_PROFILE=/usr/local/share/droiddeck/ibus.profile
|
||||
exec /usr/bin/ibus-daemon --address "$IBUS_ADDRESS" --panel disable --config default \
|
||||
--emoji-extension disable --cache none
|
||||
@@ -14,7 +14,16 @@ chmod 700 "$state"
|
||||
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
|
||||
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
|
||||
|
||||
running() { pgrep -x vrserver >/dev/null 2>&1; }
|
||||
alive() {
|
||||
for p in $(pgrep -x "$1"); do
|
||||
case "$(awk '/^State:/ { print $2 }' "/proc/$p/status" 2>/dev/null)" in
|
||||
Z|'') ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
running() { alive vrserver; }
|
||||
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
|
||||
quest_settings() {
|
||||
backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json
|
||||
@@ -40,6 +49,19 @@ configure_graphics() {
|
||||
esac
|
||||
}
|
||||
|
||||
# On the guest's three cores Steam's web helpers took CPU time from vrcompositor's frames, so while the Quest view
|
||||
# shows SteamVR they run at a lower priority.
|
||||
steam_ui_priority() {
|
||||
status=0
|
||||
for p in $(pgrep -x steamwebhelper); do
|
||||
for t in /proc/"$p"/task/*; do
|
||||
renice -n "$1" -p "${t##*/}" >/dev/null 2>&1 || [ ! -e "$t" ] || status=1
|
||||
done
|
||||
done
|
||||
[ "$status" = 0 ] || echo "could not set every Steam web helper thread to priority $1" >&2
|
||||
return "$status"
|
||||
}
|
||||
|
||||
unregister() {
|
||||
if grep -qF "\"$steamvr\"" "$HOME/.config/openvr/openvrpaths.vrpath" 2>/dev/null; then
|
||||
rm -f "$HOME/.config/openvr/openvrpaths.vrpath"
|
||||
@@ -50,7 +72,7 @@ unregister() {
|
||||
}
|
||||
|
||||
idle() {
|
||||
[ ! -f "$state/active" ] && ! running && ! pgrep -x vrstartup >/dev/null 2>&1 &&
|
||||
[ ! -f "$state/active" ] && ! running && ! alive vrstartup &&
|
||||
( flock -n 9 ) 9>"$state/start.lock"
|
||||
}
|
||||
|
||||
@@ -61,7 +83,7 @@ stop() {
|
||||
done
|
||||
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
|
||||
attempts=0
|
||||
while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do
|
||||
while alive 'vrserver|vrcompositor'; do
|
||||
attempts=$((attempts + 1))
|
||||
if [ "$attempts" = 10 ]; then
|
||||
for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done
|
||||
@@ -69,8 +91,12 @@ stop() {
|
||||
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
# A SteamVR process killed while holding the IPC mutex in this file leaves it locked, and the next vrserver
|
||||
# gives up on it ("failed to acquire SysMgrMutex"), so the headset shows an empty void.
|
||||
alive 'vrserver|vrcompositor|vrstartup|vrdashboard|vrwebhelper' || rm -f /dev/shm/u*-ValveIPCSharedObj-SteamVR
|
||||
unregister
|
||||
quest_settings restore
|
||||
steam_ui_priority 0 || :
|
||||
}
|
||||
|
||||
case "${1:-status}" in
|
||||
@@ -81,6 +107,11 @@ launch)
|
||||
"$0" install || exit $?
|
||||
while [ -f "$state/installing" ]; do sleep 1; done
|
||||
fi
|
||||
if [ -f "$state/quest-immersive" ]; then
|
||||
: > "$state/xr-request"
|
||||
echo "asked DroidDeck to open the Quest's immersive view, which starts SteamVR"
|
||||
exit 0
|
||||
fi
|
||||
"$0" start
|
||||
;;
|
||||
status)
|
||||
@@ -122,7 +153,7 @@ start)
|
||||
flock -n 9 || { echo "SteamVR start already in progress"; exit 0; }
|
||||
installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; }
|
||||
[ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; }
|
||||
if [ -f "$state/active" ] && { running || pgrep -x vrstartup >/dev/null 2>&1; }; then
|
||||
if [ -f "$state/active" ] && { running || alive vrstartup; }; then
|
||||
echo "DroidDeck SteamVR is already running"
|
||||
exit 0
|
||||
fi
|
||||
@@ -215,8 +246,9 @@ JSON
|
||||
export LD_PRELOAD="$layer/libdroiddeck_vr_scheduling.so${LD_PRELOAD:+:$LD_PRELOAD}"
|
||||
if [ "${DROIDDECK_VR_PRESENT:-}" = questwsi ]; then
|
||||
quest_settings apply || exit 1
|
||||
steam_ui_priority 10 || :
|
||||
startup_handed_off=0
|
||||
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
|
||||
trap '[ "$startup_handed_off" = 1 ] || { quest_settings restore; steam_ui_priority 0 || :; }' EXIT
|
||||
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
|
||||
if [ -f "$cvp" ]; then
|
||||
disabled=$cvp.droiddeck-disabled
|
||||
|
||||
@@ -4,7 +4,14 @@ import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}
|
||||
# SteamVR's arm64 build throttles the compositor to save power and skipped refreshes it had time for.
|
||||
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False, 'framesToThrottle': 0, 'powersaveFramesToThrottle': 0}
|
||||
# Backups written before the throttle overrides existed do not record them.
|
||||
ADDED_LATER = {'framesToThrottle', 'powersaveFramesToThrottle'}
|
||||
|
||||
|
||||
def saved_entry(section, key):
|
||||
return [key in section, section.get(key)]
|
||||
|
||||
|
||||
def read(path):
|
||||
@@ -33,6 +40,8 @@ def saved_preferences(path):
|
||||
if not isinstance(backup.get('section'), bool) or not isinstance(backup.get('values'), dict):
|
||||
raise ValueError('invalid backup object')
|
||||
for key in OVERRIDES:
|
||||
if key not in backup['values'] and key in ADDED_LATER:
|
||||
continue
|
||||
entry = backup['values'].get(key)
|
||||
if not isinstance(entry, list) or len(entry) != 2 or not isinstance(entry[0], bool):
|
||||
raise ValueError('invalid saved preference: ' + key)
|
||||
@@ -45,12 +54,16 @@ def saved_preferences(path):
|
||||
def update(operation, settings_path, backup_path):
|
||||
settings = read(settings_path)
|
||||
if operation == 'apply':
|
||||
section = settings.get('steamvr', {})
|
||||
if backup_path.exists():
|
||||
saved_preferences(backup_path)
|
||||
backup = saved_preferences(backup_path)
|
||||
missing = [key for key in OVERRIDES if key not in backup['values']]
|
||||
if missing:
|
||||
backup['values'].update({key: saved_entry(section, key) for key in missing})
|
||||
write(backup_path, backup)
|
||||
else:
|
||||
section = settings.get('steamvr', {})
|
||||
write(backup_path, {'section': 'steamvr' in settings,
|
||||
'values': {key: [key in section, section.get(key)] for key in OVERRIDES}})
|
||||
'values': {key: saved_entry(section, key) for key in OVERRIDES}})
|
||||
settings.setdefault('steamvr', {}).update(OVERRIDES)
|
||||
write(settings_path, settings)
|
||||
elif operation == 'restore':
|
||||
@@ -59,6 +72,8 @@ def update(operation, settings_path, backup_path):
|
||||
backup = saved_preferences(backup_path)
|
||||
section = settings.setdefault('steamvr', {})
|
||||
for key in OVERRIDES:
|
||||
if key not in backup['values']:
|
||||
continue
|
||||
present, value = backup['values'][key]
|
||||
if present:
|
||||
section[key] = value
|
||||
|
||||
@@ -324,6 +324,16 @@ def cloud_on(sidecar):
|
||||
def exited(argv, code=0):
|
||||
found = find_store_game(argv)
|
||||
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
if found is None and launch_dir and compat_data and steam_ea_link(argv):
|
||||
try:
|
||||
game = str(json.loads((Path(compat_data) / STEAM_EA_STATE).read_text()).get("id") or "")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
game = ""
|
||||
if game:
|
||||
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": game}, timeout=1.0)
|
||||
log("steam ea %s exited" % game)
|
||||
return 0
|
||||
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")
|
||||
@@ -958,6 +968,7 @@ def prepare_gog(sidecar, compat_data, launch_dir):
|
||||
GOG_SCRIPTS = "goggame-*.script"
|
||||
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
|
||||
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
|
||||
GOG_SAVE_PATH_MARK = ".droiddeck-gog-save-path"
|
||||
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
|
||||
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
|
||||
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
|
||||
@@ -1552,7 +1563,7 @@ def write_licenses(compat_data, licenses):
|
||||
return written
|
||||
|
||||
|
||||
def prepare_ea(folder, sidecar, compat_data, launch_dir):
|
||||
def prepare_ea(folder, sidecar, compat_data, launch_dir, steam=None):
|
||||
game = str(sidecar.get("id"))
|
||||
proton = os.environ.get("DD_STORE_PROTON", "")
|
||||
made = create_prefix(compat_data, proton)
|
||||
@@ -1561,19 +1572,152 @@ def prepare_ea(folder, sidecar, compat_data, launch_dir):
|
||||
hardware, probe = ea_hardware(compat_data, proton) if ready else ({}, "no-prefix")
|
||||
answer = None
|
||||
if launch_dir:
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "ea-prepare", "store": "ea", "id": game, "hardware": hardware}, timeout=40.0)
|
||||
request = {"op": "ea-prepare", "store": "ea", "id": game, "hardware": hardware}
|
||||
if steam is not None:
|
||||
request["steam"] = steam
|
||||
answer = ask(Path(launch_dir) / "stores", request, timeout=40.0)
|
||||
sidecar = sidecar_at(Path(folder)) or sidecar
|
||||
log("ea %s prefix=%s stub=%s hardware=%s registry=%s touchup=%s" % (
|
||||
game, made, stub, probe, ea_registry(folder, sidecar, compat_data, proton), ea_touchup(folder, sidecar, compat_data, proton)))
|
||||
if answer is None:
|
||||
log("ea %s session=no reason=%s" % (game, "timeout" if launch_dir else "no-channel"))
|
||||
return
|
||||
return None
|
||||
written = write_licenses(compat_data, answer.get("licenses"))
|
||||
log("ea %s session=%s reason=%s lsx=%s licence=%s files=%d" % (
|
||||
game, "yes" if answer.get("ok") else "no", answer.get("reason", ""), answer.get("lsx"), answer.get("license", ""), written))
|
||||
return answer
|
||||
|
||||
|
||||
def gog_support_actions(folder):
|
||||
STEAM_EA_LINK = re.compile(r"(?i)^steam2ea://launchgame/([0-9]+)")
|
||||
STEAM_EA_LAUNCHER = "droiddeck-ea-steam.bat"
|
||||
STEAM_EA_ENV = ".droiddeck-ea-steam-env"
|
||||
STEAM_EA_STATE = ".droiddeck-ea-steam.json"
|
||||
STEAM_EA_CLIENT = "drive_c/Program Files/Electronic Arts/EA Desktop/EA Desktop/EADesktop.exe"
|
||||
STEAM_EA_OFFER = re.compile(r"^(Origin\.OFR\.[0-9]+\.[0-9]+)\.dat$", re.IGNORECASE)
|
||||
REPLACED = 13
|
||||
|
||||
|
||||
def steam_ea_link(argv):
|
||||
for raw in argv:
|
||||
if STEAM_EA_LINK.match(raw.strip().strip('"')):
|
||||
return raw
|
||||
return None
|
||||
|
||||
|
||||
def ea_manifest(folder):
|
||||
path = find_case(folder, "__Installer/installerdata.xml")
|
||||
if path is None or not path.is_file():
|
||||
return None
|
||||
import xml.etree.ElementTree as ET
|
||||
try:
|
||||
text = decode_output(path.read_bytes()).lstrip("\ufeff")
|
||||
root = ET.fromstring(re.sub(r"^\s*<\?xml[^>]*\?>", "", text))
|
||||
except (OSError, ET.ParseError):
|
||||
return None
|
||||
contents = [e.text.strip() for e in root.iter("contentID") if e.text and e.text.strip()]
|
||||
launchers = []
|
||||
for runtime in root.iter("runtime"):
|
||||
for launcher in runtime.iter("launcher"):
|
||||
path_text = (launcher.findtext("filePath") or "").strip()
|
||||
if path_text:
|
||||
launchers.append((path_text, (launcher.findtext("parameters") or "").strip(), (launcher.findtext("trial") or "0").strip() == "1"))
|
||||
launcher = next((l for l in launchers if not l[2]), launchers[0] if launchers else None)
|
||||
version = root.find("buildMetaData/gameVersion")
|
||||
titles = {e.get("locale"): (e.text or "").strip() for e in root.iter("gameTitle") if e.get("locale")}
|
||||
exe = None
|
||||
if launcher is not None:
|
||||
relative = re.sub(r"^\[[^\]]*\]", "", launcher[0]).replace("{installLocation}", "").lstrip("\\/")
|
||||
exe = find_case(folder, relative)
|
||||
return {
|
||||
"contentIds": contents,
|
||||
"exe": exe if exe is not None and exe.is_file() else None,
|
||||
"parameters": launcher[1] if launcher else "",
|
||||
"version": version.get("version", "") if version is not None else "",
|
||||
"title": titles.get("en_US") or next(iter(titles.values()), "") or Path(folder).name,
|
||||
}
|
||||
|
||||
|
||||
def steam_ea_offers(folder):
|
||||
loc = find_case(folder, "__Installer/LOC")
|
||||
try:
|
||||
names = sorted(p.name for p in loc.iterdir()) if loc is not None and loc.is_dir() else []
|
||||
except OSError:
|
||||
names = []
|
||||
return [m.group(1) for m in map(STEAM_EA_OFFER.match, names) if m]
|
||||
|
||||
|
||||
def batch_text(value):
|
||||
return value.replace("%", "%%").replace('"', "")
|
||||
|
||||
|
||||
def batch_arguments(value):
|
||||
return re.sub(r"[\x00-\x1f]+", " ", value).replace("%", "%%")
|
||||
|
||||
|
||||
def steam_ea_launcher(folder, exe, parameters, compat_data):
|
||||
env = windows_path(str(Path(compat_data) / STEAM_EA_ENV))
|
||||
lines = [
|
||||
"@echo off",
|
||||
"setlocal",
|
||||
"rem Written by DroidDeck: starts Steam's copy of an EA game without the EA app.",
|
||||
'cd /d "%s"' % batch_text(windows_path(str(exe.parent))),
|
||||
'if not exist "%s" goto run' % batch_text(env),
|
||||
'for /f "usebackq tokens=1,* delims==" %%%%a in ("%s") do set "%%%%a=%%%%b"' % batch_text(env),
|
||||
'del "%s"' % batch_text(env),
|
||||
":run",
|
||||
'if exist "%s" start "" "%s"' % (EA_STUB, EA_STUB),
|
||||
'"%s"%s %%*' % (batch_text(windows_path(str(exe))), " " + batch_arguments(parameters) if parameters else ""),
|
||||
'set "DD_RC=%errorlevel%"',
|
||||
"taskkill /f /im Origin.exe >nul 2>&1",
|
||||
"exit /b %DD_RC%",
|
||||
]
|
||||
return "\r\n".join(lines) + "\r\n"
|
||||
|
||||
|
||||
def prepare_steam_ea(argv, compat_data, launch_dir):
|
||||
"""Steam's copies of EA games start through the EA app, which does not install here: start the game itself."""
|
||||
folder = Path(os.environ.get("STEAM_COMPAT_INSTALL_PATH") or os.getcwd())
|
||||
if not compat_data:
|
||||
log("steam ea: no prefix, left to the EA app")
|
||||
return 0
|
||||
if (Path(compat_data) / "pfx" / STEAM_EA_CLIENT).is_file():
|
||||
log("steam ea: the EA app is installed in this prefix, left to it")
|
||||
return 0
|
||||
manifest = ea_manifest(folder)
|
||||
offers = steam_ea_offers(folder)
|
||||
if manifest is None or manifest["exe"] is None or not manifest["contentIds"] or not offers:
|
||||
log("steam ea: %s has no EA manifest, launcher or offer, left to the EA app" % folder)
|
||||
return 0
|
||||
if not launch_dir:
|
||||
log("steam ea: no channel to DroidDeck, left to the EA app")
|
||||
return 0
|
||||
exe = manifest["exe"]
|
||||
sidecar = {"store": "ea", "id": offers[0], "title": manifest["title"],
|
||||
"extra": {"contentIds": ",".join(manifest["contentIds"]), "displayName": manifest["title"], "locale": "en_US"}}
|
||||
steam = {"folder": str(folder), "offers": offers, "contentIds": manifest["contentIds"], "title": manifest["title"],
|
||||
"version": manifest["version"], "locale": "en_US", "exe": str(exe.relative_to(folder))}
|
||||
answer = prepare_ea(folder, sidecar, compat_data, launch_dir, steam)
|
||||
env = answer.get("env") if answer and answer.get("ok") else None
|
||||
if not isinstance(env, dict):
|
||||
log("steam ea: no EA session (%s), left to the EA app" % ((answer or {}).get("reason") or "no answer"))
|
||||
return 0
|
||||
data = Path(compat_data)
|
||||
try:
|
||||
secret = data / (STEAM_EA_ENV + ".tmp")
|
||||
secret.write_bytes("".join("%s=%s\r\n" % (k, v) for k, v in env.items()
|
||||
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", str(k)) and "\n" not in str(v)).encode())
|
||||
os.chmod(secret, 0o600)
|
||||
os.replace(secret, data / STEAM_EA_ENV)
|
||||
(data / STEAM_EA_LAUNCHER).write_bytes(steam_ea_launcher(folder, exe, manifest["parameters"], compat_data).encode())
|
||||
(data / STEAM_EA_STATE).write_text(json.dumps({"id": str(answer.get("id") or offers[0])}))
|
||||
except OSError as error:
|
||||
log("steam ea: launcher not written (%s), left to the EA app" % type(error).__name__)
|
||||
return 0
|
||||
log("steam ea: %s starts %s directly as %s" % (manifest["title"], exe.name, answer.get("id") or offers[0]))
|
||||
return REPLACED
|
||||
|
||||
|
||||
def gog_script_actions(folder, name):
|
||||
found = []
|
||||
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
|
||||
product = script.name[len("goggame-"):-len(".script")]
|
||||
@@ -1583,17 +1727,34 @@ def gog_support_actions(folder):
|
||||
continue
|
||||
for action in actions if isinstance(actions, list) else []:
|
||||
install = action.get("install") if isinstance(action, dict) else None
|
||||
if isinstance(install, dict) and install.get("action") == "supportData" \
|
||||
if isinstance(install, dict) and install.get("action") == name \
|
||||
and isinstance(install.get("arguments"), dict):
|
||||
found.append((product, install["arguments"]))
|
||||
return found
|
||||
|
||||
|
||||
def gog_support_actions(folder):
|
||||
return gog_script_actions(folder, "supportData")
|
||||
|
||||
|
||||
def gog_case_child(path, part):
|
||||
exact = path / part
|
||||
try:
|
||||
if not exact.exists() and path.is_dir():
|
||||
return next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
|
||||
except OSError:
|
||||
pass
|
||||
return exact
|
||||
|
||||
|
||||
def gog_support_bases(folder, product, pfx):
|
||||
user = Path(pfx) / "drive_c" / "users" / "steamuser"
|
||||
support = Path(folder) / "support" / product
|
||||
appdata = gog_case_child(user, "AppData")
|
||||
return {"app": Path(folder), "supportdir": support, "support": support,
|
||||
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
|
||||
"userdocs": gog_case_child(user, "Documents"),
|
||||
"localappdata": gog_case_child(appdata, "Local"),
|
||||
"userappdata": gog_case_child(appdata, "Roaming")}
|
||||
|
||||
|
||||
def gog_inside(path, base):
|
||||
@@ -1612,10 +1773,7 @@ def gog_support_path(text, bases):
|
||||
base = bases[match.group(1).lower()]
|
||||
path = base
|
||||
for part in parts:
|
||||
exact = path / part
|
||||
if not exact.exists() and path.is_dir():
|
||||
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
|
||||
path = exact
|
||||
path = gog_case_child(path, part)
|
||||
if path != base and not gog_inside(path.parent, base):
|
||||
return None
|
||||
return path, base
|
||||
@@ -1687,6 +1845,44 @@ def gog_support_data(folder, compat_data, proton):
|
||||
return "copied=%d%s" % (copied, note)
|
||||
|
||||
|
||||
def gog_save_paths(folder, compat_data, proton):
|
||||
actions = gog_script_actions(folder, "savePath")
|
||||
if not actions:
|
||||
return "none"
|
||||
pfx = Path(compat_data) / "pfx" if compat_data else None
|
||||
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
|
||||
made = create_prefix(compat_data, proton)
|
||||
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
|
||||
return "no-prefix"
|
||||
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
marker = pfx / GOG_SAVE_PATH_MARK
|
||||
try:
|
||||
if marker.is_file() and marker.read_text() == stamp:
|
||||
return "ready"
|
||||
except OSError:
|
||||
pass
|
||||
paths = skipped = 0
|
||||
for product, arguments in actions:
|
||||
bases = gog_support_bases(folder, product, pfx)
|
||||
found = gog_support_path(arguments.get("savePath") or arguments.get("target"), bases)
|
||||
if found is None:
|
||||
skipped += 1
|
||||
continue
|
||||
target, _root = found
|
||||
try:
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
paths += 1
|
||||
except OSError:
|
||||
skipped += 1
|
||||
note = " skipped=%d" % skipped if skipped else ""
|
||||
if not skipped:
|
||||
try:
|
||||
marker.write_text(stamp)
|
||||
except OSError:
|
||||
pass
|
||||
return "paths=%d%s" % (paths, note)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
||||
return 0
|
||||
@@ -1705,6 +1901,8 @@ def main(argv):
|
||||
return RAN if subprocess.call(command) == 0 else RAN_FAILED
|
||||
found = find_store_game(argv)
|
||||
if found is None:
|
||||
if steam_ea_link(argv):
|
||||
return prepare_steam_ea(argv, os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/"), os.environ.get("DD_LAUNCH_DIR", ""))
|
||||
return 0
|
||||
folder, sidecar = found
|
||||
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
|
||||
@@ -1731,6 +1929,7 @@ def main(argv):
|
||||
prepare_gog(sidecar, compat_data, launch_dir)
|
||||
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
log("gog save paths: " + gog_save_paths(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
if store == "rockstar":
|
||||
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
|
||||
if compat_data:
|
||||
|
||||
Loaded 100 of 941 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user