merge: refresh PRoot removal

This commit is contained in:
Kurt Himebauch committed 2026-12-05 16:30:33 -05:00
commit d949407c5c
406 files changed
+41180 -3048

No files matched your search

+13 -4
View File
@@ -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.
+17
View File
@@ -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
+26
View File
@@ -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
+5 -3
View File
@@ -36,9 +36,11 @@ GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-im
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 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).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp
LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349)
# 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).
+7
View File
@@ -87,6 +87,11 @@ static const char *rewrite_path(const char *path, char *out, size_t 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"
@@ -315,12 +320,14 @@ pid_t fork(void) {
}
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);
}
+3
View File
@@ -52,6 +52,9 @@ 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.
+3 -1
View File
@@ -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
@@ -519,6 +519,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"
+19
View File
@@ -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"
+6 -1
View File
@@ -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
+8 -1
View File
@@ -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": {
+2
View File
@@ -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"
+1 -1
View File
@@ -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
+2 -1
View File
@@ -100,7 +100,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)]
+5
View File
@@ -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;
};
+92
View File
@@ -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;
}
+12
View File
@@ -506,3 +506,15 @@ on a 120 Hz screen (frames alternately one and two refreshes apart). The first t
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.
+8
View File
@@ -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
@@ -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;
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-17928792
GAMESCOPE_SHA256=b25680d5f81c8ba1f3e0f6f49894686a148baa296647c3bf3dafa3a04697b7c8
GAMESCOPE_TAG=gamescope-3.16.29-verified-acquire-v1
GAMESCOPE_SHA256=0861b5f6f694842eead87e4fd68f7b3cf93c35f10e1dccffd5ea3fc75081b97d
@@ -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]);
}
+27
View File
@@ -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"
}
}
}
+230
View File
@@ -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()
+152
View File
@@ -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}')
+13 -5
View File
@@ -9,7 +9,7 @@ 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
@@ -142,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]
@@ -175,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
@@ -234,7 +242,7 @@ mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
as_user=
if [ "${DD_DESKTOP_USER:-}" = 1 ] && [ -n "${DDNATV_ROOT:-}" ]; then
if [ "${DD_DESKTOP_USER:-}" = 1 ]; then
as_user=/usr/local/bin/droiddeck-user
echo "== droiddeck-desktop: Plasma runs as an ordinary user"
fi
@@ -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);
@@ -9,42 +9,35 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;;
esac
fi
if [ -n "${DDNATV_ROOT:-}" ]; then
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
fi
if [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$image
exec /usr/local/lib/droiddeck/uruntime "$@"
fi
exec "$image" "$@"
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
@@ -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[@]}"
@@ -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
@@ -750,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):
@@ -761,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:
@@ -769,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)
@@ -781,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)
@@ -800,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:
@@ -889,11 +899,10 @@ def extract(image):
x86 = elf_arch(image) in X86.values()
if os.access(URUNTIME, os.X_OK):
with open(image, "rb") as source:
native = bool(os.environ.get("DDNATV_ROOT"))
target = "/proc/self/fd/%d" % source.fileno() if native else image
target = "/proc/self/fd/%d" % source.fileno()
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=target),
pass_fds=(source.fileno(),) if native else ())
pass_fds=(source.fileno(),))
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
@@ -963,7 +972,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":
@@ -975,6 +984,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)
@@ -996,6 +1009,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#./}
@@ -69,7 +69,8 @@ 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
@@ -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"
@@ -67,6 +68,30 @@ DOTNET_FEX = {
"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")
@@ -149,6 +174,40 @@ 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=""):
@@ -158,6 +217,7 @@ class Game:
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)
@@ -177,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:
@@ -249,6 +315,12 @@ 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":
@@ -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()
@@ -13,6 +13,12 @@ fi
export HOME=${HOME:-/root}
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.
@@ -63,9 +69,16 @@ dd_job() {
# 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}
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
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)"
@@ -705,6 +718,13 @@ if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr
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
case $mode in
@@ -1540,6 +1560,7 @@ case $mode in
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 &
@@ -1971,6 +1992,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
@@ -2086,6 +2147,12 @@ 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
+7
View File
@@ -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
@@ -162,7 +162,7 @@ def windows_path(unix):
def bionic_tool(proton):
if not proton or not os.environ.get("DDNATV_ROOT"):
if not proton:
return None
tool = Path(proton).parent
return str(tool / "proton") if (tool / "bionic" / "launch.sh").is_file() else None
+510
View File
@@ -0,0 +1,510 @@
#!/usr/bin/python3
"""Deliver committed Android IME text to the focused X11 client."""
import ctypes
import ctypes.util
import errno
import os
import select
import signal
import socket
import stat
import struct
import sys
MAX_TEXT = 65536
CANCELLABLE = 1 << 31
CLIENT_TIMEOUT = 2.0
PROBE_TIMEOUT = 0.5
FOCUS_PROPERTY = b'GAMESCOPE_KEYBOARD_FOCUS_DISPLAY'
ANY_PROPERTY_TYPE = 0
PROPERTY_WORDS = 1024
PR_SET_PDEATHSIG = 1
UNICODE_KEYSYM_FLAG = 0x01000000
X11_SPECIAL_KEYSYMS = {
'\r': 0xff0d, # XK_Return
'\n': 0xff0d, # XK_Return
'\b': 0xff08, # XK_BackSpace
'\u007f': 0xffff, # XK_Delete
'\t': 0xff09, # XK_Tab
}
_STOP = False
class XModifierKeymap(ctypes.Structure):
_fields_ = [('max_keypermod', ctypes.c_int),
('modifiermap', ctypes.POINTER(ctypes.c_ubyte))]
class _DisplayState:
"""Keep mappings stable until shutdown because clients may decode key events later."""
__slots__ = ('handle', 'codes', 'owned')
def __init__(self, handle):
self.handle = handle
self.codes = {} # keysym -> keycode, stable for the session
self.owned = {} # keycode -> (width, original row) for shutdown restore
class XBridge:
def __init__(self):
self.lib = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')
self.xtst = ctypes.CDLL(ctypes.util.find_library('Xtst') or 'libXtst.so.6')
self._open_displays = {}
self._declare()
def _declare(self):
lib = self.lib
lib.XOpenDisplay.argtypes = [ctypes.c_char_p]
lib.XOpenDisplay.restype = ctypes.c_void_p
lib.XCloseDisplay.argtypes = [ctypes.c_void_p]
lib.XCloseDisplay.restype = ctypes.c_int
lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
lib.XDefaultRootWindow.restype = ctypes.c_ulong
lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
lib.XInternAtom.restype = ctypes.c_ulong
lib.XGetWindowProperty.argtypes = [
ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long,
ctypes.c_int, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_void_p)]
lib.XGetWindowProperty.restype = ctypes.c_int
lib.XFree.argtypes = [ctypes.c_void_p]
lib.XFree.restype = ctypes.c_int
lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
lib.XDisplayKeycodes.restype = ctypes.c_int
lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong)
lib.XChangeKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]
lib.XChangeKeyboardMapping.restype = ctypes.c_int
lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]
lib.XSync.restype = ctypes.c_int
lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
lib.XQueryKeymap.restype = ctypes.c_int
lib.XGetModifierMapping.argtypes = [ctypes.c_void_p]
lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap)
lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)]
lib.XFreeModifiermap.restype = ctypes.c_int
self.xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int,
ctypes.c_ulong]
self.xtst.XTestFakeKeyEvent.restype = ctypes.c_int
def state(self, name):
existing = self._open_displays.get(name)
if existing is not None:
return existing
handle = self.lib.XOpenDisplay(name.encode())
if not handle:
return None
state = _DisplayState(handle)
self._open_displays[name] = state
return state
def display(self, name):
state = self.state(name)
return state.handle if state else None
def close(self):
for state in self._open_displays.values():
for keycode, (width, original) in state.owned.items():
row = (ctypes.c_ulong * width)(*original)
self.lib.XChangeKeyboardMapping(state.handle, keycode, width, row, 1)
self.lib.XSync(state.handle, 0)
self.lib.XCloseDisplay(state.handle)
self._open_displays.clear()
def target_display(self):
main = os.environ.get('DISPLAY', '').strip()
if not main:
return None
game = os.environ.get('STEAM_GAME_DISPLAY_0', '').strip()
if not game or game == main:
return main
main_display = self.display(main)
if not main_display:
return None
focused = self._focused_display(main_display)
if focused == game:
return game
if focused == main:
return main
return None
def _focused_display(self, display):
root = self.lib.XDefaultRootWindow(display)
atom = self.lib.XInternAtom(display, FOCUS_PROPERTY, 0)
if not atom:
return None
actual_type = ctypes.c_ulong(0)
actual_format = ctypes.c_int(0)
items = ctypes.c_ulong(0)
remaining = ctypes.c_ulong(0)
data = ctypes.c_void_p()
status = self.lib.XGetWindowProperty(
display, root, atom, 0, PROPERTY_WORDS, 0, ANY_PROPERTY_TYPE,
ctypes.byref(actual_type), ctypes.byref(actual_format), ctypes.byref(items),
ctypes.byref(remaining), ctypes.byref(data))
if status != 0 or not data or not items.value:
if data:
self.lib.XFree(data)
return None
try:
raw = _property_bytes(data, actual_format.value, items.value)
finally:
self.lib.XFree(data)
if raw is None:
return None
raw = raw.split(b'\0', 1)[0]
if not raw:
return None
try:
return raw.decode('ascii')
except UnicodeDecodeError:
return None
def keymap(self, display):
lowest = ctypes.c_int(0)
highest = ctypes.c_int(0)
self.lib.XDisplayKeycodes(display, ctypes.byref(lowest), ctypes.byref(highest))
if lowest.value < 0 or highest.value < lowest.value:
return None
count = highest.value - lowest.value + 1
width = ctypes.c_int(0)
symbols = self.lib.XGetKeyboardMapping(display, lowest.value, count, ctypes.byref(width))
if not symbols:
return None
if width.value <= 0:
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
return None
rows = [[symbols[index * width.value + level] for level in range(width.value)]
for index in range(count)]
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
return lowest.value, width.value, rows
def held_keys(self, display):
state = ctypes.create_string_buffer(32)
if not self.lib.XQueryKeymap(display, ctypes.cast(state, ctypes.c_void_p)):
return set()
raw = state.raw
return {keycode for keycode in range(len(raw) * 8)
if raw[keycode >> 3] >> (keycode & 7) & 1}
def modifier_keys(self, display):
mapping = self.lib.XGetModifierMapping(display)
if not mapping:
return set()
try:
width = mapping.contents.max_keypermod
keys = mapping.contents.modifiermap
return {keys[index] for index in range(8 * width) if keys[index]}
finally:
self.lib.XFreeModifiermap(mapping)
def empty_rows(self, display, reserved):
keymap = self.keymap(display)
if keymap is None:
return []
lowest, width, rows = keymap
held = self.held_keys(display)
modifiers = self.modifier_keys(display)
available = []
for index in range(len(rows) - 1, -1, -1):
keycode = lowest + index
if keycode < 8 or keycode > 255 or keycode in held or keycode in modifiers:
continue
if keycode in reserved:
continue
row = rows[index]
if any(row):
continue
available.append((keycode, width, tuple(row)))
return available
def type_text(self, state, text, cancelled=None):
"""Reserve all required mappings before injecting any part of a frame."""
handle = state.handle
needed = []
seen = set()
for character in text:
keysym = _character_keysym(character)
if keysym not in seen:
seen.add(keysym)
needed.append(keysym)
missing = [keysym for keysym in needed if keysym not in state.codes]
if missing:
available = self.empty_rows(handle, set(state.codes.values()))
if len(available) < len(missing):
_log_capacity_exhausted()
return False
for keysym, (keycode, width, original) in zip(missing, available):
row = (ctypes.c_ulong * width)(*[keysym] * width)
# XChangeKeyboardMapping queues the request and returns 0.
self.lib.XChangeKeyboardMapping(handle, keycode, width, row, 1)
state.codes[keysym] = keycode
state.owned[keycode] = (width, original)
self.lib.XSync(handle, 0)
for character in text:
if _STOP:
return False
if cancelled is not None and cancelled():
return False
keycode = state.codes[_character_keysym(character)]
if not self._tap(handle, keycode):
return False
return True
def _tap(self, handle, keycode):
pressed = False
try:
if not self.xtst.XTestFakeKeyEvent(handle, keycode, 1, 0):
return False
pressed = True
self.lib.XSync(handle, 0)
if not self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0):
return False
pressed = False
self.lib.XSync(handle, 0)
finally:
if pressed:
self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0)
self.lib.XSync(handle, 0)
return True
def _character_keysym(character):
keysym = X11_SPECIAL_KEYSYMS.get(character)
if keysym is not None:
return keysym
codepoint = ord(character)
return codepoint if codepoint < 256 else UNICODE_KEYSYM_FLAG | codepoint
def _log_capacity_exhausted():
try:
sys.stderr.write('droiddeck-text-input: not enough empty keycodes for this frame\n')
sys.stderr.flush()
except OSError:
pass
def _property_bytes(data, actual_format, items):
if actual_format == 8:
return ctypes.string_at(data, items)
if actual_format == 32:
# Xlib exposes format-32 property items as native longs, including on 64-bit systems.
words = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong))
return b''.join(struct.pack('<I', words[index] & 0xffffffff)
for index in range(items))
return None
def _recv_exact(connection, count):
chunks = []
remaining = count
while remaining > 0:
try:
chunk = connection.recv(remaining)
except OSError:
return None
if not chunk:
return None
chunks.append(chunk)
remaining -= len(chunk)
return b''.join(chunks)
def read_request(connection):
header = _recv_exact(connection, 4)
if header is None:
return None
raw = struct.unpack('>I', header)[0]
cancellable = bool(raw & CANCELLABLE)
length = raw & ~CANCELLABLE
if length < 1 or length > MAX_TEXT:
return None
body = _recv_exact(connection, length)
if body is None:
return None
if b'\0' in body:
return None
try:
return body.decode('utf-8'), cancellable
except UnicodeDecodeError:
return None
def answer(connection, accepted):
try:
connection.sendall(b'\x01' if accepted else b'\x00')
connection.shutdown(socket.SHUT_WR)
except OSError:
return
# Drain unread bytes so close() does not reset the connection after the ACK.
try:
connection.settimeout(0.2)
while connection.recv(4096):
pass
except OSError:
pass
def _cancellation_probe(connection):
"""Return a predicate that is true once the peer has cancelled a flagged frame.
After the full frame has been read, any readable event (POLLIN/POLLHUP/POLLERR)
means extra data, half-close or reset - all of which are cancellation for a
cancellable client.
"""
poller = select.poll()
poller.register(connection, select.POLLIN)
return lambda: bool(poller.poll(0))
def deliver(bridge, text, cancelled=None):
if cancelled is not None and cancelled():
return False
target = bridge.target_display()
if target is None:
return False
state = bridge.state(target)
if state is None:
return False
return bridge.type_text(state, text, cancelled)
def serve_connection(connection, bridge):
connection.settimeout(CLIENT_TIMEOUT)
request = read_request(connection)
accepted = False
if request is not None:
text, cancellable = request
cancelled = _cancellation_probe(connection) if cancellable else None
try:
accepted = deliver(bridge, text, cancelled)
except Exception:
accepted = False
answer(connection, accepted)
def _identity(path):
try:
info = os.stat(path)
except OSError:
return None
return info.st_dev, info.st_ino
def _release(path, owned):
if owned is None:
return
try:
info = os.lstat(path)
except OSError:
return
if stat.S_ISSOCK(info.st_mode) and (info.st_dev, info.st_ino) == owned:
try:
os.unlink(path)
except OSError:
pass
def serve(path, bridge):
if not _remove_stale(path):
print("droiddeck-text-input: refusing to replace %s" % path, file=sys.stderr)
return 1
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
owned = None
try:
server.bind(path)
os.chmod(path, 0o600)
server.listen(8)
server.setblocking(False)
owned = _identity(path)
while not _STOP:
try:
ready, _, _ = select.select([server], [], [], 0.25)
except OSError:
break
if not ready:
continue
try:
connection, _ = server.accept()
except OSError:
if _STOP:
break
continue
try:
serve_connection(connection, bridge)
finally:
connection.close()
finally:
server.close()
_release(path, owned)
return 0
def _remove_stale(path):
try:
info = os.lstat(path)
except FileNotFoundError:
return True
except OSError:
return False
if not stat.S_ISSOCK(info.st_mode):
return False
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
probe.settimeout(PROBE_TIMEOUT)
probe.connect(path)
except OSError as error:
if error.errno == errno.ENOENT:
return True
if error.errno != errno.ECONNREFUSED:
return False
else:
return False
finally:
probe.close()
_release(path, (info.st_dev, info.st_ino))
return True
def _stop(signum, frame):
global _STOP
_STOP = True
def _adopt_parent_death():
parent = os.getppid()
try:
libc = ctypes.CDLL(None, use_errno=True)
libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong,
ctypes.c_ulong]
libc.prctl.restype = ctypes.c_int
libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0)
except (OSError, AttributeError):
return True
return os.getppid() == parent and parent > 1
def main(argv):
if len(argv) != 2 or not argv[1]:
return 2
if not _adopt_parent_death():
return 0
os.umask(0o077)
for name in ('SIGTERM', 'SIGINT', 'SIGHUP'):
signal.signal(getattr(signal, name), _stop)
bridge = XBridge()
try:
return serve(argv[1], bridge)
finally:
bridge.close()
if __name__ == '__main__':
sys.exit(main(sys.argv))
@@ -28,6 +28,19 @@ CLASSES = {
'Windows.Storage.Streams.DataWriter'),
}
CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\'
# Microsoft's original Xbox releases for PC install GameInputRedist.msi. The emulator needs the GameInput it installs
# (Wine's builtin one lacks the interface it asks for), but through the GameInputService class it registers that
# GameInput starts a service needing Windows notification calls Wine lacks, and the emulator then stops with "Gaming
# Services must be installed". Without the class it runs the redistributable's GameInput in process.
BACK_COMPAT_IDENTITY = 'xbox360backwardcompatibil'
# droiddeck-game-env gives these games the emulator's switches and faster FEX settings. Their install actions run
# without the switches and with FEX's full memory ordering and x87 precision: under the faster settings
# GameInputRedist.msi's 32-bit msiexec spun a core and never finished.
EMULATOR_SWITCHES = ('WINE_SPECIAL_APC_INTERRUPT', 'WINE_MF_DISPLAY_APERTURE', 'WINE_PRECISE_SLEEP', 'FEX_SYNCX87CONTEXT',
'FEX_LOOPSUSPENDCHECK', 'FEX_SAFEIMAGEMAP', 'VKD3D_INTEROP_PRESENT', 'VKD3D_PACKED_422')
INSTALLER_FEX = {'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1',
'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'}
GAMEINPUT_SERVICE = 'Software\\Classes\\CLSID\\{B773D0F8-01F8-41E7-9F23-6871DA0AACFF}'
VIEW_DRIVES = 'xwvutsrqponmlkjihgfe'
@@ -145,8 +158,21 @@ def game_config(exe):
return None
for folder in list(path.parents)[:4]:
config = folder / 'MicrosoftGame.config'
if config.is_file():
return config
if not config.is_file():
# The Xbox store accepts the file name in any case (XboxManifest.read).
try:
config = next((entry for entry in sorted(folder.iterdir())
if entry.name.lower() == 'microsoftgame.config' and entry.is_file()), None)
except OSError:
config = None
if config is None:
continue
# As in droiddeck-game-env, a manifest that does not parse gives way to one in a parent folder.
try:
ElementTree.fromstring(config.read_bytes())
except (OSError, ElementTree.ParseError):
continue
return config
return None
@@ -186,6 +212,40 @@ def windows_arguments(text):
return arguments
def back_compat(config):
try:
root = ElementTree.fromstring(config.read_bytes())
except (OSError, ElementTree.ParseError):
return False
return any(node.tag.rsplit('}', 1)[-1] == 'Identity' and node.get('Name', '').lower().startswith(BACK_COMPAT_IDENTITY)
for node in root.iter())
def remove_gameinput_service(proton, prefix, env, installed=False):
# Just after an install action Wine may not have written system.reg yet; reg.exe sees its registry either way.
if not installed:
try:
registry = (prefix / 'system.reg').read_text(encoding='utf-8', errors='replace')
except OSError:
return
if '[%s]' % GAMEINPUT_SERVICE.replace('\\', '\\\\').lower() not in registry.lower():
return
try:
code = subprocess.run([proton, 'run', 'reg.exe', 'delete', 'HKLM\\' + GAMEINPUT_SERVICE, '/f'],
stdout=sys.stderr, env=env, timeout=90).returncode
except subprocess.TimeoutExpired:
print('droiddeck-xbox: GameInput service class could not be removed (reg.exe timed out); launching with it',
file=sys.stderr)
return
except OSError as e:
print('droiddeck-xbox: GameInput service class could not be removed (%s); launching with it' % (e.strerror or e),
file=sys.stderr)
return
# reg.exe fails when the key is absent, which after an install action only means the action registered no class.
if code != 0 and not installed:
print('droiddeck-xbox: GameInput service class could not be removed; launching with it', file=sys.stderr)
def install_actions(config):
try:
root = ElementTree.fromstring(config.read_bytes())
@@ -218,6 +278,10 @@ def run_install_actions(proton, prefix, exe, env):
if config is None:
return
done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions'
original_xbox = back_compat(config)
if original_xbox:
env = dict({k: v for k, v in env.items() if k not in EMULATOR_SWITCHES}, **INSTALLER_FEX)
installed = False
for name, target, arguments in install_actions(config):
try:
content = hashlib.sha256()
@@ -243,11 +307,14 @@ def run_install_actions(proton, prefix, exe, env):
if code != 0:
print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr)
continue
installed = True
try:
done.mkdir(parents=True, exist_ok=True)
marker.touch()
except OSError as error:
print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr)
if original_xbox:
remove_gameinput_service(proton, prefix, env, installed)
def view_drive(prefix, exe):
@@ -318,6 +318,74 @@ dd_vacdiag() {
}
"""
DD_ANTICHEAT_SETUP = """
dd_anticheat_runtime() {
local current=$1 name=$2 bridge=$3 library
if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then
printf '%s' "$current"; return 0
fi
while IFS= read -r library; do
[ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue
printf '%s' "$library/steamapps/common/$name"; return 0
done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null)
return 1
}
dd_x86_64_proton() {
[ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ]
}
dd_anticheat() {
case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac
case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac
local game=${STEAM_COMPAT_INSTALL_PATH:-} found markers eac battleye tool runtime=
[ -d "$game" ] || return 0
markers=$(find "$game" -maxdepth 5 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\
-o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print 2>/dev/null)
eac=$(printf '%s\\n' "$markers" | grep -i easyanticheat | head -n 1)
battleye=$(printf '%s\\n' "$markers" | grep -iv easyanticheat | grep . | head -n 1)
found=${eac:-$battleye}
[ -n "$found" ] || return 0
case ${DD_AC_TOOL:-DroidDeck-Proton} in
DroidDeck-Proton*) ;;
*)
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2
return 0
;;
esac
/usr/local/bin/droiddeck-fex update || true
if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2
return 0
fi
DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d"
done | sort -V | tail -n 1)
if [ -z "$tool" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2
return 0
fi
if [ -n "$eac" ] && runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so); then
export PROTON_EAC_RUNTIME="$runtime"
found=$eac
elif [ -n "$battleye" ] && runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so); then
export PROTON_BATTLEYE_RUNTIME="$runtime"
found=$battleye
else
runtime=
fi
if [ -z "$runtime" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2
return 0
fi
dd_game_cpus
declare -F dd_components >/dev/null && dd_components "$tool"
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@"
}
"""
DD_DRIVER_QUERY_SKIP = """
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
@@ -437,6 +505,7 @@ for name in %s; do
[ -n "$depot" ] && break
done
if [ -n "$depot" ]; then
dd_anticheat "$@"
dd_components "$depot"
dd_directaudio "$depot" "$@"
dd_game_cpus
@@ -457,7 +526,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -485,6 +554,11 @@ for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libddsession.so; do
esac
fi
done
if dd_x86_64_proton "$here"; then
dd_game_cpus
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@"
fi
DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"
dd_components "$here"
dd_directaudio "$here" "$@"
dd_game_cpus
@@ -499,9 +573,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
@@ -1301,10 +1375,18 @@ def tool_catalog(steam_root, extras=None):
continue
extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry
for name, entry in sorted(extras.items()):
catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False))
tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False)
if x86_64_layout(os.path.join(tools, entry)):
tool["x86_64"] = True
catalog.append(tool)
return catalog
def x86_64_layout(path):
return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and
not os.path.isdir(os.path.join(path, "files", "bin-arm64")))
def built_from(name, catalog, runnable=None):
depot = VALVE_DEPOTS.get(name)
tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and
@@ -1443,7 +1525,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
def own_builds(tools):
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")]
def build_key(name):
@@ -1481,7 +1563,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app
wanted = requested_tool(request, catalog)
state["applied"] = seq
if wanted:
if wanted != state.get("default"):
if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any(
t["name"] == wanted and t.get("x86_64") for t in catalog)):
state.update(default=wanted, seq=now or now_ms(), source="app")
else:
print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % (
@@ -1678,7 +1761,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"):
automatic = state.get("source") not in ("app", "steam")
if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}:
default = newest or TOOL
state.update(default=default, seq=now_ms(), source="update")
elif settle and newest and default == TOOL and automatic:
default = newest
state.update(default=newest, seq=now_ms(), source="update")
state.pop("own_proton", None)
+2 -1
View File
@@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) {
__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0;
struct vdec *v = vd_find(fds[0].fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vd_lock);
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vd_lock);
+31
View File
@@ -5,6 +5,7 @@
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -18,6 +19,9 @@
#include <unistd.h>
#ifndef PR_SET_SYSCALL_USER_DISPATCH
#define PR_SET_SYSCALL_USER_DISPATCH 59
#endif
#ifndef MADV_PAGEOUT
#define MADV_PAGEOUT 21
#endif
@@ -538,13 +542,40 @@ static int zr_start(void) {
return 0;
}
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
int prctl(int option, ...) {
va_list ap;
va_start(ap, option);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
va_end(ap);
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
if (selector) *dispatch = selector;
if ((unsigned long)result > -4096UL) {
errno = (int)-result;
return -1;
}
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
return (int)result;
}
static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
int saved = errno;
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
errno = saved;
if (selector) *dispatch = selector;
}
static void zr_child(void) {
+1 -1
View File
@@ -3,7 +3,7 @@ FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip \
&& apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip rpm2cpio cpio \
&& if [ "$(uname -m)" = aarch64 ]; then \
for tool in gcc g++ strip readelf objdump ar; do ln -s "$(command -v $tool)" /usr/local/bin/aarch64-linux-gnu-$tool; done; \
else \
+3
View File
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ENOSYS;
return -1;
}
if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe;
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
@@ -661,12 +662,14 @@ pid_t fork(void) {
}
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);
}
+4 -2
View File
@@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s
if (ret <= 0 || out == buf) return ret;
size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz;
memcpy(buf, out, n);
if (n < bufsiz) buf[n] = '\0';
return (ssize_t)n;
}
@@ -454,6 +455,7 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL;
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
const char *given = pathname;
DDNATV_AT_REMAP(dirfd, pathname);
// after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well
{
@@ -478,7 +480,7 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz);
}
return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz));
return copy_readlink_result(buf, bufsiz, out, postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, out, ret, outsiz));
}
// Fortified readlink variants used by dpkg / update-alternatives
@@ -776,7 +778,7 @@ char *realpath(const char *path, char *resolved_path) {
char pbuf[PATH_MAX];
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL;
if (res && g_ddnatv_root[0] != '\0') {
if (res && g_ddnatv_root[0] != '\0' && !is_rootfs_real_path(path)) {
size_t rlen = g_ddnatv_root_len;
if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) {
size_t rem_len = strlen(res + rlen);
+121 -5
View File
@@ -197,6 +197,116 @@ static int open_proc_status_at(int dirfd, const char *name, int flags) {
return open_proc_status(dir, flags);
}
static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6);
#ifndef F_SEAL_EXEC
#define F_SEAL_EXEC 0x0020
#endif
#ifndef MFD_EXEC
#define MFD_EXEC 0x0010U
#endif
static int own_fd_of_path(const char *path) {
if (!path) return -1;
const char *p;
if (strncmp(path, "/dev/fd/", 8) == 0) {
p = path + 8;
} else {
if (!is_proc_fd_link(path)) return -1;
const char *who = path + 6;
if (*who >= '0' && *who <= '9') {
long pid = 0;
while (*who >= '0' && *who <= '9') pid = pid * 10 + (*who++ - '0');
if (pid != (long)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0)) {
char task[48];
snprintf(task, sizeof(task), "/proc/self/task/%ld", pid);
if (call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)task, F_OK, 0, 0, 0) != 0) return -1;
}
}
p = strstr(path + 6, "/fd/") + 4;
}
if (*p < '0' || *p > '9') return -1;
long fd = 0;
while (*p >= '0' && *p <= '9') {
fd = fd * 10 + (*p++ - '0');
if (fd > INT_MAX) return -1;
}
return *p == '\0' ? (int)fd : -1;
}
static int copy_memfd_contents(int from, int to, off_t size) {
char chunk[32768];
off_t at = 0;
while (at < size) {
size_t want = (size_t)(size - at) < sizeof(chunk) ? (size_t)(size - at) : sizeof(chunk);
long got = call_orig_syscall(SYS_pread64, (unsigned long)from, (unsigned long)chunk, want, (unsigned long)at, 0, 0);
if (got < 0 && errno == EINTR) continue;
if (got <= 0) return -1;
long done = 0;
while (done < got) {
long put = call_orig_syscall(SYS_write, (unsigned long)to, (unsigned long)(chunk + done), (unsigned long)(got - done), 0, 0, 0);
if (put < 0 && errno == EINTR) continue;
if (put <= 0) return -1;
done += put;
}
at += got;
}
return 0;
}
static int copy_of_memfd(int src, int flags) {
char link[48], target[PATH_MAX];
snprintf(link, sizeof(link), "/proc/thread-self/fd/%d", src);
long n = call_orig_syscall(SYS_readlinkat, (unsigned long)AT_FDCWD, (unsigned long)link, (unsigned long)target, sizeof(target) - 1, 0, 0);
if (n <= 7 || strncmp(target, "/memfd:", 7) != 0) return -1;
target[n] = '\0';
char *name = target + 7;
size_t name_len = (size_t)n - 7;
if (name_len >= 10 && strcmp(name + name_len - 10, " (deleted)") == 0) name[name_len -= 10] = '\0';
if (name_len > 249) name[249] = '\0';
struct stat st;
if (call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) return -1;
long seals = call_orig_syscall(SYS_fcntl, (unsigned long)src, F_GET_SEALS, 0, 0, 0, 0);
if (seals < 0) return -1;
unsigned long mfd_flags = MFD_ALLOW_SEALING | ((flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
long copy = -1;
if (st.st_mode & 0111) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags | MFD_EXEC, 0, 0, 0, 0);
if (copy < 0) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags, 0, 0, 0, 0);
if (copy < 0) return -1;
int ok = copy_memfd_contents(src, (int)copy, st.st_size) == 0 &&
call_orig_syscall(SYS_lseek, (unsigned long)copy, 0, SEEK_SET, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fchmod, (unsigned long)copy, st.st_mode & 07777, 0, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fcntl, (unsigned long)copy, F_ADD_SEALS, (unsigned long)(seals | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK), 0, 0, 0) == 0;
if (!ok) {
call_orig_syscall(SYS_close, (unsigned long)copy, 0, 0, 0, 0, 0);
return -1;
}
return (int)copy;
}
static int reopen_denied_memfd(const char *path, int flags) {
if ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT | O_TRUNC | O_DIRECTORY | O_PATH))) return -1;
int named = own_fd_of_path(path);
if (named < 0) return -1;
long src = call_orig_syscall(SYS_fcntl, (unsigned long)named, F_DUPFD_CLOEXEC, 0, 0, 0, 0);
if (src < 0) return -1;
struct stat by_path, by_fd;
int same = call_orig_syscall(SYS_newfstatat, (unsigned long)AT_FDCWD, (unsigned long)path, (unsigned long)&by_path, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&by_fd, 0, 0, 0, 0) == 0 &&
by_path.st_dev == by_fd.st_dev && by_path.st_ino == by_fd.st_ino;
int copy = same ? copy_of_memfd((int)src, flags) : -1;
call_orig_syscall(SYS_close, (unsigned long)src, 0, 0, 0, 0, 0);
return copy;
}
static int open_or_reopen_memfd(int fd, const char *path, int flags) {
if (fd >= 0 || errno != EACCES) return fd;
int copy = reopen_denied_memfd(path, flags);
if (copy >= 0) return copy;
errno = EACCES;
return -1;
}
// Hook open
int open(const char *pathname, int flags, ...) {
static int (*orig_open)(const char *, int, ...) = NULL;
@@ -225,7 +335,7 @@ int open(const char *pathname, int flags, ...) {
forget_proc_root_fd(fd);
return fd;
}
int fd = orig_open(target, flags);
int fd = open_or_reopen_memfd(orig_open(target, flags), pathname, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
@@ -259,7 +369,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
forget_proc_root_fd(fd);
return fd;
}
int fd = orig_openat(dirfd, target, flags);
int fd = open_or_reopen_memfd(orig_openat(dirfd, target, flags), (pathname && pathname[0] == '/') ? pathname : NULL, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
@@ -304,6 +414,11 @@ static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, u
return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6);
}
static int openat2_or_reopen_memfd(int fd, const char *pathname, const struct ddnatv_open_how *how) {
if (fd >= 0 || errno != EACCES || pathname[0] != '/' || !how || how->resolve) return fd;
return open_or_reopen_memfd(fd, pathname, (int)how->flags);
}
// Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal).
// Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels
// without openat2, e.g. Android < 5.6) emulates with plain openat instead of
@@ -334,12 +449,12 @@ int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_openat2) {
int ret = orig_openat2(dirfd, target, how, usize);
if (ret >= 0 || errno != ENOSYS) return ret;
if (ret >= 0 || errno != ENOSYS) return openat2_or_reopen_memfd(ret, pathname, how);
}
#ifdef __NR_openat2
long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0);
if (sret >= 0 || errno != ENOSYS) {
return (int)sret;
return openat2_or_reopen_memfd((int)sret, pathname, how);
}
#endif
if (!how || usize < 16) {
@@ -646,6 +761,7 @@ int lstat(const char *pathname, struct stat *statbuf) {
int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
const char *given = pathname;
DDNATV_AT_REMAP(dirfd, pathname);
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? ((flags & AT_SYMLINK_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
@@ -665,7 +781,7 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1;
if (llen > 0) {
ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf));
ssize_t post_len = postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, link_buf, llen, sizeof(link_buf));
if (post_len > 0) {
statbuf->st_size = post_len;
}
+189 -2
View File
@@ -878,6 +878,9 @@ static void ddh_apply_inherited(void) {
}
}
static void ddh_open_parents(void);
static void ddh_record_own_parent(void);
__attribute__((constructor)) static void ddh_init(void) {
ddh_apply_inherited();
ddh_find_worker_binder();
@@ -885,6 +888,9 @@ __attribute__((constructor)) static void ddh_init(void) {
ddh_find_parent_table();
// tests only: as when the table could not be made here, and the first fork makes it
if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare();
ddh_open_parents();
ddh_record_own_parent();
ddnatv_manage_sigchld();
}
static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) {
@@ -1274,6 +1280,30 @@ static int ddh_job_control_job(void) {
return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent);
}
// Whether this is a program a desktop launcher starts for the user (DD_HANDOFF_LAUNCHERS names the
// launchers: Plasma's shell, KRunner, Dolphin): a plain fork and exec, still in the launcher's process
// group and session, with no controlling terminal. Those launchers are Qt programs, which wait with
// waitpid() once they have no pidfds (privileged.c), so the program's exit reaches them. A child the
// launcher set up as a terminal's (a session and a terminal of its own) stays its own child.
static int ddh_launched(const char *filename, char *const argv[], char *const envp[]) {
const char *list = ddh_env(envp, "DD_HANDOFF_LAUNCHERS");
if (!list || !*list || ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv)) return 0;
pid_t parent = (pid_t)syscall(SYS_getppid);
char path[48], name[32];
snprintf(path, sizeof(path), "/proc/%d/comm", (int)parent);
if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0;
name[strcspn(name, "\n")] = 0;
if (!ddh_listed(list, name, NULL)) return 0;
if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent) ||
(pid_t)syscall(SYS_getsid, 0) != (pid_t)syscall(SYS_getsid, parent))
return 0;
// /dev/tty opens only for a process with a controlling terminal
int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty",
O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0);
if (tty >= 0) syscall(SYS_close, tty);
return tty < 0;
}
static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) {
if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0;
// Not a job in the foreground of its controlling terminal: a handed-off program has none (the
@@ -1302,7 +1332,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename
struct ddh_buf b = {line, 0, sizeof(line) - 1};
ddh_puts(&b, "ddnatv handoff: ");
ddh_putint(&b, getpid());
ddh_puts(&b, " ");
ddh_puts(&b, " (parent ");
ddh_putint(&b, (long)syscall(SYS_getppid));
ddh_puts(&b, ", session ");
ddh_putint(&b, (long)syscall(SYS_getsid, 0));
ddh_puts(&b, ") ");
ddh_puts(&b, what);
ddh_puts(&b, " ");
ddh_puts(&b, filename ? filename : "?");
@@ -1364,7 +1398,8 @@ static void ddh_try_as(const char *filename, char *const argv[], char *const env
ddh_debug(envp, "a job-control job:", filename);
return;
}
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_pressed(match_file, match_argv, envp)) {
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_launched(match_file, match_argv, envp) &&
!ddh_pressed(match_file, match_argv, envp)) {
ddh_debug(envp, "not listed:", filename);
return;
}
@@ -1644,6 +1679,158 @@ static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) {
return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0;
}
// ---- children no wait will come for ------------------------------------------------------------
//
// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose
// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels
// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the
// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records
// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the
// session): a zombie whose record names another parent was adopted.
static uint64_t *g_ddh_parents;
static void ddh_open_parents(void) {
const char *name = getenv("DD_PARENTS");
if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return;
char path[PATH_MAX];
const char *real = rewrite_path(name, path, sizeof(path));
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0);
if (fd < 0) return;
size_t size = (size_t)DDH_FORKS * sizeof(uint64_t);
struct stat st;
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size)
call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0);
// past the file's end a page would fault (SIGBUS): mapped only once the file has its size
void *map = MAP_FAILED;
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size)
map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
syscall(SYS_close, fd);
if (map == MAP_FAILED) return;
uint64_t *none = NULL;
if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))
munmap(map, size);
}
static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; }
static void ddh_record_parent(pid_t me, pid_t parent) {
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
if (!map || me <= 0) return;
int saved = errno;
long start = ddh_start_time(me);
errno = saved;
if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE);
}
// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own
// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is
// still the one that started it (a vfork()'s waits for the exec).
static void ddh_record_own_parent(void) {
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
if (!map) return;
pid_t me = (pid_t)syscall(SYS_getpid);
int saved = errno;
long start = ddh_start_time(me);
errno = saved;
if (start <= 0) return;
uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE);
if ((uint32_t)r == (uint32_t)start && r >> 32) return;
__atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE);
}
// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read.
static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) {
char path[48] = "/proc/", digits[16], stat[512];
int n = 0, len = 6;
for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10);
while (n) path[len++] = digits[--n];
memcpy(path + len, "/stat", 6);
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0);
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
if (got <= 0) return 0;
stat[got] = 0;
char *p = strrchr(stat, ')');
if (!p || p[1] != ' ' || !p[2]) return 0;
*state = p[2];
// ") S PPID": field 4; starttime is field 22
long parent = 0;
for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0');
*ppid = (pid_t)parent;
for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' ');
long t = 0;
for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0');
*start = t;
return 1;
}
// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's
// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this
// process adopted. 1 when it did.
static int ddh_reap_unwaited(pid_t me, pid_t child) {
char state = 0;
long start = 0;
pid_t ppid = 0;
if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0;
struct ddh_entry *e = ddh_find(child);
int32_t gen = e ? ddh_gen_of(e, child) : 0;
if (gen) {
if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0;
ddh_mark_reaped(e, gen);
return 1;
}
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0;
if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0;
return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child;
}
// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will
// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc.
static void ddh_reap_unclaimed(void) {
if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return;
int saved = errno;
pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0);
// past 64 reaped this way, the rest from /proc too
int scan = 1;
for (int i = 0; i < 64; i++) {
siginfo_t si;
memset(&si, 0, sizeof(si));
if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) {
scan = 0;
break;
}
if (!ddh_reap_unwaited(me, si.si_pid)) {
break;
}
}
int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc",
O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1;
char buf[2048];
while (dir >= 0) {
long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0);
if (n <= 0) break;
for (long off = 0; off < n;) {
struct ddh_reap_dirent {
uint64_t ino;
int64_t off;
unsigned short reclen;
unsigned char type;
char name[];
} *d = (struct ddh_reap_dirent *)(buf + off);
off += d->reclen;
long pid = 0;
const char *c = d->name;
for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0');
if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid);
}
}
if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0);
errno = saved;
}
// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it.
static int ddh_take(struct ddh_entry *e) {
int expected = DDH_EXITED;
+30 -2
View File
@@ -952,6 +952,30 @@ static int is_proc_fd_link(const char *path) {
return *p == '\0';
}
static int is_proc_cwd_link(const char *path) {
if (!path || strncmp(path, "/proc/", 6) != 0) return 0;
const char *p = path + 6;
if (strncmp(p, "self/", 5) == 0) {
p += 5;
} else if (strncmp(p, "thread-self/", 12) == 0) {
p += 12;
} else {
if (*p < '0' || *p > '9') return 0;
while (*p >= '0' && *p <= '9') p++;
if (*p != '/') return 0;
p++;
}
return strcmp(p, "cwd") == 0;
}
static int is_rootfs_real_path(const char *path) {
return path && g_ddnatv_root_len > 0 && is_path_prefix(path, g_ddnatv_root, g_ddnatv_root_len);
}
static int link_answers_in_kernel_form(const char *linkpath, const char *named) {
return is_proc_fd_link(linkpath) || is_proc_cwd_link(linkpath) || is_rootfs_real_path(named);
}
// The guest path of a folder that a session mount puts outside the rootfs, for what the kernel
// reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for
// Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit.
@@ -989,7 +1013,7 @@ static char *guest_path_of_allocated_mount_source(char *res) {
return grown;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
static ssize_t postprocess_named_readlink(const char *linkpath, const char *named, char *buf, ssize_t ret, size_t bufsiz) {
if (ret <= 0) return ret;
if ((size_t)ret < bufsiz) {
buf[ret] = '\0';
@@ -998,7 +1022,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL);
// 1. Strip g_ddnatv_root if target starts with it
if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) {
if (g_ddnatv_root_len > 0 && !link_answers_in_kernel_form(linkpath, named)) {
size_t rlen = g_ddnatv_root_len;
if ((size_t)ret >= rlen && memcmp(buf, g_ddnatv_root, rlen) == 0 &&
((size_t)ret == rlen || buf[rlen] == '/')) {
@@ -1053,6 +1077,10 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
return ret;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
return postprocess_named_readlink(linkpath, linkpath, buf, ret, bufsiz);
}
// Android's SELinux label, which the xattr hooks keep away from Ubuntu programs.
static const char k_selinux_xattr[] = "security.selinux";
+43 -1
View File
@@ -235,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) {
return 0;
}
// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a
// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the
// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread,
// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus.
static int fatal_limit(int resource, const struct rlimit *rlim) {
return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0;
}
int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) {
if (sandbox_only_limit((int)resource, rlim)) return 0;
if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0;
static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL;
#if defined(__USE_FILE_OFFSET64) && !defined(__LP64__)
// With 64-bit file offsets on a 32-bit system this function is setrlimit64
@@ -339,6 +347,13 @@ __asm__(".globl setrlimit64\n" ".set setrlimit64, setrlimit\n");
#endif
#endif
#ifndef CLONE_PIDFD
#define CLONE_PIDFD 0x00001000
#endif
#ifndef P_PIDFD
#define P_PIDFD 3
#endif
#ifndef SECCOMP_SET_MODE_STRICT
#define SECCOMP_SET_MODE_STRICT 0
#endif
@@ -639,6 +654,33 @@ long syscall(long number, ...) {
}
#endif
#ifdef __NR_clone
if (number == __NR_clone && (arg1 & CLONE_PIDFD)) {
errno = EINVAL;
return -1;
}
#endif
#ifdef __NR_waitid
if (number == __NR_waitid && (int)arg1 == P_PIDFD) {
errno = EINVAL;
return -1;
}
#endif
#ifdef __NR_execve
if (number == __NR_execve) {
return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3);
}
#endif
#ifdef __NR_execveat
if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' &&
(((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) {
return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4);
}
#endif
#ifdef __NR_clone3
if (number == __NR_clone3) {
errno = ENOSYS;
+1
View File
@@ -307,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
size_t len = strlen(out_path);
size_t copy_len = (len < bufsiz) ? len : bufsiz;
memcpy(buf, out_path, copy_len);
if (copy_len < bufsiz) buf[copy_len] = '\0';
return (ssize_t)copy_len;
}
+97 -6
View File
@@ -10,6 +10,12 @@
#define SYS_SECCOMP 1
#endif
#if defined(__aarch64__)
#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U
#else
#define DDNATV_HOST_AUDIT_ARCH 0x40000028U
#endif
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *);
// A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's
@@ -57,7 +63,13 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
if (!ctx || !info) return;
if (info->si_code != SYS_SECCOMP) {
int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH;
if (!host_trap && g_app_sigsys_set) {
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
else g_app_sigsys.sa_handler(sig);
return;
}
if (!host_trap) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (real_sig) {
struct sigaction sa_dfl;
@@ -69,11 +81,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
raise(sig);
return;
}
if (info->si_errno != 0 && g_app_sigsys_set) {
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
else g_app_sigsys.sa_handler(sig);
return;
}
ucontext_t *uctx = (ucontext_t *)ctx;
int sys_nr = info->si_syscall;
@@ -174,10 +181,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) {
real_sig(SIGSYS, &sa, NULL);
}
// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it
// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for
// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD
// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the
// like return EINTR when a child exits, which a program that never had one may not expect.
static struct sigaction g_app_sigchld;
static int g_sigchld_managed;
static int g_sigchld_on_default;
static void ddh_reap_unclaimed(void);
static int ddh_listed(const char *list, const char *name, char *const argv[]);
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *));
static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) {
struct sigaction app = g_app_sigchld;
if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) {
if (app.sa_flags & SA_RESETHAND) {
// as the kernel would: the default from now on, with the handler only for a named program
g_app_sigchld.sa_handler = SIG_DFL;
g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND);
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
int saved = errno;
if (real_sig) ddnatv_apply_sigchld(real_sig);
errno = saved;
}
if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx);
else app.sa_handler(sig);
}
ddh_reap_unclaimed();
}
// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN,
// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above.
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) {
const struct sigaction *app = &g_app_sigchld;
int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN;
if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default))
return real_sig(SIGCHLD, app, NULL);
struct sigaction k;
memset(&k, 0, sizeof(k));
k.sa_sigaction = ddnatv_sigchld_handler;
k.sa_mask = app->sa_mask;
k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP));
return real_sig(SIGCHLD, &k, NULL);
}
static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *),
const struct sigaction *act, struct sigaction *oldact) {
struct sigaction prev = g_app_sigchld;
if (act) {
g_app_sigchld = *act;
if (ddnatv_apply_sigchld(real_sig) != 0) {
int err = errno;
g_app_sigchld = prev;
errno = err;
return -1;
}
}
if (oldact) *oldact = prev;
return 0;
}
// From the hook's start (handoff.c), once the parents file is open
static void ddnatv_manage_sigchld(void) {
if (!getenv("DD_PARENTS")) return;
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return;
const char *named = getenv("DD_REAP_ADOPTED");
g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL);
if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1;
}
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig) return -1;
if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact);
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return real_sig(signum, act, oldact);
@@ -192,6 +272,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda
static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL;
if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction");
if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact);
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0;
@@ -210,6 +291,16 @@ typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler) {
static sighandler_t (*orig_signal)(int, sighandler_t) = NULL;
if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal");
if (signum == SIGCHLD && g_sigchld_managed) {
// glibc's signal(): BSD semantics
struct sigaction act, old;
memset(&act, 0, sizeof(act));
act.sa_handler = handler;
act.sa_flags = SA_RESTART;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGCHLD);
return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR;
}
if (signum == SIGSYS) {
struct sigaction act, old;
memset(&act, 0, sizeof(act));
+110 -6
View File
@@ -10,6 +10,7 @@ import argparse
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import struct
@@ -49,8 +50,14 @@ LOCAL_ANDROID_SOURCES = {'app/src/main/cpp/CMakeLists.txt',
'app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c',
'app/src/main/cpp/waylandcomp/src/spatialpose.c',
'app/src/main/cpp/waylandcomp/CMakeLists.txt'}
LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr'}
LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-session',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input'}
IME_SOURCES = {'tools/ime/packages.json', 'tools/ime/prepare.py', 'tools/ime/smoke.py'}
IME_MANIFEST = 'usr/local/share/droiddeck/ime-files.json'
IME_PACKAGES = 'build/windows-setup/ime-packages'
VR_PREFIX = 'assets/linuxfs/usr/local/lib/droiddeck-vr/'
CHECK_PATHS = list(dict.fromkeys(runtime.SOURCE_PATHS + [
'app/src/main/cpp', 'app/src/main/jniLibs', 'app/src/main/rust/stores', 'tools/vr']))
@@ -82,20 +89,23 @@ def check_sources():
if git('merge-tree', '--write-tree', DONOR_PR_SOURCE, DONOR_MAIN_SOURCE).decode().splitlines()[0] != DONOR_TREE:
raise ValueError('The donor CI merge does not match the audited source tree')
helper_sources = {path.relative_to(ROOT).as_posix() for path in source_assets()}
reviewed = LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | (LOCAL_SESSION_HELPERS & helper_sources)
reviewed = (LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | IME_SOURCES |
(LOCAL_SESSION_HELPERS & helper_sources))
unexpected = {p for p in changed(AUDITED_SOURCE, 'HEAD') - reviewed if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Sources changed since the component audit:\n' + '\n'.join(sorted(unexpected)))
local = changed('HEAD')
untracked = set(filter(None, git('ls-files', '--others', '--exclude-standard', '-z',
'--', *CHECK_PATHS).decode().split('\0')))
unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES)
unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES - IME_SOURCES)
if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Unreviewed runtime/native/Rust changes:\n' + '\n'.join(sorted(unexpected)))
classifications = {}
for path in sorted(changed(DONOR_TREE, 'HEAD') | local | untracked):
if vr_build.is_source(path):
if path in IME_SOURCES:
action = 'regenerated from checksum-pinned RPMs; never reused from donor'
elif vr_build.is_source(path):
action = 'VR component rebuilt from current source and verified; never imported from donor'
elif path in LOCAL_ANDROID_SOURCES:
action = 'Android native source compiled by Gradle; not imported from donor'
@@ -161,6 +171,92 @@ def read_gamescope(path):
return files, pins
def find_docker():
docker = shutil.which('docker')
if docker:
return docker
desktop = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Docker/Docker/resources/bin/docker.exe'
if desktop.is_file():
return str(desktop)
raise ValueError('Docker is required to prepare IME files on Windows; install Docker Desktop or add docker to PATH')
def prepare_ime(image):
workspace = ROOT / 'build/windows-setup'
workspace.mkdir(parents=True, exist_ok=True)
packages = ROOT / IME_PACKAGES
packages.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='droiddeck-ime-', dir=workspace) as folder:
temporary = Path(folder)
linuxfs = temporary / 'linuxfs'
linuxfs.mkdir()
script = ROOT / 'tools/ime/prepare.py'
if sys.platform == 'win32':
docker = find_docker()
inspect_cmd = [docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image]
inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False)
fields = inspected.stdout.strip().split() if inspected.returncode == 0 else []
image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else ''
if not image_id and image == vr_build.IMAGE:
dockerfile = (ROOT / 'tools/local-cross.Dockerfile').read_bytes().replace(b'\r\n', b'\n')
try:
subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image,
'--file', '-', str(temporary)], input=dockerfile, check=True)
except subprocess.CalledProcessError as error:
raise ValueError('IME preparation failed to build default compiler Docker image ' + image +
'; inspect the Docker build output above, resolve the build error, and rerun preparation') from error
inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False)
fields = inspected.stdout.strip().split() if inspected.returncode == 0 else []
image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else ''
if not image_id:
detail = inspected.stdout.strip() if inspected.returncode == 0 else inspected.stderr.strip()
detail = detail or 'no image id or platform returned'
raise ValueError('IME preparation requires the existing Docker image ' + image +
' for linux/amd64; build or load it first (inspect result: ' + detail + ')')
snapshot = temporary / 'src'
(snapshot / 'tools/ime').mkdir(parents=True)
shutil.copy2(script, snapshot / 'tools/ime/prepare.py')
shutil.copy2(ROOT / 'tools/ime/packages.json', snapshot / 'tools/ime/packages.json')
command = [docker, 'run', '--rm', '--platform', 'linux/amd64',
'-v', str(snapshot) + ':/src:ro',
'-v', str(packages) + ':/cache',
'-v', str(linuxfs) + ':/out',
image_id, 'sh', '-c',
'for tool in rpm2cpio cpio; do command -v "$tool" >/dev/null 2>&1 || { '
'echo "missing $tool; rebuild compiler image using tools/local-cross.Dockerfile" >&2; exit 1; }; done; '
'exec python3 /src/tools/ime/prepare.py --packages /cache --download --output /out']
else:
command = [sys.executable, str(script), '--packages', str(packages), '--download',
'--output', str(linuxfs)]
try:
subprocess.run(command, check=True)
except subprocess.CalledProcessError as error:
if sys.platform == 'win32':
raise ValueError('IME preparation failed; ensure Docker is running and image ' + image +
' is available') from error
raise
manifest_path = linuxfs / IME_MANIFEST
if not manifest_path.is_file():
raise ValueError('IME preparation did not produce ' + IME_MANIFEST)
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
if manifest.get('version') != 1 or not isinstance(manifest.get('files'), dict):
raise ValueError('Unexpected IME manifest format')
files = {}
for relative, entry in sorted(manifest['files'].items()):
if not isinstance(entry, dict):
raise ValueError('Unexpected IME manifest entry: ' + str(relative))
validate_relative(relative)
path = linuxfs / relative
if not path.is_file():
raise ValueError('IME manifest references a missing file: ' + relative)
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != entry.get('sha256'):
raise ValueError('IME file checksum mismatch: ' + relative)
files[relative] = data
files[IME_MANIFEST] = manifest_path.read_bytes()
return files, manifest
def validate_rebuilt(path, machine):
data = path.read_bytes()
if len(data) < 20 or data[:4] != b'\x7fELF' or data[5] != 1 or struct.unpack('<H', data[18:20])[0] != machine:
@@ -212,6 +308,7 @@ def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_in
vr_files, vr_manifest = vr_build.build(ROOT / 'build/windows-setup/vr', vk_include, root=ROOT, image=vr_image)
else:
vr_files, vr_manifest = vr_build.validate(rebuilt_vr, vk_include, root=ROOT)
ime_files, ime_manifest = prepare_ime(vr_image)
helpers = source_assets()
helper_assets = set(helpers.values())
plan = {}
@@ -258,6 +355,11 @@ def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_in
checked_output(target)
plan[target] = data
origins[target] = 'VR rebuilt from current source; source and output checksums verified'
for name, data in ime_files.items():
target = 'app/src/main/assets/linuxfs/' + name
checked_output(target)
plan[target] = data
origins[target] = 'regenerated from checksum-pinned RPMs; never reused from donor'
expected = set(plan) | {'app/src/main/' + name for name in helper_assets}
for tree in ('linuxfs', 'directaudio', 'droiddeck-esync'):
base = ROOT / 'app/src/main/assets' / tree
@@ -294,6 +396,7 @@ def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_in
'archive_sha256': pins['GAMESCOPE_SHA256']},
'tracked_files_verified': tracked,
'vr_build': vr_manifest,
'ime_build': ime_manifest,
'outputs': {name: {'origin': origins[name], 'sha256': hashlib.sha256(data).hexdigest()}
for name, data in sorted(plan.items())},
'preload_sources': {path.relative_to(ROOT).as_posix(): runtime.digest(path)
@@ -319,7 +422,8 @@ def main():
'AppData/Local/Android/Sdk/ndk/27.3.13750724/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-strip.exe')
parser.add_argument('--rebuilt-vr', type=Path, help='Reuse a VR build with vr-build.json; default rebuilds in Docker')
parser.add_argument('--vk-include', type=Path, help='NDK Vulkan headers; defaults to the sysroot beside --llvm-strip')
parser.add_argument('--vr-image', default=vr_build.IMAGE, help='Docker compiler image for a fresh VR build')
parser.add_argument('--vr-image', default=vr_build.IMAGE,
help='Docker compiler image for VR/IME preparation; default is built if missing')
parser.add_argument('--check-sources', action='store_true', help='Audit source differences without extracting files')
args = parser.parse_args()
zstd = ROOT / 'build/windows-setup/tools/zstd/zstd.exe'
+6 -22
View File
@@ -7,37 +7,21 @@ MARK="<!-- droiddeck-pr-build -->"
echo
[ -f /tmp/pr-merge.md ] && cat /tmp/pr-merge.md
echo
case "$BUILD_OUTCOME:$UNIT_TEST_OUTCOME:$APK_OUTCOME" in
success:success:success)
case "$BUILD_OUTCOME:$APK_OUTCOME" in
success:success)
echo "### Build passed"
echo
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key."
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. Unit tests run in the separate **Unit tests** workflow and must pass before merging."
echo
echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds after the full build passes. Label the PR \`no-test-build\` to skip that."
echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds once the APK compiles. Label the PR \`no-test-build\` to skip that."
echo "For other PRs, a maintainer can add the \`publish-test\` label to request a signed build."
echo
echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`."
;;
success:success:*)
success:*)
echo "### APK publication incomplete"
echo
echo "Compilation and unit tests passed, but APK publication did not complete. See [the run]($RUN_URL)."
;;
success:failure:*)
echo "### ERROR: Unit tests failed"
echo
echo "The APK compiled, but unit tests failed. No installable artifact was published."
echo
if [ -n "$TEST_DIAGNOSTICS_URL" ]; then
echo "The [unit-test-results]($TEST_DIAGNOSTICS_URL) artifact contains the test log and any generated reports."
else
echo "The test diagnostics upload did not complete. See [the test log]($RUN_URL)."
fi
;;
success:*)
echo "### Build incomplete"
echo
echo "The APK compiled, but unit tests did not complete successfully. See [the run]($RUN_URL)."
echo "Compilation passed, but APK publication did not complete. See [the run]($RUN_URL)."
;;
failure:*)
echo "### ERROR: Build failed"
+5 -1
View File
@@ -25,7 +25,7 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/linuxfs', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/ime', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'tools/gpuload', 'app/src/main/resources/rockstar/legacy-cipher.bin',
@@ -128,6 +128,10 @@ def required():
['xodus-cli', 'xodus-service', 'version', 'backend.lock.json', 'runtime.lock.json', 'LICENSE.xodus', 'LICENSE.nexus', 'LICENSE.LGPL-2.1', 'LICENSE.nghttp2',
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll',
'compat/PlayFabGameSave.dll', 'LICENSE.runtime-compat']]
paths += ['assets/linuxfs/' + name for name in
['usr/local/share/droiddeck/ime-files.json', 'usr/local/share/droiddeck/ibus.profile',
'usr/local/lib/droiddeck-ime/ibus-engine-pinyin', 'usr/local/lib/droiddeck-ime/libpyzy-1.0.so.0',
'usr/local/lib/droiddeck-ime/liblua-5.4.so', 'usr/share/pyzy/db/android.db']]
for driver in ['linux-wine11', 'linux-wine11-systhread']:
paths += ['assets/directaudio/' + driver + '/' + name for name in
['aarch64-unix/winedirectaudio.so', 'aarch64-windows/winedirectaudio.drv',
+1 -1
View File
@@ -28,7 +28,7 @@ else
python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" "$P.agentchat=$pkg.agentchat" \
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
fi
+51 -11
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import json
import os
import re
import subprocess
import sys
import time
@@ -40,6 +41,39 @@ def compilation_state(run, jobs):
return "failure" if run["status"] == "completed" else "pending"
def run_state(run):
if run["status"] != "completed":
return "pending"
return "success" if run["conclusion"] == "success" else "failure"
def latest_run(repo, workflow, sha, source_event):
query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20})
runs = api(f"repos/{repo}/actions/workflows/{workflow}/runs?{query}")["workflow_runs"]
runs = [item for item in runs if item["head_sha"] == sha]
return max(runs, key=lambda item: item["id"]) if runs else None
def pull_request_run_base(run, sha):
# A PR can reopen at the same head SHA after main advances. Do not mix results
# from different event snapshots, even if both workflows individually passed.
title = run.get("display_title") or ""
match = re.search(rf" on {re.escape(sha)} against ([0-9a-f]{{40}})$", title)
return match[1] if match else None
def combined_state(build, tests):
if build == "failure":
return "failure", "APK compilation failed"
if tests == "failure":
return "failure", "Unit tests failed"
if build == "pending":
return "pending", "Source validated; awaiting APK compilation"
if tests == "pending":
return "pending", "APK compiled; awaiting unit tests"
return "success", "Source validation, APK compilation and unit tests passed"
def fetch_source(ref, sha):
subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True)
fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip()
@@ -123,19 +157,25 @@ def main():
state = "success"
description = "Source validated; no APK source changes"
return
query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20})
runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"]
runs = [item for item in runs if item["head_sha"] == sha]
if runs:
latest = max(runs, key=lambda item: item["id"])
build_state = tests_state = "pending"
latest = latest_run(repo, "build.yml", sha, source_event)
if latest:
jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"]
state = compilation_state(latest, jobs)
build_state = compilation_state(latest, jobs)
target = latest["html_url"]
else:
state = "pending"
description = {"pending": "Source validated; awaiting APK compilation",
"success": "Source validation and APK compilation passed",
"failure": "APK compilation failed"}[state]
tests = latest_run(repo, "unit-tests.yml", sha, source_event)
if tests:
if pr and latest and build_state == "success":
build_base = pull_request_run_base(latest, sha)
tests_base = pull_request_run_base(tests, sha)
if not build_base or build_base != tests_base:
state = "pending"
description = "APK and unit tests must run against the same main commit"
return
tests_state = run_state(tests)
if tests_state == "failure" and build_state != "failure":
target = tests["html_url"]
state, description = combined_state(build_state, tests_state)
finally:
api(f"repos/{repo}/statuses/{sha}", "--method", "POST",
"-f", "context=Build APK", "-f", f"state={state}",
+42 -3
View File
@@ -67,7 +67,12 @@ static void VKAPI_CALL pipeline_barrier(VkCommandBuffer cmd, VkPipelineStageFlag
static void VKAPI_CALL begin_pass(VkCommandBuffer c, const VkRenderPassBeginInfo *i, VkSubpassContents s) {}
static void VKAPI_CALL viewport(VkCommandBuffer c, uint32_t f, uint32_t n, const VkViewport *v) {}
static void VKAPI_CALL scissor(VkCommandBuffer c, uint32_t f, uint32_t n, const VkRect2D *v) {}
static void VKAPI_CALL bind_pipeline(VkCommandBuffer c, VkPipelineBindPoint b, VkPipeline p) {}
static unsigned area_copies, search_copies, weight_passes;
static void VKAPI_CALL bind_pipeline(VkCommandBuffer c, VkPipelineBindPoint b, VkPipeline p) {
if (p != g_pipe[P_SMAA_WEIGHTS]) return;
weight_passes++;
assert(area_copies == weight_passes && search_copies == weight_passes);
}
static void VKAPI_CALL bind_sets(VkCommandBuffer c, VkPipelineBindPoint b, VkPipelineLayout l, uint32_t f,
uint32_t n, const VkDescriptorSet *s, uint32_t nd, const uint32_t *d) {}
static void VKAPI_CALL push(VkCommandBuffer c, VkPipelineLayout l, VkShaderStageFlags s, uint32_t o,
@@ -77,13 +82,45 @@ static void VKAPI_CALL end_pass(VkCommandBuffer c) {}
static void VKAPI_CALL blit(VkCommandBuffer c, VkImage a, VkImageLayout al, VkImage b, VkImageLayout bl,
uint32_t n, const VkImageBlit *r, VkFilter f) {}
static void check_generated_settings_and_layout(void) {
static void VKAPI_CALL copy_table(VkCommandBuffer c, VkBuffer b, VkImage i, VkImageLayout l,
uint32_t n, const VkBufferImageCopy *r) {
assert(i == g_smaa_area.img || i == g_smaa_search.img);
if (i == g_smaa_area.img) area_copies++;
else search_copies++;
}
static void record_into_stubs(void) {
g_vk.CmdPipelineBarrier = pipeline_barrier;
g_vk.CmdBeginRenderPass = begin_pass;
g_vk.CmdSetViewport = viewport; g_vk.CmdSetScissor = scissor;
g_vk.CmdBindPipeline = bind_pipeline; g_vk.CmdBindDescriptorSets = bind_sets;
g_vk.CmdPushConstants = push; g_vk.CmdDraw = draw; g_vk.CmdEndRenderPass = end_pass;
g_vk.CmdBlitImage = blit;
g_vk.CmdCopyBufferToImage = copy_table;
}
static void check_smaa_tables(void) {
record_into_stubs();
g_rp = g_smaa_edge_rp = g_smaa_weights_rp = (VkRenderPass)(uintptr_t)5;
for (int k = P_FXAA; k <= P_SMAA_BLEND; k++) g_pipe[k] = (VkPipeline)(uintptr_t)(60 + k);
g_smaa_buf = (VkBuffer)(uintptr_t)7;
g_smaa_area.img = (VkImage)(uintptr_t)40;
g_smaa_search.img = (VkImage)(uintptr_t)41;
g_ready = 1;
struct fx_target *targets[] = {&g_t[0], &g_smaa_edges, &g_smaa_weights};
for (int k = 0; k < 3; k++) {
targets[k]->img = (VkImage)(uintptr_t)(30 + k); targets[k]->w = 1280; targets[k]->h = 720;
}
vkp_effects_set_screen(0, 0, 1, 100, 2, 0, 0, 0);
for (unsigned frame = 1; frame <= 2; frame++) {
int w, h;
assert(vkp_effects_run(VK_NULL_HANDLE, (VkImage)(uintptr_t)10, 1280, 720, 1280, 720, &w, &h) == g_t[0].img);
assert(weight_passes == frame && area_copies == frame && search_copies == frame);
}
}
static void check_generated_settings_and_layout(void) {
record_into_stubs();
g_rp = (VkRenderPass)(uintptr_t)5;
g_pipe[P_SGSR] = (VkPipeline)(uintptr_t)6;
g_pipe[P_COLOR] = (VkPipeline)(uintptr_t)7;
@@ -93,7 +130,7 @@ static void check_generated_settings_and_layout(void) {
t->img = (VkImage)(uintptr_t)(30 + k); t->w = 1920; t->h = 1080;
}
vkp_effects_set_scaling(3);
assert(vkp_effects_prepare_generated());
assert(vkp_effects_prepare_generated(1280, 720, 1920, 1080));
vkp_effects_set_scaling(0);
vkp_effects_set_cas(1, 75);
vkp_effects_sync();
@@ -153,6 +190,8 @@ int main(int argc, char **argv) {
VkImageView original = bound_view;
if (!strcmp(argv[1], "generated-layout")) {
check_generated_settings_and_layout();
} else if (!strcmp(argv[1], "smaa-tables")) {
check_smaa_tables();
} else if (!strcmp(argv[1], "generated")) {
for (int k = 1; k < FX_CONTEXTS; k++) {
g_context = k;
+51
View File
@@ -0,0 +1,51 @@
#define _GNU_SOURCE
#include "frame_worker_peer.h"
#include <assert.h>
#include <fcntl.h>
#include <poll.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/wait.h>
#include <unistd.h>
static uint64_t start_ticks(pid_t id) {
char proc[64], line[4096]; snprintf(proc,sizeof(proc),"/proc/%d/stat",id);
FILE *f=fopen(proc,"r");assert(f);assert(fgets(line,sizeof(line),f));fclose(f);
uint64_t ticks=0;
assert(dd_worker_parse_start(line,&ticks)==DD_WORKER_STAT_OK);
return ticks;
}
static bool check_maps(const struct dd_worker_grant *g,pid_t id,uint64_t ticks) {
char proc[64],line[4096];snprintf(proc,sizeof(proc),"/proc/%d/maps",id);
FILE *f=fopen(proc,"r");assert(f);bool found=false;
while(fgets(line,sizeof(line),f)) if(dd_worker_grant_matches(g,4,getuid(),id,ticks,4,line)){ found=true;break;}
fclose(f);return found;
}
int main(void){
char p[]="/tmp/dd-live-map.XXXXXX";int fd=mkstemp(p);assert(fd>=0);
assert(ftruncate(fd,4096)==0);struct stat st;assert(fstat(fd,&st)==0);
int a[2],b[2];assert(pipe(a)==0&&pipe(b)==0);pid_t id=fork();assert(id>=0);
if(id==0){
close(a[0]);close(b[1]);
void *m=mmap(NULL,4096,PROT_READ|PROT_EXEC,MAP_PRIVATE,fd,0);assert(m!=MAP_FAILED);
assert(write(a[1],"y",1)==1);
char c;assert(read(b[0],&c,1)==1);assert(mprotect(m,4096,PROT_READ)==0);
assert(write(a[1],"y",1)==1);assert(read(b[0],&c,1)==1);_exit(0);
}
close(a[1]);close(b[0]);char c;assert(read(a[0],&c,1)==1);
int pfd=syscall(SYS_pidfd_open,id,0);assert(pfd>=0);
struct pollfd pfd_poll={.fd=pfd,.events=POLLIN};assert(poll(&pfd_poll,1,0)==0);
uint64_t start=start_ticks(id);assert(start);
struct dd_worker_grant g={.owner=4,.uid=getuid(),.pid=id,.dev_major=major(st.st_dev),.dev_minor=minor(st.st_dev),.ino=st.st_ino,.start_ticks=start,.expires=10,.canonical_file=p,.app_launch_verified=true,.final_go=true};
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED,0,start+1));
assert(!check_maps(&g,id,start+1)); // A forged self receipt fails against live post-exec ticks.
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK,start,start));
assert(check_maps(&g,id,start));
g.final_go=false;assert(!check_maps(&g,id,start));g.final_go=true;
assert(write(b[1],"n",1)==1);assert(read(a[0],&c,1)==1);assert(!check_maps(&g,id,start));
assert(write(b[1],"n",1)==1);assert(poll(&pfd_poll,1,2000)==1);
assert(pfd_poll.revents&POLLIN);int status;assert(waitpid(id,&status,0)==id&&WIFEXITED(status)&&WEXITSTATUS(status)==0);
close(fd); close(pfd);unlink(p); puts("Live executable map, start-time reuse rejection, no-GO revocation, non-executable map rejection, and pidfd exit readiness passed.");
}
+48
View File
@@ -0,0 +1,48 @@
#include "frame_worker_peer.h"
#include <assert.h>
static const char file[]="/app/private/linuxfs/opt/droiddeck-agent/bin/gamescope";
static const char good[]="1000-2000 r-xp 00001000 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope\n";
int main(void) {
uint64_t ticks = 0;
assert(dd_worker_parse_start("650 (with ) parens) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 251191 123\n", &ticks) == DD_WORKER_STAT_OK);
assert(ticks == 251191);
assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 0 123\n", &ticks) == DD_WORKER_STAT_ZERO);
assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551616 123\n", &ticks) == DD_WORKER_STAT_PARSE);
assert(dd_worker_parse_start("650 (x) S 1 2 3", &ticks) == DD_WORKER_STAT_PARSE);
assert(dd_worker_open_failure(EACCES) == DD_WORKER_STAT_DENIED);
assert(dd_worker_open_failure(EPERM) == DD_WORKER_STAT_DENIED);
assert(dd_worker_open_failure(ENOENT) == DD_WORKER_STAT_HIDDEN);
assert(dd_worker_open_failure(ESRCH) == DD_WORKER_STAT_HIDDEN);
assert(dd_worker_open_failure(EMFILE) == DD_WORKER_STAT_OPEN);
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251191, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251192, 251191));
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 251191));
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_HIDDEN, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 0));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OPEN, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_READ, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_PARSE, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_ZERO, 0, 251191));
struct dd_worker_grant g={.owner=3,.uid=10197,.pid=650,.dev_major=254,.dev_minor=21,
.start_ticks=251191,.ino=5502,.expires=1000,.canonical_file=file,.app_launch_verified=true,.final_go=true};
assert(dd_worker_grant_matches(&g,3,10197,650,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,1000,good));
assert(!dd_worker_grant_matches(&g,4,10197,650,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10198,650,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,651,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,650,251192,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,NULL));
const char *invalid[]={
"1000-2000 r--p 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope",
"1000-2000 r-xp 0 fe:15 5503 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope",
"1000-2000 r-xp 0 fe:16 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope",
"1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope (deleted)",
"1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope.bak",
"1000-2000 r-xp 0 fe:15 5502 /system/lib64/libddexec.so", "", NULL};
for (int i=0;invalid[i];i++) assert(!dd_worker_map_matches(&g,invalid[i]));
g.final_go=false;
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good));
g.final_go=true; g.app_launch_verified=false;
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good));
}
+2
View File
@@ -26,6 +26,8 @@ struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, v
struct wl_resource { struct wl_list listeners; int acquired, releases, errors; };
struct dmabuf_buffer { int unused; };
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE };
/* These release fixtures exercise legacy attachments, which own no acquire FD. */
#define dd_frame_acquire_clear(slot) ((void)0)
struct surface {
struct wl_list link;
struct wl_resource *dmabuf;
+245
View File
@@ -0,0 +1,245 @@
import json
import os
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility")
SETUP = COMPAT["DD_ANTICHEAT_SETUP"]
class AntiCheatRoutingTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / "Steam"
self.common = self.steam / "steamapps" / "common"
self.tools = self.steam / "compatibilitytools.d"
self.game = self.common / "Some Game"
self.game.mkdir(parents=True)
self.tools.mkdir(parents=True)
self.record = self.root / "record.json"
self.fex = self.root / "droiddeck-fex"
self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; "
"[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n"
"python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], "
"\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, "
"open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n")
self.fex.chmod(0o755)
self.patches = self.root / "fex-patches"
self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n")
def tool(self, name, x86_64=True):
tool = self.tools / name
(tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True)
if not x86_64:
(tool / "files" / "bin-arm64").mkdir()
(tool / "proton").write_text("#!/bin/sh\n")
(tool / "proton").chmod(0o755)
return tool
def runtime(self, name, library):
folder = self.common / name / "v2" / "lib64"
folder.mkdir(parents=True)
(folder / library).write_text("")
return self.common / name
def file(self, relative):
path = self.game / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("{}")
def launch(self, verb="waitforexitandrun", extra=None):
script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace(
"/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + (
"dd_game_cpus() { :; }\n"
"verb=$1; shift\n"
"dd_anticheat \"$@\"\n"
"echo stayed\n")
env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches),
"STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)}
env.update(extra or {})
result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")],
env=env, capture_output=True, text=True, timeout=30)
routed = json.loads(self.record.read_text()) if self.record.exists() else None
return result, routed
def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
newest = self.tool("DroidDeck-Proton-11.0-10-x86_64")
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertNotIn("stayed", result.stdout)
self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")])
self.assertEqual(routed["eac"], str(runtime))
self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr)
def test_battleye_sets_its_own_runtime(self):
self.file("BattlEye/BEClient_x64.so")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
_, routed = self.launch()
self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None))
def test_anti_cheat_in_an_unreal_binaries_folder_is_found(self):
for found in ("Project/Binaries/Win64/BattlEye/BEService_x64.exe", "Project/Binaries/Win64/EasyAntiCheat/Settings.json"):
with self.subTest(found=found):
self.setUp()
self.file(found)
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
_, routed = self.launch()
self.assertEqual(routed["argv"][1], str(tool / "proton"))
def test_a_game_with_both_kinds_uses_whichever_runtime_is_installed(self):
for installed, key in (("Proton BattlEye Runtime", "be"), ("Proton EasyAntiCheat Runtime", "eac")):
with self.subTest(installed=installed):
self.setUp()
self.file("BattlEye/BEService_x64.exe")
self.file("Project/Binaries/Win64/EasyAntiCheat/Settings.json")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
runtime = self.runtime(installed, "beclient_x64.so" if key == "be" else "easyanticheat_x64.so")
_, routed = self.launch()
self.assertEqual((routed["argv"][1], routed[key]), (str(tool / "proton"), str(runtime)))
def test_a_runtime_already_set_with_files_is_kept(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
own = self.root / "own-eac"
(own / "v2").mkdir(parents=True)
(own / "v2" / "easyanticheat_x64.so").write_text("")
_, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)})
self.assertEqual(routed["eac"], str(own))
def test_games_without_anti_cheat_files_stay_on_arm64(self):
self.file("Data/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertEqual(result.stderr, "")
def test_without_an_x86_64_build_the_launch_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr)
def test_without_the_runtime_files_the_launch_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
(self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True)
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("its Proton runtime is not installed", result.stderr)
def test_the_user_can_turn_routing_off(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
def test_a_tool_the_user_chose_is_kept(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"):
result, routed = self.launch(extra={"DD_AC_TOOL": chosen})
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr)
def test_droiddeck_proton_builds_still_route(self):
self.file("EasyAntiCheat/Settings.json")
newest = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"):
self.record.unlink(missing_ok=True)
result, routed = self.launch(extra={"DD_AC_TOOL": own})
self.assertEqual(routed["argv"][1], str(newest / "proton"))
def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for patches in ("openat2-enosys-fallback\n", None):
if patches is None:
self.patches.unlink()
else:
self.patches.write_text(patches)
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr)
def test_an_older_fex_build_is_updated_before_routing(self):
self.file("EasyAntiCheat/Settings.json")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
self.patches.unlink()
result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"})
self.assertEqual(routed["argv"][1], str(tool / "proton"))
self.assertNotIn("cannot run anti-cheat", result.stderr)
self.assertTrue((self.root / "record.json.update").exists())
def test_games_without_anti_cheat_files_do_not_update_fex(self):
self.file("Data/Settings.json")
self.launch()
self.assertFalse((self.root / "record.json.update").exists())
def test_choices_are_kept_the_same_with_an_older_fex_build(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
self.patches.unlink()
result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"})
self.assertIsNone(routed)
self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr)
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
self.assertIsNone(routed)
self.assertEqual(result.stderr, "")
def test_the_fex_build_lists_its_patches(self):
build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text()
self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build)
names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")}
self.assertIn("fixed-guest-memory-above-host-address-limit", names)
def test_adopted_tools_pass_their_own_folder_name(self):
wrapper = COMPAT["extra_wrapper_sh"]("proton")
self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper)
self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"])
def test_other_verbs_are_left_alone(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch(verb="getcompatpath")
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self):
launcher = COMPAT["LAUNCHER_SH"]
self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"'))
wrapper = COMPAT["extra_wrapper_sh"]("proton")
self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback="))
self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"'))
self.assertIn('! dd_x86_64_proton "$d"', wrapper)
if __name__ == "__main__":
unittest.main()
+13
View File
@@ -2,6 +2,7 @@ import importlib.machinery
import importlib.util
import os
import re
import runpy
import shutil
import subprocess
import tempfile
@@ -74,6 +75,18 @@ class ToolArguments(unittest.TestCase):
self.assertEqual(['BANNER_AUDIO_DIRECT_MIC=1', 'BANNER_AUDIO_DIRECT_MS=60'], result.stdout.split())
def test_original_xbox_switches_reach_wine(self):
game_env = runpy.run_path(str(BIN / 'droiddeck-game-env'))
switches = dict(game_env['XBOX_BACK_COMPAT_ENV'], VKD3D_PACKED_422_SWIZZLE='rbg1')
text = LAUNCH.read_text()
block = text[text.index('KEEP="'):text.index('export PATH=/system/bin')]
env = dict(switches, PATH=os.environ['PATH'], DROIDDECK_BIONIC_KEEP='PATH', OTHER='x')
result = subprocess.run(['sh', '-c', block + 'env\n'], env=env, text=True, capture_output=True, check=True)
kept = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
self.assertEqual(switches, {name: kept.get(name) for name in switches})
self.assertNotIn('OTHER', kept)
class SessionLogs(unittest.TestCase):
SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam'
@@ -0,0 +1,38 @@
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src"
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
class BottomMirrorCompositionTest(unittest.TestCase):
def test_mirror_requests_composition_until_its_last_consumer_leaves(self):
panel = (APP / "ui/BottomMirrorPage.kt").read_text()
self.assertIn("actions.holdComposed(true)", panel)
self.assertIn("onDispose { actions.holdComposed(false) }", panel)
activity = (APP / "SessionActivity.kt").read_text()
hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0]
self.assertIn("if (held == wasHeld) return", hold)
self.assertIn("nativeSetMirrorCapture(held)", hold)
self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold)
self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity)
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity)
self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold)
self.assertNotIn("SessionPrefs.set", hold)
def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self):
jni = (NATIVE / "waylandcomp_jni.c").read_text()
self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni)
host = (NATIVE / "droiddeck_ext.c").read_text()
self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host)
compositor = (NATIVE / "compositor.c").read_text()
self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor)
self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor)
self.assertIn("if (un && g_zero_copy)", compositor)
self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor)
self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor)
if __name__ == "__main__":
unittest.main()
+128 -7
View File
@@ -25,7 +25,7 @@ class CiChecksTest(unittest.TestCase):
self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle)
def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')]
for cache in caches:
for path in cache['path'].split('\n'):
@@ -33,14 +33,25 @@ class CiChecksTest(unittest.TestCase):
robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')]
self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2)
def test_only_main_saves_the_robolectric_cache(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
saves = [step for step in steps if step.get('uses', '').startswith('actions/cache/save')
and step['with']['key'].startswith('robolectric-')]
self.assertEqual(len(saves), 1)
self.assertIn("github.event_name != 'pull_request'", saves[0]['if'])
def test_unit_test_retry_requires_maven_exception(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
run = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
line = next(line for line in run.splitlines() if 'grep -Eq' in line)
pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1]
for log, expected in (
("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0),
("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo1.maven.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo1.maven.org/maven2/a.pom.sha512", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://example.org/a.jar", 1),
("Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://repo1.maven.org/maven2/a.jar", 1),
("SomeTest > test FAILED: Too Many Requests", 1),
("Caused by: java.lang.AssertionError: HTTP 429", 1),
):
@@ -59,15 +70,125 @@ class CiChecksTest(unittest.TestCase):
self.assertEqual(result.strip(), '2')
def test_build_and_tests_use_identical_generated_metadata(self):
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
steps = {step.get('id'): step for step in jobs['build']['steps']}
self.assertEqual(steps['build']['env'], steps['unit-tests']['env'])
self.assertIn('DROIDDECK_BUILD_LABEL', steps['unit-tests']['env'])
self.assertIn('SGDB_API_KEY', steps['unit-tests']['env'])
build = {step.get('id'): step for step in
yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']}
tests = {step.get('id'): step for step in
yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']}
self.assertEqual(build['build']['env'], tests['unit-tests']['env'])
self.assertIn('DROIDDECK_BUILD_LABEL', tests['unit-tests']['env'])
self.assertIn('SGDB_API_KEY', tests['unit-tests']['env'])
self.assertEqual(build['build-label'], tests['build-label'])
gradle = (ROOT / 'app/build.gradle').read_text()
self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle)
self.assertIn('outputs.upToDateWhen { false }', gradle)
def test_unit_tests_switch_mirrors_only_for_robolectric_rate_limits(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
script = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
central = 'https://repo.maven.apache.org/maven2/'
native = f'{central}org/robolectric/nativeruntime-dist-compat/1.0.18/nativeruntime-dist-compat-1.0.18.jar'
sdk = 'https://repo1.maven.org/maven2/org/robolectric/android-all-instrumented/sdk.jar.sha512'
gradle_error = 'org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException'
get_error = f"Could not GET '{native}'. Received status code 429 from server: Too Many Requests"
mirror = '-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2'
# These two resolvers report the status and URL in opposite orders.
cases = [
('ok', 0, 0, 0, 1),
(f'Could not GET {native}. Received status code 429', 1, 0, 0, 2),
(f'Server returned HTTP response code: 429 for URL: {sdk}', 1, 9, 9, 2),
(f' Caused by: {gradle_error}: {get_error}', 1, 0, 0, 2),
(f' Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: {sdk}', 1, 0, 0, 2),
(f'Failed to get resource: GET. [HTTP HTTP/1.1 429 Too Many Requests: {native})]\n'
'java.lang.AssertionError: expected a visible window', 7, 0, 7, 1),
('AssertionError: expected 429', 7, 0, 7, 1),
(f'AssertionError: expected status code 429 for URL: {sdk}', 7, 0, 7, 1),
(f'Caused by: java.lang.AssertionError: {get_error}', 7, 0, 7, 1),
(f'Could not GET {central}other/group/lib.jar. Received status code 429', 8, 0, 8, 1),
]
for message, first, retry, expected, attempts in cases:
with self.subTest(message=message), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
gradle = root / 'gradlew'
gradle.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n'
'case "$*" in *-ProbolectricMavenMirror=*) exit "$RETRY";; esac\n'
'echo "$MESSAGE"\nexit "$FIRST"\n')
gradle.chmod(0o755)
sleep = root / 'sleep'
sleep.write_text('#!/bin/sh\necho "sleep $*" >> calls\n')
sleep.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
NDK_VERSION='test', MESSAGE=message, FIRST=str(first), RETRY=str(retry))
result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, capture_output=True, timeout=15)
self.assertEqual(result.returncode, expected, result.stdout)
calls = (root / 'calls').read_text().splitlines()
self.assertEqual(len(calls), attempts)
self.assertNotIn(mirror, calls[0])
if attempts == 2:
self.assertEqual(calls[1].split(), [*calls[0].split(), mirror])
def test_unit_tests_back_off_on_maven_central_rate_limits(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
script = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
rate_limit = (
"Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: "
"Could not GET 'https://repo.maven.apache.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar'. "
"Received status code 429 from server: Too Many Requests"
)
for exit_codes, expected_status, expected_events in (
([7, 0], 0, ['gradle', 'sleep 60', 'gradle']),
([7, 9, 23, 0], 23, ['gradle', 'sleep 60', 'gradle', 'sleep 180', 'gradle']),
):
with self.subTest(exit_codes=exit_codes), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'statuses').write_text(''.join(f'{code}\n' for code in exit_codes))
gradle = root / 'gradlew'
gradle.write_text('#!/bin/sh\n'
'echo gradle >> events\n'
'echo "$*" >> gradle-args\n'
'attempt=$(wc -l < gradle-args)\n'
'status=$(sed -n "${attempt}p" statuses)\n'
'if [ "$status" != 0 ]; then echo "$MAVEN_ERROR"; fi\n'
'exit "${status:-99}"\n')
gradle.chmod(0o755)
sleep = root / 'sleep'
sleep.write_text('#!/bin/sh\necho "sleep $*" >> events\n')
sleep.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
NDK_VERSION='test', MAVEN_ERROR=rate_limit)
result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env,
capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, expected_status, result.stdout + result.stderr)
self.assertEqual((root / 'events').read_text().splitlines(), expected_events)
self.assertNotIn('-ProbolectricMavenMirror=', (root / 'gradle-args').read_text())
def test_unit_tests_do_not_hold_up_the_apk(self):
build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())
for step in build['jobs']['build']['steps']:
self.assertNotIn('UnitTest', step.get('run', ''))
tests = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())
for event in ('push', 'pull_request'):
self.assertEqual(tests[True][event], build[True][event])
authorship = yaml.safe_load((ROOT / '.github/workflows/authorship.yml').read_text())
self.assertEqual(set(authorship[True]['workflow_run']['workflows']), {build['name'], tests['name']})
self.assertIn('workflow_run.head_sha', authorship['concurrency']['group'])
self.assertFalse(authorship['concurrency']['cancel-in-progress'])
self.assertIn('unit-tests.yml', (ROOT / '.github/workflows/release.yml').read_text())
run = next(step['run'] for step in tests['jobs']['unit-tests']['steps'] if step.get('id') == 'unit-tests')
self.assertIn('-PunitTestsOnly=true', run)
def test_apk_and_unit_tests_pin_the_same_pr_event_base(self):
for filename, job, name in (
("build.yml", "source", "Pin and merge the APK source"),
("unit-tests.yml", "unit-tests", "Merge the pinned APK base"),
):
with self.subTest(workflow=filename):
workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text())
step = next(step for step in workflow["jobs"][job]["steps"] if step.get("name") == name)
self.assertEqual(step["env"]["PR_BASE_SHA"], "${{ github.event.pull_request.base.sha }}")
self.assertIn('git fetch --no-tags origin "$PR_BASE_SHA"', step["run"])
self.assertIn("git merge --no-ff --no-edit FETCH_HEAD", step["run"])
self.assertIn("github.event.pull_request.base.sha", workflow["run-name"])
def test_independent_jobs_wait_only_for_the_pinned_source(self):
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
for name in ('xbox', 'python-tests', 'components-runner'):
@@ -74,6 +74,11 @@ static int poll(struct pollfd *p, unsigned n, int timeout) {
}
static int fcntl(int fd, int cmd, int arg) { (void)cmd; (void)arg; dup_of[next_dup] = fd; return next_dup++; }
static int close(int fd) { closed[fd]++; return 0; }
struct dd_frame_acquire { int fd_plus_one; };
static void dd_frame_acquire_clear(struct dd_frame_acquire *f) {
if (f->fd_plus_one) close(f->fd_plus_one - 1);
f->fd_plus_one = 0;
}
struct wl_event_source { int fd; int (*fd_cb)(int, uint32_t, void *); int (*timer_cb)(void *); void *data; int armed_ms, removed; };
struct wl_event_loop;
@@ -121,6 +126,7 @@ struct surface {
struct wl_resource *resource, *xdg_toplevel;
int toplevel_committed;
struct wl_resource *pending_buffer;
struct dd_frame_acquire pending_frame_acquire;
struct wl_listener pending_buffer_destroy;
int pending_attach, pending_src_set, pending_dst_set, pending_opaque_set;
float pending_src[4];
@@ -146,6 +152,7 @@ FUNCTIONS
static void surface_state_apply(struct surface *s, struct surface_state *st) {
(void)s;
dd_frame_acquire_clear(&st->frame_acquire);
applies++;
applied_attach = st->attach;
applied_buffer = st->attach ? st->buffer : NULL;
+3 -3
View File
@@ -24,7 +24,7 @@ class ComponentReuseTest(unittest.TestCase):
self.root = Path(self.temp.name)
(self.root / 'tools/ci').mkdir(parents=True)
(self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n')
self.local = {'runtime': 'a', 'proot': 'b'}
self.local = {'runtime': 'a', 'nativeguest': 'b'}
self.unregistered, self.submodules = [], []
for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)),
mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]),
@@ -57,10 +57,10 @@ class ComponentReuseTest(unittest.TestCase):
self.assertFalse(stale.exists())
def test_a_changed_component_is_not_reused(self):
self.write_archive(dict(self.local, proot='other'))
self.write_archive(dict(self.local, nativeguest='other'))
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
self.assertFalse(reuse.reuse(self.archive, self.root))
self.assertIn('proot', stdout.getvalue())
self.assertIn('nativeguest', stdout.getvalue())
self.assertFalse((self.root / prepare.LIBRARIES[0]).exists())
def test_a_tampered_file_is_rejected_and_local_outputs_survive(self):
+58
View File
@@ -0,0 +1,58 @@
import os
import re
import shlex
import subprocess
import tempfile
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
def decky_job():
match = re.search(r"^ *_dd_job_decky\(\) \{\n.*?^ {8}\}\n", SESSION.read_text(), re.M | re.S)
return match.group(0) if match else None
class DeckyLoaderEnvironmentTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
(self.root / "homebrew/services").mkdir(parents=True)
def loader_environment(self, inherited=None):
job = decky_job()
self.assertIsNotNone(job, "droiddeck-session has no _dd_job_decky()")
seen = self.root / "seen.env"
loader = self.root / "PluginLoader"
loader.write_text("#!/bin/sh\nenv > %s\nexit 1\n" % shlex.quote(str(seen)))
loader.chmod(0o755)
script = "sleep() { :; }\n" + job
script += "decky_arch=arm64\ndecky_loader=%s\n_dd_job_decky\n" % shlex.quote(str(loader))
env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.root)}
env.update(inherited or {})
out = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30, env=env, check=True).stdout
self.assertIn("stopped after 5 loader exits", out)
return dict(line.split("=", 1) for line in seen.read_text().splitlines() if "=" in line)
def test_the_loader_runs_without_its_file_watcher(self):
self.assertEqual("0", self.loader_environment().get("LIVE_RELOAD"))
def test_a_live_reload_from_the_session_environment_does_not_reach_the_loader(self):
self.assertEqual("0", self.loader_environment({"LIVE_RELOAD": "1"}).get("LIVE_RELOAD"))
def test_the_loader_still_runs_as_root_and_keeps_its_plugin_permission_fixes(self):
env = self.loader_environment()
self.assertEqual("root", env.get("UNPRIVILEGED_USER"))
self.assertNotIn("CHOWN_PLUGIN_PATH", env)
def test_only_the_decky_job_sets_live_reload(self):
text = SESSION.read_text()
job = decky_job()
self.assertEqual(1, text.count("LIVE_RELOAD"))
self.assertIn("export LIVE_RELOAD=0", job)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -36,7 +36,7 @@ class ClassifyTest(unittest.TestCase):
self.assertEqual(blocked, {})
def test_everything_else_fails_closed(self):
changes = {'app/src/main/java/com/droiddeck/launcher/Foo.kt': 'M', 'tools/proot/build.sh': 'M',
changes = {'app/src/main/java/com/droiddeck/launcher/Foo.kt': 'M', 'tools/nativeguest/build.sh': 'M',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-new': 'A'}
self.assertEqual(set(self.classify(changes)[2]), set(changes))
self.assertEqual(set(self.classify({self.agent: 'D'})[2]), {self.agent})
+70 -18
View File
@@ -940,7 +940,7 @@ class ExtractTest(FexTestCase):
return str(self.write(self.tmp / "uruntime", "#!/bin/sh\n" + body, 0o755))
def test_uruntime_unpacks_an_x86_image_without_fex(self):
tool = self.uruntime('[ "$1" = --appimage-extract ] && [ "$TARGET_APPIMAGE" = "%s" ] || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
tool = self.uruntime('[ "$1" = --appimage-extract ] && cmp -s "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual((status, said), (0, ""))
@@ -1045,36 +1045,23 @@ class ExtractTest(FexTestCase):
status, said = self.quiet(FEX["extract"], "image.AppImage")
return status, said, commands
def test_without_proot_the_shipped_runtime_reads_the_open_image(self):
def test_the_shipped_runtime_reads_the_open_image(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime('cmp "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual((status, said), (0, ""))
self.assertEqual([], commands)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_without_proot_runtime_failure_falls_back_to_7zip(self):
def test_runtime_failure_falls_back_to_7zip(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime("exit 1\n")
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual("/usr/bin/7z", commands[-1][0])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_with_proot_the_shipped_runtime_is_still_tried_first(self):
ran = self.tmp / "uruntime-ran"
tool = self.uruntime("touch %s\nexit 1\n" % ran)
env = {k: v for k, v in os.environ.items() if k != "DDNATV_ROOT"}
with mock.patch.dict(os.environ, env, clear=True):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertTrue(ran.exists())
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual("/usr/bin/7z", commands[-1][0])
def test_unsquashfs_is_preferred_over_7zip(self):
tool = self.uruntime("exit 1\n")
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
@@ -1235,6 +1222,29 @@ class LaunchTest(FexTestCase):
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self):
proton = self.proton("4183110")
folder = proton.parent
os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig")
self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n')
self.assertEqual(FEX["required_runtime"](str(proton)), "4183110")
os.unlink(folder / "toolmanifest.vdf.droiddeck-orig")
self.assertEqual(FEX["required_runtime"](str(proton)), "1628350")
def test_proton_action_keeps_the_prefix_and_runs_under_fex(self):
self.fex_tool()
self.runtime()
proton = self.proton("1628350")
prefix = str(self.tmp / "compatdata" / "730")
env = {"STEAM_COMPAT_DATA_PATH": prefix}
with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated:
self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"])
command, guest = emulated.call_args[0][1], emulated.call_args[0][2]
self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"])
self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix)
self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix)
self.assertEqual(FEX["main"](["proton", str(proton)]), 2)
def test_native_programs_run_directly(self):
program = self.write(self.tmp / "native", elf(183), 0o755)
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
@@ -1351,6 +1361,48 @@ class LaunchTest(FexTestCase):
self.assertEqual(started(unity, "10")[:2], ("1", None))
self.assertEqual(started(other, "10")[:2], (None, None))
def test_x86_64_proton_launches_keep_the_game_debug_and_graphics_logs(self):
config = self.home / ".config/droiddeck/game-environment.json"
session = self.tmp / "session"
session.mkdir()
proton = str(self.tmp / "Proton x86-64/proton")
def started(verb, debug, extra=None):
self.write(config, json.dumps({"version": 1, "gameDebugLogs": debug,
"games": {"976730": {"DXVK_HUD": "fps"}}}))
env = {"SteamAppId": "976730", "SteamGameId": "976730", "DD_DEBUG_DIR": str(session), **(extra or {})}
with mock.patch.dict(G, {"launch": mock.Mock(return_value=0), "GAME_ENVIRONMENT": str(config)}), \
mock.patch.dict(os.environ, env, clear=True), mock.patch("subprocess.Popen") as capped:
_, said = self.quiet(FEX["main"], ["proton", proton, verb, "C:/game/game.exe"])
command, guest, mode = G["launch"].call_args[0]
self.assertEqual((command, mode), ([proton, verb, "C:/game/game.exe"], "on"))
return guest, said, capped
guest, said, capped = started("waitforexitandrun", True)
self.assertEqual((guest["PROTON_LOG"], guest["PROTON_LOG_DIR"]), ("1", str(session)))
self.assertIn("+seh", guest["WINEDEBUG"])
self.assertEqual(guest["DXVK_HUD"], "fps")
self.assertIn("game debug logs enabled for this launch", said)
self.assertIn(str(session / "steam-976730.log"), capped.call_args[0][0])
guest, said, _ = started("waitforexitandrun", False, {"DD_GAME_LOGS": "1"})
folder = Path(guest["PROTON_LOG_DIR"])
self.assertEqual((guest["PROTON_LOG"], folder.parent), ("1", session / "games"))
self.assertTrue(folder.name.endswith("-976730"))
self.assertNotIn("game debug logs enabled", said)
guest, _, capped = started("waitforexitandrun", False)
self.assertNotIn("PROTON_LOG", guest)
self.assertEqual(guest["DXVK_HUD"], "fps")
capped.assert_not_called()
guest, _, capped = started("run", True)
self.assertNotIn("PROTON_LOG", guest)
capped.assert_not_called()
guest, _, _ = started("waitforexitandrun", True, {"PROTON_LOG": "1", "PROTON_LOG_DIR": "/mine"})
self.assertEqual(guest["PROTON_LOG_DIR"], str(session))
class AppInfoTest(unittest.TestCase):
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
@@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False}
NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False}
X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64",
"valve": False, "x86_64": True}
def config_text(entries):
@@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase):
self.assertEqual(newest, "b")
self.assertEqual(gone, {OLD["name"]})
def test_an_x86_64_build_never_becomes_the_automatic_default(self):
default, mapping, state = self.run_default(
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"])
self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"]))
default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_an_automatic_x86_64_default_moves_back_to_arm64(self):
default, mapping, state = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86])
self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update"))
default, mapping, _ = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_an_x86_64_default_the_user_picked_is_kept(self):
for source in ("app", "steam"):
default, mapping, _ = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86])
self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]}))
def test_a_request_for_the_automatic_x86_64_default_keeps_it(self):
default, mapping, state = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])],
[VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]})
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86],
request={"seq": 2, "name": X86["name"]})
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
def test_x86_64_layouts_are_marked_in_the_catalog(self):
with tempfile.TemporaryDirectory() as tmp:
tools = Path(tmp) / "compatibilitytools.d"
for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)):
(tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
if arm:
(tools / entry / "files" / "bin-arm64").mkdir()
(tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("")
catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]}
self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64"))
self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"])
newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values()))
self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"])
if __name__ == "__main__":
unittest.main()
+3 -1
View File
@@ -522,7 +522,9 @@ class DroiddeckctlTest(FakeAdbTest):
answer = ctl.provider_call("adb", "fake-1", "state", arg="a b", request={"x": 1})
self.assertEqual({"ok": True, "command": "state"}, answer)
broadcast = next(c for c in calls if c[:2] == ("shell", "am"))
self.assertEqual(("shell", "am", "broadcast", "-a", ctl.PACKAGE + ".AGENT_CALL", "-p", ctl.PACKAGE), broadcast[:7])
receiver = ctl.PACKAGE + "/com.droiddeck.launcher.agent.AgentCallReceiver"
self.assertEqual(("shell", "am", "broadcast", "-n", receiver), broadcast[:5])
self.assertNotIn("-a", broadcast)
self.assertIn("'a b'", broadcast)
self.assertEqual(ctl.encode_request({"x": 1}), broadcast[broadcast.index("request") + 1])
call_id = broadcast[broadcast.index("id") + 1]
+3
View File
@@ -63,6 +63,9 @@ class EffectsSourceCacheTest(unittest.TestCase):
def test_generated_settings_snapshot_and_source_layout_restoration(self):
self.check_cache('generated-layout')
def test_every_recorded_frame_fills_the_smaa_tables(self):
self.check_cache('smaa-tables')
if __name__ == '__main__':
unittest.main()
+60 -3
View File
@@ -31,7 +31,7 @@ class EffectsSourceResolutionTest(unittest.TestCase):
'static int draw_to_scene_blit(', 'static int effects_source_draw(',
'static void effects_source_note(',
'static void effects_overlay_draws(',
'static int render_impl(', 'static int pass_begin_impl('))
'static int render_impl(', 'static int pass_begin_impl(', 'static int pass_finish(', 'int vkp_pass_copy_generated('))
functions = (re.search(r'static int spatial_mode\([^\n]+', effects).group() + '\n' +
re.search(r'static int cas_active\([^\n]+', effects).group() + '\n' +
function(effects, 'int vkp_effects_upscaling(') +
@@ -109,6 +109,9 @@ class EffectsSourceResolutionTest(unittest.TestCase):
def test_frame_generation_runs_spatial_post_upscale(self):
self.check_case('framegen-upscale')
def test_display_layer_interpolates_before_the_spatial_upscale(self):
self.check_case('framegen-layer-upscale')
TYPES = r'''
#include <assert.h>
@@ -116,6 +119,7 @@ TYPES = r'''
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer;
typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags;
typedef uint64_t VkDeviceSize;
@@ -179,6 +183,8 @@ typedef struct AHardwareBuffer AHardwareBuffer;
STUBS = r'''
static void zfg_discard_history_update(void) {}
static void zfg_commit_history_update(void) {}
static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; }
static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; }
static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; }
@@ -214,7 +220,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map;
static struct { VkImage img; int w, h; } g_scene;
struct vkp_img_slot { VkImage img; int w, h; };
static struct vkp_img_slot g_hdrscene, g_fgscene;
static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass;
static struct { int active, rw, rh, ow, oh, post_upscale, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass;
static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf;
static int effects_active = 1, framegen, cardboard;
struct fx_settings { int scaling, cas_on, cas_pct; };
@@ -280,7 +286,8 @@ static VkImage vkp_effects_run(int cmd, int source, int w, int h, int ow, int oh
if (fail_effects) { *rw = w; *rh = h; return source; }
*rw = ow; *rh = oh; return 4;
}
static int vkp_effects_prepare_generated(void) {
static int vkp_effects_prepare_generated(int in_w, int in_h, int out_w, int out_h) {
(void)in_w; (void)in_h; (void)out_w; (void)out_h;
return g_cur.scaling >= 3 && g_cur.scaling <= 8 && g_cur.scaling != 6 && !postprocessing;
}
static VkImage vkp_effects_run_before_generated(int cmd, int source, int w, int h, int *rw, int *rh) {
@@ -294,6 +301,21 @@ static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int fo
return generations;
}
static void vkp_effects_release_generated_sources(void) {}
static void vkp_framegen_set_layer_timing(int layer) {}
static int g_wait_sem, blit_count, blit_src_w[4], blit_src_h[4], blit_dst_w[4], blit_dst_h[4];
static VkImage blit_src_images[4], blit_dst_images[4];
static VkImageLayout blit_layouts[4];
static int take_wait_fd(int fd) { return fd < 0 ? 0 : fd; }
static void blit_to_layer(int cmd, VkImage src, VkImageLayout layout, struct vkp_image *dst,
const VkImageBlit *blit, VkFilter filter) {
assert(blit_count < 4);
blit_src_images[blit_count] = src; blit_dst_images[blit_count] = dst->image;
blit_layouts[blit_count] = layout;
blit_src_w[blit_count] = blit->srcOffsets[1].x; blit_src_h[blit_count] = blit->srcOffsets[1].y;
blit_dst_w[blit_count] = blit->dstOffsets[1].x; blit_dst_h[blit_count] = blit->dstOffsets[1].y;
blit_count++;
}
static void vkp_framegen_completed(void) {}
static VkImage vkp_effects_run_generated(int cmd, int source, int w, int h, int ow, int oh,
int slot, int *rw, int *rh) {
assert(slot == post_count && slot < 4);
@@ -660,6 +682,40 @@ static void check_framegen_upscale(void) {
struct vkp_hdr_frame hdr = {0};
run_path(0, &draw, 1, &hdr); assert(post_count == 0);
}
static void check_framegen_layer_upscale(void) {
reset(); framegen = 1; generations = 2;
struct vkp_draw draw = fullscreen();
int rw = 0, rh = 0;
assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0);
assert(effects_count == 1 && output_w == 1280 && output_h == 720);
assert(fg_w == 1280 && fg_h == 720);
assert(g_pass.post_upscale && g_pass.rw == 1280 && g_pass.rh == 720);
assert(rw == 1920 && rh == 1080);
struct vkp_image generated_dst[2] = {{.image = 50, .w = 1920, .h = 1080, .blit_dst = 1}, {.image = 51, .w = 1920, .h = 1080, .blit_dst = 1}};
struct vkp_image real_dst = {.image = 52, .w = 1920, .h = 1080, .blit_dst = 1};
struct vkp_image *generated_ptrs[2] = {&generated_dst[0], &generated_dst[1]};
g_pass.gens[0] = 20; g_pass.gens[1] = 21; g_pass.result = 4; g_pass.ngen = 2;
assert(vkp_pass_copy_generated(generated_ptrs, 2, &real_dst, -1) == 0);
assert(post_count == 3 && blit_count == 3);
assert(post_sources[0] == 20 && post_sources[1] == 21 && post_sources[2] == 4);
for (int i = 0; i < 3; i++) {
assert(blit_src_images[i] == 40 + i);
assert(blit_dst_images[i] == 50 + i);
assert(blit_layouts[i] == VK_IMAGE_LAYOUT_GENERAL);
}
for (int i = 0; i < 3; i++) {
assert(blit_src_w[i] == 1920 && blit_src_h[i] == 1080);
assert(blit_dst_w[i] == 1920 && blit_dst_h[i] == 1080);
}
reset(); framegen = 1; postprocessing = 1;
draw = fullscreen();
assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0);
assert(!g_pass.post_upscale && rw == g_pass.rw && rh == g_pass.rh);
reset(); framegen = 1;
draw = fullscreen();
assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 0, &rw, &rh) == 0);
assert(!g_pass.post_upscale);
}
int main(int argc, char **argv) {
assert(argc == 2); reset();
if (!strcmp(argv[1], "helper")) check_helper();
@@ -677,6 +733,7 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[1], "postprocessing")) check_postprocessing();
else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening();
else if (!strcmp(argv[1], "framegen-upscale")) check_framegen_upscale();
else if (!strcmp(argv[1], "framegen-layer-upscale")) check_framegen_layer_upscale();
else assert(0);
puts("PASS");
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,73 @@
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch"
LOADER = "Source/Tools/FEXInterpreter/ELFCodeLoader.h"
MIN_GAP = 128 * 1024 * 1024
STACK = 128 * 1024 * 1024
PAGE = 4096
def lines(sign):
return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)]
def reservation(top, rlimit):
top = (top + PAGE - 1) & ~(PAGE - 1)
gap = min(max(rlimit, MIN_GAP), max(top // 6 * 5, MIN_GAP)) + 256 * PAGE
return (top - gap if top > gap else 0, top)
def place(hint, low, high):
if hint < high and hint + STACK > low and low > STACK:
hint = (low - STACK) & ~(PAGE - 1)
return hint
class FexGuestStackReserveTest(unittest.TestCase):
def test_only_the_elf_loader_changes(self):
self.assertEqual([LOADER], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
def test_nothing_is_removed(self):
self.assertEqual([], lines("-"))
def test_the_reserve_starts_at_the_end_of_the_host_environment(self):
added = lines("+")
self.assertIn("uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast<uint64_t>(__builtin_frame_address(0));", added)
self.assertIn("uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast<uint64_t>(Limit.rlim_cur) : MinGap;", added)
self.assertIn("Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize;", added)
def test_every_stack_hint_is_checked_against_the_reserve(self):
text = PATCH.read_text()
self.assertLess(text.index("HostStackReservation(PageSize);"), text.index("do {"))
self.assertLess(text.index("do {"), text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)"))
self.assertLess(text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)"), text.index("// Allocate the base of the full 128MB stack range."))
def test_a_guest_stack_overlapping_the_reserve_moves_below_it(self):
host_env_end = 0x7FFC391000
low, high = reservation(host_env_end, 8 * 1024 * 1024)
hint = place((1 << 39) - STACK, low, high)
self.assertLessEqual(hint + STACK, low)
self.assertGreaterEqual(host_env_end - (hint + STACK), MIN_GAP)
def test_a_guest_stack_clear_of_the_reserve_stays_put(self):
low, high = reservation(0x7FC491C000, 8 * 1024 * 1024)
hint = (1 << 39) - STACK
self.assertEqual(hint, place(hint, low, high))
def test_a_larger_stack_limit_widens_the_reserve(self):
low, _ = reservation(0x7FFC391000, 512 * 1024 * 1024)
self.assertEqual(0x7FFC391000 - 512 * 1024 * 1024 - 256 * PAGE, low)
def test_an_unlimited_stack_limit_keeps_room_for_the_guest(self):
low, _ = reservation(0x7FFC391000, (1 << 64) - 1)
self.assertGreater(low, STACK)
def test_no_comments_are_added(self):
self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+22
View File
@@ -117,6 +117,28 @@ class FexInstallTest(unittest.TestCase):
self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text())
self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text())
def test_a_build_without_a_patch_list_drops_the_old_one(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertFalse(marker.exists())
def test_a_failed_install_keeps_the_old_patch_list(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("FAILED", self.install(installed_loads=False)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n", marker.read_text())
def test_a_build_with_a_patch_list_installs_it(self):
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").write_text("openat2-enosys-fallback\n")
shipped = Path(self.temp.name) / "pkg/usr/local/share/fex-emu"
shipped.mkdir(parents=True)
(shipped / ".droiddeck-patches").write_text("fixed-guest-memory-above-host-address-limit\n")
self.pack()
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n",
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").read_text())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
+157
View File
@@ -0,0 +1,157 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch"
EMULATED = "Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles"
HOST_MOUNTS = """/dev/block/dm-28 / ext4 ro,seclabel,relatime,discard 0 0
tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,size=5791196k,nr_inodes=1447799,mode=755 0 0
proc /proc proc rw,relatime,gid=3009,hidepid=invisible 0 0
sysfs /sys sysfs rw,seclabel,relatime 0 0
/dev/fuse /mnt/user/0/emulated fuse rw,lazytime,nosuid,nodev,noexec,noatime,user_id=0,group_id=0,allow_other 0 0
"""
HOST_MOUNTINFO = """9838 9837 254:28 / / ro,relatime master:1 - ext4 /dev/block/dm-28 ro,seclabel,discard
9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw,gid=3009,hidepid=invisible
9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw,hidepid=2,subset=pid
9871 9838 0:21 / /sys rw,relatime master:5 - sysfs sysfs rw,seclabel
"""
HARNESS = r"""
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
namespace fextl {
using string = std::string;
template<typename T> using vector = std::vector<T>;
}
HELPERS
static std::string Filter(const std::string& In, bool MountInfo) {
std::string Out;
size_t Pos = 0;
while (Pos < In.size()) {
size_t Eol = In.find('\n', Pos);
const size_t LineEnd = Eol == std::string::npos ? In.size() : Eol;
Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
if (Eol != std::string::npos) {
Out += '\n';
}
Pos = LineEnd + 1;
}
return Out;
}
int main(int argc, char** argv) {
if (argv[1][0] == 'p') {
for (int i = 2; i < argc; ++i) {
std::printf("%s\n", IsProcMountTablePath(argv[i]) ? "yes" : "no");
}
return 0;
}
std::string In;
char Buf[4096];
size_t Len;
while ((Len = std::fread(Buf, 1, sizeof(Buf), stdin)) > 0) {
In.append(Buf, Len);
}
std::fputs(Filter(In, argv[1][0] == 'i').c_str(), stdout);
return 0;
}
"""
def added():
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
def helpers():
body = added()
start = body.index("static const char* ProcFileOfPid(const char* Path) {")
end = body.index("static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {")
end = body.index("}", end) + 1
return "\n".join(body[start:end])
class FexProcMountTablesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.binary = None
compiler = shutil.which("g++") or shutil.which("clang++")
if compiler:
source = Path(cls.tmp.name) / "mounts.cpp"
source.write_text(HARNESS.replace("HELPERS", helpers()))
binary = Path(cls.tmp.name) / "mounts"
subprocess.run([compiler, "-std=c++20", "-O1", "-o", str(binary), str(source)], check=True)
cls.binary = binary
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_filter(self, mode, text):
if not self.binary:
self.skipTest("no C++ compiler")
return subprocess.run([str(self.binary), mode], input=text, capture_output=True, text=True, check=True).stdout
def matches(self, *paths):
if not self.binary:
self.skipTest("no C++ compiler")
out = subprocess.run([str(self.binary), "p", *paths], capture_output=True, text=True, check=True).stdout
return out.split()
def test_only_the_emulated_files_change(self):
files = re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)
self.assertEqual({EMULATED + ".cpp", EMULATED + ".h"}, set(files))
def test_mount_tables_are_routed_to_the_filter_on_open(self):
body = added()
self.assertIn(" if (pathname && IsProcMountTablePath(pathname)) {", body)
self.assertIn(" return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);", body)
def test_every_path_form_of_the_mount_tables_matches(self):
paths = ["/proc/mounts", "/proc/self/mounts", "/proc/thread-self/mounts", "/proc/self/mountinfo", "/proc/4242/mounts",
"/proc/4242/mountinfo", "/proc/4242/task/4243/mountinfo"]
self.assertEqual(["yes"] * len(paths), self.matches(*paths))
def test_other_proc_files_do_not_match(self):
paths = ["/proc/self/maps", "/proc/self/status", "/proc/self/mountstats", "/proc/4242/task/mounts", "/proc/self/mounts/x",
"/etc/mounts", "/proc/4242x/mounts"]
self.assertEqual(["no"] * len(paths), self.matches(*paths))
def test_only_the_proc_line_of_mounts_changes(self):
out = self.run_filter("m", HOST_MOUNTS).splitlines()
expected = HOST_MOUNTS.splitlines()
expected[2] = "proc /proc proc rw,relatime 0 0"
self.assertEqual(expected, out)
def test_only_proc_super_options_of_mountinfo_change(self):
out = self.run_filter("i", HOST_MOUNTINFO).splitlines()
expected = HOST_MOUNTINFO.splitlines()
expected[1] = "9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw"
expected[2] = "9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw"
self.assertEqual(expected, out)
def test_tables_without_proc_pass_through_unchanged(self):
text = "".join(line + "\n" for line in HOST_MOUNTS.splitlines() if " proc " not in line)
self.assertEqual(text, self.run_filter("m", text))
def test_malformed_lines_pass_through_unchanged(self):
text = "proc /proc proc\nno dash here proc rw\n\nproc\n"
self.assertEqual(text, self.run_filter("m", text))
self.assertEqual(text, self.run_filter("i", text))
def test_no_comments_are_added(self):
self.assertFalse([line for line in added() if line.strip().startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+49 -2
View File
@@ -8,14 +8,17 @@ from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
EMULATION = FEX / "patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch"
MCONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
PROBE = FEX / "probes/signal-register-update.c"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
def files(patch=PATCH):
sections = re.split(r"^diff --git a/(\S+) \S+\n", patch.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
@@ -96,6 +99,50 @@ class SignalRegisterUpdateTest(unittest.TestCase):
self.assertNotIn("Fixed-upstream", PATCH.read_text())
class ClearedSyscallInfoTest(unittest.TestCase):
SOURCE = "ArchHelpers::Context::SavedSyscallInfo(Context)"
def saved_info(self):
lines = [line[1:] for line in files(EMULATION)[MCONTEXT].splitlines() if line.startswith("+") and not line.startswith("+++")]
start = lines.index("template<typename Backup>")
end = lines.index("}", start)
return "\n".join(lines[start:end + 1])
def test_register_writeback_reads_the_same_saved_state_as_the_restore(self):
frames = files(EMULATION)[FRAMES]
self.assertIn("- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;", frames)
self.assertIn("+ const uint32_t Spilled = " + self.SOURCE + " & 0xFFFF;", frames)
delegator = added(files(EMULATION)[DELEGATOR])
self.assertIn("Thread->CurrentFrame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = Context->InSyscallInfo;", removed(files(EMULATION)[DELEGATOR]))
self.assertNotIn("Context->ClearedSyscallInfo :", "\n".join(delegator))
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "needs a C++ compiler")
def test_cleared_state_is_preferred_only_when_flagged(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
source = "\n".join([
"#include <cstdint>",
"#include <cstdio>",
"enum ContextFlags : uint32_t { CONTEXT_FLAG_INJIT = 1U << 0, CONTEXT_FLAG_SYSCALLINFO_CLEARED = 1U << 1 };",
"struct Backup { uint16_t InSyscallInfo; uint16_t ClearedSyscallInfo; uint32_t Flags; };",
self.saved_info(),
"int main() {",
" const Backup Thunk {0, 0xFFFF, CONTEXT_FLAG_SYSCALLINFO_CLEARED};",
" const Backup Jit {0x0F0F, 0x1234, CONTEXT_FLAG_INJIT};",
" const Backup Idle {0, 0x1234, 0};",
" std::printf(\"%x %x %x\\n\", SavedSyscallInfo(&Thunk), SavedSyscallInfo(&Jit), SavedSyscallInfo(&Idle));",
"}",
])
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "saved.cpp"
binary = Path(tmp) / "saved"
path.write_text(source)
subprocess.run([compiler, "-std=c++20", "-Wall", "-Werror", "-o", str(binary), str(path)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
self.assertEqual(output.split(), ["ffff", "f0f", "0"])
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalRegisterUpdateProbeTest(unittest.TestCase):
@classmethod
@@ -0,0 +1,81 @@
"""Focused worker-grant contract; no Android or guest boot required."""
import os
import sys
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'app/src/main/cpp/waylandcomp/src'
JAVA=ROOT/'app/src/main/java/com/droiddeck/launcher'
class FrameAcquirePeerGateTest(unittest.TestCase):
def test_app_issued_identity_and_executable_mapping(self):
with tempfile.TemporaryDirectory() as tmp:
image=Path(tmp)/'probe'
subprocess.run([os.environ.get('CC','cc'), '-std=c11','-Wall','-Wextra','-Werror',
'-I',str(SRC),str(Path(__file__).with_name('frame_worker_peer_test.c')),
'-o',str(image)],check=True)
subprocess.run([str(image)],check=True,timeout=10)
@unittest.skipUnless(sys.platform.startswith("linux"), "Requires Linux procfs and pidfd")
def test_live_worker_mapping_starttime_and_revocation(self):
with tempfile.TemporaryDirectory() as tmp:
image = Path(tmp) / "probe"
subprocess.run([os.environ.get("CC", "cc"), "-std=c11", "-Wall", "-Wextra", "-Werror",
"-I", str(SRC), str(Path(__file__).with_name("frame_worker_peer_live_test.c")),
"-o", str(image)], check=True)
subprocess.run([str(image)], check=True, timeout=10)
def test_publish_before_worker_go_and_require_map_at_bind(self):
workers=(JAVA/'runtime/GuestWorkers.kt').read_text()
broker=workers.split("private fun start(",1)[1].split("private fun takeWarm",1)[0]
check=broker.index("if (stopping() || !confirmed())")
publish=broker.index("FrameAcquireWorkerProbe.publish",check)
self.assertLess(publish,broker.index("Os.write(go[1]",check))
self.assertIn("if (slot.service === service) startTicks else 0L",broker)
self.assertIn("val size = reply.dataAvail()",broker)
self.assertIn("if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)",broker)
service=workers.split("override fun onTransact",1)[1].split("Handler(",1)[0]
self.assertIn("data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG",service)
self.assertIn("Binder.getCallingUid() == Process.myUid()",service)
self.assertIn("data.dataAvail() == Int.SIZE_BYTES",service)
self.assertIn("reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))",service)
self.assertIn('if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke',workers)
comp=(SRC/'compositor.c').read_text()
bind=comp.split('static void bind_frame_acquire',1)[1].split('#endif',1)[0]
self.assertIn('frame_acquire_peer_allowed(client, true, true)',bind)
self.assertIn('poll(&alive, 1, 0) == 0',comp)
def test_admission_diagnostics_are_coarse_bounded_and_probe_only(self):
kt=(JAVA/'runtime/FrameAcquireWorkerProbe.kt').read_text()
comp=(SRC/'compositor.c').read_text()
jni=(SRC/'waylandcomp_jni.c').read_text()
prepare=kt.split('fun prepare(',1)[1].split('fun arm(',1)[0]
match=kt.split('fun match(',1)[1].split('fun publish(',1)[0]
self.assertIn('!WaylandCompositor.frameWorkerProbeEnabled()',prepare)
self.assertIn('context.assets.open("linuxfs" + PATH)',prepare)
self.assertIn('context.assets.open("linuxfs" + SESSION_SCRIPT)',prepare)
svc=(JAVA/'session/SessionService.kt').read_text()
self.assertIn('SessionPrefs.producerAcquireFences(this)',svc)
self.assertIn('nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment',svc)
prefs=(JAVA/'session/SessionPrefs.kt').read_text()
self.assertIn('getBoolean("producerAcquireFences", false)',prefs)
self.assertLess(match.index('?: return null'),match.index('breadcrumb('))
self.assertIn('"--version" !in argv',match)
self.assertIn('if (reported.add(stage))',kt)
self.assertIn('"worker_admission=" + reason.name',kt)
for name in ('MATCH_ACK','MATCH_OWNER','MATCH_EXPIRED','MATCH_PATH','MATCH_ROOT',
'MATCH_ARGV','MATCH_FILE','MATCH_DIGEST','QUALIFIED','PUBLISH_TICKET',
'PUBLISH_RESTAT','PUBLISH_NATIVE','PUBLISH_RECEIPT','RESERVED'):
self.assertIn('Reason.'+name,kt)
self.assertIn(' return JNI_FALSE;\n#endif',jni.split('frameWorkerProbeEnabled(',1)[1])
self.assertIn('if (!frame_worker_map_reported)',comp)
for name in ('NATIVE_FILE','NATIVE_PIDFD','NATIVE_STAT_OPEN_DENIED','NATIVE_STAT_OPEN_HIDDEN',
'NATIVE_STAT_OPEN_OTHER','NATIVE_STAT_READ','NATIVE_STAT_PARSE','NATIVE_STAT_ZERO',
'NATIVE_STAT_MISMATCH','NATIVE_PIDFD_NOT_LIVE','NATIVE_ALREADY_RESERVED',
'MAP_STARTTIME','MAP_OPEN','MAP_IDENTITY'):
self.assertIn('"worker_admission='+name+'"',comp)
+166
View File
@@ -0,0 +1,166 @@
"""Exercise production receiver and attachment replacement with Unix FD passing.
This Linux fixture stubs Wayland resources and only the success/status values of
SYNC_IOC_FILE_INFO. It does not claim a Vulkan or SurfaceFlinger hardware test.
"""
import os
from pathlib import Path
import platform
import subprocess
import tempfile
import unittest
from test_vk_pending_completion import function
SRC = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src'
HEAD = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/sync_file.h>
static int query_status, query_result;
static unsigned query_count;
static int test_ioctl(int fd, unsigned long request, void *arg) {
assert(fd >= 0 && request == SYNC_IOC_FILE_INFO);
struct sync_file_info *info = arg;
assert(!info->flags && !info->sync_fence_info);
query_count++;
info->status = query_status;
info->num_fences = 1;
return query_result;
}
#define ioctl test_ioctl
#include "frame_acquire.h"
#undef ioctl
#include "wayland-util.h"
void wl_list_init(struct wl_list *list) { list->prev = list->next = list; }
void wl_list_remove(struct wl_list *list) { (void)list; }
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
struct wl_client { int identity; };
struct wl_resource { struct wl_client *owner; void *data; int type; unsigned error; };
struct surface {
struct wl_resource *pending_buffer;
struct wl_listener pending_buffer_destroy;
struct dd_frame_acquire pending_frame_acquire;
int pending_attach;
};
static int wl_surface_interface, surface_impl;
static int peer_allowed=1;
static int frame_acquire_peer_allowed(const struct wl_client *c, bool verify_exec, bool bind) { (void)c; (void)verify_exec; (void)bind; return peer_allowed; }
static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->owner; }
static void *wl_resource_get_user_data(struct wl_resource *r) { return r->data; }
static int wl_resource_instance_of(struct wl_resource *r, const void *iface, const void *impl) {
assert(iface == &wl_surface_interface && impl == &surface_impl);
return r->type == 1;
}
static int get_dmabuf(struct wl_resource *r) { return r->type == 2; }
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { (void)r; (void)l; }
static void wl_resource_post_error(struct wl_resource *r, unsigned err, const char *why) {
assert(why && !r->error);
r->error = err+1;
}
'''
TAIL = r'''
/* Real descriptor transfer and sender close; before dispatch, receiver owns it. */
static int tx(int fd) {
int conn[2]; char byte = 'F';
assert(socketpair(AF_UNIX, SOCK_DGRAM, 0, conn) == 0);
union { struct cmsghdr a; char bytes[CMSG_SPACE(sizeof(fd))]; } control = {0};
struct iovec payload = {.iov_base=&byte, .iov_len=1};
struct msghdr msg = {.msg_iov=&payload, .msg_iovlen=1, .msg_control=control.bytes,
.msg_controllen=sizeof(control.bytes)};
struct cmsghdr *h = CMSG_FIRSTHDR(&msg);
h->cmsg_len=CMSG_LEN(sizeof(fd)); h->cmsg_level=SOL_SOCKET; h->cmsg_type=SCM_RIGHTS;
memcpy(CMSG_DATA(h), &fd, sizeof(fd));
assert(sendmsg(conn[0], &msg, 0) == 1);
assert(close(fd) == 0);
memset(&control, 0, sizeof(control));
assert(recvmsg(conn[1], &msg, MSG_CMSG_CLOEXEC) == 1);
assert(!(msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) && byte == 'F');
h=CMSG_FIRSTHDR(&msg);
assert(h && h->cmsg_len==CMSG_LEN(sizeof(fd)) && h->cmsg_level==SOL_SOCKET && h->cmsg_type==SCM_RIGHTS);
memcpy(&fd, CMSG_DATA(h), sizeof(fd));
close(conn[0]); close(conn[1]);
return fd;
}
static int transmit_fd(void) {
int p[2]; assert(pipe(p) == 0); close(p[1]); return tx(p[0]);
}
static void closed(int fd) {
assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF);
}
int main(void) {
struct wl_client client={1}, unrelated={2};
struct surface s={0};
struct wl_resource manager={.owner=&client}, surf={.owner=&client,.data=&s,.type=1};
struct wl_resource buf={.owner=&client,.type=2}, other={.owner=&client,.type=2};
struct wl_resource wrong_owner={.owner=&unrelated,.type=2}, not_dmabuf={.owner=&client,.type=3};
int fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(manager.error == 1 && !query_count); closed(fd);
surface_attach(&client,&surf,&buf,0,0);
struct wl_resource *bad[] = {&other, &wrong_owner, &not_dmabuf, NULL};
for (unsigned i=0; i<sizeof(bad)/sizeof(*bad); i++) {
fd=transmit_fd(); manager.error=0;
frame_acquire_set(&client,&manager,&surf,bad[i],fd);
assert(manager.error == 1 && !query_count); closed(fd);
}
manager.error=0; query_status=1; fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(!manager.error && query_count==1 && s.pending_frame_acquire.fd_plus_one==fd+1);
int display_fd=dd_frame_acquire_dup(&s.pending_frame_acquire);
assert(display_fd>=0 && display_fd!=fd && (fcntl(display_fd,F_GETFD)&FD_CLOEXEC));
close(display_fd);
int duplicate=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,duplicate);
assert(manager.error==2 && query_count==1); closed(duplicate);
/* The same Wayland buffer, attached a second time, is a different write. */
surface_attach(&client,&surf,&buf,0,0);
assert(dd_frame_acquire_dup(&s.pending_frame_acquire)==-1); closed(fd);
for (int status=0; status>=-2; status--) {
manager.error=0; query_status=status;
if (status==-2) query_result=-1; /* non-sync file ioctl failure */
fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(manager.error == 3 && !s.pending_frame_acquire.fd_plus_one); closed(fd);
}
manager.error=0; query_result=0; query_status=1;
fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(!manager.error);
on_pending_buffer_destroyed(&s.pending_buffer_destroy,NULL);
assert(!s.pending_buffer && !s.pending_frame_acquire.fd_plus_one); closed(fd);
peer_allowed=0; manager.error=0;
surface_attach(&client,&surf,&buf,0,0);
fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(manager.error==4&&!s.pending_frame_acquire.fd_plus_one);closed(fd);
return 0;
}
'''
@unittest.skipUnless(platform.system() == 'Linux', 'Linux sync_file UAPI')
class FrameAcquireProtocolTest(unittest.TestCase):
def test_production_receiver_rejects_invalid_and_keeps_exact_attachment(self):
comp = (SRC / 'compositor.c').read_text()
protocol = (SRC.parent / 'generated/droiddeck-frame-acquire-v1-server-protocol.h').read_text()
errors = protocol.split('enum droiddeck_frame_acquire_v1_error {', 1)[1].split('};', 1)[0]
actual = '\n'.join(function(comp, name) for name in (
'on_pending_buffer_destroyed', 'surface_attach', 'frame_acquire_set'))
with tempfile.TemporaryDirectory(prefix='droiddeck-frame-acquire-') as tmp:
probe = Path(tmp) / 'probe.c'
exe = Path(tmp) / 'probe'
probe.write_text(HEAD + '\nenum droiddeck_frame_acquire_v1_error {' + errors + '};\n' + actual + TAIL)
subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-Wall', '-Wextra',
'-Werror', '-Wno-unused-parameter', '-UNDEBUG', '-fsanitize=address,undefined',
'-I', str(SRC), '-I', str(SRC.parent / 'prebuilt/include'),
str(probe), '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True, timeout=10)
+69
View File
@@ -0,0 +1,69 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_vk_pending_completion import function
class FramegenHangBreakerTest(unittest.TestCase):
def run_c(self, body):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if not compiler:
self.skipTest('A host C compiler is required')
root = Path(__file__).resolve().parents[2]
source = (root / 'app/src/main/cpp/waylandcomp/src/framegen_bridge.c').read_text()
code = '#include <assert.h>\n#include <stdatomic.h>\n#include <stdint.h>\n'
code += '#define FG_PROVEN_FRAMES 120\n#define FG_HANG_STRIKES 2\n'
code += 'static _Atomic int g_hang_strikes, g_dev_lost;\n'
code += 'static int g_submitted_since_ready;\nstatic uint64_t g_total_generated, g_generated_at_ready;\n'
code += function(source, 'framegen_loss_strike')
code += function(source, 'framegen_count_loss')
code += 'int main(void) {\n' + body + '\n}\n'
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
probe = folder / 'breaker.c'
binary = folder / 'breaker'
probe.write_text(code)
subprocess.run([compiler, '-std=c11', str(probe), '-o', str(binary)], check=True,
capture_output=True, text=True)
subprocess.run([str(binary)], check=True, capture_output=True, timeout=10)
def test_losses_before_any_generated_frame_completes_switch_generation_off(self):
self.run_c('''
assert(framegen_loss_strike(1, 0) == 0);
assert(framegen_loss_strike(1, 0) == 1);
assert(framegen_loss_strike(1, 0) == 0);
''')
def test_a_loss_after_generation_worked_keeps_it_armed(self):
self.run_c('''
assert(framegen_loss_strike(1, 0) == 0);
assert(framegen_loss_strike(1, 500) == 0);
assert(framegen_loss_strike(1, 0) == 0);
''')
def test_a_loss_without_generation_work_is_not_a_strike(self):
self.run_c('''
assert(framegen_loss_strike(1, 0) == 0);
assert(framegen_loss_strike(0, 0) == 0);
assert(framegen_loss_strike(1, 0) == 0);
''')
def test_a_loss_reported_twice_counts_once(self):
self.run_c('''
for (int loss = 0; loss < 2; loss++) {
g_dev_lost = 0;
g_submitted_since_ready = 1;
int first = framegen_count_loss();
int again = framegen_count_loss();
assert(again == 0);
assert(first == (loss == 1));
}
''')
if __name__ == '__main__':
unittest.main()
@@ -31,6 +31,8 @@ static void destroy_image(int d, int image, const void *a) {
static void destroy_view(int d, int view, const void *a) { assert(idle == 1); views++; }
static void free_memory(int d, int mem, const void *a) { assert(images > memory); memory++; }
static void fge_forget_targets(void) { assert(images == 3); engine++; }
static void vkp_framegen_set_layer_timing(int layer) { (void)layer; }
static void vkp_framegen_completed(void) {}
static struct {
void (*DeviceWaitIdle)(int);
void (*DestroyImage)(int, int, const void *);
+94 -6
View File
@@ -24,6 +24,16 @@ STATE = tempfile.TemporaryDirectory()
COMPAT["main"].__globals__["COMPAT_DIR"] = STATE.name
class ProducerAcquireGameEnvironmentTest(unittest.TestCase):
def test_prefixed_opt_in_enters_only_the_game_environment(self):
key = "DROIDDECK_GAME_FRAME_ACQUIRE"
scope = MODULE["GAME_PREFIX"] + key
self.assertEqual({}, MODULE["game_gpu"]({scope: "1"}, keep=True))
self.assertEqual({key: "1"}, MODULE["game_gpu"]({scope: "1"}))
self.assertEqual({}, MODULE["game_gpu"]({key: "1", scope: ""}))
self.assertEqual({}, MODULE["game_gpu"]({}))
class SupergiantDotnetReporterTest(unittest.TestCase):
def test_allows_the_builtin_mscoree_for_supergiant_reporter(self):
game = mock.Mock(files={"basecampbugreporter.native.dll"})
@@ -689,6 +699,7 @@ class GameDebugLoggingTest(unittest.TestCase):
inherited = {"DD_DEBUG_DIR": debug_dir, "PROTON_LOG": "0", "WINEDEBUG": "-all,+relay",
"PROTON_LOG_DIR": "/old", "PROTON_CRASH_REPORT_DIR": "/old-crashes",
"DXVK_LOG_PATH": "/old-dxvk", "DXVK_LOG_LEVEL": "none", "VKD3D_DEBUG": "none",
"VKD3D_SHADER_DEBUG": "none",
"CUSTOM": "$(touch never); 'quoted' = literal", "DXVK_CONFIG": "dxvk.tearFree = True"}
config = {"version": 1, "gameDebugLogs": True,
"shared": {"PROTON_LOG": "0", "DD_DEBUG_DIR": "/profile-redirect"},
@@ -699,7 +710,8 @@ class GameDebugLoggingTest(unittest.TestCase):
for key in ("PROTON_LOG_DIR", "PROTON_CRASH_REPORT_DIR", "DXVK_LOG_PATH"):
self.assertEqual(debug[key], debug_dir)
self.assertEqual(debug["DXVK_LOG_LEVEL"], "debug")
self.assertEqual(debug["VKD3D_DEBUG"], "info")
self.assertEqual(debug["VKD3D_DEBUG"], "warn")
self.assertEqual(debug["VKD3D_SHADER_DEBUG"], "warn")
self.assertIn("+relay", debug["WINEDEBUG"].split(","))
self.assertTrue(debug["WINEDEBUG"].endswith("+loaddll,+mscoree"))
for key in ("CUSTOM", "DXVK_CONFIG", "DD_DEBUG_DIR"):
@@ -1582,6 +1594,48 @@ class GameEnvironmentTest(unittest.TestCase):
(other / "Other.exe").touch()
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
def test_original_xbox_games_get_the_emulator_fixes_instead_of_the_dotnet_preset(self):
expected = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "0", "FEX_MEMCPYSETTSOENABLED": "0",
"FEX_HALFBARRIERTSOENABLED": "1", "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"}
def package(folder, identity):
(folder / "EmuMenu").mkdir(parents=True)
for name in ("Emu.exe", "EmuMenu/EmuMenu.exe", "EmuMenu/coreclr.dll"):
(folder / name).touch()
(folder / "MicrosoftGame.config").write_text(
'<?xml version="1.0" encoding="utf-8"?><Game configVersion="1"><Identity Name="%s" '
'Publisher="CN=Microsoft" Version="1.0.0.0"/><ExecutableList><Executable Name="EmuMenu\\EmuMenu.exe"/>'
'</ExecutableList></Game>' % identity)
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "Fuzion Frenzy"
package(game, "Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio")
for exe in (game / "Emu.exe", game / "EmuMenu/EmuMenu.exe"):
env, extra, notes = MODULE["engine_fixes"](str(exe), [], "2773102903")
self.assertEqual((env, extra), (expected, []))
self.assertEqual(len(notes), 1)
self.assertTrue(notes[0].startswith("Original Xbox game"))
config = {"version": 1, "games": {"2773102903": {"FEX_X87REDUCEDPRECISION": "0", "VKD3D_PACKED_422": None}}}
result = MODULE["apply_config"]({}, config, "2773102903", env)
self.assertEqual(result["FEX_X87REDUCEDPRECISION"], "0")
self.assertNotIn("VKD3D_PACKED_422", result)
self.assertEqual(result["WINE_SPECIAL_APC_INTERRUPT"], "1")
store = Path(tmp) / "Psychonauts"
package(store, "Microsoft.PsychonautsforWindows10")
env, extra, notes = MODULE["engine_fixes"](str(store / "Emu.exe"), [])
self.assertEqual(env, MODULE["DOTNET_FEX"])
self.assertEqual(notes, [".NET runtime: FEX with full TSO"])
(store / "MicrosoftGame.config").write_text("<Game><Identity Name=")
self.assertEqual(MODULE["engine_fixes"](str(store / "Emu.exe"), [])[0], MODULE["DOTNET_FEX"])
self.assertEqual(MODULE["xbox_identity"](str(Path(tmp) / "Other/Game.exe")), "")
# The Xbox store accepts the file name in any case.
(game / "MicrosoftGame.config").rename(game / "microsoftgame.config")
self.assertEqual(MODULE["xbox_identity"](str(game / "EmuMenu/EmuMenu.exe")),
"Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio")
def test_easy_anti_cheat_games_start_offline_only_when_opted_in(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "ELDEN RING/Game"
@@ -1741,6 +1795,38 @@ class GameEnvironmentTest(unittest.TestCase):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_playstation_pc_sdk_games_get_full_x87_precision_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
unreal = Path(tmp) / "StellarBlade"
binaries = unreal / "SB/Binaries/Win64"
binaries.mkdir(parents=True)
for name in ("SB-Win64-Shipping.exe", "PsPcSdkRuntimeInstaller.msi"):
(binaries / name).touch()
(unreal / "SB.exe").touch()
for exe in (unreal / "SB.exe", binaries / "SB-Win64-Shipping.exe"):
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
self.assertEqual((env, extra), ({"FEX_X87REDUCEDPRECISION": "0"}, []))
self.assertIn("PlayStation PC SDK: FEX with full x87 precision", notes)
config = {"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3489700", env)["FEX_X87REDUCEDPRECISION"], "0")
config["games"] = {"3489700": {"FEX_X87REDUCEDPRECISION": "1"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3489700", env)["FEX_X87REDUCEDPRECISION"], "1")
port = Path(tmp) / "Port"
port.mkdir()
for name in ("Game.exe", "install_pspc_sdk_runtime.bat"):
(port / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(port / "Game.exe"), [])[0], {"FEX_X87REDUCEDPRECISION": "0"})
other = Path(tmp) / "OtherUnreal"
other_binaries = other / "Other/Binaries/Win64"
other_binaries.mkdir(parents=True)
(other_binaries / "Other-Win64-Shipping.exe").touch()
(other / "Other.exe").touch()
(other / "Other/Binaries/Win64/PsPcSdkRuntimeInstaller.txt").touch()
for exe in (other / "Other.exe", other_binaries / "Other-Win64-Shipping.exe"):
self.assertEqual(MODULE["engine_fixes"](str(exe), []), ({}, [], []))
def test_store_launcher_resolves_the_game_executable_from_the_sidecar(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "BatmanArkhamCity"
@@ -2612,8 +2698,8 @@ class GameEnvironmentTest(unittest.TestCase):
def test_both_proton_wrappers_call_environment_launcher(self):
self.assertIn('dd_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["extra_wrapper_sh"]("proton"))
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
@@ -2621,9 +2707,11 @@ class GameEnvironmentTest(unittest.TestCase):
scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton"))
query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe"
probe = "/root/.local/share/Steam/steamapps/compatdata/0"
for script in scripts:
for script, here in zip(scripts, ("$depot", "$here")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("dd_components "))
answered = script.index('case "$verb:${1##*/}:')
self.assertLess(answered, script.index('dd_components "%s"' % here))
self.assertLess(answered, script.index('dd_anticheat "$@"'))
for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"),
([query.replace("64.exe", ".exe")], probe)):
result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True,
@@ -2652,7 +2740,7 @@ class GameEnvironmentTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
for name in ("libddsession.so", "libfakeinput.so"):
(Path(tmp) / name).write_bytes(b"")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
start = script.index("for fake in ")
block = script[start:script.index("\ndone\n", start) + 6].replace("/usr/local/lib/", tmp + "/")
for inherited, expected in (
+134
View File
@@ -0,0 +1,134 @@
'''Regression tests for tools/ime/prepare.py RPM extraction.'''
import contextlib
import importlib.util
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
import unittest
from unittest import mock
MODULE_PATH = Path(__file__).resolve().parents[1] / 'ime' / 'prepare.py'
SPEC = importlib.util.spec_from_file_location('ime_prepare', MODULE_PATH)
PREPARE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(PREPARE)
NUL = bytes(1)
def _newc(files):
archive = bytearray()
for inode, (name, data) in enumerate(files.items(), start=1):
encoded = name.encode('utf-8')
name_size = len(encoded) + 1
header = '070701' + ''.join(f'{value:08x}' for value in (
inode, 0o100644, 0, 0, 1, 0, len(data), 0, 0, 0, 0, name_size, 0))
archive += header.encode('ascii')
archive += encoded + NUL
archive += NUL * (-(110 + name_size) % 4)
archive += data
archive += NUL * (-len(data) % 4)
trailer = b'TRAILER!!!' + NUL
header = '070701' + ''.join(f'{value:08x}' for value in (
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, len(trailer), 0))
archive += header.encode('ascii')
archive += trailer
archive += NUL * (-(110 + len(trailer)) % 4)
return bytes(archive)
class ExtractTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
def _write_executable(self, path, text):
path.write_text(text, encoding='utf-8')
path.chmod(0o755)
def _tools(self, base, cpio, payload=None, exit_code=1):
tools = base / 'bin'
tools.mkdir(parents=True)
fixture = base / 'payload.cpio'
if payload is None:
script = f'''#!/bin/sh
echo rpm2cpio failed >&2
exit {exit_code}
'''
else:
fixture.write_bytes(payload)
script = f'''#!/bin/sh
exec cat {shlex.quote(str(fixture))}
'''
self._write_executable(tools / 'rpm2cpio', script)
self._write_executable(tools / 'cpio', f'''#!/bin/sh
exec {shlex.quote(str(cpio))} "$@"
''')
return tools
@contextlib.contextmanager
def _path(self, tools):
with mock.patch.dict(os.environ,
{'PATH': str(tools) + os.pathsep + os.environ.get('PATH', '')}):
yield
def _cpio_candidates(self):
candidates = []
for command in ('cpio', 'bsdcpio'):
path = shutil.which(command)
if path:
candidates.append((command, Path(path)))
return candidates
def test_extract_normal_payload_with_available_cpio(self):
candidates = self._cpio_candidates()
if not candidates:
self.skipTest('no cpio implementation is available')
payload = _newc({'usr/share/demo.txt': b'hello'})
for command, cpio in candidates:
with self.subTest(cpio=command):
base = self.root / ('normal-' + command)
base.mkdir()
tools = self._tools(base, cpio, payload)
destination = base / 'destination'
with self._path(tools):
PREPARE.extract('demo', base / 'demo.rpm', destination)
self.assertEqual((destination / 'usr/share/demo.txt').read_bytes(), b'hello')
def test_extract_rejects_unsafe_paths_before_writing(self):
candidates = self._cpio_candidates()
if not candidates:
self.skipTest('no cpio implementation is available')
cpio = candidates[0][1]
for label in ('absolute', 'parent'):
with self.subTest(case=label):
base = self.root / ('unsafe-' + label)
base.mkdir()
outside = base / (label + '-escaped.txt')
name = str(outside) if label == 'absolute' else '../' + outside.name
tools = self._tools(base, cpio, _newc({'payload/safe.txt': b'safe', name: b'bad'}))
destination = base / 'destination'
with self._path(tools), self.assertRaises(ValueError) as caught:
PREPARE.extract('unsafe', base / 'unsafe.rpm', destination)
self.assertIn('unsafe path', str(caught.exception))
self.assertFalse((destination / 'payload/safe.txt').exists())
self.assertFalse(outside.exists())
def test_extract_propagates_rpm2cpio_failure(self):
candidates = self._cpio_candidates()
if not candidates:
self.skipTest('no cpio implementation is available')
base = self.root / 'failed'
base.mkdir()
tools = self._tools(base, candidates[0][1], exit_code=7)
with self._path(tools), self.assertRaises(subprocess.CalledProcessError) as caught:
PREPARE.extract('broken', base / 'broken.rpm', base / 'destination')
self.assertEqual(caught.exception.returncode, 7)
if __name__ == '__main__':
unittest.main()
+247 -4
View File
@@ -1025,6 +1025,19 @@ int main(int argc, char **argv) {
errno = 0;
printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH);
}
if (strcmp(argv[1], "nowait") == 0) {
// no wait until the program has long exited, as Plasma's shell never waits for what it launches
usleep(2000000);
char path[64], line[256] = "";
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
FILE *f = fopen(path, "r");
if (f) {
if (!fgets(line, sizeof(line), f)) line[0] = 0;
fclose(f);
}
char *s = strrchr(line, ')');
printf("zombie\t%d\n", s && s[1] == ' ' && s[2] == 'Z');
}
int group = strcmp(argv[1], "group") == 0;
if (group) {
setpgid(pid, pid);
@@ -1111,6 +1124,121 @@ int main(void) {
# A worker's program with its table at fd 1000 (kept, as 900 and 901 are): a dup2() onto the pidfd
# lets go of 900 while another thread's close_range(899, 2000) is between its parts, held there by the
# hook's test gate. The kept fds above 900 stay open.
PIDFD_PROBE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
errno = 0;
long r = syscall(SYS_waitid, 3, INT_MAX, NULL, WEXITED | WNOHANG, NULL);
printf("waitid\t%ld %d\n", r, errno);
int pidfd = -1;
errno = 0;
r = syscall(SYS_clone, 0x00001000 | SIGCHLD, NULL, &pidfd, NULL, 0);
if (r == 0) _exit(9);
printf("clone\t%ld %d %d\n", r < 0 ? -1L : 1L, errno, pidfd);
if (r > 0) waitpid((pid_t)r, NULL, 0);
r = syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0);
if (r == 0) _exit(7);
int status = 0;
printf("fork\t%d\n", r > 0 && waitpid((pid_t)r, &status, 0) == r && WIFEXITED(status) ? WEXITSTATUS(status) : -1);
return 0;
}
"""
# A child subreaper, as every session process is (preload/subreaper.c), that never waits for a child
# it did not fork. adopt: a child that exits at once leaves a grandchild, which exits once the child is
# gone; own: its own child, which it waits for only later; vfork: one vfork() made, its program static
# (no hook, so no record of it); handler: as adopt, with a SIGCHLD handler of its own; ignore: SIGCHLD
# ignored, so the kernel reaps.
ORPHANS = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static volatile sig_atomic_t calls;
static void counted(int sig) { (void)sig; calls++; }
static void nap(long ms) {
struct timespec t = {ms / 1000, (ms % 1000) * 1000000L};
while (nanosleep(&t, &t) != 0 && errno == EINTR) {}
}
static int zombie(pid_t pid) {
char path[64], line[256] = "";
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
FILE *f = fopen(path, "r");
if (!f) return 0;
if (!fgets(line, sizeof(line), f)) line[0] = 0;
fclose(f);
char *s = strrchr(line, ')');
return s && s[1] == ' ' && s[2] == 'Z';
}
int main(int argc, char **argv) {
const char *mode = argv[1];
int subreaper = 0;
printf("subreaper\t%d\n", prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 && prctl(PR_GET_CHILD_SUBREAPER, &subreaper) == 0 && subreaper);
fflush(stdout);
if (strcmp(mode, "handler") == 0) {
struct sigaction sa, seen;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = counted;
sa.sa_flags = SA_RESTART;
sigaction(SIGCHLD, &sa, NULL);
sigaction(SIGCHLD, NULL, &seen);
printf("view\t%d\n", seen.sa_handler == counted);
}
if (strcmp(mode, "ignore") == 0) signal(SIGCHLD, SIG_IGN);
if (strcmp(mode, "own") == 0 || strcmp(mode, "vfork") == 0) {
pid_t child = strcmp(mode, "vfork") == 0 ? vfork() : fork();
if (child == 0) {
if (argc > 2) execl(argv[2], "target", "7", (char *)NULL);
_exit(7);
}
nap(1500);
int status = 0;
pid_t r = waitpid(child, &status, 0);
printf("own\t%d\n", r == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1);
return 0;
}
int pipefd[2];
if (pipe(pipefd) != 0) return 1;
pid_t middle = fork();
if (middle == 0) {
pid_t grandchild = fork();
if (grandchild == 0) {
nap(300); // its parent is gone by then
_exit(5);
}
if (write(pipefd[1], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) _exit(1);
_exit(0);
}
pid_t grandchild = 0;
if (read(pipefd[0], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) return 1;
int status = 0;
printf("middle\t%d\n", waitpid(middle, &status, 0) == middle);
nap(1500);
printf("orphan\t%d\n", zombie(grandchild));
printf("adopted\t%d\n", waitpid(grandchild, &status, WNOHANG) == grandchild);
if (strcmp(mode, "handler") == 0) printf("calls\t%d\n", calls > 0);
return 0;
}
"""
DUPRACE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
@@ -1452,7 +1580,7 @@ class NativeHookHandoffTest(unittest.TestCase):
raise RuntimeError("workers that may still run: %s" % failed)
def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False,
delay=0, extra_env=None):
delay=0, extra_env=None, parent_name=None):
name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook)
spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay)
spawner.start()
@@ -1468,9 +1596,9 @@ class NativeHookHandoffTest(unittest.TestCase):
hook_env["QEMU_LD_PREFIX"] = self.prefix[self.prefix.index("-L") + 1]
env = {k: v for k, v in os.environ.items() if k not in hook_env}
prefix, parent = list(self.prefix or []), str(self.parent)
if as_shell:
# the hook tells a shell's child by its parent's name (qemu-user takes the program's)
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / "bash"
if as_shell or parent_name:
# the hook tells a shell's or a launcher's child by its parent's name (qemu-user takes the program's)
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / (parent_name or "bash")
shell.parent.mkdir(exist_ok=True)
shutil.copy(parent, shell)
parent = str(shell)
@@ -1679,6 +1807,41 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual([], requests)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def run_launcher(self, *argv, parent_name="plasmashell", **kwargs):
return self.run_parent(*argv, handoff="other", pressure=1000, parent_name=parent_name,
extra_env={"DD_HANDOFF_LAUNCHERS": "plasmashell:krunner"}, **kwargs)
def test_a_program_a_desktop_launcher_starts_is_handed_off(self):
# an app from Plasma's panel: unlisted, far from the limit, still its own app process
result, requests, out = self.run_launcher("wait", "7")
self.assertEqual(1, len(requests), out.stderr)
self.assertEqual(["target", "7"], requests[0]["argv"])
self.assertEqual("7", result.get("exit"), out.stdout)
def test_a_child_of_a_program_not_named_a_launcher_is_not(self):
result, requests, out = self.run_launcher("wait", "3", parent_name="konsole")
self.assertEqual([], requests, out.stderr)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_a_launchers_child_in_a_process_group_of_its_own_is_not(self):
result, requests, out = self.run_launcher("group", "4")
self.assertEqual([], requests, out.stderr)
self.assertEqual("4" if self.child_status == "3" else "127", result.get("exit"), out.stdout)
def test_a_launchers_child_on_a_terminal_is_not(self):
# a terminal's shell, set up by its launcher (Konsole's part in Dolphin): the terminal is its own
result, requests, out = self.run_launcher("wait", "3", terminal=True)
self.assertEqual([], requests, out.stderr)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_the_steam_client_a_launcher_starts_is_not(self):
steam = self.root / "bin/steam"
if not steam.exists():
shutil.copy(self.root / "bin/target", steam)
result, requests, out = self.run_launcher("wait", "3", "/bin/steam")
self.assertEqual([], requests, out.stderr)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_near_the_limit_a_child_of_another_program_is_not(self):
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0)
self.assertEqual([], requests)
@@ -2217,6 +2380,86 @@ class NativeHookHandoffTest(unittest.TestCase):
pass_fds=(table,))
return parent, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
def run_orphans(self, mode, named=True, parents=True, *args):
tmp = Path(self.tmp.name)
probe = tmp / "orphans"
if not probe.exists():
(tmp / "orphans.c").write_text(ORPHANS)
subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "orphans.c")], check=True)
(self.root / "run").mkdir(exist_ok=True)
env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)}
if parents:
env["DD_PARENTS"] = "/run/parents-%s" % self.id().rsplit(".", 1)[-1]
if named:
env["DD_REAP_ADOPTED"] = "other:orphans"
# not a session's own settings, when run inside one
inherited = {k: v for k, v in os.environ.items() if k not in ("DD_PARENTS", "DD_REAP_ADOPTED")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in env.items() for arg in ("-E", f"{key}={value}")]
run_env = inherited
else:
cmd = []
run_env = dict(inherited, **env)
out = subprocess.run(cmd + [str(probe), mode, *args], env=run_env, capture_output=True, text=True, timeout=60)
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
if mode == "adopt" and result.get("subreaper") != "1":
self.skipTest("no child subreaper here (qemu-user has no PR_SET_CHILD_SUBREAPER)")
return result, out
def test_a_subreaper_reaps_the_zombie_it_adopted(self):
result, out = self.run_orphans("adopt")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual("1", result.get("middle"), out.stdout)
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
self.assertEqual("0", result.get("adopted"), out.stdout)
def test_a_program_not_named_keeps_its_default_sigchld_and_its_adopted_zombie(self):
result, out = self.run_orphans("adopt", False)
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
self.assertEqual("1", result.get("adopted"), out.stdout)
def test_without_a_parents_file_nothing_is_reaped(self):
result, out = self.run_orphans("adopt", True, False)
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
def test_a_subreapers_own_child_waits_for_its_wait(self):
result, out = self.run_orphans("own")
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
def test_a_vfork_child_with_no_record_waits_for_its_parents_wait(self):
result, out = self.run_orphans("vfork", True, True, "/bin/target")
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
def test_a_programs_own_sigchld_handler_runs_and_shows_as_its_own(self):
result, out = self.run_orphans("handler", False)
self.assertEqual("1", result.get("view"), out.stdout + out.stderr)
self.assertEqual("1", result.get("calls"), out.stdout)
if result.get("subreaper") == "1":
self.assertEqual("0", result.get("orphan"), out.stdout)
def test_an_ignored_sigchld_stays_the_kernels(self):
result, out = self.run_orphans("ignore")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
def test_an_unwaited_handoffs_child_is_reaped(self):
# a parent that never waits until its program has long exited, as Plasma's shell
(self.root / "run").mkdir(exist_ok=True)
env = {"DD_PARENTS": "/run/parents-nowait", "DD_REAP_ADOPTED": "parent"}
result, requests, out = self.run_parent("nowait", "6", extra_env=env)
self.assertEqual(1, len(requests), out.stderr)
self.assertEqual("0", result.get("zombie"), out.stdout + out.stderr)
# its program's exit, still there for the wait that comes at last
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual("6", result.get("exit"), out.stdout)
def test_a_guest_sees_no_pidfd_support_so_its_waits_go_through_the_handoff(self):
parent, result, out = self.run_worker_program("pidfd", PIDFD_PROBE)
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual("-1 %d" % errno.EINVAL, result.get("waitid"), out.stdout + out.stderr)
self.assertEqual("-1 %d -1" % errno.EINVAL, result.get("clone"), out.stdout)
self.assertEqual("7", result.get("fork"), out.stdout)
def test_a_dup2_onto_the_parents_pidfd_while_a_close_range_runs_closes_no_kept_fd(self):
parent, result, out = self.run_worker_program("duprace", DUPRACE, table_fd=1000)
self.assertEqual(0, out.returncode, out.stderr)
Loaded 100 of 406 files, more files were not shown because too many files have changed in this diff. Show more