chore: merge main into feat/lse-emu

This commit is contained in:
Kurt Himebauch committed 2026-11-24 00:23:06 -05:00
commit 83f9067a51
609 files changed
+46314 -8272

No files matched your search

+5 -4
View File
@@ -116,10 +116,11 @@ if [ ! -d "$ANDROID_HOME/platforms/android-34" ]; then
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null
fi
# A full Kotlin compile of the app runs out of memory with 2.4 GB of heap, and Gradle needs about 1 GB,
# so devices with less memory to spare swap rather than fail. Both daemons end with this script's
# process when the build is done.
heap=${DD_LAB_HEAP_MB:-4096}
# A full Kotlin compile of the app runs out of memory with 2.7 GB of heap, and Gradle needs about 1 GB,
# so devices with less memory to spare swap rather than fail. This script does not stop either daemon:
# when the app runs it, proot's --kill-on-exit ends both with it; run by hand, they outlive it, and the
# Kotlin daemon stays warm for the next incremental compile.
heap=${DD_LAB_HEAP_MB:-6144}
kotlin_heap=$(( heap * 2 / 3 )); gradle_heap=$(( heap - kotlin_heap ))
# Only the Kotlin daemon compiles incrementally; in-process compiles always redo the whole app, and the
+323 -232
View File
@@ -24,6 +24,7 @@ java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents
[[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17"
[[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir"
[[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir"
requested_image=${DROIDDECK_BUILD_IMAGE:-}
. "${repo_root}/tools/docker_platform.sh"
image_name=${DROIDDECK_BUILD_IMAGE}
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
@@ -63,6 +64,11 @@ fi
ndk_version=${DROIDDECK_NDK_VERSION:-}
if [[ -z "${ndk_version}" ]]; then
. "${repo_root}/tools/ci/toolchains.env"
[[ -d "${sdk_dir}/ndk/${CI_ANDROID_NDK_VERSION}" ]] && ndk_version=${CI_ANDROID_NDK_VERSION}
fi
if [[ -z "${ndk_version}" ]]; then
echo "NDK ${CI_ANDROID_NDK_VERSION} (tools/ci/toolchains.env) is not installed; using the newest NDK instead, so native caches will not match CI." >&2
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1)
ndk_version=${ndk_path##*/}
fi
@@ -112,94 +118,6 @@ save_step() {
python3 "${repo_root}/tools/docker_preflight.py" "${image_name}"
image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
docker run --rm --platform "${docker_platform}" \
--user "$(id -u):$(id -g)" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
set -euo pipefail
d=app/src/main/assets/linuxfs
mkdir -p "$d"
put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; }
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so"
bash tools/nativeguest/build.sh "$d/libddnatv-hook.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c
aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
mkdir -p "$d/usr/local/bin"
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
bash tools/linuxfs/lse-emu/build.sh "$d"
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
put "$script" "$d/usr/local/bin/$(basename "$script")"
done
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
[ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}"
done
put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper"
put tools/linuxfs/desktop/firefox-droiddeck.js \
"$d/usr/lib/firefox/defaults/pref/droiddeck.js"
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
'
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
app/src/main/cpp/fakeinput_steam.cpp)
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
docker run --rm --platform linux/amd64 \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
mkdir -p "${x86_stage}"
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
save_step x86-preloads "${x86_key}" "${x86_stage}"
fi
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
if ! restore_step vr "${vr_key}" "${vr_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
save_step vr "${vr_key}" "${vr_out}"
fi
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
save_step gpuload "${gpuload_key}" "${gpuload_out}"
fi
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
if [[ -z "${github_repo}" ]]; then
origin_url=$(git -C "${repo_root}" remote get-url origin)
@@ -216,46 +134,290 @@ if [[ -z "${github_repo}" ]]; then
github_repo=${github_repo%.git}
fi
cached() {
local sha=$1 name=$2 out
shift 2
out="${cache_dir}/${sha}-${name}"
if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then
echo "${out}"
return 0
ci_components=0
ci_run=
ci_cache="${cache_dir}/ci-components"
reuse_ci_components() {
[[ "${DROIDDECK_CI_COMPONENTS:-1}" == 1 ]] && command -v gh >/dev/null 2>&1 || return 1
# CI prepares with the pinned NDK, its own build image and PulseAudio source, and the system Vulkan headers.
. "${repo_root}/tools/ci/toolchains.env"
[[ "${ndk_version}" == "${CI_ANDROID_NDK_VERSION}" && -z "${DROIDDECK_PA13_SOURCE_DIR:-}" && -z "${VK_INCLUDE:-}" \
&& -z "${requested_image}" ]] || return 1
local base candidates run artifact archive part
base=$(git -C "${repo_root}" merge-base HEAD origin/main 2>/dev/null || true)
# Only runs of this repository's own main: a fork's pull request can also name its branch main.
candidates=$(gh api "repos/${github_repo}/actions/artifacts?name=prepared-components&per_page=100" \
-q "[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == \"main\")
| select(.workflow_run.head_repository_id == .workflow_run.repository_id)]
| sort_by(.workflow_run.head_sha != \"${base}\") | .[:3][] | \"\(.workflow_run.id):\(.id)\"" 2>/dev/null) || return 1
mkdir -p "${ci_cache}"
# CI keeps these artifacts for 14 days.
find "${ci_cache}" -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf {} +
for candidate in ${candidates}; do
run=${candidate%%:*}
artifact=${candidate#*:}
archive="${ci_cache}/${artifact}.tar.gz"
if [[ ! -f "${archive}" ]]; then
part=$(mktemp -d "${ci_cache}/${run}.part.XXXXXX")
if gh run download "${run}" -R "${github_repo}" -n prepared-components -D "${part}" >/dev/null 2>&1; then
mv "${part}/prepared-components.tar.gz" "${archive}"
fi
rm -rf "${part}"
[[ -f "${archive}" ]] || continue
fi
if python3 "${repo_root}/tools/components/reuse.py" "${archive}"; then
ci_run=${run}
return 0
fi
done
return 1
}
fetch_ci_xbox() {
local stored="${ci_cache}/${ci_run}-xbox" part
if [[ ! -d "${stored}" ]]; then
part=$(mktemp -d "${ci_cache}/${ci_run}-xbox.part.XXXXXX")
gh run download "${ci_run}" -R "${github_repo}" -n xbox-arm64 -D "${part}" >/dev/null 2>&1 || { rm -rf "${part}"; return 1; }
# rename(2) refuses a non-empty destination, so a copy another build published first wins.
python3 -c 'import os, sys; os.rename(sys.argv[1], sys.argv[2])' "${part}" "${stored}" 2>/dev/null || rm -rf "${part}"
fi
rm -f "${out}.part"
out="${out}.part" "$@" >&2
printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2
mv "${out}.part" "${out}"
echo "${out}"
rm -rf "${xbox_out}" && mkdir -p "${xbox_out}" && cp -R "${stored}/." "${xbox_out}/"
}
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
. "${repo_root}/tools/gamescope/release.env"
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
fi
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
if reuse_ci_components; then
ci_components=1
echo "components: every recipe identity matches main CI run ${ci_run}; reusing its prepared components (DROIDDECK_CI_COMPONENTS=0 builds them here)"
else
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
. "${repo_root}/tools/linuxfs/uruntime.env"
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
docker run --rm --platform "${docker_platform}" \
--user "$(id -u):$(id -g)" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
set -euo pipefail
d=app/src/main/assets/linuxfs
mkdir -p "$d"
put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; }
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so"
bash tools/nativeguest/build.sh "$d/libddnatv-hook.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c
aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
mkdir -p "$d/usr/local/bin"
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
bash tools/linuxfs/lse-emu/build.sh "$d"
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
put "$script" "$d/usr/local/bin/$(basename "$script")"
done
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
[ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}"
done
put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper"
put tools/linuxfs/desktop/firefox-droiddeck.js \
"$d/usr/lib/firefox/defaults/pref/droiddeck.js"
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
'
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
app/src/main/cpp/fakeinput_steam.cpp)
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
x86_platform=linux/amd64
x86_packages="gcc g++ gcc-multilib g++-multilib binutils"
x86_cross=0
if [[ "${docker_platform}" == linux/arm64 ]]; then
x86_platform=linux/arm64
x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu"
x86_cross=1
fi
docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
mkdir -p "${x86_stage}"
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
save_step x86-preloads "${x86_key}" "${x86_stage}"
fi
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
if ! restore_step vr "${vr_key}" "${vr_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
save_step vr "${vr_key}" "${vr_out}"
fi
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
save_step gpuload "${gpuload_key}" "${gpuload_out}"
fi
cached() {
local sha=$1 name=$2 out
shift 2
out="${cache_dir}/${sha}-${name}"
if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then
echo "${out}"
return 0
fi
rm -f "${out}.part"
out="${out}.part" "$@" >&2
printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2
mv "${out}.part" "${out}"
echo "${out}"
}
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
. "${repo_root}/tools/gamescope/release.env"
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
fi
. "${repo_root}/tools/linuxfs/uruntime.env"
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
. "${repo_root}/tools/droiddeck-esync/release.env"
sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \
bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}")
rm -rf "${sync_assets}"
mkdir -p "${sync_assets}"
zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}"
test -f "${sync_assets}/index.json"
test -f "${sync_assets}/index.json.sig"
elif [[ -d "${sync_assets}" ]]; then
echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2
fi
msi_pkgs="${staging_dir}/msi-pkgs"
msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools"
mkdir -p "${msi_pkgs}" "${msi_dir}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
tar -xJf "${package_archive}" -C "${msi_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done
for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}"
done
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools"
for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
install -m644 "${repo_root}/tools/msitools/licenses/${license}" \
"${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}"
done
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
mango_pkgs="${staging_dir}/mango-pkgs"
mkdir -p "${mango_dir}" "${mango_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
done
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
mkdir -p "${linuxfs_dir}/usr/local/bin"
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
pw_pkgs="${staging_dir}/pw-pkgs"
mkdir -p "${pw_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
mv "${pa_tarball}.part" "${pa_tarball}"
fi
mkdir -p "${pa_source}"
tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1
fi
if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2
exit 1
fi
sink_output="${staging_dir}/sink-out"
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1)
proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
&& "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
else
proot_stage="${staging_dir}/proot"
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
save_step proot "${proot_inputs}" "${proot_stage}"
fi
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
fi
fi
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
# Packs revoked after a bundle was published are dropped from local and CI-prepared bundles alike.
. "${repo_root}/tools/droiddeck-esync/release.env"
sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \
bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}")
rm -rf "${sync_assets}"
mkdir -p "${sync_assets}"
zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}"
test -f "${sync_assets}/index.json"
test -f "${sync_assets}/index.json.sig"
sync_index=$(mktemp)
gh release download "${SYNC_BUNDLE_TAG}" -R "${SYNC_BUNDLE_REPO}" -p index.json -O "${sync_index}" --clobber
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' "${sync_index}")
@@ -266,94 +428,6 @@ if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
fi
done
rm -f "${sync_index}"
elif [[ -d "${sync_assets}" ]]; then
echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2
fi
msi_pkgs="${staging_dir}/msi-pkgs"
msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools"
mkdir -p "${msi_pkgs}" "${msi_dir}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
tar -xJf "${package_archive}" -C "${msi_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done
for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}"
done
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools"
for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
install -m644 "${repo_root}/tools/msitools/licenses/${license}" \
"${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}"
done
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
mango_pkgs="${staging_dir}/mango-pkgs"
mkdir -p "${mango_dir}" "${mango_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
done
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
mkdir -p "${linuxfs_dir}/usr/local/bin"
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
pw_pkgs="${staging_dir}/pw-pkgs"
mkdir -p "${pw_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
mv "${pa_tarball}.part" "${pa_tarball}"
fi
mkdir -p "${pa_source}"
tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1
fi
if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2
exit 1
fi
sink_output="${staging_dir}/sink-out"
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1)
proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
&& "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
else
proot_stage="${staging_dir}/proot"
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
save_step proot "${proot_inputs}" "${proot_stage}"
fi
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
fi
syncthing_src="${repo_root}/tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing"
@@ -377,21 +451,23 @@ else
echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs"
fi
bundle_dir="${staging_dir}/pulseaudio-bundle"
mkdir -p "${bundle_dir}"
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
echo "The committed audio bundle already contains a built ARM64 sink." >&2
exit 1
if [[ "${ci_components}" != 1 ]]; then
bundle_dir="${staging_dir}/pulseaudio-bundle"
mkdir -p "${bundle_dir}"
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
echo "The committed audio bundle already contains a built ARM64 sink." >&2
exit 1
fi
install -m755 "${sink_output}/module-aaudio-sink.so" \
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
mkdir -p "${repo_root}/app/build/prepared-assets"
mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst"
fi
install -m755 "${sink_output}/module-aaudio-sink.so" \
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
mkdir -p "${repo_root}/app/build/prepared-assets"
mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst"
gradle_rust_arg=""
if [[ "${DROIDDECK_SKIP_RUST:-0}" == 1 ]]; then
@@ -412,19 +488,23 @@ else
fi
cd "${repo_root}"
python3 tools/quest/build-driver.py "${NDK}"
[[ "${ci_components}" == 1 ]] || python3 tools/quest/build-driver.py "${NDK}"
xbox_out="${linuxfs_dir}/usr/local/lib/droiddeck-xbox"
xbox_key=$(inputs_hash "native-arm64-ubuntu24.04" tools/xbox)
if ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
if [[ "${ci_components}" == 1 ]] && fetch_ci_xbox; then
echo "xbox: reused main CI run ${ci_run}"
elif ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
bash tools/xbox/build-local.sh
save_step xbox "${xbox_key}" "${xbox_out}"
fi
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
comet_key=$(inputs_hash "${image_id}" tools/comet)
if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
if [[ "${ci_components}" != 1 ]]; then
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
comet_key=$(inputs_hash "${image_id}" tools/comet)
if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
fi
fi
if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft"
@@ -437,10 +517,21 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
rockstar_out="${linuxfs_dir}/usr/local/lib/droiddeck-rockstar"
rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh)
if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then
command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}"
if [[ "$(uname -s)" == Darwin ]]; then
bash tools/rockstar-launcher/build-container.sh "${rockstar_out}"
else
command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}"
fi
save_step rockstar "${rockstar_key}" "${rockstar_out}"
fi
epic_out="${linuxfs_dir}/usr/local/lib/droiddeck-epic"
epic_key=$(inputs_hash "x86_64-pc-windows-gnu" tools/epic-launcher/src tools/epic-launcher/Cargo.toml tools/epic-launcher/Cargo.lock tools/epic-launcher/build.sh)
if ! restore_step epic "${epic_key}" "${epic_out}"; then
command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 || { echo "x86_64-w64-mingw32-gcc is required for EpicGamesLauncher.exe." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/epic-target" bash tools/epic-launcher/build.sh "${epic_out}"
save_step epic "${epic_key}" "${epic_out}"
fi
fi
python3 tools/powervr/fetch.py
bash tools/packs/build.sh app/build/packs
@@ -467,7 +558,7 @@ readelf_path=$(find "${NDK}/toolchains/llvm/prebuilt" -name llvm-readelf | head
[[ -x "${readelf_path}" ]] || { echo "NDK llvm-readelf is missing" >&2; exit 1; }
stores_check=()
[[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]] || stores_check+=(--without-stores)
python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" "${stores_check[@]}"
python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" ${stores_check[@]+"${stores_check[@]}"}
git diff --exit-code -- app/src/main/rust/stores/Cargo.lock
build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
set -uo pipefail
workspace="${1:?}"
find /tmp -maxdepth 1 -user "$(id -u)" \( -name 'robolectric-*' -o -name 'junit*' -o -name 'gradle-*' -o -name 'kotlin-*' \) -mmin +180 -print0 |
while IFS= read -r -d '' entry; do
recent=$(find "$entry" -xdev -mmin -180 -print -quit 2>/dev/null) && [ -z "$recent" ] && rm -rf --one-file-system --preserve-root=all -- "$entry"
done
free=$(df --output=avail -k "$workspace" | tail -1)
if [ "$free" -lt 20971520 ]; then
rm -rf --one-file-system --preserve-root=all -- "${HOME:?}/.gradle/caches/build-cache-1" "${HOME:?}/.gradle/.tmp"
fi
df -h /tmp "$workspace"
du -xsh /tmp "${HOME:?}/.gradle" "${HOME:?}/.cargo" "${HOME:?}/.m2" "$(dirname "$workspace")" 2>/dev/null | sort -h
exit 0
+134 -87
View File
@@ -1,121 +1,168 @@
{
"archive_sha256": "cb6487a94f25a3068fd07958174eb5b5e14f709655ff4ef0a8cdbd99138513b2",
"arm64_recipe": "1c92a1b0669277de3e78e9f292634affb5b5a19d5ea49d3ad8610c1dc638c2fb",
"archive_sha256": "2d1f53c795615e7066a47ad26c791397d830bb8b028e9c89f9f809eaeebd3fae",
"arm64_recipe": "d89e4bbf9533840a44d77c52a392cdce242822b1e80293ea4de26d2f06a09698",
"groups": {
"arm64": {
"@runner": "84f825635599f81ed33f62c5fc4c73f66044d1468b060d65f83855eb9c8bfe77",
"@runner": "37a91043149e9747985b419002d87ff4df41ec6def4169e0ef16711d7261dbf2",
"app/src/main/cpp/adrenotools/src/hook/kgsl.h": "396c56761034a4ed783543ee3312c6ec64d63b2a1cf7eecf1939c23251f25adf",
"app/src/main/cpp/fakeinput_steam.cpp": "3d11e859ca58a42a9da92a3fc589d404df790e151f7e18ea6114645750e70ef5",
"app/src/main/cpp/venc/venc_proto.h": "2242ddbc8981d14a33bac70264bb3e7f701fd1c3ebb988e17bbb2b19b6b808f7",
"app/src/main/cpp/fakeinput_steam.cpp": "e1377f9d7cd8539a9a327e2851b04c8e05e931f8b5ee554fa4f36d4b17f96718",
"app/src/main/cpp/venc/venc_proto.h": "57636af2644b36ea101cd09de42c423e864a612160561239ceda77ce888d5370",
"tools/linuxfs/clipboard/clipboard.c": "96291c2bbc040c83caabf059ab3e95a9ed90d6a768c759d7cb4c0b64706bddfa",
"tools/linuxfs/preload/binfmt.c": "0933cc49cb53f0aa1206e2eae516d38dc3337e74174be07e10619c42aa56792b",
"tools/linuxfs/preload/dircache.c": "8e7f19ea4a1198783d53a3f357326c6177da157b0cc7e0d22e1670963e1c26e7",
"tools/linuxfs/preload/drm.c": "e0eabab0d8ed9e841918e827bf87168efa7f2dfb8404169e9bed3ab5eda2836c",
"tools/linuxfs/preload/fsync.c": "795c114c2a05d3f250d07145d04c5658091699da3b96290da36348ccadfb0c09",
"tools/linuxfs/preload/inputudev.c": "2648248d3d235a582eb8459709e0a85de537c03ac10c5040fbfb50d9846c68eb",
"tools/linuxfs/preload/kgslid.c": "88a7875fd5289930204d155d92ac9d15492cd06db16ed87aa9c95af37f3e7089",
"tools/linuxfs/preload/kgslpoll.c": "f0d853d919a52487c04cbda5fb3fa22269da54b7f4ee2f7dd3b5bd9909418670",
"tools/linuxfs/preload/links.c": "b7bbcf9112393b152f358fe6f8dc9a1955f0c8532e1eddf016a971415cd13c64",
"tools/linuxfs/preload/lock.c": "f71b3fd40e6a2b74908d3cdc601e8748699ae9c7a89b542d2445b999015ffd66",
"tools/linuxfs/preload/net.c": "335853c8ea0e9a8ebbc5a5500dc4bded9c34c4310a6ab8aa46b07d5ce1c2b55e",
"tools/linuxfs/preload/netif.c": "cc26d50b8d4639d8dd4697811bbf85c9d9f31761f9504a4af42473de3cb22b3c",
"tools/linuxfs/preload/noexec.c": "1855aeaeda3d506329bd9af1107580c74d1f56787c411b2e01c0a8a9d4059c7b",
"tools/linuxfs/preload/ntsync.c": "0614c48af0c062bfcb4c30141efe1b792b340767a67d2fe92ee9877d2ba16e0d",
"tools/linuxfs/preload/opens.c": "92ae4aea16aa457a898dedf4a70eb332d80d3b1e77f3a60bace7715a4317399e",
"tools/linuxfs/preload/pathcache.c": "eb0d4b5238fe6c8891e805d90bd837e466754100c978fad2d0ff717116b9b8a3",
"tools/linuxfs/preload/perms.c": "f600619c4ca130f69001ed7ad7bd74a3dc215b14c61479c45bb770f916d244b9",
"tools/linuxfs/preload/pulseguard.c": "57674ea40283e53a27bc78362de1ba41ee972d172ea38b1f818b1d6eed0abe65",
"tools/linuxfs/preload/binfmt.c": "45e820cdd75f2bd42710d98a4d5fee7398b667c9793ee94d8b8b7c4f29f4380c",
"tools/linuxfs/preload/clockpause.c": "5c8cbe1303e3b5fce97b000a952ab15691c0b56dc874e4a963f0e7888ce3f2c7",
"tools/linuxfs/preload/descriptor.c": "673b1cd0a5cd287a572e67aa60c2c36d1bc90ccac4f73ad0a783d4d2e2e5df07",
"tools/linuxfs/preload/dircache.c": "09d3dee98e49ef85b8e8112acb6a2b3d8b980eac80f07b3c82785e567f0606a6",
"tools/linuxfs/preload/drm.c": "9c9b9deab902276ee23a08a98730b2c6adbf7ea6d61e1e73d2a2e7c7016b1335",
"tools/linuxfs/preload/fsync.c": "f2f5fd3197d536d9396dd3d69837f6a2b0b4ff9aaffdb6f55b200408aaf5793d",
"tools/linuxfs/preload/inputudev.c": "76d7f720cd9531d8d38c2977956bf764b0db6055cb56aa35493476a244d9a22e",
"tools/linuxfs/preload/kgslid.c": "1a9639606ece49c5aff74baa5b9ef0921ec5dbc321d19d3f59184e4456f324a4",
"tools/linuxfs/preload/kgslpoll.c": "d03c09e0c82f76716dcc1f3ca77e718c60929bedf221ea5dae8ab43f5ab3e3f3",
"tools/linuxfs/preload/links.c": "c5761d450e070de912fbc9c71562d3fbf54775b484ea0fa57ded2e0c0771f7cf",
"tools/linuxfs/preload/lock.c": "1fcfefe28ef49ccd73f13b69ceb576492101cd1ddb88f08e0c73646ddeb327f2",
"tools/linuxfs/preload/net.c": "0645013df15656573d484bf6f8e6d8657beb228c779ae1143c0874e12559bf3e",
"tools/linuxfs/preload/netif.c": "cf6568ce8ffea44f24a8443160d86e4efddcdb964c908532935cbc4c4570ca91",
"tools/linuxfs/preload/noexec.c": "12f5245a893f9044558270cb03cfb7020546bfe3e90a9264b33d3f818dd30433",
"tools/linuxfs/preload/ntsync.c": "acffede0324fc89ac91f8181c2df23e6f39459a4db678a44ce9e65e0f282418c",
"tools/linuxfs/preload/oomadj.c": "d84d552a24ec3467e7ba5cf92a384521dfbcf1fc9a97e899b7b18d20bf1b45d5",
"tools/linuxfs/preload/opens.c": "2ba8f056ae0f2ab87a3d58ca0926b09af67deb1e24048506117bc26601e249c6",
"tools/linuxfs/preload/owner.c": "746d0a1834d0e19f7d9adfad72a6080a1104610f98c1d61e14d2c3a91a9eb04d",
"tools/linuxfs/preload/pathcache.c": "7d8287736f8f1988738d233c002ff6e00127c98034fcd35c2bb63a84c04b85a3",
"tools/linuxfs/preload/perms.c": "5ffa0ce5ff8269fc567dc5581bec380dcf2c90b9fb178c8dbae747e61430608f",
"tools/linuxfs/preload/pulseguard.c": "a91a0d5c745ea32ad52d57010a8b3cf7171bc4a3d2f73b870c64a6a62b233b56",
"tools/linuxfs/preload/quest_kgsl.c": "59d9b8416be6a1c680f1d1e4c2427d2cbb7b415344261adb357d9d211ec95cfe",
"tools/linuxfs/preload/robust.c": "9eb6c0ed50e0f48a8cfb86bd92587f471354bdf2531b9177f4b3ab83bdfed39a",
"tools/linuxfs/preload/rptouch.c": "0e3f8bf2f9a41324361f38fa4da8d2d47593c9555f0cabf8228767397846c7c3",
"tools/linuxfs/preload/space.c": "118389bcc89dfa2b4230b80915e21d2d4331c4cff1f5a58265f85e6ecb5c29d2",
"tools/linuxfs/preload/storage.c": "08a8b46c3588f3160bb8608489768010ec36d5ccdb2b25a431ec9d6fcd413a6e",
"tools/linuxfs/preload/sysv.c": "49774ee5e2e39b84dcfadf63abdc741b3df236cb11783744a1280adee36965e8",
"tools/linuxfs/preload/robust.c": "02cd25316912c79897e2c5a1ed44b059b815d36bc62ba8d4691f718eeae92947",
"tools/linuxfs/preload/rptouch.c": "fc6db7e4b9432a7361e805a9a2dd134f9f3ec4ffba7927ab4b2c7b6bd2a22644",
"tools/linuxfs/preload/space.c": "9258ec8a8f8d87f2629b753d1838a09000110d936103284a04134b8cbed024d3",
"tools/linuxfs/preload/storage.c": "5c0dc4e5901e8cc32cdf241e38e3d5dcd3dae8b8ca94579f633754c8eadd617b",
"tools/linuxfs/preload/subreaper.c": "6f3830c0368a768bd0d367fa94345e6e4725875acc9662cf3690f1c5f28bf71c",
"tools/linuxfs/preload/sysv.c": "893dfad1db964eb1f79af94978b4af8b87279b85c30a4d589b5844cded476ed3",
"tools/linuxfs/preload/tracefs.c": "be3f8a2f032b56e6e08a931e77a9386aea4bb93421a482271e06386ec0c469b6",
"tools/linuxfs/preload/tracer.c": "f34e5377c891b0a8d00489245d66f96bc352df4cd90f47a951dcadae980af4c1",
"tools/linuxfs/preload/udevmon.c": "2045dfb883cfb6e2016c359a3dc3af17f3b8f383f6dd0d5dfee407ef0d344852",
"tools/linuxfs/preload/usr2.c": "6ae704380b45a9b3a74c4fe2b3ce4482470dae59ced26cf0aee64f4b4dcc11f9",
"tools/linuxfs/preload/venc.c": "24c3c46fe49d28adfc8c977e52c9cc407f534b26f56d94b3425b8bb01803dba8",
"tools/linuxfs/preload/tracer.c": "4b5481ea91a475bb6ac16a7ba63e371f0a850a17adac5399302a610c0a57ec0a",
"tools/linuxfs/preload/udevmon.c": "4d5f07f2521af702b3f2adda3c93a39873f87c0946de007bca8b1fe6699596fa",
"tools/linuxfs/preload/usr2.c": "4b4044da1ddf07d12bafeb893c257679e26a5ea2f58e6cc0d715f27b931e7b1e",
"tools/linuxfs/preload/vdec.c": "a7b2d0754067493cde1929846f7b2c9692c4dde96ee273a92c81ac65470fac50",
"tools/linuxfs/preload/venc.c": "7fda60f013736d98dab734a9344e0f1d527dc3d976a71f5ccd4a0bc17d9f346f",
"tools/linuxfs/preload/venus.c": "d4af5c3532d4c7d9891b75cd5a137252e791beafe319b9fd976be123f7b80403",
"tools/linuxfs/preload/vmwrite.c": "1a3ea2ec4354e0716c17f7db537b19ab82bcd524f2aece2fa5dec89b076a2188",
"tools/linuxfs/preload/webhelper.c": "a8213a7a96b407459c83fb93365cfe58fd05964e7bb262b8061c1c0792a6aac8",
"tools/linuxfs/preload/writewatch.c": "61e395d1caa184d329dead0e36c4e92cb1069b1154ac36581f37406c1c242240",
"tools/linuxfs/preload/xmode.c": "9a09995bf52d40b07f16828bcc545b59b8fb1ba60d9cb09f14f7f31dba1e65a6",
"tools/linuxfs/preload/zram.c": "12bcf07459728d4a7ede6fa0fea8deb330f7c5d0f0dd61e610e81b9efecd4262",
"tools/linuxfs/preload/webhelper.c": "bec759f908fb7c52238a7b72d3888aac6187aaec2378c190749ab8a5f7f1d81a",
"tools/linuxfs/preload/writewatch.c": "285ed7e627dc9349dd3ae45e8c1ffeaf4c56970b9eac5046754e348b4587dd6b",
"tools/linuxfs/preload/xmode.c": "3b6e36b29795544fdc0299822049b1890a7612578051d2a8982485c263dcf259",
"tools/linuxfs/preload/zram.c": "60b8c9fbd96adcc2026e48c651948d592f06017ff679e4775b1752be26525a2e",
"tools/linuxfs/ssbs/ssbs_adapter.c": "9e4e0fe637f7b8f91f12d8151f02e8d31bcb4294be2b2c62d3cd3ce76f200306",
"tools/nativeguest/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
"tools/nativeguest/app-seccomp-dump.c": "b5bfb92de5d64fa286b5a1cf3f4f71687817fc093cf698c65ffb2a5c575ce809",
"tools/nativeguest/build-gosys.sh": "34877be3fdbf7cf74f1dc19fbe708d428b135e65caf92a8ad0cbc7772ad699c7",
"tools/nativeguest/build.sh": "5aad4e82e293a2b47f461434dd6b024360d3b4356dadabc28b2fcc08220103be",
"tools/nativeguest/ddnatv-hook.c": "65451173bedbc332668f25b6589ca54d0a4c2d7edfaeb48f69ce00632b5d968b",
"tools/nativeguest/gosys/gosys.c": "a7808741af5fcaede7260f743b482612a7b2a818e207514bab667d06ca82f4d4",
"tools/nativeguest/gosys/gosys.ld": "dd4de106e3f9429a9373f8ed512537ed5b4927efc368ce3b8364776be435fb80",
"tools/nativeguest/gosys/gosys_abi.h": "8c246268e0645a7148bc2ad9f0c1d6147e0a3bc0c7625956be9afc018c58ada0",
"tools/nativeguest/hook/env.c": "ed84ca5c1f9704eba140263123f0b1876d1e2daee7b92d444f06edab3246f327",
"tools/nativeguest/hook/exec.c": "69111bf9a9ebaf56f59825c99fa16078f53ba708e8816e2c9bd02aff909149f5",
"tools/nativeguest/hook/exec_probe.c": "539ba604469d0a7fcc1677709bc56386ac92de4ba07fe80fda10f4cd85bf6d1a",
"tools/nativeguest/hook/fileops.c": "10bde17100bc2d7ed44f8921b16472309bb108b6f77371aaa3036d0737867706",
"tools/nativeguest/hook/files.c": "be6affd0bdf55e4759b5ba5edbbd280b47bae74013d790c0132474e8aca9abeb",
"tools/nativeguest/hook/go_programs.c": "418340c66a1d9fd5b492fff8b22d929ca3b4ef672ba73968c0d0ca5a4e9f3937",
"tools/nativeguest/hook/hardlinks.c": "eae44472aaefb9c24854610acfe16b221081a8bdc39bc63f8c957292ddced6ed",
"tools/nativeguest/hook/identity.c": "89f1632f00b141c568e8dbc0226039d3f6d9bd0752ff337e343cac2cb3a60705",
"tools/nativeguest/hook/net.c": "ec62f2bf9bb1eb15b7947d577a6cdde67dcce21bdaf217fd74c00ceb78e4f471",
"tools/nativeguest/hook/paths.c": "7d3098f944c6c13621eb4295df3ecb06350fc61381e4b92070764d66d8c85354",
"tools/nativeguest/hook/posix_shm.c": "0bb3782c538723051d51d147d35a9f5b37872b2a6ffa49d3059264539533d0f7",
"tools/nativeguest/hook/privileged.c": "d1acc6faca83f9b7a1a4d5a07fe19d73d139f8f9f3ec6215347c6ec7088f1819",
"tools/nativeguest/hook/setup.c": "2a3baa4ecc9fe39ff96e920a5e49e8b94fe432c63cc3fecd8badf40003a67ffc",
"tools/nativeguest/hook/signals.c": "b9e3646c3376150d64afff81a1e3f40a7ef5662de6b2b01d15f1bb8f2c5ecdf9",
"tools/nativeguest/hook/sockets.c": "6e221ca047351e67b2a0a4611d9782b60f7f309309b83a46406cf371becc2f40",
"tools/nativeguest/hook/static_programs.c": "f53db68d18240d1bbf92cf7ecabfb207861bbf563785516be3325bc9c511e629",
"tools/nativeguest/hook/syscalls.c": "1e6e7e44e2a49ac768aaf55661748a4ce703c06bab6dbe1ce25c5de80f416053",
"tools/nativeguest/hook/sysv_shm.c": "1ef54c48aa25d827494502c913423612f270767a6343435fbc5868ad927b5ed1",
"tools/nativeguest/seccomp-sim.c": "261d8ef8364f05a45acc43767eab22057357f056558b69835a0198d5bae3d9b8",
"tools/proot/fastpath/audit.c": "bfe347a2ddaceef40a78d7d590e4e679724ee4c82f3f1f1e3c7017a18ad536d4",
"tools/proot/fastpath/fastpath.c": "4cd07b25ba14f6faa6bac5091ae323ded6b646dbb34b9e5a92ea6385e4d37cb5",
"tools/quest/kgsl_compat.c": "111afffda7a6df2469610f6c342ae086b1a97a559c586efc4a28015b86efd6bd",
"tools/proot/fastpath/fastpath.c": "8fe165886b0462b912507636592462599f4657b4c2c56723968b8f95981dd05e",
"tools/proot/fastpath/svc-cache.h": "bf0b4669ff3d5b72354cc0fdb62d1c2637b545db2096d782a1f713ae9cfbdc89",
"tools/proot/fastpath/svc-dispatch.h": "18dbd595a181ac9d7c0e2eb9ef4321cd9e3ea24e7506beac71cd9e9923d327e5",
"tools/proot/fastpath/svc-patch.h": "9c1d05485a4f79e71b4a49e73e6d2fa37473de20db93acdc7fbfe04c6156fb96",
"tools/proot/fastpath/svc-publish.h": "1c4491e8b22d15319619c1d61707f614fa2b152afd5d02ad197c3da9a2f26e62",
"tools/proot/fastpath/svc-stack.h": "2545db824775ea4673e0272cf7c16f64c87e92db4853f6874cf2c3451cba474b",
"tools/quest/kgsl_compat.c": "92cf5b3da0b3704c20d9e1307bb5abc0530717b9a2e2fd7c8db876a85dc333a1",
"tools/quest/kgsl_compat.h": "2e9e0eb647530a35277954b7e61a22ee958067fe46056a608fb32f40f273f1bf"
},
"x86": {
"@runner": "84f825635599f81ed33f62c5fc4c73f66044d1468b060d65f83855eb9c8bfe77",
"@runner": "37a91043149e9747985b419002d87ff4df41ec6def4169e0ef16711d7261dbf2",
"app/src/main/cpp/adrenotools/src/hook/kgsl.h": "396c56761034a4ed783543ee3312c6ec64d63b2a1cf7eecf1939c23251f25adf",
"app/src/main/cpp/fakeinput_steam.cpp": "3d11e859ca58a42a9da92a3fc589d404df790e151f7e18ea6114645750e70ef5",
"app/src/main/cpp/venc/venc_proto.h": "2242ddbc8981d14a33bac70264bb3e7f701fd1c3ebb988e17bbb2b19b6b808f7",
"tools/linuxfs/build-x86-preloads.sh": "d0820252809881db89db5a17427e74b9aa4964aae70623cb7f4b474e90c7a23b",
"app/src/main/cpp/fakeinput_steam.cpp": "e1377f9d7cd8539a9a327e2851b04c8e05e931f8b5ee554fa4f36d4b17f96718",
"app/src/main/cpp/venc/venc_proto.h": "57636af2644b36ea101cd09de42c423e864a612160561239ceda77ce888d5370",
"tools/linuxfs/build-x86-preloads.sh": "cf283b41c9a39b61bb628035a405cc8d33bd8085056ea482f80253a3ddd6ab8b",
"tools/linuxfs/debian-image.env": "1c79dea4314c784042a5c59208765c8401771098f293185d61a157d89edf6e52",
"tools/linuxfs/fex/faultreport.c": "573bf780f32f7256dc2fbf40fe850d67e67c354509fdedcac3ff7f1a261daac3",
"tools/linuxfs/fex/vulkanpin.c": "f2693ac2be8d15f7881115e61b1c6b3fe4aeec8f603584c6fce5b0f046563d51",
"tools/linuxfs/fex/webkitinput.c": "693ffd6c8c8c97e87156444ad2255c84dbf22cd0053d135fb8d9be094b5534d1",
"tools/linuxfs/preload/binfmt.c": "0933cc49cb53f0aa1206e2eae516d38dc3337e74174be07e10619c42aa56792b",
"tools/linuxfs/preload/dircache.c": "8e7f19ea4a1198783d53a3f357326c6177da157b0cc7e0d22e1670963e1c26e7",
"tools/linuxfs/preload/drm.c": "e0eabab0d8ed9e841918e827bf87168efa7f2dfb8404169e9bed3ab5eda2836c",
"tools/linuxfs/preload/fsync.c": "795c114c2a05d3f250d07145d04c5658091699da3b96290da36348ccadfb0c09",
"tools/linuxfs/preload/inputudev.c": "2648248d3d235a582eb8459709e0a85de537c03ac10c5040fbfb50d9846c68eb",
"tools/linuxfs/preload/kgslid.c": "88a7875fd5289930204d155d92ac9d15492cd06db16ed87aa9c95af37f3e7089",
"tools/linuxfs/preload/kgslpoll.c": "f0d853d919a52487c04cbda5fb3fa22269da54b7f4ee2f7dd3b5bd9909418670",
"tools/linuxfs/preload/links.c": "b7bbcf9112393b152f358fe6f8dc9a1955f0c8532e1eddf016a971415cd13c64",
"tools/linuxfs/preload/lock.c": "f71b3fd40e6a2b74908d3cdc601e8748699ae9c7a89b542d2445b999015ffd66",
"tools/linuxfs/preload/net.c": "335853c8ea0e9a8ebbc5a5500dc4bded9c34c4310a6ab8aa46b07d5ce1c2b55e",
"tools/linuxfs/preload/netif.c": "cc26d50b8d4639d8dd4697811bbf85c9d9f31761f9504a4af42473de3cb22b3c",
"tools/linuxfs/preload/noexec.c": "1855aeaeda3d506329bd9af1107580c74d1f56787c411b2e01c0a8a9d4059c7b",
"tools/linuxfs/preload/ntsync.c": "0614c48af0c062bfcb4c30141efe1b792b340767a67d2fe92ee9877d2ba16e0d",
"tools/linuxfs/preload/opens.c": "92ae4aea16aa457a898dedf4a70eb332d80d3b1e77f3a60bace7715a4317399e",
"tools/linuxfs/preload/pathcache.c": "eb0d4b5238fe6c8891e805d90bd837e466754100c978fad2d0ff717116b9b8a3",
"tools/linuxfs/preload/perms.c": "f600619c4ca130f69001ed7ad7bd74a3dc215b14c61479c45bb770f916d244b9",
"tools/linuxfs/preload/pulseguard.c": "57674ea40283e53a27bc78362de1ba41ee972d172ea38b1f818b1d6eed0abe65",
"tools/linuxfs/fex/vulkanpin.c": "c530e265486fd106705fac906848871c9bce6acef2718a9c2d5dbb5bd7650227",
"tools/linuxfs/fex/webkitinput.c": "5356a003aa30686218f403ad4ea67f792ac84dc434f289032292f234908d5c48",
"tools/linuxfs/preload/binfmt.c": "45e820cdd75f2bd42710d98a4d5fee7398b667c9793ee94d8b8b7c4f29f4380c",
"tools/linuxfs/preload/clockpause.c": "5c8cbe1303e3b5fce97b000a952ab15691c0b56dc874e4a963f0e7888ce3f2c7",
"tools/linuxfs/preload/descriptor.c": "673b1cd0a5cd287a572e67aa60c2c36d1bc90ccac4f73ad0a783d4d2e2e5df07",
"tools/linuxfs/preload/dircache.c": "09d3dee98e49ef85b8e8112acb6a2b3d8b980eac80f07b3c82785e567f0606a6",
"tools/linuxfs/preload/drm.c": "9c9b9deab902276ee23a08a98730b2c6adbf7ea6d61e1e73d2a2e7c7016b1335",
"tools/linuxfs/preload/fsync.c": "f2f5fd3197d536d9396dd3d69837f6a2b0b4ff9aaffdb6f55b200408aaf5793d",
"tools/linuxfs/preload/inputudev.c": "76d7f720cd9531d8d38c2977956bf764b0db6055cb56aa35493476a244d9a22e",
"tools/linuxfs/preload/kgslid.c": "1a9639606ece49c5aff74baa5b9ef0921ec5dbc321d19d3f59184e4456f324a4",
"tools/linuxfs/preload/kgslpoll.c": "d03c09e0c82f76716dcc1f3ca77e718c60929bedf221ea5dae8ab43f5ab3e3f3",
"tools/linuxfs/preload/links.c": "c5761d450e070de912fbc9c71562d3fbf54775b484ea0fa57ded2e0c0771f7cf",
"tools/linuxfs/preload/lock.c": "1fcfefe28ef49ccd73f13b69ceb576492101cd1ddb88f08e0c73646ddeb327f2",
"tools/linuxfs/preload/net.c": "0645013df15656573d484bf6f8e6d8657beb228c779ae1143c0874e12559bf3e",
"tools/linuxfs/preload/netif.c": "cf6568ce8ffea44f24a8443160d86e4efddcdb964c908532935cbc4c4570ca91",
"tools/linuxfs/preload/noexec.c": "12f5245a893f9044558270cb03cfb7020546bfe3e90a9264b33d3f818dd30433",
"tools/linuxfs/preload/ntsync.c": "acffede0324fc89ac91f8181c2df23e6f39459a4db678a44ce9e65e0f282418c",
"tools/linuxfs/preload/oomadj.c": "d84d552a24ec3467e7ba5cf92a384521dfbcf1fc9a97e899b7b18d20bf1b45d5",
"tools/linuxfs/preload/opens.c": "2ba8f056ae0f2ab87a3d58ca0926b09af67deb1e24048506117bc26601e249c6",
"tools/linuxfs/preload/owner.c": "746d0a1834d0e19f7d9adfad72a6080a1104610f98c1d61e14d2c3a91a9eb04d",
"tools/linuxfs/preload/pathcache.c": "7d8287736f8f1988738d233c002ff6e00127c98034fcd35c2bb63a84c04b85a3",
"tools/linuxfs/preload/perms.c": "5ffa0ce5ff8269fc567dc5581bec380dcf2c90b9fb178c8dbae747e61430608f",
"tools/linuxfs/preload/pulseguard.c": "a91a0d5c745ea32ad52d57010a8b3cf7171bc4a3d2f73b870c64a6a62b233b56",
"tools/linuxfs/preload/quest_kgsl.c": "59d9b8416be6a1c680f1d1e4c2427d2cbb7b415344261adb357d9d211ec95cfe",
"tools/linuxfs/preload/robust.c": "9eb6c0ed50e0f48a8cfb86bd92587f471354bdf2531b9177f4b3ab83bdfed39a",
"tools/linuxfs/preload/rptouch.c": "0e3f8bf2f9a41324361f38fa4da8d2d47593c9555f0cabf8228767397846c7c3",
"tools/linuxfs/preload/space.c": "118389bcc89dfa2b4230b80915e21d2d4331c4cff1f5a58265f85e6ecb5c29d2",
"tools/linuxfs/preload/storage.c": "08a8b46c3588f3160bb8608489768010ec36d5ccdb2b25a431ec9d6fcd413a6e",
"tools/linuxfs/preload/sysv.c": "49774ee5e2e39b84dcfadf63abdc741b3df236cb11783744a1280adee36965e8",
"tools/linuxfs/preload/robust.c": "02cd25316912c79897e2c5a1ed44b059b815d36bc62ba8d4691f718eeae92947",
"tools/linuxfs/preload/rptouch.c": "fc6db7e4b9432a7361e805a9a2dd134f9f3ec4ffba7927ab4b2c7b6bd2a22644",
"tools/linuxfs/preload/space.c": "9258ec8a8f8d87f2629b753d1838a09000110d936103284a04134b8cbed024d3",
"tools/linuxfs/preload/storage.c": "5c0dc4e5901e8cc32cdf241e38e3d5dcd3dae8b8ca94579f633754c8eadd617b",
"tools/linuxfs/preload/subreaper.c": "6f3830c0368a768bd0d367fa94345e6e4725875acc9662cf3690f1c5f28bf71c",
"tools/linuxfs/preload/sysv.c": "893dfad1db964eb1f79af94978b4af8b87279b85c30a4d589b5844cded476ed3",
"tools/linuxfs/preload/tracefs.c": "be3f8a2f032b56e6e08a931e77a9386aea4bb93421a482271e06386ec0c469b6",
"tools/linuxfs/preload/tracer.c": "f34e5377c891b0a8d00489245d66f96bc352df4cd90f47a951dcadae980af4c1",
"tools/linuxfs/preload/udevmon.c": "2045dfb883cfb6e2016c359a3dc3af17f3b8f383f6dd0d5dfee407ef0d344852",
"tools/linuxfs/preload/usr2.c": "6ae704380b45a9b3a74c4fe2b3ce4482470dae59ced26cf0aee64f4b4dcc11f9",
"tools/linuxfs/preload/venc.c": "24c3c46fe49d28adfc8c977e52c9cc407f534b26f56d94b3425b8bb01803dba8",
"tools/linuxfs/preload/tracer.c": "4b5481ea91a475bb6ac16a7ba63e371f0a850a17adac5399302a610c0a57ec0a",
"tools/linuxfs/preload/udevmon.c": "4d5f07f2521af702b3f2adda3c93a39873f87c0946de007bca8b1fe6699596fa",
"tools/linuxfs/preload/usr2.c": "4b4044da1ddf07d12bafeb893c257679e26a5ea2f58e6cc0d715f27b931e7b1e",
"tools/linuxfs/preload/vdec.c": "a7b2d0754067493cde1929846f7b2c9692c4dde96ee273a92c81ac65470fac50",
"tools/linuxfs/preload/venc.c": "7fda60f013736d98dab734a9344e0f1d527dc3d976a71f5ccd4a0bc17d9f346f",
"tools/linuxfs/preload/venus.c": "d4af5c3532d4c7d9891b75cd5a137252e791beafe319b9fd976be123f7b80403",
"tools/linuxfs/preload/vmwrite.c": "1a3ea2ec4354e0716c17f7db537b19ab82bcd524f2aece2fa5dec89b076a2188",
"tools/linuxfs/preload/webhelper.c": "a8213a7a96b407459c83fb93365cfe58fd05964e7bb262b8061c1c0792a6aac8",
"tools/linuxfs/preload/writewatch.c": "61e395d1caa184d329dead0e36c4e92cb1069b1154ac36581f37406c1c242240",
"tools/linuxfs/preload/xmode.c": "9a09995bf52d40b07f16828bcc545b59b8fb1ba60d9cb09f14f7f31dba1e65a6",
"tools/linuxfs/preload/zram.c": "12bcf07459728d4a7ede6fa0fea8deb330f7c5d0f0dd61e610e81b9efecd4262",
"tools/quest/kgsl_compat.c": "111afffda7a6df2469610f6c342ae086b1a97a559c586efc4a28015b86efd6bd",
"tools/linuxfs/preload/webhelper.c": "bec759f908fb7c52238a7b72d3888aac6187aaec2378c190749ab8a5f7f1d81a",
"tools/linuxfs/preload/writewatch.c": "285ed7e627dc9349dd3ae45e8c1ffeaf4c56970b9eac5046754e348b4587dd6b",
"tools/linuxfs/preload/xmode.c": "3b6e36b29795544fdc0299822049b1890a7612578051d2a8982485c263dcf259",
"tools/linuxfs/preload/zram.c": "60b8c9fbd96adcc2026e48c651948d592f06017ff679e4775b1752be26525a2e",
"tools/quest/kgsl_compat.c": "92cf5b3da0b3704c20d9e1307bb5abc0530717b9a2e2fd7c8db876a85dc333a1",
"tools/quest/kgsl_compat.h": "2e9e0eb647530a35277954b7e61a22ee958067fe46056a608fb32f40f273f1bf"
}
},
"origin": {
"artifact": 12520502054,
"artifact_sha256": "b7e800a1884a516ec52b050b7f904f9881427bca4579f660b909fd18f15e49ff",
"commit": "b76f13f7acc0af0cc00369dde61fb88e40529e6d",
"run": 39992155294,
"url": "https://github.com/Droid-Deck/DroidDeck/actions/runs/39992155294"
"artifact": 14400591108,
"artifact_sha256": "974023be39cb1b7a168efb38369d1adfe2a51f0e1d7b9b535b50c8692a24f870",
"commit": "c8b291b9dbdeae137236a56ad66f08b1f3370a8a",
"run": 44240744255,
"url": "https://github.com/Droid-Deck/DroidDeck/actions/runs/44240744255"
},
"outputs": {
"i386/libddsession.so": "5343cdb704217ddc81ee593e67d5987363dc7b5ac78bd4bd36000219e5063268",
"i386/libfakeinput.so": "188d88dfb13b6e2f2df948e7b8b4d9ec604770f55d1ea5b6b9e21ad56a74ce5e",
"i386/libddsession.so": "da5562f924faf98144b569ee3ed113be7dcee59deef24abc84be56fd4ba9ccd3",
"i386/libfakeinput.so": "99f6328a3a380672680969a54cd2e9996edf25c287fa5a00e2db54264da8d898",
"i386/libfaultreport.so": "95f9ef60f04a13ee60cfbd4d2d2efb60a7063b722e646c78c9dc27162292877b",
"libddaudit.so": "6c6abe89baf5d7309babee0c3372a4b00c2b689e2a63de38c5e9a660626509b5",
"libddfastpath.so": "0e1f151b5c1c5ea9dd380ad58d09f8fe7ba3ae037d0991cb3eef6899e9d5ec83",
"libddsession.so": "29d4b5ea46dba941107e02c0ee544244b137a339cada43bff65c350f2ef2755a",
"libfakeinput.so": "5f6dc3aea05de2dc1fbe0bbfac2ce4d11e3d47f761c6b06c8badb15fe1904392",
"libddfastpath.so": "9cdf153a8f9d4e150123dd5bac8ff678a0b84c1318e036c1d928b542821103b6",
"libddnatv-hook.so": "8ed3de674273734ae239408a315ab7813e1e5bb606ed126b9e45eec0e84fe399",
"libddsession.so": "da6c3a919bd6f48f5abfdab383c45be71fb20b684c6defec4fbbbb450b8e2d59",
"libfakeinput.so": "46b671065c0a811fc10d46dcf8dc4b58fce110079c8d919d2e1072c3b02eca02",
"libssbs.so": "c288ed0da26c2481aff270d1cdafe1205061c4a300c2c46ae1b53c6e0c94f44b",
"usr/local/bin/droiddeck-clipboard": "ec50e8f67fdf76372927189b0fdb670f9b70fd3484f2fe3e833bc8f9fdc44205",
"x86_64/libddsession.so": "61d19f06aebab6a789f8c99f687af9903376bfc853e46b70c48a2ce5e497accc",
"x86_64/libfakeinput.so": "8663dd2086bf8ae53069a480dd9ae4619109d32f0947a29e2ce38f07a21ae2e6",
"x86_64/libddsession.so": "1438bc246fb0fec985ef71fccbe4acdc067b1ae4b97befdc8f01fdd79c99b151",
"x86_64/libfakeinput.so": "74ef688919a0f757d2c022b7a18d64e7c4819301e79e0aa8572d8e0ef8318e49",
"x86_64/libfaultreport.so": "bb0dc9165d0d764473e552508650edd586df16d620fc5b16b8b1c5740a28ce22",
"x86_64/libvulkan-thunk.so": "74f01b652d7e8179561a096a552328b68da640cc4bad3981edd38e6afbf90243",
"x86_64/libwebkitinput.so": "9b07380a7b017397b9c56bb7bb1161e046b0c6a647fc413888904606b0def6d0"
"x86_64/libwebkitinput.so": "d0ba6886642595132d1ec9abb8d9f4cc7e1bc4c750b4a5d53d2f089334a6b4e3"
},
"toolchain": {
"arm64": "Ubuntu 24.04 GCC cross compiler; exact build commands pinned by arm64_recipe",
+7 -4
View File
@@ -23,12 +23,12 @@
"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/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so"
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
],
"ndk": true,
"packages": [
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross",
"g++-aarch64-linux-gnu",
"libvulkan1",
"mesa-vulkan-drivers"
@@ -155,7 +155,8 @@
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet/version"
],
"packages": [
"gcc-aarch64-linux-gnu"
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross"
]
},
"arm64-preloads": {
@@ -178,6 +179,7 @@
],
"packages": [
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross",
"g++-aarch64-linux-gnu"
],
"source_inputs": [
@@ -245,7 +247,8 @@
"app/src/main/assets/linuxfs/usr/local/bin/droiddeck-vkbridge-smoke"
],
"packages": [
"gcc-aarch64-linux-gnu"
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross"
]
},
"dirt-ws2": {
+150
View File
@@ -0,0 +1,150 @@
"""Install the components a main CI run prepared when they match this tree.
The run's prepared-components archive is used only when every recipe identity it records equals
the identity of the local tree, the inputs CI builds outside the recipes are unchanged from the
run's source tree, and no recipe submodule has local edits. Files are verified in a staging
directory before any local output is replaced.
"""
import argparse
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import subprocess
import sys
import tarfile
import tempfile
sys.path.insert(0, str(Path(__file__).resolve().parent))
import prepare # noqa: E402
# CI records identities under its runner labels and pinned NDK, not this host's.
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
# The components job builds these outside the recipe registry.
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu',
'tools/venus/glprobe.c', 'tools/quest']
def ci_environment(architecture, root):
ndk = next(line.split('=', 1)[1].strip()
for line in (root / 'tools/ci/toolchains.env').read_text().splitlines()
if line.startswith('CI_ANDROID_NDK_VERSION='))
return dict(RUNNER_OS='Linux', RUNNER_ARCH=architecture, NDK_VERSION=ndk)
@contextmanager
def environ(values):
saved = {key: os.environ.get(key) for key in values}
os.environ.update(values)
try:
yield
finally:
for key, value in saved.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def identities(environment, root):
with environ(environment):
return {name: prepare.identity(name, root) for name in prepare.registry(root)}
def git(root, *args):
return subprocess.run(['git', *args], cwd=root, capture_output=True, text=True)
def unregistered_changes(source_tree, root):
if git(root, 'cat-file', '-e', source_tree + '^{tree}').returncode:
return ['source tree ' + source_tree + ' (fetch origin main)']
changed = git(root, 'diff', '--name-only', source_tree, '--', *UNREGISTERED_INPUTS).stdout.split()
changed += git(root, 'ls-files', '--others', '--exclude-standard', '--', *UNREGISTERED_INPUTS).stdout.split()
return sorted(set(changed))
def edited_submodules(root):
inputs = [path for spec in prepare.registry(root).values()
for path in spec.get('inputs', []) + spec.get('source_inputs', [])]
staged = git(root, 'ls-files', '--stage', '--', *inputs).stdout.splitlines()
links = [line.split('\t', 1)[1] for line in staged if line.startswith('160000 ')]
return [link for link in links
if git(root, 'diff', '--quiet', '--ignore-submodules=none', '--', link).returncode]
def extract(archive_path, stage):
allowed = set(prepare.LIBRARIES + [prepare.MANIFEST])
total = 0
with tarfile.open(archive_path, mode='r:gz') as archive:
for entry in archive:
name = PurePosixPath(entry.name)
total += entry.size
if (not entry.isfile() or name.is_absolute() or '..' in name.parts or '\\' in entry.name
or name.as_posix() != entry.name or total > 2 * 1024**3
or not (entry.name in allowed or any(entry.name.startswith(t + '/') for t in prepare.TREES))):
raise ValueError('Unsafe prepared component archive: ' + entry.name)
path = stage / entry.name
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('xb') as output:
shutil.copyfileobj(archive.extractfile(entry), output)
path.chmod(entry.mode & 0o777)
def digest(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def install(stage, root):
for name in prepare.TREES:
shutil.rmtree(root / name, ignore_errors=True)
(root / name).parent.mkdir(parents=True, exist_ok=True)
os.replace(stage / name, root / name)
for name in prepare.LIBRARIES + [prepare.MANIFEST]:
(root / name).parent.mkdir(parents=True, exist_ok=True)
os.replace(stage / name, root / name)
def reuse(archive_path, root=prepare.ROOT):
with tarfile.open(archive_path, mode='r:gz') as archive:
data = json.load(archive.extractfile(prepare.MANIFEST))
if data.get('version') != 1:
raise ValueError('Unknown prepared component archive version')
recorded = data.get('recipes') or {}
environment = next((ci_environment(a, root) for a in RUNNER_ARCHITECTURES
if identities(ci_environment(a, root), root) == recorded), None)
if environment is None:
local = identities(ci_environment(RUNNER_ARCHITECTURES[0], root), root)
changed = sorted(name for name in local.keys() | recorded.keys() if local.get(name) != recorded.get(name))
print('CI run ' + str(data.get('run')) + ' prepared different components: ' + ', '.join(changed))
return False
differences = unregistered_changes(data['source_tree'], root) + edited_submodules(root)
if differences:
print('CI run ' + str(data.get('run')) + ' built from other sources: ' + ', '.join(differences))
return False
(root / 'app/build').mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=root / 'app/build', prefix='.reuse-') as stage:
stage = Path(stage)
extract(archive_path, stage)
files = sorted(path.relative_to(stage).as_posix() for path in stage.rglob('*')
if path.is_file() and path.relative_to(stage).as_posix() != prepare.MANIFEST)
if data.get('files') != {name: digest(stage / name) for name in files}:
raise ValueError('Prepared components do not match their recorded file hashes')
missing = [name for name in prepare.TREES if not (stage / name).is_dir()]
missing += [name for name in prepare.LIBRARIES + [prepare.MANIFEST] if not (stage / name).is_file()]
if missing:
raise ValueError('Prepared component archive is missing ' + ', '.join(missing))
install(stage, root)
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('archive', type=Path)
args = parser.parse_args()
try:
sys.exit(0 if reuse(args.archive) else 3)
except (ValueError, OSError, KeyError, tarfile.TarError) as error:
sys.exit('Cannot reuse CI components: ' + str(error))
+157 -7
View File
@@ -153,6 +153,31 @@ def checked(response: dict, default_code: str) -> dict:
return response
def find_game(adb: str, serial: str, wanted: str) -> dict:
games = checked(provider_call(adb, serial, "library", request={}), "LIBRARY_FAILED").get("games") or []
exact = [g for g in games if g.get("id") == wanted]
if exact:
return exact[0]
named = [g for g in games if wanted.casefold() in str(g.get("name", "")).casefold()]
if len(named) == 1:
return named[0]
if not named:
raise ControlError(f"No library game matches {wanted!r}; list them with library", "GAME_NOT_FOUND")
names = ", ".join(f"{g.get('name')} ({g.get('id')})" for g in named[:10])
raise ControlError(f"{wanted!r} matches {len(named)} games: {names}", "GAME_AMBIGUOUS")
def open_game_link(adb: str, serial: str, game_id: str) -> None:
if not game_id.isdigit():
raise ControlError(f"Library id {game_id!r} is not a number", "INVALID_GAME_ID")
result = run_adb(adb, serial, "shell", "am", "start", "-W", "-a", "android.intent.action.VIEW",
"-d", f"droiddeck://game/{game_id}", "-n", f"{PACKAGE}/com.droiddeck.launcher.FrontEndActivity",
timeout=60)
output = (result.stdout + result.stderr).decode(errors="replace")
if result.returncode != 0 or "error" in output.lower():
raise ControlError(output.strip() or "The game link did not open", "ACTIVITY_START_FAILED")
def start_agent_activity(adb: str, serial: str, request: dict) -> None:
encoded = encode_request(request)
result = run_adb(
@@ -387,10 +412,10 @@ def pacing(adb: str, serial: str, seconds: float) -> dict:
try:
time.sleep(seconds)
dump = run_adb(adb, serial, *timestats, "-dump", timeout=60)
elapsed = time.monotonic() - started
except ControlError as exc:
raise ControlError(str(exc), "PACING_FAILED") from exc
finally:
elapsed = time.monotonic() - started
try:
disabled = run_adb(adb, serial, *timestats, "-disable").returncode == 0
except ControlError:
@@ -767,7 +792,7 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict
{"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}]
def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
def uinput_check(adb: str, serial: str) -> None:
probe = run_adb(adb, serial, "shell",
"command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput")
if probe.returncode != 0:
@@ -777,6 +802,10 @@ def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE")
if "no-dev-uinput" in missing:
raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE")
def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
uinput_check(adb, serial)
viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace"))
script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport))
started = time.monotonic()
@@ -792,6 +821,68 @@ def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
"viewport": {key: viewport[key] for key in ("display", "rotation", "size")}}
GAMEPAD_NAME = "DroidDeck test pad"
GAMEPAD_SYNC = "droiddeckctl-gamepad-done"
GAMEPAD_BUTTONS = {"a": "BTN_SOUTH", "b": "BTN_EAST", "x": "BTN_NORTH", "y": "BTN_WEST", "lb": "BTN_TL", "rb": "BTN_TR",
"select": "BTN_SELECT", "start": "BTN_START", "guide": "BTN_MODE", "l3": "BTN_THUMBL", "r3": "BTN_THUMBR"}
GAMEPAD_DPAD = {"up": ("ABS_HAT0Y", -1), "down": ("ABS_HAT0Y", 1), "left": ("ABS_HAT0X", -1), "right": ("ABS_HAT0X", 1)}
GAMEPAD_MAX_PRESSES = 200
GAMEPAD_DPAD_MIN_GAP_MS = 20
def gamepad_commands(buttons: list[str], hold: int, gap: int) -> list[dict]:
def axis(code: str, low: int, high: int) -> dict:
return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}}
unknown = [name for name in buttons if name not in GAMEPAD_BUTTONS and name not in GAMEPAD_DPAD]
if unknown:
raise ControlError(f"Unknown gamepad button {unknown[0]!r}; use "
f"{', '.join(list(GAMEPAD_BUTTONS) + list(GAMEPAD_DPAD))}", "INVALID_INPUT")
if not 1 <= len(buttons) <= GAMEPAD_MAX_PRESSES:
raise ControlError(f"Press between 1 and {GAMEPAD_MAX_PRESSES} buttons", "INVALID_INPUT")
if not 10 <= hold <= 5000 or not 0 <= gap <= 5000:
raise ControlError("--hold must be 10..5000 ms and --gap 0..5000 ms", "INVALID_INPUT")
commands: list[dict] = [
{"id": 1, "command": "register", "name": GAMEPAD_NAME, "bus": "usb", "vid": 0x045E, "pid": 0x028E,
"configuration": [
{"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]},
{"type": "UI_SET_KEYBIT", "data": sorted(GAMEPAD_BUTTONS.values())},
{"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_RX", "ABS_RY", "ABS_HAT0X", "ABS_HAT0Y"]},
],
"abs_info": [axis("ABS_X", -32768, 32767), axis("ABS_Y", -32768, 32767), axis("ABS_RX", -32768, 32767),
axis("ABS_RY", -32768, 32767), axis("ABS_HAT0X", -1, 1), axis("ABS_HAT0Y", -1, 1)]},
{"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS},
]
for name in buttons:
code, down, up = (GAMEPAD_BUTTONS[name], 1, 0) if name in GAMEPAD_BUTTONS else \
(GAMEPAD_DPAD[name][0], GAMEPAD_DPAD[name][1], 0)
kind = "EV_KEY" if name in GAMEPAD_BUTTONS else "EV_ABS"
commands += [{"id": 1, "command": "inject", "events": [kind, code, down, "EV_SYN", "SYN_REPORT", 0]},
{"id": 1, "command": "delay", "duration": hold},
{"id": 1, "command": "inject", "events": [kind, code, up, "EV_SYN", "SYN_REPORT", 0]}]
pause = gap if name in GAMEPAD_BUTTONS else max(gap, GAMEPAD_DPAD_MIN_GAP_MS)
if pause > 0:
commands.append({"id": 1, "command": "delay", "duration": pause})
return commands + [{"id": 1, "command": "delay", "duration": UINPUT_TAIL_MS},
{"id": 1, "command": "sync", "syncToken": GAMEPAD_SYNC}]
def gamepad_uinput(adb: str, serial: str, buttons: list[str], hold: int, gap: int) -> dict:
commands = gamepad_commands(buttons, hold, gap)
uinput_check(adb, serial)
script = "".join(json.dumps(command) + "\n" for command in commands)
started = time.monotonic()
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(),
timeout=(UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30)
elapsed = round((time.monotonic() - started) * 1000)
if GAMEPAD_SYNC not in result.stdout.decode(errors="replace"):
detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:]
raise ControlError(f"uinput stopped before the last button (exit {result.returncode})"
+ (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why",
"UINPUT_FAILED")
return {"ok": True, "command": "input", "type": "gamepad", "buttons": buttons, "ms": elapsed}
def xr_ppm_to_png(data: bytes, linear: bool = False) -> bytes:
header = re.match(rb"P6\n([0-9]+) ([0-9]+)\n255\n", data)
if not header:
@@ -949,6 +1040,17 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
return add_serial(checked(provider_call(adb, serial, "resume"), "RESUME_FAILED"), serial)
if command == "launch":
if (args.app_id is None) == (args.game is None):
raise ControlError("launch takes a Steam app id or --game, not both", "INVALID_ARGUMENTS")
if args.game is not None:
game = find_game(adb, serial, args.game)
open_game_link(adb, serial, game["id"])
response = {"ok": True, "command": "launch", "game": game}
if args.wait:
state = wait_until(adb, serial, f"{game['name']} to have focus",
lambda s: focused(s, None), args.timeout, 0.5)
response["focus"] = state["session"].get("focus")
return add_serial(response, serial)
response = checked(provider_call(adb, serial, "launch", request={"appId": str(args.app_id)}), "LAUNCH_FAILED")
if args.wait:
state = wait_until(adb, serial, f"app {args.app_id} to have focus",
@@ -957,10 +1059,33 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
return add_serial(response, serial)
if command == "quit":
response = provider_call(adb, serial, "quit", request={"appId": args.app_id, "timeout": args.timeout},
app_id = args.app_id
if app_id is None:
current = (get_state(adb, serial)["session"].get("focus") or {}).get("focusedApp")
if current in (None, 0, STEAM_CLIENT_APP):
raise ControlError("No game has focus; name the app id to quit", "NO_FOCUSED_GAME")
app_id = current
response = provider_call(adb, serial, "quit", request={"appId": app_id, "timeout": args.timeout},
timeout=args.timeout + 40)
return add_serial(checked(response, "QUIT_FAILED"), serial)
if command == "library":
request = {"query": args.query or "", "source": args.source or ""}
return add_serial(checked(provider_call(adb, serial, "library", request=request), "LIBRARY_FAILED"), serial)
if command == "xodus":
argv = args.argv[1:] if args.argv[:1] == ["--"] else args.argv
if not argv:
raise ControlError("xodus needs its arguments after --", "INVALID_ARGUMENTS")
response = provider_call(adb, serial, "xodus", request={"args": argv, "timeout": args.timeout},
timeout=args.timeout + 30)
return add_serial(checked(response, "XODUS_FAILED"), serial)
if command == "cloud":
request = {"direction": args.direction, "store": args.store, "id": args.game_id, "force": args.force}
response = provider_call(adb, serial, "cloud", request=request, timeout=args.timeout)
return add_serial(checked(response, "CLOUD_FAILED"), serial)
if command == "focus":
return add_serial(checked(provider_call(adb, serial, "focus", timeout=40), "FOCUS_FAILED"), serial)
@@ -1022,6 +1147,8 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if command == "input":
if args.input_type == "pen":
return add_serial(pen_uinput(adb, serial, pen_samples(args), args.tool), serial)
if args.input_type == "gamepad":
return add_serial(gamepad_uinput(adb, serial, args.buttons, args.hold, args.gap), serial)
return add_serial(checked(provider_call(adb, serial, "input", request=input_request(args), timeout=60),
"INPUT_FAILED"), serial)
@@ -1224,15 +1351,31 @@ def build_parser() -> argparse.ArgumentParser:
stop.add_argument("--artifact-timeout", type=float, default=300)
commands.add_parser("resume", help="resume a suspended session")
launch = commands.add_parser("launch", help="launch a Steam game in the running Steam session")
launch.add_argument("app_id", type=int)
launch = commands.add_parser("launch", help="launch a Steam game in the running Steam session, or any library game with --game")
launch.add_argument("app_id", type=int, nargs="?")
launch.add_argument("--game", help="a library game id or a unique part of its name (store and added games too)")
launch.add_argument("--wait", action="store_true", help="wait until the game has focus")
launch.add_argument("--timeout", type=float, default=180)
quit_ = commands.add_parser("quit", help="quit a running game (through the client, then signals)")
quit_.add_argument("app_id", type=int)
quit_ = commands.add_parser("quit", help="quit a running game (through the client, then signals); the focused one by default")
quit_.add_argument("app_id", type=int, nargs="?")
quit_.add_argument("--timeout", type=float, default=15)
library = commands.add_parser("library", help="the library games the front end lists, with the ids launch --game takes")
library.add_argument("--query", help="only games whose name contains this")
library.add_argument("--source", help="only games from this source, e.g. steam, xbox, ea, ubisoft, gog, epic")
xodus = commands.add_parser("xodus", help="run the Xbox backend with the app's credentials (debugging tools)")
xodus.add_argument("--timeout", type=float, default=120)
xodus.add_argument("argv", nargs=argparse.REMAINDER)
cloud = commands.add_parser("cloud", help="sync a store game's cloud saves now (debugging tools)")
cloud.add_argument("direction", choices=["down", "up"])
cloud.add_argument("store", help="gog, epic, ea or ubisoft")
cloud.add_argument("game_id", help="the store's id for the game, as its install record names it")
cloud.add_argument("--force", action="store_true", help="take this side even over conflicts")
cloud.add_argument("--timeout", type=float, default=300)
commands.add_parser("focus", help="gamescope's focus and every Xwayland server's windows, fresh")
guest = commands.add_parser("guest", help="run a command inside the session (debugging tools)")
@@ -1284,6 +1427,13 @@ def build_parser() -> argparse.ArgumentParser:
pad.add_argument("button")
pad.add_argument("--action", choices=["tap", "down", "up"], default="tap")
pad.add_argument("--hold", type=int, default=120)
gamepad = kinds.add_parser(
"gamepad", help="press buttons on a real uinput gamepad that Android sees as a physical controller "
"(unlike pad, which only feeds the guest's virtual pad)")
gamepad.add_argument("buttons", nargs="+", metavar="BUTTON",
help="a b x y lb rb select start guide l3 r3 up down left right, pressed in order")
gamepad.add_argument("--hold", type=int, default=120, help="ms each button stays down")
gamepad.add_argument("--gap", type=int, default=400, help="ms between buttons (a d-pad press always waits at least 20 ms)")
stick = kinds.add_parser("stick", help="hold a stick at x, y (-1..1)")
stick.add_argument("stick", choices=["left", "right"])
stick.add_argument("x", type=float)
+1
View File
@@ -0,0 +1 @@
/target/
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "droiddeck-epic-launcher"
version = "0.1.0"
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "droiddeck-epic-launcher"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-only"
publish = false
[[bin]]
name = "EpicGamesLauncher"
path = "src/main.rs"
[profile.release]
opt-level = "s"
lto = true
panic = "abort"
strip = true
+13
View File
@@ -0,0 +1,13 @@
# Epic Games Launcher parent stand-in
`EpicGamesLauncher.exe` starts the game named by its first argument as its own child, passes the rest of its command line to the game unchanged, waits for the game and returns its exit code.
Some Epic titles only accept a launch whose parent process is named `EpicGamesLauncher.exe`. Rockstar's launcher logs `Epic Games Launcher not detected as parent process.` and then treats the Epic copy as unowned. In DroidDeck the Epic client is a Linux program, so it can never be that parent. The check matches the process name, not its path: Heroic's stand-in works from `C:\windows\command` and from the game folder.
`StoreLaunch` writes the Epic `.droiddeck-launch.bat` to run the game through this executable for the titles in `EPIC_PARENT_TITLES`, or for any Epic game whose per-game environment sets `DD_EPIC_PARENT=1`. `DD_EPIC_PARENT=0` turns it off. Without the staged executable the game starts directly, as before.
`build.sh` builds it with the GNU Windows target for the `epic` add-on pack. The app fetches the pack when it starts signed in to Epic, or when a launch that needs it finds it missing, and stages it in the Linux runtime at `/usr/local/lib/droiddeck-epic`.
```sh
cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml
```
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
out=${1:-"$here/../../app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic"}
target=x86_64-pc-windows-gnu
rustup target add "$target" >/dev/null 2>&1 || true
cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target"
mkdir -p "$out"
install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/EpicGamesLauncher.exe" "$out/EpicGamesLauncher.exe"
+110
View File
@@ -0,0 +1,110 @@
const QUOTE: u16 = b'"' as u16;
const BACKSLASH: u16 = b'\\' as u16;
fn blank(c: u16) -> bool {
c == b' ' as u16 || c == b'\t' as u16
}
fn trim_start(line: &[u16]) -> &[u16] {
let start = line.iter().position(|&c| !blank(c)).unwrap_or(line.len());
&line[start..]
}
/// Splits this program's command line into the game executable that follows the program name and
/// the rest of the line, which reaches the game unchanged.
pub fn split(line: &[u16]) -> Option<(Vec<u16>, &[u16])> {
let mut quoted = false;
let mut end = line.len();
for (i, &c) in line.iter().enumerate() {
if c == QUOTE {
quoted = !quoted;
} else if blank(c) && !quoted {
end = i;
break;
}
}
let rest = trim_start(&line[end..]);
let mut exe = Vec::new();
let mut quoted = false;
let mut slashes = 0;
let mut end = rest.len();
for (i, &c) in rest.iter().enumerate() {
if c == BACKSLASH {
slashes += 1;
continue;
}
if c == QUOTE {
exe.extend(std::iter::repeat(BACKSLASH).take(slashes / 2));
if slashes % 2 == 1 {
exe.push(QUOTE);
} else {
quoted = !quoted;
}
} else if blank(c) && !quoted {
exe.extend(std::iter::repeat(BACKSLASH).take(slashes));
end = i;
slashes = 0;
break;
} else {
exe.extend(std::iter::repeat(BACKSLASH).take(slashes));
exe.push(c);
}
slashes = 0;
}
exe.extend(std::iter::repeat(BACKSLASH).take(slashes));
if exe.is_empty() {
return None;
}
Some((exe, trim_start(&rest[end..])))
}
#[cfg(test)]
mod tests {
use super::split;
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
fn parts(line: &str) -> Option<(String, String)> {
let line = wide(line);
split(&line).map(|(exe, rest)| (String::from_utf16(&exe).unwrap(), String::from_utf16(rest).unwrap()))
}
#[test]
fn the_game_gets_the_rest_of_the_line_exactly_as_written() {
assert_eq!(
parts(r#""Z:\usr\local\lib\droiddeck-epic\EpicGamesLauncher.exe" "Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe" -AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#),
Some((
r"Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe".into(),
r#"-AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#.into()
))
);
}
#[test]
fn a_game_without_arguments_gets_none() {
assert_eq!(parts(r#"EpicGamesLauncher.exe "C:\Games\x.exe" "#), Some((r"C:\Games\x.exe".into(), String::new())));
assert_eq!(parts(r"EpicGamesLauncher.exe C:\Games\x.exe"), Some((r"C:\Games\x.exe".into(), String::new())));
}
#[test]
fn the_program_name_follows_its_own_quoting_rules() {
assert_eq!(parts("\"C:\\a b\\\"EpicGamesLauncher.exe\tgame.exe -x"), Some(("game.exe".into(), "-x".into())));
}
#[test]
fn the_executable_follows_the_argument_quoting_rules() {
assert_eq!(parts(r#"e "C:\dir with\"part\"s\x.exe" -y"#), Some((r#"C:\dir with"part"s\x.exe"#.into(), "-y".into())));
assert_eq!(parts(r#"e C:\a"b c"\x.exe -y"#), Some((r"C:\ab c\x.exe".into(), "-y".into())));
assert_eq!(parts(r"e C:\games\ -y"), Some((r"C:\games\".into(), "-y".into())));
}
#[test]
fn a_missing_executable_is_refused() {
assert_eq!(parts("EpicGamesLauncher.exe"), None);
assert_eq!(parts("EpicGamesLauncher.exe "), None);
assert_eq!(parts(r#"EpicGamesLauncher.exe "" -x"#), None);
assert_eq!(parts(""), None);
}
}
+42
View File
@@ -0,0 +1,42 @@
#[cfg(windows)]
fn main() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::process::CommandExt;
#[link(name = "kernel32")]
extern "system" {
fn GetCommandLineW() -> *const u16;
}
let line = unsafe {
let start = GetCommandLineW();
let mut len = 0;
while *start.add(len) != 0 {
len += 1;
}
std::slice::from_raw_parts(start, len)
};
let Some((exe, rest)) = droiddeck_epic_launcher::split(line) else {
eprintln!("usage: EpicGamesLauncher.exe <game.exe> [arguments]");
std::process::exit(2);
};
let exe = OsString::from_wide(&exe);
let mut command = std::process::Command::new(&exe);
if !rest.is_empty() {
command.raw_arg(OsString::from_wide(rest));
}
match command.status() {
Ok(status) => std::process::exit(status.code().unwrap_or(1)),
Err(error) => {
eprintln!("EpicGamesLauncher: could not start {}: {error}", exe.to_string_lossy());
std::process::exit(1);
}
}
}
#[cfg(not(windows))]
fn main() {
eprintln!("EpicGamesLauncher.exe runs on Windows or Wine");
std::process::exit(1);
}
+6 -3
View File
@@ -1,6 +1,8 @@
#!/usr/bin/bash
set -euxo pipefail
VERSION=${FEX_VERSION:-FEX-2610}
VERSION=${FEX_VERSION:?FEX_VERSION must name a FEX release tag, e.g. FEX-2611.1}
RELEASE=${VERSION#FEX-}
RELEASE=${RELEASE%%.*}
WORK=/work
cd "$WORK"
grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf
@@ -38,7 +40,7 @@ fi
rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src
for p in tools/fex/patches/*.patch; do
upstream=$(sed -n 's/^Fixed-upstream: FEX-\([0-9]\{4\}\)$/\1/p' "$p")
if [ -n "$upstream" ] && [ "${VERSION#FEX-}" -ge "$upstream" ]; then
if [ -n "$upstream" ] && [ "$RELEASE" -ge "$upstream" ]; then
echo "$(basename "$p"): already in FEX-$upstream, skipped for $VERSION"
continue
fi
@@ -56,7 +58,8 @@ cmake -S fex-src -B fex-build -G Ninja \
-DTUNE_CPU=none -DTUNE_ARCH=armv8-a \
-DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \
$( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF -DFMT_MODULE=OFF \
-DCMAKE_CXX_MODULE_STD=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
@@ -0,0 +1,81 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h
index d720866..f55bce4 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h
@@ -288,6 +288,7 @@ public:
///// VMA (Virtual Memory Area) tracking /////
static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext);
void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override;
+ void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length);
void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override;
std::optional<FEXCore::ExecutableFileSectionInfo>
LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override;
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
index 94bdd37..5d6c850 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
@@ -196,6 +196,44 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState
}
}
+void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) {
+ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK) {
+ return;
+ }
+
+ const auto End = Base + Length;
+ auto Mapping = VMATracking.FindVMAEntry(Base);
+ if (Mapping == VMATracking.VMAs.end()) {
+ Mapping = VMATracking.VMAs.lower_bound(Base);
+ }
+
+ for (; Mapping != VMATracking.VMAs.end() && Mapping->first < End; ++Mapping) {
+ if (!Mapping->second.Flags.Shared || !Mapping->second.Prot.Writable || !Mapping->second.Resource) {
+ continue;
+ }
+
+ const auto MapBase = std::max(Base, Mapping->first);
+ const auto MapTop = std::min(End, Mapping->first + Mapping->second.Length);
+ if (MapTop <= MapBase) {
+ continue;
+ }
+
+ const auto OffsetBase = Mapping->second.Offset + (MapBase - Mapping->first);
+ const auto OffsetTop = OffsetBase + (MapTop - MapBase);
+
+ for (auto VMA = Mapping->second.Resource->FirstVMA; VMA; VMA = VMA->ResourceNextVMA) {
+ if (!VMA->Prot.Executable || VMA->Offset >= OffsetTop || VMA->Offset + VMA->Length <= OffsetBase) {
+ continue;
+ }
+
+ const auto OverlapBase = std::max(VMA->Offset, OffsetBase);
+ const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop);
+ auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ);
+ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase);
+ }
+ }
+}
+
void SyscallHandler::InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {
InvalidateCodeRangeIfNecessary(Thread, Start, Length, false);
}
@@ -334,6 +372,9 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState
}
LateMetadata = TrackMmap(Thread, Result, length, prot, flags, fd, offset, CachedSection);
+ if (prot & PROT_WRITE) {
+ ProtectWritableAliasOfCode(Result, Size);
+ }
PendingResourceDeletion = VMATracking.HasPendingResourceDeletions();
}
@@ -479,6 +520,9 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa
}
TrackMprotect(Thread, addr, len, prot);
+ if (prot & PROT_WRITE) {
+ ProtectWritableAliasOfCode(reinterpret_cast<uint64_t>(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE));
+ }
}
InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast<uint64_t>(addr), len, false);
@@ -0,0 +1,20 @@
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8976588..3ae54f4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -776,7 +776,6 @@ if (BUILD_THUNKS)
CODE "
execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest)"
- DEPENDS guest-libs
COMPONENT Runtime)
install(
@@ -784,7 +783,6 @@ if (BUILD_THUNKS)
CODE "
execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest_32)"
- DEPENDS guest-libs-32
COMPONENT Runtime)
add_custom_target(uninstall_guest-libs
@@ -0,0 +1,18 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index b4c7b24..643185d 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
auto Frame = Thread->CurrentFrame;
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
// XXX: Unsupported since it needs state reconstruction
// If we are in the JIT then SRA might need to be restored to values from the context
// We can't currently support this since it might result in tearing without real state reconstruction
+ Frame->InSyscallInfo = Context->InSyscallInfo;
}
if (Is64BitMode) {
RestoreFrame_x64(Thread, Context, Frame, ucontext);
} else {
if (Type == RestoreType::TYPE_NONREALTIME) {
@@ -0,0 +1,174 @@
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
index 02bb6bf..2e72492 100644
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
@@ -49,6 +49,11 @@ struct X86ContextBackup {
uint64_t FPStateLocation;
uint64_t UContextLocation;
uint64_t SigInfoLocation;
+ uint64_t PrevGuestFrame;
+ uint64_t GuestFrameEnd;
+ uint64_t GuestInterruptedSP;
+ uint64_t GuestAltBase;
+ uint64_t GuestAltEnd;
FEXCore::Core::CPUState GuestState;
static constexpr int RedZoneSize = 128;
};
@@ -76,6 +81,11 @@ struct ArmContextBackup {
uint64_t FPStateLocation;
uint64_t UContextLocation;
uint64_t SigInfoLocation;
+ uint64_t PrevGuestFrame;
+ uint64_t GuestFrameEnd;
+ uint64_t GuestInterruptedSP;
+ uint64_t GuestAltBase;
+ uint64_t GuestAltEnd;
FEXCore::Core::CPUState GuestState;
// 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
--- 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*
#endif
}
+namespace {
+ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) {
+ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd;
+ }
+
+ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) {
+ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP);
+ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) {
+ return GuestSP >= Backup->GuestFrameEnd;
+ }
+ if (SPOnAlt) {
+ return false;
+ }
+ auto Entry = Backup;
+ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) {
+ if (--Limit == 0 || !Entry->PrevGuestFrame) {
+ return false;
+ }
+ Entry = reinterpret_cast<const ArchHelpers::Context::ContextBackup*>(Entry->PrevGuestFrame);
+ }
+ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase &&
+ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP;
+ }
+}
+
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
}
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
+
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
+ uint64_t Entry = SignalInfo.GuestFrames;
+ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) {
+ auto EntryBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Entry);
+ if (Entry == OldSP) {
+ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;
+ SignalInfo.GuestFrameCount -= Depth;
+ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;
+ break;
+ }
+ Entry = EntryBackup->PrevGuestFrame;
+ }
}
uintptr_t NewSP = OldSP;
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
auto Frame = Thread->CurrentFrame;
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
// 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
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
uint64_t NewGuestSP = OldGuestSP;
+ uint64_t GuestAltBase = 0;
+ uint64_t GuestAltEnd = 0;
// 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
// 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;
+ GuestAltBase = AltStackBase;
+ GuestAltEnd = AltStackEnd;
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
}
}
+#ifdef ARCHITECTURE_arm64
+ auto Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(SignalInfo.GuestFrames);
+ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames &&
+ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) {
+ uint32_t LeftFrames = 0;
+ while (Newest && LeftFrames < SignalInfo.GuestFrameCount &&
+ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) {
+ Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Newest->PrevGuestFrame);
+ ++LeftFrames;
+ }
+
+ const uint64_t HostTop = Newest ? reinterpret_cast<uint64_t>(Newest) : Frame->ReturningStackLocation;
+ const uint64_t MovedBackup = FEXCore::AlignDown(
+ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16);
+ if (MovedBackup > reinterpret_cast<uint64_t>(ContextBackup)) {
+ memmove(reinterpret_cast<void*>(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup));
+ ContextBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(MovedBackup);
+ ContextBackup->PrevSP = HostTop;
+ ArchHelpers::Context::SetSp(ucontext, MovedBackup);
+ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(Newest);
+ SignalInfo.GuestFrameCount -= LeftFrames;
+ Frame->SignalHandlerRefCounter -= LeftFrames;
+ }
+ }
+#endif
+
+ ContextBackup->GuestFrameEnd = NewGuestSP;
+ ContextBackup->GuestInterruptedSP = OldGuestSP;
+ ContextBackup->GuestAltBase = GuestAltBase;
+ ContextBackup->GuestAltEnd = GuestAltEnd;
+ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;
+ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);
+ ++SignalInfo.GuestFrameCount;
+
// siginfo_t
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
// Our ref counting doesn't matter anymore
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
+ ThreadObject->SignalInfo.GuestFrames = 0;
+ ThreadObject->SignalInfo.GuestFrameCount = 0;
// 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
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
// Queue of thread local signal frames that have been deferred.
// Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO.
fextl::vector<DeferredSignalState> DeferredSignalFrames;
+
+ uint64_t GuestFrames {};
+ uint32_t GuestFrameCount {};
} SignalInfo {};
// Seccomp thread specific data.
@@ -0,0 +1,23 @@
Fixed-upstream: FEX-2612
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
index c2b1d8e287..fcdf261484 100644
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
@@ -285,6 +285,8 @@ DEF_OP(CondJump) {
DEF_OP(Syscall) {
SpillStaticRegs(TMP1);
+ ResetStack();
+
// Jump to the syscall dispatch handler. We won't return after this.
ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler));
br(TMP1);
@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) {
SpillStaticRegs(TMP1);
+ ResetStack();
+
// Store the new RIP to go to.
str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip));
@@ -0,0 +1,109 @@
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
--- a/FEXCore/Source/Interface/Core/Core.cpp
+++ b/FEXCore/Source/Interface/Core/Core.cpp
@@ -383,7 +383,11 @@
}
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
- static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP);
+ auto Frame = Thread->CurrentFrame;
+ const auto InSyscallInfo = Frame->InSyscallInfo;
+ Frame->InSyscallInfo = 0;
+ static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP);
+ Frame->InSyscallInfo = InSyscallInfo;
}
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
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
@@ -305,6 +305,9 @@
PushDynamicRegs(TMP1);
+ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);
+ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));
+
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
@@ -320,6 +323,8 @@
FillStaticRegs({
.NZCV = false,
});
+
+ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));
}
DEF_OP(ValidateCode) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -107,6 +107,10 @@
#ifdef ARCHITECTURE_arm64
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
+ if ((IgnoreMask & 0xFFFF) == 0xFFFF) {
+ return;
+ }
+
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
if (IgnoreMask & (1U << SRAIdxMap)) {
@@ -301,12 +305,10 @@
if (Context->UContextLocation) {
auto Frame = Thread->CurrentFrame;
- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
- // XXX: Unsupported since it needs state reconstruction
- // If we are in the JIT then SRA might need to be restored to values from the context
- // We can't currently support this since it might result in tearing without real state reconstruction
- Frame->InSyscallInfo = Context->InSyscallInfo;
- }
+ // XXX: Unsupported since it needs state reconstruction
+ // If we are in the JIT then SRA might need to be restored to values from the context
+ // We can't currently support this since it might result in tearing without real state reconstruction
+ Frame->InSyscallInfo = Context->InSyscallInfo;
if (Is64BitMode) {
RestoreFrame_x64(Thread, Context, Frame, ucontext);
@@ -361,6 +363,9 @@
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
Thread->CurrentFrame->InSyscallInfo = 0;
} else {
+ ContextBackup->InSyscallInfo = Frame->InSyscallInfo;
+ Frame->InSyscallInfo = 0;
+
if (!IsAddressInDispatcher(OldPC)) {
// 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
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -131,7 +131,7 @@
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
- Frame->InSyscallInfo = Context->InSyscallInfo;
+ Frame->InSyscallInfo = 0;
// 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 @@
// 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.
- Frame->InSyscallInfo = Context->InSyscallInfo;
+ Frame->InSyscallInfo = 0;
// 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 @@
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
- Frame->InSyscallInfo = Context->InSyscallInfo;
+ Frame->InSyscallInfo = 0;
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
@@ -0,0 +1,112 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
@@ -263,6 +263,8 @@
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
+ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
+ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask);
///< 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
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -122,6 +122,32 @@
}
}
+void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
+ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) {
+#ifdef ARCHITECTURE_arm64
+ const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;
+ const bool AllSpilled = Spilled == 0xFFFF;
+ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {
+ return;
+ }
+
+ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {
+ const uint8_t HostReg = Config.SRAGPRMapping[i];
+ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));
+ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg);
+ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {
+ continue;
+ }
+
+ if (InFrame) {
+ Frame->State.gregs[i] = GuestGPRs[i];
+ } else {
+ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);
+ }
+ }
+#endif
+}
+
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 @@
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
}
+ } else {
+ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];
+#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];
+ COPY_REG(R8);
+ COPY_REG(R9);
+ COPY_REG(R10);
+ COPY_REG(R11);
+ COPY_REG(R12);
+ COPY_REG(R13);
+ COPY_REG(R14);
+ COPY_REG(R15);
+ COPY_REG(RDI);
+ COPY_REG(RSI);
+ COPY_REG(RBP);
+ COPY_REG(RBX);
+ COPY_REG(RDX);
+ COPY_REG(RAX);
+ COPY_REG(RCX);
+ COPY_REG(RSP);
+#undef COPY_REG
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);
}
}
@@ -280,6 +327,17 @@
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
+ } else {
+ uint64_t GuestGPRs[8];
+ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax;
+ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx;
+ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx;
+ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx;
+ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp;
+ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp;
+ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si;
+ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di;
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);
}
}
@@ -359,6 +417,17 @@
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
+ } else {
+ uint64_t GuestGPRs[8];
+ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX];
+ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX];
+ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX];
+ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX];
+ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP];
+ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP];
+ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI];
+ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI];
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);
}
}
@@ -0,0 +1,144 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
index 11ff163..4c3be85 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1,
}
#endif
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) {
+ uint64_t Result = ::syscall(syscall_num, arg1);
+ SYSCALL_ERRNO();
+}
+
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough2(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2) {
+ uint64_t Result = ::syscall(syscall_num, arg1, arg2);
+ SYSCALL_ERRNO();
+}
+
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough3(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3) {
+ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3);
+ SYSCALL_ERRNO();
+}
+
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough4(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) {
+ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4);
+ SYSCALL_ERRNO();
+}
+
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) {
+ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4, arg5);
+ SYSCALL_ERRNO();
+}
+
static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3<SYSCALL_DEF(read)>);
REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3<SYSCALL_DEF(write)>);
@@ -220,11 +255,11 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(shmctl, SyscallPassthrough3<SYSCALL_DEF(shmctl)>);
REGISTER_SYSCALL_IMPL(getpid, SyscallPassthrough0<SYSCALL_DEF(getpid)>);
REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3<SYSCALL_DEF(socket)>);
- REGISTER_SYSCALL_IMPL(connect, SyscallPassthrough3<SYSCALL_DEF(connect)>);
+ REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3<SYSCALL_DEF(connect)>);
REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6<SYSCALL_DEF(sendto)>);
REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6<SYSCALL_DEF(recvfrom)>);
REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2<SYSCALL_DEF(shutdown)>);
- REGISTER_SYSCALL_IMPL(bind, SyscallPassthrough3<SYSCALL_DEF(bind)>);
+ REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3<SYSCALL_DEF(bind)>);
REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2<SYSCALL_DEF(listen)>);
REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3<SYSCALL_DEF(getsockname)>);
REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3<SYSCALL_DEF(getpeername)>);
@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2<SYSCALL_DEF(flock)>);
REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1<SYSCALL_DEF(fsync)>);
REGISTER_SYSCALL_IMPL(fdatasync, SyscallPassthrough1<SYSCALL_DEF(fdatasync)>);
- REGISTER_SYSCALL_IMPL(truncate, SyscallPassthrough2<SYSCALL_DEF(truncate)>);
+ REGISTER_SYSCALL_IMPL(truncate, SyscallPathPassthrough2<SYSCALL_DEF(truncate)>);
REGISTER_SYSCALL_IMPL(getcwd, SyscallPassthrough2<SYSCALL_DEF(getcwd)>);
- REGISTER_SYSCALL_IMPL(chdir, SyscallPassthrough1<SYSCALL_DEF(chdir)>);
+ REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>);
REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>);
REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>);
REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
@@ -280,7 +315,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(mlock, SyscallPassthrough2<SYSCALL_DEF(mlock)>);
REGISTER_SYSCALL_IMPL(munlock, SyscallPassthrough2<SYSCALL_DEF(munlock)>);
REGISTER_SYSCALL_IMPL(pivot_root, SyscallPassthrough2<SYSCALL_DEF(pivot_root)>);
- REGISTER_SYSCALL_IMPL(chroot, SyscallPassthrough1<SYSCALL_DEF(chroot)>);
+ REGISTER_SYSCALL_IMPL(chroot, SyscallPathPassthrough1<SYSCALL_DEF(chroot)>);
REGISTER_SYSCALL_IMPL(sync, SyscallPassthrough0<SYSCALL_DEF(sync)>);
REGISTER_SYSCALL_IMPL(acct, SyscallPassthrough1<SYSCALL_DEF(acct)>);
REGISTER_SYSCALL_IMPL(mount, SyscallPassthrough5<SYSCALL_DEF(mount)>);
@@ -312,17 +347,17 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(keyctl, SyscallPassthrough5<SYSCALL_DEF(keyctl)>);
REGISTER_SYSCALL_IMPL(ioprio_set, SyscallPassthrough2<SYSCALL_DEF(ioprio_set)>);
REGISTER_SYSCALL_IMPL(ioprio_get, SyscallPassthrough3<SYSCALL_DEF(ioprio_get)>);
- REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPassthrough3<SYSCALL_DEF(inotify_add_watch)>);
+ REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPathPassthrough3<SYSCALL_DEF(inotify_add_watch)>);
REGISTER_SYSCALL_IMPL(inotify_rm_watch, SyscallPassthrough2<SYSCALL_DEF(inotify_rm_watch)>);
REGISTER_SYSCALL_IMPL(migrate_pages, SyscallPassthrough4<SYSCALL_DEF(migrate_pages)>);
- REGISTER_SYSCALL_IMPL(mkdirat, SyscallPassthrough3<SYSCALL_DEF(mkdirat)>);
- REGISTER_SYSCALL_IMPL(mknodat, SyscallPassthrough4<SYSCALL_DEF(mknodat)>);
- REGISTER_SYSCALL_IMPL(fchownat, SyscallPassthrough5<SYSCALL_DEF(fchownat)>);
- REGISTER_SYSCALL_IMPL(unlinkat, SyscallPassthrough3<SYSCALL_DEF(unlinkat)>);
- REGISTER_SYSCALL_IMPL(renameat, SyscallPassthrough4<SYSCALL_DEF(renameat)>);
- REGISTER_SYSCALL_IMPL(linkat, SyscallPassthrough5<SYSCALL_DEF(linkat)>);
- REGISTER_SYSCALL_IMPL(symlinkat, SyscallPassthrough3<SYSCALL_DEF(symlinkat)>);
- REGISTER_SYSCALL_IMPL(fchmodat, SyscallPassthrough3<SYSCALL_DEF(fchmodat)>);
+ REGISTER_SYSCALL_IMPL(mkdirat, SyscallPathPassthrough3<SYSCALL_DEF(mkdirat)>);
+ REGISTER_SYSCALL_IMPL(mknodat, SyscallPathPassthrough4<SYSCALL_DEF(mknodat)>);
+ REGISTER_SYSCALL_IMPL(fchownat, SyscallPathPassthrough5<SYSCALL_DEF(fchownat)>);
+ REGISTER_SYSCALL_IMPL(unlinkat, SyscallPathPassthrough3<SYSCALL_DEF(unlinkat)>);
+ REGISTER_SYSCALL_IMPL(renameat, SyscallPathPassthrough4<SYSCALL_DEF(renameat)>);
+ REGISTER_SYSCALL_IMPL(linkat, SyscallPathPassthrough5<SYSCALL_DEF(linkat)>);
+ REGISTER_SYSCALL_IMPL(symlinkat, SyscallPathPassthrough3<SYSCALL_DEF(symlinkat)>);
+ REGISTER_SYSCALL_IMPL(fchmodat, SyscallPathPassthrough3<SYSCALL_DEF(fchmodat)>);
REGISTER_SYSCALL_IMPL(unshare, SyscallPassthrough1<SYSCALL_DEF(unshare)>);
REGISTER_SYSCALL_IMPL(splice, SyscallPassthrough6<SYSCALL_DEF(splice)>);
REGISTER_SYSCALL_IMPL(tee, SyscallPassthrough4<SYSCALL_DEF(tee)>);
@@ -343,7 +378,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(kcmp, SyscallPassthrough5<SYSCALL_DEF(kcmp)>);
REGISTER_SYSCALL_IMPL(sched_setattr, SyscallPassthrough3<SYSCALL_DEF(sched_setattr)>);
REGISTER_SYSCALL_IMPL(sched_getattr, SyscallPassthrough4<SYSCALL_DEF(sched_getattr)>);
- REGISTER_SYSCALL_IMPL(renameat2, SyscallPassthrough5<SYSCALL_DEF(renameat2)>);
+ REGISTER_SYSCALL_IMPL(renameat2, SyscallPathPassthrough5<SYSCALL_DEF(renameat2)>);
REGISTER_SYSCALL_IMPL(getrandom, SyscallPassthrough3<SYSCALL_DEF(getrandom)>);
REGISTER_SYSCALL_IMPL(memfd_create, SyscallPassthrough2<SYSCALL_DEF(memfd_create)>);
REGISTER_SYSCALL_IMPL(membarrier, SyscallPassthrough2<SYSCALL_DEF(membarrier)>);
@@ -468,7 +503,7 @@ namespace x64 {
REGISTER_SYSCALL_IMPL_X64(get_robust_list, SyscallPassthrough3<SYSCALL_DEF(get_robust_list)>);
REGISTER_SYSCALL_IMPL_X64(sync_file_range, SyscallPassthrough4<SYSCALL_DEF(sync_file_range)>);
REGISTER_SYSCALL_IMPL_X64(vmsplice, SyscallPassthrough4<SYSCALL_DEF(vmsplice)>);
- REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPassthrough4<SYSCALL_DEF(utimensat)>);
+ REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPathPassthrough4<SYSCALL_DEF(utimensat)>);
REGISTER_SYSCALL_IMPL_X64(fallocate, SyscallPassthrough4<SYSCALL_DEF(fallocate)>);
REGISTER_SYSCALL_IMPL_X64(timerfd_settime, SyscallPassthrough4<SYSCALL_DEF(timerfd_settime)>);
REGISTER_SYSCALL_IMPL_X64(timerfd_gettime, SyscallPassthrough2<SYSCALL_DEF(timerfd_gettime)>);
@@ -492,7 +527,7 @@ namespace x64 {
REGISTER_SYSCALL_IMPL_X64(cachestat, UnimplementedSyscallSafe);
}
if (Handler->IsHostKernelVersionAtLeast(6, 6, 0)) {
- REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPassthrough4<SYSCALL_DEF(fchmodat2)>);
+ REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPathPassthrough4<SYSCALL_DEF(fchmodat2)>);
} else {
REGISTER_SYSCALL_IMPL_X64(fchmodat2, UnimplementedSyscallSafe);
}
@@ -529,7 +564,7 @@ namespace x32 {
REGISTER_SYSCALL_IMPL_X32(timer_settime64, SyscallPassthrough4<SYSCALL_DEF(timer_settime)>);
REGISTER_SYSCALL_IMPL_X32(timerfd_gettime64, SyscallPassthrough2<SYSCALL_DEF(timerfd_gettime)>);
REGISTER_SYSCALL_IMPL_X32(timerfd_settime64, SyscallPassthrough4<SYSCALL_DEF(timerfd_settime)>);
- REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPassthrough4<SYSCALL_DEF(utimensat)>);
+ REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPathPassthrough4<SYSCALL_DEF(utimensat)>);
REGISTER_SYSCALL_IMPL_X32(ppoll_time64, SyscallPassthrough5<SYSCALL_DEF(ppoll)>);
REGISTER_SYSCALL_IMPL_X32(io_pgetevents_time64, SyscallPassthrough6<SYSCALL_DEF(io_pgetevents)>);
REGISTER_SYSCALL_IMPL_X32(mq_timedsend_time64, SyscallPassthrough5<SYSCALL_DEF(mq_timedsend)>);
@@ -0,0 +1,51 @@
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
index e1f601b..cebf1f5 100644
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
@@ -222,6 +222,32 @@ class ELFCodeLoader final : public FEX::CodeLoader {
public:
+ static fextl::string GuestPreload(const char* List, const fextl::string& RootFS) {
+ fextl::string Result;
+ for (const char* Start = List; *Start; Start += *Start ? 1 : 0) {
+ size_t Length = strcspn(Start, ": ");
+ fextl::string Entry(Start, Length);
+ Start += Length;
+ if (Entry.empty()) {
+ continue;
+ }
+ if (Entry[0] == '/') {
+ auto Type = ::ELFLoader::ELFContainer::GetELFType(ResolveRootfsFile(Entry, RootFS));
+ if (Type == ::ELFLoader::ELFContainer::TYPE_NONE) {
+ Type = ::ELFLoader::ELFContainer::GetELFType(Entry);
+ }
+ if (Type == ::ELFLoader::ELFContainer::TYPE_OTHER_ELF) {
+ continue;
+ }
+ }
+ if (!Result.empty()) {
+ Result += ':';
+ }
+ Result += Entry;
+ }
+ return Result;
+ }
+
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) {
// If the path is relative then just run that
if (File[0] != '/') {
@@ -330,6 +356,13 @@ public:
if (envp[i] == nullptr) {
break;
}
+ if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
+ auto Preload = GuestPreload(envp[i] + 11, RootFS);
+ if (!Preload.empty()) {
+ EnvironmentVariables.emplace_back("LD_PRELOAD=" + Preload);
+ }
+ continue;
+ }
EnvironmentVariables.emplace_back(envp[i]);
}
}
@@ -0,0 +1,15 @@
diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json
index d52ff04..886379a 100644
--- a/Data/ThunksDB.json
+++ b/Data/ThunksDB.json
@@ -6,7 +6,9 @@
"@PREFIX_LIB@/libGL.so",
"@PREFIX_LIB@/libGL.so.1",
"@PREFIX_LIB@/libGL.so.1.2.0",
- "@PREFIX_LIB@/libGL.so.1.7.0"
+ "@PREFIX_LIB@/libGL.so.1.7.0",
+ "@PREFIX_LIB@/libOpenGL.so.0",
+ "@PREFIX_LIB@/libOpenGL.so.0.0.0"
]
},
"Vulkan": {
@@ -0,0 +1,106 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
index 4c3be85..e287cd2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
@@ -209,6 +209,13 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1,
}
#endif
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough0(FEXCore::Core::CpuStateFrame* Frame) {
+ uint64_t Result = ::syscall(syscall_num);
+ SYSCALL_ERRNO();
+}
+
template<int syscall_num>
requires (syscall_num != -1)
uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) {
@@ -278,29 +285,29 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>);
REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>);
REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>);
- REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
+ REGISTER_SYSCALL_IMPL(fchown, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>);
REGISTER_SYSCALL_IMPL(umask, SyscallPassthrough1<SYSCALL_DEF(umask)>);
- REGISTER_SYSCALL_IMPL(getuid, SyscallPassthrough0<SYSCALL_DEF(getuid)>);
+ REGISTER_SYSCALL_IMPL(getuid, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>);
REGISTER_SYSCALL_IMPL(syslog, SyscallPassthrough3<SYSCALL_DEF(syslog)>);
- REGISTER_SYSCALL_IMPL(getgid, SyscallPassthrough0<SYSCALL_DEF(getgid)>);
- REGISTER_SYSCALL_IMPL(setuid, SyscallPassthrough1<SYSCALL_DEF(setuid)>);
- REGISTER_SYSCALL_IMPL(setgid, SyscallPassthrough1<SYSCALL_DEF(setgid)>);
- REGISTER_SYSCALL_IMPL(geteuid, SyscallPassthrough0<SYSCALL_DEF(geteuid)>);
- REGISTER_SYSCALL_IMPL(getegid, SyscallPassthrough0<SYSCALL_DEF(getegid)>);
+ REGISTER_SYSCALL_IMPL(getgid, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>);
+ REGISTER_SYSCALL_IMPL(setuid, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>);
+ REGISTER_SYSCALL_IMPL(setgid, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>);
+ REGISTER_SYSCALL_IMPL(geteuid, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>);
+ REGISTER_SYSCALL_IMPL(getegid, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>);
REGISTER_SYSCALL_IMPL(setpgid, SyscallPassthrough2<SYSCALL_DEF(setpgid)>);
REGISTER_SYSCALL_IMPL(getppid, SyscallPassthrough0<SYSCALL_DEF(getppid)>);
REGISTER_SYSCALL_IMPL(setsid, SyscallPassthrough0<SYSCALL_DEF(setsid)>);
- REGISTER_SYSCALL_IMPL(setreuid, SyscallPassthrough2<SYSCALL_DEF(setreuid)>);
- REGISTER_SYSCALL_IMPL(setregid, SyscallPassthrough2<SYSCALL_DEF(setregid)>);
- REGISTER_SYSCALL_IMPL(getgroups, SyscallPassthrough2<SYSCALL_DEF(getgroups)>);
- REGISTER_SYSCALL_IMPL(setgroups, SyscallPassthrough2<SYSCALL_DEF(setgroups)>);
- REGISTER_SYSCALL_IMPL(setresuid, SyscallPassthrough3<SYSCALL_DEF(setresuid)>);
- REGISTER_SYSCALL_IMPL(getresuid, SyscallPassthrough3<SYSCALL_DEF(getresuid)>);
- REGISTER_SYSCALL_IMPL(setresgid, SyscallPassthrough3<SYSCALL_DEF(setresgid)>);
- REGISTER_SYSCALL_IMPL(getresgid, SyscallPassthrough3<SYSCALL_DEF(getresgid)>);
+ REGISTER_SYSCALL_IMPL(setreuid, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>);
+ REGISTER_SYSCALL_IMPL(setregid, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>);
+ REGISTER_SYSCALL_IMPL(getgroups, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>);
+ REGISTER_SYSCALL_IMPL(setgroups, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>);
+ REGISTER_SYSCALL_IMPL(setresuid, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>);
+ REGISTER_SYSCALL_IMPL(getresuid, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>);
+ REGISTER_SYSCALL_IMPL(setresgid, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>);
+ REGISTER_SYSCALL_IMPL(getresgid, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>);
REGISTER_SYSCALL_IMPL(getpgid, SyscallPassthrough1<SYSCALL_DEF(getpgid)>);
- REGISTER_SYSCALL_IMPL(setfsuid, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>);
- REGISTER_SYSCALL_IMPL(setfsgid, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>);
+ REGISTER_SYSCALL_IMPL(setfsuid, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>);
+ REGISTER_SYSCALL_IMPL(setfsgid, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>);
REGISTER_SYSCALL_IMPL(getsid, SyscallPassthrough1<SYSCALL_DEF(getsid)>);
REGISTER_SYSCALL_IMPL(capget, SyscallPassthrough2<SYSCALL_DEF(capget)>);
REGISTER_SYSCALL_IMPL(capset, SyscallPassthrough2<SYSCALL_DEF(capset)>);
@@ -537,23 +544,23 @@ namespace x64 {
namespace x32 {
void RegisterPassthrough(FEX::HLE::SyscallHandler* Handler) {
RegisterCommon(Handler);
- REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPassthrough0<SYSCALL_DEF(getuid)>);
- REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPassthrough0<SYSCALL_DEF(getgid)>);
- REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPassthrough0<SYSCALL_DEF(geteuid)>);
- REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPassthrough0<SYSCALL_DEF(getegid)>);
- REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPassthrough2<SYSCALL_DEF(setreuid)>);
- REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPassthrough2<SYSCALL_DEF(setregid)>);
- REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPassthrough2<SYSCALL_DEF(getgroups)>);
- REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPassthrough2<SYSCALL_DEF(setgroups)>);
- REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
- REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPassthrough3<SYSCALL_DEF(setresuid)>);
- REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPassthrough3<SYSCALL_DEF(getresuid)>);
- REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPassthrough3<SYSCALL_DEF(setresgid)>);
- REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPassthrough3<SYSCALL_DEF(getresgid)>);
- REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPassthrough1<SYSCALL_DEF(setuid)>);
- REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPassthrough1<SYSCALL_DEF(setgid)>);
- REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>);
- REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>);
+ REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>);
+ REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>);
+ REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>);
+ REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>);
+ REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>);
+ REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>);
+ REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>);
+ REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>);
+ REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>);
+ REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>);
+ REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>);
+ REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>);
+ REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>);
REGISTER_SYSCALL_IMPL_X32(sendfile64, SyscallPassthrough4<SYSCALL_DEF(sendfile)>);
REGISTER_SYSCALL_IMPL_X32(clock_gettime64, SyscallPassthrough2<SYSCALL_DEF(clock_gettime)>);
REGISTER_SYSCALL_IMPL_X32(clock_settime64, SyscallPassthrough2<SYSCALL_DEF(clock_settime)>);
+84
View File
@@ -0,0 +1,84 @@
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <ucontext.h>
#include <unistd.h>
volatile long base;
static volatile long hits, matched, stale, stop;
static long want;
static pid_t target;
extern char probe_loop_start[], probe_loop_end[];
static void handler(int sig, siginfo_t *info, void *context) {
greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs;
(void)sig;
(void)info;
if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) {
long below = base - g[REG_RSP];
if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L &&
g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 &&
(below == 0 || below == 8))
matched++;
else
stale++;
}
hits++;
}
static void *sender(void *arg) {
(void)arg;
while (!stop) {
syscall(SYS_tgkill, getpid(), target, SIGUSR1);
usleep(50);
}
return NULL;
}
int main(int argc, char **argv) {
struct sigaction action = {0};
pthread_t thread;
want = argc > 1 ? atol(argv[1]) : 2000;
action.sa_sigaction = handler;
action.sa_flags = SA_SIGINFO | SA_RESTART;
sigaction(SIGUSR1, &action, NULL);
sigset_t usr1;
sigemptyset(&usr1);
sigaddset(&usr1, SIGUSR1);
pthread_sigmask(SIG_UNBLOCK, &usr1, NULL);
target = syscall(SYS_gettid);
if (pthread_create(&thread, NULL, sender, NULL) != 0) {
fprintf(stderr, "cannot start the signal sender\n");
return 2;
}
while (matched + stale < want) {
__asm__ volatile("mov $0x1111111111111111, %%rbx\n"
"mov $0x2222222222222222, %%r12\n"
"mov $0x3333333333333333, %%r13\n"
"mov $0x4444444444444444, %%r14\n"
"mov $0x5555555555555555, %%r15\n"
"mov %%rsp, base(%%rip)\n"
"mov $4096, %%ecx\n"
".globl probe_loop_start\n"
"probe_loop_start:\n"
"push %%rax\n"
"1: dec %%ecx\n"
"jnz 1b\n"
"pop %%rax\n"
"mov $4096, %%ecx\n"
"2: dec %%ecx\n"
"jnz 2b\n"
".globl probe_loop_end\n"
"probe_loop_end:\n"
:
:
: "rbx", "rcx", "r12", "r13", "r14", "r15", "memory");
}
stop = 1;
pthread_join(thread, NULL);
printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale);
return stale ? 1 : 0;
}
+90
View File
@@ -0,0 +1,90 @@
#define _GNU_SOURCE
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static sigjmp_buf main_env, inner_env;
static volatile int depth, nested_mode;
static volatile long escapes, nested, returns, wrong;
static void fault(long i) {
*(volatile int *)(long)(8 + (i & 7)) = 1;
}
static void segv(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)info;
(void)context;
if (!nested_mode) {
escapes++;
siglongjmp(main_env, 1);
}
if (depth == 1) {
nested++;
siglongjmp(inner_env, 1);
}
depth = 1;
for (volatile int k = 0; k < 3; k++)
if (sigsetjmp(inner_env, 0) == 0)
fault(k);
depth = 0;
escapes++;
siglongjmp(main_env, 1);
}
static void trap(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)info;
(void)context;
returns++;
}
static void install(int onstack) {
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_sigaction = segv;
action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0);
sigaction(SIGSEGV, &action, NULL);
}
static long run(long count, int with_trap) {
long start = escapes;
for (volatile long i = 0; i < count; i++) {
if (with_trap) {
volatile long before = i * 3;
__asm__ volatile("int3" ::: "memory");
if (before != i * 3)
wrong++;
}
if (sigsetjmp(main_env, 1) == 0)
fault(i);
}
return escapes - start;
}
int main(int argc, char **argv) {
long want = argc > 1 ? atol(argv[1]) : 50000;
stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144};
struct sigaction action;
sigaltstack(&ss, NULL);
memset(&action, 0, sizeof(action));
action.sa_sigaction = trap;
action.sa_flags = SA_SIGINFO;
sigaction(SIGTRAP, &action, NULL);
install(1);
long onstack = run(want, 0);
install(0);
long offstack = run(want, 0);
install(1);
long mixed = run(want, 1);
nested_mode = 1;
long outer = run(want, 0);
printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns,
outer, nested, wrong);
return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0
: 1;
}
+88
View File
@@ -0,0 +1,88 @@
#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <ucontext.h>
#define MARK 0x5eed
static volatile sig_atomic_t alarms;
static volatile sig_atomic_t give_up;
static void count_alarm(void) {
if (++alarms > 100) {
give_up = 1;
}
}
static void on_alarm(int sig, siginfo_t *si, void *ctx) {
(void)sig;
(void)si;
ucontext_t *uc = ctx;
count_alarm();
#ifdef __x86_64__
uc->uc_mcontext.gregs[REG_R12] = MARK;
#else
uc->uc_mcontext.gregs[REG_ESI] = MARK;
#endif
}
#ifdef __i386__
static void on_alarm_legacy(int sig, struct sigcontext sc) {
(void)sig;
count_alarm();
((volatile struct sigcontext *)&sc)->esi = MARK;
}
#endif
int main(int argc, char **argv) {
int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_RESTART;
#ifdef __i386__
if (legacy) {
sa.sa_handler = (void (*)(int))on_alarm_legacy;
} else
#endif
{
legacy = 0;
sa.sa_sigaction = on_alarm;
sa.sa_flags |= SA_SIGINFO;
}
sigaction(SIGALRM, &sa, NULL);
struct itimerval it = {{0, 20000}, {0, 20000}};
setitimer(ITIMER_REAL, &it, NULL);
unsigned long spins, seen;
#ifdef __x86_64__
__asm__ volatile("xor %%r12, %%r12\n"
"xor %0, %0\n"
"1: inc %0\n"
"test %%r12, %%r12\n"
"jnz 2f\n"
"cmpl $0, %2\n"
"je 1b\n"
"2: mov %%r12, %1\n"
: "=&r"(spins), "=&r"(seen)
: "m"(give_up)
: "r12", "cc");
#else
__asm__ volatile("xor %%esi, %%esi\n"
"xor %0, %0\n"
"1: inc %0\n"
"test %%esi, %%esi\n"
"jnz 2f\n"
"cmpl $0, %2\n"
"je 1b\n"
"2: mov %%esi, %1\n"
: "=&r"(spins), "=&r"(seen)
: "m"(give_up)
: "esi", "cc");
#endif
struct itimerval off = {{0, 0}, {0, 0}};
setitimer(ITIMER_REAL, &off, NULL);
printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins);
return seen == MARK ? 0 : 1;
}
+65
View File
@@ -0,0 +1,65 @@
#define _GNU_SOURCE
#include <cpuid.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#define YMM_STEP(a, b) "vpaddq %%ymm" #b ", %%ymm" #a ", %%ymm" #a "\n"
#define MMX_STEP(a, b) "paddq %%mm" #b ", %%mm" #a "\n"
static int has_avx2(void) {
unsigned a, b, c, d;
if (!__get_cpuid(1, &a, &b, &c, &d) || !(c & bit_AVX) || !(c & bit_OSXSAVE))
return 0;
unsigned lo, hi;
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
if ((lo & 6) != 6 || !__get_cpuid_count(7, 0, &a, &b, &c, &d))
return 0;
return (b & bit_AVX2) != 0;
}
static long ymm_round(long n) {
long pid = 0;
for (long i = 0; i < n; i++) {
__asm__ volatile(
YMM_STEP(0, 1) YMM_STEP(1, 2) YMM_STEP(2, 3) YMM_STEP(3, 4) YMM_STEP(4, 5) YMM_STEP(5, 6) YMM_STEP(6, 7) YMM_STEP(7, 8)
YMM_STEP(8, 9) YMM_STEP(9, 10) YMM_STEP(10, 11) YMM_STEP(11, 12) YMM_STEP(12, 13) YMM_STEP(13, 14) YMM_STEP(14, 15)
YMM_STEP(15, 0) YMM_STEP(0, 15) YMM_STEP(1, 14) YMM_STEP(2, 13) YMM_STEP(3, 12) YMM_STEP(4, 11) YMM_STEP(5, 10)
YMM_STEP(6, 9) YMM_STEP(7, 8)
"mov %1, %%eax\n"
"syscall\n"
: "=a"(pid)
: "i"(SYS_getpid)
: "rcx", "r11", "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10",
"xmm11", "xmm12", "xmm13", "xmm14", "xmm15");
}
__asm__ volatile("vzeroupper" ::: "memory");
return pid;
}
static long mmx_round(long n) {
long pid = 0;
for (long i = 0; i < n; i++) {
__asm__ volatile(
MMX_STEP(0, 1) MMX_STEP(1, 2) MMX_STEP(2, 3) MMX_STEP(3, 4) MMX_STEP(4, 5) MMX_STEP(5, 6) MMX_STEP(6, 7) MMX_STEP(7, 0)
"mov %1, %%eax\n"
"syscall\n"
: "=a"(pid)
: "i"(SYS_getpid)
: "rcx", "r11", "memory", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7");
}
__asm__ volatile("emms" ::: "memory");
return pid;
}
int main(int argc, char **argv) {
long want = argc > 1 ? atol(argv[1]) : 2000000;
int avx = has_avx2();
long done = 0;
for (; done < want; done += 1000) {
if (avx ? ymm_round(1000) <= 0 : mmx_round(1000) <= 0)
return 2;
}
printf("mode=%s syscalls=%ld\n", avx ? "avx" : "mmx", done);
return 0;
}
+49
View File
@@ -0,0 +1,49 @@
#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
static volatile sig_atomic_t alarms;
static void on_alarm(int sig) {
(void)sig;
alarms++;
}
int main(int argc, char **argv) {
int seconds = argc > 1 ? atoi(argv[1]) : 3;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_alarm;
sa.sa_flags = SA_RESTART;
sigaction(SIGALRM, &sa, NULL);
struct itimerval it = {{0, 1000}, {0, 1000}};
setitimer(ITIMER_REAL, &it, NULL);
struct timespec start, now, last;
clock_gettime(CLOCK_MONOTONIC, &start);
last = start;
unsigned long calls = 0, bad = 0;
unsigned long a = 1, b = 3, c = 1 ^ 0x5a5a5a5a5a5a5a5aUL;
do {
clock_gettime(CLOCK_MONOTONIC, &now);
calls++;
__asm__ volatile("" : "+r"(a), "+r"(b), "+r"(c));
if (b != a * 3 || c != (a ^ 0x5a5a5a5a5a5a5a5aUL))
bad++;
if (now.tv_sec < last.tv_sec || (now.tv_sec == last.tv_sec && now.tv_nsec < last.tv_nsec))
bad++;
last = now;
a = a * 6364136223846793005UL + 1442695040888963407UL;
b = a * 3;
c = a ^ 0x5a5a5a5a5a5a5a5aUL;
} while ((now.tv_sec - start.tv_sec) * 1000000000L + (now.tv_nsec - start.tv_nsec) < seconds * 1000000000L);
struct itimerval off = {{0, 0}, {0, 0}};
setitimer(ITIMER_REAL, &off, NULL);
printf("calls=%lu alarms=%d bad=%lu\n", calls, (int)alarms, bad);
return bad || alarms == 0;
}
+58
View File
@@ -358,3 +358,61 @@ and clears the held flag. wlroots counts repeated presses of one button and send
reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the
game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no
earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch.
## 0135 Wayland backend: a limit on the planes handed to the host
`wayland_overlay_planes` says how many planes above the base one the host compositor shows without composing them
itself. With more layers than that, gamescope composites them into one picture, as it already does for a scaler or
`composite_force`. -1, the default, keeps every layer on its own plane. The app sets it while a host that shows the
game picture directly cannot give an overlay a display layer of its own, so the overlay is drawn into the game
picture here and the frame still reaches the display without a copy.
## 0136 rendervulkan, Wayland backend: composite only into output images the host has released
The composite output images were used in a fixed rotation of three, with no check that the host compositor had
released the one about to be written. A host that puts the buffer on the display itself, without copying it, was
still reading that image when the next composite wrote into it. A backend framebuffer now says whether the host
holds it, the Wayland backend answers from the buffer's release event, and the composite takes the next image the
host does not hold. Backends that are not a session get five images instead of three, so one is free while the
host holds two and the last and deferred pictures stay intact. Session backends keep three images and their order.
## 0137 Wayland backend: the host's refresh rates and the app's target
A nested session had one refresh rate, the host's, so Steam offered no refresh control and a frame limit never moved
the display. The backend binds the host's `droiddeck_refresh_v1`, takes the list of rates the host display can switch
between and returns it as the connector's dynamic refresh rates, so the rates reach Steam with the rest of the
display state and are sent again when the list changes. On every present it tells the host the refresh rate the
frame limit resolves to and the limit itself; the host switches its display and the new rate comes back through
`wl_output`, which the nested refresh already follows. A host without the global leaves all of this as it was.
## 0138 Frame limiter: a limit the refresh rate does not divide is spread evenly
The limiter held a window for a whole number of refreshes, the refresh rate divided by the limit and rounded down. A
limit of 45 or 40 on a 60 Hz display rounded to one refresh per frame, so the limit did nothing, and each frame was
timed from the moment the previous one was shown, so a late frame pushed every frame after it. The limited cycle is
now the exact time between frames at the limit, and each window keeps the time its next frame is due on that line.
A frame is released on the refresh nearest its due time: 45 on 60 Hz shows frames for one, one and two refreshes in
turn, 40 for one and two, and a limit that divides the refresh rate is paced as before. A frame that arrives most of a
refresh late, or more than a refresh early, starts the line again from that frame, so a stall is not followed by a
burst. `tools/tests/test_gamescope_limiter_cadence.py` compiles the two rules from this patch and runs them across
refresh rates and limits.
## 0139 HDR output can be switched while a session runs
The Wayland backend read `hdr_enabled` once, when the host compositor described its output, and kept the answer: a
session started with HDR off told its clients the display had no HDR for as long as it ran, and its environment
carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's output description alone, and
`hdr_enabled` decides only whether HDR is used, so setting it during a session takes effect on the next frame in
either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit
output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of
forcing it to 0, so a game started after HDR is switched on finds it.
## 0140 Focus is chosen again when a window turns visible or fully transparent
A window is a focus candidate only while its `_NET_WM_WINDOW_OPACITY` is above zero, but a change of that property
did not ask for focus to be chosen again. Wine sets the property for layered windows, and a window that fades in maps
fully transparent, so it was skipped when it mapped and stayed skipped once it was opaque until something else
changed focus. In a nested session with no other window the SDL window stayed hidden, and the game ran with nothing
on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between
two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this
patch and checks the property handler applies it.
@@ -0,0 +1,20 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 372fc08..fe38c7d 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -126,6 +126,7 @@ namespace gamescope
gamescope::ConVar<bool> cv_wayland_mouse_warp_without_keyboard_focus( "wayland_mouse_warp_without_keyboard_focus", true, "Should we only forward mouse warps to the app when we have keyboard focus?" );
gamescope::ConVar<bool> cv_wayland_mouse_relmotion_without_keyboard_focus( "wayland_mouse_relmotion_without_keyboard_focus", false, "Should we only forward mouse relative motion to the app when we have keyboard focus?" );
gamescope::ConVar<bool> cv_wayland_use_modifiers( "wayland_use_modifiers", true, "Use DMA-BUF modifiers?" );
+ gamescope::ConVar<int> cv_wayland_overlay_planes( "wayland_overlay_planes", -1, "How many planes above the base one the host shows without composing them itself; more are composited here into one. -1 for no limit." );
gamescope::ConVar<float> cv_wayland_hdr10_saturation_scale( "wayland_hdr10_saturation_scale", 1.0, "Saturation scale for HDR10 content by gamut expansion. 1.0 - 1.2 is a good range to play with." );
@@ -1102,6 +1103,7 @@ namespace gamescope
eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize;
bNeedsFullComposite |= cv_composite_force;
+ bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes;
bNeedsFullComposite |= pFrameInfo->useFSRLayer0;
bNeedsFullComposite |= pFrameInfo->useNISLayer0;
bNeedsFullComposite |= pFrameInfo->useSGSRLayer0;
@@ -0,0 +1,218 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index fe38c7d..be99e6d 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -503,6 +503,8 @@ namespace gamescope
wl_buffer *GetHostBuffer() const { return m_pHostBuffer; }
wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; }
+ bool HeldByHost() const override { return m_bCompositorAcquired; }
+
void Wayland_Buffer_Release( wl_buffer *pBuffer );
static const wl_buffer_listener s_BufferListener;
diff --git a/src/backend.h b/src/backend.h
index fbfa7c7..30b42ca 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -288,6 +288,8 @@ namespace gamescope
virtual void SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint ) = 0;
virtual IBackendFb *EnsureImported() = 0;
+
+ virtual bool HeldByHost() const { return false; }
};
class IBackendPlane
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 0835bfe..42cc9c4 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -3644,15 +3644,12 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
outputImageflags.bSampled = true; // for pipewire blits
outputImageflags.bOutputImage = true;
- pOutput->outputImages.resize(3); // extra image for partial composition.
- pOutput->outputImagesPartialOverlay.resize(3);
+ const uint32_t uImageCount = GetBackend()->IsSessionBased() ? 3u : 5u;
- pOutput->outputImages[0] = nullptr;
- pOutput->outputImages[1] = nullptr;
- pOutput->outputImages[2] = nullptr;
- pOutput->outputImagesPartialOverlay[0] = nullptr;
- pOutput->outputImagesPartialOverlay[1] = nullptr;
- pOutput->outputImagesPartialOverlay[2] = nullptr;
+ pOutput->outputImages.clear();
+ pOutput->outputImagesPartialOverlay.clear();
+ pOutput->outputImages.resize( uImageCount );
+ pOutput->outputImagesPartialOverlay.resize( uImageCount );
uint32_t uDRMFormat = pOutput->uOutputFormat;
@@ -3662,28 +3659,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
if ( g_uOutputRotation & 1u )
std::swap( uOutputWidth, uOutputHeight );
- pOutput->outputImages[0] = new CVulkanTexture();
- bool bSuccess = pOutput->outputImages[0]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags );
- if ( bSuccess != true )
- {
- vk_log.errorf( "failed to allocate buffer for KMS" );
- return false;
- }
-
- pOutput->outputImages[1] = new CVulkanTexture();
- bSuccess = pOutput->outputImages[1]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags );
- if ( bSuccess != true )
+ for ( uint32_t i = 0; i < uImageCount; i++ )
{
- vk_log.errorf( "failed to allocate buffer for KMS" );
- return false;
- }
-
- pOutput->outputImages[2] = new CVulkanTexture();
- bSuccess = pOutput->outputImages[2]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags );
- if ( bSuccess != true )
- {
- vk_log.errorf( "failed to allocate buffer for KMS" );
- return false;
+ pOutput->outputImages[i] = new CVulkanTexture();
+ if ( !pOutput->outputImages[i]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ) )
+ {
+ vk_log.errorf( "failed to allocate buffer for KMS" );
+ return false;
+ }
}
// Oh no.
@@ -3696,28 +3679,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
{
uint32_t uPartialDRMFormat = pOutput->uOutputFormatOverlay;
- pOutput->outputImagesPartialOverlay[0] = new CVulkanTexture();
- bool bSuccess = pOutput->outputImagesPartialOverlay[0]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[0].get() );
- if ( bSuccess != true )
- {
- vk_log.errorf( "failed to allocate buffer for KMS" );
- return false;
- }
-
- pOutput->outputImagesPartialOverlay[1] = new CVulkanTexture();
- bSuccess = pOutput->outputImagesPartialOverlay[1]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[1].get() );
- if ( bSuccess != true )
+ for ( uint32_t i = 0; i < uImageCount; i++ )
{
- vk_log.errorf( "failed to allocate buffer for KMS" );
- return false;
- }
-
- pOutput->outputImagesPartialOverlay[2] = new CVulkanTexture();
- bSuccess = pOutput->outputImagesPartialOverlay[2]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[2].get() );
- if ( bSuccess != true )
- {
- vk_log.errorf( "failed to allocate buffer for KMS" );
- return false;
+ pOutput->outputImagesPartialOverlay[i] = new CVulkanTexture();
+ if ( !pOutput->outputImagesPartialOverlay[i]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[i].get() ) )
+ {
+ vk_log.errorf( "failed to allocate buffer for KMS" );
+ return false;
+ }
}
}
@@ -3755,6 +3724,8 @@ bool vulkan_remake_output_images()
g_device.waitIdle();
pOutput->nOutImage = 0;
+ pOutput->nLastOutImage = 0;
+ pOutput->nDeferredOutImage = 0;
// Delete screenshot/capture textures to be remade if needed
for (auto& pScreenshotTexture : pOutput->pScreenshotTextures)
@@ -4604,6 +4575,30 @@ namespace
ReshadeEffectPipeline *g_pLastReshadeEffect = nullptr;
+static bool vulkan_output_image_held( uint32_t nImage )
+{
+ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } )
+ {
+ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && pImage->GetBackendFb()->HeldByHost() )
+ return true;
+ }
+ return false;
+}
+
+static uint32_t vulkan_free_output_image( uint32_t nFirst )
+{
+ const uint32_t uCount = g_output.outputImages.size();
+ for ( uint32_t i = 0; i < uCount; i++ )
+ {
+ const uint32_t nImage = ( nFirst + i ) % uCount;
+ if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) )
+ continue;
+ if ( !vulkan_output_image_held( nImage ) )
+ return nImage;
+ }
+ return nFirst;
+}
+
std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc<CVulkanTexture> pPipewireTexture, bool partial, gamescope::Rc<CVulkanTexture> pOutputOverride, bool increment, std::unique_ptr<CVulkanCmdBuffer> pInCommandBuffer )
{
EOTF outputTF = frameInfo->outputEncodingEOTF;
@@ -4643,6 +4638,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
if ( !pOutputOverride && !vulkan_ensure_output_images() )
return std::nullopt;
+ if ( !pOutputOverride && !GetBackend()->UsesVulkanSwapchain() )
+ g_output.nOutImage = vulkan_free_output_image( g_output.nOutImage );
+
gamescope::Rc<CVulkanTexture> compositeImage;
if ( pOutputOverride )
compositeImage = pOutputOverride;
@@ -4877,7 +4875,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
if ( !GetBackend()->UsesVulkanSwapchain() && pOutputOverride == nullptr && increment )
{
- g_output.nOutImage = ( g_output.nOutImage + 1 ) % 3;
+ g_output.nDeferredOutImage = g_output.nLastOutImage;
+ g_output.nLastOutImage = g_output.nOutImage;
+ g_output.nOutImage = ( g_output.nOutImage + 1 ) % g_output.outputImages.size();
}
return sequence;
@@ -4931,19 +4931,7 @@ bool vulkan_format_supports_features(VkFormat format, VkFormatFeatureFlags featu
gamescope::Rc<CVulkanTexture> vulkan_get_last_output_image( bool partial, bool defer )
{
- // Get previous image ( +2 )
- // 1 2 3
- // |
- // |
- uint32_t nRegularImage = ( g_output.nOutImage + 2 ) % 3;
-
- // Get previous previous image ( +1 )
- // 1 2 3
- // |
- // |
- uint32_t nDeferredImage = ( g_output.nOutImage + 1 ) % 3;
-
- uint32_t nOutImage = defer ? nDeferredImage : nRegularImage;
+ uint32_t nOutImage = defer ? g_output.nDeferredOutImage : g_output.nLastOutImage;
if ( partial )
{
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index e0ede11..8ae3b71 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -591,6 +591,8 @@ struct VulkanOutput_t
std::vector<gamescope::OwningRc<CVulkanTexture>> presentationImages;
uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs
+ uint32_t nLastOutImage = 0;
+ uint32_t nDeferredOutImage = 0;
std::vector<gamescope::OwningRc<CVulkanTexture>> outputImages;
std::vector<gamescope::OwningRc<CVulkanTexture>> outputImagesPartialOverlay;
gamescope::OwningRc<CVulkanTexture> temporaryHackyBlankImage;
@@ -0,0 +1,293 @@
diff --git a/protocol/droiddeck-refresh-v1.xml b/protocol/droiddeck-refresh-v1.xml
new file mode 100644
index 0000000..c4464a0
--- /dev/null
+++ b/protocol/droiddeck-refresh-v1.xml
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="droiddeck_refresh_v1">
+ <copyright>
+ Copyright 2026 DroidDeck contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice (including the next
+ paragraph) shall be included in all copies or substantial portions of the
+ Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ </copyright>
+
+ <interface name="droiddeck_refresh_v1" version="1">
+ <description summary="panel refresh rates a nested compositor may ask for">
+ A nested compositor paces its clients against the refresh rate of the
+ panel it is shown on. When its clients are held to a frame rate the
+ panel's current rate does not divide evenly, frames are shown for an
+ uneven number of refreshes. This interface lets the nested compositor
+ see every refresh rate the panel can run at its current size and ask
+ for the one that suits the frame rate it is pacing to.
+
+ On bind the compositor sends one rate event per refresh rate, lowest
+ first, followed by done. The list is sent again, in full, whenever it
+ changes (a different panel, or a limit the user placed on the panel's
+ rate). The rate the panel is running at is still reported the standard
+ way, through wl_output.mode.
+
+ A request is a preference, not a guarantee: the user, the platform or
+ another output mirroring the panel may hold the panel at another rate.
+ The client reads the result from wl_output.mode.
+ </description>
+
+ <request name="destroy" type="destructor">
+ <description summary="destroy the object">
+ The preference set through this object is dropped.
+ </description>
+ </request>
+
+ <request name="set_target">
+ <description summary="ask for a refresh rate">
+ refresh is the panel rate the client would like, in Hz, taken from
+ the advertised list; 0 withdraws the preference. frame_rate is the
+ frame rate the client holds its content to, in frames per second, or
+ 0 when the content is not held to a rate. The compositor may multiply
+ the content's frame rate itself (generated frames); when it does, it
+ picks the advertised rate that the multiplied frame rate divides
+ evenly instead of the requested one.
+ </description>
+ <arg name="refresh" type="uint" summary="wanted panel refresh rate in Hz, 0 for none"/>
+ <arg name="frame_rate" type="uint" summary="content frame rate in frames per second, 0 for unpaced"/>
+ </request>
+
+ <event name="rate">
+ <description summary="a refresh rate the panel can run">
+ Sent once per rate, lowest first, in Hz rounded to the nearest whole
+ number.
+ </description>
+ <arg name="refresh" type="uint" summary="panel refresh rate in Hz"/>
+ </event>
+
+ <event name="done">
+ <description summary="the list of rates is complete">
+ Ends a list of rate events. The rates received since the previous
+ done replace the earlier list.
+ </description>
+ </event>
+ </interface>
+</protocol>
diff --git a/protocol/meson.build b/protocol/meson.build
index cf8fbd1..71fe31b 100644
--- a/protocol/meson.build
+++ b/protocol/meson.build
@@ -43,6 +43,8 @@ protocols = [
'gamescope-private.xml',
'gamescope-action-binding.xml',
+ 'droiddeck-refresh-v1.xml',
+
# wlroots protocols
'wlr-layer-shell-unstable-v1.xml',
]
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index be99e6d..9862641 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -38,6 +38,7 @@
#include <primary-selection-unstable-v1-client-protocol.h>
#include <fractional-scale-v1-client-protocol.h>
#include <xdg-toplevel-icon-v1-client-protocol.h>
+#include <droiddeck-refresh-v1-client-protocol.h>
#include "wlr_end.hpp"
#include "drm_include.h"
@@ -705,6 +706,10 @@ namespace gamescope
virtual bool UsesVulkanSwapchain() const override;
virtual bool IsSessionBased() const override;
+ virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override;
+
+ std::span<const uint32_t> GetHostRefreshRates() const;
+ void SyncHostRefreshTarget();
virtual bool SupportsExplicitSync() const override;
virtual bool IsPaused() const override;
@@ -778,6 +783,10 @@ namespace gamescope
void Wayland_Output_Geometry( wl_output *pOutput, int32_t nX, int32_t nY, int32_t nPhysicalWidth, int32_t nPhysicalHeight, int32_t nSubpixel, const char *pMake, const char *pModel, int32_t nTransform );
void Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh );
void Wayland_Output_Done( wl_output *pOutput );
+
+ void Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh );
+ void Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh );
+ static const droiddeck_refresh_v1_listener s_RefreshListener;
void Wayland_Output_Scale( wl_output *pOutput, int32_t nFactor );
void Wayland_Output_Name( wl_output *pOutput, const char *pName );
void Wayland_Output_Description( wl_output *pOutput, const char *pDescription );
@@ -829,6 +838,12 @@ namespace gamescope
OwningRc<CWaylandFb> m_pOwnedBlackFb;
OwningRc<CVulkanTexture> m_pBlackTexture;
wp_presentation *m_pPresentation = nullptr;
+ droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
+ std::array<uint32_t, 16> m_HostRefreshRates{};
+ std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
+ std::vector<uint32_t> m_PendingHostRefreshRates;
+ int m_nSentHostRefresh = 0;
+ int m_nSentHostFrameRate = 0;
frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr;
wp_color_manager_v1 *m_pWPColorManager = nullptr;
wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{};
@@ -890,6 +905,11 @@ namespace gamescope
.global = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Registry_Global ),
.global_remove = WAYLAND_NULL(),
};
+ const droiddeck_refresh_v1_listener CWaylandBackend::s_RefreshListener =
+ {
+ .rate = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Rate ),
+ .done = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Done ),
+ };
const wl_output_listener CWaylandBackend::s_OutputListener =
{
.geometry = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Output_Geometry ),
@@ -1087,6 +1107,7 @@ namespace gamescope
{
droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputPresent );
UpdateFullscreenState();
+ m_pBackend->SyncHostRefreshTarget();
bool bNeedsFullComposite = false;
@@ -1244,7 +1265,7 @@ namespace gamescope
}
std::span<const uint32_t> CWaylandConnector::GetValidDynamicRefreshRates() const
{
- return std::span<const uint32_t>{};
+ return m_pBackend->GetHostRefreshRates();
}
void CWaylandConnector::GetNativeColorimetry(
@@ -2396,6 +2417,52 @@ namespace gamescope
return false;
}
+ std::span<const uint32_t> CWaylandBackend::GetHostRefreshRates() const
+ {
+ const uint32_t uCount = m_uHostRefreshRateCount;
+ if ( uCount < 2 )
+ return std::span<const uint32_t>{};
+ return std::span<const uint32_t>{ m_HostRefreshRates.data(), uCount };
+ }
+
+ bool CWaylandBackend::HackTemporarySetDynamicRefresh( int nRefresh )
+ {
+ if ( !m_pHostRefresh )
+ return false;
+ SyncHostRefreshTarget();
+ return true;
+ }
+
+ void CWaylandBackend::SyncHostRefreshTarget()
+ {
+ if ( !m_pHostRefresh )
+ return;
+ const int nFrameRate = steamcompmgr_get_app_target_fps();
+ const int nRefresh = steamcompmgr_get_app_dynamic_refresh();
+ if ( nRefresh == m_nSentHostRefresh && nFrameRate == m_nSentHostFrameRate )
+ return;
+ xdg_log.infof( "Asking the host for %dhz at %dfps", nRefresh, nFrameRate );
+ droiddeck_refresh_v1_set_target( m_pHostRefresh, nRefresh, nFrameRate );
+ m_nSentHostRefresh = nRefresh;
+ m_nSentHostFrameRate = nFrameRate;
+ }
+
+ void CWaylandBackend::Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh )
+ {
+ m_PendingHostRefreshRates.push_back( uRefresh );
+ }
+ void CWaylandBackend::Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh )
+ {
+ std::sort( m_PendingHostRefreshRates.begin(), m_PendingHostRefreshRates.end() );
+ const uint32_t uCount = std::min<size_t>( m_PendingHostRefreshRates.size(), m_HostRefreshRates.size() );
+ m_uHostRefreshRateCount = 0;
+ std::copy_n( m_PendingHostRefreshRates.begin(), uCount, m_HostRefreshRates.begin() );
+ m_uHostRefreshRateCount = uCount;
+ m_PendingHostRefreshRates.clear();
+ steamcompmgr_display_rates_changed();
+ force_repaint();
+ }
+
bool CWaylandBackend::SupportsExplicitSync() const
{
// GAMESCOPE_DISABLE_EXPLICIT_SYNC=1: a kernel without DRM_IOCTL_SYNCOBJ_EVENTFD (before
@@ -2647,6 +2714,11 @@ 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 ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) )
+ {
+ m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u );
+ droiddeck_refresh_v1_add_listener( m_pHostRefresh, &s_RefreshListener, this );
+ }
else if ( !strcmp( pInterface, frog_color_management_factory_v1_interface.name ) )
{
m_pFrogColorMgmtFactory = (frog_color_management_factory_v1 *)wl_registry_bind( pRegistry, uName, &frog_color_management_factory_v1_interface, 1u );
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 38b304b..d7d11b3 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -1229,6 +1229,25 @@ static int g_nCombinedAppRefreshCycleOverride[gamescope::GAMESCOPE_SCREEN_TYPE_C
bool g_nCombinedAppRefreshCycleChangeRefresh[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true };
bool g_nCombinedAppRefreshCycleChangeFPS[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true };
+int steamcompmgr_get_app_target_fps()
+{
+ return g_nSteamCompMgrTargetFPS;
+}
+
+int steamcompmgr_get_app_dynamic_refresh()
+{
+ if ( !GetBackend()->GetCurrentConnector() )
+ return 0;
+ return g_nDynamicRefreshRate[ GetBackend()->GetCurrentConnector()->GetScreenType() ];
+}
+
+static std::atomic<bool> g_bDisplayRatesChanged = { false };
+
+void steamcompmgr_display_rates_changed()
+{
+ g_bDisplayRatesChanged = true;
+}
+
static void _update_app_target_refresh_cycle()
{
if ( !GetBackend()->GetCurrentConnector() )
@@ -9703,7 +9722,8 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush =
*needs_flush = true;
}
- if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || force )
+ const bool bDisplayRatesChanged = g_bDisplayRatesChanged.exchange( false );
+ if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || bDisplayRatesChanged || force )
{
int32_t nRefresh = gamescope::ConvertmHzToHz( g_nOutputRefresh );
XChangeProperty(root_ctx->dpy, root_ctx->root, root_ctx->atoms.gamescopeDisplayRefreshRateFeedback, XA_CARDINAL, 32, PropModeReplace,
diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp
index ff54d8e..9e0bb79 100644
--- a/src/steamcompmgr.hpp
+++ b/src/steamcompmgr.hpp
@@ -202,4 +202,7 @@ MouseCursor *steamcompmgr_get_server_cursor(uint32_t serverId);
extern gamescope::ConVar<bool> cv_tearing_enabled;
+extern int steamcompmgr_get_app_target_fps();
+extern int steamcompmgr_get_app_dynamic_refresh();
+extern void steamcompmgr_display_rates_changed();
extern void steamcompmgr_set_app_refresh_cycle_override( gamescope::GamescopeScreenType type, int override_fps, bool change_refresh, bool change_fps_cap );
@@ -0,0 +1,67 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index d7d11b3..cfec551 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -7188,6 +7188,19 @@ init_runtime_info()
update_runtime_info();
}
+static uint64_t limiter_latch_target( uint64_t ulPreviousTarget, uint64_t ulLatched, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle )
+{
+ const uint64_t ulTarget = ulPreviousTarget + ulLimitedCycle;
+ const bool bLate = ulTarget + ulRefreshCycle * 3 / 4 < ulLatched;
+ const bool bEarly = ulTarget > ulLatched + ulRefreshCycle;
+ return ( bLate || bEarly ) ? ulLatched : ulTarget;
+}
+
+static bool limiter_holds_vblank( uint64_t ulTarget, uint64_t ulNow, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle )
+{
+ return ulNow + ulRefreshCycle / 2 < ulTarget + ulLimitedCycle;
+}
+
static void
steamcompmgr_flush_frame_done( steamcompmgr_win_t *w )
{
@@ -7206,6 +7219,9 @@ steamcompmgr_flush_frame_done( steamcompmgr_win_t *w )
w->last_commit_first_latch_time = timespec_to_nanos(now);
+ w->limiter_latch_target_time = limiter_latch_target( w->limiter_latch_target_time, w->last_commit_first_latch_time,
+ g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle );
+
// Acknowledge commit once.
wlserver_lock();
@@ -7258,8 +7274,7 @@ static bool steamcompmgr_should_vblank_window( bool bShouldLimitFPS, uint64_t vb
{
if ( w && now )
{
- uint64_t schedule = w->last_commit_first_latch_time + g_SteamCompMgrLimitedAppRefreshCycle;
- if ( now + g_SteamCompMgrAppRefreshCycle / 2 < schedule )
+ if ( limiter_holds_vblank( w->limiter_latch_target_time, now, g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ) )
bSendCallback = false;
}
else
@@ -11047,9 +11062,7 @@ steamcompmgr_main(int argc, char **argv)
}
else
{
- int nVblankDivisor = nRealRefreshHz / nTargetFPS;
-
- g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nVblankDivisor;
+ g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS;
}
}
}
diff --git a/src/steamcompmgr_shared.hpp b/src/steamcompmgr_shared.hpp
index 0fcc80b..3c74d62 100644
--- a/src/steamcompmgr_shared.hpp
+++ b/src/steamcompmgr_shared.hpp
@@ -146,6 +146,7 @@ struct steamcompmgr_win_t {
bool outdatedInteractiveFocus = false;
uint64_t last_commit_first_latch_time = 0;
+ uint64_t limiter_latch_target_time = 0;
uint64_t last_commit_present_time = 0;
bool hasHwndStyle = false;
@@ -0,0 +1,54 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 9862641..e9d2923 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -1972,7 +1972,7 @@ namespace gamescope
{
auto *pHDRInfo = &m_pConnector->m_HDRInfo;
if (m_pBackend->SupportsColorManagement()) {
- pHDRInfo->bExposeHDRSupport = ( cv_hdr_enabled && m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance );
+ pHDRInfo->bExposeHDRSupport = ( m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance );
pHDRInfo->eOutputEncodingEOTF = pHDRInfo->bExposeHDRSupport ? EOTF_PQ : EOTF_Gamma22;
}
@@ -2282,7 +2282,7 @@ namespace gamescope
assert( u8BitFormat != DRM_FORMAT_INVALID );
- *pPrimaryPlaneFormat = u10BitFormat != DRM_FORMAT_INVALID ? u10BitFormat : u8BitFormat;
+ *pPrimaryPlaneFormat = ( cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID ) ? u10BitFormat : u8BitFormat;
*pOverlayPlaneFormat = u8BitFormat;
}
@@ -2493,13 +2493,17 @@ namespace gamescope
// XXX: We should do this a better way that handles per-window and appid stuff
// down the line
- if ( cv_hdr_enabled && GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport )
+ if ( !GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport )
+ {
+ setenv( "DXVK_HDR", "0", true );
+ }
+ else if ( cv_hdr_enabled )
{
setenv( "DXVK_HDR", "1", true );
}
else
{
- setenv( "DXVK_HDR", "0", true );
+ unsetenv( "DXVK_HDR" );
}
WritePatchedEdid( GetCurrentConnector()->GetRawEDID(), GetCurrentConnector()->GetHDRInfo(), false );
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 42cc9c4..d0d21f0 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -3735,6 +3735,7 @@ bool vulkan_remake_output_images()
if ( vulkan_defer_output_images() )
{
+ GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );
pOutput->outputImages.clear();
pOutput->outputImagesPartialOverlay.clear();
pOutput->temporaryHackyBlankImage = vulkan_create_debug_blank_texture();
@@ -0,0 +1,32 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index cfec551..e98d320 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -6945,6 +6945,12 @@ handle_system_tray_opcode(xwayland_ctx_t *ctx, XClientMessageEvent *ev)
}
}
+static bool
+opacity_changes_focus_candidacy( unsigned int oldOpacity, unsigned int newOpacity )
+{
+ return ( oldOpacity > TRANSLUCENT ) != ( newOpacity > TRANSLUCENT );
+}
+
/* See http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4 */
static void
handle_wm_change_state(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, XClientMessageEvent *ev)
@@ -7329,8 +7335,14 @@ handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev)
if (newOpacity != w->opacity)
{
+ const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );
w->opacity = newOpacity;
+ if ( bFocusCandidacyChanged )
+ {
+ MakeFocusDirty();
+ }
+
if ( gameFocused && ( w == ctx->focus.overlayWindow || w == ctx->focus.notificationWindow ) )
{
hasRepaintNonBasePlane = true;
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p23
GAMESCOPE_SHA256=f5f2b8f658234ad2910a1be53c238188db7e7b2a9079f8cc5fa9ea006bebbe7e
GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d
GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02
+3 -10
View File
@@ -1,6 +1,5 @@
#!/usr/bin/env bash
# Builds VK_LAYER_DROIDDECK_gpu_load for the arm64 guest: tools/gpuload/build.sh [--native] OUT
# OUT gets libVkLayer_droiddeck_gpuload.so, libVkLayer_droiddeck_vramcap.so and their implicit-layer manifests.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
@@ -36,15 +35,10 @@ cmd=(sh -c '
build/gpuload/test_gpuload_busy
cc -std=c11 -O2 -Wall -Wextra -Werror -Ibuild/gpuload/include -Itools/gpuload/src -o build/gpuload/test_gpuload_ring tools/gpuload/tests/test_gpuload_ring.c
build/gpuload/test_gpuload_ring
cc -std=c11 -O2 -Wall -Wextra -Werror -Ibuild/gpuload/include -Itools/gpuload/src -pthread -Wno-unused-parameter -Wno-missing-field-initializers -o build/gpuload/test_vramcap_budget tools/gpuload/tests/test_vramcap_budget.c
build/gpuload/test_vramcap_budget
aarch64-linux-gnu-gcc -std=c11 -shared -fPIC -O2 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers \
-fvisibility=hidden -pthread -Wl,-z,defs -Ibuild/gpuload/include -Itools/gpuload/src \
-o build/gpuload/out/libVkLayer_droiddeck_gpuload.so tools/gpuload/src/vk_layer_droiddeck_gpuload.c
aarch64-linux-gnu-gcc -std=c11 -shared -fPIC -O2 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers \
-fvisibility=hidden -pthread -Wl,-z,defs -Ibuild/gpuload/include -Itools/gpuload/src \
-o build/gpuload/out/libVkLayer_droiddeck_vramcap.so tools/gpuload/src/vk_layer_droiddeck_vramcap.c
aarch64-linux-gnu-strip --strip-unneeded build/gpuload/out/libVkLayer_droiddeck_gpuload.so build/gpuload/out/libVkLayer_droiddeck_vramcap.so')
aarch64-linux-gnu-strip --strip-unneeded build/gpuload/out/libVkLayer_droiddeck_gpuload.so')
if [ "$native" = 1 ]; then
(cd "$repo" && "${cmd[@]}")
else
@@ -52,8 +46,7 @@ else
"${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}" "${cmd[@]}"
fi
cp "$here/layer/VK_LAYER_DROIDDECK_gpu_load.json" "$here/layer/VK_LAYER_DROIDDECK_vram_cap.json" "$work/out/"
cp "$here/layer/VK_LAYER_DROIDDECK_gpu_load.json" "$work/out/"
mkdir -p "$out"
cp "$work/out/libVkLayer_droiddeck_gpuload.so" "$work/out/libVkLayer_droiddeck_vramcap.so" \
"$work/out/VK_LAYER_DROIDDECK_gpu_load.json" "$work/out/VK_LAYER_DROIDDECK_vram_cap.json" "$out/"
cp "$work/out/libVkLayer_droiddeck_gpuload.so" "$work/out/VK_LAYER_DROIDDECK_gpu_load.json" "$out/"
echo "built $out"
@@ -1,20 +0,0 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_vram_cap",
"type": "GLOBAL",
"library_path": "/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"api_version": "1.3.0",
"implementation_version": "1",
"description": "Reports a smaller video memory budget to DXVK and vkd3d-proton",
"functions": {
"vkNegotiateLoaderLayerInterfaceVersion": "DroidDeckVramCap_NegotiateLoaderLayerInterfaceVersion"
},
"enable_environment": {
"DROIDDECK_VRAM_CAP": "1"
},
"disable_environment": {
"DROIDDECK_VRAM_CAP_DISABLE": "1"
}
}
}
@@ -1,206 +0,0 @@
#define _GNU_SOURCE
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "vramcap_budget.h"
#define EXPORT __attribute__((visibility("default")))
static uint64_t g_cap;
__attribute__((constructor)) static void init(void) {
g_cap = vramcap_parse_mb(getenv("DROIDDECK_VRAM_CAP_MB"));
}
struct inst {
struct inst *next_in_list;
VkInstance handle;
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance destroy;
PFN_vkGetPhysicalDeviceMemoryProperties2 mem2;
PFN_vkGetPhysicalDeviceMemoryProperties2 mem2_khr;
};
struct dev {
struct dev *next_in_list;
VkDevice handle;
PFN_vkGetDeviceProcAddr gdpa;
PFN_vkDestroyDevice destroy;
};
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct inst *g_insts;
static struct dev *g_devs;
static int g_announced;
static void *key(const void *obj) { return *(void *const *)obj; }
static struct inst *inst_for(const void *obj) {
struct inst *r;
pthread_mutex_lock(&g_lock);
for (r = g_insts; r && key(r->handle) != key(obj); r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static struct dev *dev_for(const void *obj) {
struct dev *r;
pthread_mutex_lock(&g_lock);
for (r = g_devs; r && key(r->handle) != key(obj); r = r->next_in_list) {}
pthread_mutex_unlock(&g_lock);
return r;
}
static void say(const char *what) {
fprintf(stderr, "[droiddeck-vram-cap] pid %d: %s\n", (int)getpid(), what);
}
static void announce(void) {
if (__atomic_exchange_n(&g_announced, 1, __ATOMIC_RELAXED)) return;
char line[96];
snprintf(line, sizeof(line), "reported device memory budget %llu MB", (unsigned long long)(g_cap >> 20));
say(line);
}
static void clamp_properties2(PFN_vkGetPhysicalDeviceMemoryProperties2 next, VkPhysicalDevice pd,
VkPhysicalDeviceMemoryProperties2 *out) {
next(pd, out);
for (VkBaseOutStructure *s = out->pNext; s; s = s->pNext)
if (s->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT) {
vramcap_budget(&out->memoryProperties, (VkPhysicalDeviceMemoryBudgetPropertiesEXT *)s, g_cap);
if (g_cap) announce();
}
}
static void VKAPI_CALL GetMemoryProperties2(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *out) {
struct inst *in = inst_for(pd);
if (in) clamp_properties2(in->mem2, pd, out);
}
static void VKAPI_CALL GetMemoryProperties2KHR(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *out) {
struct inst *in = inst_for(pd);
if (in) clamp_properties2(in->mem2_khr, pd, out);
}
static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *alloc, VkInstance *out) {
VkLayerInstanceCreateInfo *link = (VkLayerInstanceCreateInfo *)ci->pNext;
while (link && !(link->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && link->function == VK_LAYER_LINK_INFO))
link = (VkLayerInstanceCreateInfo *)link->pNext;
if (!link) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = link->u.pLayerInfo->pfnNextGetInstanceProcAddr;
link->u.pLayerInfo = link->u.pLayerInfo->pNext;
PFN_vkCreateInstance create = (PFN_vkCreateInstance)next_gipa(VK_NULL_HANDLE, "vkCreateInstance");
if (!create) return VK_ERROR_INITIALIZATION_FAILED;
struct inst *in = calloc(1, sizeof(*in));
if (!in) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkResult r = create(ci, alloc, out);
if (r != VK_SUCCESS) { free(in); return r; }
in->handle = *out;
in->gipa = next_gipa;
in->destroy = (PFN_vkDestroyInstance)next_gipa(*out, "vkDestroyInstance");
in->mem2 = (PFN_vkGetPhysicalDeviceMemoryProperties2)next_gipa(*out, "vkGetPhysicalDeviceMemoryProperties2");
in->mem2_khr = (PFN_vkGetPhysicalDeviceMemoryProperties2)next_gipa(*out, "vkGetPhysicalDeviceMemoryProperties2KHR");
pthread_mutex_lock(&g_lock);
in->next_in_list = g_insts;
g_insts = in;
pthread_mutex_unlock(&g_lock);
return VK_SUCCESS;
}
static void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCallbacks *alloc) {
struct inst *in = inst_for(instance);
if (!in) return;
PFN_vkDestroyInstance destroy = in->destroy;
pthread_mutex_lock(&g_lock);
for (struct inst **p = &g_insts; *p; p = &(*p)->next_in_list)
if (*p == in) { *p = in->next_in_list; break; }
pthread_mutex_unlock(&g_lock);
free(in);
if (destroy) destroy(instance, alloc);
}
static VkLayerDeviceCreateInfo *device_chain(const VkDeviceCreateInfo *ci, VkLayerFunction function) {
VkLayerDeviceCreateInfo *c = (VkLayerDeviceCreateInfo *)ci->pNext;
while (c && !(c->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && c->function == function))
c = (VkLayerDeviceCreateInfo *)c->pNext;
return c;
}
static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci, const VkAllocationCallbacks *alloc,
VkDevice *out) {
VkLayerDeviceCreateInfo *link = device_chain(ci, VK_LAYER_LINK_INFO);
if (!link) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = link->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr next_gdpa = link->u.pLayerInfo->pfnNextGetDeviceProcAddr;
link->u.pLayerInfo = link->u.pLayerInfo->pNext;
struct inst *in = inst_for(pd);
PFN_vkCreateDevice create = (PFN_vkCreateDevice)next_gipa(in ? in->handle : VK_NULL_HANDLE, "vkCreateDevice");
if (!create) return VK_ERROR_INITIALIZATION_FAILED;
struct dev *d = calloc(1, sizeof(*d));
if (!d) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkResult r = create(pd, ci, alloc, out);
if (r != VK_SUCCESS) { free(d); return r; }
d->handle = *out;
d->gdpa = next_gdpa;
d->destroy = (PFN_vkDestroyDevice)next_gdpa(*out, "vkDestroyDevice");
pthread_mutex_lock(&g_lock);
d->next_in_list = g_devs;
g_devs = d;
pthread_mutex_unlock(&g_lock);
return VK_SUCCESS;
}
static void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallbacks *alloc) {
struct dev *d = dev_for(device);
if (!d) return;
pthread_mutex_lock(&g_lock);
for (struct dev **p = &g_devs; *p; p = &(*p)->next_in_list)
if (*p == d) { *p = d->next_in_list; break; }
pthread_mutex_unlock(&g_lock);
PFN_vkDestroyDevice destroy = d->destroy;
free(d);
if (destroy) destroy(device, alloc);
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVramCap_GetDeviceProcAddr(VkDevice device, const char *name);
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVramCap_GetInstanceProcAddr(VkInstance instance, const char *name) {
if (!strcmp(name, "vkCreateInstance")) return (PFN_vkVoidFunction)CreateInstance;
if (!strcmp(name, "vkDestroyInstance")) return (PFN_vkVoidFunction)DestroyInstance;
if (!strcmp(name, "vkCreateDevice")) return (PFN_vkVoidFunction)CreateDevice;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)DestroyDevice;
if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)DroidDeckVramCap_GetInstanceProcAddr;
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)DroidDeckVramCap_GetDeviceProcAddr;
if (!instance) return NULL;
struct inst *in = inst_for(instance);
if (!in) return NULL;
if (g_cap) {
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties2") && in->mem2) return (PFN_vkVoidFunction)GetMemoryProperties2;
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties2KHR") && in->mem2_khr)
return (PFN_vkVoidFunction)GetMemoryProperties2KHR;
}
return in->gipa(instance, name);
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVramCap_GetDeviceProcAddr(VkDevice device, const char *name) {
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)DroidDeckVramCap_GetDeviceProcAddr;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)DestroyDevice;
struct dev *d = dev_for(device);
if (!d) return NULL;
return d->gdpa(device, name);
}
EXPORT VKAPI_ATTR VkResult VKAPI_CALL DroidDeckVramCap_NegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *v) {
if (v->loaderLayerInterfaceVersion > 2) v->loaderLayerInterfaceVersion = 2;
v->pfnGetInstanceProcAddr = DroidDeckVramCap_GetInstanceProcAddr;
v->pfnGetDeviceProcAddr = DroidDeckVramCap_GetDeviceProcAddr;
v->pfnGetPhysicalDeviceProcAddr = NULL;
return VK_SUCCESS;
}
-32
View File
@@ -1,32 +0,0 @@
#ifndef VRAMCAP_BUDGET_H
#define VRAMCAP_BUDGET_H
#include <stdint.h>
#include <vulkan/vulkan.h>
static inline uint64_t vramcap_parse_mb(const char *text) {
if (!text || !*text) return 0;
uint64_t value = 0, limit = UINT64_MAX >> 20;
for (; *text; text++) {
if (*text < '0' || *text > '9') return 0;
unsigned digit = (unsigned)(*text - '0');
if (value > (limit - digit) / 10) return 0;
value = value * 10 + digit;
}
return value << 20;
}
static inline VkDeviceSize vramcap_clamp(VkDeviceSize value, uint64_t cap) {
return cap && value > cap ? cap : value;
}
static inline void vramcap_budget(const VkPhysicalDeviceMemoryProperties *p,
VkPhysicalDeviceMemoryBudgetPropertiesEXT *budget, uint64_t cap) {
for (uint32_t i = 0; i < p->memoryHeapCount && i < VK_MAX_MEMORY_HEAPS; i++)
if (p->memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
budget->heapBudget[i] = vramcap_clamp(budget->heapBudget[i], cap);
budget->heapBudget[i] = vramcap_clamp(budget->heapBudget[i], p->memoryHeaps[i].size);
}
}
#endif
-154
View File
@@ -1,154 +0,0 @@
#include <assert.h>
#include <inttypes.h>
#include "../src/vk_layer_droiddeck_vramcap.c"
static int instance_dispatch, device_dispatch;
static void *instance_object = &instance_dispatch, *physical_object = &instance_dispatch;
static void *device_object = &device_dispatch;
static VkInstance instance;
static VkPhysicalDevice physical;
static VkDevice device;
static unsigned allocations, frees, destroyed_devices, destroyed_instances;
static void VKAPI_CALL memory_properties(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties *out) {
assert(pd == physical);
*out = (VkPhysicalDeviceMemoryProperties){
.memoryHeapCount = 3,
.memoryHeaps = {{8ULL << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}, {4ULL << 30, 0},
{512ULL << 20, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}},
.memoryTypeCount = 1,
.memoryTypes = {{VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0}},
};
}
static void VKAPI_CALL memory_properties2(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *out) {
memory_properties(pd, &out->memoryProperties);
for (VkBaseOutStructure *p = out->pNext; p; p = p->pNext)
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT) {
VkPhysicalDeviceMemoryBudgetPropertiesEXT *b = (void *)p;
b->heapBudget[0] = 6ULL << 30;
b->heapBudget[1] = 3ULL << 30;
b->heapBudget[2] = 256ULL << 20;
b->heapUsage[0] = 3ULL << 30;
}
}
static VkResult VKAPI_CALL allocate(VkDevice d, const VkMemoryAllocateInfo *info,
const VkAllocationCallbacks *a, VkDeviceMemory *out) {
assert(d == device && info->allocationSize == (3ULL << 30));
*out = (VkDeviceMemory)(uintptr_t)++allocations;
return VK_SUCCESS;
}
static void VKAPI_CALL release(VkDevice d, VkDeviceMemory m, const VkAllocationCallbacks *a) {
assert(d == device && m);
frees++;
}
static void VKAPI_CALL destroy_device(VkDevice d, const VkAllocationCallbacks *a) {
assert(d == device);
destroyed_devices++;
}
static void VKAPI_CALL destroy_instance(VkInstance in, const VkAllocationCallbacks *a) {
assert(in == instance);
destroyed_instances++;
}
static PFN_vkVoidFunction VKAPI_CALL gdpa(VkDevice d, const char *name) {
assert(d == device);
if (!strcmp(name, "vkAllocateMemory")) return (PFN_vkVoidFunction)allocate;
if (!strcmp(name, "vkFreeMemory")) return (PFN_vkVoidFunction)release;
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)destroy_device;
return NULL;
}
static VkResult VKAPI_CALL create_device(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci,
const VkAllocationCallbacks *a, VkDevice *out) {
assert(pd == physical);
*out = device;
return VK_SUCCESS;
}
static VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *a, VkInstance *out) {
*out = instance;
return VK_SUCCESS;
}
static PFN_vkVoidFunction VKAPI_CALL gipa(VkInstance in, const char *name) {
assert(in == instance || in == VK_NULL_HANDLE);
if (!strcmp(name, "vkCreateInstance")) return (PFN_vkVoidFunction)create_instance;
if (!strcmp(name, "vkDestroyInstance")) return (PFN_vkVoidFunction)destroy_instance;
if (!strcmp(name, "vkCreateDevice")) return (PFN_vkVoidFunction)create_device;
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties")) return (PFN_vkVoidFunction)memory_properties;
if (!strcmp(name, "vkGetPhysicalDeviceMemoryProperties2") || !strcmp(name, "vkGetPhysicalDeviceMemoryProperties2KHR"))
return (PFN_vkVoidFunction)memory_properties2;
return NULL;
}
int main(void) {
assert(vramcap_parse_mb("2048") == (2ULL << 30));
assert(vramcap_parse_mb(NULL) == 0 && vramcap_parse_mb("") == 0 && vramcap_parse_mb("0") == 0);
const char *bad[] = {"-1", "+1", " 1024", "1024 ", "1GB", "18446744073709551616", "17592186044416"};
for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) assert(vramcap_parse_mb(bad[i]) == 0);
assert(vramcap_parse_mb("17592186044415") == ((UINT64_MAX >> 20) << 20));
instance = (VkInstance)&instance_object;
physical = (VkPhysicalDevice)&physical_object;
device = (VkDevice)&device_object;
g_cap = 2ULL << 30;
VkLayerInstanceLink il = {.pfnNextGetInstanceProcAddr = gipa};
VkLayerInstanceCreateInfo ic = {.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO,
.function = VK_LAYER_LINK_INFO, .u.pLayerInfo = &il};
VkInstanceCreateInfo ici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &ic};
VkInstance got_instance;
assert(CreateInstance(&ici, NULL, &got_instance) == VK_SUCCESS && got_instance == instance);
VkPhysicalDeviceMemoryProperties p;
PFN_vkGetPhysicalDeviceMemoryProperties get = (void *)DroidDeckVramCap_GetInstanceProcAddr(instance, "vkGetPhysicalDeviceMemoryProperties");
assert(get == memory_properties);
get(physical, &p);
assert(p.memoryHeaps[0].size == (8ULL << 30) && p.memoryHeaps[1].size == (4ULL << 30));
assert(p.memoryHeaps[2].size == (512ULL << 20));
assert(p.memoryTypes[0].propertyFlags == (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT));
const char *names[] = {"vkGetPhysicalDeviceMemoryProperties2", "vkGetPhysicalDeviceMemoryProperties2KHR"};
for (size_t i = 0; i < 2; i++) {
VkPhysicalDeviceMemoryBudgetPropertiesEXT b = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT};
VkPhysicalDeviceIDProperties id = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES, .pNext = &b};
VkPhysicalDeviceMemoryProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, .pNext = &id};
PFN_vkGetPhysicalDeviceMemoryProperties2 get2 = (void *)DroidDeckVramCap_GetInstanceProcAddr(instance, names[i]);
get2(physical, &p2);
assert(p2.memoryProperties.memoryHeaps[0].size == (8ULL << 30));
assert(b.heapBudget[0] == g_cap && b.heapBudget[1] == (3ULL << 30));
assert(b.heapBudget[2] == (256ULL << 20));
assert(b.heapUsage[0] == (3ULL << 30));
assert(p2.pNext == &id && id.pNext == &b);
}
VkLayerDeviceLink dl = {.pfnNextGetInstanceProcAddr = gipa, .pfnNextGetDeviceProcAddr = gdpa};
VkLayerDeviceCreateInfo dc = {.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO,
.function = VK_LAYER_LINK_INFO, .u.pLayerInfo = &dl};
VkDeviceCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = &dc};
VkDevice got_device;
assert(CreateDevice(physical, &dci, NULL, &got_device) == VK_SUCCESS && got_device == device);
PFN_vkAllocateMemory next_allocate = (void *)DroidDeckVramCap_GetDeviceProcAddr(device, "vkAllocateMemory");
PFN_vkFreeMemory next_free = (void *)DroidDeckVramCap_GetDeviceProcAddr(device, "vkFreeMemory");
assert(next_allocate == allocate && next_free == release);
VkMemoryAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = 3ULL << 30};
VkDeviceMemory blocks[2];
for (unsigned i = 0; i < 2; i++) assert(next_allocate(device, &ai, NULL, &blocks[i]) == VK_SUCCESS);
assert(allocations == 2);
for (unsigned i = 0; i < 2; i++) next_free(device, blocks[i], NULL);
assert(frees == 2);
g_cap = 0;
assert(DroidDeckVramCap_GetInstanceProcAddr(instance, names[0]) == (PFN_vkVoidFunction)memory_properties2);
assert(DroidDeckVramCap_GetInstanceProcAddr(instance, "vkGetPhysicalDeviceMemoryProperties") == (PFN_vkVoidFunction)memory_properties);
PFN_vkDestroyDevice destroy = (void *)DroidDeckVramCap_GetInstanceProcAddr(instance, "vkDestroyDevice");
assert(destroy == DestroyDevice);
destroy(device, NULL);
DestroyInstance(instance, NULL);
assert(destroyed_devices == 1 && destroyed_instances == 1 && !g_devs && !g_insts);
puts("test_vramcap_budget: ok");
return 0;
}
+27 -17
View File
@@ -1,26 +1,34 @@
#!/bin/sh
set -eu
out=${1:?usage: build-x86-preloads.sh <linuxfs asset directory>}
tools() {
prefix=
if [ "${X86_CROSS:-}" = 1 ]; then
case $1 in i386) prefix=i686-linux-gnu- ;; *) prefix=x86_64-linux-gnu- ;; esac
fi
GCC=${prefix}gcc GXX=${prefix}g++ STRIP=${prefix}strip OBJDUMP=${prefix}objdump NM=${prefix}nm
}
for arch in x86_64 i386; do
tools $arch
case $arch in
x86_64) bits=-m64 ;;
i386) bits=-m32 ;;
esac
mkdir -p "$out/$arch"
gcc $bits -shared -fPIC -O2 -Wall -pthread \
$GCC $bits -shared -fPIC -O2 -Wall -pthread \
-o "$out/$arch/libddsession.so" tools/linuxfs/preload/*.c -ldl
g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
$GXX $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
strip --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"
$STRIP --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"
for lib in "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"; do
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
minor=${newest#GLIBC_2.}
if [ "$minor" -gt 31 ]; then
echo "$lib needs $newest; Steam Linux Runtime 3.0 has glibc 2.31" >&2
exit 1
fi
if objdump -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
if $OBJDUMP -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
echo "$lib links the C++ runtime dynamically" >&2
exit 1
fi
@@ -28,37 +36,39 @@ for arch in x86_64 i386; do
done
for target in x86_64/faultreport i386/faultreport; do
arch=${target%/*} name=${target#*/}
tools $arch
case $arch in
x86_64) bits=-m64 ;;
i386) bits=-m32 ;;
esac
lib=$out/$arch/lib$name.so
gcc $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
$GCC $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/$name.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ -n "$(nm -D --undefined-only "$lib" 2>/dev/null)" ]; then
$STRIP --strip-unneeded "$lib"
if $OBJDUMP -p "$lib" | grep -q NEEDED || [ -n "$($NM -D --undefined-only "$lib" 2>/dev/null)" ]; then
echo "$lib must not need any library" >&2
exit 1
fi
done
tools x86_64
lib=$out/x86_64/libwebkitinput.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/webkitinput.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
$STRIP --strip-unneeded "$lib"
if $OBJDUMP -p "$lib" | grep -q NEEDED || [ "$($NM -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
exit 1
fi
stub=$(mktemp -d)
gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
$GCC -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
lib=$out/x86_64/libvulkan-thunk.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
-o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl
rm -rf "$stub"
strip --strip-unneeded "$lib"
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
$STRIP --strip-unneeded "$lib"
newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
if ! $OBJDUMP -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! $OBJDUMP -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2
exit 1
fi
+1 -1
View File
@@ -24,7 +24,7 @@ if [ -n "${DD_DEBUG_DIR:-}" ]; then
exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1
echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}"
fi
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' ! -name 'droiddeck-display-buffers' -exec rm -rf {} + 2>/dev/null
chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null
export DD_DESKTOP=1
+2 -49
View File
@@ -1,7 +1,6 @@
#!/usr/bin/python3
import os
import re
import shutil
HOME = os.environ.get("HOME", "/root")
SYSTEM_DIR = "/usr/share/applications"
@@ -10,8 +9,6 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
USER_DIR = os.path.join(HOME, ".local/share/applications")
MARK = "X-DroidDeck-GPU=1"
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
def enabled():
@@ -27,33 +24,6 @@ def main_group(text):
return lines[:start + 1], lines[start + 1:end], lines[end:]
def split_program(exec_line):
if exec_line.startswith('"'):
end = exec_line.find('"', 1)
if end < 0:
return None, None
return exec_line[:end + 1], exec_line[end + 1:]
program, _, rest = exec_line.partition(" ")
return program, (" " + rest) if rest else ""
def chromium(exec_line):
program, _ = split_program(exec_line)
if not program:
return False
program = program.strip('"')
path = program if os.path.isabs(program) else shutil.which(program)
if not path:
return False
here = os.path.dirname(os.path.realpath(path))
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
def chromium_exec(exec_line):
program, rest = split_program(exec_line)
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
def gpu_exec(exec_line):
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
@@ -75,24 +45,8 @@ def wrap(text, gpu_on=True):
if not exec_line or exec_line.startswith("droiddeck-gpu "):
return None
cats = set(filter(None, keys.get("Categories", "").split(";")))
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
browser = chromium(exec_line)
if not gpu and not browser:
if not (gpu_on and cats & {"Game", "Emulator"}):
return None
if browser:
exec_line = chromium_exec(exec_line)
if not gpu:
def fix(lines):
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
for l in lines]
out_group = fix(group)
while out_group and not out_group[-1].strip():
out_group.pop()
out_group.append(MARK)
out_rest = fix(rest)
if out_rest and out_rest[0].strip():
out_rest.insert(0, "")
return "\n".join(head + out_group + out_rest) + "\n"
out_group = []
actions = keys.get("Actions", "")
for l in group:
@@ -111,8 +65,7 @@ def wrap(text, gpu_on=True):
wrapped_rest = []
for l in rest:
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
action = l[5:].strip()
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
l = "Exec=" + gpu_exec(l[5:].strip())
wrapped_rest.append(l)
if wrapped_rest and wrapped_rest[0].strip():
wrapped_rest.insert(0, "")
@@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread):
class WebSocket:
def __init__(self, url, timeout):
def __init__(self, url, timeout, bounded=False):
target = urllib.parse.urlsplit(url)
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
or target.username is not None or target.password is not None or target.fragment):
@@ -442,6 +442,7 @@ class WebSocket:
if target.query:
path += "?" + target.query
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
self.deadline = time.monotonic() + timeout if bounded else None
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
try:
self._handshake(path, hostport)
@@ -457,6 +458,7 @@ class WebSocket:
).encode())
head = b""
while b"\r\n\r\n" not in head:
self._wait()
chunk = self.s.recv(4096)
if not chunk:
raise OSError("DevTools closed the connection during the handshake")
@@ -468,8 +470,17 @@ class WebSocket:
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
self.buffer = head.split(b"\r\n\r\n", 1)[1]
def _wait(self):
if self.deadline is None:
return
left = self.deadline - time.monotonic()
if left <= 0:
raise socket.timeout("DevTools did not answer in time")
self.s.settimeout(left)
def _read(self, n):
while len(self.buffer) < n:
self._wait()
chunk = self.s.recv(65536)
if not chunk:
raise OSError("DevTools closed the connection")
@@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5):
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
INSPECTOR_URL = re.compile(r"ws://127\.0\.0\.1:([0-9]{4,5})/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
def inspector_url(url):
found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None
if not found or not 1024 <= int(found.group(1)) <= 65535:
raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id")
return url
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
command_line_api=False):
if inspector is not None:
url, name = inspector_url(inspector), "inspector"
else:
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title")
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True,
}}))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
message = json.loads(ws.recv())
ws = WebSocket(url, timeout, bounded=True)
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e)
try:
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True, "includeCommandLineAPI": command_line_api,
}}))
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
while True:
try:
message = json.loads(ws.recv())
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
if message.get("id") != 1:
continue
if "error" in message:
@@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
raise AgentError("JS_EXCEPTION", text)
value = result.get("result", {})
return {"target": match[0].get("title"), "type": value.get("type"),
return {"target": name, "type": value.get("type"),
"value": value.get("value"), "description": value.get("description")}
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
finally:
ws.close()
@@ -1157,7 +1196,7 @@ def handle(agent_dir, req):
if not isinstance(expression, str) or not expression:
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
request_timeout(req, 15))
request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True)
if kind == "steam-selection":
return steam_selection(agent_dir, request_timeout(req, 5))
if kind == "quit":
@@ -1167,6 +1206,15 @@ def handle(agent_dir, req):
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
def reply(agent_dir, req):
try:
return dict(handle(agent_dir, req), ok=True)
except AgentError as e:
return {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
def answer(agent_dir, path):
rid = path.stem
try:
@@ -1186,12 +1234,7 @@ def answer(agent_dir, path):
except OSError:
pass
if req is not None:
try:
result = dict(handle(agent_dir, req), ok=True)
except AgentError as e:
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
result = reply(agent_dir, req)
write_json(agent_dir / "resp" / (rid + ".json"), result)
@@ -1218,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1):
def main(argv):
if argv and argv[0] == "--cdp-inspector":
if len(argv) != 4:
print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr)
return 2
print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2],
"expression": argv[3], "commandLineApi": True})))
return 0
base = os.environ.get("DD_LAUNCH_DIR")
if not base:
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
@@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
export QT_QPA_PLATFORM=xcb
fi
arch=$(cat "$dir/arch" 2>/dev/null)
if [ "$arch" = arm64 ]; then
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
while IFS= read -r lib; do
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
done
fi
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("$APPDIR/AppRun")
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $fex:$(cat "$dir/arch" 2>/dev/null) in
case $fex:$arch in
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
auto:arm64) ;;
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
@@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask"
WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00))
CLIENT_AREA_ANIMATION = (4, 0x02)
WALLPAPER_MAX = (1280, 720)
FEX_REQUEST = "battlenet-fex.request"
FEX_RESULT = "battlenet-fex.result"
FEX_WAIT = 120
START_GRACE = 90
POLL = 2
STOP_WAIT = 5
@@ -82,8 +79,7 @@ AGENT_START = 90
AGENT_HELPER = "agent.js"
AGENT_RUNTIME = "agent-runtime"
AGENT_LOG = "agent.log"
AGENT_LOG_LIMIT = 4 << 20
HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"]
HEADLESS = "/usr/local/bin/droiddeck-headless"
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
COUNTRY = re.compile(r"[A-Z]{3}")
@@ -321,6 +317,15 @@ def install_path(root, library):
return letter.upper() + ":\\" + path[len(target):].strip("/").replace("/", "\\")
def keeps_open(root):
try:
with open(os.path.join(drive_c(root), *CONFIG), encoding="utf-8-sig") as f:
client = json.load(f).get("Client")
except (OSError, ValueError, AttributeError):
return False
return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1]
def write_config(root, library=None):
path = os.path.join(drive_c(root), *CONFIG)
key, value = LAUNCH_BEHAVIOR
@@ -338,7 +343,7 @@ def write_config(root, library=None):
return None
client = config["Client"]
changes = []
if client.get(key) != value:
if key not in client:
client[key] = value
changes.append("launch")
if client.get("HardwareAcceleration") != "false":
@@ -770,32 +775,6 @@ def write_menu(path=MENU):
say("menu entry not written: %s" % error)
def ask_fex(launch_dir, wait=FEX_WAIT):
if not launch_dir or not os.path.isdir(launch_dir):
say("not inside a DroidDeck session; FEX stays as Components has it")
return None
result = os.path.join(launch_dir, FEX_RESULT)
request = os.path.join(launch_dir, FEX_REQUEST)
try:
os.unlink(result)
except OSError:
pass
with open(request + ".tmp", "w", encoding="utf-8") as f:
f.write("appid=%s\n" % APP_ID)
os.replace(request + ".tmp", request)
deadline = time.monotonic() + wait
while time.monotonic() < deadline:
try:
with open(result, encoding="utf-8") as f:
answer = f.read().strip()
except OSError:
time.sleep(0.5)
continue
os.unlink(result)
return answer
return None
def wine_processes(pfx, proc="/proc"):
want = os.path.realpath(pfx).rstrip("/")
found = []
@@ -875,6 +854,9 @@ class Tidy:
self.game_since = self.game_since if self.game_since is not None else now
if own and not self.closed_for_game and now - self.game_since >= self.settle:
self.closed_for_game, self.agent_seen, self.agent_lost = True, False, None
if keeps_open(steam_root()):
say("Battle.net is set to stay open as a game launches: left open")
return False
if any(is_client(argv) for _, argv in own) and any(shares_sign_in(argv) for argv in games):
say("Battle.net stayed open beside a game signing in with its token: left open")
return False
@@ -1136,8 +1118,6 @@ def stop_leftovers(pfx):
def open_client(root, reinstall=False):
pfx = os.path.join(prefix(root), "pfx")
write_menu()
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
if running(pfx):
say("Battle.net is already running in its prefix; waiting for it to close")
wait_while_open(pfx, grace=0)
@@ -1226,8 +1206,6 @@ def launch(root, code):
try:
own = None
if lock is not None and not running(pfx):
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
verb = None if stop_leftovers(pfx) else "run"
configure(root, LIBRARY)
own = start(launcher(root), verb)
@@ -1437,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
windows = install_path(root, folder)
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
os.makedirs(CACHE, exist_ok=True)
for suffix in (".json", ".game", ".form", ".error"):
try:
os.unlink(base + suffix)
except OSError:
pass
runtime = os.path.join(CACHE, AGENT_RUNTIME)
os.makedirs(runtime, mode=0o700, exist_ok=True)
env = agent_env()
for name in ("DISPLAY", "WAYLAND_DISPLAY"):
env.pop(name, None)
env["XDG_RUNTIME_DIR"] = runtime
cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--",
os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
output = os.path.join(CACHE, AGENT_LOG)
try:
if os.path.getsize(output) > AGENT_LOG_LIMIT:
os.replace(output, output + ".1")
except OSError:
pass
before = {pid for pid, _ in wine_processes(pfx)}
with open(output, "ab") as log:
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
seen = None
mark = None
moved = time.monotonic()
+129
View File
@@ -0,0 +1,129 @@
#!/bin/bash
set -u
umask 077
self=${BASH_SOURCE[0]}
proc=${DD_PROC:-/proc}
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless}
wait_s=${DD_CURSEFORGE_WAIT:-60}
cmd=${1:-}
dir=${2:-}
flag=--inspect-publish-uid=stderr
case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac
if [ ! -d "$dir/app" ]; then
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
exit 2
fi
running() {
local p
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0
done
return 1
}
started_at() {
local stat
stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
stat=${stat##*) }
set -- $stat
echo "${20}"
}
tracked() {
local pid at launched
read -r pid at launched 2>/dev/null < "$state/pid" || return 1
case $pid in ''|*[!0-9]*) return 1 ;; esac
kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1
printf '%s %s\n' "$pid" "$launched"
}
ours() {
local pid launched
read -r pid launched <<<"$(tracked)"
[ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid"
}
lock() {
mkdir -p "$state" && chmod 700 "$state" || return 1
exec 9>"$state/lock" || return 1
flock 9
}
inspector() {
grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null
}
start() {
local url pid child=
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
if ! ours >/dev/null; then
if tracked >/dev/null || running; then
exec 9>&-
echo busy
return 3
fi
mv -f "$state/log" "$state/log.1" 2>/dev/null
env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \
"$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- &
pid=$!
child=$pid
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
fi
exec 9>&-
for _ in $(seq 1 $((wait_s * 2))); do
if url=$(inspector); then
echo "$url"
hold "$child"
return 0
fi
ours >/dev/null || break
sleep 0.5
done
tail -n 20 "$state/log" >&2
return 5
}
hold() {
local pid
if [ -n "$1" ]; then
wait "$1"
return 0
fi
pid=$(ours) || return 0
while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do
sleep 1
done
}
stop() {
local pid p
lock || return 1
pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; }
kill -TERM -- "-$pid" 2>/dev/null
for _ in $(seq 1 20); do
kill -0 -- "-$pid" 2>/dev/null || break
sleep 0.5
done
kill -KILL -- "-$pid" 2>/dev/null
kill -KILL "$pid" 2>/dev/null
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
done
rm -f "$state/pid"
exec 9>&-
return 0
}
case $cmd in
start)
start
exit $?
;;
stop)
stop
exit 0
;;
esac
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
"libssl.so.3", "libcrypto.so.3",
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
))
PROVIDED_NEEDS = {
"libwayland-client.so.0": ("libffi.so.8",),
@@ -670,6 +670,8 @@ def guest_environment(fex, env):
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
result.pop("GLIBC_TUNABLES", None)
if "aarch64" in result.get("GCONV_PATH", ""):
result["GCONV_PATH"] = ""
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
@@ -14,7 +14,6 @@ from pathlib import Path
GAME_PREFIX = "DROIDDECK_GAME_"
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
D3D9_DEFAULT_MEMORY_MB = 4096
SYNC_KEYS = ("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"
PACK_KEYS = ("WINESERVER", "DD_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
@@ -86,9 +85,10 @@ def game_files(exe):
class Game:
def __init__(self, exe, args):
def __init__(self, exe, args, app_id=""):
self.exe = exe
self.args = args
self.app_id = app_id
self.stem = os.path.splitext(os.path.basename(exe))[0].lower()
self.files = game_files(exe)
@@ -152,12 +152,24 @@ def deep_rock_gdk_raytracing(game):
return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)"
@fix
def dragons_dogma_2_wine_detection(game):
if game.app_id == "2054970" and not any(a.lower().startswith("/winedetectionenabled:") for a in game.args):
return {}, ["/WineDetectionEnabled:False"], "Dragon's Dogma 2: the game's Wine detection off (its Wine path does not start)"
@fix
def ff7_rebirth_feature_level(game):
if game.stem in ("ff7rebirth", "ff7rebirth_"):
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)"
@fix
def kcd2_feature_level(game):
if game.app_id == "1771300":
return {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"}, [], "Kingdom Come: Deliverance II: D3D12 feature level 12_2 and shader model 6_9 (the detected level fails its startup check, and 12_0 alone stalls on the splash screen)"
@fix
def arkham_city_x87(game):
if "batmanac.exe" in game.files:
@@ -188,6 +200,12 @@ def protonfixes_off(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def black_ops_ii_steam_exec(game):
if game.app_id in ("202970", "202990", "212910") or game.stem in ("t6sp", "t6mp", "t6zm"):
return {"WINESTEAMNOEXEC": "0"}, [], "Black Ops II: Steam exec handling on (the game does not start without it)"
@fix
def little_nightmares_threads(game):
if game.stem == "littlenightmares":
@@ -367,8 +385,8 @@ def offline_without_anticheat(command, env):
return command[:2] + [game] + command[3:]
def engine_fixes(exe, args):
game = Game(exe, args)
def engine_fixes(exe, args, app_id=""):
game = Game(exe, args, app_id)
env, extra, notes = {}, [], []
for check in FIXES:
found = check(game)
@@ -453,18 +471,13 @@ def game_gpu(env, keep=False):
return result
def vram_cap(env):
value = env.get("DD_VRAM_MB", "")
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
return env
result = env.copy()
cap = "dxgi.maxDeviceMemory = {0}; dxgi.maxSharedMemory = {0}".format(int(value))
if int(value) < D3D9_DEFAULT_MEMORY_MB:
cap += "; d3d9.maxAvailableMemory = {0}".format(int(value))
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
result["DROIDDECK_VRAM_CAP"] = "1"
result["DROIDDECK_VRAM_CAP_MB"] = value
def split_game_gpu(entries):
result = dict(entries)
for key in GAME_SPLIT_KEYS:
if GAME_PREFIX + key in result:
value = result.pop(GAME_PREFIX + key)
if key not in entries:
result[key] = None if value == "" else value
return result
@@ -596,12 +609,12 @@ def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
result = env.copy()
entries = dict(config.get("shared", {}))
entries = split_game_gpu(config.get("shared", {}))
for name, value in (fixes or {}).items():
if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)):
value = entries.get(name, env.get(name)) + ";" + value
entries[name] = value
game = config.get("games", {}).get(app_id, {})
game = split_game_gpu(config.get("games", {}).get(app_id, {}))
fix = (fixes or {}).get("WINEDLLOVERRIDES")
if fix and isinstance(game.get("WINEDLLOVERRIDES"), str):
own = game["WINEDLLOVERRIDES"]
@@ -1395,7 +1408,7 @@ def main():
death_stranding_allocator(app_id, command[2])
ubisoft_overlay_off(env)
project_zomboid_jvm(command)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], [])
if not gl_default:
fixes.pop("vblank_mode", None)
for note in notes:
@@ -1439,7 +1452,6 @@ def main():
if mic_enabled == "0":
env["AUDIO_DIRECT_MIC"] = "0"
env = directaudio_settings(env)
env = vram_cap(env)
note = render_path_defaults(command, env) if app_id else None
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
set -u
runtime=${1:-}
shift
log=
if [ "${1:-}" = --log ]; then
log=${2:-}
shift 2
fi
if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then
echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2
exit 2
fi
shift
umask 077
mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1
if [ -n "$log" ]; then
size=$(stat -c %s "$log" 2>/dev/null || echo 0)
[ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1"
exec >>"$log" 2>&1
fi
unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY
export XDG_RUNTIME_DIR=$runtime
exec gamescope --backend headless -w 640 -h 480 -- "$@"
@@ -137,6 +137,7 @@ clear_stale_tmp() {
[ -z "${DD_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${DD_INSIDE:-}" ]; then
if [ "${DD_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.dd-zram; else rm -f /tmp/.dd-zram; fi
rm -f /tmp/.dd-zram.hold
dd if=/dev/zero of=/tmp/.dd-clock bs=8 count=1 conv=notrunc status=none
fi
@@ -761,13 +762,6 @@ case $mode in
fi
if [ "${DD_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${DD_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)"
_dd_ram_cap=0
case ${DD_RAM_CAP_MB:-} in
''|0) ;;
*[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$DD_RAM_CAP_MB'" ;;
*) _dd_ram_cap=$((DD_RAM_CAP_MB * 1024)); step "RAM cap: ${DD_RAM_CAP_MB} MB" ;;
esac
(
dd_zram_scan() {
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
@@ -844,284 +838,235 @@ case $mode in
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
}
dd_memory_read() {
local _k _v _u _kind _fields _avg _whole _frac _gpu_bytes _growth _saved_growth _saved_fall
_saved_growth=${_dd_preserved_growth:-0} _saved_fall=${_dd_preserved_fall:-0}
_dd_preserved_growth=0 _dd_preserved_fall=0
_dd_mem_total=0 _dd_available=-1 _dd_swap_total=0 _dd_swap_free=-1
_dd_psi_some=0 _dd_psi_full=0 _dd_gpu=0 _dd_unevictable=0 _dd_shmem=0
local _k _v _u _kind _fields _name _type _size _used _orig _comp _mem _dt _fall
local _stall=-1 _swap_total=0 _swap_free=0 _total=0 _room=0 _listed=0 _in=-1
_dd_mem_total=0 _dd_available=-1
while read -r _k _v _u; do
case $_v in ''|*[!0-9]*) continue ;; esac
case $_k in
MemTotal:) _dd_mem_total=$_v ;;
MemAvailable:) _dd_available=$_v ;;
SwapTotal:) _dd_swap_total=$_v ;;
SwapFree:) _dd_swap_free=$_v ;;
Unevictable:) _dd_unevictable=$_v ;;
Shmem:) _dd_shmem=$_v ;;
SwapTotal:) _swap_total=$_v ;;
SwapFree:) _swap_free=$_v ;;
esac
done 2>/dev/null < /proc/meminfo
while read -r _name _type _size _used _u; do
_listed=1
case $_name in */zram[0-9]*) ;; *) continue ;; esac
case $_size$_used in ''|*[!0-9]*) continue ;; esac
_total=$((_total + _size)) _room=$((_room + _size - _used))
done 2>/dev/null < /proc/swaps
[ "$_listed" = 1 ] || _total=$_swap_total _room=$_swap_free
_dd_swap_room=$((_total / 8))
[ "$_dd_swap_room" -ge $((128 * 1024)) ] || _dd_swap_room=$((128 * 1024))
_dd_swap_room=$((_room - _dd_swap_room))
_dd_saving=600
if [ -r /sys/block/zram0/mm_stat ] && read -r _orig _comp _mem _u 2>/dev/null < /sys/block/zram0/mm_stat; then
case $_orig$_mem in
''|*[!0-9]*) ;;
*) [ "$_orig" -lt $((64 << 20)) ] || _dd_saving=$(((_orig - _mem) / (_orig / 1000))) ;;
esac
[ "$_dd_saving" -ge 167 ] || _dd_saving=167
[ "$_dd_saving" -le 833 ] || _dd_saving=833
fi
if [ -r /proc/pressure/memory ]; then
while read -r _kind _fields; do
[ "$_kind" = some ] || [ "$_kind" = full ] || continue
_avg=${_fields#avg10=} _avg=${_avg%% *}
_whole=${_avg%%.*} _frac=${_avg#*.}
[ "$_frac" = "$_avg" ] && _frac=00
_frac=${_frac}00
_frac=${_frac:0:2}
case $_whole$_frac in ''|*[!0-9]*) continue ;; esac
if [ "$_kind" = some ]; then
_dd_psi_some=$((10#$_whole * 100 + 10#$_frac))
else
_dd_psi_full=$((10#$_whole * 100 + 10#$_frac))
fi
[ "$_kind" = some ] || continue
_fields=${_fields##*total=}
case $_fields in ''|*[!0-9]*) ;; *) _stall=$_fields ;; esac
done 2>/dev/null < /proc/pressure/memory
fi
if [ -r /sys/class/kgsl/kgsl/page_alloc ]; then
read -r _gpu_bytes _u < /sys/class/kgsl/kgsl/page_alloc
case $_gpu_bytes in ''|*[!0-9]*) _gpu_bytes=0 ;; esac
_dd_gpu=$((_gpu_bytes / 1024))
while read -r _k _v; do
[ "$_k" = pswpin ] || continue
case $_v in ''|*[!0-9]*) ;; *) _in=$((_v * _dd_page_kb)) ;; esac
break
done 2>/dev/null < /proc/vmstat
_dt=$((SECONDS - ${_dd_sample_at:-$SECONDS}))
if [ -z "${_dd_sample_at:-}" ]; then
_dd_rate=0 _dd_psi=0 _dd_returned=0
elif [ "$_dt" -gt 0 ] && [ "$_dd_available" -ge 0 ]; then
_fall=$(((_dd_sample_available - _dd_available + _dd_freed) / _dt))
_dd_rate=$((_dd_rate * 3 / 4))
[ "$_fall" -le "$_dd_rate" ] || _dd_rate=$_fall
_dd_psi=0
[ "$_stall" -lt 0 ] || [ "$_dd_sample_stall" -lt 0 ] || _dd_psi=$(((_stall - _dd_sample_stall) / (_dt * 100)))
_dd_returned=$((_dt < 30 ? _dd_returned * (30 - _dt) / 30 : 0))
[ "$_in" -lt "$_dd_sample_in" ] || [ "$_dd_sample_in" -lt 0 ] || _dd_returned=$((_dd_returned + _in - _dd_sample_in))
fi
_dd_psi=$_dd_psi_some
[ "$_dd_psi_full" -gt "$_dd_psi" ] && _dd_psi=$_dd_psi_full
if [ "${_dd_sample_at:-}" = "" ]; then
_dd_growth=0 _dd_fall=0
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu
_dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem
elif [ "$SECONDS" -gt "$_dd_sample_at" ]; then
_dd_growth=0 _dd_fall=0
_growth=$((_dd_gpu - _dd_sample_gpu)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
_growth=$((_dd_unevictable - _dd_sample_unevictable)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
_growth=$((_dd_shmem - _dd_sample_shmem)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
_dd_fall=$((_dd_sample_available - _dd_available))
[ "$_saved_growth" -gt "$_dd_growth" ] && _dd_growth=$_saved_growth
[ "$_saved_fall" -gt "$_dd_fall" ] && _dd_fall=$_saved_fall
if [ $((SECONDS - _dd_sample_at)) -ge 5 ]; then
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu
_dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem
fi
if [ "$_dd_available" -ge 0 ] && { [ -z "${_dd_sample_at:-}" ] || [ "$_dt" -gt 0 ]; }; then
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_stall=$_stall _dd_sample_in=$_in _dd_freed=0
fi
_dd_real_available=$_dd_available
[ "$_dd_real_available" -ge 0 ] && _dd_real_available=$((_dd_real_available - _dd_growth))
_dd_headroom=$((_dd_mem_total / 5))
[ "$_dd_headroom" -ge $((512 * 1024)) ] || _dd_headroom=$((512 * 1024))
[ "$_dd_headroom" -le $((1536 * 1024)) ] || _dd_headroom=$((1536 * 1024))
_dd_tier_headroom=$((_dd_mem_total / 4))
[ "$_dd_tier_headroom" -ge $((768 * 1024)) ] || _dd_tier_headroom=$((768 * 1024))
[ "$_dd_tier_headroom" -le $((2560 * 1024)) ] || _dd_tier_headroom=$((2560 * 1024))
_dd_fall_headroom=$((_dd_tier_headroom * 2))
[ "$_dd_fall_headroom" -ge $((_dd_mem_total * 2 / 5)) ] || _dd_fall_headroom=$((_dd_mem_total * 2 / 5))
_dd_swap_reserve=$((_dd_swap_total / 5))
[ "$_dd_swap_reserve" -ge $((256 * 1024)) ] || _dd_swap_reserve=$((256 * 1024))
_dd_floor=$((_dd_mem_total / 8))
[ "$_dd_floor" -ge $((640 * 1024)) ] || _dd_floor=$((640 * 1024))
[ "$_dd_floor" -le $((1280 * 1024)) ] || _dd_floor=$((1280 * 1024))
_dd_target=$((_dd_floor + _dd_rate * 10))
}
dd_memory_tight() {
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_real_available" -lt "$_dd_headroom" ] ||
{ [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_mem_total / 3)) ]; } ||
{ [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt $((_dd_headroom * 2)) ]; }; }
}
dd_client_can_pageout() {
dd_memory_read
dd_zram_usage "${_dd_pids[@]}" > /dev/null
[ "$_dd_mem_total" -gt 0 ] && dd_zram_has_room
}
dd_zram_has_room() {
[ "$_dd_swap_total" -gt 0 ] &&
[ $((_dd_swap_free - _dd_anon - ${_dd_client_reserve:-0})) -ge "$_dd_swap_reserve" ]
}
dd_client_can_readback() {
dd_memory_read
dd_zram_usage "${_dd_pids[@]}" > /dev/null
[ "$_dd_mem_total" -gt 0 ] && ! dd_memory_tight && ! dd_memory_critical &&
[ "$_dd_real_available" -ge $((_dd_swap * 2)) ] &&
[ $((_dd_real_available - _dd_swap)) -ge "$_dd_headroom" ]
}
dd_client_pressure() {
[ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ "$_dd_game" = 1 ] &&
[ "${#_dd_pids[@]}" -gt 0 ] && { dd_memory_tight || dd_memory_critical; } || return 0
[ "$_dd_pressure_at" -lt 0 ] ||
[ $((SECONDS - _dd_pressure_at)) -ge "$_dd_pressure_backoff" ] || return 0
[ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 30 ] || return 0
_dd_pressure_at=$SECONDS
if ! dd_client_can_pageout; then
step "zRAM: pressure reclaim skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)"
return 0
dd_memory_need() {
local _burst=$((_dd_rate * 2))
_dd_need=0 _dd_hard=0 _dd_force=0
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] || return 0
_dd_need=$((_dd_target - _dd_available)) _dd_hard=$((_dd_floor - _dd_available))
if [ "$_burst" -ge $((64 * 1024)) ] && [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] && [ "$_burst" -gt "$_dd_need" ]; then
_dd_need=$_burst
fi
[ "$_dd_rss" -ge $((128 * 1024)) ] || return 0
_dd_pressure_before=$_dd_rss
if [ "${1:-}" = defer ]; then
_dd_client_reserve=$_dd_anon
_dd_client_pending=1
fi
dd_zram_send 1 "memory pressure, compressing the client (available $((_dd_available / 1024)) MB, swap free $((_dd_swap_free / 1024)) MB)" client "${1:-}"
_dd_packed=$SECONDS
if [ "${1:-}" = defer ]; then
_dd_client_targets=("${_dd_zram_targets[@]}")
else
dd_client_pressure_result
if [ "$_dd_psi" -ge 100 ] && [ "$_burst" -gt "$_dd_hard" ]; then
_dd_hard=$_burst
fi
[ "$_dd_hard" -gt 0 ] || _dd_hard=0
[ "$_dd_need" -ge "$_dd_hard" ] || _dd_need=$_dd_hard
[ "$_dd_available" -ge $((_dd_floor / 2)) ] || _dd_force=1
}
dd_client_pressure_finish() {
[ "${_dd_client_pending:-0}" = 1 ] || return 0
dd_zram_finish 1 "${_dd_client_targets[@]}"
dd_client_pressure_result "${_dd_client_targets[@]}"
_dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=()
}
dd_client_pressure_result() {
[ "${_dd_pageout_complete:-0}" = 1 ] || return 0
if [ "$#" -gt 0 ]; then dd_zram_usage "$@" > /dev/null; else dd_zram_usage "${_dd_pids[@]}" > /dev/null; fi
if [ $((_dd_pressure_before - _dd_rss)) -lt $((16 * 1024)) ]; then
_dd_pressure_backoff=$((_dd_pressure_backoff * 2 > 300 ? 300 : _dd_pressure_backoff * 2))
else
_dd_pressure_backoff=30
fi
}
dd_memory_critical() {
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_real_available" -lt "$_dd_tier_headroom" ] ||
{ [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_tier_headroom * 3 / 2)) ]; } ||
{ [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; }; }
}
dd_session_pressure() {
dd_memory_read
dd_memory_critical || _dd_tier_backoff=30 _dd_tier_nogain=0
[ "$_dd_game" = 1 ] && dd_memory_critical || return 0
[ "${DD_ZRAM_IDLE:-1}" = 1 ] && dd_game_focused 0 || return 0
local _wait=$_dd_tier_backoff _before _available_before _pids _targets _gain _min_gain
[ "$_dd_available" -ge $((_dd_headroom / 2)) ] || [ "$_dd_tier_pushed" -lt 0 ] || _wait=30
[ "$_dd_tier_at" -lt 0 ] || [ $((SECONDS - _dd_tier_at)) -ge "$_wait" ] || return 0
if [ "$_dd_tier_at" -ge 0 ] && [ "$_dd_tier_pushed" -gt 0 ]; then
dd_tier_readback
if [ "$_dd_tier_back" -le $((_dd_tier_pushed / 2)) ]; then
[ "${_dd_tier_nogain:-0}" = 1 ] || _dd_tier_backoff=30
else
_dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2))
_dd_tier_at=$SECONDS _dd_tier_pushed=-1
step "zRAM: the game read back most of its last page-out, next try in ${_dd_tier_backoff} s"
return 0
fi
fi
_dd_tier_at=$SECONDS _dd_tier_pushed=0
dd_zram_pick session
dd_zram_usage "${_pids[@]}" > /dev/null
[ "$_dd_rss" -ge $((256 * 1024)) ] || return 0
if ! dd_zram_has_room; then
step "zRAM: low-memory page-out skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)"
return 0
fi
_targets=("${_pids[@]}") _before=$_dd_swap _available_before=$_dd_available
dd_zram_send 1 "low memory (available $((_dd_real_available / 1024)) MB), compressing idle game memory" session
dd_zram_usage "${_targets[@]}" > /dev/null
_dd_tier_pushed=$((_dd_swap - _before))
dd_tier_note "${_targets[@]}"
if [ "${_dd_pageout_complete:-0}" = 1 ]; then
dd_memory_read
_gain=$((_dd_available - _available_before))
_min_gain=$((_dd_tier_headroom / 16))
[ "$_min_gain" -ge $((16 * 1024)) ] || _min_gain=$((16 * 1024))
if [ "$_gain" -lt "$_min_gain" ]; then
_dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2))
_dd_tier_at=$SECONDS _dd_tier_nogain=1
step "zRAM: low-memory page-out gained only $((_gain / 1024)) MB available, next try in ${_dd_tier_backoff} s"
else
_dd_tier_nogain=0
fi
fi
}
dd_proc_start() {
local _s=
_dd_start=
read -r _s 2>/dev/null < "/proc/$1/stat" || return 1
_s=${_s##*) }
set -- $_s
[ "$1" != Z ] && [ "$#" -ge 20 ] || return 1
_dd_start=${20}
}
dd_tier_note() {
local _p
_dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
for _p in "$@"; do
dd_proc_start "$_p" || continue
dd_zram_usage "$_p" > /dev/null
_dd_tier_targets+=("$_p") _dd_tier_swaps+=("$_dd_swap") _dd_tier_starts+=("$_dd_start")
done
}
dd_tier_readback() {
local _i _back=0
for _i in "${!_dd_tier_targets[@]}"; do
dd_proc_start "${_dd_tier_targets[$_i]}" && [ "$_dd_start" = "${_dd_tier_starts[$_i]}" ] || continue
dd_zram_usage "${_dd_tier_targets[$_i]}" > /dev/null
[ "${_dd_tier_swaps[$_i]}" -le "$_dd_swap" ] || _back=$((_back + _dd_tier_swaps[_i] - _dd_swap))
done
_dd_tier_back=$_back
}
dd_watch_nap() {
local _i
if [ "$_dd_game" = 1 ] && [ "$_dd_available" -ge 0 ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; then
for _i in 1 2 3 4 5; do
nap 1
dd_memory_read
dd_memory_critical && return 0
done
else
nap 5
fi
return 0
dd_pid_key() {
local _s
_dd_key=$1
read -r _s 2>/dev/null < "/proc/$1/stat" || return 0
set -- ${_s##*) }
_dd_key=$_dd_key.${20:-}
}
dd_session_others() {
local _p
local -A _known=()
_dd_session=()
for _p in "${_dd_others[@]}"; do
grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null && _dd_session+=("$_p")
dd_pid_key "$_p"
[ -n "${_dd_preloaded[$_dd_key]:-}" ] ||
grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null || continue
_known[$_dd_key]=1
dd_zram_usage "$_p" > /dev/null
_dd_session+=("$_dd_anon $_p")
done
_dd_preloaded=()
for _p in "${!_known[@]}"; do
_dd_preloaded[$_p]=1
done
[ "${#_dd_session[@]}" -gt 0 ] || return 0
mapfile -t _dd_session < <(printf '%s\n' "${_dd_session[@]}" | sort -rn)
_dd_session=("${_dd_session[@]#* }")
}
dd_zram_pick() {
if [ "$1" = game ]; then
dd_session_others
_pids=("${_dd_session[@]}")
[ "${DD_ZRAM_CLIENT:-1}" != 1 ] || _pids+=("${_dd_pids[@]}")
elif [ "$1" = session ]; then
dd_session_others
_pids=("${_dd_session[@]}")
dd_memory_relieved() {
local _k _v _u
while read -r _k _v _u; do
[ "$_k" = MemAvailable: ] || continue
case $_v in ''|*[!0-9]*) return 1 ;; esac
[ "$_v" -ge "$_dd_goal" ]
return
done 2>/dev/null < /proc/meminfo
return 1
}
dd_zram_trim() {
local _mode=$1 _left=$2 _p _k _n _i _acks=()
shift 2
_dd_trimmed=0
for _k in "${!_dd_deaf[@]}"; do
[ "${_dd_deaf[$_k]}" -gt "$SECONDS" ] || unset "_dd_deaf[$_k]"
done
for _p in "$@"; do
[ "$_left" -ge 4096 ] && [ "$_dd_polls" -lt 250 ] && [ $((SECONDS - _dd_pass_at)) -lt 6 ] &&
[ ! -e /tmp/.dd-zram.hold ] || break
! dd_memory_relieved || break
dd_pid_key "$_p"
_k=$_dd_key
[ "${_dd_deaf[$_k]:-0}" -le "$SECONDS" ] || continue
dd_zram_usage "$_p" > /dev/null
[ "$_dd_anon" -ge 8192 ] || continue
printf %s - > "/tmp/.dd-zram.trim.$_p"
_acks+=("/tmp/.dd-zram.trim.$_p")
printf '%s %s\n' "$_mode" "$_left" > /tmp/.dd-zram
kill -URG "$_p" 2>/dev/null || continue
_dd_deaf[$_k]=$((SECONDS + 60))
for ((_i = 0; _dd_polls < 250 && SECONDS - _dd_pass_at < 6; _i++, _dd_polls++)); do
[ ! -e /tmp/.dd-zram.hold ] || { _dd_deaf[$_k]=0; break; }
_n=
read -r _n 2>/dev/null < "/tmp/.dd-zram.trim.$_p" || :
case $_n in
-) [ "$_i" -lt 25 ] || break ;;
''|*[!0-9]*) ;;
*) _dd_trimmed=$((_dd_trimmed + _n)) _left=$((_left - _n)) _dd_deaf[$_k]=0; break ;;
esac
nap 0.02
done
done
[ ! -e /tmp/.dd-zram.hold ] || return 0
printf '2 0\n' > /tmp/.dd-zram
[ "${#_acks[@]}" = 0 ] || rm -f "${_acks[@]}"
}
dd_memory_relieve() {
local _mode=2 _budget _gain=0 _rest _cap=$((256 * 1024)) _all=$((1024 * 1024))
dd_memory_need
_dd_polls=0 _dd_pass_at=$SECONDS
if [ "$_dd_need" -le 0 ]; then
_dd_rest=0
return 0
fi
[ "$_dd_rest" = 0 ] || [ "$_dd_force" = 1 ] || [ "$SECONDS" -ge "$_dd_rest_until" ] ||
[ "$_dd_available" -lt $((_dd_rest_available - _dd_floor / 8)) ] || return 0
if [ "$_dd_swap_room" -lt $((64 * 1024)) ]; then
if [ $((SECONDS - _dd_full_at)) -ge 60 ]; then
_dd_full_at=$SECONDS
step "memory: available $((_dd_available / 1024)) MB and zRAM has no room left"
fi
return 0
fi
if [ "$_dd_force" = 1 ] && [ $((SECONDS - _dd_forced_at)) -ge 10 ]; then
_mode=3 _dd_forced_at=$SECONDS _cap=$_all
else
_pids=("${_dd_pids[@]}")
_cap=$((_cap - _dd_returned)) _all=$((_all - _dd_returned))
fi
if [ "${#_dd_pids[@]}" -gt 0 ] && [ "$_all" -ge 4096 ] &&
{ [ "$_dd_hard" -gt 0 ] ||
{ [ "$_dd_game" = 1 ] && [ "$_dd_focus" != 1 ] && [ $((SECONDS - _dd_back_at)) -ge 30 ]; }; }; then
_budget=$((_dd_need * 1000 / _dd_saving))
[ "$_budget" -le "$_all" ] || _budget=$_all
[ "$_budget" -le "$_dd_swap_room" ] || _budget=$_dd_swap_room
_dd_goal=$((_dd_available + _dd_need))
dd_zram_trim "$_mode" "$_budget" "${_dd_pids[@]}"
_gain=$((_dd_trimmed * _dd_saving / 1000))
_dd_swap_room=$((_dd_swap_room - _dd_trimmed)) _all=$((_all - _dd_trimmed))
[ "$_cap" -le "$_all" ] || _cap=$_all
_dd_client_out=$((_dd_client_out + _dd_trimmed)) _dd_note_client=$((_dd_note_client + _dd_trimmed))
[ "$_dd_trimmed" = 0 ] || _dd_trim_at=$SECONDS
fi
_rest=$((_dd_hard - _gain))
if [ "$_rest" -gt 0 ] && [ "$_cap" -ge 4096 ] && [ "$_dd_swap_room" -ge $((64 * 1024)) ]; then
[ "$_dd_session_at" = "$_dd_scan_at" ] || dd_session_others
_dd_session_at=$_dd_scan_at
_budget=$((_rest * 1000 / _dd_saving))
[ "$_budget" -le "$_cap" ] || _budget=$_cap
[ "$_budget" -le "$_dd_swap_room" ] || _budget=$_dd_swap_room
_dd_goal=$((_dd_available + _dd_hard))
dd_zram_trim "$_mode" "$_budget" "${_dd_session[@]}"
_gain=$((_gain + _dd_trimmed * _dd_saving / 1000))
_dd_note_session=$((_dd_note_session + _dd_trimmed))
fi
_dd_freed=$((_dd_freed + _gain))
if [ "$_dd_hard" -gt 0 ] && [ "$_gain" -lt $((_dd_hard / 4)) ]; then
_dd_rest=$((_dd_rest > 0 ? _dd_rest * 2 : 5))
[ "$_dd_rest" -le 60 ] || _dd_rest=60
_dd_rest_until=$((SECONDS + _dd_rest)) _dd_rest_available=$_dd_available
else
_dd_rest=0
fi
}
dd_zram_wait() {
local _p _left _start=$SECONDS
while [ $((SECONDS - _start)) -lt 12 ]; do
_left=0
for _p in "$@"; do
[ -s "/tmp/.dd-zram.ack.$_p" ] && continue
[ -d "/proc/$_p" ] || continue
[ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.dd-zram.ack.$_p" ] && continue
_left=1
done
[ "$_left" = 1 ] || break
nap 0.2
done
_dd_pageout_complete=1
for _p in "$@"; do
if [ -d "/proc/$_p" ] && [ ! -s "/tmp/.dd-zram.ack.$_p" ]; then _dd_pageout_complete=0; fi
rm -f "/tmp/.dd-zram.ack.$_p"
done
dd_memory_note() {
[ $((_dd_note_client + _dd_note_session)) -ge $((16 * 1024)) ] && [ $((SECONDS - _dd_noted_at)) -ge 5 ] || return 0
step "memory: available $((_dd_available / 1024)) MB, falling $((_dd_rate / 1024)) MB/s, compressed $((_dd_note_client / 1024)) MB of the client and $((_dd_note_session / 1024)) MB of the session"
_dd_note_client=0 _dd_note_session=0 _dd_noted_at=$SECONDS
}
dd_zram_send() {
local _mode=$1 _what=$2 _which=$3 _pids _p
dd_zram_pick "$_which"
step "zRAM: $_what ($(dd_zram_usage "${_pids[@]}"))"
for _p in "${_pids[@]}"; do rm -f "/tmp/.dd-zram.ack.$_p"; done
printf '%s' "$_mode" > /tmp/.dd-zram
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
_dd_zram_targets=("${_pids[@]}")
[ "${4:-}" != defer ] || return 0
dd_zram_finish "$_mode" "${_pids[@]}"
}
dd_zram_finish() {
local _mode=$1
shift
if [ "$_mode" = 1 ]; then dd_zram_wait "$@"; else nap 5; fi
dd_zram_scan
step "zRAM: done ($(dd_zram_usage "$@"))"
dd_client_readback() {
[ "$_dd_client_out" -gt 0 ] && [ "${#_dd_pids[@]}" -gt 0 ] || return 0
[ "$_dd_game" = 0 ] || { [ -n "$_dd_away" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; } || return 0
[ $((SECONDS - _dd_trim_at)) -ge 30 ] || return 0
dd_zram_usage "${_dd_pids[@]}" > /dev/null
if [ "$_dd_swap" -lt $((16 * 1024)) ]; then
_dd_client_out=0
return 0
fi
[ $((_dd_available - _dd_swap)) -ge $((_dd_target + _dd_floor)) ] || return 0
step "memory: available $((_dd_available / 1024)) MB, reading $((_dd_swap / 1024)) MB of the client back"
printf 0 > /tmp/.dd-zram || return 0
kill -URG "${_dd_pids[@]}" 2>/dev/null || return 0
_dd_freed=$((_dd_freed - _dd_swap * _dd_saving / 1000))
_dd_client_out=0 _dd_back_at=$SECONDS
}
dd_game_focused() {
if [ "${DD_DESKTOP:-}" = 1 ] || [ -z "${DD_LAUNCH_DIR:-}" ]; then
@@ -1136,92 +1081,40 @@ case $mode in
esac
return 1
}
dd_over_cap() {
[ "$_dd_ram_cap" -gt 0 ] || return 1
_dd_measured=$SECONDS
dd_session_others
dd_zram_usage "${_dd_pids[@]}" "${_dd_session[@]}" > /dev/null
[ "$_dd_rss" -gt "$_dd_ram_cap" ]
}
dd_cap_due() {
[ "$_dd_ram_cap" -gt 0 ] && { [ "$_dd_measured" -lt 0 ] || [ $((SECONDS - _dd_measured)) -ge 30 ]; }
}
_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_measured=-1 _dd_unpack=0 _dd_capped=-1 _dd_backoff=30
_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_back=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
_dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=() _dd_away=
_dd_sample_at= _dd_sample_available=0 _dd_sample_gpu=0 _dd_sample_unevictable=0 _dd_sample_shmem=0
while kill -0 $$ 2>/dev/null; do
dd_zram_scan
dd_memory_read
if dd_cap_due; then
if dd_over_cap; then
if [ "$_dd_capped" -lt 0 ] || [ $((SECONDS - _dd_capped)) -ge "$_dd_backoff" ]; then
dd_zram_usage "${_dd_pids[@]}" > /dev/null
if [ "$_dd_rss" -ge $((512 * 1024)) ]; then
dd_zram_send 1 "over the ${DD_RAM_CAP_MB} MB RAM cap, compressing the client" client
[ "$_dd_game" = 1 ] && _dd_packed=$SECONDS
else
step "RAM cap: over, client already small ($((_dd_rss / 1024)) MB resident), skipping it"
fi
dd_over_cap && dd_zram_send 1 "still over the RAM cap, compressing the rest of the session" session
if dd_over_cap; then
_dd_backoff=$((_dd_backoff * 2 > 600 ? 600 : _dd_backoff * 2))
step "RAM cap: still over after paging out, next try in ${_dd_backoff} s"
else
_dd_backoff=30
fi
_dd_capped=$SECONDS
fi
else
_dd_backoff=30
dd_memory_tick() {
if [ $((SECONDS - _dd_scan_at)) -ge 5 ]; then
_dd_scan_at=$SECONDS
dd_zram_scan
_dd_focus=1
if [ "$_dd_game" = 1 ]; then
dd_game_focused && _dd_focus=0 || _dd_focus=$?
fi
fi
_dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall
dd_client_pressure defer
_dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall
dd_session_pressure
dd_client_pressure_finish
_dd_focus=1
[ "$_dd_game" = 1 ] && { dd_game_focused && _dd_focus=0 || _dd_focus=$?; }
if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 0 ]; then
_dd_away=
if [ "$_dd_since" -lt 0 ] || [ "$_dd_since_apps" != "$_dd_apps" ]; then
_dd_since=$SECONDS _dd_since_apps=$_dd_apps
fi
if [ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _dd_since)) -ge 20 ] && [ "${#_dd_pids[@]}" -gt 0 ] &&
{ [ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 300 ]; } && dd_client_can_pageout; then
dd_zram_send 1 "compressing the client" client
_dd_packed=$SECONDS
fi
elif [ "$_dd_game" != 1 ]; then
_dd_away=
if [ "$_dd_packed" -ge 0 ]; then
_dd_unpack=1
fi
_dd_since=-1 _dd_packed=-1 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
else
_dd_since=-1
if [ "$_dd_focus" = 1 ]; then
[ -n "${_dd_away-}" ] || _dd_away=$SECONDS
if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 1 ]; then
[ -n "$_dd_away" ] || _dd_away=$SECONDS
else
_dd_away=
fi
if [ "$_dd_packed" -ge 0 ]; then
_dd_unpack=1
fi
fi
if [ "$_dd_unpack" = 1 ] &&
{ [ "$_dd_game" = 0 ] || { [ "${_dd_ram_cap:-0}" = 0 ] && [ -n "${_dd_away-}" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; }; } &&
! dd_over_cap && dd_client_can_readback; then
if [ "$_dd_game" = 0 ]; then
dd_zram_send 0 "memory recovered, reading the client back" client
else
dd_zram_send 0 "the client is in front of the game, reading it back" client
_dd_packed=-1
fi
_dd_unpack=0
dd_memory_read
[ ! -e /tmp/.dd-zram.hold ] || return 0
dd_memory_relieve
dd_memory_note
[ "$_dd_need" -gt 0 ] || dd_client_readback
}
declare -A _dd_deaf=() _dd_preloaded=()
_dd_scan_at=-5 _dd_session_at=-1 _dd_session=() _dd_focus=1 _dd_away=
_dd_page_kb=$(($(getconf PAGESIZE 2>/dev/null || echo 4096) / 1024)) _dd_returned=0 _dd_polls=0 _dd_pass_at=0 _dd_goal=0
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
while kill -0 $$ 2>/dev/null; do
dd_memory_tick
if [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
nap 1
else
nap 5
fi
dd_watch_nap
done
) &
fi
@@ -1529,11 +1422,10 @@ case $mode in
export STEAM_STEAMRT_RECURSION_GUARD=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
dd_steam_path=$PATH
dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
dd_steam_angle=vulkan
dd_steam_presentation=()
if [ "${DD_STEAM_GL_PRESENT:-}" = 1 ]; then
dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true
dd_steam_angle=gl
dd_steam_presentation=(-cef-disable-gpu-compositing)
@@ -66,19 +66,32 @@ BRIGHTNESS_JS = r"""
""".replace("__BINDING__", BRIGHTNESS_BINDING)
def control_request(name, text, directory):
path = os.path.join(directory, name)
with open(path + ".tmp", "w") as target:
target.write(text + "\n")
os.replace(path + ".tmp", path)
def brightness_request(payload, directory=CONTROLS_DIR):
try:
value = float(payload)
if not math.isfinite(value) or not 0 <= value <= 1:
return
path = os.path.join(directory, "brightness.request")
with open(path + ".tmp", "w") as target:
target.write(str(value) + "\n")
os.replace(path + ".tmp", path)
control_request("brightness.request", str(value), directory)
except (ValueError, TypeError, OSError):
return
def hdr_request(payload, directory=CONTROLS_DIR):
if payload not in ("0", "1"):
return
try:
control_request("hdr.request", payload, directory)
except OSError:
return
INSTALL_JS = r"""
(() => {
if (window.__droiddeckCompat) return "present";
@@ -256,6 +269,49 @@ TOUR_JS = r"""
return "off";
})()
"""
SET_SETTING_JS = r"""(field, value) => {
const bytes = [];
for (let n of [field * 8, value]) {
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
bytes.push(n);
}
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
}"""
HDR_BINDING = "droiddeckHdrChanged"
HDR_JS = r"""
(() => {
if (window.__droiddeckHdr) return "present";
const settings = window.settingsStore;
if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" ||
typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
const write = __SET_SETTING__;
const HOLD_MS = 3000;
const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 };
self.set = value => {
if (typeof value !== "boolean") return true;
self.known = value;
if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true;
self.pending = value;
self.until = performance.now() + HOLD_MS;
write(21015, value ? 1 : 0);
return true;
};
self.check = () => {
const value = settings.clientSettings.gamescope_hdr_enabled;
if (typeof value !== "boolean") return;
if (self.pending !== null) {
if (value !== self.pending && performance.now() < self.until) return;
self.pending = null;
}
if (value === self.known) return;
self.known = value;
if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0");
};
self.interval = setInterval(self.check, 500);
window.__droiddeckHdr = self;
return "installed";
})()
""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS)
FRAME_LIMIT_JS = r"""
(() => {
if (window.__droiddeckFrameLimit) return "present";
@@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r"""
}
if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
const self = { timer: null };
const write = value => {
const bytes = [];
for (let n of [21002 * 8, value]) {
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
bytes.push(n);
}
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
};
const write = value => (__SET_SETTING__)(21002, value);
self.check = async () => {
let rates;
try {
@@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r"""
window.__droiddeckFrameLimit = self;
return "installed";
})()
"""
""".replace("__SET_SETTING__", SET_SETTING_JS)
WINDOW_BINDING = "droiddeckWindowAction"
WINDOW_TARGET = "createflags=18"
WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8}
@@ -923,6 +972,9 @@ class Helper:
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.hdr_state = None
self.hdr_installed = False
self.hdr_retry = 0
self.windows = {}
self.windows_retry = 0
@@ -983,6 +1035,29 @@ class Helper:
except (Closed, OSError, ValueError):
del self.windows[ident]
def sync_hdr(self):
try:
with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
value = json.load(source).get("hdr")
if not isinstance(value, bool):
return
if not self.hdr_installed:
if time.monotonic() < self.hdr_retry:
return
self.page.call("Runtime.addBinding", {"name": HDR_BINDING})
self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present")
if not self.hdr_installed:
self.hdr_retry = time.monotonic() + 10
return
if value != self.hdr_state:
if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True:
self.hdr_state = value
else:
self.hdr_state = None
self.hdr_installed = False
except (OSError, ValueError, TypeError, AttributeError):
pass
def sync_frame_limit(self):
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
return
@@ -1095,6 +1170,9 @@ class Helper:
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.hdr_state = None
self.hdr_installed = False
self.hdr_retry = 0
self.sync_controls()
return True
@@ -1231,6 +1309,8 @@ class Helper:
for e in events:
if called(e, BRIGHTNESS_BINDING):
brightness_request(e.get("params", {}).get("payload"))
if called(e, HDR_BINDING):
hdr_request(e.get("params", {}).get("payload"))
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
return events
@@ -1260,6 +1340,7 @@ class Helper:
while True:
self.sync_controls()
self.sync_frame_limit()
self.sync_hdr()
self.sync_windows()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
sources += [page.ws for page in self.windows.values()]
@@ -65,12 +65,14 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
cache_only=
[ "${1:-}" = --cache ] && cache_only=1
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
@@ -167,6 +169,46 @@ if ! fetch_manifest; then
fallback=1
fetch_manifest || exit 1
fi
if [ -n "$cache_only" ]; then
cache=$steam_root/package
cached=$cache/droiddeck-cached
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
$2 == "size" { size[block] = $4 }
$2 == "zipvz" { vz[block] = $4 }
$2 == "sha2vz" { vzsha[block] = $4 }
END {
for (b in file) {
f = file[b]; h = sha[b]; n = size[b] + 0
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
print b, f, h, n
}
}
' "$work/manifest" | sort > "$work/cache"
mkdir -p "$cache"
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
done_bytes=0
i=0
while read -r block file sum size; do
i=$((i + 1))
progress "$cache/$file" "$block"
fetched=""
for host in "${cdn_order[@]}"; do
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
fetched=$host
break
fi
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
done_bytes=$((done_bytes + size))
done < "$work/cache"
echo "$version" > "$cached"
exit 0
fi
if [ -n "$sync" ]; then
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
@@ -10,6 +10,7 @@ import tempfile
DISPLAY = "External: gamescope|||Windowed"
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
@@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text):
return seed_value(text, SCREENSAVER_IN_GAME, '0')
def seed_bouncing_logo(text):
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
def atomic_write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
@@ -179,6 +184,11 @@ def initialize_screensaver(steam_root):
'== steam: no screensaver over a running game')
def initialize_screensaver_choice(steam_root):
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
'== steam: bouncing logo screensaver')
if __name__ == '__main__':
status = 0
try:
@@ -186,7 +196,7 @@ if __name__ == '__main__':
except (OSError, ValueError, RecursionError) as error:
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
status = 1
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
try:
step(sys.argv[1])
except (OSError, ValueError, RecursionError) as error:
@@ -713,14 +713,67 @@ x64_webhelper_gpu() {
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ]
}
x64_thunk_appconfigs() {
python3 - "$1" "$2" "$3" "$4" <<'PY' || true
import json, os, sys, tempfile
src, dst, cfg, on = sys.argv[1:5]
want = json.loads(cfg)
try:
names = sorted(os.listdir(src))
except OSError:
names = []
for name in names:
if not name.endswith(".json"):
continue
try:
db = json.load(open(os.path.join(src, name), encoding="utf-8")).get("ThunksDB") or {}
if not any(k in want["ThunksDB"] and not v for k, v in db.items()):
continue
except (OSError, ValueError, AttributeError):
continue
path = os.path.join(dst, name)
try:
cur = json.load(open(path, encoding="utf-8"))
except FileNotFoundError:
cur = None
except (OSError, ValueError):
continue
if cur is not None and cur != want:
continue
if on == "1" and cur is None:
try:
os.makedirs(dst, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=dst, prefix=".fex", suffix=".tmp")
except OSError:
continue
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(cfg + "\n")
os.link(tmp, path)
except OSError:
pass
finally:
try:
os.remove(tmp)
except OSError:
pass
elif on != "1" and cur is not None:
try:
os.remove(path)
except OSError:
pass
PY
}
x64_env() {
export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true
mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env"
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
gpu_vars="GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR mesa_glthread"
thunk_cfg='{"ThunksDB": {"GL": 1, "Vulkan": 1}}'
rm -f "$X64_HOME/game-gpu.env"
if x64_gpu; then
printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json"
printf '%s\n' "$thunk_cfg" > "$X64_HOME/thunks.json"
{
echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'"
echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER"
@@ -729,7 +782,10 @@ if x64_gpu; then
done
} > "$X64_HOME/game-gpu.env"
fi
if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then
client_thunks=0
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && client_thunks=1
x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"
if [ "$client_thunks" = 1 ]; then
export FEX_THUNKCONFIG=$X64_HOME/thunks.json
unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE
else
@@ -5,6 +5,7 @@ import binascii
import json
import os
import re
import runpy
import shlex
import shutil
import stat
@@ -116,7 +117,7 @@ def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
return str(answer.get("reason") or "failed")
def ask(channel, request, timeout=TIMEOUT):
def ask(channel, request, timeout=TIMEOUT, claim=False):
req_dir, resp_dir = channel / "req", channel / "resp"
req_dir.mkdir(parents=True, exist_ok=True)
resp_dir.mkdir(parents=True, exist_ok=True)
@@ -125,19 +126,33 @@ def ask(channel, request, timeout=TIMEOUT):
tmp.write_text(json.dumps(request))
os.rename(tmp, req_dir / (rid + ".json"))
answer = resp_dir / (rid + ".json")
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
def wait(seconds):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
value = json.loads(answer.read_text())
answer.unlink()
return value
except (OSError, ValueError):
time.sleep(0.05)
return None
value = wait(timeout)
if value is not None:
return value
for pending in (req_dir / (rid + ".json"), resp_dir / (rid + ".taken")):
abandoned = pending.with_name(rid + ".abandoned")
try:
value = json.loads(answer.read_text())
answer.unlink()
return value
except (OSError, ValueError):
time.sleep(0.05)
try:
(req_dir / (rid + ".json")).unlink()
except OSError:
pass
return None
os.rename(pending, abandoned)
except OSError:
continue
try:
abandoned.unlink()
except OSError:
pass
return None
return wait(CLAIMED_TIMEOUT) if claim else None
def windows_path(unix):
@@ -255,7 +270,8 @@ def create_prefix(compat_data, proton, timeout=120):
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
CLAIMED_TIMEOUT = 120.0
CLOUD_STORES = ("gog", "epic", "ea", "ubisoft")
STORE_GAME = 10
RAN = 11
RAN_FAILED = 12
@@ -304,11 +320,14 @@ def exited(argv, code=0):
if found is not None and launch_dir and str(found[1].get("store")) == "ea":
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0)
log("ea %s exited" % found[1].get("id"))
return 0
if found is None or not launch_dir or not cloud_on(found[1]):
return 0
store, game = str(found[1].get("store")), str(found[1].get("id"))
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
try:
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
except OSError as error:
log("cloud %s %s up not requested (%s)" % (store, game, type(error).__name__))
return 0
log("cloud %s %s up requested" % (store, game))
return 0
@@ -319,6 +338,13 @@ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/Ub
ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar")
SERVICE_WAIT = 300.0
ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher"
EPIC_SDK_SETUP = ROCKSTAR_FOLDER + "/Redistributables/SocialClub/Social-Club-Setup.exe"
SDK_SOURCE = ".droiddeck-sdk-source"
SDK_SETUP_LIMIT = 256 * 1024 * 1024
EPIC_PARENT = Path("/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe")
EPIC_PARENT_ON = 'set "DD_P=1"'
EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
EPIC_SERVICE_WAIT = 60.0
ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas",
"gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"}
@@ -376,10 +402,9 @@ def rockstar_sdk(folder, sidecar):
return False
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None, launcher=True):
pfx = Path(compat_data) / "pfx"
launcher = r"C:\Program Files\Rockstar Games\Launcher"
values = [(r"Rockstar Games\Launcher", launcher)]
values = [(r"Rockstar Games\Launcher", r"C:\Program Files\Rockstar Games\Launcher")] if launcher else []
if title:
values.append(("Rockstar Games\\" + title, windows_path(str(folder))))
entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values]
@@ -402,23 +427,29 @@ def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
return result.returncode == 0
def rockstar_runtime(folder, exe, compat_data, arch):
def rockstar_runtime(folder, exe, compat_data, arch, installer=None):
if arch == "x86":
rockstar_runtime(folder, exe, compat_data, "x64")
rockstar_runtime(folder, exe, compat_data, "x64", installer)
pfx = Path(compat_data) / "pfx"
target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club"
if not target.resolve().is_relative_to(pfx.resolve()):
raise ValueError("invalid Social Club destination")
required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ())
marker = target / ".droiddeck-installing"
if all((target / name).is_file() for name in required) and not marker.exists():
source_file, stamp = target / SDK_SOURCE, None
if installer is not None:
info = installer.stat()
stamp = "%d %d %s" % (info.st_size, info.st_mtime_ns, installer)
current = stamp is None or source_file.is_file() and not source_file.is_symlink() and source_file.read_text(errors="replace") == stamp
if all((target / name).is_file() for name in required) and not marker.exists() and current:
return "present"
root = folder.resolve()
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None)
if installer is None:
return "game-runtime"
root = folder.resolve()
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= SDK_SETUP_LIMIT), None)
if installer is None:
return "game-runtime"
tool = shutil.which("7z")
if not tool:
return "no-unpacker"
@@ -470,15 +501,67 @@ def rockstar_runtime(folder, exe, compat_data, arch):
raise
os.replace(stage_path, output)
marker.unlink()
if stamp is not None:
source_file.unlink(missing_ok=True)
source_file.write_text(stamp)
return "installed"
def fetch_service(service, store, launch_dir, ask_app=None):
def epic_parent_switch(sidecar, env=None):
own = sidecar.get("env") if isinstance(sidecar.get("env"), dict) else {}
if EPIC_PARENT_SWITCH in own:
return str(own[EPIC_PARENT_SWITCH]).replace('"', "")
env = os.environ if env is None else env
try:
game_env = runpy.run_path(str(Path(__file__).resolve().with_name("droiddeck-game-env")))
try:
config = json.loads((Path(env.get("HOME") or "/root") / ".config/droiddeck/game-environment.json").read_text(encoding="utf-8"))
except FileNotFoundError:
config = {"version": 1}
env = game_env["apply_config"](env, config, game_env["game_id"](env))
except (OSError, ValueError, KeyError, TypeError, AttributeError):
pass
return env.get(EPIC_PARENT_SWITCH, "")
def wants_epic_parent(folder, switch):
if switch in ("0", "1"):
return switch == "1"
try:
return EPIC_PARENT_ON in (folder / LAUNCHER).read_text(errors="replace").splitlines()
except OSError:
return False
def epic_rockstar_sdk(folder, sidecar, compat_data, proton):
if not compat_data:
return None
pfx = Path(compat_data) / "pfx"
root = folder.resolve()
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
if not exe.is_relative_to(root):
return None
setups = [(pfx / EPIC_SDK_SETUP, pfx)] + [(base / sub / "Social-Club-Setup.exe", root) for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
setup = next((path for path, inside in setups if path.is_file() and path.resolve().is_relative_to(inside.resolve())
and path.stat().st_size <= SDK_SETUP_LIMIT), None)
if setup is None:
return None
made = "present" if (pfx / "user.reg").is_file() else create_prefix(compat_data, proton)
if made not in ("created", "present"):
return "prefix-" + made
state = rockstar_runtime(folder, exe, compat_data, "x64", setup)
if state in ("present", "installed") and not rockstar_registry(folder, None, compat_data, proton, sdk_arch="x64", launcher=False):
return state + " registry-unavailable"
return state
def fetch_service(service, store, launch_dir, ask_app=None, timeout=SERVICE_WAIT):
if service.is_file():
return True
if not launch_dir:
return False
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT)
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=timeout)
return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file()
@@ -1601,7 +1684,7 @@ def main(argv):
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
if launch_dir and cloud_on(sidecar):
if launch_dir and cloud_on(sidecar) and store != "ea":
made = create_prefix(compat_data, os.environ.get("DD_STORE_PROTON", ""))
if made != "present":
log("cloud %s %s prefix=%s" % (store, game, made))
@@ -1632,6 +1715,15 @@ def main(argv):
pass
log("ubisoft %s: not prepared (%s), starting directly" % (game, e))
if store == "epic":
try:
if launch_dir and not EPIC_PARENT.is_file() and wants_epic_parent(folder, epic_parent_switch(sidecar)):
got = fetch_service(EPIC_PARENT, "epic", launch_dir, timeout=EPIC_SERVICE_WAIT)
log("epic parent stand-in: " + ("staged" if got else "unavailable"))
sdk = epic_rockstar_sdk(folder, sidecar, compat_data, os.environ.get("DD_STORE_PROTON", ""))
except (OSError, ValueError, subprocess.TimeoutExpired) as error:
sdk = "failed (%s)" % type(error).__name__
if sdk:
log("epic rockstar sdk: " + sdk)
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
drop_stale(folder)
@@ -1670,13 +1762,16 @@ def main(argv):
log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data)))
if store == "ea":
prepare_ea(folder, sidecar, compat_data, launch_dir)
return STORE_GAME
if not cloud_on(sidecar):
if store in CLOUD_STORES:
log("cloud %s %s down result=skipped reason=off" % (store, game))
return 0
return STORE_GAME if store == "ea" else 0
if launch_dir:
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
try:
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT, claim=True)
except OSError as error:
log("cloud %s %s down result=failed reason=%s" % (store, game, type(error).__name__))
return STORE_GAME
if answer is None:
log("cloud %s %s down result=timeout" % (store, game))
else:
@@ -1,4 +1,5 @@
#!/usr/bin/python3
import hashlib
import hmac
import json
import os
@@ -11,6 +12,7 @@ import subprocess
import sys
import tempfile
import threading
import xml.etree.ElementTree as ElementTree
BIN = Path(__file__).resolve().parent
RUNTIME = Path('/usr/local/lib/droiddeck-xbox')
@@ -137,6 +139,117 @@ def register_classes(proton, prefix, env):
print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr)
def game_config(exe):
path = Path(exe)
if not path.is_absolute():
return None
for folder in list(path.parents)[:4]:
config = folder / 'MicrosoftGame.config'
if config.is_file():
return config
return None
def windows_arguments(text):
arguments, current, quoted, started, at = [], [], False, False, 0
while at < len(text):
char = text[at]
if char == '\\':
run = len(text) - at - len(text[at:].lstrip('\\'))
at += run
if at < len(text) and text[at] == '"':
current.append('\\' * (run // 2))
if run % 2:
current.append('"')
at += 1
else:
current.append('\\' * run)
started = True
continue
if char == '"':
if quoted and text[at + 1:at + 2] == '"':
current.append('"')
at += 2
continue
quoted = not quoted
started = True
elif char in ' \t' and not quoted:
if started:
arguments.append(''.join(current))
current, started = [], False
else:
current.append(char)
started = True
at += 1
if started:
arguments.append(''.join(current))
return arguments
def install_actions(config):
try:
root = ElementTree.fromstring(config.read_bytes())
except (OSError, ElementTree.ParseError):
return []
actions = []
for registration in root.iter():
if registration.tag.rsplit('}', 1)[-1] != 'CustomInstallActions':
continue
folder = next((node.text or '' for node in registration if node.tag.rsplit('}', 1)[-1] == 'Folder'), '')
for node in registration.iter():
if node.tag.rsplit('}', 1)[-1] != 'InstallAction':
continue
name, file = node.get('Name', ''), node.get('File', '')
parts = [part for part in (folder.strip() + '\\' + file).replace('/', '\\').split('\\') if part]
if not name or not file or any(part in ('.', '..') or ':' in part for part in parts):
continue
target = config.parent.joinpath(*parts)
try:
inside = target.resolve().is_relative_to(config.parent.resolve())
except OSError:
inside = False
if inside and target.is_file() and target.suffix.lower() in ('.msi', '.exe'):
actions.append((name, target, windows_arguments(node.get('Arguments', ''))))
return actions
def run_install_actions(proton, prefix, exe, env):
config = game_config(exe)
if config is None:
return
done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions'
for name, target, arguments in install_actions(config):
try:
content = hashlib.sha256()
with target.open('rb') as source:
for block in iter(lambda: source.read(1 << 20), b''):
content.update(block)
identity = hashlib.sha256(name.encode('utf-8') + b'\0' + content.digest()).hexdigest()[:24]
marker = done / ('%s-%s' % (''.join(c for c in name if c.isalnum() or c in '-_')[:64], identity))
if marker.exists():
continue
except OSError as error:
print('droiddeck-xbox: install action %s could not be read (%s); launching without it' % (name, error), file=sys.stderr)
continue
windows = 'Z:' + str(target).replace('/', '\\')
if target.suffix.lower() == '.msi':
command = [proton, 'run', 'msiexec', '/i', windows, *arguments]
else:
command = [proton, 'run', windows, *arguments]
try:
code = subprocess.run(command, stdout=sys.stderr, env=env, timeout=600).returncode
except (OSError, subprocess.TimeoutExpired):
code = None
if code != 0:
print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr)
continue
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)
def view_drive(prefix, exe):
path = Path(exe)
view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None)
@@ -184,6 +297,7 @@ def wine(argv, source_env=None):
target.unlink()
shutil.copyfile(RUNTIME / 'windows' / name, target)
register_classes(command[0], prefix, env)
run_install_actions(command[0], prefix, argv[0], env)
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
exe, drive = view_drive(prefix, argv[0])
@@ -390,7 +504,7 @@ def launch(command, env):
raise RuntimeError('No Xbox account channel; start the game from DroidDeck')
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190)
if not reply or not reply.get('ok'):
raise RuntimeError('Xbox account service is unavailable; sign in again and retry')
raise RuntimeError((reply or {}).get('reason') or 'Xbox account service is unavailable; sign in again and retry')
stopped = threading.Event()
close = lambda: None
try:
@@ -404,7 +518,7 @@ def launch(command, env):
context.chmod(0o600)
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'none')
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
owned_env.pop(name, None)
if reply.get('playfab'):
@@ -1089,9 +1089,10 @@ NATIVE_CHOICE = object()
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
native_choices=(), tools=None):
native_choices=(), tools=None, removed=()):
tools = tools or {}
runnable = {n.lower() for n in runnable}
removed = {n.lower() for n in removed} - runnable
installed = set(installed)
picks = set(picks) | {app for app, platforms in tools.items() if "linux" not in platforms}
native = native or {}
@@ -1121,7 +1122,7 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
target = native.get(app, default)
if not name and (app in native_choices or (app in current and app in FEX_DEFAULT_APPS)):
target = NATIVE_CHOICE
stale = unrunnable(name, runnable)
stale = unrunnable(name, runnable) or name.lower() in removed
if name and not stale and (mine is None or name != mine):
continue
if target is NATIVE_CHOICE:
@@ -1163,6 +1164,26 @@ def followers(state, current):
return {app: name for app, name in current.items() if app != "0" and name == TOOL}
REPLACING = ".droiddeck-experimental-old"
def removed_tools(state, catalog, directory=None):
known = state.get("tools") if isinstance(state.get("tools"), list) else ()
previous = {t.get("name") for t in known if isinstance(t, dict) and not t.get("valve") and t.get("name")}
removed = previous - {t["name"] for t in catalog}
if directory is None:
return removed
known_dirs = {t.get("name"): t.get("dir") for t in known if isinstance(t, dict)}
return {name for name in removed if isinstance(known_dirs.get(name), str) and
not os.path.lexists(os.path.join(directory, known_dirs[name])) and
not os.path.lexists(os.path.join(directory, REPLACING, known_dirs[name]))}
def removed_dirs(state, removed):
known = state.get("tools") if isinstance(state.get("tools"), list) else ()
return {t["dir"] for t in known if isinstance(t, dict) and not t.get("valve") and t.get("name") in removed and isinstance(t.get("dir"), str)} - {""}
def tool_entry(name, display, path, valve):
return {"name": name, "display": display, "dir": os.path.basename(path) if path else "", "valve": valve}
@@ -1248,15 +1269,19 @@ def valid_game_request(app, request):
request["dir"] != "" and isinstance(request.get("valve"), bool)))
def settle_game_requests(requests, state, current, catalog, missing_is_cleared=False):
def settle_game_requests(requests, state, current, catalog, missing_is_cleared=False, removed=()):
recorded = state.get("games_applied")
if isinstance(recorded, dict):
applied = dict(recorded)
else:
applied = dict(requests) if "tools" in state else {}
by_name = {t["name"]: t for t in catalog}
gone = removed_dirs(state, removed)
out = dict(requests)
for app, request in requests.items():
if isinstance(request, dict) and request.get("valve") is False and isinstance(request.get("dir"), str) and request["dir"] in gone:
del out[app]
continue
if not valid_game_request(app, request) or app not in applied or applied[app] != request:
continue
if request is None:
@@ -1281,10 +1306,10 @@ def settle_game_requests(requests, state, current, catalog, missing_is_cleared=F
return out, out != requests
def settled_game_requests(state, current, catalog, missing_is_cleared=False, directory=None):
def settled_game_requests(state, current, catalog, missing_is_cleared=False, directory=None, removed=()):
for _ in range(2):
requests, text = read_game_requests(directory)
settled, moved = settle_game_requests(requests, state, current, catalog, missing_is_cleared)
settled, moved = settle_game_requests(requests, state, current, catalog, missing_is_cleared, removed)
if not moved or write_game_requests(settled, text, directory):
return settled
return None
@@ -1579,7 +1604,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
set_mappings(tokens, mapping, moved)
current.update(moved)
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
removed = removed_tools(state, catalog, os.path.join(steam_root, "compatibilitytools.d"))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory, removed)
overrides = requested_games(requests or {}, catalog)
managed = state.get("auto", {}).keys() if isinstance(state.get("auto"), dict) else ()
native_choices = state.get("native_choices", ())
@@ -1590,7 +1616,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
current.setdefault(app, "")
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices, tool_platforms(steam_root))
overrides, managed, native_choices, tool_platforms(steam_root), removed)
set_mappings(tokens, mapping, changes)
text = serialize(tokens)
if text != serialize(tokenize(original)):
+38 -21
View File
@@ -21,6 +21,29 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) {
if (!file || !*file) return 0;
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
const char *paths = getenv("PATH");
if (!paths) paths = "/bin:/usr/bin";
char candidate[PATH_MAX];
int found = 0;
for (const char *p = paths;; ) {
const char *end = strchrnul(p, ':');
int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file)
: snprintf(candidate, sizeof candidate, "%s", file);
struct stat st;
if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) {
int runs = access(candidate, X_OK) == 0;
if (runs || !found) memcpy(out, candidate, (size_t)n + 1);
found = 1;
if (runs) return 1;
}
if (!*end) return found;
p = end + 1;
}
}
#if defined(__aarch64__) || defined(BINFMT_TEST)
static int flag(const char *name) {
@@ -32,17 +55,26 @@ static int handing_off(void) {
return flag("DD_DESKTOP") || flag("DD_BINFMT");
}
static int appimage(int fd, const unsigned char *head, ssize_t n) {
Elf64_Ehdr eh;
if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0;
memcpy(&eh, head, sizeof eh);
char magic[6];
off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum;
return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6));
}
static int foreign(const char *path, int error) {
if (!path || !strcmp(path, BINFMT_HANDLER)) return 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
struct stat st;
unsigned char head[20];
unsigned char head[sizeof(Elf64_Ehdr)];
ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1;
int kind = 0;
if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) {
unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8;
kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0;
kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0;
} else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') {
kind = 2;
} else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) {
@@ -58,21 +90,6 @@ static int wanted(const char *path, int error) {
return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error);
}
static int lookup(const char *file, char *out, size_t size) {
if (!file || !*file) return 0;
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
const char *paths = getenv("PATH");
if (!paths) paths = "/bin:/usr/bin";
for (const char *p = paths;; ) {
const char *end = strchrnul(p, ':');
int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file);
struct stat st;
if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1;
if (!*end) return 0;
p = end + 1;
}
}
static int count(char *const argv[]) {
int n = 0;
while (argv && argv[n]) n++;
@@ -117,12 +134,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char
__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) {
char path[PATH_MAX];
if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
}
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) {
char path[PATH_MAX];
if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
errno = error;
return -1;
}
@@ -144,7 +161,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char
int execvpe(const char *file, char *const argv[], char *const envp[]) {
char resolved[PATH_MAX];
const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file;
const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file;
char *const *adjusted = dd_webhelper_argv(path, argv, envp);
static int (*real)(const char *, char *const[], char *const[]);
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe");
@@ -156,7 +173,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) {
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr,
char *const argv[], char *const envp[]) {
char path[PATH_MAX];
int found = lookup(file, path, sizeof path);
int found = dd_program_lookup(file, path, sizeof path);
char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp);
static spawn_fn real, spawn;
if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp");
+2 -14
View File
@@ -25,7 +25,6 @@
#define CP_FDS 65536
static const int64_t *cp_shift;
static int cp_state;
static size_t cp_cond_byte;
static unsigned char cp_cond_mask;
static unsigned char cp_fds[CP_FDS / 8];
@@ -94,25 +93,14 @@ static void cp_init(void) {
}
static int64_t cp_offset(void) {
const int64_t *shift;
int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE);
if (state == 0) {
int expected = 0;
if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
cp_init();
__atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE);
}
return 0;
}
if (state != 2) return 0;
shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
if (!shift) return 0;
int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED);
return value > 0 ? value : 0;
}
__attribute__((constructor)) static void cp_start(void) {
cp_offset();
cp_init();
}
static int cp_mono(clockid_t clock) {
+168 -57
View File
@@ -23,10 +23,11 @@
#define MAX_ENTRIES 100000
#define MAX_HANDLES 64
#define MAX_UP 32
#define MAX_ALIASES 4
#define FUSE_MAGIC 0x65735546
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR)
#define ABOVE (IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR | IN_MASK_ADD)
#define GONE (IN_DELETE_SELF | IN_MOVE_SELF | IN_IGNORED)
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ATTRIB | IN_ONLYDIR)
#define ABOVE (IN_DELETE_SELF | IN_MOVE_SELF | IN_ATTRIB | IN_ONLYDIR | IN_MASK_ADD)
#define GONE (IN_DELETE_SELF | IN_MOVE_SELF | IN_ATTRIB | IN_IGNORED)
#define LINKED (IN_DELETE_SELF | IN_MOVE_SELF | IN_DONT_FOLLOW | IN_MASK_ADD)
#if __SIZEOF_POINTER__ == 8
@@ -54,6 +55,9 @@ struct listing {
size_t len;
char *where;
int folds;
int loose;
char *alias[MAX_ALIASES];
int aliases;
};
struct handle {
@@ -78,6 +82,7 @@ static struct listing *table[MAX_LISTINGS];
static struct handle *handles[MAX_HANDLES];
static int high_water;
static int cached_listings;
static int blind_listings;
static int changing;
static int notify = -1;
static int forked;
@@ -171,6 +176,7 @@ static void destroy(struct listing *l) {
free(l->e);
free(l->recs);
free(l->where);
for (int i = 0; i < MAX_ALIASES; i++) free(l->alias[i]);
free(l);
}
@@ -201,6 +207,7 @@ static void let_go(int wd, const int *up, int nup) {
static void detach(struct listing *l) {
__atomic_sub_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
if (l->blind || l->where == NULL) blind_listings--;
l->detached = 1;
if (l->refs == 0) destroy(l);
}
@@ -255,6 +262,7 @@ static void pump(struct expect *x, int nx) {
changed(-1, 0);
continue;
}
if ((ev->mask & IN_ATTRIB) && ev->len) continue;
int k = 0;
while (k < nx && !(x[k].wd == ev->wd && (ev->mask & x[k].mask) && ev->len && strcmp(ev->name, x[k].name) == 0)) k++;
if (k < nx) {
@@ -304,6 +312,7 @@ static int push(struct listing *l, ino_t ino, unsigned char type, const char *na
static void install(struct listing *l) {
l->detached = 0;
__atomic_add_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
if (l->blind || l->where == NULL) blind_listings++;
int slot = find(l->dev, l->ino);
if (slot >= 0) {
struct listing *old = table[slot];
@@ -416,10 +425,104 @@ __attribute__((constructor)) static void resolve(void) {
}
#pragma GCC diagnostic pop
static int named(const struct listing *l, const char *name) {
for (size_t i = 0; i < l->n; i++)
if (strcasecmp(l->e[i].name, name) == 0) return 1;
return 0;
}
static int folded_match(const char *where, const char *dir) {
const char *at = strstr(where, "/steamapps");
if (at == NULL) return 0;
size_t n = (size_t)(at - where);
return strncmp(where, dir, n) == 0 && strcasecmp(where + n, dir + n) == 0;
}
static int same_dir(const struct listing *l, const char *dir) {
struct stat st;
int saved = errno;
int same = stat(dir, &st) == 0 && st.st_dev == l->dev && st.st_ino == l->ino;
errno = saved;
return same;
}
static int plain(const char *where, char *dir) {
const char *at = strstr(where, "/steamapps");
int saved = errno, fine = at != NULL;
for (size_t from = fine ? (size_t)(at - where) + 1 : 0; fine && dir[from];) {
size_t to = from + strcspn(dir + from, "/");
char kept = dir[to];
struct stat st;
dir[to] = 0;
fine = strcmp(dir + from, ".") != 0 && strcmp(dir + from, "..") != 0 && lstat(dir, &st) == 0 && !S_ISLNK(st.st_mode);
dir[to] = kept;
from = kept ? to + 1 : to;
}
errno = saved;
return fine;
}
static int aliased(struct listing *l, const char *dir) {
for (int i = 0; i < MAX_ALIASES; i++)
if (l->alias[i] && strcmp(l->alias[i], dir) == 0) return 1;
if (!same_dir(l, dir)) return 0;
char *copy = strdup(dir);
if (copy && !plain(l->where, copy)) {
free(copy);
copy = NULL;
}
if (copy) {
int at = l->aliases++ % MAX_ALIASES;
free(l->alias[at]);
l->alias[at] = copy;
}
return 1;
}
static struct listing *listed(const char *dir, long long now) {
for (int i = 0; i < MAX_LISTINGS; i++) {
struct listing *l = table[i];
if (l == NULL || l->where == NULL || l->blind || now - l->filled >= DIR_TTL_NS) continue;
if (strcmp(l->where, dir) == 0) return l;
if (l->folds && folded_match(l->where, dir)) return aliased(l, dir) ? l : NULL;
}
return NULL;
}
static int watching(const char *path) {
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
}
static DIR *listed_open(struct handle *h, long long now) {
DIR *d = NULL;
if (__atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) == 0) return NULL;
take(&lock);
if (!changing) {
pump(NULL, 0);
struct listing *l = listed(h->path, now);
if (l && records(l) == 0) {
h->snap = l;
l->refs++;
l->used = now;
d = wrap(h);
if (d == NULL) {
unref(l);
h->snap = NULL;
}
}
}
give(&lock);
return d;
}
static DIR *hit(const struct stat *st, struct handle *h, long long now) {
take(&lock);
if (!changing) pump(NULL, 0);
int slot = find(st->st_dev, st->st_ino);
if (slot >= 0 && table[slot]->loose && now - table[slot]->filled < DIR_TTL_NS) {
stamp(table[slot], st);
table[slot]->loose = 0;
}
if (slot >= 0 && same(table[slot], st) && now - table[slot]->filled < DIR_TTL_NS && records(table[slot]) == 0) {
h->snap = table[slot];
h->snap->refs++;
@@ -509,8 +612,7 @@ static void untrack(struct handle *h) {
DIR *opendir(const char *path) {
NEXT(opendir);
struct stat st;
if (!eligible(path) || stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !on_fuse(st.st_dev, path))
return next_opendir(path);
if (!eligible(path)) return next_opendir(path);
struct handle *h = calloc(1, sizeof(*h));
char *copy = strdup(path);
if (h == NULL || copy == NULL) {
@@ -522,7 +624,14 @@ DIR *opendir(const char *path) {
h->wd = -1;
h->path = copy;
long long now = now_ns();
DIR *d = hit(&st, h, now);
DIR *d = listed_open(h, now);
if (d) return d;
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !on_fuse(st.st_dev, path)) {
free(h->path);
free(h);
return next_opendir(path);
}
d = hit(&st, h, now);
if (d) return d;
if (!track(h, path)) {
free(h->path);
@@ -699,7 +808,9 @@ void seekdir(DIR *d, long pos) {
}
}
struct side { char dir[PATH_MAX]; const char *name; struct stat before; int known; };
struct side { char dir[PATH_MAX]; const char *name; struct stat before; int known; int trusted; };
struct made { int known; ino_t ino; unsigned char type; };
static int split(const char *path, struct side *s) {
size_t n = strlen(path);
@@ -713,10 +824,6 @@ static int split(const char *path, struct side *s) {
return strchr(s->name, '/') == NULL && strcmp(s->name, ".") != 0 && strcmp(s->name, "..") != 0;
}
static int watching(const char *path) {
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
}
static void begin(void) {
take(&lock);
pump(NULL, 0);
@@ -725,13 +832,42 @@ static void begin(void) {
}
static void before(struct side *s) {
s->known = stat(s->dir, &s->before) == 0;
take(&lock);
struct listing *l = listed(s->dir, now_ns());
int unlisted = l == NULL && blind_listings == 0;
s->trusted = l != NULL;
if (l) {
memset(&s->before, 0, sizeof(s->before));
s->before.st_dev = l->dev;
s->before.st_ino = l->ino;
s->before.st_size = l->size;
s->before.st_nlink = l->nlink;
s->before.st_mtim = l->mtime;
s->before.st_ctim = l->ctime;
}
give(&lock);
s->known = s->trusted || (!unlisted && stat(s->dir, &s->before) == 0);
}
static unsigned char type_of(mode_t mode) {
return S_ISDIR(mode) ? DT_DIR : S_ISLNK(mode) ? DT_LNK : S_ISREG(mode) ? DT_REG : DT_UNKNOWN;
}
static int made_at(const struct side *s, const char *target, struct made *m) {
struct stat t;
if (s->trusted && m && m->known) return 1;
if (lstat(target, &t) != 0) return 0;
*m = (struct made){1, t.st_ino, type_of(t.st_mode)};
return 1;
}
enum { ADDED, REMOVED };
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct expect *x) {
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct made *m,
struct expect *x) {
struct stat now;
struct made local = {0};
if (m == NULL) m = &local;
if (!s->known) return 0;
int slot = find(s->before.st_dev, s->before.st_ino);
if (slot < 0) return 0;
@@ -750,7 +886,7 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
drop(slot);
return 0;
}
if (stat(s->dir, &now) != 0 || now.st_ino != l->ino) {
if (!s->trusted && (stat(s->dir, &now) != 0 || now.st_ino != l->ino)) {
drop(slot);
return 0;
}
@@ -771,6 +907,7 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
copy->blind = l->blind;
copy->where = l->where ? strdup(l->where) : NULL;
copy->folds = l->folds;
copy->loose = l->loose;
copy->detached = 0;
stamp(copy, &s->before);
table[slot] = copy;
@@ -781,18 +918,17 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
l->recs = NULL;
l->len = 0;
int fine = 1, expected = 1;
struct stat t;
if (what == ADDED) {
if (exact < l->n) {
if (lstat(target, &t) == 0) l->e[exact].ino = t.st_ino;
if (event == IN_MOVED_TO && made_at(s, target, m)) l->e[exact].ino = m->ino;
expected = event == IN_MOVED_TO;
} else if (folded < l->n || lstat(target, &t) != 0) {
} else if (folded < l->n || !made_at(s, target, m)) {
fine = 0;
} else {
unsigned char type = S_ISDIR(t.st_mode) ? DT_DIR : S_ISLNK(t.st_mode) ? DT_LNK : S_ISREG(t.st_mode) ? DT_REG : DT_UNKNOWN;
fine = l->n < MAX_ENTRIES && push(l, t.st_ino, type, s->name) == 0;
fine = l->n < MAX_ENTRIES && push(l, m->ino, m->type, s->name) == 0;
}
} else if (exact < l->n) {
*m = (struct made){1, l->e[exact].ino, l->e[exact].type};
free(l->e[exact].name);
memmove(&l->e[exact], &l->e[exact + 1], (l->n - exact - 1) * sizeof(l->e[0]));
l->n--;
@@ -803,7 +939,8 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co
drop(slot);
return 0;
}
stamp(l, &now);
if (s->trusted) l->loose = 1;
else stamp(l, &now);
if (!expected) return 0;
*x = (struct expect){l->wd, event, s->name};
return 1;
@@ -829,8 +966,11 @@ int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int fd = real(dirfd, path, flags, mode);
int saved = errno;
struct expect x;
struct stat opened;
struct made m = {0};
if (fd >= 0 && s.trusted && fstat(fd, &opened) == 0) m = (struct made){1, opened.st_ino, type_of(opened.st_mode)};
take(&lock);
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &x);
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &m, &x);
give(&lock);
end(&x, nx);
give(&oplock);
@@ -850,7 +990,7 @@ int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int saved = errno; \
struct expect x; \
take(&lock); \
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, &x); \
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, NULL, &x); \
if (r == 0 && what == REMOVED) forget_below(path); \
give(&lock); \
end(&x, nx); \
@@ -885,12 +1025,13 @@ ONE_PATH(remove, REMOVED, IN_DELETE, dd_descriptor_remove(path, next_remove))
int r = call(from, to); \
int saved = errno; \
struct expect x[2]; \
struct made m = {0}; \
int nx = 0; \
take(&lock); \
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &x[nx]); \
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &m, &x[nx]); \
if (track_b) { \
if (track_a && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
nx += patch(&b, ADDED, event, r == 0, saved, to, &x[nx]); \
if (track_a && !b.trusted && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
nx += patch(&b, ADDED, event, r == 0, saved, to, &m, &x[nx]); \
} \
if (r == 0 && gone) { forget_below(from); forget_below(to); } \
give(&lock); \
@@ -907,37 +1048,6 @@ TWO_PATHS(rename, 1, IN_MOVED_TO, moved)
TWO_PATHS(link, 0, IN_CREATE, link_or_lock)
TWO_PATHS(symlink, 0, IN_CREATE, next_symlink)
static int named(const struct listing *l, const char *name) {
for (size_t i = 0; i < l->n; i++)
if (strcasecmp(l->e[i].name, name) == 0) return 1;
return 0;
}
static int folded_match(const char *where, const char *dir) {
const char *at = strstr(where, "/steamapps");
if (at == NULL) return 0;
size_t n = (size_t)(at - where);
return strncmp(where, dir, n) == 0 && strcasecmp(where + n, dir + n) == 0;
}
static int same_dir(const struct listing *l, const char *dir) {
struct stat st;
int saved = errno;
int same = stat(dir, &st) == 0 && st.st_dev == l->dev && st.st_ino == l->ino;
errno = saved;
return same;
}
static int listed_absent(const char *dir, const char *name, long long now) {
for (int i = 0; i < MAX_LISTINGS; i++) {
struct listing *l = table[i];
if (l == NULL || l->where == NULL || l->blind || now - l->filled >= DIR_TTL_NS) continue;
if (strcmp(l->where, dir) == 0) return !named(l, name);
if (l->folds && folded_match(l->where, dir)) return same_dir(l, dir) && !named(l, name);
}
return 0;
}
int dd_dircache_absent(const char *path) __attribute__((visibility("hidden")));
int dd_dircache_absent(const char *path) {
struct side s;
@@ -949,7 +1059,8 @@ int dd_dircache_absent(const char *path) {
int absent = 0;
if (!changing) {
pump(NULL, 0);
absent = listed_absent(s.dir, s.name, now);
struct listing *l = listed(s.dir, now);
absent = l != NULL && !named(l, s.name);
}
give(&lock);
return absent;
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -111,6 +111,9 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
static unsigned guarded_port(void);
__attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd);
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
int (*real_bind)(int, const struct sockaddr *, socklen_t),
int *rc);
__attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr,
socklen_t len, int *rc);
__attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr,
@@ -121,6 +124,7 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
int nl_rc;
if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind");
if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc;
if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc;
if (dd_udevmon_stand_in(fd)) {
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) {
errno = EINVAL;
@@ -273,6 +277,7 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size);
__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
spawn_fn real);
@@ -373,7 +378,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
}
int execvp(const char *file, char *const argv_in[]) {
char *const *argv = dd_webhelper_argv(file, argv_in, environ);
char resolved[PATH_MAX];
char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
maybe_answer_lsof(file, argv);
+111 -27
View File
@@ -22,6 +22,7 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
@@ -520,6 +521,13 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
fprintf(out, "%6s: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", link->name);
} else if (strcmp(table, "arp") == 0) {
fprintf(out, "IP address HW type Flags HW address Mask Device\n");
} else if (strcmp(table, "tcp") == 0 || strcmp(table, "udp") == 0) {
fprintf(out, " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n",
table[0] == 'u' ? " ref pointer drops" : "");
} else if (strcmp(table, "tcp6") == 0 || strcmp(table, "udp6") == 0) {
fprintf(out, " sl local_address remote_address "
"st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n",
table[0] == 'u' ? " ref pointer drops" : "");
} else {
fprintf(out, "1\n");
}
@@ -527,7 +535,10 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
#define CARRIER_TABLE 5
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" };
#define SOCKET_TABLES 6
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier",
"tcp", "tcp6", "udp", "udp6" };
static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])];
#define CARRIER_SLOTS 8
@@ -564,8 +575,8 @@ static void remember_denial(int table, const char *path) {
static int denied_table(const char *path) {
if (strncmp(path, "/proc/net/", 10) == 0) {
for (int i = 0; i < CARRIER_TABLE; i++) {
if (strcmp(path + 10, net_tables[i]) == 0) return i;
for (int i = 0; i < (int) (sizeof(net_tables) / sizeof(net_tables[0])); i++) {
if (i != CARRIER_TABLE && strcmp(path + 10, net_tables[i]) == 0) return i;
}
return -1;
}
@@ -576,17 +587,17 @@ static int denied_table(const char *path) {
return -1;
}
static FILE *synthesize(const char *table) {
static FILE *synthesize(int table) {
struct link link;
if (!load_link(&link)) return NULL;
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC);
if (!load_link(&link) && table < SOCKET_TABLES) return NULL;
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) return NULL;
FILE *out = fdopen(fd, "w+");
if (out == NULL) {
close(fd);
return NULL;
}
write_table(out, table, &link);
write_table(out, net_tables[table], &link);
if (fflush(out) != 0) {
fclose(out);
return NULL;
@@ -610,11 +621,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
path = dd_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+')));
int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1;
FILE *f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f;
f = real(path, mode);
if (f || table < 0) return f;
int saved = errno;
if ((f = synthesize(net_tables[table])) != NULL) {
if ((f = synthesize(table)) != NULL) {
if (saved == EACCES) remember_denial(table, path);
return f;
}
@@ -622,6 +633,33 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
return NULL;
}
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
int dd_net_open(const char *path, int flags, int fd) {
if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
int table = denied_table(path);
if (table < 0) return fd;
int saved = errno;
FILE *f = synthesize(table);
if (f == NULL) {
errno = saved;
return fd;
}
char self[32];
snprintf(self, sizeof(self), "/proc/self/fd/%d", fileno(f));
int copy = open(self, O_RDONLY | (flags & O_CLOEXEC));
if (copy < 0 && fcntl(fileno(f), F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) == 0) {
copy = fcntl(fileno(f), flags & O_CLOEXEC ? F_DUPFD_CLOEXEC : F_DUPFD, 0);
}
fclose(f);
if (copy < 0) {
errno = saved;
return fd;
}
if (saved == EACCES) remember_denial(table, path);
return copy;
}
FILE *fopen(const char *path, const char *mode) {
static fopen_fn real;
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen");
@@ -664,6 +702,7 @@ struct nl_socket {
unsigned references;
int type;
int cap_ack;
uint64_t groups;
struct nl_socket *next;
};
@@ -685,13 +724,14 @@ struct nl_fd_page {
struct nl_metadata {
uint64_t nonce;
uint64_t groups;
uint32_t port;
uint32_t type;
uint32_t cap_ack;
char magic[12];
};
_Static_assert(sizeof(struct nl_metadata) == 32, "netlink socket metadata ABI");
_Static_assert(sizeof(struct nl_metadata) == 40, "netlink socket metadata ABI");
struct nl_packet {
struct nl_packet *next;
@@ -705,9 +745,9 @@ struct nl_reply {
int overflow;
};
static const char nl_client_magic[12] = "dd-nl-c-v1";
static const char nl_peer_magic[12] = "dd-nl-p-v1";
static const char nl_reservation_magic[12] = "dd-nl-r-v1";
static const char nl_client_magic[12] = "dd-nl-c-v2";
static const char nl_peer_magic[12] = "dd-nl-p-v2";
static const char nl_reservation_magic[12] = "dd-nl-r-v2";
static struct nl_socket *nl_sockets;
static struct nl_fd *nl_fds;
static struct nl_fd_page *nl_fd_pages[NL_FD_BUCKETS];
@@ -910,13 +950,13 @@ static int nl_save_packets(int fd, struct nl_packet **packets) {
}
}
static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped) {
static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped, uint64_t groups) {
static int (*real_socket)(int, int, int);
static int (*real_close)(int);
if (real_socket == NULL) real_socket = (int (*)(int, int, int)) dlsym(RTLD_NEXT, "socket");
if (real_close == NULL) real_close = (int (*)(int)) dlsym(RTLD_NEXT, "close");
struct sockaddr_un client_addr, peer_addr;
struct nl_metadata client, peer = { .port = port, .type = socket->type, .cap_ack = capped };
struct nl_metadata client, peer = { .groups = groups, .port = port, .type = socket->type, .cap_ack = capped };
if (!nl_address(fd, 0, &client_addr, &client, nl_client_magic)) {
errno = EINVAL;
return -1;
@@ -955,6 +995,7 @@ static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int
socket->peer_inode = status.st_ino;
socket->port = port;
socket->cap_ack = capped;
socket->groups = groups;
errno = saved;
return replayed;
failed: {
@@ -1025,7 +1066,7 @@ static struct nl_fd *nl_restore(int fd) {
socket->device = status.st_dev;
socket->inode = status.st_ino;
socket->type = peer.type;
if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack) != 0) {
if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack, peer.groups) != 0) {
free(socket);
free(entry);
return NULL;
@@ -1159,7 +1200,7 @@ static int nl_peer_of(int fd) {
if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) {
if ((metadata.nonce == socket->peer_inode
&& nl_identity(socket->peer, socket->device, socket->peer_inode))
|| nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack) == 0) {
|| nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack, metadata.groups) == 0) {
if (socket->port != 0 && (socket->reservation < 0
|| !nl_identity(socket->reservation, socket->device, socket->reservation_inode)))
nl_reserve_port(socket, socket->port);
@@ -1317,7 +1358,7 @@ static int nl_bind_port(int fd, unsigned requested, int automatic) {
}
if (other == NULL) {
if (nl_reserve_port(socket, port) == 0) {
result = nl_replace_peer(fd, socket, port, socket->cap_ack);
result = nl_replace_peer(fd, socket, port, socket->cap_ack, socket->groups);
if (result != 0) nl_close_reservation(socket);
break;
}
@@ -1342,6 +1383,23 @@ static int nl_autobind(int fd) {
return nl_bind_port(fd, 0, 1);
}
static int nl_set_groups(int fd, uint64_t keep, uint64_t add) {
int result = 0;
pthread_mutex_lock(&nl_sockets_lock);
struct nl_fd *entry = nl_find(fd);
if (entry) {
struct nl_socket *socket = entry->socket;
struct sockaddr_un addr;
struct nl_metadata metadata;
uint64_t current = nl_address(fd, 1, &addr, &metadata, nl_peer_magic) ? metadata.groups : socket->groups;
uint64_t groups = (current & keep) | add;
if (groups != current || groups != socket->groups)
result = nl_replace_peer(fd, socket, socket->port, socket->cap_ack, groups);
}
pthread_mutex_unlock(&nl_sockets_lock);
return result;
}
int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) {
const struct sockaddr_nl *nl;
if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd);
@@ -1352,15 +1410,39 @@ int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) {
return 1;
}
nl = (const struct sockaddr_nl *) addr;
if (nl->nl_groups != 0) {
errno = EACCES;
*rc = -1;
return 1;
}
*rc = nl_bind_port(fd, nl->nl_pid, 0);
if (*rc == 0) *rc = nl_set_groups(fd, ~(uint64_t) UINT32_MAX, nl->nl_groups);
return 1;
}
static unsigned nl_groups_of(int fd) {
struct sockaddr_un addr;
struct nl_metadata metadata;
if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) return (unsigned) metadata.groups;
unsigned groups = 0;
pthread_mutex_lock(&nl_sockets_lock);
struct nl_fd *entry = nl_find(fd);
if (entry) groups = (unsigned) entry->socket->groups;
pthread_mutex_unlock(&nl_sockets_lock);
return groups;
}
static int nl_membership(int fd, int option, const void *value, socklen_t len) {
unsigned group;
if (value == NULL || len < sizeof(group)) {
errno = value == NULL ? EFAULT : EINVAL;
return -1;
}
memcpy(&group, value, sizeof(group));
if (group == 0 || group > RTNLGRP_MAX) {
errno = EINVAL;
return -1;
}
if (group > 64) return 0;
uint64_t bit = (uint64_t) 1 << (group - 1);
return nl_set_groups(fd, ~bit, option == NETLINK_ADD_MEMBERSHIP ? bit : 0);
}
int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) {
struct sockaddr_nl nl;
socklen_t size;
@@ -1373,6 +1455,7 @@ int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) {
memset(&nl, 0, sizeof(nl));
nl.nl_family = AF_NETLINK;
nl.nl_pid = nl_port_of(fd);
nl.nl_groups = nl_groups_of(fd);
size = *len < sizeof(nl) ? *len : (socklen_t) sizeof(nl);
memcpy(addr, &nl, size);
*len = sizeof(nl);
@@ -1517,9 +1600,10 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t
*rc = real(peer, level, option, value, len);
return 1;
}
if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) {
errno = option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP
? EACCES : ENOPROTOOPT;
if (option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP) {
*rc = nl_membership(fd, option, value, len);
} else if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) {
errno = ENOPROTOOPT;
*rc = -1;
} else if (value == NULL || len < sizeof(int)) {
errno = value == NULL ? EFAULT : EINVAL;
@@ -1530,7 +1614,7 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t
memcpy(&enabled, value, sizeof(enabled));
pthread_mutex_lock(&nl_sockets_lock);
struct nl_fd *entry = nl_find(fd);
if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0) != 0) {
if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0, entry->socket->groups) != 0) {
pthread_mutex_unlock(&nl_sockets_lock);
*rc = -1;
return 1;
+3 -2
View File
@@ -17,6 +17,7 @@ int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidde
const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
int dd_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
int dd_vdec_open(const char *path, int flags) __attribute__((visibility("hidden")));
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
@@ -62,7 +63,7 @@ static int open_from(const char *path, int flags, mode_t mode, const void *calle
fd = dd_dircache_create(AT_FDCWD, path, flags, mode, via_open);
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
if (fd < 0 && dd_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
return fd;
return dd_net_open(path, flags, fd);
}
static int openat_from(int dirfd, const char *path, int flags, mode_t mode, const void *caller) {
@@ -85,7 +86,7 @@ static int openat_from(int dirfd, const char *path, int flags, mode_t mode, cons
fd = dd_dircache_create(dirfd, path, flags, mode, via_openat);
if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
if (fd < 0 && dd_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
return fd;
return dd_net_open(path, flags, fd);
}
int open(const char *path, int flags, ...) {
+24 -3
View File
@@ -6,6 +6,7 @@
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
@@ -55,12 +56,16 @@ static unsigned hash_of(const char *s, int kind, int mode, int flags) {
return h;
}
static struct entry *slot(unsigned h) {
return &table[(h ^ (h >> 16)) % PATH_CACHE_SLOTS];
}
static int cacheable(const char *path) {
return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled();
}
static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) {
struct entry *e = &table[h % PATH_CACHE_SLOTS];
struct entry *e = slot(h);
if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL;
if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL;
@@ -68,7 +73,7 @@ static struct entry *find(const char *path, int kind, int mode, int flags, unsig
}
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
struct entry *e = &table[h % PATH_CACHE_SLOTS];
struct entry *e = slot(h);
char *copy = value != NULL ? strdup(value) : NULL;
if (value != NULL && copy == NULL) return;
@@ -172,6 +177,10 @@ static int check_cwd(const char *path, int mode, int flags) {
return result;
}
static int absolute(const char *path) {
return path != NULL && path[0] == '/';
}
int access(const char *path, int mode) {
return cached_access(path, mode, 0, check_cwd);
}
@@ -188,7 +197,7 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int);
int err;
if (dirfd == AT_FDCWD) {
if (dirfd == AT_FDCWD || absolute(path)) {
return cached_access(path, mode, flags, check_cwd);
}
real = next_faccessat();
@@ -202,3 +211,15 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
errno = err;
return -1;
}
int __xstat64(int version, const char *path, struct stat64 *out) {
static int (*real)(int, const char *, struct stat64 *);
if (dd_dircache_absent && dd_dircache_absent(path)) {
errno = ENOENT;
return -1;
}
if (real == NULL) real = (int (*)(int, const char *, struct stat64 *))dlsym(RTLD_NEXT, "__xstat64");
if (real != NULL) return real(version, path, out);
return stat64(path, out);
}
+7 -1
View File
@@ -100,7 +100,11 @@ static long path_statx(int dirfd, const char *path, int flags, unsigned int mask
return next_statx(dirfd, path, flags, mask, out);
}
void bl_inputudev_note_dlopen(const char *path, void *handle) __attribute__((weak, visibility("hidden")));
void *dlopen(const char *filename, int flags) {
void *handle;
if (!real_dlopen) {
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
}
@@ -109,7 +113,9 @@ void *dlopen(const char *filename, int flags) {
if (basename && strcmp(basename, "vrclient.so") == 0) {
flags &= ~RTLD_DEEPBIND;
}
return real_dlopen(filename, flags);
handle = real_dlopen != NULL ? real_dlopen(filename, flags) : NULL;
if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle);
return handle;
}
int dd_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
+71 -8
View File
@@ -14,6 +14,7 @@
#include <sys/stat.h>
#include <endian.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct stand_in {
@@ -40,6 +41,19 @@ static ino_t socket_inode(int fd) {
return fstat(fd, &st) == 0 ? st.st_ino : 0;
}
static struct stand_in *available_stand_in(void) {
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
struct stand_in *entry = &stand_ins[i];
if (entry->fd == -1) return entry;
if (entry->inode != socket_inode(entry->fd)) {
close(entry->peer);
entry->fd = -1;
return entry;
}
}
return NULL;
}
static int is_stand_in(int fd) {
int found = 0;
if (fd < 0)
@@ -86,14 +100,11 @@ static int make_stand_in(int type) {
}
fcntl(sv[1], F_SETFD, FD_CLOEXEC);
pthread_mutex_lock(&lock);
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
if (stand_ins[i].fd == -1) {
stand_ins[i].fd = sv[0];
stand_ins[i].peer = sv[1];
stand_ins[i].inode = socket_inode(sv[0]);
pthread_mutex_unlock(&lock);
return sv[0];
}
struct stand_in *entry = available_stand_in();
if (entry != NULL) {
*entry = (struct stand_in){.fd = sv[0], .peer = sv[1], .inode = socket_inode(sv[0])};
pthread_mutex_unlock(&lock);
return sv[0];
}
pthread_mutex_unlock(&lock);
close(sv[0]);
@@ -146,6 +157,58 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) {
return is_stand_in(fd);
}
static int subscribed(int fd) {
#ifdef UDEVMON_TEST
if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0;
#endif
struct sockaddr_nl nl;
socklen_t len = sizeof(nl);
memset(&nl, 0, sizeof(nl));
return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0;
}
/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none
when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under
the same descriptor, by a stand-in. */
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
int (*real_bind)(int, const struct sockaddr *, socklen_t),
int *rc) {
int protocol = -1;
socklen_t protocol_len = sizeof(protocol);
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0;
if (is_stand_in(fd) || is_wine_process()) return 0;
if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT)
return 0;
*rc = real_bind(fd, addr, len);
int refused = errno;
if (subscribed(fd)) {
errno = refused;
return 1;
}
int status = fcntl(fd, F_GETFL);
int descriptor = fcntl(fd, F_GETFD);
int sv[2];
if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) {
errno = refused;
return 1;
}
pthread_mutex_lock(&lock);
struct stand_in *entry = available_stand_in();
if (entry == NULL || dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) {
pthread_mutex_unlock(&lock);
close(sv[0]);
close(sv[1]);
errno = refused;
return 1;
}
close(sv[0]);
if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
*entry = (struct stand_in){.fd = fd, .peer = sv[1], .inode = socket_inode(fd)};
pthread_mutex_unlock(&lock);
*rc = 0;
return 1;
}
int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
struct sockaddr_nl nl;
+192 -5
View File
@@ -29,6 +29,8 @@
#define VDEC_BITSTREAM_SIZE (4u << 20)
#define VDEC_PADDING 64
#define VDEC_DUMB 64
#define VDEC_CAP_MIN_WIDTH 4096u
#define VDEC_CAP_MIN_HEIGHT 2304u
struct vd_dma_heap_alloc {
uint64_t len;
@@ -135,6 +137,8 @@ struct vdec {
uint32_t n_cap_done;
int out_on, cap_on;
int sock, hw, hw_failed;
int resizing;
uint32_t stream_w, stream_h;
int64_t pts;
void *ctx, *packet, *frame;
uint8_t *packet_data;
@@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) {
if (sock < 0) return -1;
struct vdec_config c = {
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
.width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width,
.height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height,
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
};
struct vdec_result r;
@@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
t.fourcc = p->pixelformat;
t.width = p->width;
t.height = p->height;
t.stream_w = p->width;
t.stream_h = p->height;
} else {
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH;
if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT;
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
t.cap_width = (w + 15) & ~15u;
t.cap_height = (h + 15) & ~15u;
@@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
if (apply) {
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
*v = t;
if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0;
}
vd_fill_format(&t, f);
return 0;
@@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
struct vd_bits {
const uint8_t *data;
size_t size, pos;
};
static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) {
uint32_t value = 0;
while (count--) {
size_t byte = b->pos >> 3;
value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u);
b->pos++;
}
return value;
}
static uint32_t vd_get_ue(struct vd_bits *b) {
unsigned zeros = 0;
while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++;
if (zeros >= 32) return 0;
return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0);
}
static int32_t vd_get_se(struct vd_bits *b) {
uint32_t k = vd_get_ue(b);
return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2);
}
static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) {
int32_t last = 8, next = 8;
for (unsigned i = 0; i < size; i++) {
if (next != 0) {
int32_t delta = vd_get_se(b);
if (delta < -128 || delta > 127) return -1;
next = (last + delta + 256) % 256;
}
last = next == 0 ? last : next;
}
return 0;
}
/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */
static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
uint32_t profile = vd_get_bits(&b, 8);
vd_get_bits(&b, 16);
vd_get_ue(&b);
uint32_t chroma = 1;
if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 ||
profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) {
chroma = vd_get_ue(&b);
if (chroma == 3) vd_get_bits(&b, 1);
vd_get_ue(&b);
vd_get_ue(&b);
vd_get_bits(&b, 1);
if (vd_get_bits(&b, 1)) {
for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++)
if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1;
}
}
vd_get_ue(&b);
uint32_t poc = vd_get_ue(&b);
if (poc == 0) {
vd_get_ue(&b);
} else if (poc == 1) {
vd_get_bits(&b, 1);
vd_get_se(&b);
vd_get_se(&b);
uint32_t cycle = vd_get_ue(&b);
for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b);
}
vd_get_ue(&b);
vd_get_bits(&b, 1);
uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1;
if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1;
uint32_t frame_mbs_only = vd_get_bits(&b, 1);
if (b.pos > b.size * 8) return -1;
*width = mbs_wide * 16;
*height = map_units_high * 16 * (2 - frame_mbs_only);
return 0;
}
/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */
static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 4 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue;
size_t start = i + 4, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h264(data + start, end - start, width, height);
}
return -1;
}
/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */
static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
vd_get_bits(&b, 4);
uint32_t sub_layers = vd_get_bits(&b, 3);
vd_get_bits(&b, 1);
for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8);
vd_get_bits(&b, 8);
uint32_t profile_present = 0, level_present = 0;
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
profile_present |= vd_get_bits(&b, 1) << i;
level_present |= vd_get_bits(&b, 1) << i;
}
if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2);
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8);
if (level_present >> i & 1) vd_get_bits(&b, 8);
}
vd_get_ue(&b);
if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1);
uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b);
if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1;
*width = (w + 15) & ~15u;
*height = (h + 15) & ~15u;
return 0;
}
static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 5 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue;
size_t start = i + 5, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h265(data + start, end - start, width, height);
}
return -1;
}
/*
* A stream can change its picture size without telling the client: the host switches games or the window
* becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which
* the client polls; the capture buffers it already allocated stay at the old size until it reconfigures.
*/
static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) {
uint32_t width, height;
int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height)
: vd_stream_size_h264(data, size, &width, &height);
if (found != 0) return 0;
uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height;
if (width == known_w && height == known_h) return 0;
vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h);
if (width <= v->cap_width && height <= v->cap_height) {
/* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */
v->stream_w = width;
v->stream_h = height;
if (v->hw) vd_close_decoder(v);
return 1;
}
v->width = v->stream_w = width;
v->height = v->stream_h = height;
v->resizing = 1;
v->n_cap_done = 0;
return 1;
}
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
uint32_t bytes = b->m.planes[0].bytesused;
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes);
if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp);
v->out_done[v->n_out_done++] = b->index;
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
@@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
if (v->n_cap_done == 0) return -EAGAIN;
struct vd_done d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct vd_done d;
for (;;) {
if (v->n_cap_done == 0) return -EAGAIN;
d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct stat st;
struct vd_capture *c = &v->cap[d.index];
if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break;
}
b->index = d.index;
b->memory = V4L2_MEMORY_DMABUF;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
+67 -24
View File
@@ -26,40 +26,83 @@ static char *join_features(const char *have, const char *add) {
return strcat(out, add);
}
static int electron_node_mode(char *const envp[]) {
static const char variable[] = "ELECTRON_RUN_AS_NODE=";
static const char *env_value(char *const envp[], const char *variable) {
size_t n = strlen(variable);
for (int i = 0; envp && envp[i]; i++)
if (!strncmp(envp[i], variable, sizeof variable - 1))
return envp[i][sizeof variable - 1] != 0;
return 0;
if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1;
return NULL;
}
static char *const *chromium_argv(const char *path, char *const argv[]) {
const char *slash = path ? strrchr(path, '/') : NULL;
if (!slash || !argv || !argv[0]) return argv;
int argc = 0;
for (; argv[argc]; argc++)
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
size_t dir = (size_t)(slash - path) + 1;
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
if (!sandbox) return argv;
memcpy(sandbox, path, dir);
strcpy(sandbox + dir, "chrome-sandbox");
int chromium = access(sandbox, F_OK) == 0;
free(sandbox);
if (!chromium) return argv;
char **out = calloc((size_t)argc + 2, sizeof *out);
static int electron_node_mode(char *const envp[]) {
const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE");
return mode && *mode;
}
static int beside_chrome_sandbox(const char *path) {
char *real = realpath(path, NULL);
if (!real) return 0;
int found = 0;
for (int up = 0; up < 2 && !found; up++) {
char *slash = strrchr(real, '/');
if (!slash) break;
*slash = 0;
size_t dir = strlen(real);
char *sandbox = malloc(dir + sizeof "/chrome-sandbox");
if (!sandbox) break;
memcpy(sandbox, real, dir);
strcpy(sandbox + dir, "/chrome-sandbox");
found = access(sandbox, F_OK) == 0;
free(sandbox);
}
free(real);
return found;
}
static char *folder_of(const char *path) {
char *real = realpath(path, NULL);
char *slash = real ? strrchr(real, '/') : NULL;
if (slash) *slash = 0;
return real;
}
static int started_by_its_own_app(const char *path) {
char self[4096];
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n <= 0) return 0;
self[n] = 0;
char *mine = folder_of(self), *theirs = folder_of(path);
int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self);
free(mine);
free(theirs);
return same;
}
static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) {
if (!path || !argv || !argv[0]) return argv;
int argc = 0, sandbox = 1, ozone = 0;
for (; argv[argc]; argc++) {
if (!argc) continue;
if (!strncmp(argv[argc], "--type=", 7)) return argv;
if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0;
if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1;
}
const char *display = env_value(envp, "DISPLAY");
int x11 = !ozone && display && *display;
if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv;
char **out = calloc((size_t)argc + 3, sizeof *out);
if (!out) return argv;
out[0] = argv[0];
out[1] = (char *)"--no-sandbox";
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
int n = 0;
out[n++] = argv[0];
if (sandbox) out[n++] = (char *)"--no-sandbox";
if (x11) out[n++] = (char *)"--ozone-platform=x11";
for (int i = 1; i < argc; i++) out[n++] = argv[i];
return out;
}
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) {
if (electron_node_mode(envp)) return argv;
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp);
const char *spec = getenv("DD_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;
+419 -78
View File
@@ -1,8 +1,9 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#pragma GCC optimize("no-stack-protector", "no-tree-loop-distribute-patterns")
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <string.h>
@@ -10,6 +11,9 @@
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#if defined(__i386__)
#include <asm/ldt.h>
#endif
#include <unistd.h>
@@ -20,31 +24,220 @@
#define ZR_CTL "/tmp/.dd-zram"
#endif
#define ZR_SWAPPED (1ULL << 62)
#define ZR_PRESENT (1ULL << 63)
#define ZR_BATCH 512
#define ZR_CHUNK (1UL << 20)
#define ZR_SLOTS 32768UL
#define ZR_PROBES 16
#define ZR_HEAT_MAX 3
#define ZR_SKIP 32U
#define ZR_INLINE_KB (32UL << 10)
#define ZR_INLINE_CHUNKS 512UL
#define ZR_FAILED (~0UL)
#define ZR_FUTEX_WAIT 0
#define ZR_FUTEX_WAKE 1
#define ZR_STACK (128UL << 10)
#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \
CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID)
#define ZR_TEXT(x) #x
#define ZR_NR(x) ZR_TEXT(x)
#define ZR_CALL(n, a, b, c, d, e, f, ...) \
zr_call((long)(n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f))
#define zr_sys(...) ZR_CALL(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0)
#if defined(__aarch64__)
#define ZR_MMAP SYS_mmap
__asm__(".pushsection .text\n"
".p2align 2\n"
".hidden zr_call\n"
".type zr_call, %function\n"
"zr_call:\n"
" mov x8, x0\n"
" mov x0, x1\n"
" mov x1, x2\n"
" mov x2, x3\n"
" mov x3, x4\n"
" mov x4, x5\n"
" mov x5, x6\n"
" svc #0\n"
" ret\n"
".size zr_call, . - zr_call\n"
".hidden zr_clone\n"
".type zr_clone, %function\n"
"zr_clone:\n"
" mov x5, x2\n"
" mov x2, x3\n"
" mov x3, x4\n"
" mov x4, x5\n"
" mov x8, #" ZR_NR(SYS_clone) "\n"
" svc #0\n"
" cbnz x0, 1f\n"
" mov x29, xzr\n"
" mov x30, xzr\n"
" bl zr_thread\n"
" mov x0, xzr\n"
" mov x8, #" ZR_NR(SYS_exit) "\n"
" svc #0\n"
" brk #0\n"
"1:\n"
" ret\n"
".size zr_clone, . - zr_clone\n"
".popsection\n");
#elif defined(__x86_64__)
#define ZR_MMAP SYS_mmap
__asm__(".pushsection .text\n"
".p2align 4\n"
".hidden zr_call\n"
".type zr_call, @function\n"
"zr_call:\n"
" mov %rdi, %rax\n"
" mov %rsi, %rdi\n"
" mov %rdx, %rsi\n"
" mov %rcx, %rdx\n"
" mov %r8, %r10\n"
" mov %r9, %r8\n"
" mov 8(%rsp), %r9\n"
" syscall\n"
" ret\n"
".size zr_call, . - zr_call\n"
".hidden zr_clone\n"
".type zr_clone, @function\n"
"zr_clone:\n"
" mov %rdx, %r10\n"
" mov %rcx, %rdx\n"
" mov $" ZR_NR(SYS_clone) ", %eax\n"
" syscall\n"
" test %rax, %rax\n"
" jnz 1f\n"
" xor %ebp, %ebp\n"
" call zr_thread\n"
" xor %edi, %edi\n"
" mov $" ZR_NR(SYS_exit) ", %eax\n"
" syscall\n"
" hlt\n"
"1:\n"
" ret\n"
".size zr_clone, . - zr_clone\n"
".popsection\n");
#elif defined(__i386__)
#define ZR_MMAP SYS_mmap2
__asm__(".pushsection .text\n"
".p2align 4\n"
".hidden zr_call\n"
".type zr_call, @function\n"
"zr_call:\n"
" push %ebp\n"
" push %edi\n"
" push %esi\n"
" push %ebx\n"
" mov 20(%esp), %eax\n"
" mov 24(%esp), %ebx\n"
" mov 28(%esp), %ecx\n"
" mov 32(%esp), %edx\n"
" mov 36(%esp), %esi\n"
" mov 40(%esp), %edi\n"
" mov 44(%esp), %ebp\n"
" int $0x80\n"
" pop %ebx\n"
" pop %esi\n"
" pop %edi\n"
" pop %ebp\n"
" ret\n"
".size zr_call, . - zr_call\n"
".hidden zr_clone\n"
".type zr_clone, @function\n"
"zr_clone:\n"
" push %ebx\n"
" push %esi\n"
" push %edi\n"
" mov 16(%esp), %ebx\n"
" mov 20(%esp), %ecx\n"
" mov 24(%esp), %edi\n"
" mov 28(%esp), %edx\n"
" mov 32(%esp), %esi\n"
" mov $" ZR_NR(SYS_clone) ", %eax\n"
" int $0x80\n"
" test %eax, %eax\n"
" jnz 1f\n"
" xor %ebp, %ebp\n"
" call zr_thread\n"
" xor %ebx, %ebx\n"
" mov $" ZR_NR(SYS_exit) ", %eax\n"
" int $0x80\n"
" hlt\n"
"1:\n"
" pop %edi\n"
" pop %esi\n"
" pop %ebx\n"
" ret\n"
".size zr_clone, . - zr_clone\n"
".popsection\n");
#else
#error "zram.c needs a raw system call for this architecture"
#endif
long zr_call(long n, long a, long b, long c, long d, long e, long f) __attribute__((visibility("hidden")));
long zr_clone(long flags, char *stack, int *child, int *parent, void *tls) __attribute__((visibility("hidden")));
void zr_thread(void) __attribute__((visibility("hidden")));
static long (*zr_sys)(long, ...);
static unsigned long zr_page;
static int zr_busy;
static int zr_pending;
static int zr_worker;
static unsigned zr_requests;
static int zr_stack_busy;
static int zr_tid;
static long zr_filters;
static char *zr_stack;
static char zr_maps[8192];
static uint64_t zr_entries[ZR_BATCH];
static struct iovec zr_iov[ZR_BATCH];
static char zr_sink[ZR_BATCH];
static struct zr_slot {
unsigned long key;
uint16_t gen;
uint16_t pushed;
uint16_t kept;
uint8_t heat;
uint8_t skip;
} zr_slots[ZR_SLOTS];
static uint16_t zr_gen = 1;
static unsigned long zr_cursor;
static unsigned long zr_visits;
static int zr_prefix(const char *text, const char *prefix) {
while (*prefix)
if (*text++ != *prefix++) return 0;
return 1;
}
static char *zr_find(char *text, char c, size_t n) {
for (; n > 0; n--, text++)
if (*text == c) return text;
return NULL;
}
static int zr_open(const char *path) {
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
}
static int zr_mode(void) {
char c = 0;
int fd = zr_open(ZR_CTL);
if (fd < 0) return -1;
long n = zr_sys(SYS_read, fd, &c, 1);
zr_sys(SYS_close, fd);
return n == 1 && (c == '0' || c == '1') ? c - '0' : -1;
static int zr_mode(unsigned long *want) {
char text[24];
long n = 0;
int fd = zr_open(ZR_CTL ".hold");
if (fd >= 0) {
n = zr_sys(SYS_read, fd, text, sizeof(text));
zr_sys(SYS_close, fd);
}
if (n < 1) {
fd = zr_open(ZR_CTL);
if (fd < 0) return -1;
n = zr_sys(SYS_read, fd, text, sizeof(text));
zr_sys(SYS_close, fd);
}
if (n < 1 || text[0] < '0' || text[0] > '3') return -1;
unsigned long kb = 0;
for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++)
kb = kb * 10 + (unsigned long)(text[i] - '0');
*want = kb / (zr_page / 1024);
if (text[0] >= '2' && *want == 0) return -1;
return text[0] - '0';
}
static unsigned long zr_hex(const char **p) {
@@ -69,7 +262,7 @@ static int zr_eligible(const char *line, int compress, unsigned long *start, uns
while (*p && *p != ' ') p++;
while (*p == ' ') p++;
}
return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0;
return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[anon:");
}
static void zr_read_back(int pagemap, unsigned long start, unsigned long end) {
@@ -96,43 +289,131 @@ static void zr_read_back(int pagemap, unsigned long start, unsigned long end) {
}
}
static void zr_walk(int compress) {
int maps = zr_open("/proc/self/maps");
if (maps < 0) return;
int pagemap = compress ? -1 : zr_open("/proc/self/pagemap");
if (!compress && pagemap < 0) {
zr_sys(SYS_close, maps);
return;
static unsigned long zr_count(int pagemap, unsigned long start, unsigned long end, uint64_t bit) {
unsigned long count = 0;
long size = (long)((end - start) / zr_page * sizeof(uint64_t));
long got;
do {
if (zr_sys(SYS_lseek, pagemap, (long)(start / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return ZR_FAILED;
got = zr_sys(SYS_read, pagemap, zr_entries, size);
} while (got == -EINTR);
if (got != size) return ZR_FAILED;
for (long i = 0; i < got / (long)sizeof(uint64_t); i++)
if (zr_entries[i] & bit) count++;
return count;
}
static struct zr_slot *zr_slot(unsigned long addr, int create) {
unsigned long key = addr / zr_page + 1;
unsigned long home = key * 2654435761UL % ZR_SLOTS;
for (unsigned long i = 0; i < ZR_PROBES; i++) {
struct zr_slot *slot = &zr_slots[(home + i) % ZR_SLOTS];
if (slot->key == key) return slot;
if (slot->key == 0 && !create) return NULL;
if (slot->key == 0) {
slot->key = key;
return slot;
}
}
if (!create) return NULL;
zr_slots[home] = (struct zr_slot){.key = key};
return &zr_slots[home];
}
static unsigned long zr_trim(int pagemap, unsigned long start, unsigned long end,
unsigned long want, int force, unsigned long lo, unsigned long hi) {
unsigned long done = 0;
for (unsigned long addr = start, next; addr < end && done < want; addr = next) {
next = (addr | (ZR_CHUNK - 1)) + 1;
if (next > end || next < addr) next = end;
if (next <= lo || addr >= hi) continue;
if (zr_visits == 0) break;
zr_visits--;
zr_cursor = next;
if (addr < (unsigned long)(zr_slots + ZR_SLOTS) && next > (unsigned long)zr_slots) continue;
unsigned long present = zr_count(pagemap, addr, next, ZR_PRESENT);
if (present == ZR_FAILED) continue;
struct zr_slot *slot = zr_slot(addr, 0);
if (slot != NULL && slot->gen == zr_gen && slot->pushed > 0) {
if (present > slot->kept && (present - slot->kept) * 4 > slot->pushed) {
if (slot->heat < ZR_HEAT_MAX) slot->heat++;
slot->skip = (uint8_t)(ZR_SKIP << slot->heat > 255 ? 255 : ZR_SKIP << slot->heat);
slot->pushed = 0;
} else if (slot->heat > 0) {
slot->heat--;
}
}
if (slot != NULL && slot->skip > 0 && !force) {
slot->skip--;
continue;
}
if (present == 0) continue;
unsigned long from = addr < lo ? lo : addr;
unsigned long left = present;
while (from < next && done + present - left < want) {
unsigned long budget = want - done - (present - left);
unsigned long i = (from - addr) / zr_page;
for (; i < (next - addr) / zr_page && budget > 0; i++)
if (zr_entries[i] & ZR_PRESENT) budget--;
unsigned long to = addr + i * zr_page;
zr_sys(SYS_madvise, from, to - from, MADV_PAGEOUT);
from = to;
unsigned long now = zr_count(pagemap, addr, next, ZR_PRESENT);
if (now == ZR_FAILED) break;
left = now < present ? now : present;
}
if (from < next) zr_cursor = from;
if (left >= present) continue;
if (slot == NULL) slot = zr_slot(addr, 1);
if (slot->gen != zr_gen) slot->pushed = 0;
slot->gen = zr_gen;
slot->pushed = (uint16_t)(slot->pushed + present - left);
slot->kept = (uint16_t)left;
done += present - left;
}
return done;
}
static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, unsigned long hi) {
int maps = zr_open("/proc/self/maps");
if (maps < 0) return 0;
int pagemap = mode == 1 ? -1 : zr_open("/proc/self/pagemap");
if (mode != 1 && pagemap < 0) {
zr_sys(SYS_close, maps);
return 0;
}
unsigned long done = 0;
size_t have = 0;
for (;;) {
while (done < want && zr_visits > 0) {
long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have);
if (n < 0 && errno == EINTR) continue;
if (n == -EINTR) continue;
if (n <= 0) break;
have += (size_t)n;
zr_maps[have] = 0;
char *line = zr_maps;
char *nl;
while ((nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
while (done < want && zr_visits > 0 && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
*nl = 0;
unsigned long s, e;
if (zr_eligible(line, compress, &s, &e) && e > s) {
if (compress) zr_sys(SYS_madvise, s, e - s, MADV_PAGEOUT);
else zr_read_back(pagemap, s, e);
if (zr_eligible(line, mode != 0, &s, &e) && e > s) {
if (mode == 0) zr_read_back(pagemap, s, e);
else if (mode == 1) zr_sys(SYS_madvise, s, e - s, MADV_PAGEOUT);
else done += zr_trim(pagemap, s, e, want - done, mode == 3, lo, hi);
}
line = nl + 1;
}
have -= (size_t)(line - zr_maps);
memmove(zr_maps, line, have);
for (size_t i = 0; i < have; i++) zr_maps[i] = line[i];
if (have == sizeof(zr_maps) - 1) have = 0;
}
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
zr_sys(SYS_close, maps);
return done;
}
static void zr_ack(int done) {
static const char suffix[] = ".ack.";
char path[sizeof(ZR_CTL) + sizeof(suffix) + 20];
static void zr_ack(long value, int trim) {
const char *suffix = trim ? ".trim." : ".ack.";
char path[sizeof(ZR_CTL) + sizeof(".trim.") + 20];
char digits[20];
size_t n = 0, d = 0;
for (const char *p = ZR_CTL; *p; p++) path[n++] = *p;
@@ -143,26 +424,113 @@ static void zr_ack(int done) {
path[n] = 0;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) return;
if (done) zr_sys(SYS_write, fd, "1", 1UL);
for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10);
for (n = 0; d > 0;) path[n++] = digits[--d];
if (n > 0) zr_sys(SYS_write, fd, path, n);
zr_sys(SYS_close, fd);
}
static void zr_request(void) {
int mode = zr_mode();
if (mode == 1) zr_ack(0);
if (mode >= 0) zr_walk(mode);
if (mode == 1) zr_ack(1);
static void zr_request(int worker) {
unsigned long want = 0;
int mode = zr_mode(&want);
if (mode < 0) return;
if (!worker && want > ZR_INLINE_KB / (zr_page / 1024)) want = ZR_INLINE_KB / (zr_page / 1024);
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
if (mode > 0) zr_ack(-1, mode > 1);
if (mode < 2) {
zr_walk(mode, 1, 0, 0);
zr_gen++;
if (mode == 1) zr_ack(1, 0);
return;
}
unsigned long from = zr_cursor;
unsigned long done = zr_walk(mode, want, from, ~0UL);
if (done < want && from > 0) done += zr_walk(mode, want - done, 0, from);
zr_ack((long)(done * (zr_page / 1024)), 1);
}
static void *zr_worker_main(void *unused) {
(void)unused;
prctl(PR_SET_NAME, "zr-worker", 0, 0, 0);
for (;;) {
while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST))
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0);
zr_request();
static void zr_drain(int worker) {
unsigned seen;
do {
seen = __atomic_load_n(&zr_requests, __ATOMIC_ACQUIRE);
zr_request(worker);
} while (!__atomic_compare_exchange_n(&zr_requests, &seen, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE));
}
void zr_thread(void) {
zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker");
zr_drain(1);
}
static void *zr_tls(void *desc) {
#if defined(__aarch64__)
(void)desc;
return __builtin_thread_pointer();
#elif defined(__x86_64__)
(void)desc;
void *self;
__asm__("mov %%fs:0, %0" : "=r"(self));
return self;
#else
struct user_desc *entry = desc;
unsigned short selector;
__asm__("mov %%gs, %0" : "=r"(selector));
entry->entry_number = selector >> 3;
return zr_sys(SYS_get_thread_area, entry) == 0 ? entry : NULL;
#endif
}
static long zr_field(const char *text, const char *key) {
for (const char *line = text; *line; line++) {
if ((line == text || line[-1] == '\n') && zr_prefix(line, key)) {
long value = 0;
for (const char *k = key; *k; k++) line++;
while (*line == ' ' || *line == '\t') line++;
for (; *line >= '0' && *line <= '9'; line++) value = value * 10 + (*line - '0');
return value;
}
}
return NULL;
return -1;
}
static int zr_status(long *threads, long *filters) {
int fd = zr_open("/proc/thread-self/status");
if (fd < 0) return 0;
long have = 0, n;
while (have < (long)sizeof(zr_maps) - 1 &&
((n = zr_sys(SYS_read, fd, zr_maps + have, sizeof(zr_maps) - 1 - (size_t)have)) > 0 || n == -EINTR))
if (n > 0) have += n;
zr_sys(SYS_close, fd);
zr_maps[have] = 0;
*threads = zr_field(zr_maps, "Threads:");
*filters = zr_field(zr_maps, "Seccomp_filters:");
return have > 0;
}
static int zr_start(void) {
long threads, filters;
if (!zr_status(&threads, &filters) || threads < 2 || filters > zr_filters) return 0;
if (zr_stack == NULL) {
long base = zr_sys(ZR_MMAP, 0, ZR_STACK, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
if ((unsigned long)base > -4096UL) return 0;
zr_stack = (char *)base;
}
struct { long sec, nsec; } wait = {0, 5000000};
for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++)
zr_sys(SYS_futex, &zr_stack_busy, ZR_FUTEX_WAIT, 1, &wait, NULL, 0);
if (__atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE)) return 0;
uint64_t desc[4] = {0};
void *tls = zr_tls(desc);
if (tls == NULL) return 0;
uint64_t all = ~0ULL, previous;
if (zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &all, &previous, sizeof(all)) != 0) return 0;
__atomic_store_n(&zr_stack_busy, 1, __ATOMIC_RELEASE);
long tid = zr_clone(ZR_THREAD, zr_stack + ZR_STACK, &zr_stack_busy, &zr_tid, tls);
zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &previous, NULL, sizeof(previous));
if (tid > 0) return 1;
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
return 0;
}
static void zr_handler(int sig, siginfo_t *info, void *context) {
@@ -170,34 +538,23 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
int saved = errno;
__atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST);
if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) {
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0);
} else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST)
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
zr_request();
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
}
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
errno = saved;
}
static void zr_child(void) {
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
__atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
}
__attribute__((constructor)) static void zr_init(void) {
void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD);
if (libc == NULL) return;
zr_sys = (long (*)(long, ...))dlsym(libc, "syscall");
if (zr_sys == NULL) return;
int fd = zr_open(ZR_CTL);
if (fd < 0) return;
zr_sys(SYS_close, fd);
long page = sysconf(_SC_PAGESIZE);
zr_page = page > 0 ? (unsigned long)page : 4096UL;
long threads;
if (!zr_status(&threads, &zr_filters)) zr_filters = -1;
struct sigaction old;
if (sigaction(SIGURG, NULL, &old) != 0) return;
if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return;
@@ -206,21 +563,5 @@ __attribute__((constructor)) static void zr_init(void) {
sa.sa_sigaction = zr_handler;
sa.sa_flags = SA_SIGINFO | SA_RESTART;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGURG, &sa, NULL) == 0) {
pthread_atfork(NULL, NULL, zr_child);
pthread_attr_t attr;
if (pthread_attr_init(&attr) == 0) {
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
sigset_t blocked;
sigset_t previous;
if (sigfillset(&blocked) == 0 &&
pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) {
if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0)
__atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE);
pthread_sigmask(SIG_SETMASK, &previous, NULL);
}
pthread_attr_destroy(&attr);
}
}
if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child);
}
+441
View File
@@ -0,0 +1,441 @@
#!/usr/bin/env python3
"""A/B the session's keep-top guard on a rooted dual-screen device.
See docs/development/memory-guard-ab.md. Needs `su` on the device and a running DroidDeck build
with debugging tools (tools/droiddeckctl).
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from adb_device import DeviceResolutionError, resolve_serial # noqa: E402
TOOLS = Path(__file__).resolve().parent
PACKAGE = "com.droiddeck.launcher"
SESSION = f"{PACKAGE}/.SessionActivity"
HOG_PATH = "/data/local/tmp/dd-memory-hog.sh"
HOG_MOUNT = "/dev/dd-memory-hog"
SEED_PATH = "/data/local/tmp/dd-memory-burst.bin"
# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call
# can then open its request screen on top of the game.
# Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps
# killing by oom_score_adj while it is held.
HOG = f"""#!/system/bin/sh
stop_mb=$1; hold=$2; mode=$3
cleanup() {{ kill $(jobs -p) 2>/dev/null; rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }}
trap 'cleanup; exit 1' HUP INT TERM
mkdir -p {HOG_MOUNT}
grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT}
i=0; failed=0
if [ "$mode" = burst ]; then
[ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] ||
{{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} ||
{{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }}
cat {SEED_PATH} > /dev/null
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
echo "avail=$avail"
take=$((avail - stop_mb))
[ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }}
n=$((take / 256)); rest=$((take % 256)); pids=""
echo "burst_mb=$take start=$(date +%s%N)"
while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done
[ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }}
for pid in $pids; do wait "$pid" || failed=1; done
echo "burst_done=$(date +%s%N)"
echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)"
i=512
fi
while [ $i -lt 512 ]; do
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
echo "avail=$avail"
[ "$avail" -le "$stop_mb" ] && break
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }}
i=$((i+1))
done
[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }}
sleep "$hold"
cleanup
echo released
"""
# Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The
# bracketed patterns keep pkill from matching the shell that runs this line.
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; "
f"umount {HOG_MOUNT} 2>/dev/null; true")
def focused_display(input_dump: str) -> int | None:
match = re.search(r"FocusedDisplayId: (-?\d+)", input_dump)
return int(match.group(1)) if match else None
def activity_count(activities_dump: str, activity: str) -> int:
return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r"[ }]", activities_dump))
def guard_count(activities_dump: str) -> int:
return activity_count(activities_dump, f"{PACKAGE}/.session.KeepTopActivity")
def session_count(activities_dump: str) -> int:
return activity_count(activities_dump, SESSION)
def panel_windows(windows_dump: str, display: int) -> int:
count, current = 0, None
for line in windows_dump.splitlines():
header = re.match(r"\s*Window #\d+ Window\{\S+ u\d+ (.+?)\}:", line)
if header:
current = header.group(1)
continue
shown = re.search(r"mDisplayId=(\d+)", line)
if shown and current is not None:
if current == PACKAGE and int(shown.group(1)) == display:
count += 1
current = None
return count
def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None:
"""The visible home on another display, else the visible app on top of it."""
display, top = None, None
for line in activities_dump.splitlines():
section = re.match(r"Display #(\d+) \(activities", line)
if section:
display = int(section.group(1))
continue
if line.strip() == "" or display is None or display == session_display:
continue
home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line)
if home:
return display, home.group(1)
app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line)
if app and top is None and not app.group(1).startswith(PACKAGE):
top = display, app.group(1)
return top
def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None:
current = None
for line in displays_dump.splitlines():
header = re.search(r"Display: mDisplayId=(\d+)", line)
if header:
current = int(header.group(1))
continue
size = re.search(r"\bcur=(\d+)x(\d+)", line)
if size and current == display:
return int(size.group(1)), int(size.group(2))
return None
def max_adj(samples: list[str]) -> int | None:
values = [int(sample) for sample in samples if re.fullmatch(r"-?\d+", sample)]
return max(values) if values else None
def summarize_events(events: str) -> dict:
kills = [tuple(int(field) for field in match.groups())
for match in re.finditer(r"killinfo: \[(\d+),(\d+),(-?\d+),(-?\d+),", events)]
died = [(match.group(1), int(match.group(2)))
for match in re.finditer(r"am_proc_died: \[\d+,\d+,([^,\]]+),(-?\d+),", events)]
session_died = [adj for name, adj in died if name == PACKAGE]
return {
"lmkd_kills": len(kills),
"lmkd_kills_down_to_adj0": sum(1 for kill in kills if kill[3] <= 0),
"processes_died": {name: sum(1 for other, _ in died if other == name) for name in sorted({n for n, _ in died})},
"droiddeck_died_at_adj": session_died[0] if session_died else None,
"session_top_lost": len(re.findall(r"wm_on_top_resumed_lost_called: \[\d+,com\.droiddeck\.launcher\.SessionActivity,", events)),
"task_to_front": len(re.findall(r"wm_task_to_front:", events)),
"guard_creates": len(re.findall(r"wm_create_activity: .*KeepTopActivity", events)),
}
class Device:
def __init__(self, adb: str, serial: str):
self.adb, self.serial = adb, serial
def run(self, *args: str, timeout: int = 120, check: bool = False) -> str:
result = subprocess.run([self.adb, "-s", self.serial, *args], capture_output=True, text=True, timeout=timeout)
if check and result.returncode != 0:
raise RuntimeError(f"adb {' '.join(args)} failed: {result.stderr.strip()}")
return result.stdout.replace("\r", "")
def sh(self, command: str, timeout: int = 120) -> str:
return self.run("shell", command, timeout=timeout)
def su(self, command: str, timeout: int = 120) -> str:
return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout)
def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]:
command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args]
try:
return subprocess.run(command, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s")
def phase(self) -> str | None:
match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout)
return match.group(1) if match else None
def pid(self) -> str:
return self.sh(f"pidof {PACKAGE}").strip()
def running_pid(self) -> str:
pid = self.pid()
if not re.fullmatch(r"\d+", pid):
raise RuntimeError(f"{PACKAGE} is not running")
return pid
def size(self, display: int) -> tuple[int, int]:
size = logical_size(self.sh("dumpsys window displays"), display)
if not size:
raise RuntimeError(f"no size for display {display}")
return size
class Bench:
def __init__(self, device: Device, out: Path, label: str, session_display: int, bottom_tap: tuple[float, float],
panel_close: tuple[float, float]):
self.d, self.out, self.label, self.session_display = device, out, label, session_display
self.bottom_tap, self.panel_close = bottom_tap, panel_close
self.out.mkdir(parents=True, exist_ok=True)
def bottom(self) -> tuple[int, str]:
found = bottom_home(self.d.sh("dumpsys activity activities"), self.session_display)
if not found:
raise RuntimeError("no visible home activity on another display")
return found
def tap(self, display: int, fraction: tuple[float, float]):
width, height = self.d.size(display)
self.d.sh(f"input -d {display} tap {int(width * fraction[0])} {int(height * fraction[1])}")
def tap_bottom(self):
self.tap(self.bottom()[0], self.bottom_tap)
def game_front(self):
self.d.su(f"am start --display {self.session_display} -n {SESSION} -f 0x20000000")
time.sleep(3)
def close_panel(self):
display = self.bottom()[0]
for _ in range(3):
if panel_windows(self.d.sh("dumpsys window windows"), display) == 0:
return
self.tap(display, self.panel_close)
time.sleep(3)
def prepare(self, apk: str | None):
self.d.sh("input keyevent KEYCODE_WAKEUP")
if self.d.ctl("stop", timeout=120).returncode != 0:
self.d.sh(f"am force-stop {PACKAGE}")
if apk:
env = dict(os.environ, ADB_SERIAL=self.d.serial)
subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True)
self.d.sh(f"monkey -p {PACKAGE} -c android.intent.category.LAUNCHER 1")
time.sleep(6)
for attempt in range(2):
started = self.d.ctl("start", "steam", "--wait", "--timeout", "240")
if self.d.phase() == "READY":
break
if attempt == 1:
raise RuntimeError("the Steam session did not reach READY: "
+ (started.stderr.strip() or started.stdout.strip() or f"exit {started.returncode}"))
time.sleep(5)
time.sleep(15)
self.game_front()
def snapshot(self) -> dict:
activities = self.d.sh("dumpsys activity activities")
display = self.bottom()[0]
pid = self.d.running_pid()
return {
"focused_display": focused_display(self.d.sh("dumpsys input")),
"guards": guard_count(activities),
"sessions": session_count(activities),
"panel": panel_windows(self.d.sh("dumpsys window windows"), display),
"adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
"pid": pid,
}
def write(self, kind: str, record: dict):
record = {"label": self.label, "kind": kind, **record}
with (self.out / f"{self.label}.jsonl").open("a") as results:
results.write(json.dumps(record) + "\n")
print(json.dumps(record))
def probe(self, state: str):
self.d.run("logcat", "-b", "events", "-c")
time.sleep(3)
idle_creates = summarize_events(self.d.run("logcat", "-b", "events", "-d"))["guard_creates"]
before = self.snapshot()
_, home = self.bottom()
self.d.run("logcat", "-b", "events", "-c")
self.d.su(f"kill -9 $(pidof {home})")
samples = self.d.sh(f"for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj"
" 2>/dev/null || echo DEAD; sleep 0.1; done").split()
events = self.d.run("logcat", "-b", "events", "-d")
(self.out / f"{self.label}-{state}-events.txt").write_text(events)
summary = summarize_events(events)
self.write("state", {
"state": state, "bottom_home": home, **{k: v for k, v in before.items() if k != "pid"},
"guard_creates_idle_3s": idle_creates, "adj_max_after_home_kill": max_adj(samples),
"session_top_lost": summary["session_top_lost"], "droiddeck_alive": self.d.pid() == before["pid"],
"phase": self.d.phase(),
})
time.sleep(4)
def states(self):
self.probe("panel_open")
self.game_front()
self.close_panel()
self.probe("panel_closed_untouched")
self.game_front()
self.tap_bottom()
time.sleep(1)
self.probe("one_bottom_tap_just_now")
self.game_front()
self.tap_bottom()
time.sleep(8)
self.probe("one_bottom_tap_then_stayed")
self.game_front()
self.tap_bottom()
time.sleep(1)
self.tap_bottom()
time.sleep(1)
self.tap(self.session_display, (0.36, 0.11))
time.sleep(3)
self.probe("used_bottom_then_tapped_game")
self.game_front()
self.d.sh("input keyevent KEYCODE_HOME")
time.sleep(4)
self.probe("home_pip")
self.game_front()
self.tap_bottom()
time.sleep(1)
self.tap_bottom()
time.sleep(2)
self.probe("using_bottom_now")
self.game_front()
def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool:
with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script:
script.write(HOG)
try:
self.d.run("push", script.name, HOG_PATH, check=True)
finally:
os.unlink(script.name)
self.d.sh(f"chmod 755 {HOG_PATH}")
self.close_panel()
self.game_front()
self.tap(self.session_display, (0.36, 0.11))
time.sleep(2)
before = self.snapshot()
self.d.run("logcat", "-b", "events", "-c")
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"],
stdout=subprocess.PIPE, text=True)
samples = []
try:
while hog.poll() is None:
samples.append(self.d.sh(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip())
time.sleep(0.5)
output = hog.stdout.read() if hog.stdout else ""
finally:
if hog.poll() is None:
hog.terminate()
self.d.su(HOG_CLEANUP)
time.sleep(3)
events = self.d.run("logcat", "-b", "events", "-d")
(self.out / f"{self.label}-{run}-events.txt").write_text(events)
workload_ok = hog.returncode == 0 and "released" in output.splitlines()
if not workload_ok:
print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): "
f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr)
available = [int(value) for value in re.findall(r"avail=(\d+)", output)]
took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S)
self.write("pressure", {
"run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold,
"burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{k: v for k, v in before.items() if k != "pid"},
"min_available_mb": min(available) if available else None, "adj_max": max_adj(samples),
"droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events),
})
return workload_ok
def fraction_pair(text: str) -> tuple[float, float]:
x, y = (float(part) for part in text.split(","))
return x, y
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--adb", default=os.environ.get("ADB", "adb"))
parser.add_argument("--serial")
parser.add_argument("--out", type=Path, default=Path.home() / ".cache" / "droiddeck-memory-guard-ab")
parser.add_argument("--label", required=True, help="build name for the results, e.g. main or fix")
parser.add_argument("--apk", help="install this APK and start a fresh Steam session first")
parser.add_argument("--session-display", type=int, default=0)
parser.add_argument("--bottom-tap", type=fraction_pair, default=(0.78, 0.47),
help="x,y fractions of an inert spot on the bottom home (default 0.78,0.47)")
parser.add_argument("--panel-close", type=fraction_pair, default=(0.053, 0.071),
help="x,y fractions of the dual-screen panel's close button")
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("states", help="kill the bottom home like lmkd in each session state")
pressure = commands.add_parser("pressure", help="hold real memory pressure and record lmkd kills")
pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable")
pressure.add_argument("--hold", type=int, default=30)
pressure.add_argument("--runs", type=int, default=1)
pressure.add_argument("--burst", action="store_true",
help="take everything above --stop-mb at once instead of filling 32 MiB at a time")
summarize = commands.add_parser("summarize", help="summarize a saved events log")
summarize.add_argument("events", type=Path)
args = parser.parse_args()
if args.command == "summarize":
print(json.dumps(summarize_events(args.events.read_text()), indent=2))
return 0
try:
device = Device(args.adb, resolve_serial(args.adb, args.serial))
except DeviceResolutionError as exc:
print(f"memory-guard-ab: {exc}", file=sys.stderr)
return 2
if device.su("id -u").strip() != "0":
print("memory-guard-ab: needs a rooted device (su)", file=sys.stderr)
return 2
bench = Bench(device, args.out, args.label, args.session_display, args.bottom_tap, args.panel_close)
try:
if args.command == "states":
bench.prepare(args.apk)
bench.states()
else:
completed = 0
for run in range(args.runs):
try:
bench.prepare(args.apk if run == 0 else None)
except RuntimeError as exc:
print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr)
continue
if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb,
args.hold, args.burst):
completed += 1
if completed == 0:
print("memory-guard-ab: no pressure run completed", file=sys.stderr)
return 1
except RuntimeError as exc:
print(f"memory-guard-ab: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+1
View File
@@ -41,6 +41,7 @@
#include <elf.h>
#include <sys/sendfile.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sched.h>
#include <time.h>
#include <sys/xattr.h>
+13 -1
View File
@@ -72,7 +72,7 @@ static char *map_preload_paths(const char *value) {
return out;
}
static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) {
init_ddnatv_hook();
int count = 0;
int has_preload = 0;
@@ -164,6 +164,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) {
continue;
}
if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) {
continue;
}
new_env[dst++] = envp[i];
}
@@ -178,6 +181,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
new_env[dst++] = str;
}
}
if (chosen_real_exe && lib_path && lib_path[0] != '\0') {
size_t len = strlen(lib_path);
char *str = malloc(20 + len + 1);
if (str) {
memcpy(str, "DDNATV_LIBRARY_PATH=", 20);
memcpy(str + 20, lib_path, len + 1);
new_env[dst++] = str;
}
}
char hook_buf[PATH_MAX];
const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL;
+91 -71
View File
@@ -44,8 +44,8 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d
resolve_symlinks(next_path, out, out_size, depth + 1);
}
static char **ensure_hook_in_envp(char *const envp[], const char *real_exe) {
return prepare_ddnatv_env(envp, real_exe);
static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) {
return prepare_ddnatv_env(envp, real_exe, lib_path);
}
// The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and
@@ -162,7 +162,7 @@ static int exec_interp_missing(int fd) {
syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz)
return ENOEXEC;
interp[ph.p_filesz] = 0;
int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0);
if (ifd < 0) return errno;
syscall(SYS_close, ifd);
return 0;
@@ -174,7 +174,7 @@ static int exec_interp_missing(int fd) {
// a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at
// ENOEXEC.
static int exec_preflight(const char *path) {
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0);
if (fd < 0) return errno;
struct stat st;
int err = 0;
@@ -263,6 +263,60 @@ static int is_ldconfig_name(const char *name) {
return strcmp(name, "ldconfig") == 0 || strcmp(name, "ldconfig.real") == 0;
}
struct ldso_direct {
char prog[PATH_MAX];
char lib_path[PATH_MAX * 6];
};
// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads
// gets the --library-path a start of its own gets, or ldd reports its libraries as not found,
// and its path mapped into the rootfs, since ld.so opens it without the hook
static char **ldso_direct_argv(char *const argv[], char *const envp[], struct ldso_direct *buf, int *err) {
*err = 0;
int caller_lib_path = 0;
int pi = ldso_program_index(argv, &caller_lib_path);
if (pi <= 0) return NULL;
int argc = 0;
while (argv[argc]) argc++;
const char *prog = argv[pi];
if (caller_lib_path) {
// the caller's own --library-path stays as it is; only the program is mapped (when it is
// in the rootfs: a caller can also name a file by its real path)
if (prog[0] == '/') {
const char *mapped = rewrite_path(prog, buf->prog, sizeof(buf->prog));
int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1;
if (fd >= 0) {
syscall(SYS_close, fd);
prog = mapped;
}
}
char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 1));
if (!out) {
*err = ENOMEM;
return NULL;
}
for (int i = 0; i <= argc; i++) out[i] = argv[i];
out[pi] = (char *)prog;
return out;
}
if (prog[0] == '/') prog = rewrite_path(prog, buf->prog, sizeof(buf->prog));
struct exec_probe prog_probe;
probe_exec_file(prog, &prog_probe);
build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath,
prog[0] == '/' ? prog : NULL, buf->lib_path, sizeof(buf->lib_path));
char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 3));
if (!out) {
*err = ENOMEM;
return NULL;
}
out[0] = argv[0];
out[1] = (char *)"--library-path";
out[2] = buf->lib_path;
for (int i = 1; i <= argc; i++) out[i + 2] = argv[i];
out[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well
return out;
}
static int ddnatv_execve(const char *filename, char *const argv[], char *const envp[], int depth) {
orig_execve_f_type orig_execve = real_execve();
if (!orig_execve) {
@@ -374,7 +428,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ENOMEM;
return -1;
}
char **new_env = ensure_hook_in_envp(envp, elf_target);
char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path);
int ret = run_execve(orig_execve, ld_so, new_argv, new_env);
if (errno == EACCES && chmod(ld_so, 0755) == 0) {
// ld.so without its exec bit (an unusual restore): fix it once and retry
@@ -388,65 +442,17 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
}
}
// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads
// gets the --library-path a start of its own gets, or ldd reports its libraries as not found,
// and its path mapped into the rootfs, since ld.so opens it without the hook
if (probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) {
int caller_lib_path = 0;
int pi = ldso_program_index(argv, &caller_lib_path);
if (pi > 0 && caller_lib_path) {
// the caller's own --library-path stays as it is; only the program is mapped (when it is
// in the rootfs: a caller can also name a file by its real path)
char prog_buf[PATH_MAX];
const char *prog = argv[pi];
if (prog[0] == '/') {
const char *mapped = rewrite_path(prog, prog_buf, sizeof(prog_buf));
int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1;
if (fd >= 0) {
syscall(SYS_close, fd);
prog = mapped;
}
}
int argc = 0;
while (argv[argc]) argc++;
char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 1));
if (!new_argv) {
errno = ENOMEM;
return -1;
}
for (int i = 0; i <= argc; i++) new_argv[i] = argv[i];
new_argv[pi] = (char *)prog;
prepare_static_program(static_elf); // ld.so is a static program itself
char **ddnatv_env = prepare_ddnatv_env(envp, target);
int ret = run_execve(orig_execve, target, new_argv, ddnatv_env);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
free(new_argv);
errno = saved_errno;
return ret;
struct ldso_direct direct;
int err;
char **new_argv = ldso_direct_argv(argv, envp, &direct, &err);
if (err) {
errno = err;
return -1;
}
if (pi > 0) {
char prog_buf[PATH_MAX];
const char *prog = argv[pi][0] == '/' ? rewrite_path(argv[pi], prog_buf, sizeof(prog_buf)) : argv[pi];
struct exec_probe prog_probe;
probe_exec_file(prog, &prog_probe);
char ld_lib_path[PATH_MAX * 6];
build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath,
prog[0] == '/' ? prog : NULL, ld_lib_path, sizeof(ld_lib_path));
int argc = 0;
while (argv[argc]) argc++;
char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 3));
if (!new_argv) {
errno = ENOMEM;
return -1;
}
new_argv[0] = argv[0];
new_argv[1] = (char *)"--library-path";
new_argv[2] = ld_lib_path;
for (int i = 1; i <= argc; i++) new_argv[i + 2] = argv[i];
new_argv[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well
if (new_argv) {
prepare_static_program(static_elf); // ld.so is a static program itself
char **ddnatv_env = prepare_ddnatv_env(envp, target);
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
int ret = run_execve(orig_execve, target, new_argv, ddnatv_env);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
@@ -470,7 +476,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
return -1;
}
int ret;
if (is_host_interpreter(rewritten_interp)) {
if (is_host_interpreter(interp, rewritten_interp)) {
char **sys_env = clean_env_for_system(envp);
ret = run_execve(orig_execve, rewritten_interp, new_argv, sys_env);
int saved_errno = errno;
@@ -480,7 +486,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ELOOP;
ret = -1;
} else {
char **ddnatv_env = prepare_ddnatv_env(envp, NULL);
char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL);
ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
@@ -500,7 +506,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
}
if (static_elf) prepare_static_program(static_elf);
char **ddnatv_env = prepare_ddnatv_env(envp, target);
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
int ret = run_execve(orig_execve, target, argv, ddnatv_env);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
@@ -823,7 +829,7 @@ static int spawn_script(pid_t *pid, const char *script, struct exec_probe *probe
char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv);
if (!new_argv) return ENOMEM;
int ret;
if (is_host_interpreter(rewritten_interp)) {
if (is_host_interpreter(interp, rewritten_interp)) {
orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn();
char **sys_env = clean_env_for_system(envp);
ret = orig_posix_spawn ? orig_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, sys_env) : ENOSYS;
@@ -942,17 +948,21 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
// Android programs get Android's environment, as execve() gives them: the glibc hook in
// LD_PRELOAD crashes them.
char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target) : clean_env_for_system(orig_ep);
int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0;
char ld_lib_path[PATH_MAX * 6];
ld_lib_path[0] = '\0';
if (via_ld_so)
build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL)
: clean_env_for_system(orig_ep);
int ret = -1;
if (has_ld_so && strcmp(elf_target, ld_so) != 0) {
if (via_ld_so) {
ensure_exec_bit(elf_target, probe.mode);
if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42)
char hook_buf[PATH_MAX];
const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf));
char ld_lib_path[PATH_MAX * 6];
build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv);
if (!new_argv) {
ret = ENOMEM;
@@ -968,9 +978,19 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
}
} else {
if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target);
if (orig_posix_spawn) {
ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, argv, new_envp);
char **spawn_argv = (char **)argv;
int err = 0;
struct ldso_direct direct;
if (in_root && probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) {
char **direct_argv = ldso_direct_argv(argv, orig_ep, &direct, &err);
if (direct_argv) spawn_argv = direct_argv;
}
if (err) {
ret = err;
} else if (orig_posix_spawn) {
ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, spawn_argv, new_envp);
}
if (spawn_argv != argv) free(spawn_argv);
}
if (!orig_posix_spawn) {
+8 -4
View File
@@ -966,10 +966,14 @@ static void parse_shebang(char *hdr, char **interp, char **interp_arg) {
*interp_arg = arg;
}
// Interpreters outside the rootfs (Android's /system/bin/sh) run with Android's environment.
static int is_host_interpreter(const char *interp) {
return strncmp(interp, "/system", 7) == 0 ||
(g_ddnatv_root[0] != '\0' && strncmp(interp, g_ddnatv_root, g_ddnatv_root_len) != 0);
// Interpreters outside the rootfs and its binds (Android's /system/bin/sh) run with Android's environment.
static int is_host_interpreter(const char *interp, const char *rewritten) {
if (strncmp(rewritten, "/system", 7) == 0) return 1;
if (g_ddnatv_root[0] == '\0' || get_rootfs_subpath(rewritten)) return 0;
if (!is_mapped_guest_path(interp)) return 1;
struct exec_probe probe;
probe_exec_file(rewritten, &probe);
return probe.android_interp;
}
// argv for running `script` with its interpreter: interp [arg] script args... (the script's own
+1 -1
View File
@@ -21,7 +21,7 @@ int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (voi
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; }
int getgroups(int size, gid_t list[]) {
if (size > 0 && list != NULL) list[0] = 0;
if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1;
return 1;
}
// What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is
+61 -21
View File
@@ -82,7 +82,7 @@ static void ddnatv_load_binds(const char *spec) {
char kernel_src[PATH_MAX];
if (strcmp(src, dst) != 0) {
ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src));
src = kernel_src;
if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src;
}
b->src = strdup(src);
b->dst = strdup(dst);
@@ -188,6 +188,25 @@ static __thread int t_bind_link_depth = 0;
static void normalize_path(char *path);
static int climbs_past_root(const char *dir, const char *target) {
long depth = 0;
for (const char *p = dir; *p; p++)
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
for (const char *p = target; *p;) {
while (*p == '/') p++;
const char *end = p;
while (*end && *end != '/') end++;
size_t len = (size_t)(end - p);
if (len == 2 && p[0] == '.' && p[1] == '.') {
if (--depth < 0) return 1;
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
depth++;
}
p = end;
}
return 0;
}
#if defined(__aarch64__)
static long raw_link_dir(const char *link, char *out, size_t size) {
const char *slash = strrchr(link, '/');
@@ -215,25 +234,6 @@ static long raw_link_dir(const char *link, char *out, size_t size) {
return n;
}
static int climbs_past_root(const char *dir, const char *target) {
long depth = 0;
for (const char *p = dir; *p; p++)
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
for (const char *p = target; *p;) {
while (*p == '/') p++;
const char *end = p;
while (*end && *end != '/') end++;
size_t len = (size_t)(end - p);
if (len == 2 && p[0] == '.' && p[1] == '.') {
if (--depth < 0) return 1;
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
depth++;
}
p = end;
}
return 0;
}
static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted);
static const char *guest_path_of_host_dir(const char *dir, char *out, size_t size) {
@@ -335,6 +335,15 @@ static const char *resolve_drive_links(const char *host, char *buffer, size_t bu
// Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past
// redundant leading "/" and "/." components) when it needs no change, else `buffer`.
static const char *rewrite_normalized_in_root(const char *path, char *buffer, size_t bufsize) {
char normalized[PATH_MAX];
ddnatv_copy_cstr(normalized, sizeof(normalized), path);
normalize_path(normalized);
const char *mapped = rewrite_path_in_root(normalized, buffer, bufsize);
if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped);
return buffer;
}
static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize) {
if (!path) return NULL;
if (path[0] != '/' || g_ddnatv_root_len == 0) return path;
@@ -354,6 +363,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
}
}
if (strstr(path, "/..") && climbs_past_root("", path)) return rewrite_normalized_in_root(path, buffer, bufsize);
// Root directory
if (path[1] == '\0') {
ddnatv_append(buffer, bufsize, 0, g_ddnatv_root, g_ddnatv_root_len);
@@ -364,6 +375,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
const struct ddnatv_bind *b = &g_binds[i];
if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) {
if (b->identity) return path;
if (strstr(path + b->dst_len, "/..") && climbs_past_root("", path + b->dst_len))
return rewrite_normalized_in_root(path, buffer, bufsize);
size_t n = ddnatv_append(buffer, bufsize, 0, b->src, b->src_len);
ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len));
return resolve_bind_links(buffer, b->src_len, buffer, bufsize);
@@ -806,10 +819,36 @@ static void ddnatv_build_at_dirs(void) {
}
}
#if defined(__aarch64__)
static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) {
char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX];
if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd");
else snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd);
long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1);
if (n <= 0 || host[0] != '/') return NULL;
host[n] = '\0';
const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf));
if (!dir || strcmp(dir, host) == 0) return NULL;
if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL;
size_t used = ddnatv_append(guest, sizeof(guest), 0, dir, strlen(dir));
used = ddnatv_append(guest, sizeof(guest), used, "/", 1);
used = ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel));
if (used + 1 >= sizeof(guest)) return NULL;
const char *mapped = rewrite_path_in_root(guest, buf, size);
if (mapped != buf) ddnatv_copy_cstr(buf, size, mapped);
return buf;
}
#endif
// The absolute host path for `rel` given relative to `dirfd`, or NULL when the call needs no change.
static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
#if defined(__aarch64__)
if (dirfd == AT_FDCWD || !rel || rel[0] == '\0' || rel[0] == '/' || g_nbinds == 0) return NULL;
if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL;
if (strstr(rel, "..")) {
const char *walked = map_parent_walk(dirfd, rel, buf, size);
if (walked || dirfd == AT_FDCWD) return walked;
}
if (dirfd == AT_FDCWD || g_nbinds == 0) return NULL;
pthread_once(&g_at_once, ddnatv_build_at_dirs);
if (g_n_at_dirs == 0) return NULL;
struct stat st;
@@ -818,6 +857,7 @@ static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
if (g_at_dirs[i].ino != (unsigned long)st.st_ino || g_at_dirs[i].dev != (unsigned long)st.st_dev) continue;
char guest[PATH_MAX];
const char *base = g_at_dirs[i].guest;
if (base[1] && climbs_past_root(base, rel)) return NULL;
size_t used = ddnatv_append(guest, sizeof(guest), 0, base, strlen(base));
if (used > 1) used = ddnatv_append(guest, sizeof(guest), used, "/", 1);
ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel));
+125 -9
View File
@@ -1,32 +1,148 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c.
//
// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which
// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink()
// here, which map /dev/shm.
// shm_open(), shm_unlink() and the named semaphores of glibc open /dev/shm/NAME with system calls
// of their own, which the path hooks never see and Android has no /dev/shm for. They go through
// open(), renameat2() and unlink() here, which map /dev/shm.
#ifndef DDNATV_HOST_TEST
static int posix_shm_path(const char *name, char *path, size_t size) {
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) {
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
size_t len = strlen(name);
if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
size_t len = strlen(name) + strlen(prefix);
if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
return -1;
}
if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
int shm_open(const char *name, int oflag, mode_t mode) {
char path[PATH_MAX];
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode);
}
int shm_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
struct posix_sem {
dev_t dev;
ino_t ino;
sem_t *addr;
unsigned int refs;
struct posix_sem *next;
};
static struct posix_sem *g_posix_sems;
static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER;
static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); }
static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); }
__attribute__((constructor)) static void posix_sems_across_fork(void) {
pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock);
}
static void close_keeping_errno(int fd) {
int saved = errno;
close(fd);
errno = saved;
}
static sem_t *posix_sem_map(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) return SEM_FAILED;
sem_t *sem = SEM_FAILED;
posix_sems_hold();
struct posix_sem *e = g_posix_sems;
while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next;
if (e) {
e->refs++;
sem = e->addr;
} else {
void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e));
if (e) {
*e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems};
g_posix_sems = e;
sem = addr;
} else if (addr != MAP_FAILED) {
munmap(addr, sizeof(sem_t));
errno = ENOMEM;
}
}
posix_sems_unlock();
return sem;
}
static sem_t *posix_sem_open_fd(int fd) {
if (fd < 0) return SEM_FAILED;
sem_t *sem = posix_sem_map(fd);
close_keeping_errno(fd);
return sem;
}
sem_t *sem_open(const char *name, int oflag, ...) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED;
if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC));
va_list args;
va_start(args, oflag);
mode_t mode = va_arg(args, mode_t);
unsigned int value = va_arg(args, unsigned int);
va_end(args);
static unsigned int serial;
for (;;) {
if (!(oflag & O_EXCL)) {
int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd);
}
if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; }
sem_t initial;
memset(&initial, 0, sizeof(initial));
sem_init(&initial, 1, value);
char temp[PATH_MAX];
int fd;
do {
snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED));
fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
} while (fd < 0 && errno == EEXIST);
if (fd < 0) return SEM_FAILED;
errno = EIO;
sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED;
close_keeping_errno(fd);
if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem;
int saved = errno;
if (sem != SEM_FAILED) sem_close(sem);
unlink(temp);
errno = saved;
if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED;
}
}
int sem_close(sem_t *sem) {
posix_sems_hold();
struct posix_sem **link = &g_posix_sems;
while (*link && (*link)->addr != sem) link = &(*link)->next;
struct posix_sem *e = *link;
if (e && --e->refs == 0) {
*link = e->next;
munmap(e->addr, sizeof(sem_t));
free(e);
}
posix_sems_unlock();
if (!e) { errno = EINVAL; return -1; }
return 0;
}
int sem_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
+140 -48
View File
@@ -519,6 +519,19 @@ static int close_range_all(unsigned int first, unsigned int last, int flags) {
static __thread int t_syscall_redirect = 0;
static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) {
char nested_buf[PATH_MAX];
const char *path = (const char *)pathname;
if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf));
return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0);
}
static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) {
long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0);
if (rc == 0) *real = *effective = *saved = 0;
return rc;
}
long syscall(long number, ...) {
va_list ap;
va_start(ap, number);
@@ -563,6 +576,38 @@ long syscall(long number, ...) {
}
#endif
#ifdef __NR_rt_sigprocmask
if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) {
uint64_t mask;
memcpy(&mask, (const void *)arg2, sizeof(mask));
mask &= ~(1ULL << (SIGSYS - 1));
return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0);
}
#endif
#ifdef __NR_rt_sigaction
if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) {
struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold;
struct sigaction act, old;
memset(&act, 0, sizeof(act));
if (arg2) {
memcpy(&kact, (const void *)arg2, sizeof(kact));
act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler;
act.sa_flags = (int)kact.flags;
memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask));
}
remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL);
if (arg3) {
memset(&kold, 0, sizeof(kold));
kold.handler = (void *)old.sa_sigaction;
kold.flags = (unsigned long)(unsigned int)old.sa_flags;
memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask));
memcpy((void *)arg3, &kold, sizeof(kold));
}
return 0;
}
#endif
#ifdef __NR_seccomp
if (number == __NR_seccomp) {
return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3);
@@ -618,16 +663,94 @@ long syscall(long number, ...) {
}
#endif
if (g_initialized) {
#ifdef __NR_openat
if (number == __NR_openat) {
if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4);
t_syscall_redirect++;
long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4);
t_syscall_redirect--;
return ret;
}
#endif
#if defined(__NR_mkdirat)
if (number == __NR_mkdirat) {
return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3);
}
#endif
#if defined(__NR_unlinkat)
if (number == __NR_unlinkat) {
return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3);
}
#endif
#if defined(__NR_renameat)
if (number == __NR_renameat) {
return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4);
}
#endif
#if defined(__NR_renameat2)
if (number == __NR_renameat2) {
return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5);
}
#endif
#if defined(__NR_symlinkat)
if (number == __NR_symlinkat) {
return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3);
}
#endif
#if defined(__NR_fchmodat)
if (number == __NR_fchmodat) {
return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0);
}
#endif
#if defined(__NR_fchownat)
if (number == __NR_fchownat) {
return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5);
}
#endif
#if defined(__NR_utimensat)
if (number == __NR_utimensat) {
if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0);
return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4);
}
#endif
#if defined(__NR_connect)
if (number == __NR_connect) {
return (long)connect((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
}
#endif
#if defined(__NR_bind)
if (number == __NR_bind) {
return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
}
#endif
#if defined(__NR_truncate)
if (number == __NR_truncate) {
return (long)truncate((const char *)arg1, (off_t)arg2);
}
#endif
#if defined(__NR_chdir)
if (number == __NR_chdir) {
return (long)chdir((const char *)arg1);
}
#endif
#if defined(__NR_chroot)
if (number == __NR_chroot) {
return (long)chroot((const char *)arg1);
}
#endif
#if defined(__NR_inotify_add_watch)
if (number == __NR_inotify_add_watch) {
return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3);
}
#endif
}
#ifdef __NR_openat2
if (number == __NR_openat2) {
// libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested
// call maps the path and goes straight to the kernel
if (t_syscall_redirect) {
char nested_buf[PATH_MAX];
const char *path = (const char *)arg2;
if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf));
return call_orig_syscall(number, arg1, (unsigned long)path, arg3, arg4, 0, 0);
}
if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4);
t_syscall_redirect++;
long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4);
t_syscall_redirect--;
@@ -649,12 +772,7 @@ long syscall(long number, ...) {
#if defined(__NR_faccessat)
if (number == __NR_faccessat) {
if (t_syscall_redirect) {
char nested_buf[PATH_MAX];
const char *path = (const char *)arg2;
if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf));
return call_orig_syscall(number, arg1, (unsigned long)path, arg3, 0, 0, 0);
}
if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0);
t_syscall_redirect++;
long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0);
t_syscall_redirect--;
@@ -765,48 +883,22 @@ long syscall(long number, ...) {
if (number == __NR_getegid32) return 0;
#endif
#if defined(__NR_getresuid)
if (number == __NR_getresuid) {
uid_t *ruid = (uid_t *)arg1;
uid_t *euid = (uid_t *)arg2;
uid_t *suid = (uid_t *)arg3;
if (ruid) *ruid = 0;
if (euid) *euid = 0;
if (suid) *suid = 0;
return 0;
}
if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getresuid32)
if (number == __NR_getresuid32) {
uid_t *ruid = (uid_t *)arg1;
uid_t *euid = (uid_t *)arg2;
uid_t *suid = (uid_t *)arg3;
if (ruid) *ruid = 0;
if (euid) *euid = 0;
if (suid) *suid = 0;
return 0;
}
if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getresgid)
if (number == __NR_getresgid) {
gid_t *rgid = (gid_t *)arg1;
gid_t *egid = (gid_t *)arg2;
gid_t *sgid = (gid_t *)arg3;
if (rgid) *rgid = 0;
if (egid) *egid = 0;
if (sgid) *sgid = 0;
return 0;
}
if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getresgid32)
if (number == __NR_getresgid32) {
gid_t *rgid = (gid_t *)arg1;
gid_t *egid = (gid_t *)arg2;
gid_t *sgid = (gid_t *)arg3;
if (rgid) *rgid = 0;
if (egid) *egid = 0;
if (sgid) *sgid = 0;
return 0;
}
if (number == __NR_getresgid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getgroups)
if (number == __NR_getgroups) return (long)getgroups((int)arg1, (gid_t *)arg2);
#endif
#if defined(__NR_fchown)
if (number == __NR_fchown) return (long)fchown((int)arg1, (uid_t)arg2, (gid_t)arg3);
#endif
return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6);
+18 -2
View File
@@ -84,6 +84,19 @@ static void init_ddnatv_hook(void) {
setenv("TZDIR", tzdir_buf, 0);
}
const char *curr_locpath = getenv("LOCPATH");
if (!curr_locpath || curr_locpath[0] == '\0') {
char locpath_buf[PATH_MAX];
snprintf(locpath_buf, sizeof(locpath_buf), "%s/usr/lib/locale", g_ddnatv_root);
setenv("LOCPATH", locpath_buf, 1);
}
if (!getenv("GCONV_PATH")) {
char gconv_buf[PATH_MAX];
snprintf(gconv_buf, sizeof(gconv_buf), "%s/usr/lib/aarch64-linux-gnu/gconv", g_ddnatv_root);
setenv("GCONV_PATH", gconv_buf, 0);
}
const char *curr_cert = getenv("SSL_CERT_FILE");
if (!curr_cert || curr_cert[0] == '\0' || strcmp(curr_cert, "/etc/ssl/certs/ca-certificates.crt") == 0) {
char cert_buf[PATH_MAX];
@@ -350,8 +363,11 @@ static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, si
static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) {
if (!path) return NULL;
// Relative paths must NEVER be rewritten to rootfs root
if (path[0] != '/') return path;
init_ddnatv_hook();
if (path[0] != '/') {
const char *walked = map_at(AT_FDCWD, path, buffer, bufsize);
return walked ? walked : path;
}
return rewrite_path_in_root(path, buffer, bufsize);
}
@@ -361,7 +377,7 @@ static const char *rewrite_path(const char *path, char *buffer, size_t bufsize)
// followed in the guest's view first. The rootfs's own links were made relative already.
static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize) {
if (!path) return NULL;
if (path[0] != '/') return path;
if (path[0] != '/') return rewrite_path(path, buffer, bufsize);
init_ddnatv_hook();
int moved = 0;
for (int i = 0; i < g_nbinds; i++) {
+11 -5
View File
@@ -94,6 +94,13 @@ int listen(int sockfd, int backlog) {
return ret;
}
static void copy_unix_path(const struct sockaddr_un *sun, socklen_t addrlen, char *out) {
size_t max = addrlen - offsetof(struct sockaddr_un, sun_path);
if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path);
memcpy(out, sun->sun_path, max);
out[max] = '\0';
}
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
static int (*orig_bind)(int, const struct sockaddr *, socklen_t) = NULL;
if (!orig_bind) orig_bind = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "bind");
@@ -104,7 +111,9 @@ int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
struct sockaddr_un mod_sun;
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
char guest[sizeof(sun->sun_path) + 1];
copy_unix_path(sun, addrlen, guest);
rewrite_unix_socket_path(guest, mod_sun.sun_path, sizeof(mod_sun.sun_path));
return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
}
}
@@ -133,10 +142,7 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
char guest[sizeof(sun->sun_path) + 1];
size_t max = addrlen - offsetof(struct sockaddr_un, sun_path);
if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path);
memcpy(guest, sun->sun_path, max);
guest[max] = '\0';
copy_unix_path(sun, addrlen, guest);
char followed[PATH_MAX];
const char *path = guest[0] == '/' ? follow_guest_link(guest, followed, sizeof(followed)) : guest;
rewrite_unix_socket_path(path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
+20 -1
View File
@@ -11,6 +11,8 @@ linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib"
source "$here/tracking/release.env"
# shellcheck source=butler/release.env
source "$here/butler/release.env"
# shellcheck source=zstd/release.env
source "$here/zstd/release.env"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
@@ -21,6 +23,22 @@ fetch() {
bash "$here/fetch-verified.sh" "$@"
}
zstd_version() { "$1" -V 2>/dev/null | sed -n 's/.* v\([0-9][0-9.]*\),.*/\1/p'; }
zstd=$(command -v zstd || true)
if [ -z "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then
zstd="${DROIDDECK_PACK_CACHE:-"$HOME/.cache/droiddeck-pack-inputs"}/zstd-$ZSTD_VERSION/zstd"
if [ ! -x "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then
fetch "https://github.com/facebook/zstd/releases/download/v$ZSTD_VERSION/zstd-$ZSTD_VERSION.tar.gz" \
"$ZSTD_SHA256" "$work/zstd.tar.gz"
tar -xzf "$work/zstd.tar.gz" -C "$work"
make -s -C "$work/zstd-$ZSTD_VERSION" -j"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)" zstd-release >/dev/null
mkdir -p "$(dirname "$zstd")"
install -m755 "$work/zstd-$ZSTD_VERSION/programs/zstd" "$zstd.part.$$"
mv -f "$zstd.part.$$" "$zstd"
fi
fi
[ "$(zstd_version "$zstd")" = "$ZSTD_VERSION" ] || { echo "packs need zstd $ZSTD_VERSION, $zstd is not it" >&2; exit 1; }
pack() {
local name=$1 src=$2
shift 2
@@ -47,7 +65,7 @@ with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar:
with open(path, "rb") as f:
tar.addfile(info, f)
EOF
zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
"$zstd" -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')"
}
@@ -80,6 +98,7 @@ pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt
[ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe
[ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe
[ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll
[ ! -f "$linuxfs/droiddeck-epic/EpicGamesLauncher.exe" ] || pack epic "$linuxfs/droiddeck-epic" EpicGamesLauncher.exe
mkdir "$work/butler"
fetch "https://broth.itch.zone/butler/linux-arm64/${BUTLER_VERSION}/archive/default" \
+2 -2
View File
@@ -1,2 +1,2 @@
PROOT_PACK_SHA256=5a2b7284e6357f88a14a790abd54e61effbe5f202c63b6aaba9b974c559649c3
PROOT_PACK_SIZE=96643
PROOT_PACK_SHA256=7800e188363f2b99485e8b9e4f68ea77eb65b088ca66b9e508a3a0938acea394
PROOT_PACK_SIZE=99536
+2
View File
@@ -0,0 +1,2 @@
ZSTD_VERSION=1.5.5
ZSTD_SHA256=9c4396cc829cfae319a6e2615202e82aad41372073482fce286fac78646d3ee4
+2 -1
View File
@@ -23,7 +23,8 @@ while IFS= read -r dir; do
done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV)
[[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; }
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease
# Lint vital is most of an incremental build and CI runs it.
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease -x lintVitalAnalyzeRelease
(
cd "$(dirname "${signing_env}")"
set -a; . "${signing_env}"; set +a
+12
View File
@@ -1,6 +1,7 @@
from pathlib import Path
import importlib.util
import re
import shutil
import sys
from zipfile import ZipFile
@@ -34,6 +35,14 @@ def source_assets(overlay=OVERLAY):
return result
def stage(target=OVERLAY.parents[2] / 'app/src/main', overlay=OVERLAY):
for source, asset in source_assets(overlay).items():
path = target / asset
if not path.is_file() or path.read_bytes() != source.read_bytes():
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, path)
def check(apk, overlay=OVERLAY):
errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else []
with ZipFile(apk) as package:
@@ -60,6 +69,9 @@ def check(apk, overlay=OVERLAY):
if __name__ == '__main__':
if sys.argv[1:] == ['--stage']:
stage()
sys.exit()
errors = check(sys.argv[1])
if errors:
sys.exit('\n'.join(errors))
+34 -9
View File
@@ -15,18 +15,18 @@ MANIFEST = Path('app/build/runtime-inputs.json')
PACKS = Path('app/build/packs')
PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet',
'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar',
'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt',
'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', 'assets/linuxfs/usr/local/lib/droiddeck-epic/': 'epic',
'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'}
# DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker.
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')}
# The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory.
PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': 'libproot-loader.so'}
PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so']
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt']
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic']
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
@@ -48,20 +48,38 @@ def digest(path):
return result.hexdigest()
def copied(root):
# Helper scripts are staged verbatim on every Gradle build and checked against the APK by
# check_session_assets.py, so they are neither preparation inputs nor prepared outputs.
if str(Path(__file__).resolve().parent) not in sys.path:
sys.path.insert(0, str(Path(__file__).resolve().parent))
from check_session_assets import OVERLAY, source_assets
found = source_assets() if root == ROOT else source_assets(root / OVERLAY.relative_to(ROOT))
return {source.relative_to(root).as_posix(): 'app/src/main/' + asset for source, asset in found.items()}
def sources(root):
files = []
files, builds = [], set()
skipped = set(copied(root))
for name in SOURCE_PATHS:
path = root / name
files.extend(path.rglob('*') if path.is_dir() else [path])
if path.is_dir():
builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml'))
return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files))
if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'}
if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'
and path.relative_to(root).as_posix() not in skipped
and not any(build in path.parents for build in builds)}
def outputs(root):
result = {}
skipped = set(copied(root).values())
for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']:
base = root / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.relative_to(root).as_posix() in skipped:
continue
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
result['assets/' + tree + '/' + path.relative_to(base).as_posix()] = path.relative_to(root).as_posix()
for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']:
@@ -81,7 +99,6 @@ def required():
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so',
'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
'usr/local/bin/droiddeck-gog-maintenance',
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
'usr/local/lib/droiddeck-pipewire.tzst']]
for arch in ['x86_64', 'i386']:
@@ -101,8 +118,7 @@ def required():
'layer/VK_LAYER_DROIDDECK_vr.json', 'layer/VK_LAYER_DROIDDECK_vr_implicit.json',
'layer/libdroiddeck_vr_scheduling.so']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-gpuload/' + name for name in
['libVkLayer_droiddeck_gpuload.so', 'VK_LAYER_DROIDDECK_gpu_load.json',
'libVkLayer_droiddeck_vramcap.so', 'VK_LAYER_DROIDDECK_vram_cap.json']]
['libVkLayer_droiddeck_gpuload.so', 'VK_LAYER_DROIDDECK_gpu_load.json']]
for side in ['left', 'right']:
paths += [f'assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/resources/rendermodels/droiddeck_hand_{side}/{name}'
for name in [f'droiddeck_hand_{side}.json', 'hand.mtl', 'hand.png', 'hand_open.obj', 'hand_fist.obj',
@@ -177,6 +193,10 @@ def verify(root=ROOT, stale_sources_ok=False):
raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.')
if data.get('version') != 1:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
copies = copied(root)
data['sources'] = {name: value for name, value in (data.get('sources') or {}).items() if name not in copies}
data['outputs'] = {name: output for name, output in (data.get('outputs') or {}).items()
if output.get('path') not in copies.values()}
current = sources(root)
if data.get('sources') != current:
if not stale_sources_ok:
@@ -194,6 +214,11 @@ def verify(root=ROOT, stale_sources_ok=False):
raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.')
if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}:
raise ValueError('Runtime file set changed. Run tools/build_local.sh.')
for source, asset in copies.items():
path = root / asset
if not path.is_file() or path.read_bytes() != (root / source).read_bytes():
raise ValueError(asset + ' is not a current copy of ' + source
+ '. Run python3 tools/release/check_session_assets.py --stage.')
return data
@@ -229,7 +254,7 @@ def windows_binaries(package):
def check_apk(apk, root=ROOT):
data = verify(root)
packs = {name: pack_digests(root, name) for name in PACK_NAMES
if name not in ('ubisoft', 'rockstar', 'dirt') or (root / PACKS / (name + '.tar.zst')).is_file()}
if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') or (root / PACKS / (name + '.tar.zst')).is_file()}
for name, rel in PROOT_LOADER.items():
if packs['proot'].get(rel) != data['outputs'][name]['sha256']:
raise ValueError('Add-on pack proot is missing or has a stale ' + rel)
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Builds the Rockstar launcher in a container, on the host's own architecture. Rust's
# i686-pc-windows-gnu target needs a DWARF2 mingw; Homebrew's i686 mingw uses SJLJ and fails to link.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
out=${1:?usage: build-container.sh <output directory>}
. "$repo/tools/docker_platform.sh"
cache=${DROIDDECK_BUILD_CACHE:-$HOME/.cache/droiddeck-build}/rockstar-container
mkdir -p "$out" "$cache/cargo" "$cache/target"
out=$(cd "$out" && pwd)
image=droiddeck-rockstar-build:v2-${docker_platform#linux/}
if ! docker image inspect "$image" >/dev/null 2>&1; then
docker build --platform "$docker_platform" -t "$image" - <<'EOF'
FROM public.ecr.aws/docker/library/ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo PATH=/opt/cargo/bin:$PATH
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates curl gcc libc6-dev \
gcc-mingw-w64-i686-posix gcc-mingw-w64-x86-64-posix >/dev/null
RUN curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --default-toolchain stable \
-t i686-pc-windows-gnu -t x86_64-pc-windows-gnu && chmod -R a+rX /opt/rustup /opt/cargo
EOF
fi
docker run --rm --platform "$docker_platform" --user "$(id -u):$(id -g)" \
-e CARGO_HOME=/cache/cargo -e CARGO_TARGET_DIR=/cache/target -e HOME=/tmp \
-v "$repo:/src" -v "$out:/out" -v "$cache:/cache" -w /src "$image" \
bash tools/rockstar-launcher/build.sh /out
+7 -2
View File
@@ -10,14 +10,19 @@ paths=(
app/build/packs app/build/localPackAssets app/build/packs-local-aside app/build/quest-inputs
app/build/rustJniLibs app/build/vkbridgeJniLibs
app/src/main/assets/directaudio app/src/main/assets/droiddeck-esync app/src/main/assets/linuxfs
app/src/main/assets/desktop-removal
app/src/main/assets/desktop-removal app/src/main/assets/hybris
app/src/main/jniLibs/arm64-v8a
app/src/main/rust/stores/target
)
for path in "${paths[@]}"; do
[[ -e "${main_root}/${path}" ]] || continue
if [[ -d "${main_root}/${path}" ]]; then
[[ -z "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]] || continue
if [[ -n "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]]; then
# A directory holding only tracked files (jniLibs) still lacks every built library.
[[ -z "$(git -C "${repo_root}" ls-files --others -- "${path}")" ]] || continue
cp -Rn "${main_root}/${path}/." "${repo_root}/${path}/"
continue
fi
mkdir -p "$(dirname "${repo_root}/${path}")"
staged=$(mktemp -d "${repo_root}/${path}.seed.XXXXXX")
trap 'rm -rf "${staged}"' EXIT
+548
View File
@@ -0,0 +1,548 @@
#include "mali_compat.h"
#include <spirv/unified1/spirv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OPCODE(word) ((word) & 0xffffu)
#define LENGTH(word) ((word) >> 16)
static const uint32_t newer[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000a, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000,
0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006, 0x00000003,
0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x00040020, 0x00000007, 0x00000006,
0x00000005, 0x0004003b, 0x00000007, 0x00000003, 0x00000006, 0x00030021, 0x00000008, 0x00000004,
0x00050036, 0x00000004, 0x00000001, 0x00000000, 0x00000008, 0x000200f8, 0x00000009, 0x00011140,
0x00010038,
};
static const size_t newer_count = sizeof(newer) / sizeof(uint32_t);
static const uint32_t readonly_parameter[] = {
SpvMagicNumber, 0x00010600, 0, 13, 0,
(2u << 16) | SpvOpCapability, SpvCapabilityShader,
(3u << 16) | SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450,
(5u << 16) | SpvOpEntryPoint, SpvExecutionModelFragment, 7, 0x6e69616d, 0,
(3u << 16) | SpvOpExecutionMode, 7, SpvExecutionModeOriginUpperLeft,
(3u << 16) | SpvOpDecorate, 3, SpvDecorationBlock,
(5u << 16) | SpvOpMemberDecorate, 3, 0, SpvDecorationOffset, 0,
(3u << 16) | SpvOpDecorate, 10, SpvDecorationNonWritable,
(4u << 16) | SpvOpDecorate, 12, SpvDecorationDescriptorSet, 0,
(4u << 16) | SpvOpDecorate, 12, SpvDecorationBinding, 0,
(2u << 16) | SpvOpTypeVoid, 1,
(3u << 16) | SpvOpTypeFloat, 2, 32,
(3u << 16) | SpvOpTypeStruct, 3, 2,
(4u << 16) | SpvOpTypePointer, 4, SpvStorageClassStorageBuffer, 3,
(4u << 16) | SpvOpVariable, 4, 12, SpvStorageClassStorageBuffer,
(3u << 16) | SpvOpTypeFunction, 5, 1,
(4u << 16) | SpvOpTypeFunction, 6, 1, 4,
(5u << 16) | SpvOpFunction, 1, 7, 0, 5,
(2u << 16) | SpvOpLabel, 8,
(1u << 16) | SpvOpReturn,
(1u << 16) | SpvOpFunctionEnd,
(5u << 16) | SpvOpFunction, 1, 9, 0, 6,
(3u << 16) | SpvOpFunctionParameter, 4, 10,
(2u << 16) | SpvOpLabel, 11,
(1u << 16) | SpvOpReturn,
(1u << 16) | SpvOpFunctionEnd,
};
static const uint32_t older[] = {
0x07230203, 0x00010300, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013,
0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, 0x00000003, 0x00000004,
0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, 0x00000003, 0x00050036,
0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, 0x000100fd, 0x00010038,
};
static const size_t older_count = sizeof(older) / sizeof(uint32_t);
static const uint32_t capability[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x00000046, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006,
0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007,
0x000100fd, 0x00010038,
};
static const size_t capability_count = sizeof(capability) / sizeof(uint32_t);
static const uint32_t memory[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x000014e1, 0x0003000e, 0x00000000, 0x00000003, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006,
0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007,
0x000100fd, 0x00010038,
};
static const size_t memory_count = sizeof(memory) / sizeof(uint32_t);
static const uint32_t zinklike[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000017, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000,
0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040015, 0x00000006, 0x00000020,
0x00000001, 0x00040017, 0x00000007, 0x00000005, 0x00000004, 0x0003001e, 0x00000008, 0x00000007,
0x00040020, 0x00000009, 0x00000003, 0x00000005, 0x0004003b, 0x00000009, 0x00000002, 0x00000003,
0x00040020, 0x0000000a, 0x00000006, 0x00000008, 0x00040020, 0x0000000b, 0x00000007, 0x00000008,
0x0004003b, 0x0000000a, 0x00000003, 0x00000006, 0x00040020, 0x0000000c, 0x00000006, 0x00000005,
0x00040020, 0x0000000d, 0x00000007, 0x00000005, 0x0004002b, 0x00000005, 0x0000000e, 0x3f800000,
0x0004002b, 0x00000006, 0x0000000f, 0x00000000, 0x00030021, 0x00000010, 0x00000004, 0x00050036,
0x00000004, 0x00000001, 0x00000000, 0x00000010, 0x000200f8, 0x00000011, 0x0004003b, 0x0000000b,
0x00000012, 0x00000007, 0x00060041, 0x0000000d, 0x00000013, 0x00000012, 0x0000000f, 0x0000000f,
0x0003003e, 0x00000013, 0x0000000e, 0x0004003d, 0x00000005, 0x00000014, 0x00000013, 0x00070050,
0x00000007, 0x00000015, 0x00000014, 0x00000014, 0x00000014, 0x00000014, 0x00040041, 0x00000009,
0x00000016, 0x00000002, 0x0003003e, 0x00000016, 0x00000014, 0x000100fd, 0x00010038,
};
static const size_t zinklike_count = sizeof(zinklike) / sizeof(uint32_t);
static const uint32_t nonuniform[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x000014b5, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004,
0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001,
0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd,
0x00010038,
};
static const size_t nonuniform_count = sizeof(nonuniform) / sizeof(uint32_t);
static const uint32_t nonuniform_extension[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x000014b5, 0x0008000a, 0x5f565053, 0x5f545845, 0x63736564, 0x74706972, 0x695f726f, 0x7865646e,
0x00676e69, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004,
0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001,
0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd,
0x00010038,
};
static const size_t nonuniform_extension_count = sizeof(nonuniform_extension) / sizeof(uint32_t);
static const uint32_t select_struct[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000011, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013,
0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x0004001e, 0x00000006,
0x00000005, 0x00000005, 0x00040020, 0x00000007, 0x00000003, 0x00000005, 0x0004003b, 0x00000007,
0x00000002, 0x00000003, 0x0004002b, 0x00000005, 0x00000008, 0x3f800000, 0x0004002b, 0x00000005,
0x00000009, 0x00000000, 0x00030029, 0x00000004, 0x0000000a, 0x0005002c, 0x00000006, 0x0000000b,
0x00000008, 0x00000009, 0x0005002c, 0x00000006, 0x0000000c, 0x00000009, 0x00000008, 0x00030021,
0x0000000d, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x0000000d, 0x000200f8,
0x0000000e, 0x000600a9, 0x00000006, 0x0000000f, 0x0000000a, 0x0000000b, 0x0000000c, 0x00050051,
0x00000005, 0x00000010, 0x0000000f, 0x00000000, 0x0003003e, 0x00000002, 0x00000010, 0x000100fd,
0x00010038,
};
static const size_t select_struct_count = sizeof(select_struct) / sizeof(uint32_t);
static const uint32_t select_scalar[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000d, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013,
0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006,
0x00000003, 0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x0004002b, 0x00000005,
0x00000007, 0x3f800000, 0x0004002b, 0x00000005, 0x00000008, 0x00000000, 0x00030029, 0x00000004,
0x00000009, 0x00030021, 0x0000000a, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000,
0x0000000a, 0x000200f8, 0x0000000b, 0x000600a9, 0x00000005, 0x0000000c, 0x00000009, 0x00000007,
0x00000008, 0x0003003e, 0x00000002, 0x0000000c, 0x000100fd, 0x00010038,
};
static const size_t select_scalar_count = sizeof(select_scalar) / sizeof(uint32_t);
static const uint32_t nonsemantic[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000b,
0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003,
0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003,
0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020,
0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b,
0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005,
0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b,
0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038,
};
static const size_t nonsemantic_count = sizeof(nonsemantic) / sizeof(uint32_t);
static const uint32_t nonsemantic_extension[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000a,
0x5f565053, 0x5f52484b, 0x5f6e6f6e, 0x616d6573, 0x6369746e, 0x666e695f, 0x0000006f, 0x0008000b,
0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003,
0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003,
0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020,
0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b,
0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005,
0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b,
0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038,
};
static const size_t nonsemantic_extension_count = sizeof(nonsemantic_extension) / sizeof(uint32_t);
static int failures;
static void check(int condition, const char *what)
{
if (!condition) {
printf("FAIL: %s\n", what);
failures++;
}
}
static size_t count_opcodes(const uint32_t *words, size_t count, uint32_t opcode)
{
size_t found = 0;
for (size_t i = 5; i < count; i += LENGTH(words[i])) {
if (OPCODE(words[i]) == opcode)
found++;
}
return found;
}
static size_t interface_size(const uint32_t *words, size_t count)
{
for (size_t i = 5; i < count; i += LENGTH(words[i])) {
if (OPCODE(words[i]) != SpvOpEntryPoint)
continue;
size_t length = LENGTH(words[i]);
size_t name = 3;
while (name < length) {
uint32_t word = words[i + name];
if (!(word & 0xff) || !(word & 0xff00) || !(word & 0xff0000) || !(word & 0xff000000))
break;
name++;
}
return length - (name + 1);
}
return 0;
}
static void write_module(const char *path, const struct spirv_code *code)
{
FILE *out = fopen(path, "wb");
if (!out) {
printf("FAIL: %s cannot be written\n", path);
failures++;
return;
}
fwrite(code->words, sizeof(uint32_t), code->count, out);
fclose(out);
}
static struct device test_device;
static int failed_allocations;
static bool fail_allocations;
static int driver_calls;
static bool chain_was_layer_owned;
static VkStructureType first_link;
static uint32_t driver_version;
static uint32_t driver_subgroup_size;
void *test_calloc(size_t count, size_t size)
{
if (fail_allocations) {
failed_allocations++;
return NULL;
}
if (size && count > SIZE_MAX / size)
return NULL;
size_t bytes = count * size;
void *memory = malloc(bytes > 0 ? bytes : 1);
if (memory)
memset(memory, 0, bytes);
return memory;
}
struct device *device_from_handle(const void *dispatchable)
{
return &test_device;
}
void layer_log(const char *format, ...)
{
}
void *map_get(const struct handle_map *map, uint64_t key)
{
return NULL;
}
void map_put(struct handle_map *map, uint64_t key, void *value)
{
}
void *map_remove(struct handle_map *map, uint64_t key)
{
return NULL;
}
static void read_stage(const VkPipelineShaderStageCreateInfo *stage, const void *app_chain)
{
driver_calls++;
chain_was_layer_owned = stage->pNext != app_chain;
first_link = stage->pNext ? ((const VkBaseInStructure *)stage->pNext)->sType : VK_STRUCTURE_TYPE_MAX_ENUM;
driver_version = 0;
driver_subgroup_size = 0;
for (const VkBaseInStructure *s = stage->pNext; s; s = s->pNext) {
if (s->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO)
driver_subgroup_size = ((const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo *)s)->requiredSubgroupSize;
if (s->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) {
const VkShaderModuleCreateInfo *info = (const VkShaderModuleCreateInfo *)s;
driver_version = spirv_version(info->pCode, info->codeSize / sizeof(uint32_t));
}
}
}
static const void *expected_chain;
static VkResult VKAPI_CALL driver_compute(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkComputePipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
read_stage(&infos[0].stage, expected_chain);
return VK_SUCCESS;
}
static VkResult VKAPI_CALL driver_graphics(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkGraphicsPipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
read_stage(&infos[0].pStages[0], expected_chain);
return VK_SUCCESS;
}
static const VkShaderModuleCreateInfo app_module = {
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = sizeof(newer),
.pCode = newer,
};
static const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo app_subgroup = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO,
.pNext = &app_module,
.requiredSubgroupSize = 16,
};
static const VkApplicationInfo app_unknown = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = &app_module,
};
static const VkPipelineShaderStageCreateInfo app_fragment = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.pNext = &app_subgroup,
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
.pName = "main",
};
static void check_pipelines(void)
{
VkDevice device = (VkDevice)&test_device;
VkPipeline pipeline = VK_NULL_HANDLE;
pthread_mutex_init(&test_device.lock, NULL);
test_device.CreateComputePipelines = driver_compute;
test_device.CreateGraphicsPipelines = driver_graphics;
VkComputePipelineCreateInfo compute = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.pNext = &app_subgroup,
.stage = VK_SHADER_STAGE_COMPUTE_BIT,
.pName = "main"},
};
expected_chain = &app_subgroup;
check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS,
"a compute pipeline with inline code behind another structure is created");
check(chain_was_layer_owned, "the compute stage gets the layer's own chain");
check(first_link == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO,
"the compute stage keeps its chain order");
check(driver_subgroup_size == 16, "the compute stage keeps its required subgroup size");
check(driver_version == 0x00010300u, "the compute stage's inline code reaches the driver as SPIR-V 1.3");
check(app_module.pCode == newer && app_module.codeSize == sizeof(newer),
"the application's shader module create info is untouched");
check(compute.stage.pNext == &app_subgroup, "the application's compute stage is untouched");
compute.stage.pNext = &app_module;
expected_chain = &app_module;
check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS,
"a compute pipeline with inline code first in its chain is created");
check(chain_was_layer_owned && driver_version == 0x00010300u,
"inline code first in the chain reaches the driver as SPIR-V 1.3");
compute.stage.pNext = &app_unknown;
expected_chain = &app_unknown;
check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS,
"a compute pipeline behind an unknown structure is created");
check(!chain_was_layer_owned && driver_version == 0x00010600u,
"a chain the layer cannot copy reaches the driver as the application wrote it");
VkGraphicsPipelineCreateInfo graphics = {
.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
.stageCount = 1,
.pStages = &app_fragment,
};
expected_chain = &app_subgroup;
check(CreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics, NULL, &pipeline) == VK_SUCCESS,
"a graphics pipeline with inline code behind another structure is created");
check(chain_was_layer_owned && driver_subgroup_size == 16 && driver_version == 0x00010300u,
"the graphics stage reaches the driver capped with its chain intact");
check(app_fragment.pNext == &app_subgroup && graphics.pStages == &app_fragment,
"the application's graphics stages are untouched");
driver_calls = 0;
failed_allocations = 0;
fail_allocations = true;
VkPipeline compute_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2};
VkPipeline graphics_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2};
VkResult compute_result = CreateComputePipelines(device, VK_NULL_HANDLE, 2, &compute, NULL, compute_outputs);
VkResult graphics_result = CreateGraphicsPipelines(device, VK_NULL_HANDLE, 2, &graphics, NULL, graphics_outputs);
fail_allocations = false;
check(failed_allocations > 0, "the allocations were made to fail");
check(compute_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a compute pipeline without memory reports it");
check(graphics_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a graphics pipeline without memory reports it");
check(compute_outputs[0] == VK_NULL_HANDLE && compute_outputs[1] == VK_NULL_HANDLE,
"failed compute pipeline outputs are cleared");
check(graphics_outputs[0] == VK_NULL_HANDLE && graphics_outputs[1] == VK_NULL_HANDLE,
"failed graphics pipeline outputs are cleared");
check(driver_calls == 0, "the driver is not called without memory");
pthread_mutex_destroy(&test_device.lock);
}
int main(int argc, char **argv)
{
struct spirv_code capped = {0};
check(spirv_cap_version(newer, newer_count, &capped), "a SPIR-V 1.6 module is capped");
check(capped.words != NULL, "the capped module is there");
if (capped.words) {
check(capped.words[1] == 0x00010300u, "the capped module is SPIR-V 1.3");
check(interface_size(capped.words, capped.count) == 1,
"the entry point lists only the input and output variables");
check(count_opcodes(capped.words, capped.count, SpvOpKill) == 1, "the discard is an OpKill");
check(count_opcodes(capped.words, capped.count, SpvOpTerminateInvocation) == 0,
"no OpTerminateInvocation is left");
if (argc > 1)
write_module(argv[1], &capped);
free(capped.words);
}
struct spirv_code kept = {0};
check(!spirv_cap_version(older, older_count, &kept), "a SPIR-V 1.3 module is left alone");
check(kept.words == NULL, "the untouched module is not handed back");
check(!spirv_cap_version(capability, capability_count, &kept),
"a module with a capability from SPIR-V 1.5 is left alone");
check(!spirv_cap_version(memory, memory_count, &kept), "a module with the Vulkan memory model is left alone");
check(!spirv_cap_version(nonuniform, nonuniform_count, &kept),
"a module with ShaderNonUniform and no SPV_EXT_descriptor_indexing is left alone");
check(!spirv_cap_version(select_struct, select_struct_count, &kept),
"a module selecting a structure is left alone");
check(!spirv_cap_version(nonsemantic, nonsemantic_count, &kept),
"a module importing a NonSemantic set without SPV_KHR_non_semantic_info is left alone");
uint32_t private_readonly[sizeof(zinklike) / sizeof(uint32_t) + 3];
size_t declaration = 5;
while (OPCODE(zinklike[declaration]) != SpvOpTypeVoid)
declaration += LENGTH(zinklike[declaration]);
memcpy(private_readonly, zinklike, declaration * sizeof(uint32_t));
private_readonly[declaration] = (3u << 16) | SpvOpDecorate;
private_readonly[declaration + 1] = 3;
private_readonly[declaration + 2] = SpvDecorationNonWritable;
memcpy(private_readonly + declaration + 3, zinklike + declaration,
(zinklike_count - declaration) * sizeof(uint32_t));
check(!spirv_cap_version(private_readonly, zinklike_count + 3, &kept),
"a private NonWritable variable is left alone");
if (argc > 6) {
struct spirv_code source = {.words = private_readonly, .count = zinklike_count + 3};
write_module(argv[6], &source);
}
uint32_t converted[sizeof(zinklike) / sizeof(uint32_t) + 9];
size_t function = declaration;
while (OPCODE(zinklike[function]) != SpvOpFunction)
function += LENGTH(zinklike[function]);
memcpy(converted, zinklike, function * sizeof(uint32_t));
const uint32_t conversion[] = {(4u << 16) | SpvOpTypeInt, 23, 32, 0,
(5u << 16) | SpvOpSpecConstantOp, 23, 24, SpvOpUConvert, 15};
memcpy(converted + function, conversion, sizeof(conversion));
memcpy(converted + function + 9, zinklike + function, (zinklike_count - function) * sizeof(uint32_t));
converted[3] = 25;
check(!spirv_cap_version(converted, zinklike_count + 9, &kept),
"a specialization UConvert without its extension is left alone");
if (argc > 7) {
struct spirv_code source = {.words = converted, .count = zinklike_count + 9};
write_module(argv[7], &source);
}
check(kept.words == NULL, "no rejected module is handed back");
struct spirv_code extension = {0};
check(spirv_cap_version(nonuniform_extension, nonuniform_extension_count, &extension),
"a module declaring SPV_EXT_descriptor_indexing for ShaderNonUniform is capped");
if (extension.words) {
check(extension.words[1] == 0x00010300u, "the module with the extension is SPIR-V 1.3");
if (argc > 3)
write_module(argv[3], &extension);
free(extension.words);
}
struct spirv_code scalar = {0};
check(spirv_cap_version(select_scalar, select_scalar_count, &scalar), "a module selecting a scalar is capped");
if (scalar.words) {
check(count_opcodes(scalar.words, scalar.count, SpvOpSelect) == 1, "the scalar select is kept");
if (argc > 4)
write_module(argv[4], &scalar);
free(scalar.words);
}
struct spirv_code debug = {0};
check(spirv_cap_version(nonsemantic_extension, nonsemantic_extension_count, &debug),
"a module declaring SPV_KHR_non_semantic_info for its NonSemantic import is capped");
if (debug.words) {
check(debug.words[1] == 0x00010300u, "the module with the NonSemantic import is SPIR-V 1.3");
if (argc > 5)
write_module(argv[5], &debug);
free(debug.words);
}
struct spirv_code guest = {0};
check(spirv_cap_version(zinklike, zinklike_count, &guest), "a guest module with a private global is capped");
if (guest.words) {
check(guest.words[1] == 0x00010300u, "the guest module is SPIR-V 1.3");
check(interface_size(guest.words, guest.count) == 1,
"the guest module lists only the input and output variables");
check(count_opcodes(guest.words, guest.count, SpvOpFunction) == 1, "the guest module keeps its function");
if (argc > 2)
write_module(argv[2], &guest);
free(guest.words);
}
struct spirv_code parameter = {0};
size_t parameter_count = sizeof(readonly_parameter) / sizeof(uint32_t);
check(spirv_cap_version(readonly_parameter, parameter_count, &parameter),
"a NonWritable storage buffer parameter is capped");
if (parameter.words) {
check(count_opcodes(parameter.words, parameter.count, SpvOpFunctionParameter) == 1,
"the storage buffer parameter is preserved");
if (argc > 8)
write_module(argv[8], &parameter);
free(parameter.words);
}
uint32_t incompatible_parameter[sizeof(readonly_parameter) / sizeof(uint32_t)];
memcpy(incompatible_parameter, readonly_parameter, sizeof(readonly_parameter));
for (size_t i = 5; i < parameter_count; i += LENGTH(incompatible_parameter[i])) {
if (OPCODE(incompatible_parameter[i]) == SpvOpTypePointer) {
incompatible_parameter[i + 2] = SpvStorageClassPrivate;
check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept),
"a NonWritable Private parameter is left alone");
incompatible_parameter[i + 2] = SpvStorageClassFunction;
check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept),
"a NonWritable Function parameter is left alone");
}
}
check_pipelines();
if (failures)
printf("%d check(s) failed\n", failures);
else
printf("mali compat spirv ok\n");
return failures ? 1 : 0;
}
+318
View File
@@ -0,0 +1,318 @@
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "wayland-util.h"
void wl_list_init(struct wl_list *list) { list->prev = list->next = list; }
void wl_list_insert(struct wl_list *list, struct wl_list *elm) {
elm->prev = list;
elm->next = list->next;
list->next = elm;
elm->next->prev = elm;
}
void wl_list_remove(struct wl_list *elm) {
elm->prev->next = elm->next;
elm->next->prev = elm->prev;
elm->next = elm->prev = NULL;
}
int wl_list_empty(const struct wl_list *list) { return list->next == list; }
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
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 };
struct surface {
struct wl_list link;
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
int64_t next_release_ns;
int releases_pending;
enum surface_role role;
struct surface *parent;
int sub_desync;
};
#define TFD_TIMER_ABSTIME 1
static struct wl_list g_surfaces;
static struct wl_list g_pending_releases;
static int g_release_timer_fd = 3;
static int g_fps_limit;
static int64_t g_refresh_ns = 8333333;
static int g_release_unpaced;
static int64_t g_now = 1000000000LL;
static int64_t g_armed;
static struct dmabuf_buffer g_buf;
static int64_t now_ns(void) { return g_now; }
static void perf_note_release(int64_t since) { (void)since; }
static int buffer_release_blocked(struct wl_resource *b) { (void)b; return 0; }
static int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *r, struct surface *s, int paced) {
(void)b; (void)r; (void)s; (void)paced;
return 0;
}
static void dmabuf_buffer_unref(struct dmabuf_buffer *b) { (void)b; }
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) {
wl_list_insert(r->listeners.prev, &l->link);
}
static int timerfd_settime(int fd, int flags, const struct itimerspec *its, struct itimerspec *old) {
(void)fd; (void)flags; (void)old;
g_armed = (int64_t)its->it_value.tv_sec * 1000000000LL + its->it_value.tv_nsec;
return 0;
}
static void send_buffer_release(struct wl_resource *b) {
b->releases++;
if (b->acquired) b->acquired = 0;
else b->errors++;
}
#include "release.inc"
static void present(struct wl_resource *b) { b->acquired = 1; }
static void commit(struct surface *s, struct wl_resource *b) {
if (s->dmabuf != b) {
drop_dmabuf(s, 1);
if (b) {
pending_releases_cancel(b);
s->dmabuf = b;
s->dmabuf_buf = &g_buf;
wl_resource_add_destroy_listener(b, &s->dmabuf_destroy);
}
}
pending_releases_apply(s);
}
static void timer_fires(int64_t at) {
if (g_now < at) g_now = at;
release_due_buffers();
arm_release_timer();
}
static void surface_init(struct surface *s, enum surface_role role, struct surface *parent) {
memset(s, 0, sizeof(*s));
s->role = role;
s->parent = parent;
wl_list_insert(g_surfaces.prev, &s->link);
}
static void buffer_init(struct wl_resource *b) {
memset(b, 0, sizeof(*b));
wl_list_init(&b->listeners);
}
static void check(const struct wl_resource *b, int releases) {
if (b->releases != releases || b->errors) {
fprintf(stderr, "releases %d (want %d), released while not acquired %d\n", b->releases, releases, b->errors);
exit(1);
}
}
static void moved_between_planes(void) {
struct surface root, low, high;
struct wl_resource a, b, c;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&low, ROLE_SUBSURFACE, &root);
surface_init(&high, ROLE_SUBSURFACE, &root);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
present(&a); present(&b);
commit(&high, &a);
commit(&low, &b);
commit(&root, NULL);
present(&a); present(&b);
commit(&high, NULL);
timer_fires(g_now);
check(&a, 0);
commit(&low, &a);
timer_fires(g_now);
commit(&root, &b);
timer_fires(g_now + 100000000LL);
check(&a, 0);
check(&b, 0);
present(&c);
commit(&high, NULL);
commit(&low, NULL);
commit(&root, &c);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&b, 1);
check(&c, 0);
}
static void reattached_before_release(void) {
struct surface s;
struct wl_resource a, b, c;
surface_init(&s, ROLE_TOPLEVEL, NULL);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
g_fps_limit = 60;
present(&a); commit(&s, &a);
present(&b); commit(&s, &b);
present(&a); commit(&s, &a);
present(&c); commit(&s, &c);
timer_fires(g_now + 1000000000LL);
check(&a, 1);
check(&b, 1);
check(&c, 0);
}
static void desync_child_not_held(void) {
struct surface root, child;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&child, ROLE_SUBSURFACE, &root);
child.sub_desync = 1;
buffer_init(&a); buffer_init(&b);
present(&a); commit(&child, &a);
present(&b); commit(&child, &b);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&b, 0);
}
static void toplevel_pacing_kept(void) {
struct surface s;
struct wl_resource a, b, c;
surface_init(&s, ROLE_TOPLEVEL, NULL);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
g_fps_limit = 60;
const int64_t interval = 1000000000LL / 60;
present(&a); commit(&s, &a);
present(&b); commit(&s, &b);
present(&c); commit(&s, &c);
const int64_t start = g_now;
timer_fires(g_now);
check(&a, 1);
check(&b, 0);
assert(g_armed == start + interval);
timer_fires(start + interval / 2);
check(&b, 0);
timer_fires(g_armed);
check(&b, 1);
check(&c, 0);
}
static void unpaced_sync_child(void) {
struct surface root, low, high;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&low, ROLE_SUBSURFACE, &root);
surface_init(&high, ROLE_SUBSURFACE, &root);
buffer_init(&a); buffer_init(&b);
g_release_unpaced = 1;
present(&a); commit(&high, &a); commit(&root, NULL);
present(&a);
commit(&high, NULL);
check(&a, 0);
commit(&low, &a);
commit(&root, NULL);
check(&a, 0);
commit(&low, NULL);
check(&a, 0);
commit(&root, NULL);
check(&a, 1);
present(&b); commit(&root, &b);
commit(&root, NULL);
check(&b, 1);
}
static void holder_destroyed(void) {
struct surface root, child;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&child, ROLE_SUBSURFACE, &root);
buffer_init(&a); buffer_init(&b);
present(&a); commit(&child, &a); commit(&root, NULL);
present(&b); commit(&child, &b);
timer_fires(g_now + 100000000LL);
check(&a, 0);
child.parent = NULL;
wl_list_remove(&root.link);
pending_releases_forget_surface(&root);
check(&a, 1);
}
static void cycled_faster_than_releases(void) {
struct surface s;
struct wl_resource a, b, c;
struct wl_resource *order[3] = {&a, &b, &c};
surface_init(&s, ROLE_TOPLEVEL, NULL);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
g_fps_limit = 60;
const int64_t interval = 1000000000LL / 60;
for (int i = 0; i < 30; i++) {
present(order[i % 3]);
commit(&s, order[i % 3]);
assert(s.releases_pending <= 2);
assert(g_armed <= g_now + 3 * interval);
}
timer_fires(g_now + 1000000000LL);
check(&a, 1);
check(&b, 1);
check(&c, 0);
}
static void desync_parent_holds_sync_grandchild(void) {
struct surface root, middle, child;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&middle, ROLE_SUBSURFACE, &root);
surface_init(&child, ROLE_SUBSURFACE, &middle);
middle.sub_desync = 1;
buffer_init(&a); buffer_init(&b);
present(&a); commit(&child, &a); commit(&middle, NULL);
present(&b); commit(&child, &b);
timer_fires(g_now + 100000000LL);
check(&a, 0);
commit(&middle, NULL);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&b, 0);
}
static void set_desync_frees_held_release(void) {
struct surface root, outer, inner;
struct wl_resource a, b, c, d;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&outer, ROLE_SUBSURFACE, &root);
surface_init(&inner, ROLE_SUBSURFACE, &outer);
buffer_init(&a); buffer_init(&b); buffer_init(&c); buffer_init(&d);
present(&a); commit(&inner, &a); commit(&root, NULL);
present(&b); commit(&inner, &b);
present(&c); commit(&outer, &c); commit(&root, NULL);
present(&d); commit(&outer, &d);
inner.sub_desync = 1;
pending_releases_rehold(&inner);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&c, 0);
outer.sub_desync = 1;
pending_releases_rehold(&outer);
timer_fires(g_now + 100000000LL);
check(&c, 1);
check(&b, 0);
check(&d, 0);
}
int main(int argc, char **argv) {
assert(argc == 2);
wl_list_init(&g_surfaces);
wl_list_init(&g_pending_releases);
if (!strcmp(argv[1], "moved")) moved_between_planes();
else if (!strcmp(argv[1], "reattached")) reattached_before_release();
else if (!strcmp(argv[1], "cycled")) cycled_faster_than_releases();
else if (!strcmp(argv[1], "desync")) desync_child_not_held();
else if (!strcmp(argv[1], "toplevel")) toplevel_pacing_kept();
else if (!strcmp(argv[1], "unpaced")) unpaced_sync_child();
else if (!strcmp(argv[1], "destroyed")) holder_destroyed();
else if (!strcmp(argv[1], "nested")) desync_parent_holds_sync_grandchild();
else if (!strcmp(argv[1], "set-desync")) set_desync_frees_held_release();
else return 2;
return 0;
}
+18
View File
@@ -146,6 +146,24 @@ class AppImageRunTest(unittest.TestCase):
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem"))
self.assertEqual("sysmem", env["TU_DEBUG"])
def test_an_arm64_app_uses_the_sessions_gl_libraries(self):
(self.dir / "arch").write_text("arm64")
self.bundle("usr/lib/libGLESv2.so.2", "usr/lib/libEGL.so.1", "usr/lib/libglfw.so.3", "usr/lib/libGLESv2.so.2.1.0")
_, log = self.launch(RUN_MODE)
lib = self.dir / "app/usr/lib"
self.assertEqual(["libGLESv2.so.2.1.0", "libglfw.so.3"], sorted(p.name for p in lib.iterdir()))
self.assertEqual(["libEGL.so.1", "libGLESv2.so.2"], sorted(p.name for p in (self.dir / "bundled-gl/usr/lib").iterdir()))
self.assertIn("the session's libGLESv2.so.2 replaces the bundled one", log)
_, log = self.launch(RUN_MODE)
self.assertNotIn("replaces the bundled one", log)
def test_other_architectures_keep_their_gl_libraries(self):
(self.dir / "arch").write_text("x86_64")
self.bundle("usr/lib/libGLESv2.so.2")
self.launch(RUN_MODE)
self.assertTrue((self.dir / "app/usr/lib/libGLESv2.so.2").exists())
self.assertFalse((self.dir / "bundled-gl").exists())
if __name__ == "__main__":
unittest.main()
+39 -53
View File
@@ -6,7 +6,6 @@ import re
import runpy
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
@@ -93,8 +92,6 @@ class IdTest(unittest.TestCase):
self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000)
found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text())
self.assertEqual(found.group(1), BNET["APP_ID"])
for name in ("FEX_REQUEST", "FEX_RESULT"):
self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text())
class ProtonRunOptionsTest(Temp):
@@ -180,7 +177,7 @@ class ConfigAndMenuTest(Temp):
self.assertEqual(config["Client"]["Streaming"]["StreamingEnabled"], "false")
self.assertEqual(config["Client"]["GameLaunchWindowBehavior"], "2")
self.assertIsNone(BNET["write_config"](root))
path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "0"}, "Games": {"osi": {}}}')
path.write_text('{"Client": {"HardwareAcceleration": "false"}, "Games": {"osi": {}}}')
self.assertEqual(BNET["write_config"](root), "launch 32-bit")
config = json.loads(path.read_text())
self.assertEqual(config, {"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"},
@@ -189,6 +186,29 @@ class ConfigAndMenuTest(Temp):
self.assertEqual(BNET["write_config"](root), "acceleration 32-bit")
self.assertEqual(json.loads(path.read_text())["Client"]["HardwareAcceleration"], "false")
def test_a_launch_behavior_the_player_chose_is_kept(self):
root = str(self.tmp)
path = self.config_path()
path.parent.mkdir(parents=True)
for behavior in ("0", "1"):
with self.subTest(behavior):
path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "%s"}, '
'"Games": {"s1": {"Run64Bit": "false", "Run64BitSet": "true"}}}' % behavior)
self.assertIsNone(BNET["write_config"](root))
self.assertEqual(json.loads(path.read_text())["Client"]["GameLaunchWindowBehavior"], behavior)
self.assertTrue(BNET["keeps_open"](root))
def test_only_a_launch_behavior_other_than_exit_keeps_battle_net_open(self):
root = str(self.tmp)
self.assertFalse(BNET["keeps_open"](root))
path = self.config_path()
path.parent.mkdir(parents=True)
for text in ("{not json", "[1, 2]", '{"Client": "x"}', '{"Client": {}}',
'{"Client": {"GameLaunchWindowBehavior": "2"}}'):
with self.subTest(text):
path.write_text(text)
self.assertFalse(BNET["keeps_open"](root))
def test_starcraft_starts_its_32_bit_client_until_a_player_picks_one(self):
root = str(self.tmp)
BNET["write_config"](root)
@@ -656,6 +676,7 @@ class TidyTest(unittest.TestCase):
"say": lambda message: None,
"stop": lambda found, wait=0: self.stopped.append(sorted(pid for pid, _ in found)),
"notify": lambda title, body, icon=None: self.notified.append(title),
"keeps_open": lambda root: False,
})
patcher.start()
self.addCleanup(patcher.stop)
@@ -672,6 +693,14 @@ class TidyTest(unittest.TestCase):
self.assertEqual(self.stopped, [[1, 2, 3]])
self.assertEqual(self.notified, [])
def test_battle_net_the_player_set_to_stay_open_is_left_open(self):
up = [self.CLIENT, self.PAGE, self.AGENT, self.WINE]
tidy = BNET["Tidy"](settle=20, gone=30)
with mock.patch.dict(BNET, {"keeps_open": lambda root: True}):
closed = self.run_tidy(tidy, [(0, up), (5, up + [self.GAME]), (25, up + [self.GAME]), (60, up + [self.GAME])])
self.assertEqual(closed, [False, False, False, False])
self.assertEqual(self.stopped, [])
def test_battle_net_beside_a_game_signing_in_with_its_token_is_left_open(self):
d4 = (6, ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-nostreamline", "-sso", "-launch", "-uid", "fenris"])
up = [self.CLIENT, self.PAGE, self.AGENT]
@@ -729,36 +758,6 @@ class TidyTest(unittest.TestCase):
self.assertEqual(self.stopped, [])
class FexRequestTest(Temp):
def answer(self, text, delay=0.2):
def respond():
request = self.tmp / BNET["FEX_REQUEST"]
deadline = time.monotonic() + 5
while not request.exists() and time.monotonic() < deadline:
time.sleep(0.02)
self.requested = request.read_text()
request.unlink()
time.sleep(delay)
(self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n")
os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"])
thread = threading.Thread(target=respond)
thread.start()
self.addCleanup(thread.join)
def test_the_apps_answer_comes_back(self):
(self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n")
self.answer("ok FEXCore-2610-d2rfix28-linux.wcp")
self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp")
self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"])
self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists())
def test_no_answer_or_no_session_starts_without_one(self):
with mock.patch.dict(BNET, {"say": lambda message: None}):
self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3))
self.assertIsNone(BNET["ask_fex"](None))
self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone")))
class OpenTest(Temp):
def setUp(self):
super().setUp()
@@ -767,7 +766,6 @@ class OpenTest(Temp):
self.alive = []
self.menu = self.tmp / "droiddeck-battlenet.desktop"
patcher = mock.patch.dict(BNET, {
"ask_fex": lambda launch_dir, wait=0: "ok fex.wcp",
"say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])),
"wine_processes": lambda pfx, proc="/proc": list(self.alive),
"stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(),
@@ -956,7 +954,6 @@ class Harness(Temp):
self.states = []
self.last = []
patcher = mock.patch.dict(BNET, {
"ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp",
"say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])),
"wine_processes": self.processes,
"stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))),
@@ -987,7 +984,7 @@ class LaunchTest(Harness):
self.states = [[], [], up, up + [(40, self.GAME)], up, up]
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
self.assertEqual(self.calls, [
("fex",), ("start", "Battle.net Launcher.exe", None),
("start", "Battle.net Launcher.exe", None),
("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]),
("stop", [10, 11, 12, 13, 14, 30]),
])
@@ -1002,7 +999,7 @@ class LaunchTest(Harness):
with mock.patch.dict(BNET, {"GAME_SETTLE": 0}):
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
self.assertEqual(self.calls, [
("fex",), ("start", "Battle.net Launcher.exe", None),
("start", "Battle.net Launcher.exe", None),
("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]),
("stop", [10, 11, 12, 13, 14, 30]),
("stop", [50]),
@@ -1416,7 +1413,8 @@ class AgentJobTest(Harness):
self.assertEqual(code, 0)
self.assertTrue(os.path.isdir(folder))
cmd = self.started[0]
self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"])
self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log",
str(self.tmp / "cache" / "agent.log")])
self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"])
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
@@ -1644,16 +1642,6 @@ class AgentJobTest(Harness):
path.write_bytes(json.dumps({"state": 1004}).encode("utf-8"))
self.assertEqual(BNET["read_status"](str(path)), {"state": 1004})
def test_a_large_agent_log_is_rotated_before_a_job(self):
self.install()
os.makedirs(self.tmp / "cache")
log = self.tmp / "cache" / "agent.log"
log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1))
self.files = {".game": json.dumps({"installed": False})}
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1)
self.assertEqual(log.stat().st_size, 0)
def test_it_queues_behind_another_battle_net_job(self):
self.install()
self.files = {".game": json.dumps({"installed": False})}
@@ -1684,13 +1672,11 @@ class AgentJobTest(Harness):
self.assertEqual(self.lines[0], ("STATE", "waiting"))
self.assertEqual(self.lines[1], ("STATE", "starting"))
def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self):
def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self):
self.install()
os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1")
self.files = {".game": json.dumps({"installed": False})}
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
self.assertNotIn("DISPLAY", self.envs[0])
self.assertNotIn("WAYLAND_DISPLAY", self.envs[0])
self.assertEqual(self.started[0][0], BNET["HEADLESS"])
self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0")
os.environ["DISPLAY"] = ":0"
self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0")
+39
View File
@@ -138,6 +138,27 @@ class BinfmtPreloadTest(unittest.TestCase):
program = self.file("arm64", bytes(arm64))
self.assertEqual(self.run_program("execve", program), (3, "errno %d" % errno.ENOEXEC, None))
def arm64_appimage(self, name, filesystem):
image = bytearray(128)
image[0:4], image[4], image[5], image[8:11], image[18] = b"\x7fELF", 2, 1, b"AI\x02", 183
image[0x28:0x30] = (64).to_bytes(8, "little")
image[0x3A:0x3C], image[0x3C:0x3E] = (32).to_bytes(2, "little"), (1).to_bytes(2, "little")
image[96:102] = filesystem
return self.file(name, bytes(image))
def test_an_arm64_appimage_goes_to_the_handler(self):
program = self.arm64_appimage("App.AppImage", b"hsqs\0\0")
for how in ("execve", "execvp"):
self.log.unlink(missing_ok=True)
target = program if how == "execve" else program.name
self.assertEqual(self.run_program(how, target, "--x"), (7, "", ["--exec", str(program), "--x"]))
self.log.unlink()
self.assertEqual(self.run_program("spawn", program, "y"), (0, "exit 7", ["--exec", str(program), "y"]))
def test_an_appimage_runtime_without_a_filesystem_keeps_its_error(self):
runtime = self.arm64_appimage("uruntime", bytes(6))
self.assertEqual(self.run_program("execve", runtime), (3, "errno %d" % errno.ENOEXEC, None))
def test_a_script_runs_as_itself(self):
script = self.file("script.sh", b"#!/bin/sh\nexit 5\n")
self.assertEqual(self.run_program("execve", script), (5, "", None))
@@ -188,6 +209,24 @@ class BinfmtPreloadTest(unittest.TestCase):
code = self.chromium_script()
self.assertEqual(self.run_program("execve", code, "--version"), (0, "--no-sandbox\n--version", None))
def test_a_chromium_app_named_on_path_receives_no_sandbox(self):
(self.dir / "code").symlink_to(self.chromium_script())
for how in ("execvp", "execvpe", "spawnp"):
out = self.run_program(how, "code", "--version")
self.assertEqual(out[1].splitlines()[:2], ["--no-sandbox", "--version"], how)
def test_a_path_match_that_cannot_run_does_not_decide_the_flags(self):
stale = self.dir / "stale"
stale.mkdir()
(stale / "util").write_text("#!/bin/sh\n")
(stale / "chrome-sandbox").touch()
util = self.dir / "util"
util.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n")
util.chmod(0o755)
for how in ("execvp", "execvpe", "spawnp"):
out = self.run_program(how, "util", "--version", PATH=f"{stale}:{self.dir}:/usr/bin:/bin")
self.assertEqual(out[1].splitlines()[:1], ["--version"], how)
def test_the_hand_off_switch_works_without_the_desktop(self):
tool = self.x86()
for how in ("execve", "execvp"):
+2 -1
View File
@@ -19,7 +19,8 @@ class CdpGuardTest(unittest.TestCase):
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"),
str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl",
"-o", str(cls.library)],
input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n"
b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True)
@classmethod
def tearDownClass(cls):
Loaded 100 of 609 files, more files were not shown because too many files have changed in this diff. Show more